1 ! Copyright (C) 2007, 2008 Alex Chapman
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors arrays kernel locals math math.constants math.functions math.matrices math.vectors random sequences ;
6 ! An oint is a point with three linearly independent unit vectors
7 ! given relative to that point. In jamshred a player's location and
8 ! direction are given by the player's oint. Similarly, a tunnel
9 ! segment's location and orientation are given by an oint.
11 TUPLE: oint location forward up left ;
14 : rotation-quaternion ( theta axis -- quaternion )
15 swap 2 / dup cos swap sin rot n*v first3 rect> [ rect> ] dip 2array ;
19 ! inline old math.quaternions to get this to work, eww.
21 : ** ( x y -- z ) conjugate * ; inline
23 : 2q ( u v -- u' u'' v' v'' ) [ first2 ] bi@ ; inline
25 : q*a ( u v -- a ) 2q swapd ** [ * ] dip - ; inline
27 : q*b ( u v -- b ) 2q [ ** swap ] dip * + ; inline
30 [ q*a ] [ q*b ] 2bi 2array ;
33 first3 rect> [ 0 swap rect> ] dip 2array ;
36 first2 [ imaginary-part ] dip >rect 3array ;
38 : qconjugate ( u -- u' )
39 first2 [ conjugate ] [ neg ] bi* 2array ;
42 qconjugate dup norm-sq v/n ;
46 : rotate-vector ( q qrecip v -- v )
49 : rotate-oint ( oint theta axis -- )
50 rotation-quaternion dup qrecip pick
51 [ forward>> rotate-vector >>forward ]
52 [ up>> rotate-vector >>up ]
53 [ left>> rotate-vector >>left ] 3tri drop ;
55 : left-pivot ( oint theta -- )
56 over left>> rotate-oint ;
58 : up-pivot ( oint theta -- )
59 over up>> rotate-oint ;
61 : forward-pivot ( oint theta -- )
62 over forward>> rotate-oint ;
64 : random-float+- ( n -- m )
65 ! find a random float between -n/2 and n/2
66 dup 10000 * >integer random 10000 / swap 2 / - ;
68 : random-turn ( oint theta -- )
69 2 / 2dup random-float+- left-pivot random-float+- up-pivot ;
71 : location+ ( v oint -- )
72 [ location>> v+ ] [ location<< ] bi ;
74 : go-forward ( distance oint -- )
75 [ forward>> n*v ] [ location+ ] bi ;
77 : distance-vector ( oint oint -- vector )
78 [ location>> ] bi@ swap v- ;
80 : distance ( oint oint -- distance )
81 distance-vector norm ;
83 : scalar-projection ( v1 v2 -- n )
84 ! the scalar projection of v1 onto v2
85 [ v. ] [ norm ] bi / ;
87 : proj-perp ( u v -- w )
90 : perpendicular-distance ( oint oint -- distance )
91 [ distance-vector ] keep 2dup left>> scalar-projection abs
92 -rot up>> scalar-projection abs + ;
94 :: reflect ( v n -- v' )
95 ! bounce v on a surface with normal n
96 v v n v. n n v. / 2 * n n*v v- ;
98 : half-way ( p1 p2 -- p3 )
101 : half-way-between-oints ( o1 o2 -- p )
102 [ location>> ] bi@ half-way ;