View Javadoc
1   /*
2    * Copyright (c) 2002-2026 Gargoyle Software Inc.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * https://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software
10   * distributed under the License is distributed on an "AS IS" BASIS,
11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   * See the License for the specific language governing permissions and
13   * limitations under the License.
14   */
15  package org.htmlunit.javascript.host.dom;
16  
17  import java.util.ArrayList;
18  import java.util.Arrays;
19  import java.util.List;
20  
21  import org.htmlunit.corejs.javascript.Context;
22  import org.htmlunit.corejs.javascript.Function;
23  import org.htmlunit.corejs.javascript.FunctionObject;
24  import org.htmlunit.corejs.javascript.Scriptable;
25  import org.htmlunit.corejs.javascript.ScriptableObject;
26  import org.htmlunit.corejs.javascript.SymbolKey;
27  import org.htmlunit.corejs.javascript.VarScope;
28  import org.htmlunit.corejs.javascript.typedarrays.NativeFloat32Array;
29  import org.htmlunit.corejs.javascript.typedarrays.NativeFloat64Array;
30  import org.htmlunit.corejs.javascript.typedarrays.NativeTypedArrayView;
31  import org.htmlunit.javascript.HtmlUnitScriptable;
32  import org.htmlunit.javascript.JavaScriptEngine;
33  import org.htmlunit.javascript.configuration.JsxClass;
34  import org.htmlunit.javascript.configuration.JsxConstructor;
35  import org.htmlunit.javascript.configuration.JsxFunction;
36  import org.htmlunit.javascript.configuration.JsxGetter;
37  import org.htmlunit.javascript.configuration.JsxStaticFunction;
38  import org.htmlunit.javascript.host.Window;
39  
40  /**
41   * A JavaScript object for {@code DOMMatrixReadOnly}.
42   *
43   * @author Ahmed Ashour
44   * @author Ronald Brill
45   *
46   * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/DOMMatrixReadOnly">MDN Documentation</a>
47   */
48  @JsxClass
49  public class DOMMatrixReadOnly extends HtmlUnitScriptable {
50  
51      // private static final Log LOG = LogFactory.getLog(DOMMatrixReadOnly.class);
52  
53      private double m11_;
54      private double m12_;
55      private double m13_;
56      private double m14_;
57  
58      private double m21_;
59      private double m22_;
60      private double m23_;
61      private double m24_;
62  
63      private double m31_;
64      private double m32_;
65      private double m33_;
66      private double m34_;
67  
68      private double m41_;
69      private double m42_;
70      private double m43_;
71      private double m44_;
72  
73      private boolean is2D_;
74  
75      /**
76       * Ctor.
77       */
78      public DOMMatrixReadOnly() {
79          m11_ = 1;
80          m12_ = 0;
81          m13_ = 0;
82          m14_ = 0;
83  
84          m21_ = 0;
85          m22_ = 1;
86          m23_ = 0;
87          m24_ = 0;
88  
89          m31_ = 0;
90          m32_ = 0;
91          m33_ = 1;
92          m34_ = 0;
93  
94          m41_ = 0;
95          m42_ = 0;
96          m43_ = 0;
97          m44_ = 1;
98  
99          is2D_ = true;
100     }
101 
102     /**
103      * JavaScript constructor.
104      * @param cx the current context
105      * @param scope the scope
106      * @param args the arguments to the DOMMatrixReadOnly constructor
107      * @param ctorObj the function object
108      * @param inNewExpr {@code true} if invoked with the {@code new} operator
109      * @return the Java object that JavaScript can access
110      */
111     @JsxConstructor
112     public static DOMMatrixReadOnly jsConstructor(final Context cx, final VarScope scope,
113             final Object[] args, final Function ctorObj, final boolean inNewExpr) {
114 
115         final DOMMatrixReadOnly matrix = new DOMMatrixReadOnly();
116         matrix.init(args, scope, ctorObj);
117         return matrix;
118     }
119 
120     /**
121      * Initializes this matrix from the constructor arguments.
122      * <ul>
123      * <li>no argument or {@code undefined}: the identity matrix</li>
124      * <li>an iterable object (e.g. an array or a typed array): a sequence of 6 (2D)
125      * or 16 (3D) numbers</li>
126      * <li>everything else is converted to a string and parsed as CSS transform list;
127      * this is only supported in a window, workers throw a TypeError</li>
128      * </ul>
129      *
130      * @param args the constructor arguments
131      * @param scope the scope
132      * @param ctorObj the constructor function
133      */
134     protected void init(final Object[] args, final VarScope scope, final Function ctorObj) {
135         setParentScope(scope);
136         setPrototype(((FunctionObject) ctorObj).getClassPrototype());
137 
138         if (args.length == 0 || JavaScriptEngine.isUndefined(args[0])) {
139             return;
140         }
141 
142         final Object init = args[0];
143         if (init instanceof Scriptable initScriptable
144                 && ScriptableObject.hasProperty(initScriptable, SymbolKey.ITERATOR)) {
145             final List<Double> values = new ArrayList<>();
146             JavaScriptEngine.iterate(Context.getCurrentContext(), scope, initScriptable,
147                     value -> values.add(JavaScriptEngine.toNumber(value)));
148 
149             if (values.size() == 6) {
150                 setValues2D(values.get(0), values.get(1), values.get(2),
151                         values.get(3), values.get(4), values.get(5));
152                 return;
153             }
154             if (values.size() == 16) {
155                 final double[] matrix = new double[16];
156                 for (int i = 0; i < matrix.length; i++) {
157                     matrix[i] = values.get(i);
158                 }
159                 setValues(matrix, false);
160                 return;
161             }
162 
163             throw JavaScriptEngine.typeError(getClassName() + " constructor: Matrix init sequence must have "
164                     + "a length of 6 or 16 (actual value: " + values.size() + ")");
165         }
166 
167         // (DOMString or sequence<unrestricted double>): everything else is a string
168         if (!(getWindowOrWorkerGlobalScope(this) instanceof Window)) {
169             throw JavaScriptEngine.typeError(getClassName()
170                     + " constructor: a transform list can only be parsed in a window context");
171         }
172         setTransformList(JavaScriptEngine.toString(init));
173     }
174 
175     /**
176      * Parses the given CSS transform list and replaces the values of this matrix
177      * with the result.
178      *
179      * @param transformList the CSS transform list
180      */
181     protected void setTransformList(final String transformList) {
182         try {
183             DOMMatrixTransformListParser.parse(transformList, this);
184         }
185         catch (final IllegalArgumentException e) {
186             throw JavaScriptEngine.asJavaScriptException(this,
187                     "Failed to parse '" + transformList + "': " + e.getMessage(),
188                     DOMException.SYNTAX_ERR);
189         }
190     }
191 
192     /**
193      * Returns the {@code m11} property.
194      * @return the {@code m11} property
195      */
196     @JsxGetter
197     public double getM11() {
198         return m11_;
199     }
200 
201     /**
202      * Sets the {@code m11} property.
203      * @param m11 the new value
204      */
205     public void setM11(final double m11) {
206         m11_ = m11;
207     }
208 
209     /**
210      * Returns the {@code a} property.
211      * @return the {@code a} property
212      */
213     @JsxGetter
214     public double getA() {
215         return m11_;
216     }
217 
218     /**
219      * Returns the {@code m12} property.
220      * @return the {@code m12} property
221      */
222     @JsxGetter
223     public double getM12() {
224         return m12_;
225     }
226 
227     /**
228      * Sets the {@code m12} property.
229      * @param m12 the new value
230      */
231     public void setM12(final double m12) {
232         m12_ = m12;
233     }
234 
235     /**
236      * Returns the {@code b} property.
237      * @return the {@code b} property
238      */
239     @JsxGetter
240     public double getB() {
241         return m12_;
242     }
243 
244     /**
245      * Returns the {@code m13} property.
246      * @return the {@code m13} property
247      */
248     @JsxGetter
249     public double getM13() {
250         return m13_;
251     }
252 
253     /**
254      * Sets the {@code m13} property.
255      * @param m13 the new value
256      */
257     public void setM13(final double m13) {
258         m13_ = m13;
259     }
260 
261     /**
262      * Returns the {@code m14} property.
263      * @return the {@code m14} property
264      */
265     @JsxGetter
266     public double getM14() {
267         return m14_;
268     }
269 
270     /**
271      * Sets the {@code m14} property.
272      * @param m14 the new value
273      */
274     public void setM14(final double m14) {
275         m14_ = m14;
276     }
277 
278     /**
279      * Returns the {@code m21} property.
280      * @return the {@code m21} property
281      */
282     @JsxGetter
283     public double getM21() {
284         return m21_;
285     }
286 
287     /**
288      * Sets the {@code m21} property.
289      * @param m21 the new value
290      */
291     public void setM21(final double m21) {
292         m21_ = m21;
293     }
294 
295     /**
296      * Returns the {@code c} property.
297      * @return the {@code c} property
298      */
299     @JsxGetter
300     public double getC() {
301         return m21_;
302     }
303 
304     /**
305      * Returns the {@code m22} property.
306      * @return the {@code m22} property
307      */
308     @JsxGetter
309     public double getM22() {
310         return m22_;
311     }
312 
313     /**
314      * Sets the {@code m22} property.
315      * @param m22 the new value
316      */
317     public void setM22(final double m22) {
318         m22_ = m22;
319     }
320 
321     /**
322      * Returns the {@code d} property.
323      * @return the {@code d} property
324      */
325     @JsxGetter
326     public double getD() {
327         return m22_;
328     }
329 
330     /**
331      * Returns the {@code m23} property.
332      * @return the {@code m23} property
333      */
334     @JsxGetter
335     public double getM23() {
336         return m23_;
337     }
338 
339     /**
340      * Sets the {@code m23} property.
341      * @param m23 the new value
342      */
343     public void setM23(final double m23) {
344         m23_ = m23;
345     }
346 
347     /**
348      * Returns the {@code m24} property.
349      * @return the {@code m24} property
350      */
351     @JsxGetter
352     public double getM24() {
353         return m24_;
354     }
355 
356     /**
357      * Sets the {@code m24} property.
358      * @param m24 the new value
359      */
360     public void setM24(final double m24) {
361         m24_ = m24;
362     }
363 
364     /**
365      * Returns the {@code m31} property.
366      * @return the {@code m31} property
367      */
368     @JsxGetter
369     public double getM31() {
370         return m31_;
371     }
372 
373     /**
374      * Sets the {@code m31} property.
375      * @param m31 the new value
376      */
377     public void setM31(final double m31) {
378         m31_ = m31;
379     }
380 
381     /**
382      * Returns the {@code m32} property.
383      * @return the {@code m32} property
384      */
385     @JsxGetter
386     public double getM32() {
387         return m32_;
388     }
389 
390     /**
391      * Sets the {@code m32} property.
392      * @param m32 the new value
393      */
394     public void setM32(final double m32) {
395         m32_ = m32;
396     }
397 
398     /**
399      * Returns the {@code m33} property.
400      * @return the {@code m33} property
401      */
402     @JsxGetter
403     public double getM33() {
404         return m33_;
405     }
406 
407     /**
408      * Sets the {@code m33} property.
409      * @param m33 the new value
410      */
411     public void setM33(final double m33) {
412         m33_ = m33;
413     }
414 
415     /**
416      * Returns the {@code m34} property.
417      * @return the {@code m34} property
418      */
419     @JsxGetter
420     public double getM34() {
421         return m34_;
422     }
423 
424     /**
425      * Sets the {@code m34} property.
426      * @param m34 the new value
427      */
428     public void setM34(final double m34) {
429         m34_ = m34;
430     }
431 
432     /**
433      * Returns the {@code m41} property.
434      * @return the {@code m41} property
435      */
436     @JsxGetter
437     public double getM41() {
438         return m41_;
439     }
440 
441     /**
442      * Sets the {@code m41} property.
443      * @param m41 the new value
444      */
445     public void setM41(final double m41) {
446         m41_ = m41;
447     }
448 
449     /**
450      * Returns the {@code e} property.
451      * @return the {@code e} property
452      */
453     @JsxGetter
454     public double getE() {
455         return m41_;
456     }
457 
458     /**
459      * Returns the {@code m42} property.
460      * @return the {@code m42} property
461      */
462     @JsxGetter
463     public double getM42() {
464         return m42_;
465     }
466 
467     /**
468      * Sets the {@code m42} property.
469      * @param m42 the new value
470      */
471     public void setM42(final double m42) {
472         m42_ = m42;
473     }
474 
475     /**
476      * Returns the {@code f} property.
477      * @return the {@code f} property
478      */
479     @JsxGetter
480     public double getF() {
481         return m42_;
482     }
483 
484     /**
485      * Returns the {@code m43} property.
486      * @return the {@code m43} property
487      */
488     @JsxGetter
489     public double getM43() {
490         return m43_;
491     }
492 
493     /**
494      * Sets the {@code m43} property.
495      * @param m43 the new value
496      */
497     public void setM43(final double m43) {
498         m43_ = m43;
499     }
500 
501     /**
502      * Returns the {@code m44} property.
503      * @return the {@code m44} property
504      */
505     @JsxGetter
506     public double getM44() {
507         return m44_;
508     }
509 
510     /**
511      * Sets the {@code m44} property.
512      * @param m44 the new value
513      */
514     public void setM44(final double m44) {
515         m44_ = m44;
516     }
517 
518     /**
519      * Returns the {@code is2D} property.
520      * @return the {@code is2D} property
521      */
522     @JsxGetter
523     public boolean isIs2D() {
524         return is2D_;
525     }
526 
527     /**
528      * Sets the {@code is2D} property.
529      * @param is2D the new value
530      */
531     public void setIs2D(final boolean is2D) {
532         is2D_ = is2D;
533     }
534 
535     /**
536      * Returns whether this matrix is the identity matrix.
537      * @return true if m12 element, m13 element, m14 element, m21 element, m23 element, m24 element,
538      *     m31 element, m32 element, m34 element, m41 element, m42 element, m43 element are 0 or -0
539      *     and m11 element, m22 element, m33 element, m44 element are 1. Otherwise it returns false.
540      */
541     @JsxGetter
542     public boolean getIsIdentity() {
543         return m11_ == 1 && m22_ == 1 && m33_ == 1 && m44_ == 1
544                 && m12_ == 0 && m13_ == 0 && m14_ == 0
545                 && m21_ == 0 && m23_ == 0 && m24_ == 0
546                 && m31_ == 0 && m32_ == 0 && m34_ == 0
547                 && m41_ == 0 && m42_ == 0 && m43_ == 0;
548     }
549 
550     /**
551      * Returns a new matrix being the result of the original matrix flipped about the x-axis.
552      * @return a new matrix being the result of the original matrix flipped about the x-axis.
553      *     This is equivalent to multiplying the matrix by DOMMatrix(-1, 0, 0, 1, 0, 0).
554      *     The original matrix is not modified.
555      */
556     @JsxFunction
557     public DOMMatrix flipX() {
558         final double[] values = getValues();
559         for (int i = 0; i < 4; i++) {
560             values[i] = -values[i];
561         }
562 
563         final DOMMatrix matrix = copyToDOMMatrix();
564         matrix.setValues(values, is2D_);
565         return matrix;
566     }
567 
568     /**
569      * Returns a new matrix being the result of the original matrix flipped about the y-axis.
570      * @return a new matrix being the result of the original matrix flipped about the y-axis.
571      *     This is equivalent to multiplying the matrix by DOMMatrix(1, 0, 0, -1, 0, 0).
572      *     The original matrix is not modified.
573      */
574     @JsxFunction
575     public DOMMatrix flipY() {
576         final double[] values = getValues();
577         for (int i = 4; i < 8; i++) {
578             values[i] = -values[i];
579         }
580 
581         final DOMMatrix matrix = copyToDOMMatrix();
582         matrix.setValues(values, is2D_);
583         return matrix;
584     }
585 
586     /**
587      * Returns a new matrix which is the inverse of the original matrix.
588      * @return new matrix which is the inverse of the original matrix.
589      *     If the matrix cannot be inverted, the new matrix's components are all set to NaN
590      *     and its is2D property is set to false. The original matrix is not changed.
591      */
592     @JsxFunction
593     public DOMMatrix inverse() {
594         final DOMMatrix matrix = copyToDOMMatrix();
595         matrix.invertSelfInternal();
596         return matrix;
597     }
598 
599     /**
600      * Returns a new matrix which is the dot product of the matrix and the given matrix.
601      * @param other the matrix to multiply with this matrix; this can be a matrix or an
602      *     object with matrix properties (DOMMatrixInit); {@code null} and {@code undefined}
603      *     are treated as identity matrix
604      * @return a new matrix which is the dot product of the matrix and the other matrix.
605      *     The original matrix is not modified.
606      */
607     @JsxFunction
608     public DOMMatrix multiply(final Object other) {
609         final DOMMatrixReadOnly otherMatrix = fromMatrixInitForMultiply(other, "multiply", getClassName());
610 
611         final DOMMatrix matrix = copyToDOMMatrix();
612         matrix.multiplySelfInternal(otherMatrix);
613         return matrix;
614     }
615 
616     /**
617      * Returns a new matrix rotated by the specified angles.
618      * If only one argument is given, this is the rotation angle around the z-axis
619      * (a 2D rotation), otherwise the matrix is rotated around the z-axis, then around
620      * the y-axis and finally around the x-axis.
621      *
622      * @param rotX the rotation angle around the x-axis in degrees (or the rotation angle
623      *     around the z-axis if this is the only argument)
624      * @param rotY the rotation angle around the y-axis in degrees
625      * @param rotZ the rotation angle around the z-axis in degrees
626      * @return a new matrix which is the result of the original matrix rotated
627      *     by the specified angles. The original matrix is not modified.
628      */
629     @JsxFunction
630     public DOMMatrix rotate(final Object rotX, final Object rotY, final Object rotZ) {
631         final DOMMatrix matrix = copyToDOMMatrix();
632         matrix.rotateSelfInternal(rotX, rotY, rotZ);
633         return matrix;
634     }
635 
636     /**
637      * Returns a new matrix rotated by the angle between the specified vector and (1, 0).
638      *
639      * @param x the x component of the vector
640      * @param y the y component of the vector
641      * @return a new matrix which is the result of the original matrix rotated
642      *     by the angle of the vector. The original matrix is not modified.
643      */
644     @JsxFunction
645     public DOMMatrix rotateFromVector(final Object x, final Object y) {
646         final DOMMatrix matrix = copyToDOMMatrix();
647         matrix.rotateFromVectorSelfInternal(toDouble(x, 0), toDouble(y, 0));
648         return matrix;
649     }
650 
651     /**
652      * Returns a new matrix rotated by a given angle around the specified axis.
653      *
654      * @param x the x component of the axis
655      * @param y the y component of the axis
656      * @param z the z component of the axis
657      * @param angle the rotation angle in degrees
658      * @return a new matrix which is the result of the original matrix rotated
659      *     around the axis. The original matrix is not modified.
660      */
661     @JsxFunction
662     public DOMMatrix rotateAxisAngle(final Object x, final Object y, final Object z, final Object angle) {
663         final DOMMatrix matrix = copyToDOMMatrix();
664         matrix.rotateAxisAngleSelfInternal(toDouble(x, 0), toDouble(y, 0), toDouble(z, 0), toDouble(angle, 0));
665         return matrix;
666     }
667 
668     /**
669      * Returns a new matrix scaled by the given factors, centered on the given origin.
670      *
671      * @param scaleX the scale factor for the x-axis (default 1)
672      * @param scaleY the scale factor for the y-axis (default scaleX)
673      * @param scaleZ the scale factor for the z-axis (default 1)
674      * @param originX the x-coordinate of the origin (default 0)
675      * @param originY the y-coordinate of the origin (default 0)
676      * @param originZ the z-coordinate of the origin (default 0)
677      * @return a new matrix which is the result of the original matrix scaled.
678      *     The original matrix is not modified.
679      */
680     @JsxFunction
681     public DOMMatrix scale(final Object scaleX, final Object scaleY, final Object scaleZ,
682                 final Object originX, final Object originY, final Object originZ) {
683         final DOMMatrix matrix = copyToDOMMatrix();
684         final double sx = toDouble(scaleX, 1);
685         matrix.scaleSelfInternal(sx, toDouble(scaleY, sx), toDouble(scaleZ, 1),
686                 toDouble(originX, 0), toDouble(originY, 0), toDouble(originZ, 0));
687         return matrix;
688     }
689 
690     /**
691      * Returns a new matrix scaled by the given factor for all three axes,
692      * centered on the given origin.
693      *
694      * @param scale the scale factor (default 1)
695      * @param originX the x-coordinate of the origin (default 0)
696      * @param originY the y-coordinate of the origin (default 0)
697      * @param originZ the z-coordinate of the origin (default 0)
698      * @return a new matrix which is the result of the original matrix scaled.
699      *     The original matrix is not modified.
700      */
701     @JsxFunction
702     public DOMMatrix scale3d(final Object scale, final Object originX, final Object originY, final Object originZ) {
703         final DOMMatrix matrix = copyToDOMMatrix();
704         matrix.scale3dSelfInternal(toDouble(scale, 1),
705                 toDouble(originX, 0), toDouble(originY, 0), toDouble(originZ, 0));
706         return matrix;
707     }
708 
709     /**
710      * Returns a new matrix scaled by the given factors for the x- and the y-axis.
711      * This method is deprecated; use {@link #scale(Object, Object, Object, Object, Object, Object)}.
712      *
713      * @param scaleX the scale factor for the x-axis (default 1)
714      * @param scaleY the scale factor for the y-axis (default 1)
715      * @return a new matrix which is the result of the original matrix scaled.
716      *     The original matrix is not modified.
717      */
718     @JsxFunction
719     public DOMMatrix scaleNonUniform(final Object scaleX, final Object scaleY) {
720         final DOMMatrix matrix = copyToDOMMatrix();
721         matrix.scaleSelfInternal(toDouble(scaleX, 1), toDouble(scaleY, 1), 1, 0, 0, 0);
722         return matrix;
723     }
724 
725     /**
726      * Returns a new matrix skewed along the x-axis by the specified angle.
727      * @param sx the angle, in degrees, by which to skew the matrix along the x-axis
728      * @return returns a new DOMMatrix created by applying the specified skew transformation
729      *     to the source matrix along its x-axis. The original matrix is not modified.
730      */
731     @JsxFunction
732     public DOMMatrix skewX(final Object sx) {
733         final DOMMatrix matrix = copyToDOMMatrix();
734         matrix.skewXSelfInternal(toDouble(sx, 0));
735         return matrix;
736     }
737 
738     /**
739      * Returns a new matrix skewed along the y-axis by the specified angle.
740      * @param sy the angle, in degrees, by which to skew the matrix along the y-axis
741      * @return returns a new DOMMatrix created by applying the specified skew transformation
742      *     to the source matrix along its y-axis. The original matrix is not modified.
743      */
744     @JsxFunction
745     public DOMMatrix skewY(final Object sy) {
746         final DOMMatrix matrix = copyToDOMMatrix();
747         matrix.skewYSelfInternal(toDouble(sy, 0));
748         return matrix;
749     }
750 
751     /**
752      * Creates a new matrix being the result of the original matrix with a translation applied.
753      *
754      * @param tx the x component of the translating vector (default 0)
755      * @param ty the y component of the translating vector (default 0)
756      * @param tz the z component of the translating vector (default 0); if this is anything other
757      *     than 0, the resulting matrix will be 3D
758      * @return a new matrix being the result of the matrix being translated
759      *         by the given vector. The original matrix is not modified.
760      */
761     @JsxFunction
762     public DOMMatrix translate(final Object tx, final Object ty, final Object tz) {
763         final DOMMatrix matrix = copyToDOMMatrix();
764         matrix.translateSelfInternal(toDouble(tx, 0), toDouble(ty, 0), toDouble(tz, 0));
765         return matrix;
766     }
767 
768     /**
769      * Transforms the given point with this matrix.
770      *
771      * @param point the point to transform; this can be a point or an object with point
772      *     properties (DOMPointInit: x, y, z (default 0) and w (default 1));
773      *     {@code null} and {@code undefined} are treated as the point (0, 0, 0, 1)
774      * @return a new {@link DOMPoint} with the transformed coordinates
775      */
776     @JsxFunction
777     public DOMPoint transformPoint(final Object point) {
778         double x = 0;
779         double y = 0;
780         double z = 0;
781         double w = 1;
782         if (point != null && !JavaScriptEngine.isUndefined(point)) {
783             if (!(point instanceof Scriptable pointScriptable)) {
784                 throw JavaScriptEngine.typeError("Failed to execute 'transformPoint' on '" + getClassName()
785                         + "': The provided value is not of type 'DOMPointInit'.");
786             }
787             x = getDictionaryValue(pointScriptable, "x", 0);
788             y = getDictionaryValue(pointScriptable, "y", 0);
789             z = getDictionaryValue(pointScriptable, "z", 0);
790             w = getDictionaryValue(pointScriptable, "w", 1);
791         }
792 
793         final DOMPoint result = new DOMPoint(
794                 mul(m11_, x) + mul(m21_, y) + mul(m31_, z) + mul(m41_, w),
795                 mul(m12_, x) + mul(m22_, y) + mul(m32_, z) + mul(m42_, w),
796                 mul(m13_, x) + mul(m23_, y) + mul(m33_, z) + mul(m43_, w),
797                 mul(m14_, x) + mul(m24_, y) + mul(m34_, z) + mul(m44_, w));
798         result.setParentScope(getParentScope());
799         result.setPrototype(ScriptableObject.getClassPrototype(getParentScope(), "DOMPoint"));
800         return result;
801     }
802 
803     // ---------------------------------------------------------------------------------
804     // the operations; all of them are modifying this matrix (the *Self functions
805     // of DOMMatrix); the functions above are working on a copy
806 
807     /**
808      * Post-multiplies this matrix with the given one (this = this * other).
809      * The result is 2D if both matrices are 2D.
810      *
811      * @param other the matrix to multiply with
812      */
813     protected void multiplySelfInternal(final DOMMatrixReadOnly other) {
814         final boolean is2D = is2D_ && other.is2D_;
815         setValues(multiplyMatrices(getValues(), other.getValues(), is2D), is2D);
816     }
817 
818     /**
819      * Pre-multiplies this matrix with the given one (this = other * this).
820      * The result is 2D if both matrices are 2D.
821      *
822      * @param other the matrix to multiply with
823      */
824     protected void preMultiplySelfInternal(final DOMMatrixReadOnly other) {
825         final boolean is2D = is2D_ && other.is2D_;
826         setValues(multiplyMatrices(other.getValues(), getValues(), is2D), is2D);
827     }
828 
829     /**
830      * Applies a translation to this matrix.
831      *
832      * @param tx the x component of the translating vector
833      * @param ty the y component of the translating vector
834      * @param tz the z component of the translating vector
835      */
836     protected void translateSelfInternal(final double tx, final double ty, final double tz) {
837         final DOMMatrixReadOnly translation = new DOMMatrixReadOnly();
838         translation.m41_ = tx;
839         translation.m42_ = ty;
840         translation.m43_ = tz;
841         translation.is2D_ = tz == 0;
842 
843         multiplySelfInternal(translation);
844     }
845 
846     /**
847      * Applies a scaling centered on the given origin to this matrix.
848      *
849      * @param scaleX the scale factor for the x-axis
850      * @param scaleY the scale factor for the y-axis
851      * @param scaleZ the scale factor for the z-axis
852      * @param originX the x-coordinate of the origin
853      * @param originY the y-coordinate of the origin
854      * @param originZ the z-coordinate of the origin
855      */
856     protected void scaleSelfInternal(final double scaleX, final double scaleY, final double scaleZ,
857                 final double originX, final double originY, final double originZ) {
858         translateSelfInternal(originX, originY, originZ);
859 
860         final DOMMatrixReadOnly scale = new DOMMatrixReadOnly();
861         scale.m11_ = scaleX;
862         scale.m22_ = scaleY;
863         scale.m33_ = scaleZ;
864         scale.is2D_ = scaleZ == 1;
865         multiplySelfInternal(scale);
866 
867         translateSelfInternal(-originX, -originY, -originZ);
868 
869         if (scaleZ != 1 || originZ != 0) {
870             is2D_ = false;
871         }
872     }
873 
874     /**
875      * Applies a uniform scaling of all three axes centered on the given origin to this matrix.
876      *
877      * @param scale the scale factor
878      * @param originX the x-coordinate of the origin
879      * @param originY the y-coordinate of the origin
880      * @param originZ the z-coordinate of the origin
881      */
882     protected void scale3dSelfInternal(final double scale,
883                 final double originX, final double originY, final double originZ) {
884         scaleSelfInternal(scale, scale, scale, originX, originY, originZ);
885         if (scale != 1) {
886             is2D_ = false;
887         }
888     }
889 
890     /**
891      * Applies the rotation of {@link #rotate(Object, Object, Object)} to this matrix.
892      *
893      * @param rotXObj the rotation angle around the x-axis in degrees (or the rotation angle
894      *     around the z-axis if this is the only argument)
895      * @param rotYObj the rotation angle around the y-axis in degrees
896      * @param rotZObj the rotation angle around the z-axis in degrees
897      */
898     protected void rotateSelfInternal(final Object rotXObj, final Object rotYObj, final Object rotZObj) {
899         double rotX = toDouble(rotXObj, 0);
900         double rotY = toDouble(rotYObj, 0);
901         double rotZ = toDouble(rotZObj, 0);
902 
903         if (isMissing(rotYObj) && isMissing(rotZObj)) {
904             rotZ = rotX;
905             rotX = 0;
906             rotY = 0;
907         }
908 
909         rotateSelfInternal(rotX, rotY, rotZ);
910     }
911 
912     /**
913      * Rotates this matrix around the z-axis, then around the y-axis and
914      * finally around the x-axis.
915      *
916      * @param rotX the rotation angle around the x-axis in degrees
917      * @param rotY the rotation angle around the y-axis in degrees
918      * @param rotZ the rotation angle around the z-axis in degrees
919      */
920     protected void rotateSelfInternal(final double rotX, final double rotY, final double rotZ) {
921         final boolean is2D = is2D_ && rotX == 0 && rotY == 0;
922 
923         multiplySelfInternal(createRotation(0, 0, 1, rotZ));
924         if (rotY != 0) {
925             multiplySelfInternal(createRotation(0, 1, 0, rotY));
926         }
927         if (rotX != 0) {
928             multiplySelfInternal(createRotation(1, 0, 0, rotX));
929         }
930         is2D_ = is2D;
931     }
932 
933     /**
934      * Rotates this matrix by the angle between the specified vector and (1, 0).
935      *
936      * @param x the x component of the vector
937      * @param y the y component of the vector
938      */
939     protected void rotateFromVectorSelfInternal(final double x, final double y) {
940         double angle = 0;
941         if (x != 0 || y != 0) {
942             angle = Math.toDegrees(Math.atan2(y, x));
943         }
944         multiplySelfInternal(createRotation(0, 0, 1, angle));
945     }
946 
947     /**
948      * Rotates this matrix by the given angle around the specified axis.
949      * An axis of (0, 0, 0) does not change the matrix.
950      *
951      * @param x the x component of the axis
952      * @param y the y component of the axis
953      * @param z the z component of the axis
954      * @param angle the rotation angle in degrees
955      */
956     protected void rotateAxisAngleSelfInternal(final double x, final double y, final double z, final double angle) {
957         final boolean is2D = is2D_ && x == 0 && y == 0;
958         if (x != 0 || y != 0 || z != 0) {
959             multiplySelfInternal(createRotation(x, y, z, angle));
960         }
961         is2D_ = is2D;
962     }
963 
964     /**
965      * Skews this matrix along the x-axis.
966      *
967      * @param sx the angle in degrees
968      */
969     protected void skewXSelfInternal(final double sx) {
970         final DOMMatrixReadOnly skew = new DOMMatrixReadOnly();
971         skew.m21_ = Math.tan(Math.toRadians(sx));
972         multiplySelfInternal(skew);
973     }
974 
975     /**
976      * Skews this matrix along the y-axis.
977      *
978      * @param sy the angle in degrees
979      */
980     protected void skewYSelfInternal(final double sy) {
981         final DOMMatrixReadOnly skew = new DOMMatrixReadOnly();
982         skew.m12_ = Math.tan(Math.toRadians(sy));
983         multiplySelfInternal(skew);
984     }
985 
986     /**
987      * Inverts this matrix. If the matrix cannot be inverted, all values are set
988      * to NaN and the matrix is no longer 2D.
989      */
990     protected void invertSelfInternal() {
991         if (is2D_) {
992             final double det = m11_ * m22_ - m12_ * m21_;
993             if (det == 0) {
994                 setAllNaN();
995                 return;
996             }
997 
998             final double a = m22_ / det;
999             final double b = -m12_ / det;
1000             final double c = -m21_ / det;
1001             final double d = m11_ / det;
1002             final double e = (m21_ * m42_ - m22_ * m41_) / det;
1003             final double f = (m12_ * m41_ - m11_ * m42_) / det;
1004             setValues2D(a, b, c, d, e, f);
1005             return;
1006         }
1007 
1008         final double[] m = getValues();
1009         final double[] inv = new double[16];
1010         inv[0] = m[5] * m[10] * m[15] - m[5] * m[11] * m[14] - m[9] * m[6] * m[15]
1011                 + m[9] * m[7] * m[14] + m[13] * m[6] * m[11] - m[13] * m[7] * m[10];
1012         inv[4] = -m[4] * m[10] * m[15] + m[4] * m[11] * m[14] + m[8] * m[6] * m[15]
1013                 - m[8] * m[7] * m[14] - m[12] * m[6] * m[11] + m[12] * m[7] * m[10];
1014         inv[8] = m[4] * m[9] * m[15] - m[4] * m[11] * m[13] - m[8] * m[5] * m[15]
1015                 + m[8] * m[7] * m[13] + m[12] * m[5] * m[11] - m[12] * m[7] * m[9];
1016         inv[12] = -m[4] * m[9] * m[14] + m[4] * m[10] * m[13] + m[8] * m[5] * m[14]
1017                 - m[8] * m[6] * m[13] - m[12] * m[5] * m[10] + m[12] * m[6] * m[9];
1018         inv[1] = -m[1] * m[10] * m[15] + m[1] * m[11] * m[14] + m[9] * m[2] * m[15]
1019                 - m[9] * m[3] * m[14] - m[13] * m[2] * m[11] + m[13] * m[3] * m[10];
1020         inv[5] = m[0] * m[10] * m[15] - m[0] * m[11] * m[14] - m[8] * m[2] * m[15]
1021                 + m[8] * m[3] * m[14] + m[12] * m[2] * m[11] - m[12] * m[3] * m[10];
1022         inv[9] = -m[0] * m[9] * m[15] + m[0] * m[11] * m[13] + m[8] * m[1] * m[15]
1023                 - m[8] * m[3] * m[13] - m[12] * m[1] * m[11] + m[12] * m[3] * m[9];
1024         inv[13] = m[0] * m[9] * m[14] - m[0] * m[10] * m[13] - m[8] * m[1] * m[14]
1025                 + m[8] * m[2] * m[13] + m[12] * m[1] * m[10] - m[12] * m[2] * m[9];
1026         inv[2] = m[1] * m[6] * m[15] - m[1] * m[7] * m[14] - m[5] * m[2] * m[15]
1027                 + m[5] * m[3] * m[14] + m[13] * m[2] * m[7] - m[13] * m[3] * m[6];
1028         inv[6] = -m[0] * m[6] * m[15] + m[0] * m[7] * m[14] + m[4] * m[2] * m[15]
1029                 - m[4] * m[3] * m[14] - m[12] * m[2] * m[7] + m[12] * m[3] * m[6];
1030         inv[10] = m[0] * m[5] * m[15] - m[0] * m[7] * m[13] - m[4] * m[1] * m[15]
1031                 + m[4] * m[3] * m[13] + m[12] * m[1] * m[7] - m[12] * m[3] * m[5];
1032         inv[14] = -m[0] * m[5] * m[14] + m[0] * m[6] * m[13] + m[4] * m[1] * m[14]
1033                 - m[4] * m[2] * m[13] - m[12] * m[1] * m[6] + m[12] * m[2] * m[5];
1034         inv[3] = -m[1] * m[6] * m[11] + m[1] * m[7] * m[10] + m[5] * m[2] * m[11]
1035                 - m[5] * m[3] * m[10] - m[9] * m[2] * m[7] + m[9] * m[3] * m[6];
1036         inv[7] = m[0] * m[6] * m[11] - m[0] * m[7] * m[10] - m[4] * m[2] * m[11]
1037                 + m[4] * m[3] * m[10] + m[8] * m[2] * m[7] - m[8] * m[3] * m[6];
1038         inv[11] = -m[0] * m[5] * m[11] + m[0] * m[7] * m[9] + m[4] * m[1] * m[11]
1039                 - m[4] * m[3] * m[9] - m[8] * m[1] * m[7] + m[8] * m[3] * m[5];
1040         inv[15] = m[0] * m[5] * m[10] - m[0] * m[6] * m[9] - m[4] * m[1] * m[10]
1041                 + m[4] * m[2] * m[9] + m[8] * m[1] * m[6] - m[8] * m[2] * m[5];
1042 
1043         final double det = m[0] * inv[0] + m[1] * inv[4] + m[2] * inv[8] + m[3] * inv[12];
1044         if (det == 0) {
1045             setAllNaN();
1046             return;
1047         }
1048 
1049         final double invDet = 1.0 / det;
1050         for (int i = 0; i < inv.length; i++) {
1051             inv[i] = inv[i] * invDet;
1052         }
1053         setValues(inv, false);
1054     }
1055 
1056     private void setAllNaN() {
1057         final double[] values = new double[16];
1058         Arrays.fill(values, Double.NaN);
1059         setValues(values, false);
1060     }
1061 
1062     // ---------------------------------------------------------------------------------
1063     // helpers
1064 
1065     /**
1066      * Creates a new {@link DOMMatrix} with the values of this matrix.
1067      * @return the new matrix
1068      */
1069     protected DOMMatrix copyToDOMMatrix() {
1070         final DOMMatrix matrix = new DOMMatrix();
1071         matrix.setParentScope(getParentScope());
1072         matrix.setPrototype(ScriptableObject.getClassPrototype(getParentScope(), "DOMMatrix"));
1073         matrix.setValues(getValues(), is2D_);
1074         return matrix;
1075     }
1076 
1077     /**
1078      * Returns the values of this matrix in column-major order
1079      * (m11, m12, m13, m14, m21, ..., m44).
1080      * @return a new array with the 16 values
1081      */
1082     protected double[] getValues() {
1083         return new double[] {
1084             m11_, m12_, m13_, m14_,
1085             m21_, m22_, m23_, m24_,
1086             m31_, m32_, m33_, m34_,
1087             m41_, m42_, m43_, m44_
1088         };
1089     }
1090 
1091     /**
1092      * Sets all values of this matrix.
1093      * @param values the 16 values in column-major order (m11, m12, m13, m14, m21, ..., m44)
1094      * @param is2D the new value of the is2D flag
1095      */
1096     protected void setValues(final double[] values, final boolean is2D) {
1097         m11_ = values[0];
1098         m12_ = values[1];
1099         m13_ = values[2];
1100         m14_ = values[3];
1101 
1102         m21_ = values[4];
1103         m22_ = values[5];
1104         m23_ = values[6];
1105         m24_ = values[7];
1106 
1107         m31_ = values[8];
1108         m32_ = values[9];
1109         m33_ = values[10];
1110         m34_ = values[11];
1111 
1112         m41_ = values[12];
1113         m42_ = values[13];
1114         m43_ = values[14];
1115         m44_ = values[15];
1116 
1117         is2D_ = is2D;
1118     }
1119 
1120     /**
1121      * Sets this to the 2D matrix [a, b, c, d, e, f]; all other values are set to the
1122      * values of the identity matrix.
1123      *
1124      * @param a the a (m11) value
1125      * @param b the b (m12) value
1126      * @param c the c (m21) value
1127      * @param d the d (m22) value
1128      * @param e the e (m41) value
1129      * @param f the f (m42) value
1130      */
1131     protected void setValues2D(final double a, final double b, final double c,
1132                 final double d, final double e, final double f) {
1133         setValues(new double[] {a, b, 0, 0, c, d, 0, 0, 0, 0, 1, 0, e, f, 0, 1}, true);
1134     }
1135 
1136     /**
1137      * Multiplies the two given matrices (left * right); both are in column-major order.
1138      *
1139      * <p>Like in the browsers, the product of two 2D matrices only calculates the 2D values
1140      * (a, b, c, d, e, f); the other values are not touched (and therefore never polluted
1141      * by NaN or infinite values).
1142      * A value of exactly 0 of the right matrix (the transformation applied) never contributes
1143      * to the result, a value of 0 of the left matrix does (0 * NaN is NaN).</p>
1144      *
1145      * @param left the left matrix
1146      * @param right the right matrix
1147      * @param only2D whether to calculate only the 2D values
1148      * @return the product
1149      */
1150     private static double[] multiplyMatrices(final double[] left, final double[] right, final boolean only2D) {
1151         if (only2D) {
1152             final double[] result = left.clone();
1153             for (final int col : new int[] {0, 1, 3}) {
1154                 for (int row = 0; row < 2; row++) {
1155                     double sum = term(left[row], right[col * 4]) + term(left[4 + row], right[col * 4 + 1]);
1156                     if (col == 3) {
1157                         sum += left[12 + row];
1158                     }
1159                     result[col * 4 + row] = sum;
1160                 }
1161             }
1162             return result;
1163         }
1164 
1165         final double[] result = new double[16];
1166         for (int col = 0; col < 4; col++) {
1167             for (int row = 0; row < 4; row++) {
1168                 double sum = 0;
1169                 for (int k = 0; k < 4; k++) {
1170                     sum += term(left[k * 4 + row], right[col * 4 + k]);
1171                 }
1172                 result[col * 4 + row] = sum;
1173             }
1174         }
1175         return result;
1176     }
1177 
1178     private static double term(final double left, final double right) {
1179         if (right == 0) {
1180             return 0;
1181         }
1182         return left * right;
1183     }
1184 
1185     private static double mul(final double x, final double y) {
1186         if (x == 0 || y == 0) {
1187             return 0;
1188         }
1189         return x * y;
1190     }
1191 
1192     /**
1193      * Creates the matrix of a rotation by the given angle around the given axis
1194      * (see CSS rotate3d()). A rotation around the z-axis is a 2D matrix. For rotations
1195      * around one of the axes, multiples of 90 degrees result in exact values.
1196      *
1197      * @param x the x component of the axis
1198      * @param y the y component of the axis
1199      * @param z the z component of the axis
1200      * @param angle the angle in degrees
1201      * @return the rotation matrix
1202      */
1203     static DOMMatrixReadOnly createRotation(final double x, final double y, final double z, final double angle) {
1204         final DOMMatrixReadOnly rotation = new DOMMatrixReadOnly();
1205 
1206         if (x == 0 && y == 0) {
1207             // around the z-axis; this is 2D
1208             final double[] sinCos = sinCosDegrees(z < 0 ? -angle : angle);
1209             rotation.m11_ = sinCos[1];
1210             rotation.m12_ = sinCos[0];
1211             rotation.m21_ = -sinCos[0];
1212             rotation.m22_ = sinCos[1];
1213             return rotation;
1214         }
1215 
1216         if (y == 0 && z == 0) {
1217             // around the x-axis
1218             final double[] sinCos = sinCosDegrees(x < 0 ? -angle : angle);
1219             rotation.m22_ = sinCos[1];
1220             rotation.m23_ = sinCos[0];
1221             rotation.m32_ = -sinCos[0];
1222             rotation.m33_ = sinCos[1];
1223             rotation.is2D_ = false;
1224             return rotation;
1225         }
1226 
1227         if (x == 0 && z == 0) {
1228             // around the y-axis
1229             final double[] sinCos = sinCosDegrees(y < 0 ? -angle : angle);
1230             rotation.m11_ = sinCos[1];
1231             rotation.m13_ = -sinCos[0];
1232             rotation.m31_ = sinCos[0];
1233             rotation.m33_ = sinCos[1];
1234             rotation.is2D_ = false;
1235             return rotation;
1236         }
1237 
1238         final double length = Math.sqrt(x * x + y * y + z * z);
1239         final double nx = x / length;
1240         final double ny = y / length;
1241         final double nz = z / length;
1242 
1243         final double halfAngle = Math.toRadians(angle) / 2;
1244         final double sc = Math.sin(halfAngle) * Math.cos(halfAngle);
1245         final double sq = Math.sin(halfAngle) * Math.sin(halfAngle);
1246 
1247         rotation.m11_ = 1 - 2 * mul(ny * ny + nz * nz, sq);
1248         rotation.m12_ = 2 * (mul(nx * ny, sq) + mul(nz, sc));
1249         rotation.m13_ = 2 * (mul(nx * nz, sq) - mul(ny, sc));
1250 
1251         rotation.m21_ = 2 * (mul(nx * ny, sq) - mul(nz, sc));
1252         rotation.m22_ = 1 - 2 * mul(nx * nx + nz * nz, sq);
1253         rotation.m23_ = 2 * (mul(ny * nz, sq) + mul(nx, sc));
1254 
1255         rotation.m31_ = 2 * (mul(nx * nz, sq) + mul(ny, sc));
1256         rotation.m32_ = 2 * (mul(ny * nz, sq) - mul(nx, sc));
1257         rotation.m33_ = 1 - 2 * mul(nx * nx + ny * ny, sq);
1258 
1259         rotation.is2D_ = false;
1260         return rotation;
1261     }
1262 
1263     /**
1264      * Returns the sine and the cosine of the given angle; multiples of 90 degrees
1265      * are returned as exact values.
1266      *
1267      * @param angle the angle in degrees
1268      * @return an array with the sine and the cosine
1269      */
1270     private static double[] sinCosDegrees(final double angle) {
1271         if (Double.isFinite(angle) && angle % 90 == 0) {
1272             final int quarter = (int) (((angle / 90) % 4 + 4) % 4);
1273             return switch (quarter) {
1274                 case 1 -> new double[] {1, 0};
1275                 case 2 -> new double[] {0, -1};
1276                 case 3 -> new double[] {-1, 0};
1277                 default -> new double[] {0, 1};
1278             };
1279         }
1280 
1281         final double radians = Math.toRadians(angle);
1282         return new double[] {Math.sin(radians), Math.cos(radians)};
1283     }
1284 
1285     /**
1286      * Converts the given JavaScript value into a double; {@code undefined}
1287      * (or a missing argument) is converted to the given default value.
1288      *
1289      * @param value the value
1290      * @param defaultValue the default value
1291      * @return the double value
1292      */
1293     protected static double toDouble(final Object value, final double defaultValue) {
1294         if (isMissing(value)) {
1295             return defaultValue;
1296         }
1297         return JavaScriptEngine.toNumber(value);
1298     }
1299 
1300     private static boolean isMissing(final Object value) {
1301         return value == null || JavaScriptEngine.isUndefined(value);
1302     }
1303 
1304     private static double getDictionaryValue(final Scriptable dictionary, final String name,
1305                 final double defaultValue) {
1306         final Object value = ScriptableObject.getProperty(dictionary, name);
1307         if (value == Scriptable.NOT_FOUND || JavaScriptEngine.isUndefined(value)) {
1308             return defaultValue;
1309         }
1310         return JavaScriptEngine.toNumber(value);
1311     }
1312 
1313     /**
1314      * Converts the given value into a matrix following the rules of the
1315      * DOMMatrixInit dictionary (including the 'validate and fixup' steps).
1316      *
1317      * @param init the value to convert; a matrix, an object with matrix properties,
1318      *     {@code null} or {@code undefined} (the identity matrix)
1319      * @param methodName the name of the calling method for the error message
1320      * @param className the name of the calling class for the error message
1321      * @return a new matrix (without scope)
1322      */
1323     static DOMMatrixReadOnly fromMatrixInit(final Object init, final String methodName, final String className) {
1324         final DOMMatrixReadOnly result = new DOMMatrixReadOnly();
1325         if (isMissing(init)) {
1326             return result;
1327         }
1328 
1329         if (init instanceof DOMMatrixReadOnly matrix) {
1330             result.setValues(matrix.getValues(), matrix.is2D_);
1331             return result;
1332         }
1333 
1334         final String errorPrefix = "Failed to execute '" + methodName + "' on '" + className + "': ";
1335         if (!(init instanceof Scriptable dict)) {
1336             throw JavaScriptEngine.typeError(errorPrefix + "The provided value is not of type 'DOMMatrixInit'.");
1337         }
1338 
1339         // validate and fixup (2D)
1340         final double m11 = fixup(dict, "a", "m11", 1, errorPrefix);
1341         final double m12 = fixup(dict, "b", "m12", 0, errorPrefix);
1342         final double m21 = fixup(dict, "c", "m21", 0, errorPrefix);
1343         final double m22 = fixup(dict, "d", "m22", 1, errorPrefix);
1344         final double m41 = fixup(dict, "e", "m41", 0, errorPrefix);
1345         final double m42 = fixup(dict, "f", "m42", 0, errorPrefix);
1346 
1347         // validate and fixup (3D)
1348         final double m13 = getDictionaryValue(dict, "m13", 0);
1349         final double m14 = getDictionaryValue(dict, "m14", 0);
1350         final double m23 = getDictionaryValue(dict, "m23", 0);
1351         final double m24 = getDictionaryValue(dict, "m24", 0);
1352         final double m31 = getDictionaryValue(dict, "m31", 0);
1353         final double m32 = getDictionaryValue(dict, "m32", 0);
1354         final double m33 = getDictionaryValue(dict, "m33", 1);
1355         final double m34 = getDictionaryValue(dict, "m34", 0);
1356         final double m43 = getDictionaryValue(dict, "m43", 0);
1357         final double m44 = getDictionaryValue(dict, "m44", 1);
1358 
1359         final boolean only2DValues = m13 == 0 && m14 == 0 && m23 == 0 && m24 == 0
1360                 && m31 == 0 && m32 == 0 && m34 == 0 && m43 == 0
1361                 && m33 == 1 && m44 == 1;
1362 
1363         final Object is2DValue = ScriptableObject.getProperty(dict, "is2D");
1364         final boolean is2D;
1365         if (is2DValue == Scriptable.NOT_FOUND || JavaScriptEngine.isUndefined(is2DValue)) {
1366             is2D = only2DValues;
1367         }
1368         else {
1369             is2D = JavaScriptEngine.toBoolean(is2DValue);
1370             if (is2D && !only2DValues) {
1371                 throw JavaScriptEngine.typeError(errorPrefix
1372                         + "The 'is2D' property is true, but the matrix contains 3D values.");
1373             }
1374         }
1375 
1376         result.setValues(new double[] {
1377             m11, m12, m13, m14,
1378             m21, m22, m23, m24,
1379             m31, m32, m33, m34,
1380             m41, m42, m43, m44}, is2D);
1381         return result;
1382     }
1383 
1384     /**
1385      * Like {@link #fromMatrixInit(Object, String, String)}, but for the multiply functions;
1386      * for an object with matrix properties (not a matrix), the browsers ignore an
1387      * {@code is2D} property with the value {@code false}; only the values decide.
1388      *
1389      * @param init the value to convert
1390      * @param methodName the name of the calling method for the error message
1391      * @param className the name of the calling class for the error message
1392      * @return a new matrix (without scope)
1393      */
1394     static DOMMatrixReadOnly fromMatrixInitForMultiply(final Object init, final String methodName,
1395             final String className) {
1396         final DOMMatrixReadOnly result = fromMatrixInit(init, methodName, className);
1397         if (!(init instanceof DOMMatrixReadOnly)) {
1398             result.is2D_ = result.hasOnly2DValues();
1399         }
1400         return result;
1401     }
1402 
1403     /**
1404      * Returns whether this matrix contains only 2D values (m13, m14, m23, m24, m31, m32,
1405      * m34 and m43 are 0, m33 and m44 are 1).
1406      * @return true if the values are 2D values
1407      */
1408     boolean hasOnly2DValues() {
1409         return m13_ == 0 && m14_ == 0 && m23_ == 0 && m24_ == 0
1410                 && m31_ == 0 && m32_ == 0 && m34_ == 0 && m43_ == 0
1411                 && m33_ == 1 && m44_ == 1;
1412     }
1413 
1414     private static double fixup(final Scriptable dict, final String shortName, final String longName,
1415                 final double defaultValue, final String errorPrefix) {
1416         final Object shortValue = ScriptableObject.getProperty(dict, shortName);
1417         final Object longValue = ScriptableObject.getProperty(dict, longName);
1418 
1419         final boolean hasShort = shortValue != Scriptable.NOT_FOUND && !JavaScriptEngine.isUndefined(shortValue);
1420         final boolean hasLong = longValue != Scriptable.NOT_FOUND && !JavaScriptEngine.isUndefined(longValue);
1421 
1422         if (hasLong) {
1423             final double value = JavaScriptEngine.toNumber(longValue);
1424             if (hasShort) {
1425                 final double shortNumber = JavaScriptEngine.toNumber(shortValue);
1426                 // SameValueZero
1427                 final boolean same = value == shortNumber || (Double.isNaN(value) && Double.isNaN(shortNumber));
1428                 if (!same) {
1429                     throw JavaScriptEngine.typeError(errorPrefix + "The '" + shortName + "' property should equal "
1430                             + "the '" + longName + "' property.");
1431                 }
1432             }
1433             return value;
1434         }
1435         if (hasShort) {
1436             return JavaScriptEngine.toNumber(shortValue);
1437         }
1438         return defaultValue;
1439     }
1440 
1441     /**
1442      * Returns a new Float32Array containing all 16 elements of the matrix.
1443      * @return a new Float32Array containing all 16 elements
1444      *     (m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44)
1445      *     which comprise the matrix. The elements are stored into the array
1446      *     as single-precision floating-point numbers in column-major (colexographical access, or "colex") order.
1447      *     (In other words, down the first column from top to bottom, then the second column, and so forth.)
1448      */
1449     @JsxFunction
1450     public NativeFloat32Array toFloat32Array() {
1451         final NativeFloat32Array result =
1452                 (NativeFloat32Array) JavaScriptEngine.newObject(getParentScope(), "Float32Array", new Object[] {16});
1453 
1454         result.setArrayElement(0, m11_);
1455         result.setArrayElement(1, m12_);
1456         result.setArrayElement(2, m13_);
1457         result.setArrayElement(3, m14_);
1458 
1459         result.setArrayElement(4, m21_);
1460         result.setArrayElement(5, m22_);
1461         result.setArrayElement(6, m23_);
1462         result.setArrayElement(7, m24_);
1463 
1464         result.setArrayElement(8, m31_);
1465         result.setArrayElement(9, m32_);
1466         result.setArrayElement(10, m33_);
1467         result.setArrayElement(11, m34_);
1468 
1469         result.setArrayElement(12, m41_);
1470         result.setArrayElement(13, m42_);
1471         result.setArrayElement(14, m43_);
1472         result.setArrayElement(15, m44_);
1473 
1474         return result;
1475     }
1476 
1477     /**
1478      * Returns a new Float64Array containing all 16 elements of the matrix.
1479      * @return a new Float64Array containing all 16 elements
1480      *     (m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44)
1481      *     which comprise the matrix. The elements are stored into the array
1482      *     as single-precision floating-point numbers in column-major (colexographical access, or "colex") order.
1483      *     (In other words, down the first column from top to bottom, then the second column, and so forth.)
1484      */
1485     @JsxFunction
1486     public NativeFloat64Array toFloat64Array() {
1487         final NativeFloat64Array result =
1488                 (NativeFloat64Array) JavaScriptEngine.newObject(getParentScope(), "Float64Array", new Object[] {16});
1489 
1490         result.setArrayElement(0, m11_);
1491         result.setArrayElement(1, m12_);
1492         result.setArrayElement(2, m13_);
1493         result.setArrayElement(3, m14_);
1494 
1495         result.setArrayElement(4, m21_);
1496         result.setArrayElement(5, m22_);
1497         result.setArrayElement(6, m23_);
1498         result.setArrayElement(7, m24_);
1499 
1500         result.setArrayElement(8, m31_);
1501         result.setArrayElement(9, m32_);
1502         result.setArrayElement(10, m33_);
1503         result.setArrayElement(11, m34_);
1504 
1505         result.setArrayElement(12, m41_);
1506         result.setArrayElement(13, m42_);
1507         result.setArrayElement(14, m43_);
1508         result.setArrayElement(15, m44_);
1509 
1510         return result;
1511     }
1512 
1513     /**
1514      * Returns the values of the matrix as a CSS transform function string.
1515      * @return the values of the list separated by commas,
1516      *     within matrix() or matrix3d() function syntax.
1517      */
1518     @JsxFunction(functionName = "toString")
1519     public String js_toString() {
1520         final StringBuilder result = new StringBuilder();
1521 
1522         result.append(is2D_ ? "matrix(" : "matrix3d(");
1523         appendDouble(result, m11_).append(", ");
1524         appendDouble(result, m12_).append(", ");
1525         if (!is2D_) {
1526             appendDouble(result, m13_).append(", ");
1527             appendDouble(result, m14_).append(", ");
1528         }
1529 
1530         appendDouble(result, m21_).append(", ");
1531         appendDouble(result, m22_).append(", ");
1532         if (!is2D_) {
1533             appendDouble(result, m23_).append(", ");
1534             appendDouble(result, m24_).append(", ");
1535 
1536             appendDouble(result, m31_).append(", ");
1537             appendDouble(result, m32_).append(", ");
1538             appendDouble(result, m33_).append(", ");
1539             appendDouble(result, m34_).append(", ");
1540         }
1541 
1542         appendDouble(result, m41_).append(", ");
1543         appendDouble(result, m42_);
1544         if (!is2D_) {
1545             result.append(", ");
1546             appendDouble(result, m43_).append(", ");
1547             appendDouble(result, m44_);
1548         }
1549 
1550         result.append(')');
1551 
1552         return result.toString();
1553     }
1554 
1555     /**
1556      * {@inheritDoc}
1557      * The string representation (also used for the conversion of a matrix into a string,
1558      * e.g. when passing a matrix to the constructor) is the CSS transform function.
1559      */
1560     @Override
1561     public Object getDefaultValue(final Class<?> hint) {
1562         if (String.class.equals(hint) || hint == null) {
1563             return js_toString();
1564         }
1565         return super.getDefaultValue(hint);
1566     }
1567 
1568     private static StringBuilder appendDouble(final StringBuilder builder, final double d) {
1569         if (Double.isNaN(d) || Double.isInfinite(d)) {
1570             return builder.append(d);
1571         }
1572 
1573         if (d % 1 == 0) {
1574             return builder.append((int) d);
1575         }
1576 
1577         return builder.append(d);
1578     }
1579 
1580     /**
1581      * Returns a JSON representation of the DOMMatrixReadOnly object.
1582      * @return a JSON representation of the DOMMatrixReadOnly object
1583      */
1584     @JsxFunction
1585     public Scriptable toJSON() {
1586         final Scriptable json = JavaScriptEngine.newObject(getParentScope());
1587         json.put("a", json, m11_);
1588         json.put("b", json, m12_);
1589         json.put("c", json, m21_);
1590         json.put("d", json, m22_);
1591         json.put("e", json, m41_);
1592         json.put("f", json, m42_);
1593 
1594         json.put("m11", json, m11_);
1595         json.put("m12", json, m12_);
1596         json.put("m13", json, m13_);
1597         json.put("m14", json, m14_);
1598 
1599         json.put("m21", json, m21_);
1600         json.put("m22", json, m22_);
1601         json.put("m23", json, m23_);
1602         json.put("m24", json, m24_);
1603 
1604         json.put("m31", json, m31_);
1605         json.put("m32", json, m32_);
1606         json.put("m33", json, m33_);
1607         json.put("m34", json, m34_);
1608 
1609         json.put("m41", json, m41_);
1610         json.put("m42", json, m42_);
1611         json.put("m43", json, m43_);
1612         json.put("m44", json, m44_);
1613 
1614         json.put("is2D", json, is2D_);
1615         json.put("isIdentity", json, getIsIdentity());
1616 
1617         return json;
1618     }
1619 
1620     /**
1621      * Creates a new {@code DOMMatrixReadOnly} from the given matrix or matrix properties.
1622      *
1623      * @param cx the current context
1624      * @param scope the scope
1625      * @param thisObj the scriptable this object
1626      * @param args the arguments; the first one is the matrix or an object with matrix
1627      *     properties (DOMMatrixInit)
1628      * @param funObj the function object
1629      * @return the new matrix
1630      */
1631     @JsxStaticFunction(functionName = "fromMatrix")
1632     public static DOMMatrixReadOnly fromMatrixReadOnly(final Context cx, final VarScope scope,
1633             final Scriptable thisObj, final Object[] args, final Function funObj) {
1634         final DOMMatrixReadOnly init = fromMatrixInit(args.length > 0 ? args[0] : null,
1635                 "fromMatrix", "DOMMatrixReadOnly");
1636         return newInstance(new DOMMatrixReadOnly(), scope, "DOMMatrixReadOnly", init);
1637     }
1638 
1639     /**
1640      * Creates a new {@code DOMMatrixReadOnly} from the given Float32Array with 6 (2D)
1641      * or 16 (3D) values.
1642      *
1643      * @param cx the current context
1644      * @param scope the scope
1645      * @param thisObj the scriptable this object
1646      * @param args the arguments; the first one is the Float32Array
1647      * @param funObj the function object
1648      * @return the new matrix
1649      */
1650     @JsxStaticFunction(functionName = "fromFloat32Array")
1651     public static DOMMatrixReadOnly fromFloat32ArrayReadOnly(final Context cx, final VarScope scope,
1652             final Scriptable thisObj, final Object[] args, final Function funObj) {
1653         final DOMMatrixReadOnly init = fromTypedArray(args, NativeFloat32Array.class,
1654                 "fromFloat32Array", "DOMMatrixReadOnly");
1655         return newInstance(new DOMMatrixReadOnly(), scope, "DOMMatrixReadOnly", init);
1656     }
1657 
1658     /**
1659      * Creates a new {@code DOMMatrixReadOnly} from the given Float64Array with 6 (2D)
1660      * or 16 (3D) values.
1661      *
1662      * @param cx the current context
1663      * @param scope the scope
1664      * @param thisObj the scriptable this object
1665      * @param args the arguments; the first one is the Float64Array
1666      * @param funObj the function object
1667      * @return the new matrix
1668      */
1669     @JsxStaticFunction(functionName = "fromFloat64Array")
1670     public static DOMMatrixReadOnly fromFloat64ArrayReadOnly(final Context cx, final VarScope scope,
1671             final Scriptable thisObj, final Object[] args, final Function funObj) {
1672         final DOMMatrixReadOnly init = fromTypedArray(args, NativeFloat64Array.class,
1673                 "fromFloat64Array", "DOMMatrixReadOnly");
1674         return newInstance(new DOMMatrixReadOnly(), scope, "DOMMatrixReadOnly", init);
1675     }
1676 
1677     /**
1678      * Initializes the given new matrix object with the scope, the prototype and the values.
1679      *
1680      * @param <T> the matrix type
1681      * @param matrix the new matrix object
1682      * @param scope the scope
1683      * @param className the JavaScript class name used to find the prototype
1684      * @param values the matrix to copy the values from
1685      * @return the given matrix
1686      */
1687     protected static <T extends DOMMatrixReadOnly> T newInstance(final T matrix, final VarScope scope,
1688             final String className, final DOMMatrixReadOnly values) {
1689         matrix.setParentScope(scope);
1690         matrix.setPrototype(ScriptableObject.getClassPrototype(scope, className));
1691         matrix.setValues(values.getValues(), values.is2D_);
1692         return matrix;
1693     }
1694 
1695     /**
1696      * Converts the first argument (a typed array of the given type with 6 or 16 values)
1697      * into a matrix.
1698      *
1699      * @param args the arguments
1700      * @param type the expected typed array type
1701      * @param methodName the name of the calling method for the error message
1702      * @param className the name of the calling class for the error message
1703      * @return a new matrix (without scope)
1704      */
1705     protected static DOMMatrixReadOnly fromTypedArray(final Object[] args,
1706             final Class<? extends NativeTypedArrayView<?>> type,
1707             final String methodName, final String className) {
1708         final String errorPrefix = "Failed to execute '" + methodName + "' on '" + className + "': ";
1709         if (args.length == 0 || !type.isInstance(args[0])) {
1710             throw JavaScriptEngine.typeError(errorPrefix + "parameter 1 is not of type '"
1711                     + (type == NativeFloat32Array.class ? "Float32Array" : "Float64Array") + "'.");
1712         }
1713 
1714         final NativeTypedArrayView<?> array = (NativeTypedArrayView<?>) args[0];
1715         final int length = array.getArrayLength();
1716         final double[] values = new double[length];
1717         for (int i = 0; i < length; i++) {
1718             values[i] = JavaScriptEngine.toNumber(array.getArrayElement(i));
1719         }
1720 
1721         final DOMMatrixReadOnly result = new DOMMatrixReadOnly();
1722         if (length == 6) {
1723             result.setValues2D(values[0], values[1], values[2], values[3], values[4], values[5]);
1724             return result;
1725         }
1726         if (length == 16) {
1727             result.setValues(values, false);
1728             return result;
1729         }
1730 
1731         throw JavaScriptEngine.typeError(errorPrefix
1732                 + "The sequence must contain 6 elements for a 2D matrix or 16 elements for a 3D matrix.");
1733     }
1734 }