/
dynamics.coffee
1538 lines (1322 loc) · 41.1 KB
/
dynamics.coffee
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Visibility change
isDocumentVisible = ->
document.visibilityState == "visible" || dynamics.tests?
observeVisibilityChange = (() ->
fns = []
document?.addEventListener("visibilitychange", ->
for fn in fns
fn(isDocumentVisible())
)
(fn) ->
fns.push(fn)
)()
# Object helpers
# Not deep clone and not using JSON.stringify/JSON.parse because
# We want to keep functions
clone = (o) ->
newO = {}
for k, v of o
newO[k] = v
newO
# Caching
cacheFn = (func) ->
data = {}
->
key = ""
for k in arguments
key += k.toString() + ","
result = data[key]
unless result
data[key] = result = func.apply(this, arguments)
result
# Make a function accept array or single objects for the first argument
makeArrayFn = (fn) ->
(el) ->
if el instanceof Array or el instanceof NodeList or el instanceof HTMLCollection
res = for i in [0...el.length]
args = Array.prototype.slice.call(arguments, 1)
args.splice(0, 0, el[i])
fn.apply(this, args)
return res
fn.apply(this, arguments)
# Properties Helpers
applyDefaults = (options, defaults) ->
for k, v of defaults
options[k] ?= v
applyFrame = (el, properties) ->
if(el.style?)
applyProperties(el, properties)
else
for k, v of properties
el[k] = v.format()
applyProperties = (el, properties) ->
properties = parseProperties(properties)
transforms = []
isSVG = isSVGElement(el)
for k, v of properties
if transformProperties.contains(k)
transforms.push([k, v])
else
if v.format?
v = v.format()
if typeof(v) == 'number'
v = "#{v}#{unitForProperty(k, v)}"
if isSVG && svgProperties.contains(k)
el.setAttribute(k, v)
else if k of el # support animating scrollTop, etc
el[k] = v
else
el.style[propertyWithPrefix(k)] = v
if transforms.length > 0
if isSVG
matrix = new Matrix2D()
matrix.applyProperties(transforms)
el.setAttribute("transform", matrix.decompose().format())
else
v = (transforms.map (transform) ->
transformValueForProperty(transform[0], transform[1])
).join(" ")
el.style[propertyWithPrefix("transform")] = v
isSVGElement = (el) ->
if SVGElement? and SVGSVGElement?
el instanceof SVGElement && !(el instanceof SVGSVGElement)
else
dynamics.tests?.isSVG?(el) ? false
# Math
roundf = (v, decimal) ->
d = Math.pow(10, decimal)
return Math.round(v * d) / d
# Set
class Set
constructor: (array) ->
@obj = {}
for v in array
@obj[v] = 1
contains: (v) ->
return @obj[v] == 1
# String Helpers
toDashed = (str) ->
return str.replace(/([A-Z])/g, ($1) -> "-" + $1.toLowerCase())
# CSS Helpers
pxProperties = new Set('marginTop,marginLeft,marginBottom,marginRight,paddingTop,paddingLeft,paddingBottom,paddingRight,top,left,bottom,right,translateX,translateY,translateZ,perspectiveX,perspectiveY,perspectiveZ,width,height,maxWidth,maxHeight,minWidth,minHeight,borderRadius'.split(','))
degProperties = new Set('rotate,rotateX,rotateY,rotateZ,skew,skewX,skewY,skewZ'.split(','))
transformProperties = new Set('translate,translateX,translateY,translateZ,scale,scaleX,scaleY,scaleZ,rotate,rotateX,rotateY,rotateZ,rotateC,rotateCX,rotateCY,skew,skewX,skewY,skewZ,perspective'.split(','))
svgProperties = new Set('accent-height,ascent,azimuth,baseFrequency,baseline-shift,bias,cx,cy,d,diffuseConstant,divisor,dx,dy,elevation,filterRes,fx,fy,gradientTransform,height,k1,k2,k3,k4,kernelMatrix,kernelUnitLength,letter-spacing,limitingConeAngle,markerHeight,markerWidth,numOctaves,order,overline-position,overline-thickness,pathLength,points,pointsAtX,pointsAtY,pointsAtZ,r,radius,rx,ry,seed,specularConstant,specularExponent,stdDeviation,stop-color,stop-opacity,strikethrough-position,strikethrough-thickness,surfaceScale,target,targetX,targetY,transform,underline-position,underline-thickness,viewBox,width,x,x1,x2,y,y1,y2,z'.split(','))
unitForProperty = (k, v) ->
return '' unless typeof v == 'number'
if pxProperties.contains(k)
return 'px'
else if degProperties.contains(k)
return 'deg'
''
transformValueForProperty = (k, v) ->
match = "#{v}".match(/^([0-9.-]*)([^0-9]*)$/)
if match?
v = match[1]
unit = match[2]
else
v = parseFloat(v)
v = roundf(parseFloat(v), 10)
if !unit? or unit == ""
unit = unitForProperty(k, v)
"#{k}(#{v}#{unit})"
parseProperties = (properties) ->
parsed = {}
for property, value of properties
if transformProperties.contains(property)
match = property.match(/(translate|rotateC|rotate|skew|scale|perspective)(X|Y|Z|)/)
if match and match[2].length > 0
parsed[property] = value
else
for axis in ['X', 'Y', 'Z']
parsed[match[1] + axis] = value
else
parsed[property] = value
parsed
defaultValueForKey = (key) ->
v = if key == 'opacity' then 1 else 0
"#{v}#{unitForProperty(key, v)}"
getCurrentProperties = (el, keys) ->
properties = {}
isSVG = isSVGElement(el)
if el.style?
style = window.getComputedStyle(el, null)
for key in keys
if transformProperties.contains(key)
unless properties['transform']?
if isSVG
matrix = new Matrix2D(el.transform.baseVal.consolidate()?.matrix)
else
matrix = Matrix.fromTransform(style[propertyWithPrefix('transform')])
properties['transform'] = matrix.decompose()
else
v = style[key]
if !v? && svgProperties.contains(key)
v = el.getAttribute(key)
if v == "" or !v?
v = defaultValueForKey(key)
properties[key] = createInterpolable(v)
else
for key in keys
properties[key] = createInterpolable(el[key])
properties
# Interpolable
createInterpolable = (value) ->
klasses = [InterpolableArray, InterpolableObject, InterpolableNumber, InterpolableString]
for klass in klasses
interpolable = klass.create(value)
return interpolable if interpolable?
null
class InterpolableString
constructor: (@parts) ->
interpolate: (endInterpolable, t) =>
start = @parts
end = endInterpolable.parts
newParts = []
for i in [0...Math.min(start.length, end.length)]
if start[i].interpolate?
newParts.push(start[i].interpolate(end[i], t))
else
newParts.push(start[i])
new InterpolableString(newParts)
format: =>
parts = @parts.map (val) ->
if val.format?
val.format()
else
val
parts.join('')
@create: (value) =>
value = "#{value}"
matches = []
types = [
{
re: /(#[a-f\d]{3,6})/ig,
klass: InterpolableColor,
parse: (v) -> v,
},
{
re: /(rgba?\([0-9.]*, ?[0-9.]*, ?[0-9.]*(?:, ?[0-9.]*)?\))/ig,
klass: InterpolableColor,
parse: (v) -> v,
},
{
re: /([-+]?[\d.]+)/ig,
klass: InterpolableNumber,
parse: parseFloat,
},
]
for type in types
re = type.re
while match = re.exec(value)
matches.push({
index: match.index,
length: match[1].length,
interpolable: type.klass.create(type.parse(match[1])),
})
matches = matches.sort((a, b) ->
if a.index > b.index
1
else
-1
)
parts = []
index = 0
for match in matches
continue if match.index < index
if match.index > index
parts.push(value.substring(index, match.index))
parts.push(match.interpolable)
index = match.index + match.length
if index < value.length
parts.push(value.substring(index))
return new InterpolableString(parts)
class InterpolableObject
constructor: (obj) ->
@obj = obj
interpolate: (endInterpolable, t) =>
start = @obj
end = endInterpolable.obj
newObj = {}
for k, v of start
if v.interpolate?
newObj[k] = v.interpolate(end[k], t)
else
newObj[k] = v
new InterpolableObject(newObj)
format: =>
@obj
@create: (value) =>
if value instanceof Object
obj = {}
for k, v of value
obj[k] = createInterpolable(v)
return new InterpolableObject(obj)
null
class InterpolableNumber
constructor: (value) ->
@value = parseFloat(value)
interpolate: (endInterpolable, t) =>
start = @value
end = endInterpolable.value
new InterpolableNumber((end - start) * t + start)
format: =>
roundf(@value, 5)
@create: (value) =>
return new InterpolableNumber(value) if typeof(value) == 'number'
null
class InterpolableArray
constructor: (@values) ->
interpolate: (endInterpolable, t) =>
start = @values
end = endInterpolable.values
newValues = []
for i in [0...Math.min(start.length, end.length)]
if start[i].interpolate?
newValues.push(start[i].interpolate(end[i], t))
else
newValues.push(start[i])
new InterpolableArray(newValues)
format: =>
@values.map (val) ->
if val.format?
val.format()
else
val
@createFromArray: (arr) =>
values = arr.map (val) ->
createInterpolable(val) || val
values = values.filter (val) ->
val?
return new InterpolableArray(values)
@create: (value) =>
return @createFromArray(value) if value instanceof Array
null
class Color
constructor: (@rgb={}, @format) ->
@fromHex: (hex) ->
hex3 = hex.match(/^#([a-f\d]{1})([a-f\d]{1})([a-f\d]{1})$/i)
if hex3?
hex = "##{hex3[1]}#{hex3[1]}#{hex3[2]}#{hex3[2]}#{hex3[3]}#{hex3[3]}"
result = hex.match(/^#([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i)
if result?
return new Color({
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16),
a: 1
}, "hex")
null
@fromRgb: (rgb) ->
match = rgb.match(/^rgba?\(([0-9.]*), ?([0-9.]*), ?([0-9.]*)(?:, ?([0-9.]*))?\)$/)
if match?
return new Color({
r: parseFloat(match[1]),
g: parseFloat(match[2]),
b: parseFloat(match[3]),
a: parseFloat(match[4] ? 1)
}, if match[4]? then "rgba" else "rgb")
null
@componentToHex = (c) ->
hex = c.toString(16);
if hex.length == 1
"0" + hex
else
hex
toHex: =>
"#" + Color.componentToHex(@rgb.r) + Color.componentToHex(@rgb.g) + Color.componentToHex(@rgb.b)
toRgb: =>
"rgb(#{@rgb.r}, #{@rgb.g}, #{@rgb.b})"
toRgba: =>
"rgba(#{@rgb.r}, #{@rgb.g}, #{@rgb.b}, #{@rgb.a})"
class InterpolableColor
constructor: (@color) ->
interpolate: (endInterpolable, t) =>
start = @color
end = endInterpolable.color
rgb = {}
for k in ['r', 'g', 'b']
v = Math.round((end.rgb[k] - start.rgb[k]) * t + start.rgb[k])
rgb[k] = Math.min(255, Math.max(0, v))
k = "a"
v = roundf((end.rgb[k] - start.rgb[k]) * t + start.rgb[k], 5)
rgb[k] = Math.min(1, Math.max(0, v))
new InterpolableColor(new Color(rgb, end.format))
format: =>
if @color.format == "hex"
@color.toHex()
else if @color.format == "rgb"
@color.toRgb()
else if @color.format == "rgba"
@color.toRgba()
@create: (value) =>
return unless typeof(value) == "string"
color = Color.fromHex(value) || Color.fromRgb(value)
if color?
return new InterpolableColor(color)
null
# SVG Matrix2D
class DecomposedMatrix2D
constructor: (@props) ->
interpolate: (endMatrix, t) =>
newProps = {}
for k in ['translate', 'scale', 'rotate']
newProps[k] = []
for i in [0...@props[k].length]
newProps[k][i] = (endMatrix.props[k][i] - @props[k][i]) * t + @props[k][i]
for i in [1..2]
newProps['rotate'][i] = endMatrix.props['rotate'][i]
for k in ['skew']
newProps[k] = (endMatrix.props[k] - @props[k]) * t + @props[k]
new DecomposedMatrix2D(newProps)
format: =>
"translate(#{@props.translate.join(',')}) rotate(#{@props.rotate.join(',')})
skewX(#{@props.skew}) scale(#{@props.scale.join(',')})"
applyRotateCenter: (rotateC) =>
m = baseSVG.createSVGMatrix()
m = m.translate(rotateC[0], rotateC[1])
m = m.rotate(@props.rotate[0])
m = m.translate(-rotateC[0], -rotateC[1])
m2d = new Matrix2D(m)
negativeTranslate = m2d.decompose().props.translate
for i in [0..1]
@props.translate[i] -= negativeTranslate[i]
baseSVG = document?.createElementNS("http://www.w3.org/2000/svg", "svg")
class Matrix2D
constructor: (@m) ->
if !@m
@m = baseSVG.createSVGMatrix()
decompose: =>
r0 = new Vector([@m.a, @m.b])
r1 = new Vector([@m.c, @m.d])
kx = r0.length()
kz = r0.dot(r1)
r0 = r0.normalize()
ky = r1.combine(r0, 1, -kz).length()
new DecomposedMatrix2D({
translate: [@m.e, @m.f],
rotate: [Math.atan2(@m.b, @m.a) * 180 / Math.PI, @rotateCX, @rotateCY],
scale: [kx, ky],
skew: kz / ky * 180 / Math.PI
})
applyProperties: (properties) =>
hash = {}
for props in properties
hash[props[0]] = props[1]
for k, v of hash
if k == "translateX"
@m = @m.translate(v, 0)
else if k == "translateY"
@m = @m.translate(0, v)
else if k == "scaleX"
@m = @m.scaleNonUniform(v, 1)
else if k == "scaleY"
@m = @m.scaleNonUniform(1, v)
else if k == "rotateZ"
@m = @m.rotate(v)
else if k == "skewX"
@m = @m.skewX(v)
else if k == "skewY"
@m = @m.skewY(v)
@rotateCX = hash.rotateCX ? 0
@rotateCY = hash.rotateCY ? 0
# Vector
# Some code has been ported from Sylvester.js https://github.com/jcoglan/sylvester
class Vector
constructor: (@els) ->
# Returns element i of the vector
e: (i) =>
return if (i < 1 || i > this.els.length) then null else this.els[i-1]
# Returns the scalar product of the vector with the argument
# Both vectors must have equal dimensionality
dot: (vector) =>
V = vector.els || vector
product = 0
n = this.els.length
return null if n != V.length
n += 1
while --n
product += this.els[n-1] * V[n-1]
return product
# Returns the vector product of the vector with the argument
# Both vectors must have dimensionality 3
cross: (vector) =>
B = vector.els || vector
return null if this.els.length != 3 || B.length != 3
A = this.els
return new Vector([
(A[1] * B[2]) - (A[2] * B[1]),
(A[2] * B[0]) - (A[0] * B[2]),
(A[0] * B[1]) - (A[1] * B[0])
])
length: =>
a = 0
for e in @els
a += Math.pow(e, 2)
Math.sqrt(a)
normalize: =>
length = @length()
newElements = []
for i, e of @els
newElements[i] = e / length
new Vector(newElements)
combine: (b, ascl, bscl) =>
result = []
for i in [0...@els.length]
result[i] = (ascl * @els[i]) + (bscl * b.els[i])
new Vector(result)
# Matrix
class DecomposedMatrix
interpolate: (decomposedB, t, only = null) =>
decomposedA = @
# New decomposedMatrix
decomposed = new DecomposedMatrix
# Linearly interpolate translate, scale, skew and perspective
for k in [ 'translate', 'scale', 'skew', 'perspective' ]
decomposed[k] = []
for i in [0..decomposedA[k].length-1]
if !only? or only.indexOf(k) > -1 or only.indexOf("#{k}#{['x','y','z'][i]}") > -1
decomposed[k][i] = (decomposedB[k][i] - decomposedA[k][i]) * t + decomposedA[k][i]
else
decomposed[k][i] = decomposedA[k][i]
if !only? or only.indexOf('rotate') != -1
# Interpolate quaternion
qa = decomposedA.quaternion
qb = decomposedB.quaternion
angle = qa[0] * qb[0] + qa[1] * qb[1] + qa[2] * qb[2] + qa[3] * qb[3]
if angle < 0.0
for i in [0..3]
qa[i] = -qa[i]
angle = -angle
if angle + 1.0 > .05
if 1.0 - angle >= .05
th = Math.acos(angle)
invth = 1.0 / Math.sin(th)
scale = Math.sin(th * (1.0 - t)) * invth
invscale = Math.sin(th * t) * invth
else
scale = 1.0 - t
invscale = t
else
qb[0] = -qa[1]
qb[1] = qa[0]
qb[2] = -qa[3]
qb[3] = qa[2]
scale = Math.sin(piDouble * (.5 - t))
invscale = Math.sin(piDouble * t)
decomposed.quaternion = []
for i in [0..3]
decomposed.quaternion[i] = qa[i] * scale + qb[i] * invscale
else
decomposed.quaternion = decomposedA.quaternion
return decomposed
format: =>
@toMatrix().toString()
toMatrix: =>
decomposedMatrix = @
matrix = Matrix.I(4)
# apply perspective
for i in [0..3]
matrix.els[i][3] = decomposedMatrix.perspective[i]
# apply rotation
quaternion = decomposedMatrix.quaternion
x = quaternion[0]
y = quaternion[1]
z = quaternion[2]
w = quaternion[3]
# apply skew
# temp is a identity 4x4 matrix initially
skew = decomposedMatrix.skew
match = [[1,0],[2,0],[2,1]]
for i in [2..0]
if skew[i]
temp = Matrix.I(4)
temp.els[match[i][0]][match[i][1]] = skew[i]
matrix = matrix.multiply(temp)
# Construct a composite rotation matrix from the quaternion values
matrix = matrix.multiply(new Matrix([[
1 - 2 * (y * y + z * z),
2 * (x * y - z * w),
2 * (x * z + y * w),
0
], [
2 * (x * y + z * w),
1 - 2 * (x * x + z * z),
2 * (y * z - x * w),
0
], [
2 * (x * z - y * w),
2 * (y * z + x * w),
1 - 2 * (x * x + y * y),
0
], [ 0, 0, 0, 1 ]]))
# apply scale and translation
for i in [0..2]
for j in [0..2]
matrix.els[i][j] *= decomposedMatrix.scale[i]
matrix.els[3][i] = decomposedMatrix.translate[i]
matrix
# Some code has been ported from Sylvester.js https://github.com/jcoglan/sylvester
class Matrix
constructor: (@els) ->
# Returns element (i,j) of the matrix
e: (i,j) =>
return null if (i < 1 || i > this.els.length || j < 1 || j > this.els[0].length)
this.els[i-1][j-1]
# Returns a copy of the matrix
dup: () =>
return new Matrix(this.els)
# Returns the result of multiplying the matrix from the right by the argument.
# If the argument is a scalar then just multiply all the elements. If the argument is
# a vector, a vector is returned, which saves you having to remember calling
# col(1) on the result.
multiply: (matrix) =>
returnVector = if matrix.modulus then true else false
M = matrix.els || matrix
M = new Matrix(M).els if (typeof(M[0][0]) == 'undefined')
ni = this.els.length
ki = ni
kj = M[0].length
cols = this.els[0].length
elements = []
ni += 1
while (--ni)
i = ki - ni
elements[i] = []
nj = kj
nj += 1
while (--nj)
j = kj - nj
sum = 0
nc = cols
nc += 1
while (--nc)
c = cols - nc
sum += this.els[i][c] * M[c][j]
elements[i][j] = sum
M = new Matrix(elements)
return if returnVector then M.col(1) else M
# Returns the transpose of the matrix
transpose: =>
rows = this.els.length
cols = this.els[0].length
elements = []
ni = cols
ni += 1
while (--ni)
i = cols - ni
elements[i] = []
nj = rows
nj += 1
while (--nj)
j = rows - nj
elements[i][j] = this.els[j][i]
return new Matrix(elements)
# Make the matrix upper (right) triangular by Gaussian elimination.
# This method only adds multiples of rows to other rows. No rows are
# scaled up or switched, and the determinant is preserved.
toRightTriangular: =>
M = this.dup()
n = this.els.length
k = n
kp = this.els[0].length
while (--n)
i = k - n
if (M.els[i][i] == 0)
for j in [i + 1...k]
if (M.els[j][i] != 0)
els = []
np = kp
np += 1
while (--np)
p = kp - np
els.push(M.els[i][p] + M.els[j][p])
M.els[i] = els
break
if (M.els[i][i] != 0)
for j in [i + 1...k]
multiplier = M.els[j][i] / M.els[i][i]
els = []
np = kp
np += 1
while (--np)
p = kp - np
# Elements with column numbers up to an including the number
# of the row that we're subtracting can safely be set straight to
# zero, since that's the point of this routine and it avoids having
# to loop over and correct rounding errors later
els.push(if p <= i then 0 else M.els[j][p] - M.els[i][p] * multiplier)
M.els[j] = els
return M
# Returns the result of attaching the given argument to the right-hand side of the matrix
augment: (matrix) =>
M = matrix.els || matrix
M = new Matrix(M).els if (typeof(M[0][0]) == 'undefined')
T = this.dup()
cols = T.els[0].length
ni = T.els.length
ki = ni
kj = M[0].length
return null if (ni != M.length)
ni += 1
while (--ni)
i = ki - ni
nj = kj
nj += 1
while (--nj)
j = kj - nj
T.els[i][cols + j] = M[i][j]
return T
# Returns the inverse (if one exists) using Gauss-Jordan
inverse: =>
ni = this.els.length
ki = ni
M = this.augment(Matrix.I(ni)).toRightTriangular()
kp = M.els[0].length
inverse_elements = []
# Matrix is non-singular so there will be no zeros on the diagonal
# Cycle through rows from last to first
ni += 1
while (--ni)
i = ni - 1
# First, normalise diagonal elements to 1
els = []
np = kp
inverse_elements[i] = []
divisor = M.els[i][i]
np += 1
while (--np)
p = kp - np
new_element = M.els[i][p] / divisor
els.push(new_element)
# Shuffle of the current row of the right hand side into the results
# array as it will not be modified by later runs through this loop
if (p >= ki)
inverse_elements[i].push(new_element)
M.els[i] = els
# Then, subtract this row from those above it to
# give the identity matrix on the left hand side
for j in [0...i]
els = []
np = kp
np += 1
while (--np)
p = kp - np
els.push(M.els[j][p] - M.els[i][p] * M.els[j][i])
M.els[j] = els
return new Matrix(inverse_elements)
@I = (n) ->
els = []
k = n
n += 1
while --n
i = k - n
els[i] = []
nj = k
nj += 1
while --nj
j = k - nj
els[i][j] = if (i == j) then 1 else 0
new Matrix(els)
decompose: =>
matrix = @
translate = []
scale = []
skew = []
quaternion = []
perspective = []
# Deep copy
els = []
for i in [0..3]
els[i] = []
for j in [0..3]
els[i][j] = matrix.els[i][j]
if (els[3][3] == 0)
return false
# Normalize the matrix.
for i in [0..3]
for j in [0..3]
els[i][j] /= els[3][3]
# perspectiveMatrix is used to solve for perspective, but it also provides
# an easy way to test for singularity of the upper 3x3 component.
perspectiveMatrix = matrix.dup()
for i in [0..2]
perspectiveMatrix.els[i][3] = 0
perspectiveMatrix.els[3][3] = 1
# Don't do this anymore, it would return false for scale(0)..
# if perspectiveMatrix.determinant() == 0
# return false
# First, isolate perspective.
if els[0][3] != 0 || els[1][3] != 0 || els[2][3] != 0
# rightHandSide is the right hand side of the equation.
rightHandSide = new Vector(els[0..3][3])
# Solve the equation by inverting perspectiveMatrix and multiplying
# rightHandSide by the inverse.
inversePerspectiveMatrix = perspectiveMatrix.inverse()
transposedInversePerspectiveMatrix = inversePerspectiveMatrix.transpose()
perspective = transposedInversePerspectiveMatrix.multiply(rightHandSide).els
# Clear the perspective partition
for i in [0..2]
els[i][3] = 0
els[3][3] = 1
else
# No perspective.
perspective = [0,0,0,1]
# Next take care of translation
for i in [0..2]
translate[i] = els[3][i]
els[3][i] = 0
# Now get scale and shear. 'row' is a 3 element array of 3 component vectors
row = []
for i in [0..2]
row[i] = new Vector(els[i][0..2])
# Compute X scale factor and normalize first row.
scale[0] = row[0].length()
row[0] = row[0].normalize()
# Compute XY shear factor and make 2nd row orthogonal to 1st.
skew[0] = row[0].dot(row[1])
row[1] = row[1].combine(row[0], 1.0, -skew[0])
# Now, compute Y scale and normalize 2nd row.
scale[1] = row[1].length()
row[1] = row[1].normalize()
skew[0] /= scale[1]
# Compute XZ and YZ shears, orthogonalize 3rd row
skew[1] = row[0].dot(row[2])
row[2] = row[2].combine(row[0], 1.0, -skew[1])
skew[2] = row[1].dot(row[2])
row[2] = row[2].combine(row[1], 1.0, -skew[2])
# Next, get Z scale and normalize 3rd row.
scale[2] = row[2].length()
row[2] = row[2].normalize()
skew[1] /= scale[2]
skew[2] /= scale[2]
# At this point, the matrix (in rows) is orthonormal.
# Check for a coordinate system flip. If the determinant
# is -1, then negate the matrix and the scaling factors.
pdum3 = row[1].cross(row[2])
if row[0].dot(pdum3) < 0
for i in [0..2]
scale[i] *= -1
for j in [0..2]
row[i].els[j] *= -1
# Get element at row
rowElement = (index, elementIndex) ->
row[index].els[elementIndex]
# Euler angles
rotate = []
rotate[1] = Math.asin(-rowElement(0, 2))
if Math.cos(rotate[1]) != 0
rotate[0] = Math.atan2(rowElement(1, 2), rowElement(2, 2))
rotate[2] = Math.atan2(rowElement(0, 1), rowElement(0, 0))
else
rotate[0] = Math.atan2(-rowElement(2, 0), rowElement(1, 1))
rotate[1] = 0
# Now, get the rotations out
t = rowElement(0, 0) + rowElement(1, 1) + rowElement(2, 2) + 1.0
if t > 1e-4
s = 0.5 / Math.sqrt(t)
w = 0.25 / s
x = (rowElement(2, 1) - rowElement(1, 2)) * s
y = (rowElement(0, 2) - rowElement(2, 0)) * s
z = (rowElement(1, 0) - rowElement(0, 1)) * s
else if (rowElement(0, 0) > rowElement(1, 1)) && (rowElement(0, 0) > rowElement(2, 2))
s = Math.sqrt(1.0 + rowElement(0, 0) - rowElement(1, 1) - rowElement(2, 2)) * 2.0
x = 0.25 * s
y = (rowElement(0, 1) + rowElement(1, 0)) / s
z = (rowElement(0, 2) + rowElement(2, 0)) / s
w = (rowElement(2, 1) - rowElement(1, 2)) / s
else if rowElement(1, 1) > rowElement(2, 2)
s = Math.sqrt(1.0 + rowElement(1, 1) - rowElement(0, 0) - rowElement(2, 2)) * 2.0
x = (rowElement(0, 1) + rowElement(1, 0)) / s
y = 0.25 * s
z = (rowElement(1, 2) + rowElement(2, 1)) / s
w = (rowElement(0, 2) - rowElement(2, 0)) / s
else
s = Math.sqrt(1.0 + rowElement(2, 2) - rowElement(0, 0) - rowElement(1, 1)) * 2.0
x = (rowElement(0, 2) + rowElement(2, 0)) / s
y = (rowElement(1, 2) + rowElement(2, 1)) / s
z = 0.25 * s
w = (rowElement(1, 0) - rowElement(0, 1)) / s
quaternion = [x, y, z, w]
result = new DecomposedMatrix
result.translate = translate
result.scale = scale
result.skew = skew
result.quaternion = quaternion
result.perspective = perspective
result.rotate = rotate
for typeKey, type of result
for k, v of type
type[k] = 0 if isNaN(v)
result
toString: =>
str = 'matrix3d('
for i in [0..3]
for j in [0..3]
str += roundf(@els[i][j], 10)
str += ',' unless i == 3 and j == 3
str += ')'
str
@matrixForTransform: cacheFn (transform) ->
matrixEl = document.createElement('div')
matrixEl.style.position = 'absolute'
matrixEl.style.visibility = 'hidden'
matrixEl.style[propertyWithPrefix("transform")] = transform
document.body.appendChild(matrixEl)
style = window.getComputedStyle(matrixEl, null)
result = style.transform ? style[propertyWithPrefix("transform")] ? dynamics.tests?.matrixForTransform(transform)
document.body.removeChild(matrixEl)
result