Re: [NEWBIE] Right way to make lightweight class/structs?
Re: [NEWBIE] Right way to make lightweight class/structs?
- Subject: Re: [NEWBIE] Right way to make lightweight class/structs?
- From: brian hook <email@hidden>
- Date: Fri, 07 Sep 2001 08:19:19 -0700
At 01:47 AM 9/7/01 -0500, David Trevas wrote:
NSRange to name a few. Structs are just fine for simple storage, but it
seems that for vectors, you'd want to be able to add, subtract,
normalize, take scalar, dot and cross products and do matrix
multiplication (for which you'd need to develop a Matrix class).
But, in addition, I want to regularly access the data in a convenient and
easy format. For example, when I'm done processing all my vectors, it's
REALLY nice to be able to cast them to an array of floats and feed that
straight to OpenGL instead of going through a lengthy conversion process.
- (void) setXYZ: (float *)inputVector
{
x = inputVector[0]; y = inputVector[1]; z = inputVector[2];
}
My problem is having to do something more like:
- (float) dot: (const Vec3f *)pV
{
return x * [ pV x ] + y * [pV y] + z * [Pv z];
}
That's just way harder on my eyes than I'd like, but maybe that's just
because I'm not conditioned to the bracket operators =)
- (float *) xyz
{
static float temp[3];
temp[0] = x; temp[1] = y; temp[2] = z;
return temp;
}
The above isn't going to be re-entrant.
That may get a little more cumbersome, but you get added safety (if
someone put a 2D vector in the setXYZ: method above, you could be lucky
and get an explicit out-of-range message or unlucky and get garbage that
may be difficult to root out) and you don't have to mess with the static
array in xyz.
Right, but the performance is going to suffer. This is a scientific app of
sorts, so I'm doing a ton of math and iterating over huge numbers of arrays.
Of course, you can always use the @public directive to expose x, y and z
for anyone to read and write. That's quite frowned upon.
Dogmatically speaking I could see why that's bad, but in the case of a
vector class, exposing those values makes a lot of sense to me. In the
case of a 3-element vector, the implementation IS the interface, for all
intents and purpose.
Here's a method for the Vec3f class that does scalar multiplication and
the code would read:
vector2 = [vector1 multipliedByScalar: 3.453];
That's almost starting to look like plain English!
- (void) multipliedByScalar: (float) factor
{
x *= factor; y *= factor; z *= factor;
}
Except you're assigning a void return type to a variable ;)
That's one good argument for making it a subclass of NSObject.
Access to the memory management is definitely nice.
Thanks,
Brian