Package: vec
vecA reasonable, performant 2D vector object for gamesCopyright 2019-2023 by Larry HastingsOverviewvecis a module currently publishing one class:Vector2, a 2D
vector object designed for game development.Features:Vector2objects are immutable.Vector2support all the usual vector object features,
including operator overloading.Attributes ofVector2objects are lazily-computed where possible.Vector2objects effortlessly support both cartesian and polar coordinates.vecsupports Python 3.6+, and passes its unit test suite with 100% coverage.Why Another Vector Class?I've participated in four PyWeek gaming challenges.  And twice,
mid-week, I wrote my own vector class out of sheer frustration.The biggest problem with most Python vector objects in is that they'remutable.Frankly this way lies madness.  Vector objects should be
immutable--it just makes sense from an API perspective.  What if you
set the position of some game-engine pawn to be a particular vector
object, then modify that vector object?  Should the pawn update its
position automatically--and if so, how would it know the value changed?Similarly, some vector classes use degrees for polar coordinates
instead of radians.
Again this way lies madness.  The trigonometric functions in Python'smathmodule operate in the radians domain, and having to keep track
of which domain something is in--and translate back and forth--is
a needless conceptual complication.  You've got a game to write!(Some vector classes supportbothradiansanddegrees for polar
coordinates.  This is simply bad API design--it doubles the surface
area of your API, adding needless complexity and increasing maintenance
and testing overhead.  Embrace the radian, folks.)On a related note, many vector classes make polar coordinates
second-class citizens.  Most vector classes only store vectors in
cartesian coordinates, so either the programmer must perform all polar
operations externally to the vector objects, or they incur the
overhead and cumulative error of translating to polar and
back again with every operation.vec'sVector2avoids all these problems:Vector2objects are immutable,they make polar and cartesian coordinates both first-class citizens,
andthey strictly use radians for polar coordinates.The Conceptual ModelVector2objects conceptually represent a vector.  They can be
defined using either cartesian or polar coordinates, and anyVector2can be queried for both its cartesian and polar coordinates.Most vector objects in games are defined using cartesian coordinates.Vector2makes that easy, supporting any number of invocations
to create one.  Discrete parameters,
iterables, and objects that supportxandyattributes all work fine:Vector2(0, 1)
Vector2(x=0, y=1)
Vector2((0, 1))
Vector2([0, 1])
Vector2(iter([0, 1]))
Vector2({'x':0, 'y':1})
Vector2(types.SimpleNamespace(x=0, y=1))All these define the same vector.  That last example is there to demonstrate
thatVector2can create a vector based on any object withxandyattributes.EveryVector2object supports both cartesian and polar coordinates.
You can define aVector2using cartesian coordinates, then examine
its polar coordinates.  This:v = vec.Vector2(0, 1)
print(v.theta, v.r)prints1.5707963267948966 1.0.  That first number is π/2 (approximately).Conversely, you can define aVector2object using polar
coordinates, then examine its cartesian coordinates:v2 = vec.Vector2(r=1, theta=math.pi/2)
print(v2.x, v2.y)This prints6.123233995736766e-17 1.0.  Conceptually this should
print0.0, 1.0--butmath.piis only an approximation, which sadly
means our result has an infinitesimal error.Implementation DetailsTo define a validVector2object, you must have a complete
set of either cartesian or polar coordinates--either is sufficient.
All other attributes will be lazily computed on demand.Vector2objects use slots, and rely on__getattr__to implement this lazy computation.  Only the known values of the
vector are set when it's created.  If the user refers to an attribute
that hasn't been computed yet, Python will callVector2.__getattr__(),
which computes, caches, and returns that value.  Future references to that
attribute skip this mechanism and simply return the cached value, which
is only as expensive as an attribute lookup on a conventional object.Operations onVector2objects compute their result
using the cheapest approach.  If you have aVector2object
defined using polar coordinates, and you call.rotate()or.scale()on it, all the math is done in the polar domain.  On the other
hand, adding vectors isalmostalways done in the cartesian domain,
so if you add a polar vector to any other vector, its cartesian
coordinates will likely be computed--and the resulting vector will always
be defined using cartesian coordinates.What's the exception?  There's a special case for adding two polar vectors
which have the exact sametheta: just add theirrvalues.
That approach is much cheaper than converting to cartesian,
and more precise as well, returning a vector defined using polar
coordinates!Vector2takes advantage of many such serendipities,
performing your vector math as cheaply and accurately as possible.The APIVector2(x=None, y=None, *, r=None, theta=None, r_squared=None)Constructs a `Vector2` object.  You may pass in as many or as
few of these arguments as you like; however, you *must* pass in
*either* both `x` and `y` *or* both `r` and `theta`.
Any attributes not passed in at construction time will be lazily
computed at the time they are evaluated.You can also pass in a single object which will initialize the
vector.  Supported objects include:an existingVector2object (just returns that object),an object which has.xand.yattributes,a mapping object with exactly two keys,'x'and'y', andan ordered iterable object with exactly two elements.Vector2only doessomevalidation of its arguments.
It ensures thatrandthetaare normalized.  However,
it doesn't check that(x, y)and(r, theta)describe the
same vector.
If you pass inxandy, and also pass in athetaandrthat don't match, you'll get back theVector2that you
asked for.  Good luck!AttributesVector2objects support five attributes:x,y,r,theta, andr_squared.  It doesn't matter
whether the object was defined with cartesian or polar
coordinates, they'll all work.r_squaredis equivalent tor*r.  But if you have
aVector2object defined with cartesian coordinates,
it's much cheaper to computer_squaredthanr.
And there are many use cases wherer_squaredworks
just as well asr.For example, consider collision detection in a game.  One
way to decide whether two objects are colliding is to measure
the distance between them--if it's less than a certain distanceR, the two objects are colliding.  But computing the
actual distance is expensive--it requires a time-consuming
square root.  It's much cheaper to compute the distance-squared
between the two points.  If that's less thanR2, the two
objects are colliding.Operators and protocolsVector2objects support theiterator protocol.len()on aVector2object will always return 2.
You can also iterate over aVector2object,
which will yield thexandyattributes in that order.Vector2objects support thesequence protocol.You can subscript
them, which behaves as if theVector2object is a tuple of length
2 containing thexandyattributes.Vector2objects also support thebooleanprotocol; you may use them
with boolean operators, and you may callbool()on them.  When used in
a boolean context, the zero vector evaluates toFalse, and all other
vectors evaluate toTrue.Vector2objects arehashable,but they're notordered.
(You can't ask if one vector isless thananother.)Vector2objects support the following operators:v1 + v2adds the two vectors together.v1 - v2subtracts the right vector from the left vector.v1 * scalarmulitplies the vector by a scalar amount, equivalent tov1.scale(scalar).v1 / scalardivides the vector by a scalar amount.+v1is exactly the same asv1.-v1returns the opposite ofv1, such thatv1 + (-v1)should be the zero vector.
(This may not always be the case due to compounding floating-point errors.)v1 == v2isTrueif the two vectors areexactlythe same, andFalseotherwise.
For consistency, this only compares cartesian coordinates.
Note that floating-point imprecision may result in two vectors thatshouldbe the
same failing an==check.  Consider using thealmost_equalmethod, which allows
for some imprecision in its comparison.v1 != v2isFalseif the two vectors areexactlythe same, andTrueotherwise.
For consistency, this only compares cartesian coordinates.
Note that floating-point imprecision may result in two vectors thatshouldbe the
same passing an!=check.  Again, consider using thealmost_equalmethod and
negating the results.v[0]andv.xevaluate to the same number.v[1]andv.yevaluate to the same number.list(v)is the same as[v.x, v.y].Class methodsvec.from_polar(r, theta)Constructs a `Vector2` object from the two polar coordinates
`r` and `theta`.You can also pass in a single object which will be used to
initialize the vector.  Supported objects include:an existingVector2object (just returns that object),an object which has.rand.thetaattributes,a mapping object with exactly two keys,'r'and'theta', andan ordered iterable object with exactly two elements.Ifris0,thetamust beNone, andfrom_polarwill
return the zero vector.  Ifris not0,thetamust not
beNone.MethodsVector2objects support the following methods:Vector2.almost_equal(other, places)Returns `True` if the vector and `other` are the same vector,
down to `places` decimal places.  Like the `Vector2` class's
support for the `==` operator, the comparison is only done
using cartesian coordinates, for consistency.Vector2.scaled(scalar)Returns a new `Vector2` object, equivalent to the original vector multiplied by that scalar.Vector2.scaled_to_length(r)Returns a new `Vector2` object, equivalent to the original vector with its length set to `r`.Vector2.normalized()Returns a new `Vector2` object, equivalent to the original vector scaled to length 1.Vector2.rotated(theta)Returns a new `Vector2` object, equal to the original vector rotated by `theta` radians.Vector2.dot(other)Returns the "dot product" `self` • `other`.  This result is a scalar value, not a vector.Vector2.cross(other)Returns the "cross product" `self` ⨯ `other`.  This result is a scalar value, not a vector.Note:technically, there is no "cross product" defined for 2-dimensional vectors.
In actuality this returns the "perpendicular dot product", or "perp dot product",
of the two vectors, because that's what people actually want when they ask for the "cross
product" of two 2D vectors.Vector2.polar()Returns a 2-tuple of `(self.r, self.theta)`.Vector2.lerp(other, ratio)Returns a vector representing a linear interpolation between `self` and `other`, according
to the scalar ratio `ratio`.  `ratio` should be a value between (and including) `0` and `1`.
If `ratio` is `0`, this returns `self`.  If `ratio` is `1`, this returns `other`.
If `ratio` is between `0` and `1` non-inclusive, this returns a point on the line segment
defined by the two endpoints `self` and `other`, with the point being `ratio` between `self`
and `other`.  For example, if `ratio` is `0.4`, this returns `(self * 0.6) + (other * 0.4)`.Note that it's not an error to specify aratioless than0or greater than1, andratiois not clamped to this range.Vector2.slerp(other, ratio)Returns a vector representing a spherical interpolation between `self` and `other`, according
to the scalar ratio `ratio`.  `ratio` should be a value between (and including) `0` and `1`.
If `ratio` is `0`, this returns `self`.  If `ratio` is `1`, this returns `other`.Note that it's not an error to specify aratioless than0or greater than1, andratiois not clamped to this range.Vector2.nlerp(other, ratio)Returns a vector representing a normalized linear interpolation between `self` and `other`,
according to the scalar ratio `ratio`.  `ratio` should be a value between (and including)
`0` and `1`.  If `ratio` is `0`, this returns `self`.  If `ratio` is `1`, this returns `other`.Note that it's not an error to specify aratioless than0or greater than1, andratiois not clamped to this range.Constantsvector2_zeroThe "zero" `Vector2` vector object.
`vec` guarantees that every zero vector is a reference to this object:>>> v = vec.Vector2(0, 0)
>>> v is vec.vector2_zero
TrueMathematically-speaking, the zero vector when expressed in polar coordinates
doesn't have a defined angle.  Thereforevecdefines its zero vector as
having an angle ofNone.  The zero vector must haverset to zero
andthetaset toNone, and any other vector must have a non-zerorandthetaset to a value besidesNone.vector2_1_0A predefined `Vector2` vector object, equivalent to `Vector2(1, 0)`.
When constructing a `Vector2` object that is exactly equivalent to this
vector, the `Vector2` constructor will always return a reference to this
vector:>>> v = vec.Vector2(1, 0)
>>> v is vec.vector2_1_0
True
>>> v2 = vec.Vector2(r=1, theta=0)
>>> v2 is vec.vector2_1_0
Truevector2_0_1A predefined `Vector2` vector object, equivalent to `Vector2(0, 1)`.
When constructing a `Vector2` object that is exactly equivalent to this
vector, the `Vector2` constructor will always return a reference to this
vector:>>> v = vec.Vector2(0, 1)
>>> v is vec.vector2_0_1
True
>>> v2 = vec.Vector2(r=1, theta=pi/2)
>>> v2 is vec.vector2_0_1
Truevector2_1_1A predefined `Vector2` vector object, equivalent to `Vector2(1, 1)`.
When constructing a `Vector2` object that is exactly equivalent to this
vector, the `Vector2` constructor will always return a reference to this
vector:>>> v = vec.Vector2(1, 1)
>>> v is vec.vector2_1_1
True
>>> v2 = vec.Vector2(r=2 ** 0.5, theta=pi/4)
>>> v2 is vec.vector2_1_1
TrueExtending vec to handle other typesvecdoes some input verification on its inputs.
Coordinates--x,y,r,theta--are required to be
eitherintorlong.
(Technicallythetacan also beNone.)  This best serves
the intended use case ofvecas a 2D vector library for
game programming in Python.If you want to experiment withvecfor other use cases,
you may wantvecto permit other types to be valid
coordinates.vecprovides a simple mechanism to allow
this.  Simply call:vec.permit_coordinate_type(T)before creating your vector, passing in the type you want
to use as a coordinate asT, andvecwill now accept
objects of that type as coordinates.Note that the types you extendvecwith in this manner
should behave like numeric types, likeintandfloat.Changelog0.6.32023/10/26Added three new predefined vectors:vector2_1_0isVector2(1, 0)vector2_0_1isVector2(0, 1)vector2_1_1isVector2(1, 1)Any expression that results in a vector that would be exactly
equal to one of these vectors is guaranteed to return the
predefined vector.Vector2(1, 0) is vector2_1_0evaluates
toTrue.0.6.22023/06/14AddedVector2.almost_equal, which supports testing
for slightly-inexact equality.0.6.12023/06/14Enhanced theVector2constructor: now it also accepts
mappings.  The mapping must have exactly two elements,xandy.EnhancedVector2.from_polar.  It now accepts all the same
stuff as theVector2constructor:Vector2objects,
namespaces, mappings, and iterables.  Where it examines
names (attributes, keys) it naturally usesrandthetainstead ofxandy.0.62023/06/14A major improvement!vecnow has a proper test suite.vecnow passes its test suite with 100% coverage.vecexplicitly supports Python 3.6+.Added more shortcut optimizations, e.g. rotating a cartesian vector by a multiple ofpi/2.Tightened up the metaclass__call__logic a great deal.ImplementedVector2.slerp, and addedVector2.nlerp.Allowedvec.permit_coordinate_type, to allow extending the
set of permissible types for coordinates.Internal details:Now cache_cartesianand_hashinternally, as well as_polar.
(A vector can have a complete set of both cartesian and polar coordinates,
so it's nice to know everything that's available--that can make some
operations faster.)Bugfix:Vector2.dot()was simply wrong, it was adding where it should
have been multiplying.  Fixes #3.0.52021/03/21Initial version.