euclid.py 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242
  1. #!/usr/bin/env python
  2. #
  3. # euclid graphics maths module
  4. #
  5. # Copyright (c) 2006 Alex Holkner
  6. # Alex.Holkner@mail.google.com
  7. #
  8. # This library is free software; you can redistribute it and/or modify it
  9. # under the terms of the GNU Lesser General Public License as published by the
  10. # Free Software Foundation; either version 2.1 of the License, or (at your
  11. # option) any later version.
  12. #
  13. # This library is distributed in the hope that it will be useful, but WITHOUT
  14. # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  15. # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
  16. # for more details.
  17. #
  18. # You should have received a copy of the GNU Lesser General Public License
  19. # along with this library; if not, write to the Free Software Foundation,
  20. # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  21. '''euclid graphics maths module
  22. Documentation and tests are included in the file "euclid.txt", or online
  23. at http://code.google.com/p/pyeuclid
  24. '''
  25. __docformat__ = 'restructuredtext'
  26. __version__ = '$Id$'
  27. __revision__ = '$Revision$'
  28. import math
  29. import operator
  30. import types
  31. # Some magic here. If _use_slots is True, the classes will derive from
  32. # object and will define a __slots__ class variable. If _use_slots is
  33. # False, classes will be old-style and will not define __slots__.
  34. #
  35. # _use_slots = True: Memory efficient, probably faster in future versions
  36. # of Python, "better".
  37. # _use_slots = False: Ordinary classes, much faster than slots in current
  38. # versions of Python (2.4 and 2.5).
  39. _use_slots = True
  40. # If True, allows components of Vector2 and Vector3 to be set via swizzling;
  41. # e.g. v.xyz = (1, 2, 3). This is much, much slower than the more verbose
  42. # v.x = 1; v.y = 2; v.z = 3, and slows down ordinary element setting as
  43. # well. Recommended setting is False.
  44. _enable_swizzle_set = False
  45. # Requires class to derive from object.
  46. if _enable_swizzle_set:
  47. _use_slots = True
  48. # Implement _use_slots magic.
  49. class _EuclidMetaclass(type):
  50. def __new__(cls, name, bases, dct):
  51. if '__slots__' in dct:
  52. dct['__getstate__'] = cls._create_getstate(dct['__slots__'])
  53. dct['__setstate__'] = cls._create_setstate(dct['__slots__'])
  54. if _use_slots:
  55. return type.__new__(cls, name, bases + (object,), dct)
  56. else:
  57. if '__slots__' in dct:
  58. del dct['__slots__']
  59. return types.ClassType.__new__(types.ClassType, name, bases, dct)
  60. @classmethod
  61. def _create_getstate(cls, slots):
  62. def __getstate__(self):
  63. d = {}
  64. for slot in slots:
  65. d[slot] = getattr(self, slot)
  66. return d
  67. return __getstate__
  68. @classmethod
  69. def _create_setstate(cls, slots):
  70. def __setstate__(self, state):
  71. for name, value in state.items():
  72. setattr(self, name, value)
  73. return __setstate__
  74. __metaclass__ = _EuclidMetaclass
  75. class Vector2:
  76. __slots__ = ['x', 'y']
  77. __hash__ = None
  78. def __init__(self, x=0, y=0):
  79. self.x = x
  80. self.y = y
  81. def __copy__(self):
  82. return self.__class__(self.x, self.y)
  83. copy = __copy__
  84. def __repr__(self):
  85. return 'Vector2(%.2f, %.2f)' % (self.x, self.y)
  86. def __eq__(self, other):
  87. if isinstance(other, Vector2):
  88. return self.x == other.x and \
  89. self.y == other.y
  90. else:
  91. assert hasattr(other, '__len__') and len(other) == 2
  92. return self.x == other[0] and \
  93. self.y == other[1]
  94. def __ne__(self, other):
  95. return not self.__eq__(other)
  96. def __nonzero__(self):
  97. return self.x != 0 or self.y != 0
  98. def __len__(self):
  99. return 2
  100. def __getitem__(self, key):
  101. return (self.x, self.y)[key]
  102. def __setitem__(self, key, value):
  103. l = [self.x, self.y]
  104. l[key] = value
  105. self.x, self.y = l
  106. def __iter__(self):
  107. return iter((self.x, self.y))
  108. def __getattr__(self, name):
  109. try:
  110. return tuple([(self.x, self.y)['xy'.index(c)] \
  111. for c in name])
  112. except ValueError:
  113. raise AttributeError, name
  114. if _enable_swizzle_set:
  115. # This has detrimental performance on ordinary setattr as well
  116. # if enabled
  117. def __setattr__(self, name, value):
  118. if len(name) == 1:
  119. object.__setattr__(self, name, value)
  120. else:
  121. try:
  122. l = [self.x, self.y]
  123. for c, v in map(None, name, value):
  124. l['xy'.index(c)] = v
  125. self.x, self.y = l
  126. except ValueError:
  127. raise AttributeError, name
  128. def __add__(self, other):
  129. if isinstance(other, Vector2):
  130. # Vector + Vector -> Vector
  131. # Vector + Point -> Point
  132. # Point + Point -> Vector
  133. if self.__class__ is other.__class__:
  134. _class = Vector2
  135. else:
  136. _class = Point2
  137. return _class(self.x + other.x,
  138. self.y + other.y)
  139. else:
  140. assert hasattr(other, '__len__') and len(other) == 2
  141. return Vector2(self.x + other[0],
  142. self.y + other[1])
  143. __radd__ = __add__
  144. def __iadd__(self, other):
  145. if isinstance(other, Vector2):
  146. self.x += other.x
  147. self.y += other.y
  148. else:
  149. self.x += other[0]
  150. self.y += other[1]
  151. return self
  152. def __sub__(self, other):
  153. if isinstance(other, Vector2):
  154. # Vector - Vector -> Vector
  155. # Vector - Point -> Point
  156. # Point - Point -> Vector
  157. if self.__class__ is other.__class__:
  158. _class = Vector2
  159. else:
  160. _class = Point2
  161. return _class(self.x - other.x,
  162. self.y - other.y)
  163. else:
  164. assert hasattr(other, '__len__') and len(other) == 2
  165. return Vector2(self.x - other[0],
  166. self.y - other[1])
  167. def __rsub__(self, other):
  168. if isinstance(other, Vector2):
  169. return Vector2(other.x - self.x,
  170. other.y - self.y)
  171. else:
  172. assert hasattr(other, '__len__') and len(other) == 2
  173. return Vector2(other.x - self[0],
  174. other.y - self[1])
  175. def __mul__(self, other):
  176. assert type(other) in (int, long, float)
  177. return Vector2(self.x * other,
  178. self.y * other)
  179. __rmul__ = __mul__
  180. def __imul__(self, other):
  181. assert type(other) in (int, long, float)
  182. self.x *= other
  183. self.y *= other
  184. return self
  185. def __div__(self, other):
  186. assert type(other) in (int, long, float)
  187. return Vector2(operator.div(self.x, other),
  188. operator.div(self.y, other))
  189. def __rdiv__(self, other):
  190. assert type(other) in (int, long, float)
  191. return Vector2(operator.div(other, self.x),
  192. operator.div(other, self.y))
  193. def __floordiv__(self, other):
  194. assert type(other) in (int, long, float)
  195. return Vector2(operator.floordiv(self.x, other),
  196. operator.floordiv(self.y, other))
  197. def __rfloordiv__(self, other):
  198. assert type(other) in (int, long, float)
  199. return Vector2(operator.floordiv(other, self.x),
  200. operator.floordiv(other, self.y))
  201. def __truediv__(self, other):
  202. assert type(other) in (int, long, float)
  203. return Vector2(operator.truediv(self.x, other),
  204. operator.truediv(self.y, other))
  205. def __rtruediv__(self, other):
  206. assert type(other) in (int, long, float)
  207. return Vector2(operator.truediv(other, self.x),
  208. operator.truediv(other, self.y))
  209. def __neg__(self):
  210. return Vector2(-self.x,
  211. -self.y)
  212. __pos__ = __copy__
  213. def __abs__(self):
  214. return math.sqrt(self.x ** 2 + \
  215. self.y ** 2)
  216. magnitude = __abs__
  217. def magnitude_squared(self):
  218. return self.x ** 2 + \
  219. self.y ** 2
  220. def normalize(self):
  221. d = self.magnitude()
  222. if d:
  223. self.x /= d
  224. self.y /= d
  225. return self
  226. def normalized(self):
  227. d = self.magnitude()
  228. if d:
  229. return Vector2(self.x / d,
  230. self.y / d)
  231. return self.copy()
  232. def dot(self, other):
  233. assert isinstance(other, Vector2)
  234. return self.x * other.x + \
  235. self.y * other.y
  236. def cross(self):
  237. return Vector2(self.y, -self.x)
  238. def reflect(self, normal):
  239. # assume normal is normalized
  240. assert isinstance(normal, Vector2)
  241. d = 2 * (self.x * normal.x + self.y * normal.y)
  242. return Vector2(self.x - d * normal.x,
  243. self.y - d * normal.y)
  244. class Vector3:
  245. __slots__ = ['x', 'y', 'z']
  246. __hash__ = None
  247. def __init__(self, x=0, y=0, z=0):
  248. self.x = x
  249. self.y = y
  250. self.z = z
  251. def __copy__(self):
  252. return self.__class__(self.x, self.y, self.z)
  253. copy = __copy__
  254. def __repr__(self):
  255. return 'Vector3(%.2f, %.2f, %.2f)' % (self.x,
  256. self.y,
  257. self.z)
  258. def __eq__(self, other):
  259. if isinstance(other, Vector3):
  260. return self.x == other.x and \
  261. self.y == other.y and \
  262. self.z == other.z
  263. else:
  264. assert hasattr(other, '__len__') and len(other) == 3
  265. return self.x == other[0] and \
  266. self.y == other[1] and \
  267. self.z == other[2]
  268. def __ne__(self, other):
  269. return not self.__eq__(other)
  270. def __nonzero__(self):
  271. return self.x != 0 or self.y != 0 or self.z != 0
  272. def __len__(self):
  273. return 3
  274. def __getitem__(self, key):
  275. return (self.x, self.y, self.z)[key]
  276. def __setitem__(self, key, value):
  277. l = [self.x, self.y, self.z]
  278. l[key] = value
  279. self.x, self.y, self.z = l
  280. def __iter__(self):
  281. return iter((self.x, self.y, self.z))
  282. def __getattr__(self, name):
  283. try:
  284. return tuple([(self.x, self.y, self.z)['xyz'.index(c)] \
  285. for c in name])
  286. except ValueError:
  287. raise AttributeError, name
  288. if _enable_swizzle_set:
  289. # This has detrimental performance on ordinary setattr as well
  290. # if enabled
  291. def __setattr__(self, name, value):
  292. if len(name) == 1:
  293. object.__setattr__(self, name, value)
  294. else:
  295. try:
  296. l = [self.x, self.y, self.z]
  297. for c, v in map(None, name, value):
  298. l['xyz'.index(c)] = v
  299. self.x, self.y, self.z = l
  300. except ValueError:
  301. raise AttributeError, name
  302. def __add__(self, other):
  303. if isinstance(other, Vector3):
  304. # Vector + Vector -> Vector
  305. # Vector + Point -> Point
  306. # Point + Point -> Vector
  307. if self.__class__ is other.__class__:
  308. _class = Vector3
  309. else:
  310. _class = Point3
  311. return _class(self.x + other.x,
  312. self.y + other.y,
  313. self.z + other.z)
  314. else:
  315. assert hasattr(other, '__len__') and len(other) == 3
  316. return Vector3(self.x + other[0],
  317. self.y + other[1],
  318. self.z + other[2])
  319. __radd__ = __add__
  320. def __iadd__(self, other):
  321. if isinstance(other, Vector3):
  322. self.x += other.x
  323. self.y += other.y
  324. self.z += other.z
  325. else:
  326. self.x += other[0]
  327. self.y += other[1]
  328. self.z += other[2]
  329. return self
  330. def __sub__(self, other):
  331. if isinstance(other, Vector3):
  332. # Vector - Vector -> Vector
  333. # Vector - Point -> Point
  334. # Point - Point -> Vector
  335. if self.__class__ is other.__class__:
  336. _class = Vector3
  337. else:
  338. _class = Point3
  339. return Vector3(self.x - other.x,
  340. self.y - other.y,
  341. self.z - other.z)
  342. else:
  343. assert hasattr(other, '__len__') and len(other) == 3
  344. return Vector3(self.x - other[0],
  345. self.y - other[1],
  346. self.z - other[2])
  347. def __rsub__(self, other):
  348. if isinstance(other, Vector3):
  349. return Vector3(other.x - self.x,
  350. other.y - self.y,
  351. other.z - self.z)
  352. else:
  353. assert hasattr(other, '__len__') and len(other) == 3
  354. return Vector3(other.x - self[0],
  355. other.y - self[1],
  356. other.z - self[2])
  357. def __mul__(self, other):
  358. if isinstance(other, Vector3):
  359. # TODO component-wise mul/div in-place and on Vector2; docs.
  360. if self.__class__ is Point3 or other.__class__ is Point3:
  361. _class = Point3
  362. else:
  363. _class = Vector3
  364. return _class(self.x * other.x,
  365. self.y * other.y,
  366. self.z * other.z)
  367. else:
  368. assert type(other) in (int, long, float)
  369. return Vector3(self.x * other,
  370. self.y * other,
  371. self.z * other)
  372. __rmul__ = __mul__
  373. def __imul__(self, other):
  374. assert type(other) in (int, long, float)
  375. self.x *= other
  376. self.y *= other
  377. self.z *= other
  378. return self
  379. def __div__(self, other):
  380. assert type(other) in (int, long, float)
  381. return Vector3(operator.div(self.x, other),
  382. operator.div(self.y, other),
  383. operator.div(self.z, other))
  384. def __rdiv__(self, other):
  385. assert type(other) in (int, long, float)
  386. return Vector3(operator.div(other, self.x),
  387. operator.div(other, self.y),
  388. operator.div(other, self.z))
  389. def __floordiv__(self, other):
  390. assert type(other) in (int, long, float)
  391. return Vector3(operator.floordiv(self.x, other),
  392. operator.floordiv(self.y, other),
  393. operator.floordiv(self.z, other))
  394. def __rfloordiv__(self, other):
  395. assert type(other) in (int, long, float)
  396. return Vector3(operator.floordiv(other, self.x),
  397. operator.floordiv(other, self.y),
  398. operator.floordiv(other, self.z))
  399. def __truediv__(self, other):
  400. assert type(other) in (int, long, float)
  401. return Vector3(operator.truediv(self.x, other),
  402. operator.truediv(self.y, other),
  403. operator.truediv(self.z, other))
  404. def __rtruediv__(self, other):
  405. assert type(other) in (int, long, float)
  406. return Vector3(operator.truediv(other, self.x),
  407. operator.truediv(other, self.y),
  408. operator.truediv(other, self.z))
  409. def __neg__(self):
  410. return Vector3(-self.x,
  411. -self.y,
  412. -self.z)
  413. __pos__ = __copy__
  414. def __abs__(self):
  415. return math.sqrt(self.x ** 2 + \
  416. self.y ** 2 + \
  417. self.z ** 2)
  418. magnitude = __abs__
  419. def magnitude_squared(self):
  420. return self.x ** 2 + \
  421. self.y ** 2 + \
  422. self.z ** 2
  423. def normalize(self):
  424. d = self.magnitude()
  425. if d:
  426. self.x /= d
  427. self.y /= d
  428. self.z /= d
  429. return self
  430. def normalized(self):
  431. d = self.magnitude()
  432. if d:
  433. return Vector3(self.x / d,
  434. self.y / d,
  435. self.z / d)
  436. return self.copy()
  437. def dot(self, other):
  438. assert isinstance(other, Vector3)
  439. return self.x * other.x + \
  440. self.y * other.y + \
  441. self.z * other.z
  442. def cross(self, other):
  443. assert isinstance(other, Vector3)
  444. return Vector3(self.y * other.z - self.z * other.y,
  445. -self.x * other.z + self.z * other.x,
  446. self.x * other.y - self.y * other.x)
  447. def reflect(self, normal):
  448. # assume normal is normalized
  449. assert isinstance(normal, Vector3)
  450. d = 2 * (self.x * normal.x + self.y * normal.y + self.z * normal.z)
  451. return Vector3(self.x - d * normal.x,
  452. self.y - d * normal.y,
  453. self.z - d * normal.z)
  454. # a b c
  455. # e f g
  456. # i j k
  457. class Matrix3:
  458. __slots__ = list('abcefgijk')
  459. def __init__(self):
  460. self.identity()
  461. def __copy__(self):
  462. M = Matrix3()
  463. M.a = self.a
  464. M.b = self.b
  465. M.c = self.c
  466. M.e = self.e
  467. M.f = self.f
  468. M.g = self.g
  469. M.i = self.i
  470. M.j = self.j
  471. M.k = self.k
  472. return M
  473. copy = __copy__
  474. def __repr__(self):
  475. return ('Matrix3([% 8.2f % 8.2f % 8.2f\n' \
  476. ' % 8.2f % 8.2f % 8.2f\n' \
  477. ' % 8.2f % 8.2f % 8.2f])') \
  478. % (self.a, self.b, self.c,
  479. self.e, self.f, self.g,
  480. self.i, self.j, self.k)
  481. def __getitem__(self, key):
  482. return [self.a, self.e, self.i,
  483. self.b, self.f, self.j,
  484. self.c, self.g, self.k][key]
  485. def __setitem__(self, key, value):
  486. L = self[:]
  487. L[key] = value
  488. (self.a, self.e, self.i,
  489. self.b, self.f, self.j,
  490. self.c, self.g, self.k) = L
  491. def __mul__(self, other):
  492. if isinstance(other, Matrix3):
  493. # Caching repeatedly accessed attributes in local variables
  494. # apparently increases performance by 20%. Attrib: Will McGugan.
  495. Aa = self.a
  496. Ab = self.b
  497. Ac = self.c
  498. Ae = self.e
  499. Af = self.f
  500. Ag = self.g
  501. Ai = self.i
  502. Aj = self.j
  503. Ak = self.k
  504. Ba = other.a
  505. Bb = other.b
  506. Bc = other.c
  507. Be = other.e
  508. Bf = other.f
  509. Bg = other.g
  510. Bi = other.i
  511. Bj = other.j
  512. Bk = other.k
  513. C = Matrix3()
  514. C.a = Aa * Ba + Ab * Be + Ac * Bi
  515. C.b = Aa * Bb + Ab * Bf + Ac * Bj
  516. C.c = Aa * Bc + Ab * Bg + Ac * Bk
  517. C.e = Ae * Ba + Af * Be + Ag * Bi
  518. C.f = Ae * Bb + Af * Bf + Ag * Bj
  519. C.g = Ae * Bc + Af * Bg + Ag * Bk
  520. C.i = Ai * Ba + Aj * Be + Ak * Bi
  521. C.j = Ai * Bb + Aj * Bf + Ak * Bj
  522. C.k = Ai * Bc + Aj * Bg + Ak * Bk
  523. return C
  524. elif isinstance(other, Point2):
  525. A = self
  526. B = other
  527. P = Point2(0, 0)
  528. P.x = A.a * B.x + A.b * B.y + A.c
  529. P.y = A.e * B.x + A.f * B.y + A.g
  530. return P
  531. elif isinstance(other, Vector2):
  532. A = self
  533. B = other
  534. V = Vector2(0, 0)
  535. V.x = A.a * B.x + A.b * B.y
  536. V.y = A.e * B.x + A.f * B.y
  537. return V
  538. else:
  539. other = other.copy()
  540. other._apply_transform(self)
  541. return other
  542. def __imul__(self, other):
  543. assert isinstance(other, Matrix3)
  544. # Cache attributes in local vars (see Matrix3.__mul__).
  545. Aa = self.a
  546. Ab = self.b
  547. Ac = self.c
  548. Ae = self.e
  549. Af = self.f
  550. Ag = self.g
  551. Ai = self.i
  552. Aj = self.j
  553. Ak = self.k
  554. Ba = other.a
  555. Bb = other.b
  556. Bc = other.c
  557. Be = other.e
  558. Bf = other.f
  559. Bg = other.g
  560. Bi = other.i
  561. Bj = other.j
  562. Bk = other.k
  563. self.a = Aa * Ba + Ab * Be + Ac * Bi
  564. self.b = Aa * Bb + Ab * Bf + Ac * Bj
  565. self.c = Aa * Bc + Ab * Bg + Ac * Bk
  566. self.e = Ae * Ba + Af * Be + Ag * Bi
  567. self.f = Ae * Bb + Af * Bf + Ag * Bj
  568. self.g = Ae * Bc + Af * Bg + Ag * Bk
  569. self.i = Ai * Ba + Aj * Be + Ak * Bi
  570. self.j = Ai * Bb + Aj * Bf + Ak * Bj
  571. self.k = Ai * Bc + Aj * Bg + Ak * Bk
  572. return self
  573. def identity(self):
  574. self.a = self.f = self.k = 1.
  575. self.b = self.c = self.e = self.g = self.i = self.j = 0
  576. return self
  577. def scale(self, x, y):
  578. self *= Matrix3.new_scale(x, y)
  579. return self
  580. def translate(self, x, y):
  581. self *= Matrix3.new_translate(x, y)
  582. return self
  583. def rotate(self, angle):
  584. self *= Matrix3.new_rotate(angle)
  585. return self
  586. # Static constructors
  587. def new_identity(cls):
  588. self = cls()
  589. return self
  590. new_identity = classmethod(new_identity)
  591. def new_scale(cls, x, y):
  592. self = cls()
  593. self.a = x
  594. self.f = y
  595. return self
  596. new_scale = classmethod(new_scale)
  597. def new_translate(cls, x, y):
  598. self = cls()
  599. self.c = x
  600. self.g = y
  601. return self
  602. new_translate = classmethod(new_translate)
  603. def new_rotate(cls, angle):
  604. self = cls()
  605. s = math.sin(angle)
  606. c = math.cos(angle)
  607. self.a = self.f = c
  608. self.b = -s
  609. self.e = s
  610. return self
  611. new_rotate = classmethod(new_rotate)
  612. # a b c d
  613. # e f g h
  614. # i j k l
  615. # m n o p
  616. class Matrix4:
  617. __slots__ = list('abcdefghijklmnop')
  618. def __init__(self):
  619. self.identity()
  620. def __copy__(self):
  621. M = Matrix4()
  622. M.a = self.a
  623. M.b = self.b
  624. M.c = self.c
  625. M.d = self.d
  626. M.e = self.e
  627. M.f = self.f
  628. M.g = self.g
  629. M.h = self.h
  630. M.i = self.i
  631. M.j = self.j
  632. M.k = self.k
  633. M.l = self.l
  634. M.m = self.m
  635. M.n = self.n
  636. M.o = self.o
  637. M.p = self.p
  638. return M
  639. copy = __copy__
  640. def __repr__(self):
  641. return ('Matrix4([% 8.2f % 8.2f % 8.2f % 8.2f\n' \
  642. ' % 8.2f % 8.2f % 8.2f % 8.2f\n' \
  643. ' % 8.2f % 8.2f % 8.2f % 8.2f\n' \
  644. ' % 8.2f % 8.2f % 8.2f % 8.2f])') \
  645. % (self.a, self.b, self.c, self.d,
  646. self.e, self.f, self.g, self.h,
  647. self.i, self.j, self.k, self.l,
  648. self.m, self.n, self.o, self.p)
  649. def __getitem__(self, key):
  650. return [self.a, self.e, self.i, self.m,
  651. self.b, self.f, self.j, self.n,
  652. self.c, self.g, self.k, self.o,
  653. self.d, self.h, self.l, self.p][key]
  654. def __setitem__(self, key, value):
  655. L = self[:]
  656. L[key] = value
  657. (self.a, self.e, self.i, self.m,
  658. self.b, self.f, self.j, self.n,
  659. self.c, self.g, self.k, self.o,
  660. self.d, self.h, self.l, self.p) = L
  661. def __mul__(self, other):
  662. if isinstance(other, Matrix4):
  663. # Cache attributes in local vars (see Matrix3.__mul__).
  664. Aa = self.a
  665. Ab = self.b
  666. Ac = self.c
  667. Ad = self.d
  668. Ae = self.e
  669. Af = self.f
  670. Ag = self.g
  671. Ah = self.h
  672. Ai = self.i
  673. Aj = self.j
  674. Ak = self.k
  675. Al = self.l
  676. Am = self.m
  677. An = self.n
  678. Ao = self.o
  679. Ap = self.p
  680. Ba = other.a
  681. Bb = other.b
  682. Bc = other.c
  683. Bd = other.d
  684. Be = other.e
  685. Bf = other.f
  686. Bg = other.g
  687. Bh = other.h
  688. Bi = other.i
  689. Bj = other.j
  690. Bk = other.k
  691. Bl = other.l
  692. Bm = other.m
  693. Bn = other.n
  694. Bo = other.o
  695. Bp = other.p
  696. C = Matrix4()
  697. C.a = Aa * Ba + Ab * Be + Ac * Bi + Ad * Bm
  698. C.b = Aa * Bb + Ab * Bf + Ac * Bj + Ad * Bn
  699. C.c = Aa * Bc + Ab * Bg + Ac * Bk + Ad * Bo
  700. C.d = Aa * Bd + Ab * Bh + Ac * Bl + Ad * Bp
  701. C.e = Ae * Ba + Af * Be + Ag * Bi + Ah * Bm
  702. C.f = Ae * Bb + Af * Bf + Ag * Bj + Ah * Bn
  703. C.g = Ae * Bc + Af * Bg + Ag * Bk + Ah * Bo
  704. C.h = Ae * Bd + Af * Bh + Ag * Bl + Ah * Bp
  705. C.i = Ai * Ba + Aj * Be + Ak * Bi + Al * Bm
  706. C.j = Ai * Bb + Aj * Bf + Ak * Bj + Al * Bn
  707. C.k = Ai * Bc + Aj * Bg + Ak * Bk + Al * Bo
  708. C.l = Ai * Bd + Aj * Bh + Ak * Bl + Al * Bp
  709. C.m = Am * Ba + An * Be + Ao * Bi + Ap * Bm
  710. C.n = Am * Bb + An * Bf + Ao * Bj + Ap * Bn
  711. C.o = Am * Bc + An * Bg + Ao * Bk + Ap * Bo
  712. C.p = Am * Bd + An * Bh + Ao * Bl + Ap * Bp
  713. return C
  714. elif isinstance(other, Point3):
  715. A = self
  716. B = other
  717. P = Point3(0, 0, 0)
  718. P.x = A.a * B.x + A.b * B.y + A.c * B.z + A.d
  719. P.y = A.e * B.x + A.f * B.y + A.g * B.z + A.h
  720. P.z = A.i * B.x + A.j * B.y + A.k * B.z + A.l
  721. return P
  722. elif isinstance(other, Vector3):
  723. A = self
  724. B = other
  725. V = Vector3(0, 0, 0)
  726. V.x = A.a * B.x + A.b * B.y + A.c * B.z
  727. V.y = A.e * B.x + A.f * B.y + A.g * B.z
  728. V.z = A.i * B.x + A.j * B.y + A.k * B.z
  729. return V
  730. else:
  731. other = other.copy()
  732. other._apply_transform(self)
  733. return other
  734. def __imul__(self, other):
  735. assert isinstance(other, Matrix4)
  736. # Cache attributes in local vars (see Matrix3.__mul__).
  737. Aa = self.a
  738. Ab = self.b
  739. Ac = self.c
  740. Ad = self.d
  741. Ae = self.e
  742. Af = self.f
  743. Ag = self.g
  744. Ah = self.h
  745. Ai = self.i
  746. Aj = self.j
  747. Ak = self.k
  748. Al = self.l
  749. Am = self.m
  750. An = self.n
  751. Ao = self.o
  752. Ap = self.p
  753. Ba = other.a
  754. Bb = other.b
  755. Bc = other.c
  756. Bd = other.d
  757. Be = other.e
  758. Bf = other.f
  759. Bg = other.g
  760. Bh = other.h
  761. Bi = other.i
  762. Bj = other.j
  763. Bk = other.k
  764. Bl = other.l
  765. Bm = other.m
  766. Bn = other.n
  767. Bo = other.o
  768. Bp = other.p
  769. self.a = Aa * Ba + Ab * Be + Ac * Bi + Ad * Bm
  770. self.b = Aa * Bb + Ab * Bf + Ac * Bj + Ad * Bn
  771. self.c = Aa * Bc + Ab * Bg + Ac * Bk + Ad * Bo
  772. self.d = Aa * Bd + Ab * Bh + Ac * Bl + Ad * Bp
  773. self.e = Ae * Ba + Af * Be + Ag * Bi + Ah * Bm
  774. self.f = Ae * Bb + Af * Bf + Ag * Bj + Ah * Bn
  775. self.g = Ae * Bc + Af * Bg + Ag * Bk + Ah * Bo
  776. self.h = Ae * Bd + Af * Bh + Ag * Bl + Ah * Bp
  777. self.i = Ai * Ba + Aj * Be + Ak * Bi + Al * Bm
  778. self.j = Ai * Bb + Aj * Bf + Ak * Bj + Al * Bn
  779. self.k = Ai * Bc + Aj * Bg + Ak * Bk + Al * Bo
  780. self.l = Ai * Bd + Aj * Bh + Ak * Bl + Al * Bp
  781. self.m = Am * Ba + An * Be + Ao * Bi + Ap * Bm
  782. self.n = Am * Bb + An * Bf + Ao * Bj + Ap * Bn
  783. self.o = Am * Bc + An * Bg + Ao * Bk + Ap * Bo
  784. self.p = Am * Bd + An * Bh + Ao * Bl + Ap * Bp
  785. return self
  786. def transform(self, other):
  787. A = self
  788. B = other
  789. P = Point3(0, 0, 0)
  790. P.x = A.a * B.x + A.b * B.y + A.c * B.z + A.d
  791. P.y = A.e * B.x + A.f * B.y + A.g * B.z + A.h
  792. P.z = A.i * B.x + A.j * B.y + A.k * B.z + A.l
  793. w = A.m * B.x + A.n * B.y + A.o * B.z + A.p
  794. if w != 0:
  795. P.x /= w
  796. P.y /= w
  797. P.z /= w
  798. return P
  799. def identity(self):
  800. self.a = self.f = self.k = self.p = 1.
  801. self.b = self.c = self.d = self.e = self.g = self.h = \
  802. self.i = self.j = self.l = self.m = self.n = self.o = 0
  803. return self
  804. def scale(self, x, y, z):
  805. self *= Matrix4.new_scale(x, y, z)
  806. return self
  807. def translate(self, x, y, z):
  808. self *= Matrix4.new_translate(x, y, z)
  809. return self
  810. def rotatex(self, angle):
  811. self *= Matrix4.new_rotatex(angle)
  812. return self
  813. def rotatey(self, angle):
  814. self *= Matrix4.new_rotatey(angle)
  815. return self
  816. def rotatez(self, angle):
  817. self *= Matrix4.new_rotatez(angle)
  818. return self
  819. def rotate_axis(self, angle, axis):
  820. self *= Matrix4.new_rotate_axis(angle, axis)
  821. return self
  822. def rotate_euler(self, heading, attitude, bank):
  823. self *= Matrix4.new_rotate_euler(heading, attitude, bank)
  824. return self
  825. def rotate_triple_axis(self, x, y, z):
  826. self *= Matrix4.new_rotate_triple_axis(x, y, z)
  827. return self
  828. def transpose(self):
  829. (self.a, self.e, self.i, self.m,
  830. self.b, self.f, self.j, self.n,
  831. self.c, self.g, self.k, self.o,
  832. self.d, self.h, self.l, self.p) = \
  833. (self.a, self.b, self.c, self.d,
  834. self.e, self.f, self.g, self.h,
  835. self.i, self.j, self.k, self.l,
  836. self.m, self.n, self.o, self.p)
  837. def transposed(self):
  838. M = self.copy()
  839. M.transpose()
  840. return M
  841. # Static constructors
  842. def new(cls, *values):
  843. M = cls()
  844. M[:] = values
  845. return M
  846. new = classmethod(new)
  847. def new_identity(cls):
  848. self = cls()
  849. return self
  850. new_identity = classmethod(new_identity)
  851. def new_scale(cls, x, y, z):
  852. self = cls()
  853. self.a = x
  854. self.f = y
  855. self.k = z
  856. return self
  857. new_scale = classmethod(new_scale)
  858. def new_translate(cls, x, y, z):
  859. self = cls()
  860. self.d = x
  861. self.h = y
  862. self.l = z
  863. return self
  864. new_translate = classmethod(new_translate)
  865. def new_rotatex(cls, angle):
  866. self = cls()
  867. s = math.sin(angle)
  868. c = math.cos(angle)
  869. self.f = self.k = c
  870. self.g = -s
  871. self.j = s
  872. return self
  873. new_rotatex = classmethod(new_rotatex)
  874. def new_rotatey(cls, angle):
  875. self = cls()
  876. s = math.sin(angle)
  877. c = math.cos(angle)
  878. self.a = self.k = c
  879. self.c = s
  880. self.i = -s
  881. return self
  882. new_rotatey = classmethod(new_rotatey)
  883. def new_rotatez(cls, angle):
  884. self = cls()
  885. s = math.sin(angle)
  886. c = math.cos(angle)
  887. self.a = self.f = c
  888. self.b = -s
  889. self.e = s
  890. return self
  891. new_rotatez = classmethod(new_rotatez)
  892. def new_rotate_axis(cls, angle, axis):
  893. assert(isinstance(axis, Vector3))
  894. vector = axis.normalized()
  895. x = vector.x
  896. y = vector.y
  897. z = vector.z
  898. self = cls()
  899. s = math.sin(angle)
  900. c = math.cos(angle)
  901. c1 = 1. - c
  902. # from the glRotate man page
  903. self.a = x * x * c1 + c
  904. self.b = x * y * c1 - z * s
  905. self.c = x * z * c1 + y * s
  906. self.e = y * x * c1 + z * s
  907. self.f = y * y * c1 + c
  908. self.g = y * z * c1 - x * s
  909. self.i = x * z * c1 - y * s
  910. self.j = y * z * c1 + x * s
  911. self.k = z * z * c1 + c
  912. return self
  913. new_rotate_axis = classmethod(new_rotate_axis)
  914. def new_rotate_euler(cls, heading, attitude, bank):
  915. # from http://www.euclideanspace.com/
  916. ch = math.cos(heading)
  917. sh = math.sin(heading)
  918. ca = math.cos(attitude)
  919. sa = math.sin(attitude)
  920. cb = math.cos(bank)
  921. sb = math.sin(bank)
  922. self = cls()
  923. self.a = ch * ca
  924. self.b = sh * sb - ch * sa * cb
  925. self.c = ch * sa * sb + sh * cb
  926. self.e = sa
  927. self.f = ca * cb
  928. self.g = -ca * sb
  929. self.i = -sh * ca
  930. self.j = sh * sa * cb + ch * sb
  931. self.k = -sh * sa * sb + ch * cb
  932. return self
  933. new_rotate_euler = classmethod(new_rotate_euler)
  934. def new_rotate_triple_axis(cls, x, y, z):
  935. m = cls()
  936. m.a, m.b, m.c = x.x, y.x, z.x
  937. m.e, m.f, m.g = x.y, y.y, z.y
  938. m.i, m.j, m.k = x.z, y.z, z.z
  939. return m
  940. new_rotate_triple_axis = classmethod(new_rotate_triple_axis)
  941. def new_look_at(cls, eye, at, up):
  942. z = (eye - at).normalized()
  943. x = up.cross(z).normalized()
  944. y = z.cross(x)
  945. m = cls.new_rotate_triple_axis(x, y, z)
  946. m.d, m.h, m.l = eye.x, eye.y, eye.z
  947. return m
  948. new_look_at = classmethod(new_look_at)
  949. def new_perspective(cls, fov_y, aspect, near, far):
  950. # from the gluPerspective man page
  951. f = 1 / math.tan(fov_y / 2)
  952. self = cls()
  953. assert near != 0.0 and near != far
  954. self.a = f / aspect
  955. self.f = f
  956. self.k = (far + near) / (near - far)
  957. self.l = 2 * far * near / (near - far)
  958. self.o = -1
  959. self.p = 0
  960. return self
  961. new_perspective = classmethod(new_perspective)
  962. def determinant(self):
  963. return ((self.a * self.f - self.e * self.b)
  964. * (self.k * self.p - self.o * self.l)
  965. - (self.a * self.j - self.i * self.b)
  966. * (self.g * self.p - self.o * self.h)
  967. + (self.a * self.n - self.m * self.b)
  968. * (self.g * self.l - self.k * self.h)
  969. + (self.e * self.j - self.i * self.f)
  970. * (self.c * self.p - self.o * self.d)
  971. - (self.e * self.n - self.m * self.f)
  972. * (self.c * self.l - self.k * self.d)
  973. + (self.i * self.n - self.m * self.j)
  974. * (self.c * self.h - self.g * self.d))
  975. def inverse(self):
  976. tmp = Matrix4()
  977. d = self.determinant();
  978. if abs(d) < 0.001:
  979. # No inverse, return identity
  980. return tmp
  981. else:
  982. d = 1.0 / d;
  983. tmp.a = d * (self.f * (self.k * self.p - self.o * self.l) + self.j * (self.o * self.h - self.g * self.p) + self.n * (self.g * self.l - self.k * self.h));
  984. tmp.e = d * (self.g * (self.i * self.p - self.m * self.l) + self.k * (self.m * self.h - self.e * self.p) + self.o * (self.e * self.l - self.i * self.h));
  985. tmp.i = d * (self.h * (self.i * self.n - self.m * self.j) + self.l * (self.m * self.f - self.e * self.n) + self.p * (self.e * self.j - self.i * self.f));
  986. tmp.m = d * (self.e * (self.n * self.k - self.j * self.o) + self.i * (self.f * self.o - self.n * self.g) + self.m * (self.j * self.g - self.f * self.k));
  987. tmp.b = d * (self.j * (self.c * self.p - self.o * self.d) + self.n * (self.k * self.d - self.c * self.l) + self.b * (self.o * self.l - self.k * self.p));
  988. tmp.f = d * (self.k * (self.a * self.p - self.m * self.d) + self.o * (self.i * self.d - self.a * self.l) + self.c * (self.m * self.l - self.i * self.p));
  989. tmp.j = d * (self.l * (self.a * self.n - self.m * self.b) + self.p * (self.i * self.b - self.a * self.j) + self.d * (self.m * self.j - self.i * self.n));
  990. tmp.n = d * (self.i * (self.n * self.c - self.b * self.o) + self.m * (self.b * self.k - self.j * self.c) + self.a * (self.j * self.o - self.n * self.k));
  991. tmp.c = d * (self.n * (self.c * self.h - self.g * self.d) + self.b * (self.g * self.p - self.o * self.h) + self.f * (self.o * self.d - self.c * self.p));
  992. tmp.g = d * (self.o * (self.a * self.h - self.e * self.d) + self.c * (self.e * self.p - self.m * self.h) + self.g * (self.m * self.d - self.a * self.p));
  993. tmp.k = d * (self.p * (self.a * self.f - self.e * self.b) + self.d * (self.e * self.n - self.m * self.f) + self.h * (self.m * self.b - self.a * self.n));
  994. tmp.o = d * (self.m * (self.f * self.c - self.b * self.g) + self.a * (self.n * self.g - self.f * self.o) + self.e * (self.b * self.o - self.n * self.c));
  995. tmp.d = d * (self.b * (self.k * self.h - self.g * self.l) + self.f * (self.c * self.l - self.k * self.d) + self.j * (self.g * self.d - self.c * self.h));
  996. tmp.h = d * (self.c * (self.i * self.h - self.e * self.l) + self.g * (self.a * self.l - self.i * self.d) + self.k * (self.e * self.d - self.a * self.h));
  997. tmp.l = d * (self.d * (self.i * self.f - self.e * self.j) + self.h * (self.a * self.j - self.i * self.b) + self.l * (self.e * self.b - self.a * self.f));
  998. tmp.p = d * (self.a * (self.f * self.k - self.j * self.g) + self.e * (self.j * self.c - self.b * self.k) + self.i * (self.b * self.g - self.f * self.c));
  999. return tmp;
  1000. class Quaternion:
  1001. # All methods and naming conventions based off
  1002. # http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions
  1003. # w is the real part, (x, y, z) are the imaginary parts
  1004. __slots__ = ['w', 'x', 'y', 'z']
  1005. def __init__(self, w=1, x=0, y=0, z=0):
  1006. self.w = w
  1007. self.x = x
  1008. self.y = y
  1009. self.z = z
  1010. def __copy__(self):
  1011. Q = Quaternion()
  1012. Q.w = self.w
  1013. Q.x = self.x
  1014. Q.y = self.y
  1015. Q.z = self.z
  1016. return Q
  1017. copy = __copy__
  1018. def __repr__(self):
  1019. return 'Quaternion(real=%.2f, imag=<%.2f, %.2f, %.2f>)' % \
  1020. (self.w, self.x, self.y, self.z)
  1021. def __mul__(self, other):
  1022. if isinstance(other, Quaternion):
  1023. Ax = self.x
  1024. Ay = self.y
  1025. Az = self.z
  1026. Aw = self.w
  1027. Bx = other.x
  1028. By = other.y
  1029. Bz = other.z
  1030. Bw = other.w
  1031. Q = Quaternion()
  1032. Q.x = Ax * Bw + Ay * Bz - Az * By + Aw * Bx
  1033. Q.y = -Ax * Bz + Ay * Bw + Az * Bx + Aw * By
  1034. Q.z = Ax * By - Ay * Bx + Az * Bw + Aw * Bz
  1035. Q.w = -Ax * Bx - Ay * By - Az * Bz + Aw * Bw
  1036. return Q
  1037. elif isinstance(other, Vector3):
  1038. w = self.w
  1039. x = self.x
  1040. y = self.y
  1041. z = self.z
  1042. Vx = other.x
  1043. Vy = other.y
  1044. Vz = other.z
  1045. ww = w * w
  1046. w2 = w * 2
  1047. wx2 = w2 * x
  1048. wy2 = w2 * y
  1049. wz2 = w2 * z
  1050. xx = x * x
  1051. x2 = x * 2
  1052. xy2 = x2 * y
  1053. xz2 = x2 * z
  1054. yy = y * y
  1055. yz2 = 2 * y * z
  1056. zz = z * z
  1057. return other.__class__(\
  1058. ww * Vx + wy2 * Vz - wz2 * Vy + \
  1059. xx * Vx + xy2 * Vy + xz2 * Vz - \
  1060. zz * Vx - yy * Vx,
  1061. xy2 * Vx + yy * Vy + yz2 * Vz + \
  1062. wz2 * Vx - zz * Vy + ww * Vy - \
  1063. wx2 * Vz - xx * Vy,
  1064. xz2 * Vx + yz2 * Vy + \
  1065. zz * Vz - wy2 * Vx - yy * Vz + \
  1066. wx2 * Vy - xx * Vz + ww * Vz)
  1067. else:
  1068. other = other.copy()
  1069. other._apply_transform(self)
  1070. return other
  1071. def __imul__(self, other):
  1072. assert isinstance(other, Quaternion)
  1073. Ax = self.x
  1074. Ay = self.y
  1075. Az = self.z
  1076. Aw = self.w
  1077. Bx = other.x
  1078. By = other.y
  1079. Bz = other.z
  1080. Bw = other.w
  1081. self.x = Ax * Bw + Ay * Bz - Az * By + Aw * Bx
  1082. self.y = -Ax * Bz + Ay * Bw + Az * Bx + Aw * By
  1083. self.z = Ax * By - Ay * Bx + Az * Bw + Aw * Bz
  1084. self.w = -Ax * Bx - Ay * By - Az * Bz + Aw * Bw
  1085. return self
  1086. def __abs__(self):
  1087. return math.sqrt(self.w ** 2 + \
  1088. self.x ** 2 + \
  1089. self.y ** 2 + \
  1090. self.z ** 2)
  1091. magnitude = __abs__
  1092. def magnitude_squared(self):
  1093. return self.w ** 2 + \
  1094. self.x ** 2 + \
  1095. self.y ** 2 + \
  1096. self.z ** 2
  1097. def identity(self):
  1098. self.w = 1
  1099. self.x = 0
  1100. self.y = 0
  1101. self.z = 0
  1102. return self
  1103. def rotate_axis(self, angle, axis):
  1104. self *= Quaternion.new_rotate_axis(angle, axis)
  1105. return self
  1106. def rotate_euler(self, heading, attitude, bank):
  1107. self *= Quaternion.new_rotate_euler(heading, attitude, bank)
  1108. return self
  1109. def rotate_matrix(self, m):
  1110. self *= Quaternion.new_rotate_matrix(m)
  1111. return self
  1112. def conjugated(self):
  1113. Q = Quaternion()
  1114. Q.w = self.w
  1115. Q.x = -self.x
  1116. Q.y = -self.y
  1117. Q.z = -self.z
  1118. return Q
  1119. def normalize(self):
  1120. d = self.magnitude()
  1121. if d != 0:
  1122. self.w /= d
  1123. self.x /= d
  1124. self.y /= d
  1125. self.z /= d
  1126. return self
  1127. def normalized(self):
  1128. d = self.magnitude()
  1129. if d != 0:
  1130. Q = Quaternion()
  1131. Q.w = self.w / d
  1132. Q.x = self.x / d
  1133. Q.y = self.y / d
  1134. Q.z = self.z / d
  1135. return Q
  1136. else:
  1137. return self.copy()
  1138. def get_angle_axis(self):
  1139. if self.w > 1:
  1140. self = self.normalized()
  1141. angle = 2 * math.acos(self.w)
  1142. s = math.sqrt(1 - self.w ** 2)
  1143. if s < 0.001:
  1144. return angle, Vector3(1, 0, 0)
  1145. else:
  1146. return angle, Vector3(self.x / s, self.y / s, self.z / s)
  1147. def get_euler(self):
  1148. t = self.x * self.y + self.z * self.w
  1149. if t > 0.4999:
  1150. heading = 2 * math.atan2(self.x, self.w)
  1151. attitude = math.pi / 2
  1152. bank = 0
  1153. elif t < -0.4999:
  1154. heading = -2 * math.atan2(self.x, self.w)
  1155. attitude = -math.pi / 2
  1156. bank = 0
  1157. else:
  1158. sqx = self.x ** 2
  1159. sqy = self.y ** 2
  1160. sqz = self.z ** 2
  1161. heading = math.atan2(2 * self.y * self.w - 2 * self.x * self.z,
  1162. 1 - 2 * sqy - 2 * sqz)
  1163. attitude = math.asin(2 * t)
  1164. bank = math.atan2(2 * self.x * self.w - 2 * self.y * self.z,
  1165. 1 - 2 * sqx - 2 * sqz)
  1166. return heading, attitude, bank
  1167. def get_matrix(self):
  1168. xx = self.x ** 2
  1169. xy = self.x * self.y
  1170. xz = self.x * self.z
  1171. xw = self.x * self.w
  1172. yy = self.y ** 2
  1173. yz = self.y * self.z
  1174. yw = self.y * self.w
  1175. zz = self.z ** 2
  1176. zw = self.z * self.w
  1177. M = Matrix4()
  1178. M.a = 1 - 2 * (yy + zz)
  1179. M.b = 2 * (xy - zw)
  1180. M.c = 2 * (xz + yw)
  1181. M.e = 2 * (xy + zw)
  1182. M.f = 1 - 2 * (xx + zz)
  1183. M.g = 2 * (yz - xw)
  1184. M.i = 2 * (xz - yw)
  1185. M.j = 2 * (yz + xw)
  1186. M.k = 1 - 2 * (xx + yy)
  1187. return M
  1188. # Static constructors
  1189. def new_identity(cls):
  1190. return cls()
  1191. new_identity = classmethod(new_identity)
  1192. def new_rotate_axis(cls, angle, axis):
  1193. assert(isinstance(axis, Vector3))
  1194. axis = axis.normalized()
  1195. s = math.sin(angle / 2)
  1196. Q = cls()
  1197. Q.w = math.cos(angle / 2)
  1198. Q.x = axis.x * s
  1199. Q.y = axis.y * s
  1200. Q.z = axis.z * s
  1201. return Q
  1202. new_rotate_axis = classmethod(new_rotate_axis)
  1203. def new_rotate_euler(cls, heading, attitude, bank):
  1204. Q = cls()
  1205. c1 = math.cos(heading / 2)
  1206. s1 = math.sin(heading / 2)
  1207. c2 = math.cos(attitude / 2)
  1208. s2 = math.sin(attitude / 2)
  1209. c3 = math.cos(bank / 2)
  1210. s3 = math.sin(bank / 2)
  1211. Q.w = c1 * c2 * c3 - s1 * s2 * s3
  1212. Q.x = s1 * s2 * c3 + c1 * c2 * s3
  1213. Q.y = s1 * c2 * c3 + c1 * s2 * s3
  1214. Q.z = c1 * s2 * c3 - s1 * c2 * s3
  1215. return Q
  1216. new_rotate_euler = classmethod(new_rotate_euler)
  1217. def new_rotate_matrix(cls, m):
  1218. if m[0*4 + 0] + m[1*4 + 1] + m[2*4 + 2] > 0.00000001:
  1219. t = m[0*4 + 0] + m[1*4 + 1] + m[2*4 + 2] + 1.0
  1220. s = 0.5/math.sqrt(t)
  1221. return cls(
  1222. s*t,
  1223. (m[1*4 + 2] - m[2*4 + 1])*s,
  1224. (m[2*4 + 0] - m[0*4 + 2])*s,
  1225. (m[0*4 + 1] - m[1*4 + 0])*s
  1226. )
  1227. elif m[0*4 + 0] > m[1*4 + 1] and m[0*4 + 0] > m[2*4 + 2]:
  1228. t = m[0*4 + 0] - m[1*4 + 1] - m[2*4 + 2] + 1.0
  1229. s = 0.5/math.sqrt(t)
  1230. return cls(
  1231. (m[1*4 + 2] - m[2*4 + 1])*s,
  1232. s*t,
  1233. (m[0*4 + 1] + m[1*4 + 0])*s,
  1234. (m[2*4 + 0] + m[0*4 + 2])*s
  1235. )
  1236. elif m[1*4 + 1] > m[2*4 + 2]:
  1237. t = -m[0*4 + 0] + m[1*4 + 1] - m[2*4 + 2] + 1.0
  1238. s = 0.5/math.sqrt(t)
  1239. return cls(
  1240. (m[2*4 + 0] - m[0*4 + 2])*s,
  1241. (m[0*4 + 1] + m[1*4 + 0])*s,
  1242. s*t,
  1243. (m[1*4 + 2] + m[2*4 + 1])*s
  1244. )
  1245. else:
  1246. t = -m[0*4 + 0] - m[1*4 + 1] + m[2*4 + 2] + 1.0
  1247. s = 0.5/math.sqrt(t)
  1248. return cls(
  1249. (m[0*4 + 1] - m[1*4 + 0])*s,
  1250. (m[2*4 + 0] + m[0*4 + 2])*s,
  1251. (m[1*4 + 2] + m[2*4 + 1])*s,
  1252. s*t
  1253. )
  1254. new_rotate_matrix = classmethod(new_rotate_matrix)
  1255. def new_interpolate(cls, q1, q2, t):
  1256. assert isinstance(q1, Quaternion) and isinstance(q2, Quaternion)
  1257. Q = cls()
  1258. costheta = q1.w * q2.w + q1.x * q2.x + q1.y * q2.y + q1.z * q2.z
  1259. if costheta < 0.:
  1260. costheta = -costheta
  1261. q1 = q1.conjugated()
  1262. elif costheta > 1:
  1263. costheta = 1
  1264. theta = math.acos(costheta)
  1265. if abs(theta) < 0.01:
  1266. Q.w = q2.w
  1267. Q.x = q2.x
  1268. Q.y = q2.y
  1269. Q.z = q2.z
  1270. return Q
  1271. sintheta = math.sqrt(1.0 - costheta * costheta)
  1272. if abs(sintheta) < 0.01:
  1273. Q.w = (q1.w + q2.w) * 0.5
  1274. Q.x = (q1.x + q2.x) * 0.5
  1275. Q.y = (q1.y + q2.y) * 0.5
  1276. Q.z = (q1.z + q2.z) * 0.5
  1277. return Q
  1278. ratio1 = math.sin((1 - t) * theta) / sintheta
  1279. ratio2 = math.sin(t * theta) / sintheta
  1280. Q.w = q1.w * ratio1 + q2.w * ratio2
  1281. Q.x = q1.x * ratio1 + q2.x * ratio2
  1282. Q.y = q1.y * ratio1 + q2.y * ratio2
  1283. Q.z = q1.z * ratio1 + q2.z * ratio2
  1284. return Q
  1285. new_interpolate = classmethod(new_interpolate)
  1286. # Geometry
  1287. # Much maths thanks to Paul Bourke, http://astronomy.swin.edu.au/~pbourke
  1288. # ---------------------------------------------------------------------------
  1289. class Geometry:
  1290. def _connect_unimplemented(self, other):
  1291. raise AttributeError, 'Cannot connect %s to %s' % \
  1292. (self.__class__, other.__class__)
  1293. def _intersect_unimplemented(self, other):
  1294. raise AttributeError, 'Cannot intersect %s and %s' % \
  1295. (self.__class__, other.__class__)
  1296. _intersect_point2 = _intersect_unimplemented
  1297. _intersect_line2 = _intersect_unimplemented
  1298. _intersect_circle = _intersect_unimplemented
  1299. _connect_point2 = _connect_unimplemented
  1300. _connect_line2 = _connect_unimplemented
  1301. _connect_circle = _connect_unimplemented
  1302. _intersect_point3 = _intersect_unimplemented
  1303. _intersect_line3 = _intersect_unimplemented
  1304. _intersect_sphere = _intersect_unimplemented
  1305. _intersect_plane = _intersect_unimplemented
  1306. _connect_point3 = _connect_unimplemented
  1307. _connect_line3 = _connect_unimplemented
  1308. _connect_sphere = _connect_unimplemented
  1309. _connect_plane = _connect_unimplemented
  1310. def intersect(self, other):
  1311. raise NotImplementedError
  1312. def connect(self, other):
  1313. raise NotImplementedError
  1314. def distance(self, other):
  1315. c = self.connect(other)
  1316. if c:
  1317. return c.length
  1318. return 0.0
  1319. def _intersect_point2_circle(P, C):
  1320. return abs(P - C.c) <= C.r
  1321. def _intersect_line2_line2(A, B):
  1322. d = B.v.y * A.v.x - B.v.x * A.v.y
  1323. if d == 0:
  1324. return None
  1325. dy = A.p.y - B.p.y
  1326. dx = A.p.x - B.p.x
  1327. ua = (B.v.x * dy - B.v.y * dx) / d
  1328. if not A._u_in(ua):
  1329. return None
  1330. ub = (A.v.x * dy - A.v.y * dx) / d
  1331. if not B._u_in(ub):
  1332. return None
  1333. return Point2(A.p.x + ua * A.v.x,
  1334. A.p.y + ua * A.v.y)
  1335. def _intersect_line2_circle(L, C):
  1336. a = L.v.magnitude_squared()
  1337. b = 2 * (L.v.x * (L.p.x - C.c.x) + \
  1338. L.v.y * (L.p.y - C.c.y))
  1339. c = C.c.magnitude_squared() + \
  1340. L.p.magnitude_squared() - \
  1341. 2 * C.c.dot(L.p) - \
  1342. C.r ** 2
  1343. det = b ** 2 - 4 * a * c
  1344. if det < 0:
  1345. return None
  1346. sq = math.sqrt(det)
  1347. u1 = (-b + sq) / (2 * a)
  1348. u2 = (-b - sq) / (2 * a)
  1349. if not L._u_in(u1):
  1350. u1 = max(min(u1, 1.0), 0.0)
  1351. if not L._u_in(u2):
  1352. u2 = max(min(u2, 1.0), 0.0)
  1353. # Tangent
  1354. if u1 == u2:
  1355. return Point2(L.p.x + u1 * L.v.x,
  1356. L.p.y + u1 * L.v.y)
  1357. return LineSegment2(Point2(L.p.x + u1 * L.v.x,
  1358. L.p.y + u1 * L.v.y),
  1359. Point2(L.p.x + u2 * L.v.x,
  1360. L.p.y + u2 * L.v.y))
  1361. def _connect_point2_line2(P, L):
  1362. d = L.v.magnitude_squared()
  1363. assert d != 0
  1364. u = ((P.x - L.p.x) * L.v.x + \
  1365. (P.y - L.p.y) * L.v.y) / d
  1366. if not L._u_in(u):
  1367. u = max(min(u, 1.0), 0.0)
  1368. return LineSegment2(P,
  1369. Point2(L.p.x + u * L.v.x,
  1370. L.p.y + u * L.v.y))
  1371. def _connect_point2_circle(P, C):
  1372. v = P - C.c
  1373. v.normalize()
  1374. v *= C.r
  1375. return LineSegment2(P, Point2(C.c.x + v.x, C.c.y + v.y))
  1376. def _connect_line2_line2(A, B):
  1377. d = B.v.y * A.v.x - B.v.x * A.v.y
  1378. if d == 0:
  1379. # Parallel, connect an endpoint with a line
  1380. if isinstance(B, Ray2) or isinstance(B, LineSegment2):
  1381. p1, p2 = _connect_point2_line2(B.p, A)
  1382. return p2, p1
  1383. # No endpoint (or endpoint is on A), possibly choose arbitrary point
  1384. # on line.
  1385. return _connect_point2_line2(A.p, B)
  1386. dy = A.p.y - B.p.y
  1387. dx = A.p.x - B.p.x
  1388. ua = (B.v.x * dy - B.v.y * dx) / d
  1389. if not A._u_in(ua):
  1390. ua = max(min(ua, 1.0), 0.0)
  1391. ub = (A.v.x * dy - A.v.y * dx) / d
  1392. if not B._u_in(ub):
  1393. ub = max(min(ub, 1.0), 0.0)
  1394. return LineSegment2(Point2(A.p.x + ua * A.v.x, A.p.y + ua * A.v.y),
  1395. Point2(B.p.x + ub * B.v.x, B.p.y + ub * B.v.y))
  1396. def _connect_circle_line2(C, L):
  1397. d = L.v.magnitude_squared()
  1398. assert d != 0
  1399. u = ((C.c.x - L.p.x) * L.v.x + (C.c.y - L.p.y) * L.v.y) / d
  1400. if not L._u_in(u):
  1401. u = max(min(u, 1.0), 0.0)
  1402. point = Point2(L.p.x + u * L.v.x, L.p.y + u * L.v.y)
  1403. v = (point - C.c)
  1404. v.normalize()
  1405. v *= C.r
  1406. return LineSegment2(Point2(C.c.x + v.x, C.c.y + v.y), point)
  1407. def _connect_circle_circle(A, B):
  1408. v = B.c - A.c
  1409. v.normalize()
  1410. return LineSegment2(Point2(A.c.x + v.x * A.r, A.c.y + v.y * A.r),
  1411. Point2(B.c.x - v.x * B.r, B.c.y - v.y * B.r))
  1412. class Point2(Vector2, Geometry):
  1413. def __repr__(self):
  1414. return 'Point2(%.2f, %.2f)' % (self.x, self.y)
  1415. def intersect(self, other):
  1416. return other._intersect_point2(self)
  1417. def _intersect_circle(self, other):
  1418. return _intersect_point2_circle(self, other)
  1419. def connect(self, other):
  1420. return other._connect_point2(self)
  1421. def _connect_point2(self, other):
  1422. return LineSegment2(other, self)
  1423. def _connect_line2(self, other):
  1424. c = _connect_point2_line2(self, other)
  1425. if c:
  1426. return c._swap()
  1427. def _connect_circle(self, other):
  1428. c = _connect_point2_circle(self, other)
  1429. if c:
  1430. return c._swap()
  1431. class Line2(Geometry):
  1432. __slots__ = ['p', 'v']
  1433. def __init__(self, *args):
  1434. if len(args) == 3:
  1435. assert isinstance(args[0], Point2) and \
  1436. isinstance(args[1], Vector2) and \
  1437. type(args[2]) == float
  1438. self.p = args[0].copy()
  1439. self.v = args[1] * args[2] / abs(args[1])
  1440. elif len(args) == 2:
  1441. if isinstance(args[0], Point2) and isinstance(args[1], Point2):
  1442. self.p = args[0].copy()
  1443. self.v = args[1] - args[0]
  1444. elif isinstance(args[0], Point2) and isinstance(args[1], Vector2):
  1445. self.p = args[0].copy()
  1446. self.v = args[1].copy()
  1447. else:
  1448. raise AttributeError, '%r' % (args,)
  1449. elif len(args) == 1:
  1450. if isinstance(args[0], Line2):
  1451. self.p = args[0].p.copy()
  1452. self.v = args[0].v.copy()
  1453. else:
  1454. raise AttributeError, '%r' % (args,)
  1455. else:
  1456. raise AttributeError, '%r' % (args,)
  1457. if not self.v:
  1458. raise AttributeError, 'Line has zero-length vector'
  1459. def __copy__(self):
  1460. return self.__class__(self.p, self.v)
  1461. copy = __copy__
  1462. def __repr__(self):
  1463. return 'Line2(<%.2f, %.2f> + u<%.2f, %.2f>)' % \
  1464. (self.p.x, self.p.y, self.v.x, self.v.y)
  1465. p1 = property(lambda self: self.p)
  1466. p2 = property(lambda self: Point2(self.p.x + self.v.x,
  1467. self.p.y + self.v.y))
  1468. def _apply_transform(self, t):
  1469. self.p = t * self.p
  1470. self.v = t * self.v
  1471. def _u_in(self, u):
  1472. return True
  1473. def intersect(self, other):
  1474. return other._intersect_line2(self)
  1475. def _intersect_line2(self, other):
  1476. return _intersect_line2_line2(self, other)
  1477. def _intersect_circle(self, other):
  1478. return _intersect_line2_circle(self, other)
  1479. def connect(self, other):
  1480. return other._connect_line2(self)
  1481. def _connect_point2(self, other):
  1482. return _connect_point2_line2(other, self)
  1483. def _connect_line2(self, other):
  1484. return _connect_line2_line2(other, self)
  1485. def _connect_circle(self, other):
  1486. return _connect_circle_line2(other, self)
  1487. class Ray2(Line2):
  1488. def __repr__(self):
  1489. return 'Ray2(<%.2f, %.2f> + u<%.2f, %.2f>)' % \
  1490. (self.p.x, self.p.y, self.v.x, self.v.y)
  1491. def _u_in(self, u):
  1492. return u >= 0.0
  1493. class LineSegment2(Line2):
  1494. def __repr__(self):
  1495. return 'LineSegment2(<%.2f, %.2f> to <%.2f, %.2f>)' % \
  1496. (self.p.x, self.p.y, self.p.x + self.v.x, self.p.y + self.v.y)
  1497. def _u_in(self, u):
  1498. return u >= 0.0 and u <= 1.0
  1499. def __abs__(self):
  1500. return abs(self.v)
  1501. def magnitude_squared(self):
  1502. return self.v.magnitude_squared()
  1503. def _swap(self):
  1504. # used by connect methods to switch order of points
  1505. self.p = self.p2
  1506. self.v *= -1
  1507. return self
  1508. length = property(lambda self: abs(self.v))
  1509. class Circle(Geometry):
  1510. __slots__ = ['c', 'r']
  1511. def __init__(self, center, radius):
  1512. assert isinstance(center, Vector2) and type(radius) == float
  1513. self.c = center.copy()
  1514. self.r = radius
  1515. def __copy__(self):
  1516. return self.__class__(self.c, self.r)
  1517. copy = __copy__
  1518. def __repr__(self):
  1519. return 'Circle(<%.2f, %.2f>, radius=%.2f)' % \
  1520. (self.c.x, self.c.y, self.r)
  1521. def _apply_transform(self, t):
  1522. self.c = t * self.c
  1523. def intersect(self, other):
  1524. return other._intersect_circle(self)
  1525. def _intersect_point2(self, other):
  1526. return _intersect_point2_circle(other, self)
  1527. def _intersect_line2(self, other):
  1528. return _intersect_line2_circle(other, self)
  1529. def connect(self, other):
  1530. return other._connect_circle(self)
  1531. def _connect_point2(self, other):
  1532. return _connect_point2_circle(other, self)
  1533. def _connect_line2(self, other):
  1534. c = _connect_circle_line2(self, other)
  1535. if c:
  1536. return c._swap()
  1537. def _connect_circle(self, other):
  1538. return _connect_circle_circle(other, self)
  1539. # 3D Geometry
  1540. # -------------------------------------------------------------------------
  1541. def _connect_point3_line3(P, L):
  1542. d = L.v.magnitude_squared()
  1543. assert d != 0
  1544. u = ((P.x - L.p.x) * L.v.x + \
  1545. (P.y - L.p.y) * L.v.y + \
  1546. (P.z - L.p.z) * L.v.z) / d
  1547. if not L._u_in(u):
  1548. u = max(min(u, 1.0), 0.0)
  1549. return LineSegment3(P, Point3(L.p.x + u * L.v.x,
  1550. L.p.y + u * L.v.y,
  1551. L.p.z + u * L.v.z))
  1552. def _connect_point3_sphere(P, S):
  1553. v = P - S.c
  1554. v.normalize()
  1555. v *= S.r
  1556. return LineSegment3(P, Point3(S.c.x + v.x, S.c.y + v.y, S.c.z + v.z))
  1557. def _connect_point3_plane(p, plane):
  1558. n = plane.n.normalized()
  1559. d = p.dot(plane.n) - plane.k
  1560. return LineSegment3(p, Point3(p.x - n.x * d, p.y - n.y * d, p.z - n.z * d))
  1561. def _connect_line3_line3(A, B):
  1562. assert A.v and B.v
  1563. p13 = A.p - B.p
  1564. d1343 = p13.dot(B.v)
  1565. d4321 = B.v.dot(A.v)
  1566. d1321 = p13.dot(A.v)
  1567. d4343 = B.v.magnitude_squared()
  1568. denom = A.v.magnitude_squared() * d4343 - d4321 ** 2
  1569. if denom == 0:
  1570. # Parallel, connect an endpoint with a line
  1571. if isinstance(B, Ray3) or isinstance(B, LineSegment3):
  1572. return _connect_point3_line3(B.p, A)._swap()
  1573. # No endpoint (or endpoint is on A), possibly choose arbitrary
  1574. # point on line.
  1575. return _connect_point3_line3(A.p, B)
  1576. ua = (d1343 * d4321 - d1321 * d4343) / denom
  1577. if not A._u_in(ua):
  1578. ua = max(min(ua, 1.0), 0.0)
  1579. ub = (d1343 + d4321 * ua) / d4343
  1580. if not B._u_in(ub):
  1581. ub = max(min(ub, 1.0), 0.0)
  1582. return LineSegment3(Point3(A.p.x + ua * A.v.x,
  1583. A.p.y + ua * A.v.y,
  1584. A.p.z + ua * A.v.z),
  1585. Point3(B.p.x + ub * B.v.x,
  1586. B.p.y + ub * B.v.y,
  1587. B.p.z + ub * B.v.z))
  1588. def _connect_line3_plane(L, P):
  1589. d = P.n.dot(L.v)
  1590. if not d:
  1591. # Parallel, choose an endpoint
  1592. return _connect_point3_plane(L.p, P)
  1593. u = (P.k - P.n.dot(L.p)) / d
  1594. if not L._u_in(u):
  1595. # intersects out of range, choose nearest endpoint
  1596. u = max(min(u, 1.0), 0.0)
  1597. return _connect_point3_plane(Point3(L.p.x + u * L.v.x,
  1598. L.p.y + u * L.v.y,
  1599. L.p.z + u * L.v.z), P)
  1600. # Intersection
  1601. return None
  1602. def _connect_sphere_line3(S, L):
  1603. d = L.v.magnitude_squared()
  1604. assert d != 0
  1605. u = ((S.c.x - L.p.x) * L.v.x + \
  1606. (S.c.y - L.p.y) * L.v.y + \
  1607. (S.c.z - L.p.z) * L.v.z) / d
  1608. if not L._u_in(u):
  1609. u = max(min(u, 1.0), 0.0)
  1610. point = Point3(L.p.x + u * L.v.x, L.p.y + u * L.v.y, L.p.z + u * L.v.z)
  1611. v = (point - S.c)
  1612. v.normalize()
  1613. v *= S.r
  1614. return LineSegment3(Point3(S.c.x + v.x, S.c.y + v.y, S.c.z + v.z),
  1615. point)
  1616. def _connect_sphere_sphere(A, B):
  1617. v = B.c - A.c
  1618. v.normalize()
  1619. return LineSegment3(Point3(A.c.x + v.x * A.r,
  1620. A.c.y + v.y * A.r,
  1621. A.c.x + v.z * A.r),
  1622. Point3(B.c.x + v.x * B.r,
  1623. B.c.y + v.y * B.r,
  1624. B.c.x + v.z * B.r))
  1625. def _connect_sphere_plane(S, P):
  1626. c = _connect_point3_plane(S.c, P)
  1627. if not c:
  1628. return None
  1629. p2 = c.p2
  1630. v = p2 - S.c
  1631. v.normalize()
  1632. v *= S.r
  1633. return LineSegment3(Point3(S.c.x + v.x, S.c.y + v.y, S.c.z + v.z),
  1634. p2)
  1635. def _connect_plane_plane(A, B):
  1636. if A.n.cross(B.n):
  1637. # Planes intersect
  1638. return None
  1639. else:
  1640. # Planes are parallel, connect to arbitrary point
  1641. return _connect_point3_plane(A._get_point(), B)
  1642. def _intersect_point3_sphere(P, S):
  1643. return abs(P - S.c) <= S.r
  1644. def _intersect_line3_sphere(L, S):
  1645. a = L.v.magnitude_squared()
  1646. b = 2 * (L.v.x * (L.p.x - S.c.x) + \
  1647. L.v.y * (L.p.y - S.c.y) + \
  1648. L.v.z * (L.p.z - S.c.z))
  1649. c = S.c.magnitude_squared() + \
  1650. L.p.magnitude_squared() - \
  1651. 2 * S.c.dot(L.p) - \
  1652. S.r ** 2
  1653. det = b ** 2 - 4 * a * c
  1654. if det < 0:
  1655. return None
  1656. sq = math.sqrt(det)
  1657. u1 = (-b + sq) / (2 * a)
  1658. u2 = (-b - sq) / (2 * a)
  1659. if not L._u_in(u1):
  1660. u1 = max(min(u1, 1.0), 0.0)
  1661. if not L._u_in(u2):
  1662. u2 = max(min(u2, 1.0), 0.0)
  1663. return LineSegment3(Point3(L.p.x + u1 * L.v.x,
  1664. L.p.y + u1 * L.v.y,
  1665. L.p.z + u1 * L.v.z),
  1666. Point3(L.p.x + u2 * L.v.x,
  1667. L.p.y + u2 * L.v.y,
  1668. L.p.z + u2 * L.v.z))
  1669. def _intersect_line3_plane(L, P):
  1670. d = P.n.dot(L.v)
  1671. if not d:
  1672. # Parallel
  1673. return None
  1674. u = (P.k - P.n.dot(L.p)) / d
  1675. if not L._u_in(u):
  1676. return None
  1677. return Point3(L.p.x + u * L.v.x,
  1678. L.p.y + u * L.v.y,
  1679. L.p.z + u * L.v.z)
  1680. def _intersect_plane_plane(A, B):
  1681. n1_m = A.n.magnitude_squared()
  1682. n2_m = B.n.magnitude_squared()
  1683. n1d2 = A.n.dot(B.n)
  1684. det = n1_m * n2_m - n1d2 ** 2
  1685. if det == 0:
  1686. # Parallel
  1687. return None
  1688. c1 = (A.k * n2_m - B.k * n1d2) / det
  1689. c2 = (B.k * n1_m - A.k * n1d2) / det
  1690. return Line3(Point3(c1 * A.n.x + c2 * B.n.x,
  1691. c1 * A.n.y + c2 * B.n.y,
  1692. c1 * A.n.z + c2 * B.n.z),
  1693. A.n.cross(B.n))
  1694. class Point3(Vector3, Geometry):
  1695. def __repr__(self):
  1696. return 'Point3(%.2f, %.2f, %.2f)' % (self.x, self.y, self.z)
  1697. def intersect(self, other):
  1698. return other._intersect_point3(self)
  1699. def _intersect_sphere(self, other):
  1700. return _intersect_point3_sphere(self, other)
  1701. def connect(self, other):
  1702. return other._connect_point3(self)
  1703. def _connect_point3(self, other):
  1704. if self != other:
  1705. return LineSegment3(other, self)
  1706. return None
  1707. def _connect_line3(self, other):
  1708. c = _connect_point3_line3(self, other)
  1709. if c:
  1710. return c._swap()
  1711. def _connect_sphere(self, other):
  1712. c = _connect_point3_sphere(self, other)
  1713. if c:
  1714. return c._swap()
  1715. def _connect_plane(self, other):
  1716. c = _connect_point3_plane(self, other)
  1717. if c:
  1718. return c._swap()
  1719. class Line3:
  1720. __slots__ = ['p', 'v']
  1721. def __init__(self, *args):
  1722. if len(args) == 3:
  1723. assert isinstance(args[0], Point3) and \
  1724. isinstance(args[1], Vector3) and \
  1725. type(args[2]) == float
  1726. self.p = args[0].copy()
  1727. self.v = args[1] * args[2] / abs(args[1])
  1728. elif len(args) == 2:
  1729. if isinstance(args[0], Point3) and isinstance(args[1], Point3):
  1730. self.p = args[0].copy()
  1731. self.v = args[1] - args[0]
  1732. elif isinstance(args[0], Point3) and isinstance(args[1], Vector3):
  1733. self.p = args[0].copy()
  1734. self.v = args[1].copy()
  1735. else:
  1736. raise AttributeError, '%r' % (args,)
  1737. elif len(args) == 1:
  1738. if isinstance(args[0], Line3):
  1739. self.p = args[0].p.copy()
  1740. self.v = args[0].v.copy()
  1741. else:
  1742. raise AttributeError, '%r' % (args,)
  1743. else:
  1744. raise AttributeError, '%r' % (args,)
  1745. # XXX This is annoying.
  1746. #if not self.v:
  1747. # raise AttributeError, 'Line has zero-length vector'
  1748. def __copy__(self):
  1749. return self.__class__(self.p, self.v)
  1750. copy = __copy__
  1751. def __repr__(self):
  1752. return 'Line3(<%.2f, %.2f, %.2f> + u<%.2f, %.2f, %.2f>)' % \
  1753. (self.p.x, self.p.y, self.p.z, self.v.x, self.v.y, self.v.z)
  1754. p1 = property(lambda self: self.p)
  1755. p2 = property(lambda self: Point3(self.p.x + self.v.x,
  1756. self.p.y + self.v.y,
  1757. self.p.z + self.v.z))
  1758. def _apply_transform(self, t):
  1759. self.p = t * self.p
  1760. self.v = t * self.v
  1761. def _u_in(self, u):
  1762. return True
  1763. def intersect(self, other):
  1764. return other._intersect_line3(self)
  1765. def _intersect_sphere(self, other):
  1766. return _intersect_line3_sphere(self, other)
  1767. def _intersect_plane(self, other):
  1768. return _intersect_line3_plane(self, other)
  1769. def connect(self, other):
  1770. return other._connect_line3(self)
  1771. def _connect_point3(self, other):
  1772. return _connect_point3_line3(other, self)
  1773. def _connect_line3(self, other):
  1774. return _connect_line3_line3(other, self)
  1775. def _connect_sphere(self, other):
  1776. return _connect_sphere_line3(other, self)
  1777. def _connect_plane(self, other):
  1778. c = _connect_line3_plane(self, other)
  1779. if c:
  1780. return c
  1781. class Ray3(Line3):
  1782. def __repr__(self):
  1783. return 'Ray3(<%.2f, %.2f, %.2f> + u<%.2f, %.2f, %.2f>)' % \
  1784. (self.p.x, self.p.y, self.p.z, self.v.x, self.v.y, self.v.z)
  1785. def _u_in(self, u):
  1786. return u >= 0.0
  1787. class LineSegment3(Line3):
  1788. def __repr__(self):
  1789. return 'LineSegment3(<%.2f, %.2f, %.2f> to <%.2f, %.2f, %.2f>)' % \
  1790. (self.p.x, self.p.y, self.p.z,
  1791. self.p.x + self.v.x, self.p.y + self.v.y, self.p.z + self.v.z)
  1792. def _u_in(self, u):
  1793. return u >= 0.0 and u <= 1.0
  1794. def __abs__(self):
  1795. return abs(self.v)
  1796. def magnitude_squared(self):
  1797. return self.v.magnitude_squared()
  1798. def _swap(self):
  1799. # used by connect methods to switch order of points
  1800. self.p = self.p2
  1801. self.v *= -1
  1802. return self
  1803. length = property(lambda self: abs(self.v))
  1804. class Sphere:
  1805. __slots__ = ['c', 'r']
  1806. def __init__(self, center, radius):
  1807. assert isinstance(center, Vector3) and type(radius) == float
  1808. self.c = center.copy()
  1809. self.r = radius
  1810. def __copy__(self):
  1811. return self.__class__(self.c, self.r)
  1812. copy = __copy__
  1813. def __repr__(self):
  1814. return 'Sphere(<%.2f, %.2f, %.2f>, radius=%.2f)' % \
  1815. (self.c.x, self.c.y, self.c.z, self.r)
  1816. def _apply_transform(self, t):
  1817. self.c = t * self.c
  1818. def intersect(self, other):
  1819. return other._intersect_sphere(self)
  1820. def _intersect_point3(self, other):
  1821. return _intersect_point3_sphere(other, self)
  1822. def _intersect_line3(self, other):
  1823. return _intersect_line3_sphere(other, self)
  1824. def connect(self, other):
  1825. return other._connect_sphere(self)
  1826. def _connect_point3(self, other):
  1827. return _connect_point3_sphere(other, self)
  1828. def _connect_line3(self, other):
  1829. c = _connect_sphere_line3(self, other)
  1830. if c:
  1831. return c._swap()
  1832. def _connect_sphere(self, other):
  1833. return _connect_sphere_sphere(other, self)
  1834. def _connect_plane(self, other):
  1835. c = _connect_sphere_plane(self, other)
  1836. if c:
  1837. return c
  1838. class Plane:
  1839. # n.p = k, where n is normal, p is point on plane, k is constant scalar
  1840. __slots__ = ['n', 'k']
  1841. def __init__(self, *args):
  1842. if len(args) == 3:
  1843. assert isinstance(args[0], Point3) and \
  1844. isinstance(args[1], Point3) and \
  1845. isinstance(args[2], Point3)
  1846. self.n = (args[1] - args[0]).cross(args[2] - args[0])
  1847. self.n.normalize()
  1848. self.k = self.n.dot(args[0])
  1849. elif len(args) == 2:
  1850. if isinstance(args[0], Point3) and isinstance(args[1], Vector3):
  1851. self.n = args[1].normalized()
  1852. self.k = self.n.dot(args[0])
  1853. elif isinstance(args[0], Vector3) and type(args[1]) == float:
  1854. self.n = args[0].normalized()
  1855. self.k = args[1]
  1856. else:
  1857. raise AttributeError, '%r' % (args,)
  1858. else:
  1859. raise AttributeError, '%r' % (args,)
  1860. if not self.n:
  1861. raise AttributeError, 'Points on plane are colinear'
  1862. def __copy__(self):
  1863. return self.__class__(self.n, self.k)
  1864. copy = __copy__
  1865. def __repr__(self):
  1866. return 'Plane(<%.2f, %.2f, %.2f>.p = %.2f)' % \
  1867. (self.n.x, self.n.y, self.n.z, self.k)
  1868. def _get_point(self):
  1869. # Return an arbitrary point on the plane
  1870. if self.n.z:
  1871. return Point3(0., 0., self.k / self.n.z)
  1872. elif self.n.y:
  1873. return Point3(0., self.k / self.n.y, 0.)
  1874. else:
  1875. return Point3(self.k / self.n.x, 0., 0.)
  1876. def _apply_transform(self, t):
  1877. p = t * self._get_point()
  1878. self.n = t * self.n
  1879. self.k = self.n.dot(p)
  1880. def intersect(self, other):
  1881. return other._intersect_plane(self)
  1882. def _intersect_line3(self, other):
  1883. return _intersect_line3_plane(other, self)
  1884. def _intersect_plane(self, other):
  1885. return _intersect_plane_plane(self, other)
  1886. def connect(self, other):
  1887. return other._connect_plane(self)
  1888. def _connect_point3(self, other):
  1889. return _connect_point3_plane(other, self)
  1890. def _connect_line3(self, other):
  1891. return _connect_line3_plane(other, self)
  1892. def _connect_sphere(self, other):
  1893. return _connect_sphere_plane(other, self)
  1894. def _connect_plane(self, other):
  1895. return _connect_plane_plane(other, self)