@buncanvas/core 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -4,6 +4,7 @@
4
4
  import { createHash } from "crypto";
5
5
  import { basename, join } from "path";
6
6
  import { tmpdir } from "os";
7
+ import { ptr } from "bun:ffi";
7
8
 
8
9
  // BunCanvas/internal/symbols.js
9
10
  import { dlopen, FFIType, suffix } from "bun:ffi";
@@ -19,11 +20,11 @@ try {
19
20
  const req = createRequire(import.meta.url);
20
21
  nativeLib = req.resolve(`@buncanvas/native-${process.platform}-${process.arch}`);
21
22
  }
22
- console.log(nativeLib);
23
23
  if (!nativeLib) {
24
24
  console.error(`BunCanvas.${process.arch}.${suffix} binary was not found in the working directory!`);
25
25
  process.exit(-1);
26
26
  }
27
+ console.info(`[INFO] Chosen native library: ${nativeLib}`);
27
28
  var dlPath = nativeLib;
28
29
  var encoder = new TextEncoder;
29
30
  var encodedCache = new Map;
@@ -72,14 +73,6 @@ var lib = dlopen(dlPath, {
72
73
  args: [],
73
74
  returns: "ptr"
74
75
  },
75
- get_wFocusBlurViewer: {
76
- args: [],
77
- returns: "ptr"
78
- },
79
- signal_frame_ready: {
80
- args: [],
81
- returns: "void"
82
- },
83
76
  set_vsync: {
84
77
  args: ["bool"],
85
78
  returns: "void"
@@ -88,6 +81,10 @@ var lib = dlopen(dlPath, {
88
81
  args: ["int", "int", "cstring"],
89
82
  returns: "void"
90
83
  },
84
+ setup_render_thread: {
85
+ args: ["int", "int", "cstring", "ptr", "bool"],
86
+ returns: "void"
87
+ },
91
88
  window_set_fullscreen: {
92
89
  args: ["bool"],
93
90
  returns: "void"
@@ -121,7 +118,7 @@ var lib = dlopen(dlPath, {
121
118
  returns: "void"
122
119
  },
123
120
  canvas_get_context2D: {
124
- args: ["ptr", "ptr", "bool", "bool"],
121
+ args: ["int", "int", "bool", "bool", "bool", "bool"],
125
122
  returns: "ptr"
126
123
  },
127
124
  canvas_set_fill_style: {
@@ -328,6 +325,10 @@ var lib = dlopen(dlPath, {
328
325
  args: ["ptr", "cstring", "ptr"],
329
326
  returns: "void"
330
327
  },
328
+ canvas_submit_batch: {
329
+ args: ["ptr", "ptr", "int", "bool"],
330
+ returns: "void"
331
+ },
331
332
  canvas_destroy: {
332
333
  args: ["ptr"],
333
334
  returns: "void"
@@ -360,30 +361,30 @@ var lib = dlopen(dlPath, {
360
361
  args: ["cstring"],
361
362
  returns: "ptr"
362
363
  },
363
- audio_backend_init: {
364
- args: [],
365
- returns: "void"
366
- },
367
- audio_create: {
368
- args: ["cstring"],
369
- returns: "ptr"
370
- },
371
- audio_set_src: {
372
- args: ["ptr", "cstring"],
373
- returns: "void"
374
- },
375
- audio_play: {
376
- args: ["ptr"],
377
- returns: "void"
378
- },
379
- audio_stop: {
380
- args: ["ptr"],
381
- returns: "void"
382
- },
383
- audio_destroy: {
384
- args: ["ptr"],
385
- returns: "void"
386
- },
364
+ audio_backend_init: { args: [], returns: FFIType.void },
365
+ audio_create: { args: [FFIType.cstring], returns: FFIType.ptr },
366
+ audio_destroy: { args: [FFIType.ptr], returns: FFIType.void },
367
+ audio_load: { args: [FFIType.ptr], returns: FFIType.bool },
368
+ audio_play: { args: [FFIType.ptr], returns: FFIType.bool },
369
+ audio_pause: { args: [FFIType.ptr], returns: FFIType.void },
370
+ audio_stop: { args: [FFIType.ptr], returns: FFIType.void },
371
+ audio_set_src: { args: [FFIType.ptr, FFIType.cstring], returns: FFIType.void },
372
+ audio_get_src: { args: [FFIType.ptr], returns: FFIType.cstring },
373
+ audio_get_current_time: { args: [FFIType.ptr], returns: FFIType.f64 },
374
+ audio_set_current_time: { args: [FFIType.ptr, FFIType.f64], returns: FFIType.void },
375
+ audio_get_duration: { args: [FFIType.ptr], returns: FFIType.f64 },
376
+ audio_get_volume: { args: [FFIType.ptr], returns: FFIType.f32 },
377
+ audio_set_volume: { args: [FFIType.ptr, FFIType.f32], returns: FFIType.void },
378
+ audio_get_muted: { args: [FFIType.ptr], returns: FFIType.bool },
379
+ audio_set_muted: { args: [FFIType.ptr, FFIType.bool], returns: FFIType.void },
380
+ audio_get_loop: { args: [FFIType.ptr], returns: FFIType.bool },
381
+ audio_set_loop: { args: [FFIType.ptr, FFIType.bool], returns: FFIType.void },
382
+ audio_get_playback_rate: { args: [FFIType.ptr], returns: FFIType.f32 },
383
+ audio_set_playback_rate: { args: [FFIType.ptr, FFIType.f32], returns: FFIType.void },
384
+ audio_get_paused: { args: [FFIType.ptr], returns: FFIType.bool },
385
+ audio_get_ended: { args: [FFIType.ptr], returns: FFIType.bool },
386
+ audio_get_ready_state: { args: [FFIType.ptr], returns: FFIType.u16 },
387
+ audio_get_has_error: { args: [FFIType.ptr], returns: FFIType.bool },
387
388
  path2d_create: {
388
389
  args: [],
389
390
  returns: "ptr"
@@ -446,143 +447,164 @@ var lib = dlopen(dlPath, {
446
447
  }
447
448
  });
448
449
 
449
- // BunCanvas/src/Image.ts
450
- import { ptr } from "bun:ffi";
451
-
452
450
  // BunCanvas/internal/pointers.ts
453
451
  var ptrs = new WeakMap;
454
452
 
455
- // BunCanvas/internal/attachEventTarget.ts
456
- function attachEventTarget(event, target) {
457
- Object.defineProperty(event, "target", {
458
- value: target,
459
- enumerable: true,
460
- configurable: true
461
- });
462
- return event;
453
+ // BunCanvas/internal/Event/setEventHandler.js
454
+ function setHandler(target, type, current, next) {
455
+ if (current) {
456
+ target.removeEventListener(type, current);
457
+ }
458
+ if (next) {
459
+ target.addEventListener(type, next);
460
+ }
461
+ return next;
463
462
  }
464
463
 
465
464
  // BunCanvas/src/Image.ts
466
- var fRegistry = new FinalizationRegistry((ptr) => {
467
- lib.symbols.image_destroy(ptr);
465
+ var fRegistry = new FinalizationRegistry((pointer) => {
466
+ lib.symbols.image_destroy(pointer);
468
467
  });
469
- function computePath(url) {
468
+ var URL_REGEX = /^https?:\/\/(?:www\.)?[^\s/$.?#].[^\s]*$/i;
469
+ function computeTempPath(url) {
470
470
  const hash = createHash("sha256").update(url).digest("hex").slice(0, 16);
471
- const parsed = new URL(url);
472
- const filename = basename(parsed.pathname) || "index";
471
+ const { pathname } = new URL(url);
472
+ const filename = basename(pathname) || "index";
473
473
  return join(tmpdir(), `${hash}-${filename}`);
474
474
  }
475
- function fetchToTemp(url, precomputedPath) {
476
- return (async () => {
477
- let path = precomputedPath ?? computePath(url);
478
- const response = await fetch(url);
479
- if (!response.ok || !response.body) {
480
- throw new Error(`HTTP ${response.status}: ${url}`);
481
- }
482
- const buf = await response.arrayBuffer();
483
- await Bun.write(path, buf);
484
- return path;
485
- })();
475
+ async function fetchToTemp(url, targetPath = computeTempPath(url)) {
476
+ const response = await fetch(url);
477
+ if (!response.ok || !response.body) {
478
+ throw new Error(`HTTP ${response.status}: ${url}`);
479
+ }
480
+ await Bun.write(targetPath, await response.arrayBuffer());
481
+ return targetPath;
486
482
  }
487
- var urlRegex = /^https?:\/\/(?:www\.)?[^\s/$.?#].[^\s]*$/;
488
483
 
489
- class Image {
490
- #queue = null;
491
- #width = 0;
492
- #setWidth = false;
493
- #height = 0;
494
- #setHeight = false;
484
+ class Image extends EventTarget {
485
+ #loadHandler = null;
486
+ #errorHandler = null;
495
487
  #src = "";
496
- constructor() {
497
- let ptr = lib.symbols.image_create();
498
- ptrs.set(this, ptr);
499
- fRegistry.register(this, ptr);
488
+ #naturalWidth = 0;
489
+ #naturalHeight = 0;
490
+ #width = null;
491
+ #height = null;
492
+ #complete = true;
493
+ #loadId = 0;
494
+ #pendingDecode = null;
495
+ constructor(width, height) {
496
+ super();
497
+ const pointer = lib.symbols.image_create();
498
+ ptrs.set(this, pointer);
499
+ fRegistry.register(this, pointer);
500
+ if (width !== undefined)
501
+ this.width = width;
502
+ if (height !== undefined)
503
+ this.height = height;
500
504
  }
501
- onload = null;
502
- onerror = null;
503
- set src(path) {
504
- this.#src = path;
505
- if (urlRegex.test(path)) {
506
- const weakThis = new WeakRef(this);
507
- const precomp = computePath(path);
508
- const iptr = ptrs.get(this);
509
- lib.symbols.image_set_src(iptr, encoder.encode(`${precomp}\x00`), true);
510
- fetchToTemp(path, precomp).then(() => {
511
- const tArr = new Int32Array(2);
512
- const self = weakThis.deref();
513
- if (!self) {
514
- return;
515
- }
516
- if (lib.symbols.image_load(iptr, ptr(tArr))) {
517
- this.#width = !this.#setWidth ? tArr[0] : this.#width;
518
- this.#height = !this.#setHeight ? tArr[1] : this.#height;
519
- self.onload?.call(self, attachEventTarget(new Event("load", {}), self));
505
+ get onload() {
506
+ return this.#loadHandler;
507
+ }
508
+ set onload(fn) {
509
+ this.#loadHandler = setHandler(this, "load", this.#loadHandler, fn);
510
+ }
511
+ get onerror() {
512
+ return this.#errorHandler;
513
+ }
514
+ set onerror(fn) {
515
+ this.#errorHandler = setHandler(this, "error", this.#errorHandler, fn);
516
+ }
517
+ get src() {
518
+ return this.#src;
519
+ }
520
+ set src(value) {
521
+ this.#src = value;
522
+ const currentLoadId = ++this.#loadId;
523
+ if (!value) {
524
+ this.#naturalWidth = 0;
525
+ this.#naturalHeight = 0;
526
+ this.#complete = true;
527
+ this.#pendingDecode = null;
528
+ return;
529
+ }
530
+ this.#complete = false;
531
+ const isRemote = URL_REGEX.test(value);
532
+ const localPath = isRemote ? computeTempPath(value) : value;
533
+ const nativePtr = ptrs.get(this);
534
+ lib.symbols.image_set_src(nativePtr, encoder.encode(`${localPath}\x00`), isRemote);
535
+ const weakSelf = new WeakRef(this);
536
+ const loadTask = (async () => {
537
+ try {
538
+ if (isRemote) {
539
+ await fetchToTemp(value, localPath);
520
540
  } else {
521
- self.onerror?.call(self, attachEventTarget(new Event("error", {}), self));
541
+ await new Promise((resolve) => setTimeout(resolve, 0));
522
542
  }
523
- }).catch((ex) => {
524
- const self = weakThis.deref();
525
- if (!self)
543
+ const self = weakSelf.deref();
544
+ if (!self || self.#loadId !== currentLoadId)
526
545
  return;
527
- self.onerror?.call(self, attachEventTarget(new Event("error", {}), self));
528
- }).finally(() => {});
529
- return;
530
- } else {
531
- const weakThis = new WeakRef(this);
532
- lib.symbols.image_set_src(ptrs.get(this), encoder.encode(`${path}\x00`), false);
533
- let tm = setTimeout(() => {
534
- const self = weakThis.deref();
535
- if (!self) {
536
- clearTimeout(tm);
546
+ self.#finalizeLoad(nativePtr);
547
+ } catch {
548
+ const self = weakSelf.deref();
549
+ if (!self || self.#loadId !== currentLoadId)
537
550
  return;
538
- }
539
- const _ptr = ptrs.get(self);
540
- const tArr = new Int32Array(2);
541
- if (lib.symbols.image_load(_ptr, ptr(tArr))) {
542
- this.#width = !this.#setWidth ? tArr[0] : this.#width;
543
- this.#height = !this.#setHeight ? tArr[1] : this.#height;
544
- self.onload?.call(self, attachEventTarget(new Event("error", {}), self));
545
- } else {
546
- self.onerror?.call(self, attachEventTarget(new Event("error", {}), self));
547
- }
548
- clearTimeout(tm);
549
- }, 0);
551
+ self.#failLoad();
552
+ }
553
+ })();
554
+ this.#pendingDecode = loadTask.then(() => {
555
+ if (!this.#complete || this.#naturalWidth === 0 && this.#naturalHeight === 0) {
556
+ throw new DOMException("The source image cannot be decoded.", "EncodingError");
557
+ }
558
+ });
559
+ this.#pendingDecode.catch(() => {});
560
+ }
561
+ #finalizeLoad(nativePtr) {
562
+ const dimensions = new Int32Array(2);
563
+ const success = Boolean(lib.symbols.image_load(nativePtr, ptr(dimensions)));
564
+ if (success) {
565
+ this.#naturalWidth = dimensions[0];
566
+ this.#naturalHeight = dimensions[1];
567
+ this.#complete = true;
568
+ this.dispatchEvent(new Event("load"));
569
+ } else {
570
+ this.#failLoad();
550
571
  }
551
572
  }
552
- get src() {
553
- return this.#src;
573
+ #failLoad() {
574
+ this.#naturalWidth = 0;
575
+ this.#naturalHeight = 0;
576
+ this.#complete = true;
577
+ this.dispatchEvent(new Event("error"));
554
578
  }
555
- get ptr() {
556
- return ptrs.get(this);
579
+ get complete() {
580
+ return this.#complete;
581
+ }
582
+ get naturalWidth() {
583
+ return this.#naturalWidth;
584
+ }
585
+ get naturalHeight() {
586
+ return this.#naturalHeight;
557
587
  }
558
588
  get width() {
559
- return this.#width;
589
+ return this.#width ?? this.#naturalWidth;
560
590
  }
561
- get height() {
562
- return this.#height;
591
+ set width(value) {
592
+ this.#width = Math.max(0, Math.floor(Number(value) || 0));
563
593
  }
564
- set width(v) {
565
- this.#setWidth = true;
566
- this.#width = v;
594
+ get height() {
595
+ return this.#height ?? this.#naturalHeight;
567
596
  }
568
- set height(v) {
569
- this.#setHeight = true;
570
- this.#height = v;
597
+ set height(value) {
598
+ this.#height = Math.max(0, Math.floor(Number(value) || 0));
571
599
  }
572
- }
573
- {
574
- const proto = Image.prototype;
575
- for (const key of Object.getOwnPropertyNames(proto)) {
576
- const desc = Object.getOwnPropertyDescriptor(proto, key);
577
- if (key == "constructor") {
578
- desc && (desc.value.toString = () => {
579
- return `function ${proto.constructor.name}() { [native code] }`;
580
- });
581
- continue;
600
+ decode() {
601
+ if (!this.#src) {
602
+ return Promise.reject(new DOMException("Invalid image source.", "EncodingError"));
582
603
  }
583
- if (typeof desc?.value === "function") {
584
- desc.value.toString = () => `function ${key}() { [native code] }`;
604
+ if (this.#pendingDecode) {
605
+ return this.#pendingDecode;
585
606
  }
607
+ return this.#naturalWidth > 0 || this.#naturalHeight > 0 ? Promise.resolve() : Promise.reject(new DOMException("The source image cannot be decoded.", "EncodingError"));
586
608
  }
587
609
  }
588
610
  // BunCanvas/src/FontFace.js
@@ -904,434 +926,671 @@ class KeyboardEvent extends Event {
904
926
  return this.#modifiers.get(keyArg) ?? false;
905
927
  }
906
928
  }
907
- // BunCanvas/src/Canvas.ts
908
- import { ptr as ptr3, JSCallback } from "bun:ffi";
929
+ // BunCanvas/internal/colorCheck.ts
930
+ var NAMED_COLORS = new Set([
931
+ "aliceblue",
932
+ "antiquewhite",
933
+ "aqua",
934
+ "aquamarine",
935
+ "azure",
936
+ "beige",
937
+ "bisque",
938
+ "black",
939
+ "blanchedalmond",
940
+ "blue",
941
+ "blueviolet",
942
+ "brown",
943
+ "burlywood",
944
+ "cadetblue",
945
+ "chartreuse",
946
+ "chocolate",
947
+ "coral",
948
+ "cornflowerblue",
949
+ "cornsilk",
950
+ "crimson",
951
+ "cyan",
952
+ "darkblue",
953
+ "darkcyan",
954
+ "darkgoldenrod",
955
+ "darkgray",
956
+ "darkgreen",
957
+ "darkgrey",
958
+ "darkkhaki",
959
+ "darkmagenta",
960
+ "darkolivegreen",
961
+ "darkorange",
962
+ "darkorchid",
963
+ "darkred",
964
+ "darksalmon",
965
+ "darkseagreen",
966
+ "darkslateblue",
967
+ "darkslategray",
968
+ "darkslategrey",
969
+ "darkturquoise",
970
+ "darkviolet",
971
+ "deeppink",
972
+ "deepskyblue",
973
+ "dimgray",
974
+ "dimgrey",
975
+ "dodgerblue",
976
+ "firebrick",
977
+ "floralwhite",
978
+ "forestgreen",
979
+ "fuchsia",
980
+ "gainsboro",
981
+ "ghostwhite",
982
+ "gold",
983
+ "goldenrod",
984
+ "gray",
985
+ "green",
986
+ "greenyellow",
987
+ "grey",
988
+ "honeydew",
989
+ "hotpink",
990
+ "indianred",
991
+ "indigo",
992
+ "ivory",
993
+ "khaki",
994
+ "lavender",
995
+ "lavenderblush",
996
+ "lawngreen",
997
+ "lemonchiffon",
998
+ "lightblue",
999
+ "lightcoral",
1000
+ "lightcyan",
1001
+ "lightgoldenrodyellow",
1002
+ "lightgray",
1003
+ "lightgreen",
1004
+ "lightgrey",
1005
+ "lightpink",
1006
+ "lightsalmon",
1007
+ "lightseagreen",
1008
+ "lightskyblue",
1009
+ "lightslategray",
1010
+ "lightslategrey",
1011
+ "lightsteelblue",
1012
+ "lightyellow",
1013
+ "lime",
1014
+ "limegreen",
1015
+ "linen",
1016
+ "magenta",
1017
+ "maroon",
1018
+ "mediumaquamarine",
1019
+ "mediumblue",
1020
+ "mediumorchid",
1021
+ "mediumpurple",
1022
+ "mediumseagreen",
1023
+ "mediumslateblue",
1024
+ "mediumspringgreen",
1025
+ "mediumturquoise",
1026
+ "mediumvioletred",
1027
+ "midnightblue",
1028
+ "mintcream",
1029
+ "mistyrose",
1030
+ "moccasin",
1031
+ "navajowhite",
1032
+ "navy",
1033
+ "oldlace",
1034
+ "olive",
1035
+ "olivedrab",
1036
+ "orange",
1037
+ "orangered",
1038
+ "orchid",
1039
+ "palegoldenrod",
1040
+ "palegreen",
1041
+ "paleturquoise",
1042
+ "palevioletred",
1043
+ "papayawhip",
1044
+ "peachpuff",
1045
+ "peru",
1046
+ "pink",
1047
+ "plum",
1048
+ "powderblue",
1049
+ "purple",
1050
+ "rebeccapurple",
1051
+ "red",
1052
+ "rosybrown",
1053
+ "royalblue",
1054
+ "saddlebrown",
1055
+ "salmon",
1056
+ "sandybrown",
1057
+ "seagreen",
1058
+ "seashell",
1059
+ "sienna",
1060
+ "silver",
1061
+ "skyblue",
1062
+ "slateblue",
1063
+ "slategray",
1064
+ "slategrey",
1065
+ "snow",
1066
+ "springgreen",
1067
+ "steelblue",
1068
+ "tan",
1069
+ "teal",
1070
+ "thistle",
1071
+ "tomato",
1072
+ "transparent",
1073
+ "turquoise",
1074
+ "violet",
1075
+ "wheat",
1076
+ "white",
1077
+ "whitesmoke",
1078
+ "yellow",
1079
+ "yellowgreen"
1080
+ ]);
1081
+ var HEX_REGEX = /^#(?:[0-9a-fA-F]{3,4}){1,2}$/;
1082
+ var RGB_REGEX = /^rgba?\(\s*(?:\d+(?:\.\d+)?%?|\.\d+%?)\s*[, ]\s*(?:\d+(?:\.\d+)?%?|\.\d+%?)\s*[, ]\s*(?:\d+(?:\.\d+)?%?|\.\d+%?)(?:\s*[,/]\s*(?:\d+(?:\.\d+)?%?|\.\d+%?))?\s*\)$/i;
1083
+ var HSL_HWB_REGEX = /^(?:hsl|hsla|hwb)\(\s*(?:\d+(?:\.\d+)?(?:deg|rad|turn)?|\.\d+(?:deg|rad|turn)?)\s*[, ]\s*(?:\d+(?:\.\d+)?%|\.\d+%)\s*[, ]\s*(?:\d+(?:\.\d+)?%|\.\d+%)(?:\s*[,/]\s*(?:\d+(?:\.\d+)?%?|\.\d+%?))?\s*\)$/i;
1084
+ function isValidColor(str) {
1085
+ if (typeof str !== "string")
1086
+ return false;
1087
+ const normalized = str.trim().toLowerCase();
1088
+ if (normalized === "")
1089
+ return false;
1090
+ if (NAMED_COLORS.has(normalized))
1091
+ return true;
1092
+ if (normalized.startsWith("#"))
1093
+ return HEX_REGEX.test(normalized);
1094
+ return RGB_REGEX.test(normalized) || HSL_HWB_REGEX.test(normalized);
1095
+ }
909
1096
 
910
- // BunCanvas/src/ImageData.ts
911
- class ImageData {
912
- width;
913
- height;
914
- data;
915
- colorSpace;
916
- constructor(arg1, arg2, arg3, arg4) {
917
- let data;
918
- let width;
919
- let height;
920
- let settings;
921
- if (arg1 instanceof Uint8ClampedArray) {
922
- data = arg1;
923
- width = arg2;
924
- if (typeof arg3 === "number") {
925
- height = arg3;
926
- settings = arg4;
927
- } else {
928
- settings = arg3;
929
- height = data.length / 4 / width;
930
- }
931
- if (data.length === 0 || data.length % 4 !== 0) {
932
- throw new SyntaxError("The input data array length must be a non-zero multiple of 4.");
933
- }
934
- if (width <= 0 || !Number.isInteger(width)) {
935
- throw new SyntaxError("Width must be a positive integer.");
936
- }
937
- if (height <= 0 || !Number.isInteger(height)) {
938
- throw new SyntaxError("Height must be a positive integer or derived from array length.");
1097
+ // BunCanvas/internal/native/enums.ts
1098
+ //!< r = 0
1099
+ //!< r = s
1100
+ //!< r = d
1101
+ //!< r = s + (1-sa)*d
1102
+ //!< r = d + (1-da)*s
1103
+ //!< r = s * da
1104
+ //!< r = d * sa
1105
+ //!< r = s * (1-da)
1106
+ //!< r = d * (1-sa)
1107
+ //!< r = s*da + d*(1-sa)
1108
+ //!< r = d*sa + s*(1-da)
1109
+ //!< r = s*(1-da) + d*(1-sa)
1110
+ //!< r = min(s + d, 1)
1111
+ //!< r = s*d
1112
+ //!< r = s + d - s*d
1113
+ //!< multiply or screen, depending on destination
1114
+ //!< rc = s + d - max(s*da, d*sa), ra = kSrcOver
1115
+ //!< rc = s + d - min(s*da, d*sa), ra = kSrcOver
1116
+ //!< brighten destination to reflect source
1117
+ //!< darken destination to reflect source
1118
+ //!< multiply or screen, depending on source
1119
+ //!< lighten or darken, depending on source
1120
+ //!< rc = s + d - 2*(min(s*da, d*sa)), ra = kSrcOver
1121
+ //!< rc = s + d - two(s*d), ra = kSrcOver
1122
+ //!< r = s*(1-da) + d*(1-sa) + s*d
1123
+ //!< hue of source with saturation and luminosity of destination
1124
+ //!< saturation of source with hue and luminosity of destination
1125
+ //!< hue and saturation of source with luminosity of destination
1126
+ //!< luminosity of source with hue and saturation of destination
1127
+ //!< last porter duff blend mode
1128
+ //!< last blend mode operating separately on components
1129
+ //!< last valid value
1130
+ //!< extends to miter limit
1131
+ //!< adds circle
1132
+ //!< connects outside edges
1133
+ //!< equivalent to the largest value for Join
1134
+ //!< equivalent to kMiter_Join
1135
+
1136
+ // BunCanvas/src/Canvas/canvasGradient.ts
1137
+ class CanvasGradient {
1138
+ type;
1139
+ points = new Float32Array(6);
1140
+ offsets = [];
1141
+ colors = [];
1142
+ constructor(...args) {
1143
+ if (args[0] !== INTERNAL_TOKEN)
1144
+ throwIllegalConstructor(this);
1145
+ this.type = args[1];
1146
+ switch (this.type) {
1147
+ case 0 /* Linear */: {
1148
+ this.points[0] = args[2];
1149
+ this.points[1] = args[3];
1150
+ this.points[2] = args[4];
1151
+ this.points[3] = args[5];
1152
+ break;
939
1153
  }
940
- if (data.length !== width * height * 4) {
941
- throw new SyntaxError("The input data array length does not match width * height * 4.");
1154
+ case 1 /* Radial */: {
1155
+ this.points[0] = args[2];
1156
+ this.points[1] = args[3];
1157
+ this.points[2] = args[4];
1158
+ this.points[3] = args[5];
1159
+ this.points[4] = args[6];
1160
+ this.points[5] = args[7];
1161
+ break;
942
1162
  }
943
- } else if (typeof arg1 === "number" && typeof arg2 === "number") {
944
- width = arg1;
945
- height = arg2;
946
- settings = arg3;
947
- if (width <= 0 || !Number.isInteger(width) || height <= 0 || !Number.isInteger(height)) {
948
- throw new SyntaxError("Width and height must be positive integers.");
1163
+ case 2 /* Conic */: {
1164
+ this.points[0] = args[2];
1165
+ this.points[1] = args[3];
1166
+ this.points[2] = args[4];
1167
+ break;
949
1168
  }
950
- data = new Uint8ClampedArray(width * height * 4);
951
- } else {
952
- throw new TypeError("Failed to construct 'ImageData': Invalid arguments provided.");
953
1169
  }
954
- this.width = width;
955
- this.height = height;
956
- this.data = data;
957
- this.colorSpace = settings?.colorSpace ?? "srgb";
1170
+ }
1171
+ addColorStop(offset, color) {
1172
+ if (offset < 0 || offset > 1)
1173
+ throw new RangeError(`Failed to execute 'addColorStop' on 'CanvasGradient': The provided value (${offset}) is outside the range (0.0, 1.0).`);
1174
+ if (!isValidColor(color))
1175
+ throw new SyntaxError(`Failed to execute 'addColorStop' on 'CanvasGradient': The value provided ('${color}') could not be parsed as a color.`);
1176
+ const idx = this.offsets.findIndex((o) => o > offset);
1177
+ const insertIdx = idx === -1 ? this.offsets.length : idx;
1178
+ this.offsets.splice(insertIdx, 0, offset);
1179
+ this.colors.splice(insertIdx, 0, encodeCString(color));
1180
+ }
1181
+ }
1182
+ {
1183
+ const proto = CanvasGradient.prototype;
1184
+ for (const key of Object.getOwnPropertyNames(proto)) {
1185
+ const desc = Object.getOwnPropertyDescriptor(proto, key);
1186
+ if (key == "constructor") {
1187
+ desc && (desc.value.toString = () => {
1188
+ return `function ${proto.constructor.name}() { [native code] }`;
1189
+ });
1190
+ continue;
1191
+ }
1192
+ if (typeof desc?.value === "function") {
1193
+ desc.value.toString = () => `function ${key}() { [native code] }`;
1194
+ }
958
1195
  }
959
1196
  }
1197
+ // BunCanvas/src/Canvas/RenderingContexts/2D/CanvasBatchedRenderingContext2D.ts
1198
+ import { ptr as ptr3 } from "bun:ffi";
1199
+
1200
+ // BunCanvas/src/Canvas/blendModes.ts
1201
+ var CanvasBlendMode = {
1202
+ "source-over": 3 /* kSrcOver */,
1203
+ "source-in": 5 /* kSrcIn */,
1204
+ "source-out": 7 /* kSrcOut */,
1205
+ "source-atop": 9 /* kSrcATop */,
1206
+ "destination-over": 4 /* kDstOver */,
1207
+ "destination-in": 6 /* kDstIn */,
1208
+ "destination-out": 8 /* kDstOut */,
1209
+ "destination-atop": 10 /* kDstATop */,
1210
+ lighter: 17 /* kLighten */,
1211
+ copy: 1 /* kSrc */,
1212
+ xor: 11 /* kXor */,
1213
+ multiply: 24 /* kMultiply */,
1214
+ screen: 14 /* kScreen */,
1215
+ overlay: 15 /* kOverlay */,
1216
+ darken: 16 /* kDarken */,
1217
+ lighten: 17 /* kLighten */,
1218
+ "color-dodge": 18 /* kColorDodge */,
1219
+ "color-burn": 19 /* kColorBurn */,
1220
+ "hard-light": 20 /* kHardLight */,
1221
+ "soft-light": 21 /* kSoftLight */,
1222
+ difference: 22 /* kDifference */,
1223
+ exclusion: 23 /* kExclusion */,
1224
+ hue: 25 /* kHue */,
1225
+ saturation: 26 /* kSaturation */,
1226
+ color: 27 /* kColor */,
1227
+ luminosity: 28 /* kLuminosity */
1228
+ };
1229
+
1230
+ // BunCanvas/src/Canvas/smoothingQuality.ts
1231
+ var CanvasSmoothingQuality = {
1232
+ low: 0 /* Low */,
1233
+ medium: 1 /* Medium */,
1234
+ high: 2 /* High */
1235
+ };
1236
+
1237
+ // BunCanvas/src/Canvas/lineJoin.ts
1238
+ var CanvasLineJoin = {
1239
+ round: 1 /* kRound_Join */,
1240
+ bevel: 2 /* kBevel_Join */,
1241
+ miter: 0 /* kMiter_Join */
1242
+ };
1243
+
1244
+ // BunCanvas/src/Canvas/textAlignment.ts
1245
+ var CanvasTextAlignment = {
1246
+ left: 0 /* Left */,
1247
+ right: 1 /* Right */,
1248
+ center: 2 /* Center */,
1249
+ start: 3 /* Start */,
1250
+ end: 4 /* End */
1251
+ };
1252
+
1253
+ // BunCanvas/src/Canvas/textBaseline.ts
1254
+ var CanvasTextBaseline = {
1255
+ top: 0 /* Top */,
1256
+ hanging: 1 /* Hanging */,
1257
+ middle: 2 /* Middle */,
1258
+ alphabetic: 3 /* Alphabetic */,
1259
+ ideographic: 4 /* Ideographic */,
1260
+ bottom: 5 /* Bottom */
1261
+ };
960
1262
 
961
1263
  // BunCanvas/dom/DOMMatrix.ts
962
- import { ptr as ptr2 } from "bun:ffi";
963
1264
  function isMatrixArray(value) {
964
- return value == undefined || Array.isArray(value) || ArrayBuffer.isView(value) && !(value instanceof DataView);
1265
+ return Array.isArray(value) || ArrayBuffer.isView(value) && !(value instanceof DataView);
965
1266
  }
966
1267
  function multipliedMatrices(a, b) {
967
- const out = new Float64Array(16);
968
- out[0] = a[0] * b[0] + a[1] * b[4] + a[2] * b[8] + a[3] * b[12];
969
- out[1] = a[0] * b[1] + a[1] * b[5] + a[2] * b[9] + a[3] * b[13];
970
- out[2] = a[0] * b[2] + a[1] * b[6] + a[2] * b[10] + a[3] * b[14];
971
- out[3] = a[0] * b[3] + a[1] * b[7] + a[2] * b[11] + a[3] * b[15];
972
- out[4] = a[4] * b[0] + a[5] * b[4] + a[6] * b[8] + a[7] * b[12];
973
- out[5] = a[4] * b[1] + a[5] * b[5] + a[6] * b[9] + a[7] * b[13];
974
- out[6] = a[4] * b[2] + a[5] * b[6] + a[6] * b[10] + a[7] * b[14];
975
- out[7] = a[4] * b[3] + a[5] * b[7] + a[6] * b[11] + a[7] * b[15];
976
- out[8] = a[8] * b[0] + a[9] * b[4] + a[10] * b[8] + a[11] * b[12];
977
- out[9] = a[8] * b[1] + a[9] * b[5] + a[10] * b[9] + a[11] * b[13];
978
- out[10] = a[8] * b[2] + a[9] * b[6] + a[10] * b[10] + a[11] * b[14];
979
- out[11] = a[8] * b[3] + a[9] * b[7] + a[10] * b[11] + a[11] * b[15];
980
- out[12] = a[12] * b[0] + a[13] * b[4] + a[14] * b[8] + a[15] * b[12];
981
- out[13] = a[12] * b[1] + a[13] * b[5] + a[14] * b[9] + a[15] * b[13];
982
- out[14] = a[12] * b[2] + a[13] * b[6] + a[14] * b[10] + a[15] * b[14];
983
- out[15] = a[12] * b[3] + a[13] * b[7] + a[14] * b[11] + a[15] * b[15];
1268
+ const out = [];
1269
+ const a00 = a[0], a01 = a[4], a02 = a[8], a03 = a[12];
1270
+ const a10 = a[1], a11 = a[5], a12 = a[9], a13 = a[13];
1271
+ const a20 = a[2], a21 = a[6], a22 = a[10], a23 = a[14];
1272
+ const a30 = a[3], a31 = a[7], a32 = a[11], a33 = a[15];
1273
+ const b00 = b[0], b01 = b[4], b02 = b[8], b03 = b[12];
1274
+ const b10 = b[1], b11 = b[5], b12 = b[9], b13 = b[13];
1275
+ const b20 = b[2], b21 = b[6], b22 = b[10], b23 = b[14];
1276
+ const b30 = b[3], b31 = b[7], b32 = b[11], b33 = b[15];
1277
+ out[0] = a00 * b00 + a01 * b10 + a02 * b20 + a03 * b30;
1278
+ out[1] = a10 * b00 + a11 * b10 + a12 * b20 + a13 * b30;
1279
+ out[2] = a20 * b00 + a21 * b10 + a22 * b20 + a23 * b30;
1280
+ out[3] = a30 * b00 + a31 * b10 + a32 * b20 + a33 * b30;
1281
+ out[4] = a00 * b01 + a01 * b11 + a02 * b21 + a03 * b31;
1282
+ out[5] = a10 * b01 + a11 * b11 + a12 * b21 + a13 * b31;
1283
+ out[6] = a20 * b01 + a21 * b11 + a22 * b21 + a23 * b31;
1284
+ out[7] = a30 * b01 + a31 * b11 + a32 * b21 + a33 * b31;
1285
+ out[8] = a00 * b02 + a01 * b12 + a02 * b22 + a03 * b32;
1286
+ out[9] = a10 * b02 + a11 * b12 + a12 * b22 + a13 * b32;
1287
+ out[10] = a20 * b02 + a21 * b12 + a22 * b22 + a23 * b32;
1288
+ out[11] = a30 * b02 + a31 * b12 + a32 * b22 + a33 * b32;
1289
+ out[12] = a00 * b03 + a01 * b13 + a02 * b23 + a03 * b33;
1290
+ out[13] = a10 * b03 + a11 * b13 + a12 * b23 + a13 * b33;
1291
+ out[14] = a20 * b03 + a21 * b13 + a22 * b23 + a23 * b33;
1292
+ out[15] = a30 * b03 + a31 * b13 + a32 * b23 + a33 * b33;
984
1293
  return out;
985
1294
  }
986
1295
  function throwParseErrorDMatrix(fName, pString) {
987
1296
  throw new SyntaxError(`Failed to execute '${fName}' on 'DOMMatrix': Failed to parse '${pString}'.`);
988
1297
  }
1298
+ var CSS_NUMBER_RE = /^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i;
1299
+ var CSS_DIM_RE = /^([+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?)([a-z%]+)$/i;
1300
+ var f64Arrays = new WeakMap;
1301
+ function getInternalArray(dMtrx) {
1302
+ return f64Arrays.get(dMtrx);
1303
+ }
989
1304
 
990
1305
  class DOMMatrix {
991
- #internal = new Float64Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
992
- #isIdentity = true;
993
- #computeIdentity() {
994
- this.#isIdentity = this.#internal[0] == 1 && this.#internal[1] == 0 && this.#internal[2] == 0 && this.#internal[3] == 0 && this.#internal[4] == 0 && this.#internal[5] == 1 && this.#internal[6] == 0 && this.#internal[7] == 0 && this.#internal[8] == 0 && this.#internal[9] == 0 && this.#internal[10] == 1 && this.#internal[11] == 0 && this.#internal[12] == 0 && this.#internal[13] == 0 && this.#internal[14] == 0 && this.#internal[15] == 1;
1306
+ #internal = new Float64Array([
1307
+ 1,
1308
+ 0,
1309
+ 0,
1310
+ 0,
1311
+ 0,
1312
+ 1,
1313
+ 0,
1314
+ 0,
1315
+ 0,
1316
+ 0,
1317
+ 1,
1318
+ 0,
1319
+ 0,
1320
+ 0,
1321
+ 0,
1322
+ 1
1323
+ ]);
1324
+ #is2D = true;
1325
+ get is2D() {
1326
+ return this.#is2D;
1327
+ }
1328
+ get isIdentity() {
1329
+ const m = this.#internal;
1330
+ return m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 0 && m[4] === 0 && m[5] === 1 && m[6] === 0 && m[7] === 0 && m[8] === 0 && m[9] === 0 && m[10] === 1 && m[11] === 0 && m[12] === 0 && m[13] === 0 && m[14] === 0 && m[15] === 1;
995
1331
  }
996
1332
  get a() {
997
- return this.m11;
1333
+ return this.#internal[0];
998
1334
  }
999
1335
  set a(v) {
1000
- this.m11 = v;
1336
+ this.#internal[0] = Number(v);
1001
1337
  }
1002
1338
  get b() {
1003
- return this.m12;
1339
+ return this.#internal[1];
1004
1340
  }
1005
1341
  set b(v) {
1006
- this.m12 = v;
1342
+ this.#internal[1] = Number(v);
1007
1343
  }
1008
1344
  get c() {
1009
- return this.m21;
1345
+ return this.#internal[4];
1010
1346
  }
1011
1347
  set c(v) {
1012
- this.m21 = v;
1348
+ this.#internal[4] = Number(v);
1013
1349
  }
1014
1350
  get d() {
1015
- return this.m22;
1351
+ return this.#internal[5];
1016
1352
  }
1017
1353
  set d(v) {
1018
- this.m22 = v;
1354
+ this.#internal[5] = Number(v);
1019
1355
  }
1020
1356
  get e() {
1021
- return this.m41;
1357
+ return this.#internal[12];
1022
1358
  }
1023
1359
  set e(v) {
1024
- this.m41 = v;
1360
+ this.#internal[12] = Number(v);
1025
1361
  }
1026
1362
  get f() {
1027
- return this.m42;
1363
+ return this.#internal[13];
1028
1364
  }
1029
1365
  set f(v) {
1030
- this.m42 = v;
1031
- }
1032
- is2D = true;
1033
- get isIdentity() {
1034
- return this.#isIdentity;
1366
+ this.#internal[13] = Number(v);
1035
1367
  }
1036
1368
  get m11() {
1037
1369
  return this.#internal[0];
1038
1370
  }
1039
1371
  set m11(v) {
1040
- this.#internal[0] = v;
1041
- if (!this.#isIdentity) {
1042
- if (v == 1)
1043
- this.#computeIdentity();
1044
- } else {
1045
- if (v != 1)
1046
- this.#isIdentity = false;
1047
- }
1372
+ this.#internal[0] = Number(v);
1048
1373
  }
1049
1374
  get m12() {
1050
- return this.#internal[4];
1375
+ return this.#internal[1];
1051
1376
  }
1052
1377
  set m12(v) {
1053
- this.#internal[4] = v;
1054
- if (!this.#isIdentity) {
1055
- if (v == 0)
1056
- this.#computeIdentity();
1057
- } else {
1058
- if (v != 0)
1059
- this.#isIdentity = false;
1060
- }
1378
+ this.#internal[1] = Number(v);
1061
1379
  }
1062
1380
  get m13() {
1063
- return this.#internal[8];
1381
+ return this.#internal[2];
1064
1382
  }
1065
1383
  set m13(v) {
1066
- this.#internal[8] = v;
1067
- if (!this.#isIdentity) {
1068
- if (v == 0)
1069
- this.#computeIdentity();
1070
- } else {
1071
- if (v != 0)
1072
- this.#isIdentity = false;
1073
- }
1384
+ const val = Number(v);
1385
+ this.#internal[2] = val;
1386
+ if (val !== 0)
1387
+ this.#is2D = false;
1074
1388
  }
1075
1389
  get m14() {
1076
- return this.#internal[12];
1390
+ return this.#internal[3];
1077
1391
  }
1078
1392
  set m14(v) {
1079
- this.#internal[12] = v;
1080
- if (!this.#isIdentity) {
1081
- if (v == 0)
1082
- this.#computeIdentity();
1083
- } else {
1084
- if (v != 0)
1085
- this.#isIdentity = false;
1086
- }
1393
+ const val = Number(v);
1394
+ this.#internal[3] = val;
1395
+ if (val !== 0)
1396
+ this.#is2D = false;
1087
1397
  }
1088
1398
  get m21() {
1089
- return this.#internal[1];
1399
+ return this.#internal[4];
1090
1400
  }
1091
1401
  set m21(v) {
1092
- this.#internal[1] = v;
1093
- if (!this.#isIdentity) {
1094
- if (v == 0)
1095
- this.#computeIdentity();
1096
- } else {
1097
- if (v != 0)
1098
- this.#isIdentity = false;
1099
- }
1402
+ this.#internal[4] = Number(v);
1100
1403
  }
1101
1404
  get m22() {
1102
1405
  return this.#internal[5];
1103
1406
  }
1104
1407
  set m22(v) {
1105
- this.#internal[5] = v;
1106
- if (!this.#isIdentity) {
1107
- if (v == 1)
1108
- this.#computeIdentity();
1109
- } else {
1110
- if (v != 1)
1111
- this.#isIdentity = false;
1112
- }
1408
+ this.#internal[5] = Number(v);
1113
1409
  }
1114
1410
  get m23() {
1115
- return this.#internal[9];
1411
+ return this.#internal[6];
1116
1412
  }
1117
1413
  set m23(v) {
1118
- this.#internal[9] = v;
1119
- if (!this.#isIdentity) {
1120
- if (v == 0)
1121
- this.#computeIdentity();
1122
- } else {
1123
- if (v != 0)
1124
- this.#isIdentity = false;
1125
- }
1414
+ const val = Number(v);
1415
+ this.#internal[6] = val;
1416
+ if (val !== 0)
1417
+ this.#is2D = false;
1126
1418
  }
1127
1419
  get m24() {
1128
- return this.#internal[13];
1420
+ return this.#internal[7];
1129
1421
  }
1130
1422
  set m24(v) {
1131
- this.#internal[13] = v;
1132
- if (!this.#isIdentity) {
1133
- if (v == 0)
1134
- this.#computeIdentity();
1135
- } else {
1136
- if (v != 0)
1137
- this.#isIdentity = false;
1138
- }
1423
+ const val = Number(v);
1424
+ this.#internal[7] = val;
1425
+ if (val !== 0)
1426
+ this.#is2D = false;
1139
1427
  }
1140
1428
  get m31() {
1141
- return this.#internal[2];
1429
+ return this.#internal[8];
1142
1430
  }
1143
1431
  set m31(v) {
1144
- this.#internal[2] = v;
1145
- if (!this.#isIdentity) {
1146
- if (v == 0)
1147
- this.#computeIdentity();
1148
- } else {
1149
- if (v != 0)
1150
- this.#isIdentity = false;
1151
- }
1432
+ const val = Number(v);
1433
+ this.#internal[8] = val;
1434
+ if (val !== 0)
1435
+ this.#is2D = false;
1152
1436
  }
1153
1437
  get m32() {
1154
- return this.#internal[6];
1438
+ return this.#internal[9];
1155
1439
  }
1156
1440
  set m32(v) {
1157
- this.#internal[6] = v;
1158
- if (!this.#isIdentity) {
1159
- if (v == 0)
1160
- this.#computeIdentity();
1161
- } else {
1162
- if (v != 0)
1163
- this.#isIdentity = false;
1164
- }
1441
+ const val = Number(v);
1442
+ this.#internal[9] = val;
1443
+ if (val !== 0)
1444
+ this.#is2D = false;
1165
1445
  }
1166
1446
  get m33() {
1167
1447
  return this.#internal[10];
1168
1448
  }
1169
1449
  set m33(v) {
1170
- this.#internal[10] = v;
1171
- if (!this.#isIdentity) {
1172
- if (v == 1)
1173
- this.#computeIdentity();
1174
- } else {
1175
- if (v != 1)
1176
- this.#isIdentity = false;
1177
- }
1450
+ const val = Number(v);
1451
+ this.#internal[10] = val;
1452
+ if (val !== 1)
1453
+ this.#is2D = false;
1178
1454
  }
1179
1455
  get m34() {
1180
- return this.#internal[14];
1456
+ return this.#internal[11];
1181
1457
  }
1182
1458
  set m34(v) {
1183
- this.#internal[14] = v;
1184
- if (!this.#isIdentity) {
1185
- if (v == 0)
1186
- this.#computeIdentity();
1187
- } else {
1188
- if (v != 0)
1189
- this.#isIdentity = false;
1190
- }
1459
+ const val = Number(v);
1460
+ this.#internal[11] = val;
1461
+ if (val !== 0)
1462
+ this.#is2D = false;
1191
1463
  }
1192
1464
  get m41() {
1193
- return this.#internal[3];
1465
+ return this.#internal[12];
1194
1466
  }
1195
1467
  set m41(v) {
1196
- this.#internal[3] = v;
1197
- if (!this.#isIdentity) {
1198
- if (v == 0)
1199
- this.#computeIdentity();
1200
- } else {
1201
- if (v != 0)
1202
- this.#isIdentity = false;
1203
- }
1468
+ this.#internal[12] = Number(v);
1204
1469
  }
1205
1470
  get m42() {
1206
- return this.#internal[7];
1471
+ return this.#internal[13];
1207
1472
  }
1208
1473
  set m42(v) {
1209
- this.#internal[7] = v;
1210
- if (!this.#isIdentity) {
1211
- if (v == 0)
1212
- this.#computeIdentity();
1213
- } else {
1214
- if (v != 0)
1215
- this.#isIdentity = false;
1216
- }
1474
+ this.#internal[13] = Number(v);
1217
1475
  }
1218
1476
  get m43() {
1219
- return this.#internal[11];
1477
+ return this.#internal[14];
1220
1478
  }
1221
1479
  set m43(v) {
1222
- this.#internal[11] = v;
1223
- if (!this.#isIdentity) {
1224
- if (v == 0)
1225
- this.#computeIdentity();
1226
- } else {
1227
- if (v != 0)
1228
- this.#isIdentity = false;
1229
- }
1480
+ const val = Number(v);
1481
+ this.#internal[14] = val;
1482
+ if (val !== 0)
1483
+ this.#is2D = false;
1230
1484
  }
1231
1485
  get m44() {
1232
1486
  return this.#internal[15];
1233
1487
  }
1234
1488
  set m44(v) {
1235
- this.#internal[15] = v;
1236
- if (!this.#isIdentity) {
1237
- if (v == 1)
1238
- this.#computeIdentity();
1239
- } else {
1240
- if (v != 1)
1241
- this.#isIdentity = false;
1489
+ const val = Number(v);
1490
+ this.#internal[15] = val;
1491
+ if (val !== 1)
1492
+ this.#is2D = false;
1493
+ }
1494
+ constructor(init) {
1495
+ f64Arrays.set(this, this.#internal);
1496
+ if (init === undefined) {
1497
+ return;
1242
1498
  }
1243
- }
1244
- multiplySelf(other) {
1245
- const a = this.#internal;
1246
- const b = other.#internal;
1247
- this.#internal.set(multipliedMatrices(a, b));
1248
- this.is2D &&= other.is2D;
1249
- return this;
1250
- }
1499
+ if (typeof init === "string") {
1500
+ this.#parseAndApplyTransformList(init, "constructor");
1501
+ return;
1502
+ }
1503
+ if (!isMatrixArray(init)) {
1504
+ throw new SyntaxError(`Failed to construct 'DOMMatrix': Failed to parse '${init}'.`);
1505
+ }
1506
+ const len = init.length;
1507
+ if (len !== 6 && len !== 16) {
1508
+ throw new TypeError(`Failed to construct 'DOMMatrix': The sequence must contain 6 elements for a 2D matrix or 16 elements for a 3D matrix.`);
1509
+ }
1510
+ if (len === 6) {
1511
+ this.#internal[0] = init[0];
1512
+ this.#internal[1] = init[1];
1513
+ this.#internal[4] = init[2];
1514
+ this.#internal[5] = init[3];
1515
+ this.#internal[12] = init[4];
1516
+ this.#internal[13] = init[5];
1517
+ this.#is2D = true;
1518
+ } else {
1519
+ for (let i = 0;i < 16; i++) {
1520
+ this.#internal[i] = init[i];
1521
+ }
1522
+ this.#is2D = false;
1523
+ }
1524
+ }
1525
+ #clone() {
1526
+ const copy = new DOMMatrix;
1527
+ copy.#internal.set(this.#internal);
1528
+ copy.#is2D = this.#is2D;
1529
+ return copy;
1530
+ }
1531
+ multiplySelf(other) {
1532
+ const otherMatrix = other instanceof DOMMatrix ? other : DOMMatrix.fromMatrix(other);
1533
+ this.#internal.set(multipliedMatrices(this.#internal, otherMatrix.#internal));
1534
+ if (!otherMatrix.is2D) {
1535
+ this.#is2D = false;
1536
+ }
1537
+ return this;
1538
+ }
1251
1539
  preMultiplySelf(other) {
1252
- const a = this.#internal;
1253
- const b = other.#internal;
1254
- this.#internal.set(multipliedMatrices(b, a));
1255
- this.is2D &&= other.is2D;
1540
+ const otherMatrix = other instanceof DOMMatrix ? other : DOMMatrix.fromMatrix(other);
1541
+ this.#internal.set(multipliedMatrices(otherMatrix.#internal, this.#internal));
1542
+ if (!otherMatrix.is2D) {
1543
+ this.#is2D = false;
1544
+ }
1256
1545
  return this;
1257
1546
  }
1258
1547
  translateSelf(tx = 0, ty = 0, tz = 0) {
1259
- const t = new Float64Array([
1260
- 1,
1261
- 0,
1262
- 0,
1263
- tx,
1264
- 0,
1265
- 1,
1266
- 0,
1267
- ty,
1268
- 0,
1269
- 0,
1270
- 1,
1271
- tz,
1272
- 0,
1273
- 0,
1274
- 0,
1275
- 1
1276
- ]);
1277
- this.#internal.set(multipliedMatrices(this.#internal, t));
1278
- if (tz !== 0)
1279
- this.is2D = false;
1548
+ this.#internal[12] += tx;
1549
+ this.#internal[13] += ty;
1550
+ this.#internal[14] += tz;
1551
+ if (tz !== 0) {
1552
+ this.#is2D = false;
1553
+ }
1280
1554
  return this;
1281
1555
  }
1282
1556
  scaleSelf(scaleX = 1, scaleY = scaleX, scaleZ = 1, originX = 0, originY = 0, originZ = 0) {
1283
- if (originX || originY || originZ)
1557
+ if (originX !== 0 || originY !== 0 || originZ !== 0) {
1284
1558
  this.translateSelf(originX, originY, originZ);
1285
- const s = new Float64Array([
1286
- scaleX,
1287
- 0,
1288
- 0,
1289
- 0,
1290
- 0,
1291
- scaleY,
1292
- 0,
1293
- 0,
1294
- 0,
1295
- 0,
1296
- scaleZ,
1297
- 0,
1298
- 0,
1299
- 0,
1300
- 0,
1301
- 1
1302
- ]);
1303
- this.#internal.set(multipliedMatrices(this.#internal, s));
1304
- if (originX || originY || originZ)
1559
+ }
1560
+ this.#internal[0] += scaleX;
1561
+ this.#internal[5] += scaleY;
1562
+ this.#internal[10] += scaleZ;
1563
+ if (originX !== 0 || originY !== 0 || originZ !== 0) {
1305
1564
  this.translateSelf(-originX, -originY, -originZ);
1306
- if (scaleZ !== 1 || originZ !== 0)
1307
- this.is2D = false;
1565
+ }
1566
+ if (scaleZ !== 1 || originZ !== 0) {
1567
+ this.#is2D = false;
1568
+ }
1308
1569
  return this;
1309
1570
  }
1310
- scale3dSelf(scale, originX = 0, originY = 0, originZ = 0) {
1571
+ scale3dSelf(scale = 1, originX = 0, originY = 0, originZ = 0) {
1311
1572
  return this.scaleSelf(scale, scale, scale, originX, originY, originZ);
1312
1573
  }
1313
- rotateSelf(...args) {
1314
- if (args[1] === undefined && args[2] === undefined) {
1315
- args[2] = args[0];
1316
- args[0] = 0;
1317
- args[1] = 0;
1574
+ rotateSelf(rotX = 0, rotY, rotZ) {
1575
+ if (rotY === undefined && rotZ === undefined) {
1576
+ rotZ = rotX;
1577
+ rotX = 0;
1578
+ rotY = 0;
1318
1579
  } else {
1319
- args[1] ??= 0;
1320
- args[2] ??= 0;
1321
- }
1322
- const rx = args[0] * Math.PI / 180;
1323
- const ry = args[1] * Math.PI / 180;
1324
- const rz = args[2] * Math.PI / 180;
1325
- const sx = Math.sin(rx), cx = Math.cos(rx);
1326
- const sy = Math.sin(ry), cy = Math.cos(ry);
1327
- const sz = Math.sin(rz), cz = Math.cos(rz);
1328
- if (args[2] !== 0) {
1580
+ rotY ??= 0;
1581
+ rotZ ??= 0;
1582
+ }
1583
+ const deg2rad = Math.PI / 180;
1584
+ if (rotZ !== 0) {
1585
+ const radZ = rotZ * deg2rad;
1586
+ const sz = Math.sin(radZ);
1587
+ const cz = Math.cos(radZ);
1329
1588
  this.#internal.set(multipliedMatrices(this.#internal, new Float64Array([
1330
1589
  cz,
1331
- -sz,
1590
+ sz,
1332
1591
  0,
1333
1592
  0,
1334
- sz,
1593
+ -sz,
1335
1594
  cz,
1336
1595
  0,
1337
1596
  0,
@@ -1345,17 +1604,20 @@ class DOMMatrix {
1345
1604
  1
1346
1605
  ])));
1347
1606
  }
1348
- if (args[1] !== 0) {
1349
- this.#internal.set(multipliedMatrices(new Float64Array([
1607
+ if (rotY !== 0) {
1608
+ const radY = rotY * deg2rad;
1609
+ const sy = Math.sin(radY);
1610
+ const cy = Math.cos(radY);
1611
+ this.#internal.set(multipliedMatrices(this.#internal, new Float64Array([
1350
1612
  cy,
1351
1613
  0,
1352
- sy,
1614
+ -sy,
1353
1615
  0,
1354
1616
  0,
1355
1617
  1,
1356
1618
  0,
1357
1619
  0,
1358
- -sy,
1620
+ sy,
1359
1621
  0,
1360
1622
  cy,
1361
1623
  0,
@@ -1363,36 +1625,41 @@ class DOMMatrix {
1363
1625
  0,
1364
1626
  0,
1365
1627
  1
1366
- ]), this.#internal));
1628
+ ])));
1367
1629
  }
1368
- if (args[0] !== 0) {
1369
- this.#internal.set(multipliedMatrices(new Float64Array([
1630
+ if (rotX !== 0) {
1631
+ const radX = rotX * deg2rad;
1632
+ const sx = Math.sin(radX);
1633
+ const cx = Math.cos(radX);
1634
+ this.#internal.set(multipliedMatrices(this.#internal, new Float64Array([
1370
1635
  1,
1371
1636
  0,
1372
1637
  0,
1373
1638
  0,
1374
1639
  0,
1375
1640
  cx,
1376
- -sx,
1641
+ sx,
1377
1642
  0,
1378
1643
  0,
1379
- sx,
1644
+ -sx,
1380
1645
  cx,
1381
1646
  0,
1382
1647
  0,
1383
1648
  0,
1384
1649
  0,
1385
1650
  1
1386
- ]), this.#internal));
1651
+ ])));
1652
+ }
1653
+ if (rotX !== 0 || rotY !== 0) {
1654
+ this.#is2D = false;
1387
1655
  }
1388
- if (args[0] !== 0 || args[1] !== 0)
1389
- this.is2D = false;
1390
1656
  return this;
1391
1657
  }
1392
1658
  rotateAxisAngleSelf(x = 0, y = 0, z = 1, angle = 0) {
1393
1659
  const length = Math.hypot(x, y, z);
1394
- if (length === 0)
1660
+ if (length === 0) {
1395
1661
  return this;
1662
+ }
1396
1663
  x /= length;
1397
1664
  y /= length;
1398
1665
  z /= length;
@@ -1402,15 +1669,15 @@ class DOMMatrix {
1402
1669
  const t = 1 - c;
1403
1670
  const r = new Float64Array([
1404
1671
  t * x * x + c,
1405
- t * x * y - s * z,
1406
- t * x * z + s * y,
1407
- 0,
1408
1672
  t * x * y + s * z,
1409
- t * y * y + c,
1410
- t * y * z - s * x,
1411
- 0,
1412
1673
  t * x * z - s * y,
1674
+ 0,
1675
+ t * x * y - s * z,
1676
+ t * y * y + c,
1413
1677
  t * y * z + s * x,
1678
+ 0,
1679
+ t * x * z + s * y,
1680
+ t * y * z - s * x,
1414
1681
  t * z * z + c,
1415
1682
  0,
1416
1683
  0,
@@ -1419,24 +1686,26 @@ class DOMMatrix {
1419
1686
  1
1420
1687
  ]);
1421
1688
  this.#internal.set(multipliedMatrices(this.#internal, r));
1422
- if (x !== 0 || y !== 0)
1423
- this.is2D = false;
1689
+ if (x !== 0 || y !== 0) {
1690
+ this.#is2D = false;
1691
+ }
1424
1692
  return this;
1425
1693
  }
1426
1694
  rotateFromVectorSelf(x = 0, y = 0) {
1427
- if (x === 0 && y === 0)
1695
+ if (x === 0 && y === 0) {
1428
1696
  return this;
1697
+ }
1429
1698
  const angle = Math.atan2(y, x) * 180 / Math.PI;
1430
- return this.rotateSelf(angle);
1699
+ return this.rotateSelf(0, 0, angle);
1431
1700
  }
1432
1701
  skewXSelf(sx = 0) {
1433
1702
  const t = Math.tan(sx * Math.PI / 180);
1434
1703
  this.#internal.set(multipliedMatrices(this.#internal, new Float64Array([
1435
1704
  1,
1436
- t,
1437
1705
  0,
1438
1706
  0,
1439
1707
  0,
1708
+ t,
1440
1709
  1,
1441
1710
  0,
1442
1711
  0,
@@ -1455,10 +1724,10 @@ class DOMMatrix {
1455
1724
  const t = Math.tan(sy * Math.PI / 180);
1456
1725
  this.#internal.set(multipliedMatrices(this.#internal, new Float64Array([
1457
1726
  1,
1727
+ t,
1458
1728
  0,
1459
1729
  0,
1460
1730
  0,
1461
- t,
1462
1731
  1,
1463
1732
  0,
1464
1733
  0,
@@ -1473,6 +1742,173 @@ class DOMMatrix {
1473
1742
  ])));
1474
1743
  return this;
1475
1744
  }
1745
+ invertSelf() {
1746
+ const m = this.#internal;
1747
+ const m00 = m[0], m01 = m[4], m02 = m[8], m03 = m[12];
1748
+ const m10 = m[1], m11 = m[5], m12 = m[9], m13 = m[13];
1749
+ const m20 = m[2], m21 = m[6], m22 = m[10], m23 = m[14];
1750
+ const m30 = m[3], m31 = m[7], m32 = m[11], m33 = m[15];
1751
+ const b00 = m00 * m11 - m10 * m01;
1752
+ const b01 = m00 * m21 - m20 * m01;
1753
+ const b02 = m00 * m31 - m30 * m01;
1754
+ const b03 = m10 * m21 - m20 * m11;
1755
+ const b04 = m10 * m31 - m30 * m11;
1756
+ const b05 = m20 * m31 - m30 * m21;
1757
+ const b06 = m02 * m13 - m12 * m03;
1758
+ const b07 = m02 * m23 - m22 * m03;
1759
+ const b08 = m02 * m33 - m32 * m03;
1760
+ const b09 = m12 * m23 - m22 * m13;
1761
+ const b10 = m12 * m33 - m32 * m13;
1762
+ const b11 = m22 * m33 - m32 * m23;
1763
+ const det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
1764
+ if (!det || !Number.isFinite(det)) {
1765
+ this.#internal.fill(NaN);
1766
+ this.#is2D = false;
1767
+ return this;
1768
+ }
1769
+ const invDet = 1 / det;
1770
+ m[0] = (m11 * b11 - m21 * b10 + m31 * b09) * invDet;
1771
+ m[1] = (m20 * b10 - m10 * b11 - m30 * b09) * invDet;
1772
+ m[2] = (m13 * b05 - m23 * b04 + m33 * b03) * invDet;
1773
+ m[3] = (m22 * b04 - m12 * b05 - m32 * b03) * invDet;
1774
+ m[4] = (m21 * b08 - m01 * b11 - m31 * b07) * invDet;
1775
+ m[5] = (m00 * b11 - m20 * b08 + m30 * b07) * invDet;
1776
+ m[6] = (m23 * b02 - m03 * b05 - m33 * b01) * invDet;
1777
+ m[7] = (m02 * b05 - m22 * b02 + m32 * b01) * invDet;
1778
+ m[8] = (m01 * b10 - m11 * b08 + m31 * b06) * invDet;
1779
+ m[9] = (m10 * b08 - m00 * b10 - m30 * b06) * invDet;
1780
+ m[10] = (m03 * b04 - m13 * b02 + m33 * b00) * invDet;
1781
+ m[11] = (m12 * b02 - m02 * b04 - m32 * b00) * invDet;
1782
+ m[12] = (m11 * b07 - m01 * b09 - m21 * b06) * invDet;
1783
+ m[13] = (m00 * b09 - m10 * b07 + m20 * b06) * invDet;
1784
+ m[14] = (m13 * b01 - m03 * b03 - m23 * b00) * invDet;
1785
+ m[15] = (m02 * b03 - m12 * b01 + m22 * b00) * invDet;
1786
+ return this;
1787
+ }
1788
+ translate(tx = 0, ty = 0, tz = 0) {
1789
+ return this.#clone().translateSelf(tx, ty, tz);
1790
+ }
1791
+ scale(scaleX = 1, scaleY = scaleX, scaleZ = 1, originX = 0, originY = 0, originZ = 0) {
1792
+ return this.#clone().scaleSelf(scaleX, scaleY, scaleZ, originX, originY, originZ);
1793
+ }
1794
+ scale3d(scale = 1, originX = 0, originY = 0, originZ = 0) {
1795
+ return this.#clone().scale3dSelf(scale, originX, originY, originZ);
1796
+ }
1797
+ scaleNonUniform(scaleX = 1, scaleY = 1) {
1798
+ return this.#clone().scaleSelf(scaleX, scaleY, 1, 0, 0, 0);
1799
+ }
1800
+ rotate(rotX = 0, rotY, rotZ) {
1801
+ return this.#clone().rotateSelf(rotX, rotY, rotZ);
1802
+ }
1803
+ rotateAxisAngle(x = 0, y = 0, z = 1, angle = 0) {
1804
+ return this.#clone().rotateAxisAngleSelf(x, y, z, angle);
1805
+ }
1806
+ rotateFromVector(x = 0, y = 0) {
1807
+ return this.#clone().rotateFromVectorSelf(x, y);
1808
+ }
1809
+ skewX(sx = 0) {
1810
+ return this.#clone().skewXSelf(sx);
1811
+ }
1812
+ skewY(sy = 0) {
1813
+ return this.#clone().skewYSelf(sy);
1814
+ }
1815
+ multiply(other) {
1816
+ return this.#clone().multiplySelf(other);
1817
+ }
1818
+ flipX() {
1819
+ const copy = this.#clone();
1820
+ copy.#internal.set(multipliedMatrices(copy.#internal, new Float64Array([
1821
+ -1,
1822
+ 0,
1823
+ 0,
1824
+ 0,
1825
+ 0,
1826
+ 1,
1827
+ 0,
1828
+ 0,
1829
+ 0,
1830
+ 0,
1831
+ 1,
1832
+ 0,
1833
+ 0,
1834
+ 0,
1835
+ 0,
1836
+ 1
1837
+ ])));
1838
+ return copy;
1839
+ }
1840
+ flipY() {
1841
+ const copy = this.#clone();
1842
+ copy.#internal.set(multipliedMatrices(copy.#internal, new Float64Array([
1843
+ 1,
1844
+ 0,
1845
+ 0,
1846
+ 0,
1847
+ 0,
1848
+ -1,
1849
+ 0,
1850
+ 0,
1851
+ 0,
1852
+ 0,
1853
+ 1,
1854
+ 0,
1855
+ 0,
1856
+ 0,
1857
+ 0,
1858
+ 1
1859
+ ])));
1860
+ return copy;
1861
+ }
1862
+ inverse() {
1863
+ return this.#clone().invertSelf();
1864
+ }
1865
+ transformPoint(point) {
1866
+ const x = point?.x ?? 0;
1867
+ const y = point?.y ?? 0;
1868
+ const z = point?.z ?? 0;
1869
+ const w = point?.w ?? 1;
1870
+ const m = this.#internal;
1871
+ return {
1872
+ x: m[0] * x + m[4] * y + m[8] * z + m[12] * w,
1873
+ y: m[1] * x + m[5] * y + m[9] * z + m[13] * w,
1874
+ z: m[2] * x + m[6] * y + m[10] * z + m[14] * w,
1875
+ w: m[3] * x + m[7] * y + m[11] * z + m[15] * w
1876
+ };
1877
+ }
1878
+ toFloat32Array() {
1879
+ return new Float32Array(this.#internal);
1880
+ }
1881
+ toFloat64Array() {
1882
+ return new Float64Array(this.#internal);
1883
+ }
1884
+ toJSON() {
1885
+ return {
1886
+ a: this.a,
1887
+ b: this.b,
1888
+ c: this.c,
1889
+ d: this.d,
1890
+ e: this.e,
1891
+ f: this.f,
1892
+ m11: this.m11,
1893
+ m12: this.m12,
1894
+ m13: this.m13,
1895
+ m14: this.m14,
1896
+ m21: this.m21,
1897
+ m22: this.m22,
1898
+ m23: this.m23,
1899
+ m24: this.m24,
1900
+ m31: this.m31,
1901
+ m32: this.m32,
1902
+ m33: this.m33,
1903
+ m34: this.m34,
1904
+ m41: this.m41,
1905
+ m42: this.m42,
1906
+ m43: this.m43,
1907
+ m44: this.m44,
1908
+ is2D: this.is2D,
1909
+ isIdentity: this.isIdentity
1910
+ };
1911
+ }
1476
1912
  #parseTransformList(value) {
1477
1913
  const transforms = [];
1478
1914
  let i = 0;
@@ -1482,13 +1918,12 @@ class DOMMatrix {
1482
1918
  if (i >= value.length)
1483
1919
  break;
1484
1920
  const nameStart = i;
1485
- while (/[A-Za-z0-9]/.test(value[i]))
1921
+ while (/[A-Za-z0-9-]/.test(value[i]))
1486
1922
  i++;
1487
1923
  const name = value.substring(nameStart, i);
1488
- while (/\s/.test(value[i]))
1489
- i++;
1490
- if (value[i] !== "(")
1924
+ if (!name || value[i] !== "(") {
1491
1925
  return "error";
1926
+ }
1492
1927
  i++;
1493
1928
  let depth = 1;
1494
1929
  const argsStart = i;
@@ -1509,265 +1944,392 @@ class DOMMatrix {
1509
1944
  return transforms;
1510
1945
  }
1511
1946
  #splitArguments(args) {
1512
- const result = [];
1513
- let current = "";
1514
- let depth = 0;
1515
- for (const c of args) {
1516
- if (c === "(")
1517
- depth++;
1518
- if (c === ")")
1519
- depth--;
1520
- if ((c === "," || /\s/.test(c)) && depth === 0) {
1521
- if (current.length) {
1522
- result.push(current);
1523
- current = "";
1524
- }
1525
- continue;
1526
- }
1527
- current += c;
1947
+ const trimmed = args.trim();
1948
+ if (!trimmed)
1949
+ return [];
1950
+ if (trimmed.startsWith(",") || trimmed.endsWith(",") || /,\s*,/.test(trimmed)) {
1951
+ return null;
1528
1952
  }
1529
- if (current.length)
1530
- result.push(current);
1531
- return result;
1953
+ return trimmed.split(/\s*,\s*/);
1954
+ }
1955
+ #parseNumber(value) {
1956
+ if (!CSS_NUMBER_RE.test(value))
1957
+ return null;
1958
+ const n = Number.parseFloat(value);
1959
+ return Number.isFinite(n) ? n : null;
1532
1960
  }
1533
1961
  #parseAngle(value) {
1534
- if (value.endsWith("deg"))
1535
- return Number.parseFloat(value);
1536
- if (value.endsWith("rad"))
1537
- return Number.parseFloat(value) * 180 / Math.PI;
1538
- if (value.endsWith("grad"))
1539
- return Number.parseFloat(value) * 0.9;
1540
- if (value.endsWith("turn"))
1541
- return Number.parseFloat(value) * 360;
1542
- return Number.parseFloat(value);
1962
+ if (CSS_NUMBER_RE.test(value)) {
1963
+ const n = Number.parseFloat(value);
1964
+ return n === 0 ? 0 : null;
1965
+ }
1966
+ const match = CSS_DIM_RE.exec(value);
1967
+ if (!match)
1968
+ return null;
1969
+ const num = Number.parseFloat(match[1]);
1970
+ if (!Number.isFinite(num))
1971
+ return null;
1972
+ switch (match[2].toLowerCase()) {
1973
+ case "deg":
1974
+ return num;
1975
+ case "rad":
1976
+ return num * 180 / Math.PI;
1977
+ case "grad":
1978
+ return num * 0.9;
1979
+ case "turn":
1980
+ return num * 360;
1981
+ default:
1982
+ return null;
1983
+ }
1543
1984
  }
1544
1985
  #parseLength(value) {
1545
1986
  if (!value)
1546
1987
  return null;
1988
+ if (CSS_NUMBER_RE.test(value)) {
1989
+ const n = Number.parseFloat(value);
1990
+ return n === 0 ? 0 : null;
1991
+ }
1992
+ const match = CSS_DIM_RE.exec(value);
1993
+ if (!match)
1994
+ return null;
1995
+ const num = Number.parseFloat(match[1]);
1996
+ if (!Number.isFinite(num))
1997
+ return null;
1547
1998
  const rootFontSize = 16;
1548
1999
  const parentFontSize = 16;
1549
2000
  const exSize = 8;
1550
2001
  const chSize = 8;
1551
- if (value.endsWith("px"))
1552
- return Number.parseFloat(value);
1553
- if (value.endsWith("pt"))
1554
- return Number.parseFloat(value) * 1.3333333730697632;
1555
- if (value.endsWith("pc"))
1556
- return Number.parseFloat(value) * 16;
1557
- if (value.endsWith("in"))
1558
- return Number.parseFloat(value) * 96;
1559
- if (value.endsWith("cm"))
1560
- return Number.parseFloat(value) * 37.79527559055118;
1561
- if (value.endsWith("mm"))
1562
- return Number.parseFloat(value) * 3.7795275590551185;
1563
- if (value.endsWith("q"))
1564
- return Number.parseFloat(value) * 0.9448818897637796;
1565
- if (value.endsWith("em"))
1566
- return Number.parseFloat(value) * parentFontSize;
1567
- if (value.endsWith("rem"))
1568
- return Number.parseFloat(value) * rootFontSize;
1569
- if (value.endsWith("ex"))
1570
- return Number.parseFloat(value) * exSize;
1571
- if (value.endsWith("ch"))
1572
- return Number.parseFloat(value) * chSize;
1573
- if (value.endsWith("%"))
1574
- return Number.parseFloat(value) * parentFontSize / 100;
1575
- if (value.endsWith("px")) {
1576
- return Number.parseFloat(value);
1577
- } else if (value.endsWith("pt")) {
1578
- return Number.parseFloat(value) * 1.3333333730697632;
1579
- }
1580
- return null;
2002
+ switch (match[2].toLowerCase()) {
2003
+ case "px":
2004
+ return num;
2005
+ case "pt":
2006
+ return num * (96 / 72);
2007
+ case "pc":
2008
+ return num * 16;
2009
+ case "in":
2010
+ return num * 96;
2011
+ case "cm":
2012
+ return num * (96 / 2.54);
2013
+ case "mm":
2014
+ return num * (96 / 25.4);
2015
+ case "q":
2016
+ return num * (96 / 101.6);
2017
+ case "em":
2018
+ return num * parentFontSize;
2019
+ case "rem":
2020
+ return num * rootFontSize;
2021
+ case "ex":
2022
+ return num * exSize;
2023
+ case "ch":
2024
+ return num * chSize;
2025
+ default:
2026
+ return null;
2027
+ }
1581
2028
  }
1582
- setMatrixValue(value) {
1583
- value = value.trim();
1584
- if (value.length === 0)
1585
- throw new DOMException("Invalid transform.", "SyntaxError");
2029
+ #throwParseOrConstructError(caller, raw) {
2030
+ if (caller === "constructor") {
2031
+ throw new SyntaxError(`Failed to construct 'DOMMatrix': Failed to parse '${raw}'.`);
2032
+ }
2033
+ throwParseErrorDMatrix("setMatrixValue", raw);
2034
+ }
2035
+ #parseAndApplyTransformList(rawInput, caller) {
2036
+ const value = rawInput.trim();
2037
+ if (value === "" || value.toLowerCase() === "none") {
2038
+ this.#internal.set([
2039
+ 1,
2040
+ 0,
2041
+ 0,
2042
+ 0,
2043
+ 0,
2044
+ 1,
2045
+ 0,
2046
+ 0,
2047
+ 0,
2048
+ 0,
2049
+ 1,
2050
+ 0,
2051
+ 0,
2052
+ 0,
2053
+ 0,
2054
+ 1
2055
+ ]);
2056
+ this.#is2D = true;
2057
+ return this;
2058
+ }
1586
2059
  const transforms = this.#parseTransformList(value);
1587
- if (transforms == "error") {
1588
- throwParseErrorDMatrix("setMatrixValue", value);
1589
- return;
2060
+ if (transforms === "error" || transforms.length === 0) {
2061
+ this.#throwParseOrConstructError(caller, rawInput);
1590
2062
  }
2063
+ const temp = new DOMMatrix;
1591
2064
  for (const transform of transforms) {
1592
2065
  const args = this.#splitArguments(transform.args);
1593
- switch (transform.name) {
2066
+ if (!args) {
2067
+ this.#throwParseOrConstructError(caller, rawInput);
2068
+ }
2069
+ switch (transform.name.toLowerCase()) {
1594
2070
  case "matrix": {
1595
- if (args.length !== 6)
1596
- throw new DOMException("matrix() requires 6 arguments.", "SyntaxError");
1597
- let a = Number.parseFloat(args[0]);
1598
- let b = Number.parseFloat(args[1]);
1599
- let c = Number.parseFloat(args[2]);
1600
- let d = Number.parseFloat(args[3]);
1601
- if (isNaN(a) || isNaN(b) || isNaN(c) || isNaN(d))
1602
- throwParseErrorDMatrix("setMatrixValue", value);
1603
- this.a = a;
1604
- this.b = b;
1605
- this.c = c;
1606
- this.d = d;
1607
- this.e = this.#parseLength(args[4]);
1608
- this.f = this.#parseLength(args[5]);
1609
- this.is2D = true;
2071
+ if (args.length !== 6) {
2072
+ this.#throwParseOrConstructError(caller, rawInput);
2073
+ }
2074
+ const nums = args.map((arg) => this.#parseNumber(arg));
2075
+ if (nums.some((n) => n === null)) {
2076
+ this.#throwParseOrConstructError(caller, rawInput);
2077
+ }
2078
+ const [a, b, c, d, e, f] = nums;
2079
+ temp.multiplySelf(new DOMMatrix([a, b, c, d, e, f]));
1610
2080
  break;
1611
2081
  }
1612
2082
  case "matrix3d": {
1613
- if (args.length !== 16)
1614
- throwParseErrorDMatrix("setMatrixValue", value);
1615
- for (let i = 0;i < 16; i++)
1616
- this.#internal[i] = Number.parseFloat(args[i]);
1617
- this.is2D = false;
2083
+ if (args.length !== 16) {
2084
+ this.#throwParseOrConstructError(caller, rawInput);
2085
+ }
2086
+ const nums = args.map((arg) => this.#parseNumber(arg));
2087
+ if (nums.some((n) => n === null)) {
2088
+ this.#throwParseOrConstructError(caller, rawInput);
2089
+ }
2090
+ temp.multiplySelf(new DOMMatrix(nums));
1618
2091
  break;
1619
2092
  }
1620
2093
  case "translate": {
1621
- if (args.length < 1 || args.length > 2)
1622
- throwParseErrorDMatrix("setMatrixValue", value);
1623
- let lx = this.#parseLength(args[0]);
1624
- let ly = this.#parseLength(args[1]);
1625
- if (!lx) {
1626
- throwParseErrorDMatrix("setMatrixValue", value);
1627
- return;
2094
+ if (args.length < 1 || args.length > 2) {
2095
+ this.#throwParseOrConstructError(caller, rawInput);
2096
+ }
2097
+ const tx = this.#parseLength(args[0]);
2098
+ const ty = args.length === 2 ? this.#parseLength(args[1]) : 0;
2099
+ if (tx === null || ty === null) {
2100
+ this.#throwParseOrConstructError(caller, rawInput);
1628
2101
  }
1629
- const tx = lx;
1630
- const ty = args.length === 2 ? ly ?? 0 : 0;
1631
- this.translateSelf(tx, ty);
2102
+ temp.translateSelf(tx, ty, 0);
1632
2103
  break;
1633
2104
  }
1634
- case "translateX": {
1635
- if (args.length !== 1)
1636
- throwParseErrorDMatrix("setMatrixValue", value);
1637
- let l = this.#parseLength(args[0]);
1638
- if (!l) {
1639
- throwParseErrorDMatrix("setMatrixValue", value);
1640
- return;
2105
+ case "translatex": {
2106
+ if (args.length !== 1) {
2107
+ this.#throwParseOrConstructError(caller, rawInput);
1641
2108
  }
1642
- this.translateSelf(l, 0);
2109
+ const tx = this.#parseLength(args[0]);
2110
+ if (tx === null) {
2111
+ this.#throwParseOrConstructError(caller, rawInput);
2112
+ }
2113
+ temp.translateSelf(tx, 0, 0);
1643
2114
  break;
1644
2115
  }
1645
- case "translateY": {
1646
- if (args.length !== 1)
1647
- throwParseErrorDMatrix("setMatrixValue", value);
1648
- let l = this.#parseLength(args[0]);
1649
- if (!l) {
1650
- throwParseErrorDMatrix("setMatrixValue", value);
1651
- return;
2116
+ case "translatey": {
2117
+ if (args.length !== 1) {
2118
+ this.#throwParseOrConstructError(caller, rawInput);
2119
+ }
2120
+ const ty = this.#parseLength(args[0]);
2121
+ if (ty === null) {
2122
+ this.#throwParseOrConstructError(caller, rawInput);
1652
2123
  }
1653
- this.translateSelf(0, l);
2124
+ temp.translateSelf(0, ty, 0);
1654
2125
  break;
1655
2126
  }
1656
- case "translateZ": {
1657
- if (args.length !== 1)
1658
- throwParseErrorDMatrix("setMatrixValue", value);
1659
- let l = this.#parseLength(args[0]);
1660
- if (!l) {
1661
- throwParseErrorDMatrix("setMatrixValue", value);
1662
- return;
2127
+ case "translatez": {
2128
+ if (args.length !== 1) {
2129
+ this.#throwParseOrConstructError(caller, rawInput);
1663
2130
  }
1664
- this.translateSelf(0, 0, l);
2131
+ const tz = this.#parseLength(args[0]);
2132
+ if (tz === null) {
2133
+ this.#throwParseOrConstructError(caller, rawInput);
2134
+ }
2135
+ temp.translateSelf(0, 0, tz);
1665
2136
  break;
1666
2137
  }
1667
2138
  case "translate3d": {
1668
- if (args.length !== 3)
1669
- throwParseErrorDMatrix("setMatrixValue", value);
1670
- let la = this.#parseLength(args[0]);
1671
- let lb = this.#parseLength(args[0]);
1672
- let lc = this.#parseLength(args[0]);
1673
- if (!la || !lb || !lc) {
1674
- throwParseErrorDMatrix("setMatrixValue", value);
1675
- return;
2139
+ if (args.length !== 3) {
2140
+ this.#throwParseOrConstructError(caller, rawInput);
2141
+ }
2142
+ const tx = this.#parseLength(args[0]);
2143
+ const ty = this.#parseLength(args[1]);
2144
+ const tz = this.#parseLength(args[2]);
2145
+ if (tx === null || ty === null || tz === null) {
2146
+ this.#throwParseOrConstructError(caller, rawInput);
1676
2147
  }
1677
- this.translateSelf(la, lb, lc);
2148
+ temp.translateSelf(tx, ty, tz);
1678
2149
  break;
1679
2150
  }
1680
2151
  case "scale": {
1681
- if (args.length < 1 || args.length > 2)
1682
- throwParseErrorDMatrix("setMatrixValue", value);
1683
- const sx = Number.parseFloat(args[0]);
1684
- const sy = args.length === 2 ? Number.parseFloat(args[1]) : sx;
1685
- this.scaleSelf(sx, sy);
2152
+ if (args.length < 1 || args.length > 2) {
2153
+ this.#throwParseOrConstructError(caller, rawInput);
2154
+ }
2155
+ const sx = this.#parseNumber(args[0]);
2156
+ const sy = args.length === 2 ? this.#parseNumber(args[1]) : sx;
2157
+ if (sx === null || sy === null) {
2158
+ this.#throwParseOrConstructError(caller, rawInput);
2159
+ }
2160
+ temp.scaleSelf(sx, sy, 1);
1686
2161
  break;
1687
2162
  }
1688
- case "scaleX": {
1689
- if (args.length !== 1)
1690
- throwParseErrorDMatrix("setMatrixValue", value);
1691
- this.scaleSelf(Number.parseFloat(args[0]), 1);
2163
+ case "scalex": {
2164
+ if (args.length !== 1) {
2165
+ this.#throwParseOrConstructError(caller, rawInput);
2166
+ }
2167
+ const sx = this.#parseNumber(args[0]);
2168
+ if (sx === null) {
2169
+ this.#throwParseOrConstructError(caller, rawInput);
2170
+ }
2171
+ temp.scaleSelf(sx, 1, 1);
1692
2172
  break;
1693
2173
  }
1694
- case "scaleY": {
1695
- if (args.length !== 1)
1696
- throwParseErrorDMatrix("setMatrixValue", value);
1697
- this.scaleSelf(1, Number.parseFloat(args[0]));
2174
+ case "scaley": {
2175
+ if (args.length !== 1) {
2176
+ this.#throwParseOrConstructError(caller, rawInput);
2177
+ }
2178
+ const sy = this.#parseNumber(args[0]);
2179
+ if (sy === null) {
2180
+ this.#throwParseOrConstructError(caller, rawInput);
2181
+ }
2182
+ temp.scaleSelf(1, sy, 1);
1698
2183
  break;
1699
2184
  }
1700
- case "scaleZ": {
1701
- if (args.length !== 1)
1702
- throwParseErrorDMatrix("setMatrixValue", value);
1703
- this.scaleSelf(1, 1, Number.parseFloat(args[0]));
2185
+ case "scalez": {
2186
+ if (args.length !== 1) {
2187
+ this.#throwParseOrConstructError(caller, rawInput);
2188
+ }
2189
+ const sz = this.#parseNumber(args[0]);
2190
+ if (sz === null) {
2191
+ this.#throwParseOrConstructError(caller, rawInput);
2192
+ }
2193
+ temp.scaleSelf(1, 1, sz);
1704
2194
  break;
1705
2195
  }
1706
2196
  case "scale3d": {
1707
- if (args.length !== 3)
1708
- throwParseErrorDMatrix("setMatrixValue", value);
1709
- this.scale3dSelf(Number.parseFloat(args[0]), Number.parseFloat(args[1]), Number.parseFloat(args[2]));
2197
+ if (args.length !== 3) {
2198
+ this.#throwParseOrConstructError(caller, rawInput);
2199
+ }
2200
+ const sx = this.#parseNumber(args[0]);
2201
+ const sy = this.#parseNumber(args[1]);
2202
+ const sz = this.#parseNumber(args[2]);
2203
+ if (sx === null || sy === null || sz === null) {
2204
+ this.#throwParseOrConstructError(caller, rawInput);
2205
+ }
2206
+ temp.scaleSelf(sx, sy, sz);
1710
2207
  break;
1711
2208
  }
1712
2209
  case "rotate": {
1713
- if (args.length !== 1)
1714
- throwParseErrorDMatrix("setMatrixValue", value);
1715
- this.rotateSelf(this.#parseAngle(args[0]));
2210
+ if (args.length !== 1) {
2211
+ this.#throwParseOrConstructError(caller, rawInput);
2212
+ }
2213
+ const angle = this.#parseAngle(args[0]);
2214
+ if (angle === null) {
2215
+ this.#throwParseOrConstructError(caller, rawInput);
2216
+ }
2217
+ temp.rotateSelf(0, 0, angle);
1716
2218
  break;
1717
2219
  }
1718
- case "rotateX": {
1719
- if (args.length !== 1)
1720
- throwParseErrorDMatrix("setMatrixValue", value);
1721
- this.rotateSelf(this.#parseAngle(args[0]), 0, 0);
2220
+ case "rotatex": {
2221
+ if (args.length !== 1) {
2222
+ this.#throwParseOrConstructError(caller, rawInput);
2223
+ }
2224
+ const angle = this.#parseAngle(args[0]);
2225
+ if (angle === null) {
2226
+ this.#throwParseOrConstructError(caller, rawInput);
2227
+ }
2228
+ temp.rotateSelf(angle, 0, 0);
1722
2229
  break;
1723
2230
  }
1724
- case "rotateY": {
1725
- if (args.length !== 1)
1726
- throwParseErrorDMatrix("setMatrixValue", value);
1727
- this.rotateSelf(0, this.#parseAngle(args[0]), 0);
2231
+ case "rotatey": {
2232
+ if (args.length !== 1) {
2233
+ this.#throwParseOrConstructError(caller, rawInput);
2234
+ }
2235
+ const angle = this.#parseAngle(args[0]);
2236
+ if (angle === null) {
2237
+ this.#throwParseOrConstructError(caller, rawInput);
2238
+ }
2239
+ temp.rotateSelf(0, angle, 0);
1728
2240
  break;
1729
2241
  }
1730
- case "rotateZ": {
1731
- if (args.length !== 1)
1732
- throwParseErrorDMatrix("setMatrixValue", value);
1733
- this.rotateSelf(0, 0, this.#parseAngle(args[0]));
2242
+ case "rotatez": {
2243
+ if (args.length !== 1) {
2244
+ this.#throwParseOrConstructError(caller, rawInput);
2245
+ }
2246
+ const angle = this.#parseAngle(args[0]);
2247
+ if (angle === null) {
2248
+ this.#throwParseOrConstructError(caller, rawInput);
2249
+ }
2250
+ temp.rotateSelf(0, 0, angle);
1734
2251
  break;
1735
2252
  }
1736
2253
  case "rotate3d": {
1737
- if (args.length !== 4)
1738
- throwParseErrorDMatrix("setMatrixValue", value);
1739
- this.rotateAxisAngleSelf(Number.parseFloat(args[0]), Number.parseFloat(args[1]), Number.parseFloat(args[2]), this.#parseAngle(args[3]));
2254
+ if (args.length !== 4) {
2255
+ this.#throwParseOrConstructError(caller, rawInput);
2256
+ }
2257
+ const x = this.#parseNumber(args[0]);
2258
+ const y = this.#parseNumber(args[1]);
2259
+ const z = this.#parseNumber(args[2]);
2260
+ const angle = this.#parseAngle(args[3]);
2261
+ if (x === null || y === null || z === null || angle === null) {
2262
+ this.#throwParseOrConstructError(caller, rawInput);
2263
+ }
2264
+ temp.rotateAxisAngleSelf(x, y, z, angle);
1740
2265
  break;
1741
2266
  }
1742
2267
  case "skew": {
1743
- if (args.length < 1 || args.length > 2)
1744
- throwParseErrorDMatrix("setMatrixValue", value);
1745
- this.skewXSelf(this.#parseAngle(args[0]));
1746
- if (args.length === 2)
1747
- this.skewYSelf(this.#parseAngle(args[1]));
2268
+ if (args.length < 1 || args.length > 2) {
2269
+ this.#throwParseOrConstructError(caller, rawInput);
2270
+ }
2271
+ const ax = this.#parseAngle(args[0]);
2272
+ const ay = args.length === 2 ? this.#parseAngle(args[1]) : 0;
2273
+ if (ax === null || ay === null) {
2274
+ this.#throwParseOrConstructError(caller, rawInput);
2275
+ }
2276
+ const tx = Math.tan(ax * Math.PI / 180);
2277
+ const ty = Math.tan(ay * Math.PI / 180);
2278
+ temp.#internal.set(multipliedMatrices(temp.#internal, new Float64Array([
2279
+ 1,
2280
+ ty,
2281
+ 0,
2282
+ 0,
2283
+ tx,
2284
+ 1,
2285
+ 0,
2286
+ 0,
2287
+ 0,
2288
+ 0,
2289
+ 1,
2290
+ 0,
2291
+ 0,
2292
+ 0,
2293
+ 0,
2294
+ 1
2295
+ ])));
1748
2296
  break;
1749
2297
  }
1750
- case "skewX": {
1751
- if (args.length !== 1)
1752
- throwParseErrorDMatrix("setMatrixValue", value);
1753
- this.skewXSelf(this.#parseAngle(args[0]));
2298
+ case "skewx": {
2299
+ if (args.length !== 1) {
2300
+ this.#throwParseOrConstructError(caller, rawInput);
2301
+ }
2302
+ const ax = this.#parseAngle(args[0]);
2303
+ if (ax === null) {
2304
+ this.#throwParseOrConstructError(caller, rawInput);
2305
+ }
2306
+ temp.skewXSelf(ax);
1754
2307
  break;
1755
2308
  }
1756
- case "skewY": {
1757
- if (args.length !== 1)
1758
- throwParseErrorDMatrix("setMatrixValue", value);
1759
- this.skewYSelf(this.#parseAngle(args[0]));
2309
+ case "skewy": {
2310
+ if (args.length !== 1) {
2311
+ this.#throwParseOrConstructError(caller, rawInput);
2312
+ }
2313
+ const ay = this.#parseAngle(args[0]);
2314
+ if (ay === null) {
2315
+ this.#throwParseOrConstructError(caller, rawInput);
2316
+ }
2317
+ temp.skewYSelf(ay);
1760
2318
  break;
1761
2319
  }
1762
2320
  case "perspective": {
1763
- if (args.length !== 1)
1764
- throwParseErrorDMatrix("setMatrixValue", value);
2321
+ if (args.length !== 1) {
2322
+ this.#throwParseOrConstructError(caller, rawInput);
2323
+ }
2324
+ if (args[0].toLowerCase() === "none") {
2325
+ break;
2326
+ }
1765
2327
  const d = this.#parseLength(args[0]);
1766
- if (d === 0 || !d) {
1767
- throwParseErrorDMatrix("setMatrixValue", value);
1768
- return;
2328
+ if (d === null || d < 0) {
2329
+ this.#throwParseOrConstructError(caller, rawInput);
1769
2330
  }
1770
- this.#internal.set(multipliedMatrices(this.#internal, new Float64Array([
2331
+ const m34 = d === 0 ? -Infinity : -1 / d;
2332
+ temp.#internal.set(multipliedMatrices(temp.#internal, new Float64Array([
1771
2333
  1,
1772
2334
  0,
1773
2335
  0,
@@ -1779,51 +2341,33 @@ class DOMMatrix {
1779
2341
  0,
1780
2342
  0,
1781
2343
  1,
1782
- -1 / d,
2344
+ m34,
1783
2345
  0,
1784
2346
  0,
1785
2347
  0,
1786
2348
  1
1787
2349
  ])));
1788
- this.is2D = false;
2350
+ temp.#is2D = false;
1789
2351
  break;
1790
2352
  }
1791
2353
  default:
1792
- throwParseErrorDMatrix("setMatrixValue", value);
2354
+ this.#throwParseOrConstructError(caller, rawInput);
1793
2355
  }
1794
2356
  }
2357
+ this.#internal.set(temp.#internal);
2358
+ this.#is2D = temp.#is2D;
1795
2359
  return this;
1796
2360
  }
1797
- toString() {
1798
- return this.is2D ? `matrix(${this.a}, ${this.b}, ${this.c}, ${this.d}, ${this.e}, ${this.f})` : `matrix3d(${this.m11}, ${this.m12}, ${this.m13}, ${this.m14}, ${this.m21}, ${this.m22}, ${this.m23}, ${this.m24}, ${this.m31}, ${this.m32}, ${this.m33}, ${this.m34}, ${this.m41}, ${this.m42}, ${this.m43}, ${this.m44})`;
2361
+ setMatrixValue(value) {
2362
+ return this.#parseAndApplyTransformList(String(value), "setMatrixValue");
1799
2363
  }
1800
- constructor(...args) {
1801
- if (!isMatrixArray(args[0]))
1802
- throw new SyntaxError(`Failed to construct 'DOMMatrix': Failed to parse '${args[0]}'.`);
1803
- if (args[0]) {
1804
- const len = args[0].length;
1805
- if (len != 6 && len != 16)
1806
- throw new TypeError(`Failed to construct 'DOMMatrix': The sequence must contain 6 elements for a 2D matrix or 16 elements for a 3D matrix.`);
1807
- let matrix = args[0];
1808
- if (len == 6) {
1809
- this.a = matrix[0];
1810
- this.b = matrix[1];
1811
- this.c = matrix[2];
1812
- this.d = matrix[3];
1813
- this.e = matrix[4];
1814
- this.f = matrix[5];
1815
- } else {
1816
- let index = 0;
1817
- for (const item of matrix) {
1818
- this.#internal[index] = item;
1819
- index++;
1820
- }
2364
+ toString() {
2365
+ for (let i = 0;i < 16; i++) {
2366
+ if (!Number.isFinite(this.#internal[i])) {
2367
+ throw new DOMException("Failed to execute 'toString' on 'DOMMatrix': Matrix contains non-finite values.", "InvalidStateError");
1821
2368
  }
1822
- this.#isIdentity = matrix[0] == 1 && matrix[1] == 0 && matrix[2] == 0 && matrix[3] == 0 && matrix[4] == 0 && matrix[5] == 1 && matrix[6] == 0 && matrix[7] == 0 && matrix[8] == 0 && matrix[9] == 0 && matrix[10] == 1 && matrix[11] == 0 && matrix[12] == 0 && matrix[13] == 0 && matrix[14] == 0 && matrix[15] == 1;
1823
2369
  }
1824
- }
1825
- get ptr() {
1826
- return ptr2(this.#internal);
2370
+ return this.is2D ? `matrix(${this.a}, ${this.b}, ${this.c}, ${this.d}, ${this.e}, ${this.f})` : `matrix3d(${this.m11}, ${this.m12}, ${this.m13}, ${this.m14}, ${this.m21}, ${this.m22}, ${this.m23}, ${this.m24}, ${this.m31}, ${this.m32}, ${this.m33}, ${this.m34}, ${this.m41}, ${this.m42}, ${this.m43}, ${this.m44})`;
1827
2371
  }
1828
2372
  static fromFloat32Array(arr) {
1829
2373
  if (arr instanceof Float32Array)
@@ -1835,43 +2379,63 @@ class DOMMatrix {
1835
2379
  return new DOMMatrix(arr);
1836
2380
  throw new TypeError(`Failed to execute 'fromFloat64Array' on 'DOMMatrix': parameter 1 is not of type 'Float64Array'.`);
1837
2381
  }
1838
- static fromMatrix(arr) {
1839
- if (!arr)
2382
+ static fromMatrix(other) {
2383
+ if (!other)
1840
2384
  return new DOMMatrix;
1841
- if (arr.a != arr.m11 || arr.b != arr.m21 || arr.c != arr.m12 || arr.d != arr.m22 || arr.e != arr.m41 || arr.f != arr.m42)
2385
+ if (other.a !== undefined && other.m11 !== undefined && other.a !== other.m11 || other.b !== undefined && other.m12 !== undefined && other.b !== other.m12 || other.c !== undefined && other.m21 !== undefined && other.c !== other.m21 || other.d !== undefined && other.m22 !== undefined && other.d !== other.m22 || other.e !== undefined && other.m41 !== undefined && other.e !== other.m41 || other.f !== undefined && other.m42 !== undefined && other.f !== other.m42) {
1842
2386
  throw new TypeError(`Failed to execute 'fromMatrix' on 'DOMMatrix': Property mismatch on matrix initialization.`);
1843
- let a = arr.a ?? undefined;
1844
- let b = arr.b ?? undefined;
1845
- let c = arr.c ?? undefined;
1846
- let d = arr.d ?? undefined;
1847
- let e = arr.e ?? undefined;
1848
- let f = arr.f ?? undefined;
1849
- let m11 = arr.m11 ?? a ?? 1;
1850
- let m12 = arr.m12 ?? b ?? 0;
1851
- let m13 = arr.m13 ?? 0;
1852
- let m14 = arr.m14 ?? 0;
1853
- let m21 = arr.m21 ?? c ?? 0;
1854
- let m22 = arr.m22 ?? d ?? 1;
1855
- let m23 = arr.m23 ?? 0;
1856
- let m24 = arr.m24 ?? 0;
1857
- let m31 = arr.m31 ?? 0;
1858
- let m32 = arr.m32 ?? 0;
1859
- let m33 = arr.m33 ?? 1;
1860
- let m34 = arr.m34 ?? 0;
1861
- let m41 = arr.m41 ?? e ?? 0;
1862
- let m42 = arr.m42 ?? f ?? 0;
1863
- let m43 = arr.m43 ?? 0;
1864
- let m44 = arr.m44 ?? 1;
1865
- return new DOMMatrix([m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44]);
2387
+ }
2388
+ const m11 = other.m11 ?? other.a ?? 1;
2389
+ const m12 = other.m12 ?? other.b ?? 0;
2390
+ const m13 = other.m13 ?? 0;
2391
+ const m14 = other.m14 ?? 0;
2392
+ const m21 = other.m21 ?? other.c ?? 0;
2393
+ const m22 = other.m22 ?? other.d ?? 1;
2394
+ const m23 = other.m23 ?? 0;
2395
+ const m24 = other.m24 ?? 0;
2396
+ const m31 = other.m31 ?? 0;
2397
+ const m32 = other.m32 ?? 0;
2398
+ const m33 = other.m33 ?? 1;
2399
+ const m34 = other.m34 ?? 0;
2400
+ const m41 = other.m41 ?? other.e ?? 0;
2401
+ const m42 = other.m42 ?? other.f ?? 0;
2402
+ const m43 = other.m43 ?? 0;
2403
+ const m44 = other.m44 ?? 1;
2404
+ const has3DComponents = m13 !== 0 || m14 !== 0 || m23 !== 0 || m24 !== 0 || m31 !== 0 || m32 !== 0 || m33 !== 1 || m34 !== 0 || m43 !== 0 || m44 !== 1;
2405
+ if (other.is2D === true && has3DComponents) {
2406
+ throw new TypeError(`Failed to execute 'fromMatrix' on 'DOMMatrix': Property mismatch on matrix initialization.`);
2407
+ }
2408
+ const is2D = other.is2D !== undefined ? other.is2D : !has3DComponents;
2409
+ if (is2D) {
2410
+ return new DOMMatrix([m11, m12, m21, m22, m41, m42]);
2411
+ }
2412
+ return new DOMMatrix([
2413
+ m11,
2414
+ m12,
2415
+ m13,
2416
+ m14,
2417
+ m21,
2418
+ m22,
2419
+ m23,
2420
+ m24,
2421
+ m31,
2422
+ m32,
2423
+ m33,
2424
+ m34,
2425
+ m41,
2426
+ m42,
2427
+ m43,
2428
+ m44
2429
+ ]);
1866
2430
  }
1867
2431
  }
1868
2432
  var proto = DOMMatrix.prototype;
1869
2433
  for (const key of Object.getOwnPropertyNames(proto)) {
1870
2434
  const desc = Object.getOwnPropertyDescriptor(proto, key);
1871
- if (key == "constructor") {
1872
- desc && (desc.value.toString = () => {
1873
- return `function ${proto.constructor.name}() { [native code] }`;
1874
- });
2435
+ if (key === "constructor") {
2436
+ if (desc) {
2437
+ desc.value.toString = () => `function ${proto.constructor.name}() { [native code] }`;
2438
+ }
1875
2439
  continue;
1876
2440
  }
1877
2441
  if (typeof desc?.value === "function") {
@@ -1879,327 +2443,966 @@ for (const key of Object.getOwnPropertyNames(proto)) {
1879
2443
  }
1880
2444
  }
1881
2445
 
1882
- // BunCanvas/internal/colorCheck.ts
1883
- var NAMED_COLORS = new Set([
1884
- "aliceblue",
1885
- "antiquewhite",
1886
- "aqua",
1887
- "aquamarine",
1888
- "azure",
1889
- "beige",
1890
- "bisque",
1891
- "black",
1892
- "blanchedalmond",
1893
- "blue",
1894
- "blueviolet",
1895
- "brown",
1896
- "burlywood",
1897
- "cadetblue",
1898
- "chartreuse",
1899
- "chocolate",
1900
- "coral",
1901
- "cornflowerblue",
1902
- "cornsilk",
1903
- "crimson",
1904
- "cyan",
1905
- "darkblue",
1906
- "darkcyan",
1907
- "darkgoldenrod",
1908
- "darkgray",
1909
- "darkgreen",
1910
- "darkgrey",
1911
- "darkkhaki",
1912
- "darkmagenta",
1913
- "darkolivegreen",
1914
- "darkorange",
1915
- "darkorchid",
1916
- "darkred",
1917
- "darksalmon",
1918
- "darkseagreen",
1919
- "darkslateblue",
1920
- "darkslategray",
1921
- "darkslategrey",
1922
- "darkturquoise",
1923
- "darkviolet",
1924
- "deeppink",
1925
- "deepskyblue",
1926
- "dimgray",
1927
- "dimgrey",
1928
- "dodgerblue",
1929
- "firebrick",
1930
- "floralwhite",
1931
- "forestgreen",
1932
- "fuchsia",
1933
- "gainsboro",
1934
- "ghostwhite",
1935
- "gold",
1936
- "goldenrod",
1937
- "gray",
1938
- "green",
1939
- "greenyellow",
1940
- "grey",
1941
- "honeydew",
1942
- "hotpink",
1943
- "indianred",
1944
- "indigo",
1945
- "ivory",
1946
- "khaki",
1947
- "lavender",
1948
- "lavenderblush",
1949
- "lawngreen",
1950
- "lemonchiffon",
1951
- "lightblue",
1952
- "lightcoral",
1953
- "lightcyan",
1954
- "lightgoldenrodyellow",
1955
- "lightgray",
1956
- "lightgreen",
1957
- "lightgrey",
1958
- "lightpink",
1959
- "lightsalmon",
1960
- "lightseagreen",
1961
- "lightskyblue",
1962
- "lightslategray",
1963
- "lightslategrey",
1964
- "lightsteelblue",
1965
- "lightyellow",
1966
- "lime",
1967
- "limegreen",
1968
- "linen",
1969
- "magenta",
1970
- "maroon",
1971
- "mediumaquamarine",
1972
- "mediumblue",
1973
- "mediumorchid",
1974
- "mediumpurple",
1975
- "mediumseagreen",
1976
- "mediumslateblue",
1977
- "mediumspringgreen",
1978
- "mediumturquoise",
1979
- "mediumvioletred",
1980
- "midnightblue",
1981
- "mintcream",
1982
- "mistyrose",
1983
- "moccasin",
1984
- "navajowhite",
1985
- "navy",
1986
- "oldlace",
1987
- "olive",
1988
- "olivedrab",
1989
- "orange",
1990
- "orangered",
1991
- "orchid",
1992
- "palegoldenrod",
1993
- "palegreen",
1994
- "paleturquoise",
1995
- "palevioletred",
1996
- "papayawhip",
1997
- "peachpuff",
1998
- "peru",
1999
- "pink",
2000
- "plum",
2001
- "powderblue",
2002
- "purple",
2003
- "rebeccapurple",
2004
- "red",
2005
- "rosybrown",
2006
- "royalblue",
2007
- "saddlebrown",
2008
- "salmon",
2009
- "sandybrown",
2010
- "seagreen",
2011
- "seashell",
2012
- "sienna",
2013
- "silver",
2014
- "skyblue",
2015
- "slateblue",
2016
- "slategray",
2017
- "slategrey",
2018
- "snow",
2019
- "springgreen",
2020
- "steelblue",
2021
- "tan",
2022
- "teal",
2023
- "thistle",
2024
- "tomato",
2025
- "transparent",
2026
- "turquoise",
2027
- "violet",
2028
- "wheat",
2029
- "white",
2030
- "whitesmoke",
2031
- "yellow",
2032
- "yellowgreen"
2033
- ]);
2034
- var HEX_REGEX = /^#(?:[0-9a-fA-F]{3,4}){1,2}$/;
2035
- var RGB_REGEX = /^rgba?\(\s*(?:\d+(?:\.\d+)?%?|\.\d+%?)\s*[, ]\s*(?:\d+(?:\.\d+)?%?|\.\d+%?)\s*[, ]\s*(?:\d+(?:\.\d+)?%?|\.\d+%?)(?:\s*[,/]\s*(?:\d+(?:\.\d+)?%?|\.\d+%?))?\s*\)$/i;
2036
- var HSL_HWB_REGEX = /^(?:hsl|hsla|hwb)\(\s*(?:\d+(?:\.\d+)?(?:deg|rad|turn)?|\.\d+(?:deg|rad|turn)?)\s*[, ]\s*(?:\d+(?:\.\d+)?%|\.\d+%)\s*[, ]\s*(?:\d+(?:\.\d+)?%|\.\d+%)(?:\s*[,/]\s*(?:\d+(?:\.\d+)?%?|\.\d+%?))?\s*\)$/i;
2037
- function isValidColor(str) {
2038
- if (typeof str !== "string")
2039
- return false;
2040
- const normalized = str.trim().toLowerCase();
2041
- if (normalized === "")
2042
- return false;
2043
- if (NAMED_COLORS.has(normalized))
2044
- return true;
2045
- if (normalized.startsWith("#"))
2046
- return HEX_REGEX.test(normalized);
2047
- return RGB_REGEX.test(normalized) || HSL_HWB_REGEX.test(normalized);
2446
+ // BunCanvas/internal/native/memWrite.ts
2447
+ function writePtrU64(buf, index, ptr) {
2448
+ buf[index] = ptr >>> 0;
2449
+ buf[index + 1] = ptr / 4294967296 >>> 0;
2450
+ return index + 2;
2048
2451
  }
2049
2452
 
2050
- // BunCanvas/internal/native/enums.ts
2051
- //!< r = 0
2052
- //!< r = s
2053
- //!< r = d
2054
- //!< r = s + (1-sa)*d
2055
- //!< r = d + (1-da)*s
2056
- //!< r = s * da
2057
- //!< r = d * sa
2058
- //!< r = s * (1-da)
2059
- //!< r = d * (1-sa)
2060
- //!< r = s*da + d*(1-sa)
2061
- //!< r = d*sa + s*(1-da)
2062
- //!< r = s*(1-da) + d*(1-sa)
2063
- //!< r = min(s + d, 1)
2064
- //!< r = s*d
2065
- //!< r = s + d - s*d
2066
- //!< multiply or screen, depending on destination
2067
- //!< rc = s + d - max(s*da, d*sa), ra = kSrcOver
2068
- //!< rc = s + d - min(s*da, d*sa), ra = kSrcOver
2069
- //!< brighten destination to reflect source
2070
- //!< darken destination to reflect source
2071
- //!< multiply or screen, depending on source
2072
- //!< lighten or darken, depending on source
2073
- //!< rc = s + d - 2*(min(s*da, d*sa)), ra = kSrcOver
2074
- //!< rc = s + d - two(s*d), ra = kSrcOver
2075
- //!< r = s*(1-da) + d*(1-sa) + s*d
2076
- //!< hue of source with saturation and luminosity of destination
2077
- //!< saturation of source with hue and luminosity of destination
2078
- //!< hue and saturation of source with luminosity of destination
2079
- //!< luminosity of source with hue and saturation of destination
2080
- //!< last porter duff blend mode
2081
- //!< last blend mode operating separately on components
2082
- //!< last valid value
2083
- //!< extends to miter limit
2084
- //!< adds circle
2085
- //!< connects outside edges
2086
- //!< equivalent to the largest value for Join
2087
- //!< equivalent to kMiter_Join
2088
-
2089
- // BunCanvas/internal/canvas/blendModes.ts
2090
- var CanvasBlendMode = {
2091
- "source-over": 3 /* kSrcOver */,
2092
- "source-in": 5 /* kSrcIn */,
2093
- "source-out": 7 /* kSrcOut */,
2094
- "source-atop": 9 /* kSrcATop */,
2095
- "destination-over": 4 /* kDstOver */,
2096
- "destination-in": 6 /* kDstIn */,
2097
- "destination-out": 8 /* kDstOut */,
2098
- "destination-atop": 10 /* kDstATop */,
2099
- lighter: 17 /* kLighten */,
2100
- copy: 1 /* kSrc */,
2101
- xor: 11 /* kXor */,
2102
- multiply: 24 /* kMultiply */,
2103
- screen: 14 /* kScreen */,
2104
- overlay: 15 /* kOverlay */,
2105
- darken: 16 /* kDarken */,
2106
- lighten: 17 /* kLighten */,
2107
- "color-dodge": 18 /* kColorDodge */,
2108
- "color-burn": 19 /* kColorBurn */,
2109
- "hard-light": 20 /* kHardLight */,
2110
- "soft-light": 21 /* kSoftLight */,
2111
- difference: 22 /* kDifference */,
2112
- exclusion: 23 /* kExclusion */,
2113
- hue: 25 /* kHue */,
2114
- saturation: 26 /* kSaturation */,
2115
- color: 27 /* kColor */,
2116
- luminosity: 28 /* kLuminosity */
2117
- };
2453
+ // BunCanvas/src/Path2D.ts
2454
+ import { ptr as ptr2 } from "bun:ffi";
2455
+ var p2dFinalizationRegistry = new FinalizationRegistry((ptr) => {
2456
+ console.log("path destroyed!");
2457
+ lib.symbols.path2d_destroy(ptr);
2458
+ });
2118
2459
 
2119
- // BunCanvas/internal/canvas/textAlignment.ts
2120
- var CanvasTextAlignment = {
2121
- left: 0 /* Left */,
2122
- right: 1 /* Right */,
2123
- center: 2 /* Center */,
2124
- start: 3 /* Start */,
2125
- end: 4 /* End */
2126
- };
2460
+ class Path2D {
2461
+ constructor(path) {
2462
+ if (path && path instanceof Path2D) {
2463
+ let ptr = ptrs.get(path);
2464
+ if (!ptr)
2465
+ return;
2466
+ let _ptr = lib.symbols.path2d_create_from_copy(ptr);
2467
+ ptrs.set(this, _ptr);
2468
+ p2dFinalizationRegistry.register(this, _ptr);
2469
+ } else {
2470
+ let _ptr = lib.symbols.path2d_create();
2471
+ ptrs.set(this, _ptr);
2472
+ p2dFinalizationRegistry.register(this, _ptr);
2473
+ }
2474
+ }
2475
+ moveTo(x, y) {
2476
+ lib.symbols.path2d_move_to(ptrs.get(this), x, y);
2477
+ }
2478
+ lineTo(x, y) {
2479
+ lib.symbols.path2d_line_to(ptrs.get(this), x, y);
2480
+ }
2481
+ arc(x, y, radius, startAngle, endAngle) {
2482
+ lib.symbols.path2d_arc(ptrs.get(this), x, y, radius, startAngle, endAngle);
2483
+ }
2484
+ ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, counterclockwise = false) {
2485
+ lib.symbols.path2d_ellipse(ptrs.get(this), x, y, radiusX, radiusY, rotation, startAngle, endAngle, counterclockwise);
2486
+ }
2487
+ arcTo(x1, y1, x2, y2, radius) {
2488
+ lib.symbols.path2d_arc_to(ptrs.get(this), x1, y1, x2, y2, radius);
2489
+ }
2490
+ bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) {
2491
+ lib.symbols.path2d_bezier_to(ptrs.get(this), cp1x, cp1y, cp2x, cp2y, x, y);
2492
+ }
2493
+ quadraticCurveTo(cpx, cpy, x, y) {
2494
+ lib.symbols.path2d_quad_to(ptrs.get(this), cpx, cpy, x, y);
2495
+ }
2496
+ rect(x, y, width, height) {
2497
+ lib.symbols.path2d_rect(ptrs.get(this), x, y, width, height);
2498
+ }
2499
+ roundRect(x, y, width, height, radii) {
2500
+ if (radii.constructor.name.toLowerCase().includes("array")) {
2501
+ const arr = new Float32Array(radii);
2502
+ if (arr.some(Number.isNaN))
2503
+ return;
2504
+ const len = arr.length;
2505
+ lib.symbols.path2d_roundrect_array(ptrs.get(this), x, y, width, height, ptr2(arr), len);
2506
+ return;
2507
+ } else {
2508
+ lib.symbols.path2d_rect(ptrs.get(this), x, y, width, height, radii);
2509
+ }
2510
+ }
2511
+ closePath() {
2512
+ lib.symbols.path2d_close(ptrs.get(this));
2513
+ }
2514
+ }
2515
+ var proto2 = Path2D.prototype;
2516
+ for (const key of Object.getOwnPropertyNames(proto2)) {
2517
+ const desc = Object.getOwnPropertyDescriptor(proto2, key);
2518
+ if (key == "constructor") {
2519
+ desc && (desc.value.toString = () => {
2520
+ return `function ${proto2.constructor.name}() { [native code] }`;
2521
+ });
2522
+ continue;
2523
+ }
2524
+ if (typeof desc?.value === "function") {
2525
+ desc.value.toString = () => `function ${key}() { [native code] }`;
2526
+ }
2527
+ }
2127
2528
 
2128
- // BunCanvas/internal/canvas/textBaseline.ts
2129
- var CanvasTextBaseline = {
2130
- top: 0 /* Top */,
2131
- hanging: 1 /* Hanging */,
2132
- middle: 2 /* Middle */,
2133
- alphabetic: 3 /* Alphabetic */,
2134
- ideographic: 4 /* Ideographic */,
2135
- bottom: 5 /* Bottom */
2136
- };
2529
+ // BunCanvas/src/ImageData.ts
2530
+ class ImageData {
2531
+ width;
2532
+ height;
2533
+ data;
2534
+ colorSpace;
2535
+ constructor(arg1, arg2, arg3, arg4) {
2536
+ let data;
2537
+ let width;
2538
+ let height;
2539
+ let settings;
2540
+ if (arg1 instanceof Uint8ClampedArray) {
2541
+ data = arg1;
2542
+ width = arg2;
2543
+ if (typeof arg3 === "number") {
2544
+ height = arg3;
2545
+ settings = arg4;
2546
+ } else {
2547
+ settings = arg3;
2548
+ height = data.length / 4 / width;
2549
+ }
2550
+ if (data.length === 0 || data.length % 4 !== 0) {
2551
+ throw new SyntaxError("The input data array length must be a non-zero multiple of 4.");
2552
+ }
2553
+ if (width <= 0 || !Number.isInteger(width)) {
2554
+ throw new SyntaxError("Width must be a positive integer.");
2555
+ }
2556
+ if (height <= 0 || !Number.isInteger(height)) {
2557
+ throw new SyntaxError("Height must be a positive integer or derived from array length.");
2558
+ }
2559
+ if (data.length !== width * height * 4) {
2560
+ throw new SyntaxError("The input data array length does not match width * height * 4.");
2561
+ }
2562
+ } else if (typeof arg1 === "number" && typeof arg2 === "number") {
2563
+ width = arg1;
2564
+ height = arg2;
2565
+ settings = arg3;
2566
+ if (width <= 0 || !Number.isInteger(width) || height <= 0 || !Number.isInteger(height)) {
2567
+ throw new SyntaxError("Width and height must be positive integers.");
2568
+ }
2569
+ data = new Uint8ClampedArray(width * height * 4);
2570
+ } else {
2571
+ throw new TypeError("Failed to construct 'ImageData': Invalid arguments provided.");
2572
+ }
2573
+ this.width = width;
2574
+ this.height = height;
2575
+ this.data = data;
2576
+ this.colorSpace = settings?.colorSpace ?? "srgb";
2577
+ }
2578
+ }
2137
2579
 
2138
- // BunCanvas/internal/canvas/lineJoin.ts
2139
- var CanvasLineJoin = {
2140
- round: 1 /* kRound_Join */,
2141
- bevel: 2 /* kBevel_Join */,
2142
- miter: 0 /* kMiter_Join */
2143
- };
2580
+ // BunCanvas/src/Canvas/RenderingContexts/2D/CanvasRenderingContext2DBase.ts
2581
+ class CanvasRenderingContext2D {
2582
+ get canvas() {
2583
+ return;
2584
+ }
2585
+ reset() {}
2586
+ save() {}
2587
+ restore() {}
2588
+ translate(x, y) {}
2589
+ rotate(deg) {}
2590
+ scale(x, y) {}
2591
+ getTransform() {
2592
+ return;
2593
+ }
2594
+ setTransform(...args) {}
2595
+ transform(a, b, c, d, e, f) {}
2596
+ resetTransform() {}
2597
+ set globalAlpha(a) {}
2598
+ get globalAlpha() {
2599
+ return;
2600
+ }
2601
+ set globalCompositeOperation(operation) {}
2602
+ get globalCompositeOperation() {
2603
+ return;
2604
+ }
2605
+ set filter(v) {}
2606
+ get filter() {
2607
+ return;
2608
+ }
2609
+ set imageSmoothingEnabled(value) {}
2610
+ get imageSmoothingEnabled() {
2611
+ return;
2612
+ }
2613
+ set imageSmoothingQuality(quality) {}
2614
+ get imageSmoothingQuality() {
2615
+ return;
2616
+ }
2617
+ set fillStyle(style) {}
2618
+ get fillStyle() {
2619
+ return;
2620
+ }
2621
+ set strokeStyle(style) {}
2622
+ get strokeStyle() {
2623
+ return;
2624
+ }
2625
+ createConicGradient(...args) {
2626
+ return;
2627
+ }
2628
+ createLinearGradient(...args) {
2629
+ return;
2630
+ }
2631
+ createRadialGradient(...args) {
2632
+ return;
2633
+ }
2634
+ set lineWidth(width) {}
2635
+ get lineWidth() {
2636
+ return;
2637
+ }
2638
+ set lineJoin(joinType) {}
2639
+ get lineJoin() {
2640
+ return;
2641
+ }
2642
+ set lineDashOffset(v) {}
2643
+ setLineDash(lines) {}
2644
+ getLineDash() {
2645
+ return;
2646
+ }
2647
+ set shadowBlur(blur) {}
2648
+ set shadowColor(col) {}
2649
+ set shadowOffsetX(x) {}
2650
+ set shadowOffsetY(y) {}
2651
+ fillRect(x, y, w, h) {}
2652
+ strokeRect(x, y, w, h) {}
2653
+ clearRect(x, y, w, h) {}
2654
+ beginPath() {}
2655
+ closePath() {}
2656
+ moveTo(x, y) {}
2657
+ lineTo(x, y) {}
2658
+ bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) {}
2659
+ quadraticCurveTo(cpx, cpy, x, y) {}
2660
+ arc(x, y, radius, startAngle, endAngle) {}
2661
+ arcTo(x1, y1, x2, y2, radius) {}
2662
+ ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, counterclockwise = false) {}
2663
+ rect(x, y, width, height) {}
2664
+ roundRect(x, y, width, height, radii) {}
2665
+ fill(path) {}
2666
+ stroke(path) {}
2667
+ clip(path) {}
2668
+ set font(css) {}
2669
+ get font() {
2670
+ return;
2671
+ }
2672
+ set textAlign(alignment) {}
2673
+ set textBaseline(baseline) {}
2674
+ fillText(text, x, y, maxWidth = -1) {}
2675
+ strokeText(text, x, y, maxWidth = -1) {}
2676
+ measureText(text) {
2677
+ return;
2678
+ }
2679
+ drawImage(img, ...args) {}
2680
+ getImageData(x, y, w, h) {
2681
+ return;
2682
+ }
2683
+ putImageData(data, dx, dy, dirtyX = 0, dirtyY = 0, dirtyWidth = data.width, dirtyHeight = data.height) {}
2684
+ }
2144
2685
 
2145
- // BunCanvas/internal/canvas/smoothingQuality.ts
2146
- var CanvasSmoothingQuality = {
2147
- low: 0 /* Low */,
2148
- medium: 1 /* Medium */,
2149
- high: 2 /* High */
2150
- };
2686
+ class Render2DState {
2687
+ lineWidth = 0;
2688
+ globalAlpha = 1;
2689
+ transform = new DOMMatrix;
2690
+ imageSmoothingQuality = "low";
2691
+ imageSmoothingEnabled = true;
2692
+ fillStyle = "#000000";
2693
+ strokeStyle = "#000000";
2694
+ compositeOperation = "source-over";
2695
+ filter = "none";
2696
+ fontCss = "10px sans-serif";
2697
+ textBaseline = "alphabetic";
2698
+ textAlign = "start";
2699
+ lineDash = [];
2700
+ lineDashOffset = 0;
2701
+ lineJoin = "miter";
2702
+ constructor(other) {
2703
+ if (other instanceof Render2DState) {
2704
+ this.copyFrom(other);
2705
+ }
2706
+ }
2707
+ copyFrom(other) {
2708
+ if (other instanceof Render2DState) {
2709
+ this.lineWidth = other.lineWidth;
2710
+ this.globalAlpha = other.globalAlpha;
2711
+ getInternalArray(this.transform).set(getInternalArray(other.transform));
2712
+ this.imageSmoothingQuality = other.imageSmoothingQuality;
2713
+ this.imageSmoothingEnabled = other.imageSmoothingEnabled;
2714
+ this.fillStyle = other.fillStyle;
2715
+ this.strokeStyle = other.strokeStyle;
2716
+ this.compositeOperation = other.compositeOperation;
2717
+ this.filter = other.filter;
2718
+ this.fontCss = other.fontCss;
2719
+ this.textBaseline = other.textBaseline;
2720
+ this.textAlign = other.textAlign;
2721
+ this.lineDash = [...other.lineDash];
2722
+ this.lineDashOffset = other.lineDashOffset;
2723
+ this.lineJoin = other.lineJoin;
2724
+ }
2725
+ }
2726
+ }
2727
+ var ctx2ds = new WeakMap;
2151
2728
 
2152
- // BunCanvas/src/Canvas.ts
2153
- var canvasFinalizationRegistry = new FinalizationRegistry((ptr) => {
2154
- lib.symbols.canvas_destroy(ptr);
2155
- });
2156
- class CanvasGradient {
2157
- type;
2158
- points = new Float32Array(6);
2159
- offsets = [];
2160
- colors = [];
2161
- constructor(...args) {
2162
- if (args[0] !== INTERNAL_TOKEN)
2729
+ // BunCanvas/src/Canvas/RenderingContexts/2D/CanvasBatchedRenderingContext2D.ts
2730
+ class CanvasBatchedRenderingContext2D extends CanvasRenderingContext2D {
2731
+ static #MAX_BUF_SIZE = 4 * 1024 * 1024;
2732
+ #rawBuf = new ArrayBuffer(256 * 1024);
2733
+ #i32 = new Int32Array(this.#rawBuf);
2734
+ #f32 = new Float32Array(this.#rawBuf);
2735
+ #f64 = new Float64Array(this.#rawBuf);
2736
+ #u32 = new Uint32Array(this.#rawBuf);
2737
+ #byteOffset = 0;
2738
+ #retained = [];
2739
+ #flushScheduled = false;
2740
+ #flushBound = () => this.#flush(true);
2741
+ #currentState = new Render2DState;
2742
+ #savedState = new Render2DState;
2743
+ #owner;
2744
+ #transformDirty = false;
2745
+ constructor(width, height, cnv, args, token) {
2746
+ super();
2747
+ if (token !== INTERNAL_TOKEN)
2163
2748
  throwIllegalConstructor(this);
2164
- this.type = args[1];
2165
- switch (this.type) {
2166
- case 0 /* Linear */: {
2167
- this.points[0] = args[2];
2168
- this.points[1] = args[3];
2169
- this.points[2] = args[4];
2170
- this.points[3] = args[5];
2171
- break;
2749
+ const { desynchronized = false, alpha = true, willReadFrequently = false } = args ?? {};
2750
+ const renderContextPtr = lib.symbols.canvas_get_context2D(width, height, desynchronized, alpha, willReadFrequently, false);
2751
+ this.#owner = cnv;
2752
+ ptrs.set(this, renderContextPtr);
2753
+ }
2754
+ get canvas() {
2755
+ return this.#owner;
2756
+ }
2757
+ reset(token, w, h) {
2758
+ if (token === INTERNAL_TOKEN && w && h) {
2759
+ let off = this.#alloc(16);
2760
+ this.#i32[off >> 2] = 51 /* Resize */;
2761
+ this.#i32[off + 4 >> 2] = Number(w);
2762
+ this.#i32[off + 8 >> 2] = Number(h);
2763
+ this.#scheduleFlush();
2764
+ }
2765
+ this.#savedState = new Render2DState;
2766
+ this.#currentState = new Render2DState;
2767
+ }
2768
+ #alloc(bytes) {
2769
+ let off = this.#byteOffset + 7 & ~7;
2770
+ if (off + bytes > this.#rawBuf.byteLength) {
2771
+ this.#flush(false);
2772
+ off = 0;
2773
+ if (this.#rawBuf.byteLength < CanvasBatchedRenderingContext2D.#MAX_BUF_SIZE) {
2774
+ this.#rawBuf = new ArrayBuffer(this.#rawBuf.byteLength * 2);
2775
+ this.#i32 = new Int32Array(this.#rawBuf);
2776
+ this.#f32 = new Float32Array(this.#rawBuf);
2777
+ this.#f64 = new Float64Array(this.#rawBuf);
2778
+ this.#u32 = new Uint32Array(this.#rawBuf);
2779
+ }
2780
+ }
2781
+ this.#byteOffset = off + bytes;
2782
+ return off;
2783
+ }
2784
+ #flush(commit = false) {
2785
+ if (this.#byteOffset === 0)
2786
+ return;
2787
+ lib.symbols.canvas_submit_batch(ptrs.get(this), ptr3(this.#rawBuf), this.#byteOffset, commit);
2788
+ this.#byteOffset = 0;
2789
+ this.#retained.length = 0;
2790
+ this.#flushScheduled = false;
2791
+ }
2792
+ #scheduleFlush() {
2793
+ if (this.#flushScheduled === false) {
2794
+ queueMicrotask(this.#flushBound);
2795
+ this.#flushScheduled = true;
2796
+ }
2797
+ }
2798
+ #uploadTransform() {
2799
+ const src = getInternalArray(this.#currentState.transform);
2800
+ const off = this.#alloc(68);
2801
+ this.#i32[off >> 2] = 24 /* UploadTransformNoArray */;
2802
+ for (let i = 0;i < 16; i++) {
2803
+ this.#f32[off + (i + 1) * 4 >> 2] = src[i];
2804
+ }
2805
+ this.#scheduleFlush();
2806
+ this.#transformDirty = false;
2807
+ }
2808
+ #setStyleColor(style, isStroke) {
2809
+ this.#currentState.fillStyle = style;
2810
+ const encoded = encodeCString(style);
2811
+ let off = this.#alloc(16);
2812
+ const operation = !isStroke ? 2 /* SetFillStyleColor */ : 4 /* SetStrokeStyleColor */;
2813
+ this.#i32[off >> 2] = operation;
2814
+ writePtrU64(this.#u32, off + 8 >> 2, ptr3(encoded));
2815
+ this.#scheduleFlush();
2816
+ }
2817
+ #setStyleGradient(style, isStroke) {
2818
+ const count = style.colors.length;
2819
+ const ptrArray = new BigUint64Array(count);
2820
+ this.#retained.push(style);
2821
+ for (let i = 0;i < count; i++) {
2822
+ ptrArray[i] = BigInt(ptr3(style.colors[i]));
2823
+ }
2824
+ const offsetBuffer = new Float32Array(style.offsets);
2825
+ const operation = !isStroke ? 3 /* SetFillStyleGradient */ : 5 /* SetStrokeStyleGradient */;
2826
+ let off = this.#alloc(40);
2827
+ this.#i32[off >> 2] = operation;
2828
+ this.#i32[off + 4 >> 2] = style.type;
2829
+ writePtrU64(this.#u32, off + 8 >> 2, ptr3(style.points));
2830
+ this.#i32[off + 16 >> 2] = count;
2831
+ writePtrU64(this.#u32, off + 24 >> 2, ptr3(ptrArray));
2832
+ writePtrU64(this.#u32, off + 32 >> 2, ptr3(offsetBuffer));
2833
+ this.#scheduleFlush();
2834
+ }
2835
+ #batchPathOperation(opIfPathPresent, opIfPathNotPresent, path) {
2836
+ this.#retained.push(path);
2837
+ if (path instanceof Path2D) {
2838
+ let _ptr = path ? ptrs.get(path) : null;
2839
+ let off = this.#alloc(16);
2840
+ this.#i32[off >> 2] = opIfPathPresent;
2841
+ writePtrU64(this.#u32, off + 8 >> 2, _ptr);
2842
+ } else {
2843
+ let off = this.#alloc(8);
2844
+ this.#i32[off >> 2] = opIfPathNotPresent;
2845
+ }
2846
+ }
2847
+ save() {
2848
+ this.#savedState?.copyFrom(this.#currentState);
2849
+ let off = this.#alloc(8);
2850
+ this.#i32[off >> 2] = 21 /* Save */;
2851
+ this.#scheduleFlush();
2852
+ }
2853
+ restore() {
2854
+ this.#currentState?.copyFrom(this.#savedState);
2855
+ let off = this.#alloc(8);
2856
+ this.#i32[off >> 2] = 22 /* Restore */;
2857
+ this.#scheduleFlush();
2858
+ }
2859
+ translate(x, y) {
2860
+ this.#currentState.transform.translateSelf(x, y);
2861
+ this.#transformDirty = true;
2862
+ }
2863
+ rotate(deg) {
2864
+ this.#currentState.transform.rotateSelf(deg);
2865
+ this.#transformDirty = true;
2866
+ }
2867
+ scale(x, y) {
2868
+ this.#currentState.transform.scaleSelf(x, y);
2869
+ this.#transformDirty = true;
2870
+ }
2871
+ getTransform() {
2872
+ return DOMMatrix.fromMatrix(this.#currentState.transform);
2873
+ }
2874
+ setTransform(...args) {
2875
+ if (args[0] instanceof DOMMatrix) {
2876
+ getInternalArray(this.#currentState.transform).set(getInternalArray(args[0]));
2877
+ this.#transformDirty = true;
2878
+ }
2879
+ if (args.length == 6 || args.length == 16) {
2880
+ const mtx = new DOMMatrix(args);
2881
+ getInternalArray(this.#currentState.transform).set(getInternalArray(mtx));
2882
+ this.#transformDirty = true;
2883
+ }
2884
+ }
2885
+ transform(a, b, c, d, e, f) {
2886
+ const tf = this.getTransform();
2887
+ const mul = new DOMMatrix([a, b, c, d, e, f]);
2888
+ tf.multiplySelf(mul);
2889
+ this.setTransform(tf);
2890
+ }
2891
+ resetTransform() {
2892
+ getInternalArray(this.#currentState.transform).set([
2893
+ 1,
2894
+ 0,
2895
+ 0,
2896
+ 0,
2897
+ 0,
2898
+ 1,
2899
+ 0,
2900
+ 0,
2901
+ 0,
2902
+ 0,
2903
+ 1,
2904
+ 0,
2905
+ 0,
2906
+ 0,
2907
+ 0,
2908
+ 1
2909
+ ]);
2910
+ this.#transformDirty = true;
2911
+ }
2912
+ set globalAlpha(a) {
2913
+ this.#currentState.globalAlpha = Math.min(Math.max(a, 0), 1);
2914
+ let off = this.#alloc(16);
2915
+ this.#i32[off >> 2] = 7 /* SetGlobalAlpha */;
2916
+ this.#f32[off + 8 >> 2] = this.#currentState.globalAlpha;
2917
+ this.#scheduleFlush();
2918
+ }
2919
+ get globalAlpha() {
2920
+ return this.#currentState.globalAlpha;
2921
+ }
2922
+ set globalCompositeOperation(operation) {
2923
+ const composite = CanvasBlendMode[operation];
2924
+ if (composite) {
2925
+ this.#currentState.compositeOperation = operation;
2926
+ let off = this.#alloc(8);
2927
+ this.#i32[off >> 2] = 11 /* SetGlobalCompositeOperation */;
2928
+ this.#f32[off + 4 >> 2] = composite;
2929
+ this.#scheduleFlush();
2930
+ }
2931
+ }
2932
+ get globalCompositeOperation() {
2933
+ return this.#currentState.compositeOperation;
2934
+ }
2935
+ set filter(v) {
2936
+ const str = encodeCString(v);
2937
+ let off = this.#alloc(16);
2938
+ this.#i32[off >> 2] = 10 /* SetFilter */;
2939
+ writePtrU64(this.#u32, off + 8 >> 2, ptr3(str));
2940
+ this.#scheduleFlush();
2941
+ }
2942
+ get filter() {
2943
+ return this.#currentState.filter;
2944
+ }
2945
+ set imageSmoothingEnabled(value) {
2946
+ let off = this.#alloc(8);
2947
+ this.#i32[off >> 2] = 9 /* SetImageSmoothingEnabled */;
2948
+ this.#i32[off + 4 >> 2] = value ? 1 : 0;
2949
+ this.#currentState.imageSmoothingEnabled = value;
2950
+ this.#scheduleFlush();
2951
+ }
2952
+ get imageSmoothingEnabled() {
2953
+ return this.#currentState.imageSmoothingEnabled;
2954
+ }
2955
+ set imageSmoothingQuality(quality) {
2956
+ let smQuality = CanvasSmoothingQuality[quality];
2957
+ if (smQuality) {
2958
+ let off = this.#alloc(8);
2959
+ this.#i32[off >> 2] = 9 /* SetImageSmoothingEnabled */;
2960
+ this.#i32[off + 4 >> 2] = smQuality;
2961
+ this.#scheduleFlush();
2962
+ this.#currentState.imageSmoothingQuality = quality;
2963
+ }
2964
+ }
2965
+ get imageSmoothingQuality() {
2966
+ return this.#currentState.imageSmoothingQuality;
2967
+ }
2968
+ set fillStyle(style) {
2969
+ if (style == this.#currentState.fillStyle)
2970
+ return;
2971
+ if (typeof style === "string") {
2972
+ this.#setStyleColor(style, false);
2973
+ } else if (style instanceof CanvasGradient) {
2974
+ this.#setStyleGradient(style, false);
2975
+ }
2976
+ }
2977
+ get fillStyle() {
2978
+ return this.#currentState.fillStyle;
2979
+ }
2980
+ set strokeStyle(style) {
2981
+ if (typeof style === "string") {
2982
+ this.#setStyleColor(style, true);
2983
+ } else if (style instanceof CanvasGradient) {
2984
+ this.#setStyleGradient(style, true);
2985
+ }
2986
+ }
2987
+ get strokeStyle() {
2988
+ return this.#currentState.strokeStyle;
2989
+ }
2990
+ createConicGradient(...args) {
2991
+ if (args.length < 3)
2992
+ throw new TypeError(`Failed to execute 'createLinearGradient' on 'CanvasRenderingContext2D': 3 arguments required, but only ${args.length} present.`);
2993
+ return new CanvasGradient(INTERNAL_TOKEN, 2 /* Conic */, ...args);
2994
+ }
2995
+ createLinearGradient(...args) {
2996
+ if (args.length < 4)
2997
+ throw new TypeError(`Failed to execute 'createLinearGradient' on 'CanvasRenderingContext2D': 4 arguments required, but only ${args.length} present.`);
2998
+ return new CanvasGradient(INTERNAL_TOKEN, 0 /* Linear */, ...args);
2999
+ }
3000
+ createRadialGradient(...args) {
3001
+ if (args.length < 6)
3002
+ throw new TypeError(`Failed to execute 'createLinearGradient' on 'CanvasRenderingContext2D': 6 arguments required, but only ${args.length} present.`);
3003
+ return new CanvasGradient(INTERNAL_TOKEN, 1 /* Radial */, ...args);
3004
+ }
3005
+ set lineWidth(width) {
3006
+ let w = width < 1 ? 1 : width;
3007
+ let off = this.#alloc(16);
3008
+ this.#i32[off >> 2] = 6 /* SetLineWidth */;
3009
+ this.#f32[off + 8 >> 2] = w;
3010
+ this.#scheduleFlush();
3011
+ this.#currentState.lineWidth = w;
3012
+ }
3013
+ get lineWidth() {
3014
+ return this.#currentState.lineWidth;
3015
+ }
3016
+ set lineJoin(joinType) {
3017
+ let ljType = CanvasLineJoin[joinType];
3018
+ if (ljType) {
3019
+ let off = this.#alloc(16);
3020
+ this.#i32[off >> 2] = 16 /* SetLineJoin */;
3021
+ this.#f32[off + 8 >> 2] = ljType;
3022
+ this.#scheduleFlush();
3023
+ this.#currentState.lineJoin = joinType;
3024
+ }
3025
+ }
3026
+ get lineJoin() {
3027
+ return this.#currentState.lineJoin;
3028
+ }
3029
+ set lineDashOffset(v) {
3030
+ if (this.#currentState.lineDash.length <= 0) {
3031
+ this.#currentState.lineDashOffset = 0;
3032
+ return;
3033
+ }
3034
+ this.#currentState.lineDashOffset = v;
3035
+ const len = this.#currentState.lineDash.length;
3036
+ let off = this.#alloc(12 + len * 4);
3037
+ this.#i32[off >> 2] = 17 /* SetLineDash */;
3038
+ this.#f32[off + 4 >> 2] = this.#currentState.lineDashOffset;
3039
+ this.#i32[off + 8 >> 2] = len;
3040
+ const base = off + 12 >> 2;
3041
+ for (let i = 0;i < len; i++) {
3042
+ this.#f32[base + i] = this.#currentState.lineDash[i];
3043
+ }
3044
+ this.#scheduleFlush();
3045
+ }
3046
+ setLineDash(lines) {
3047
+ if (lines.constructor.name.toLowerCase().includes("array")) {
3048
+ let _a;
3049
+ if (lines.length & 1) {
3050
+ _a = lines.concat(Array.from(lines));
3051
+ } else {
3052
+ _a = lines;
2172
3053
  }
2173
- case 1 /* Radial */: {
2174
- this.points[0] = args[2];
2175
- this.points[1] = args[3];
2176
- this.points[2] = args[4];
2177
- this.points[3] = args[5];
2178
- this.points[4] = args[6];
2179
- this.points[5] = args[7];
2180
- break;
3054
+ if (_a.some(Number.isNaN))
3055
+ return;
3056
+ const len = _a.length;
3057
+ let off = this.#alloc(12 + len * 4);
3058
+ this.#i32[off >> 2] = 17 /* SetLineDash */;
3059
+ this.#f32[off + 4 >> 2] = len;
3060
+ this.#i32[off + 8 >> 2] = len;
3061
+ const base = off + 12 >> 2;
3062
+ for (let i = 0;i < len; i++) {
3063
+ this.#f32[base + i] = _a[i];
2181
3064
  }
2182
- case 2 /* Conic */: {
2183
- this.points[0] = args[2];
2184
- this.points[1] = args[3];
2185
- this.points[2] = args[4];
2186
- break;
3065
+ this.#scheduleFlush();
3066
+ this.#currentState.lineDash = _a;
3067
+ return;
3068
+ }
3069
+ throw new TypeError(`Failed to execute 'setLineDash' on 'CanvasRenderingContext2D': The provided value cannot be converted to a sequence.`);
3070
+ }
3071
+ getLineDash() {
3072
+ return this.#currentState.lineDash;
3073
+ }
3074
+ set shadowBlur(blur) {
3075
+ lib.symbols.canvas_set_shadow_blur(ptrs.get(this), blur);
3076
+ }
3077
+ set shadowColor(col) {
3078
+ lib.symbols.canvas_set_shadow_color(ptrs.get(this), encoder.encode(`${col}\x00`));
3079
+ }
3080
+ set shadowOffsetX(x) {
3081
+ lib.symbols.canvas_set_shadow_offsetX(ptrs.get(this), x);
3082
+ }
3083
+ set shadowOffsetY(y) {
3084
+ lib.symbols.canvas_set_shadow_offsetY(ptrs.get(this), y);
3085
+ }
3086
+ fillRect(x, y, w, h) {
3087
+ if (this.#transformDirty)
3088
+ this.#uploadTransform();
3089
+ let off = this.#alloc(40);
3090
+ this.#i32[off >> 2] = 25 /* FillRect */;
3091
+ this.#f64[off + 8 >> 3] = x;
3092
+ this.#f64[off + 16 >> 3] = y;
3093
+ this.#f64[off + 24 >> 3] = w;
3094
+ this.#f64[off + 32 >> 3] = h;
3095
+ this.#scheduleFlush();
3096
+ }
3097
+ strokeRect(x, y, w, h) {
3098
+ if (this.#transformDirty)
3099
+ this.#uploadTransform();
3100
+ let off = this.#alloc(40);
3101
+ this.#i32[off >> 2] = 26 /* StrokeRect */;
3102
+ this.#f64[off + 8 >> 3] = x;
3103
+ this.#f64[off + 16 >> 3] = y;
3104
+ this.#f64[off + 24 >> 3] = w;
3105
+ this.#f64[off + 32 >> 3] = h;
3106
+ this.#scheduleFlush();
3107
+ }
3108
+ clearRect(x, y, w, h) {
3109
+ if (this.#transformDirty)
3110
+ this.#uploadTransform();
3111
+ let off = this.#alloc(40);
3112
+ this.#i32[off >> 2] = 27 /* ClearRect */;
3113
+ this.#f64[off + 8 >> 3] = x;
3114
+ this.#f64[off + 16 >> 3] = y;
3115
+ this.#f64[off + 24 >> 3] = w;
3116
+ this.#f64[off + 32 >> 3] = h;
3117
+ this.#scheduleFlush();
3118
+ }
3119
+ beginPath() {
3120
+ if (this.#transformDirty)
3121
+ this.#uploadTransform();
3122
+ let off = this.#alloc(8);
3123
+ this.#i32[off >> 2] = 30 /* BeginPath */;
3124
+ this.#scheduleFlush();
3125
+ }
3126
+ closePath() {
3127
+ if (this.#transformDirty)
3128
+ this.#uploadTransform();
3129
+ let off = this.#alloc(8);
3130
+ this.#i32[off >> 2] = 38 /* ClosePath */;
3131
+ this.#scheduleFlush();
3132
+ }
3133
+ moveTo(x, y) {
3134
+ if (this.#transformDirty)
3135
+ this.#uploadTransform();
3136
+ let off = this.#alloc(24);
3137
+ this.#i32[off >> 2] = 31 /* MoveTo */;
3138
+ this.#f64[off + 8 >> 3] = x;
3139
+ this.#f64[off + 16 >> 3] = y;
3140
+ this.#scheduleFlush();
3141
+ }
3142
+ lineTo(x, y) {
3143
+ if (this.#transformDirty)
3144
+ this.#uploadTransform();
3145
+ let off = this.#alloc(24);
3146
+ this.#i32[off >> 2] = 32 /* LineTo */;
3147
+ this.#f64[off + 8 >> 3] = x;
3148
+ this.#f64[off + 16 >> 3] = y;
3149
+ this.#scheduleFlush();
3150
+ }
3151
+ bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) {
3152
+ if (this.#transformDirty)
3153
+ this.#uploadTransform();
3154
+ let off = this.#alloc(56);
3155
+ this.#i32[off >> 2] = 36 /* BezierCurveTo */;
3156
+ this.#f64[off + 8 >> 3] = cp1x;
3157
+ this.#f64[off + 16 >> 3] = cp1y;
3158
+ this.#f64[off + 24 >> 3] = cp2x;
3159
+ this.#f64[off + 32 >> 3] = cp2y;
3160
+ this.#f64[off + 40 >> 3] = x;
3161
+ this.#f64[off + 48 >> 3] = y;
3162
+ this.#scheduleFlush();
3163
+ }
3164
+ quadraticCurveTo(cpx, cpy, x, y) {
3165
+ if (this.#transformDirty)
3166
+ this.#uploadTransform();
3167
+ let off = this.#alloc(40);
3168
+ this.#i32[off >> 2] = 37 /* QuadraticCurveTo */;
3169
+ this.#f64[off + 8 >> 3] = cpx;
3170
+ this.#f64[off + 16 >> 3] = cpy;
3171
+ this.#f64[off + 24 >> 3] = x;
3172
+ this.#f64[off + 32 >> 3] = y;
3173
+ this.#scheduleFlush();
3174
+ }
3175
+ arc(x, y, radius, startAngle, endAngle) {
3176
+ if (this.#transformDirty)
3177
+ this.#uploadTransform();
3178
+ let off = this.#alloc(32);
3179
+ this.#i32[off >> 2] = 33 /* Arc */;
3180
+ this.#f32[off + 8 >> 2] = x;
3181
+ this.#f32[off + 12 >> 2] = y;
3182
+ this.#f32[off + 16 >> 2] = radius;
3183
+ this.#f32[off + 20 >> 2] = startAngle;
3184
+ this.#f32[off + 24 >> 2] = endAngle;
3185
+ this.#scheduleFlush();
3186
+ }
3187
+ arcTo(x1, y1, x2, y2, radius) {
3188
+ if (this.#transformDirty)
3189
+ this.#uploadTransform();
3190
+ let off = this.#alloc(48);
3191
+ this.#i32[off >> 2] = 35 /* ArcTo */;
3192
+ this.#f64[off + 8 >> 3] = x1;
3193
+ this.#f64[off + 16 >> 3] = y1;
3194
+ this.#f64[off + 24 >> 3] = x2;
3195
+ this.#f64[off + 32 >> 3] = y2;
3196
+ this.#f64[off + 40 >> 3] = radius;
3197
+ this.#scheduleFlush();
3198
+ }
3199
+ ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, counterclockwise = false) {
3200
+ if (this.#transformDirty)
3201
+ this.#uploadTransform();
3202
+ let off = this.#alloc(64);
3203
+ this.#i32[off >> 2] = 34 /* Ellipse */;
3204
+ this.#i32[off + 4 >> 2] = Number(counterclockwise);
3205
+ this.#f64[off + 8 >> 3] = x;
3206
+ this.#f64[off + 16 >> 3] = y;
3207
+ this.#f64[off + 24 >> 3] = radiusX;
3208
+ this.#f64[off + 32 >> 3] = radiusY;
3209
+ this.#f64[off + 40 >> 3] = rotation;
3210
+ this.#f64[off + 48 >> 3] = startAngle;
3211
+ this.#f64[off + 56 >> 3] = endAngle;
3212
+ this.#scheduleFlush();
3213
+ }
3214
+ rect(x, y, width, height) {
3215
+ if (this.#transformDirty)
3216
+ this.#uploadTransform();
3217
+ let off = this.#alloc(40);
3218
+ this.#i32[off >> 2] = 39 /* Rect */;
3219
+ this.#f64[off + 8 >> 3] = x;
3220
+ this.#f64[off + 16 >> 3] = y;
3221
+ this.#f64[off + 24 >> 3] = width;
3222
+ this.#f64[off + 32 >> 3] = height;
3223
+ this.#scheduleFlush();
3224
+ }
3225
+ roundRect(x, y, width, height, radii) {
3226
+ if (radii.constructor.name.toLowerCase().includes("array")) {
3227
+ if (radii.some(Number.isNaN))
3228
+ return;
3229
+ if (this.#transformDirty)
3230
+ this.#uploadTransform();
3231
+ let off = this.#alloc(56);
3232
+ const len = radii.length;
3233
+ this.#i32[off >> 2] = 41 /* RoundRectArray */;
3234
+ this.#i32[off + 4 >> 2] = len;
3235
+ this.#f64[off + 8 >> 3] = x;
3236
+ this.#f64[off + 16 >> 3] = y;
3237
+ this.#f64[off + 24 >> 3] = width;
3238
+ this.#f64[off + 32 >> 3] = height;
3239
+ this.#f32[off + 40 >> 2] = radii[0] ?? 0;
3240
+ this.#f32[off + 44 >> 2] = radii[1] ?? 0;
3241
+ this.#f32[off + 48 >> 2] = radii[2] ?? 0;
3242
+ this.#f32[off + 52 >> 2] = radii[3] ?? 0;
3243
+ this.#scheduleFlush();
3244
+ return;
3245
+ } else {
3246
+ if (this.#transformDirty)
3247
+ this.#uploadTransform();
3248
+ let off = this.#alloc(48);
3249
+ this.#i32[off >> 2] = 40 /* RoundRect */;
3250
+ this.#f64[off + 8 >> 3] = x;
3251
+ this.#f64[off + 16 >> 3] = y;
3252
+ this.#f64[off + 24 >> 3] = width;
3253
+ this.#f64[off + 32 >> 3] = height;
3254
+ this.#f64[off + 40 >> 3] = radii;
3255
+ this.#scheduleFlush();
3256
+ }
3257
+ }
3258
+ fill(path) {
3259
+ if (this.#transformDirty)
3260
+ this.#uploadTransform();
3261
+ this.#batchPathOperation(43 /* FillPath */, 42 /* Fill */, path);
3262
+ }
3263
+ stroke(path) {
3264
+ if (this.#transformDirty)
3265
+ this.#uploadTransform();
3266
+ this.#batchPathOperation(45 /* StrokePath */, 44 /* Stroke */, path);
3267
+ }
3268
+ clip(path) {
3269
+ if (this.#transformDirty)
3270
+ this.#uploadTransform();
3271
+ this.#batchPathOperation(47 /* ClipPath */, 46 /* Clip */, path);
3272
+ }
3273
+ set font(css) {
3274
+ const normalized = css.trim().toLowerCase();
3275
+ const encoded = encodeCString(normalized);
3276
+ let off = this.#alloc(16);
3277
+ this.#i32[off >> 2] = 1 /* SetFont */;
3278
+ writePtrU64(this.#u32, off + 8 >> 2, ptr3(encoded));
3279
+ this.#currentState.fontCss = normalized;
3280
+ this.#scheduleFlush();
3281
+ }
3282
+ get font() {
3283
+ return this.#currentState.fontCss;
3284
+ }
3285
+ set textAlign(alignment) {
3286
+ const al = CanvasTextAlignment[alignment];
3287
+ if (!al)
3288
+ return;
3289
+ let off = this.#alloc(8);
3290
+ this.#i32[off >> 2] = 20 /* SetTextAlign */;
3291
+ this.#i32[off + 4 >> 2] = al;
3292
+ this.#currentState.textAlign = alignment;
3293
+ this.#scheduleFlush();
3294
+ }
3295
+ set textBaseline(baseline) {
3296
+ const bl = CanvasTextBaseline[baseline];
3297
+ if (!bl)
3298
+ return;
3299
+ let off = this.#alloc(8);
3300
+ this.#i32[off >> 2] = 19 /* SetTextBaseline */;
3301
+ this.#i32[off + 4 >> 2] = bl;
3302
+ this.#currentState.textBaseline = baseline;
3303
+ this.#scheduleFlush();
3304
+ }
3305
+ fillText(text, x, y, maxWidth = -1) {
3306
+ if (this.#transformDirty)
3307
+ this.#uploadTransform();
3308
+ const encoded = encoder.encode(`${text}\x00`);
3309
+ this.#retained.push(encoded);
3310
+ let off = this.#alloc(40);
3311
+ this.#i32[off >> 2] = 28 /* FillText */;
3312
+ this.#i32[off + 4 >> 2] = text.length;
3313
+ writePtrU64(this.#u32, off + 8 >> 2, ptr3(encoded));
3314
+ this.#f64[off + 16 >> 3] = x;
3315
+ this.#f64[off + 24 >> 3] = y;
3316
+ this.#f64[off + 32 >> 3] = maxWidth;
3317
+ this.#scheduleFlush();
3318
+ }
3319
+ strokeText(text, x, y, maxWidth = -1) {
3320
+ if (this.#transformDirty)
3321
+ this.#uploadTransform();
3322
+ const encoded = encoder.encode(`${text}\x00`);
3323
+ this.#retained.push(encoded);
3324
+ let off = this.#alloc(40);
3325
+ this.#i32[off >> 2] = 29 /* StrokeText */;
3326
+ writePtrU64(this.#u32, off + 8 >> 2, ptr3(encoded));
3327
+ this.#f64[off + 16 >> 3] = x;
3328
+ this.#f64[off + 24 >> 3] = y;
3329
+ this.#f64[off + 32 >> 3] = maxWidth;
3330
+ this.#scheduleFlush();
3331
+ }
3332
+ measureText(text) {
3333
+ if (this.#transformDirty)
3334
+ this.#uploadTransform();
3335
+ const pArr = new Float32Array(12);
3336
+ lib.symbols.canvas_measure_text(ptrs.get(this), encoder.encode(`${text}\x00`), ptr3(pArr));
3337
+ return new TextMetrics(INTERNAL_TOKEN, pArr[0], pArr[1], pArr[2], pArr[3], pArr[4], pArr[5], pArr[6], pArr[7], pArr[8], pArr[9], pArr[10], pArr[11]);
3338
+ }
3339
+ drawImage(img, ...args) {
3340
+ const len = args.length;
3341
+ if (len == 2 || len == 4 || len == 8) {
3342
+ if (img instanceof Image) {
3343
+ if (this.#transformDirty)
3344
+ this.#uploadTransform();
3345
+ this.#retained.push(img);
3346
+ let off = this.#alloc(48);
3347
+ this.#i32[off >> 2] = 48 /* DrawImage_ImageType */;
3348
+ this.#i32[off + 4 >> 2] = len == 2 ? 4 : len;
3349
+ writePtrU64(this.#u32, off + 8 >> 2, ptrs.get(img));
3350
+ this.#f32[off + 16 >> 2] = args[0] ?? 0;
3351
+ this.#f32[off + 20 >> 2] = args[1] ?? 0;
3352
+ this.#f32[off + 24 >> 2] = len == 2 ? img.width : args[2] ?? 0;
3353
+ this.#f32[off + 28 >> 2] = len == 2 ? img.height : args[3] ?? 0;
3354
+ this.#f32[off + 32 >> 2] = args[4] ?? 0;
3355
+ this.#f32[off + 36 >> 2] = args[5] ?? 0;
3356
+ this.#f32[off + 40 >> 2] = args[6] ?? 0;
3357
+ this.#f32[off + 44 >> 2] = args[7] ?? 0;
3358
+ this.#scheduleFlush();
3359
+ return;
3360
+ }
3361
+ if (img instanceof Canvas) {
3362
+ const ctx2d = ctx2ds.get(img);
3363
+ if (!ctx2d)
3364
+ return;
3365
+ let ctxPtr = ptrs.get(ctx2d);
3366
+ if (this.#transformDirty)
3367
+ this.#uploadTransform();
3368
+ this.#retained.push(img);
3369
+ ctx2ds.get(img).#flush();
3370
+ let off = this.#alloc(48);
3371
+ this.#i32[off >> 2] = 49 /* DrawImage_CanvasType */;
3372
+ this.#i32[off + 4 >> 2] = len == 2 ? 4 : len;
3373
+ writePtrU64(this.#u32, off + 8 >> 2, ctxPtr);
3374
+ this.#f32[off + 16 >> 2] = args[0] ?? 0;
3375
+ this.#f32[off + 20 >> 2] = args[1] ?? 0;
3376
+ this.#f32[off + 24 >> 2] = len == 2 ? img.width : args[2] ?? 0;
3377
+ this.#f32[off + 28 >> 2] = len == 2 ? img.height : args[3] ?? 0;
3378
+ this.#f32[off + 32 >> 2] = args[4] ?? 0;
3379
+ this.#f32[off + 36 >> 2] = args[5] ?? 0;
3380
+ this.#f32[off + 40 >> 2] = args[6] ?? 0;
3381
+ this.#f32[off + 44 >> 2] = args[7] ?? 0;
3382
+ this.#scheduleFlush();
3383
+ return;
2187
3384
  }
3385
+ } else if (len + Number(!!img) < 3) {
3386
+ throw new TypeError(`Failed to execute 'drawImage' on '${this.constructor.name}': 3 arguments required, but only ${len + Number(!!img)} present`);
3387
+ } else {
3388
+ throw new TypeError(`Failed to execute 'drawImage' on '${this.constructor.name}': Overload resolution failed.`);
2188
3389
  }
3390
+ throw new TypeError(`Failed to execute 'drawImage' on '${this.constructor.name}': The provided value is not of type '(Image or Canvas)'.`);
2189
3391
  }
2190
- addColorStop(offset, color) {
2191
- if (offset < 0 || offset > 1)
2192
- throw new RangeError(`Failed to execute 'addColorStop' on 'CanvasGradient': The provided value (${offset}) is outside the range (0.0, 1.0).`);
2193
- if (!isValidColor(color))
2194
- throw new SyntaxError(`Failed to execute 'addColorStop' on 'CanvasGradient': The value provided ('${color}') could not be parsed as a color.`);
2195
- const idx = this.offsets.findIndex((o) => o > offset);
2196
- const insertIdx = idx === -1 ? this.offsets.length : idx;
2197
- this.offsets.splice(insertIdx, 0, offset);
2198
- this.colors.splice(insertIdx, 0, encodeCString(color));
3392
+ getImageData(x, y, w, h) {
3393
+ const arr = new Uint8ClampedArray(w * h * 4);
3394
+ lib.symbols.canvas_get_image_data(ptrs.get(this), x, y, w, h, ptr3(arr));
3395
+ return new ImageData(arr, w, h);
3396
+ }
3397
+ putImageData(data, dx, dy, dirtyX = 0, dirtyY = 0, dirtyWidth = data.width, dirtyHeight = data.height) {
3398
+ if (!(data instanceof ImageData)) {
3399
+ throw new TypeError("Failed to execute 'putImageData' on 'CanvasRenderingContext2D': " + "parameter 1 is not of type 'ImageData'");
3400
+ }
3401
+ lib.symbols.canvas_put_image_data(ptrs.get(this), dx, dy, data.width, data.height, dirtyX, dirtyY, dirtyWidth, dirtyHeight, ptr3(data.data));
2199
3402
  }
2200
3403
  }
2201
3404
  {
2202
- const proto = CanvasGradient.prototype;
3405
+ const proto = CanvasBatchedRenderingContext2D.prototype;
2203
3406
  for (const key of Object.getOwnPropertyNames(proto)) {
2204
3407
  const desc = Object.getOwnPropertyDescriptor(proto, key);
2205
3408
  if (key == "constructor") {
@@ -2213,76 +3416,28 @@ class CanvasGradient {
2213
3416
  }
2214
3417
  }
2215
3418
  }
2216
-
2217
- class Render2DState {
2218
- lineWidth = 0;
2219
- globalAlpha = 1;
2220
- imageSmoothingQuality = "low";
2221
- imageSmoothingEnabled = true;
2222
- fillStyle = "#000000";
2223
- strokeStyle = "#000000";
2224
- compositeOperation = "source-over";
2225
- filter = "none";
2226
- fontCss = "10px sans-serif";
2227
- textBaseline = "alphabetic";
2228
- textAlign = "start";
2229
- lineDash = [];
2230
- lineDashOffset = 0;
2231
- lineJoin = "miter";
2232
- constructor(other) {
2233
- if (other instanceof Render2DState) {
2234
- this.lineWidth = other.lineWidth;
2235
- this.globalAlpha = other.globalAlpha;
2236
- this.imageSmoothingQuality = other.imageSmoothingQuality;
2237
- this.imageSmoothingEnabled = other.imageSmoothingEnabled;
2238
- this.fillStyle = other.fillStyle;
2239
- this.strokeStyle = other.strokeStyle;
2240
- this.compositeOperation = other.compositeOperation;
2241
- this.filter = other.filter;
2242
- this.fontCss = other.fontCss;
2243
- this.textBaseline = other.textBaseline;
2244
- this.textAlign = other.textAlign;
2245
- this.lineDash = other.lineDash;
2246
- this.lineDashOffset = other.lineDashOffset;
2247
- this.lineJoin = other.lineJoin;
2248
- }
2249
- }
2250
- copyFrom(other) {
2251
- if (other instanceof Render2DState) {
2252
- this.lineWidth = other.lineWidth;
2253
- this.globalAlpha = other.globalAlpha;
2254
- this.imageSmoothingQuality = other.imageSmoothingQuality;
2255
- this.imageSmoothingEnabled = other.imageSmoothingEnabled;
2256
- this.fillStyle = other.fillStyle;
2257
- this.strokeStyle = other.strokeStyle;
2258
- this.compositeOperation = other.compositeOperation;
2259
- this.filter = other.filter;
2260
- this.fontCss = other.fontCss;
2261
- this.textBaseline = other.textBaseline;
2262
- this.textAlign = other.textAlign;
2263
- this.lineDash = other.lineDash;
2264
- this.lineDashOffset = other.lineDashOffset;
2265
- this.lineJoin = other.lineJoin;
2266
- }
2267
- }
2268
- }
2269
-
2270
- class CanvasRenderingContext2D {
3419
+ // BunCanvas/src/Canvas/RenderingContexts/2D/CanvasImmediateRenderingContext2D.ts
3420
+ import { ptr as ptr4 } from "bun:ffi";
3421
+ class CanvasImmediateRenderingContext2D extends CanvasRenderingContext2D {
2271
3422
  #currentState = new Render2DState;
2272
3423
  #savedState = new Render2DState;
2273
3424
  #owner;
2274
- #reset() {
2275
- this.#currentState = new Render2DState;
3425
+ reset(token, w, h) {
3426
+ if (w && h) {
3427
+ lib.symbols.canvas_resize(ptrs.get(this), w, h);
3428
+ this.#savedState = new Render2DState;
3429
+ this.#currentState = new Render2DState;
3430
+ }
2276
3431
  }
2277
3432
  #setStyleGradient(style, isStroke) {
2278
3433
  const count = style.colors.length;
2279
3434
  const ptrArray = new BigUint64Array(count);
2280
3435
  for (let i = 0;i < count; i++) {
2281
- ptrArray[i] = BigInt(ptr3(style.colors[i]));
3436
+ ptrArray[i] = BigInt(ptr4(style.colors[i]));
2282
3437
  }
2283
3438
  const offsetBuffer = new Float32Array(style.offsets);
2284
3439
  const nativeFn = isStroke ? lib.symbols.canvas_set_stroke_style_gradient : lib.symbols.canvas_set_fill_style_gradient;
2285
- return nativeFn(ptrs.get(this), style.type, ptr3(style.points), count, ptr3(ptrArray), ptr3(offsetBuffer));
3440
+ return nativeFn(ptrs.get(this), style.type, ptr4(style.points), count, ptr4(ptrArray), ptr4(offsetBuffer));
2286
3441
  }
2287
3442
  get canvas() {
2288
3443
  return this.#owner;
@@ -2427,7 +3582,7 @@ class CanvasRenderingContext2D {
2427
3582
  if (arr.some(Number.isNaN))
2428
3583
  return;
2429
3584
  const len = arr.length;
2430
- lib.symbols.canvas_path_roundrect_array(ptrs.get(this), x, y, width, height, ptr3(arr), len);
3585
+ lib.symbols.canvas_path_roundrect_array(ptrs.get(this), x, y, width, height, ptr4(arr), len);
2431
3586
  return;
2432
3587
  } else {
2433
3588
  lib.symbols.canvas_path_roundrect(ptrs.get(this), x, y, width, height, radii);
@@ -2467,25 +3622,29 @@ class CanvasRenderingContext2D {
2467
3622
  const arr = new Float32Array(_arr);
2468
3623
  const len = arr.length;
2469
3624
  if (img instanceof Image) {
2470
- lib.symbols.canvas_draw_image_imageType(ptrs.get(this), img.ptr, ptr3(arr), len);
3625
+ lib.symbols.canvas_draw_image_imageType(ptrs.get(this), ptrs.get(img), ptr4(arr), len);
2471
3626
  return;
2472
3627
  }
2473
3628
  if (img instanceof Canvas) {
2474
- lib.symbols.canvas_draw_image_canvasType(ptrs.get(this), ptrs.get(img), ptr3(arr), len);
3629
+ const ctx2d = ctx2ds.get(img);
3630
+ if (!ctx2d)
3631
+ return;
3632
+ let ctxPtr = ptrs.get(ctx2d);
3633
+ lib.symbols.canvas_draw_image_canvasType(ptrs.get(this), ctxPtr, ptr4(arr), len);
2475
3634
  return;
2476
3635
  }
2477
3636
  throw new TypeError("Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(Image or Canvas)'.");
2478
3637
  }
2479
3638
  getImageData(x, y, w, h) {
2480
3639
  const arr = new Uint8ClampedArray(w * h * 4);
2481
- lib.symbols.canvas_get_image_data(ptrs.get(this), x, y, w, h, ptr3(arr));
3640
+ lib.symbols.canvas_get_image_data(ptrs.get(this), x, y, w, h, ptr4(arr));
2482
3641
  return new ImageData(arr, w, h);
2483
3642
  }
2484
3643
  putImageData(data, dx, dy, dirtyX = 0, dirtyY = 0, dirtyWidth = data.width, dirtyHeight = data.height) {
2485
3644
  if (!(data instanceof ImageData)) {
2486
3645
  throw new TypeError("Failed to execute 'putImageData' on 'CanvasRenderingContext2D': " + "parameter 1 is not of type 'ImageData'");
2487
3646
  }
2488
- lib.symbols.canvas_put_image_data(ptrs.get(this), dx, dy, data.width, data.height, dirtyX, dirtyY, dirtyWidth, dirtyHeight, ptr3(data.data));
3647
+ lib.symbols.canvas_put_image_data(ptrs.get(this), dx, dy, data.width, data.height, dirtyX, dirtyY, dirtyWidth, dirtyHeight, ptr4(data.data));
2489
3648
  }
2490
3649
  save() {
2491
3650
  this.#savedState?.copyFrom(this.#currentState);
@@ -2520,18 +3679,20 @@ class CanvasRenderingContext2D {
2520
3679
  }
2521
3680
  getTransform() {
2522
3681
  let arr = new Float32Array(16);
2523
- lib.symbols.canvas_get_transform(ptrs.get(this), ptr3(arr));
3682
+ lib.symbols.canvas_get_transform(ptrs.get(this), ptr4(arr));
2524
3683
  return new DOMMatrix(arr);
2525
3684
  }
2526
3685
  setTransform(...args) {
2527
3686
  if (args[0] instanceof DOMMatrix)
2528
- lib.symbols.canvas_set_transform(ptrs.get(this), args[0].ptr);
3687
+ lib.symbols.canvas_set_transform(ptrs.get(this), ptr4(getInternalArray(args[0])));
2529
3688
  if (args.length == 6) {
2530
3689
  const mtx = new DOMMatrix([args[0], args[1], args[2], args[3], args[4], args[5]]);
2531
- lib.symbols.canvas_set_transform(ptrs.get(this), mtx.ptr);
3690
+ lib.symbols.canvas_set_transform(ptrs.get(this), getInternalArray(mtx));
3691
+ }
3692
+ if (args.length == 16) {
3693
+ const mtx = new DOMMatrix([args[0], args[1], args[2], args[3], args[4], args[5], args[5], args[6], args[7], args[8], args[9], args[10], args[11], args[12], args[13], args[14], args[15]]);
3694
+ lib.symbols.canvas_set_transform(ptrs.get(this), ptr4(getInternalArray(mtx)));
2532
3695
  }
2533
- if (args.length == 16)
2534
- lib.symbols.canvas_set_transform(ptrs.get(this), new DOMMatrix([args[0], args[1], args[2], args[3], args[4], args[5], args[5], args[6], args[7], args[8], args[9], args[10], args[11], args[12], args[13], args[14], args[15]]).ptr);
2535
3696
  }
2536
3697
  transform(a, b, c, d, e, f) {
2537
3698
  const tf = this.getTransform();
@@ -2553,7 +3714,7 @@ class CanvasRenderingContext2D {
2553
3714
  const arr = new Float32Array(_a);
2554
3715
  if (arr.some(Number.isNaN))
2555
3716
  return;
2556
- lib.symbols.canvas_set_line_dash(ptrs.get(this), ptr3(arr), arr.length, this.#currentState.lineDashOffset);
3717
+ lib.symbols.canvas_set_line_dash(ptrs.get(this), ptr4(arr), arr.length, this.#currentState.lineDashOffset);
2557
3718
  this.#currentState.lineDash = _a;
2558
3719
  return;
2559
3720
  }
@@ -2571,7 +3732,7 @@ class CanvasRenderingContext2D {
2571
3732
  return;
2572
3733
  }
2573
3734
  const arr = new Float32Array(this.#currentState.lineDash);
2574
- lib.symbols.canvas_set_line_dash(ptrs.get(this), ptr3(arr), arr.length, v);
3735
+ lib.symbols.canvas_set_line_dash(ptrs.get(this), ptr4(arr), arr.length, v);
2575
3736
  this.#currentState.lineDashOffset = v;
2576
3737
  }
2577
3738
  set textBaseline(baseline) {
@@ -2592,24 +3753,21 @@ class CanvasRenderingContext2D {
2592
3753
  }
2593
3754
  measureText(text) {
2594
3755
  const pArr = new Float32Array(12);
2595
- lib.symbols.canvas_measure_text(ptrs.get(this), encoder.encode(`${text}\x00`), ptr3(pArr));
3756
+ lib.symbols.canvas_measure_text(ptrs.get(this), encoder.encode(`${text}\x00`), ptr4(pArr));
2596
3757
  return new TextMetrics(INTERNAL_TOKEN, pArr[0], pArr[1], pArr[2], pArr[3], pArr[4], pArr[5], pArr[6], pArr[7], pArr[8], pArr[9], pArr[10], pArr[11]);
2597
3758
  }
2598
- constructor(iptr, cnv, args, token) {
3759
+ constructor(width, height, cnv, args, token) {
3760
+ super();
2599
3761
  if (token !== INTERNAL_TOKEN)
2600
3762
  throwIllegalConstructor(this);
2601
- const { desynchronized = false, alpha = true } = args ?? {};
2602
- const cb = new JSCallback(this.#reset.bind(this), {
2603
- args: [],
2604
- returns: "void"
2605
- });
2606
- const renderContextPtr = lib.symbols.canvas_get_context2D(iptr, cb.ptr, desynchronized, alpha);
3763
+ const { desynchronized = false, alpha = true, willReadFrequently = false } = args ?? {};
3764
+ const renderContextPtr = lib.symbols.canvas_get_context2D(width, height, desynchronized, alpha, willReadFrequently, true);
2607
3765
  this.#owner = cnv;
2608
3766
  ptrs.set(this, renderContextPtr);
2609
3767
  }
2610
3768
  }
2611
3769
  {
2612
- const proto = CanvasRenderingContext2D.prototype;
3770
+ const proto = CanvasImmediateRenderingContext2D.prototype;
2613
3771
  for (const key of Object.getOwnPropertyNames(proto)) {
2614
3772
  const desc = Object.getOwnPropertyDescriptor(proto, key);
2615
3773
  if (key == "constructor") {
@@ -2623,36 +3781,39 @@ class CanvasRenderingContext2D {
2623
3781
  }
2624
3782
  }
2625
3783
  }
3784
+ // BunCanvas/src/Canvas.ts
3785
+ var canvasFinalizationRegistry = new FinalizationRegistry((ptr) => {
3786
+ lib.symbols.canvas_destroy(ptr);
3787
+ });
2626
3788
 
2627
3789
  class Canvas {
2628
3790
  #dim = new Float64Array(2);
2629
- #rCapture = {
2630
- cb: () => {}
2631
- };
2632
- constructor(w = 1, h = 1, options) {
2633
- this.#dim[0] = w;
2634
- this.#dim[1] = h;
2635
- let ptr;
2636
- if (Bun.isMainThread) {
2637
- ptr = lib.symbols.canvas_create(w, h, options ? options.gpu : true);
2638
- } else {
2639
- ptr = lib.symbols.canvas_create(w, h, false);
3791
+ #resizequeued = false;
3792
+ #resizeQueueCb() {
3793
+ if (this.#ctx) {
3794
+ this.#ctx.reset(INTERNAL_TOKEN, this.#dim[0], this.#dim[1]);
2640
3795
  }
2641
- ptrs.set(this, ptr);
2642
- canvasFinalizationRegistry.register(this, ptr);
3796
+ this.#resizequeued = false;
2643
3797
  }
2644
- get _ptr() {
2645
- return ptrs.get(this);
3798
+ #resizeQueueCbBound = () => this.#resizeQueueCb();
3799
+ #ctx = null;
3800
+ constructor(w = 1, h = 1) {
3801
+ this.#dim[0] = w;
3802
+ this.#dim[1] = h;
2646
3803
  }
2647
3804
  set width(v) {
2648
- this.#dim[0] = Number.parseInt(v);
2649
- this.#rCapture.cb();
2650
- lib.symbols.canvas_resize(ptrs.get(this), this.#dim[0], this.#dim[1]);
3805
+ this.#dim[0] = v < 1 ? 1 : v;
3806
+ if (!this.#resizequeued) {
3807
+ this.#resizequeued = true;
3808
+ queueMicrotask(this.#resizeQueueCbBound);
3809
+ }
2651
3810
  }
2652
3811
  set height(v) {
2653
- this.#dim[1] = Number.parseInt(v);
2654
- this.#rCapture.cb();
2655
- lib.symbols.canvas_resize(ptrs.get(this), this.#dim[0], this.#dim[1]);
3812
+ this.#dim[1] = v < 1 ? 1 : v;
3813
+ if (!this.#resizequeued) {
3814
+ this.#resizequeued = true;
3815
+ queueMicrotask(this.#resizeQueueCbBound);
3816
+ }
2656
3817
  }
2657
3818
  get width() {
2658
3819
  return this.#dim[0];
@@ -2662,7 +3823,18 @@ class Canvas {
2662
3823
  }
2663
3824
  getContext(contextType, args) {
2664
3825
  if (contextType == "2d") {
2665
- return new CanvasRenderingContext2D(ptrs.get(this), this, args, INTERNAL_TOKEN);
3826
+ if (this.#ctx)
3827
+ return this.#ctx;
3828
+ if (!args || !args?.pipeline || args?.pipeline == "batched") {
3829
+ this.#ctx = new CanvasBatchedRenderingContext2D(this.#dim[0], this.#dim[1], this, args, INTERNAL_TOKEN);
3830
+ } else if (args?.pipeline == "immediate") {
3831
+ this.#ctx = new CanvasImmediateRenderingContext2D(this.#dim[0], this.#dim[1], this, args, INTERNAL_TOKEN);
3832
+ } else {
3833
+ throw new SyntaxError(`Failed to execute 'getContext' on '${this.constructor.name}': unknown pipeline: ${args?.pipeline}`);
3834
+ }
3835
+ if (!ctx2ds.has(this))
3836
+ ctx2ds.set(this, this.#ctx);
3837
+ return this.#ctx;
2666
3838
  }
2667
3839
  }
2668
3840
  getBoundingClientRect() {
@@ -2693,95 +3865,20 @@ class Canvas {
2693
3865
  }
2694
3866
  }
2695
3867
  }
2696
- // BunCanvas/src/Path2D.ts
2697
- import { ptr as ptr4 } from "bun:ffi";
2698
- var p2dFinalizationRegistry = new FinalizationRegistry((ptr) => {
2699
- lib.symbols.path2d_destroy(ptr);
2700
- });
2701
-
2702
- class Path2D {
2703
- constructor(path) {
2704
- if (path && path instanceof Path2D) {
2705
- let ptr = ptrs.get(path);
2706
- if (!ptr)
2707
- return;
2708
- let _ptr = lib.symbols.path2d_create_from_copy(ptr);
2709
- ptrs.set(this, _ptr);
2710
- p2dFinalizationRegistry.register(this, _ptr);
2711
- } else {
2712
- let _ptr = lib.symbols.path2d_create();
2713
- ptrs.set(this, _ptr);
2714
- p2dFinalizationRegistry.register(this, _ptr);
2715
- }
2716
- }
2717
- moveTo(x, y) {
2718
- lib.symbols.path2d_move_to(ptrs.get(this), x, y);
2719
- }
2720
- lineTo(x, y) {
2721
- lib.symbols.path2d_line_to(ptrs.get(this), x, y);
2722
- }
2723
- arc(x, y, radius, startAngle, endAngle) {
2724
- lib.symbols.path2d_arc(ptrs.get(this), x, y, radius, startAngle, endAngle);
2725
- }
2726
- ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, counterclockwise = false) {
2727
- lib.symbols.path2d_ellipse(ptrs.get(this), x, y, radiusX, radiusY, rotation, startAngle, endAngle, counterclockwise);
2728
- }
2729
- arcTo(x1, y1, x2, y2, radius) {
2730
- lib.symbols.path2d_arc_to(ptrs.get(this), x1, y1, x2, y2, radius);
2731
- }
2732
- bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) {
2733
- lib.symbols.path2d_bezier_to(ptrs.get(this), cp1x, cp1y, cp2x, cp2y, x, y);
2734
- }
2735
- quadraticCurveTo(cpx, cpy, x, y) {
2736
- lib.symbols.path2d_quad_to(ptrs.get(this), cpx, cpy, x, y);
2737
- }
2738
- rect(x, y, width, height) {
2739
- lib.symbols.path2d_rect(ptrs.get(this), x, y, width, height);
2740
- }
2741
- roundRect(x, y, width, height, radii) {
2742
- if (radii.constructor.name.toLowerCase().includes("array")) {
2743
- const arr = new Float32Array(radii);
2744
- if (arr.some(Number.isNaN))
2745
- return;
2746
- const len = arr.length;
2747
- lib.symbols.path2d_roundrect_array(ptrs.get(this), x, y, width, height, ptr4(arr), len);
2748
- return;
2749
- } else {
2750
- lib.symbols.path2d_rect(ptrs.get(this), x, y, width, height, radii);
2751
- }
2752
- }
2753
- closePath() {
2754
- lib.symbols.path2d_close(ptrs.get(this));
2755
- }
2756
- }
2757
- var proto2 = Path2D.prototype;
2758
- for (const key of Object.getOwnPropertyNames(proto2)) {
2759
- const desc = Object.getOwnPropertyDescriptor(proto2, key);
2760
- if (key == "constructor") {
2761
- desc && (desc.value.toString = () => {
2762
- return `function ${proto2.constructor.name}() { [native code] }`;
2763
- });
2764
- continue;
2765
- }
2766
- if (typeof desc?.value === "function") {
2767
- desc.value.toString = () => `function ${key}() { [native code] }`;
2768
- }
2769
- }
2770
3868
  // BunCanvas/src/Window.ts
2771
- import { dlopen as dlopen2, toArrayBuffer } from "bun:ffi";
3869
+ import { toArrayBuffer } from "bun:ffi";
2772
3870
 
2773
3871
  // BunCanvas/internal/WindowThread.js
2774
3872
  var WindowThread_default = `import { dlopen, FFIType, JSCallback } from "bun:ffi";
2775
3873
 
2776
3874
  const MessagePost = new JSCallback((instruction)=>{
2777
- self.postMessage(instruction);
3875
+ self.postMessage(instruction);
2778
3876
  },
2779
3877
  {
2780
3878
  args: ["int"],
2781
3879
  returns: "void"
2782
3880
  }
2783
3881
  );
2784
-
2785
3882
  self.onmessage = (msg)=>{
2786
3883
  const { w = 1, h = 1, t = "App", vsync = true, nativePath = "" } = msg.data ?? {};
2787
3884
 
@@ -3167,103 +4264,129 @@ var GLFW_CODE_MAP = {
3167
4264
  348: "ContextMenu"
3168
4265
  };
3169
4266
 
3170
- // BunCanvas/src/Window.ts
3171
- var requestedFrames = [];
3172
- var render_thread;
3173
- if (Bun.isMainThread) {
3174
- lib.symbols.glfw_init();
3175
- if (process.platform !== "darwin") {
3176
- render_thread = new Worker(URL.createObjectURL(new Blob([WindowThread_default], { type: "application/javascript" })), { ref: false });
3177
- }
3178
- lib.symbols.canvas_init_gpu_context();
4267
+ // BunCanvas/internal/Mixin.ts
4268
+ function Mixin(Base, ...mixins) {
4269
+ return mixins.reduce((acc, mixin) => mixin(acc), Base);
3179
4270
  }
3180
4271
 
3181
- class Window extends EventTarget {
3182
- #setHandler(type, current, next) {
3183
- if (current) {
3184
- this.removeEventListener(type, current);
4272
+ // BunCanvas/internal/Event/KeyboardEventTarget.ts
4273
+ function KeyboardEventMixin(Base) {
4274
+ return class KeyboardEventTarget extends Base {
4275
+ #keydownHandler = null;
4276
+ #keyupHandler = null;
4277
+ get onkeydown() {
4278
+ return this.#keydownHandler;
3185
4279
  }
3186
- if (next) {
3187
- this.addEventListener(type, next);
4280
+ set onkeydown(fn) {
4281
+ this.#keydownHandler = setHandler(this, "keydown", this.#keydownHandler, fn);
3188
4282
  }
3189
- return next;
3190
- }
4283
+ get onkeyup() {
4284
+ return this.#keyupHandler;
4285
+ }
4286
+ set onkeyup(fn) {
4287
+ this.#keyupHandler = setHandler(this, "keyup", this.#keyupHandler, fn);
4288
+ }
4289
+ };
4290
+ }
4291
+
4292
+ class KeyboardEventTarget extends KeyboardEventMixin(EventTarget) {
4293
+ }
4294
+
4295
+ // BunCanvas/internal/Event/MouseEventTarget.ts
4296
+ function MouseEventMixin(Base) {
4297
+ return class MouseEventTarget extends Base {
4298
+ #mousemoveHandler = null;
4299
+ #mousedownHandler = null;
4300
+ #mouseupHandler = null;
4301
+ #clickHandler = null;
4302
+ #contextMenuHandler = null;
4303
+ #wheelHandler = null;
4304
+ get onmousemove() {
4305
+ return this.#mousemoveHandler;
4306
+ }
4307
+ set onmousemove(fn) {
4308
+ this.#mousemoveHandler = setHandler(this, "mousemove", this.#mousemoveHandler, fn);
4309
+ }
4310
+ get onmousedown() {
4311
+ return this.#mousedownHandler;
4312
+ }
4313
+ set onmousedown(fn) {
4314
+ this.#mousedownHandler = setHandler(this, "mousedown", this.#mousedownHandler, fn);
4315
+ }
4316
+ get onmouseup() {
4317
+ return this.#mouseupHandler;
4318
+ }
4319
+ set onmouseup(fn) {
4320
+ this.#mouseupHandler = setHandler(this, "mouseup", this.#mouseupHandler, fn);
4321
+ }
4322
+ get onclick() {
4323
+ return this.#clickHandler;
4324
+ }
4325
+ set onclick(fn) {
4326
+ this.#clickHandler = setHandler(this, "click", this.#clickHandler, fn);
4327
+ }
4328
+ get oncontextmenu() {
4329
+ return this.#contextMenuHandler;
4330
+ }
4331
+ set oncontextmenu(fn) {
4332
+ this.#contextMenuHandler = setHandler(this, "contextmenu", this.#contextMenuHandler, fn);
4333
+ }
4334
+ get onwheel() {
4335
+ return this.#wheelHandler;
4336
+ }
4337
+ set onwheel(fn) {
4338
+ this.#wheelHandler = setHandler(this, "wheel", this.#wheelHandler, fn);
4339
+ }
4340
+ };
4341
+ }
4342
+
4343
+ class MouseEventTarget extends MouseEventMixin(EventTarget) {
4344
+ }
4345
+
4346
+ // BunCanvas/internal/Event/WindowEventTarget.ts
4347
+ class WindowEventTarget extends Mixin(EventTarget, MouseEventMixin, KeyboardEventMixin) {
3191
4348
  #resizeHandler = null;
3192
- #mousemoveHandler = null;
3193
- #mousedownHandler = null;
3194
- #mouseupHandler = null;
3195
- #clickHandler = null;
3196
- #keydownHandler = null;
3197
- #keyupHandler = null;
3198
- #wheelHandler = null;
4349
+ #focusHandler = null;
4350
+ #blurHandler = null;
3199
4351
  get onresize() {
3200
4352
  return this.#resizeHandler;
3201
4353
  }
3202
4354
  set onresize(fn) {
3203
- this.#resizeHandler = this.#setHandler("resize", this.#resizeHandler, fn);
3204
- }
3205
- get onmousemove() {
3206
- return this.#mousemoveHandler;
3207
- }
3208
- set onmousemove(fn) {
3209
- this.#mousemoveHandler = this.#setHandler("mousemove", this.#mousemoveHandler, fn);
3210
- }
3211
- get onmousedown() {
3212
- return this.#mousedownHandler;
3213
- }
3214
- set onmousedown(fn) {
3215
- this.#mousedownHandler = this.#setHandler("mousedown", this.#mousedownHandler, fn);
3216
- }
3217
- get onmouseup() {
3218
- return this.#mouseupHandler;
3219
- }
3220
- set onmouseup(fn) {
3221
- this.#mouseupHandler = this.#setHandler("mouseup", this.#mouseupHandler, fn);
3222
- }
3223
- get onclick() {
3224
- return this.#clickHandler;
3225
- }
3226
- set onclick(fn) {
3227
- this.#clickHandler = this.#setHandler("click", this.#clickHandler, fn);
3228
- }
3229
- get onkeydown() {
3230
- return this.#keydownHandler;
3231
- }
3232
- set onkeydown(fn) {
3233
- this.#keydownHandler = this.#setHandler("keydown", this.#keydownHandler, fn);
3234
- }
3235
- get onkeyup() {
3236
- return this.#keyupHandler;
3237
- }
3238
- set onkeyup(fn) {
3239
- this.#keyupHandler = this.#setHandler("keyup", this.#keyupHandler, fn);
3240
- }
3241
- get onwheel() {
3242
- return this.#wheelHandler;
3243
- }
3244
- set onwheel(fn) {
3245
- this.#wheelHandler = this.#setHandler("wheel", this.#wheelHandler, fn);
4355
+ this.#resizeHandler = setHandler(this, "resize", this.#resizeHandler, fn);
3246
4356
  }
3247
4357
  get onfocus() {
3248
- return this.#wheelHandler;
4358
+ return this.#focusHandler;
3249
4359
  }
3250
4360
  set onfocus(fn) {
3251
- this.#wheelHandler = this.#setHandler("focus", this.#wheelHandler, fn);
4361
+ this.#focusHandler = setHandler(this, "focus", this.#focusHandler, fn);
3252
4362
  }
3253
4363
  get onblur() {
3254
- return this.#wheelHandler;
4364
+ return this.#blurHandler;
3255
4365
  }
3256
4366
  set onblur(fn) {
3257
- this.#wheelHandler = this.#setHandler("blur", this.#wheelHandler, fn);
4367
+ this.#blurHandler = setHandler(this, "blur", this.#blurHandler, fn);
3258
4368
  }
3259
- #wPropertiesViewer = new Int32Array(toArrayBuffer(lib.symbols.get_wPropertiesViewer(), 0, 4 * 4));
4369
+ }
4370
+
4371
+ // BunCanvas/src/Window.ts
4372
+ var requestedFrames = [];
4373
+ var render_thread;
4374
+ if (Bun.isMainThread) {
4375
+ lib.symbols.glfw_init();
4376
+ if (process.platform !== "darwin") {
4377
+ render_thread = new Worker(URL.createObjectURL(new Blob([WindowThread_default], { type: "application/javascript" })), { ref: false });
4378
+ }
4379
+ lib.symbols.canvas_init_gpu_context();
4380
+ }
4381
+
4382
+ class Window extends WindowEventTarget {
4383
+ #wPropertiesViewer = new Int32Array(toArrayBuffer(lib.symbols.get_wPropertiesViewer(), 0, 6 * 4));
3260
4384
  #mMoveViewer = new Float64Array(toArrayBuffer(lib.symbols.get_mMoveViewer(), 0, 9 * 8));
3261
4385
  #mClickViewer = new Float64Array(toArrayBuffer(lib.symbols.get_mClickViewer(), 0, 9 * 8));
3262
4386
  #mDownViewer = new Float64Array(toArrayBuffer(lib.symbols.get_mDownViewer(), 0, 9 * 8));
3263
4387
  #mUpViewer = new Float64Array(toArrayBuffer(lib.symbols.get_mUpViewer(), 0, 9 * 8));
3264
4388
  #kDownViewer = new Int32Array(toArrayBuffer(lib.symbols.get_kDownViewer(), 0, 7 * 4));
3265
4389
  #kUpViewer = new Int32Array(toArrayBuffer(lib.symbols.get_kUpViewer(), 0, 7 * 4));
3266
- #wFocusBlurViewer = new Int32Array(toArrayBuffer(lib.symbols.get_wFocusBlurViewer(), 0, 2 * 4));
3267
4390
  #mWheelViewer = new Float64Array(toArrayBuffer(lib.symbols.get_mWheelViewer(), 0, 5 * 8));
3268
4391
  #getGlfwKeyLocation(kcode) {
3269
4392
  if (kcode >= 320 && kcode <= 336) {
@@ -3341,6 +4464,23 @@ class Window extends EventTarget {
3341
4464
  bubbles: true,
3342
4465
  cancelable: true
3343
4466
  });
4467
+ if (this.#mDownViewer[3] == 2) {
4468
+ const evt = new MouseEvent("contextmenu", {
4469
+ clientX: this.#mDownViewer[1],
4470
+ clientY: this.#mDownViewer[2],
4471
+ button: this.#mDownViewer[3],
4472
+ buttons: this.#mDownViewer[4],
4473
+ shiftKey: Boolean(this.#mDownViewer[5]),
4474
+ ctrlKey: Boolean(this.#mDownViewer[6]),
4475
+ altKey: Boolean(this.#mDownViewer[7]),
4476
+ metaKey: Boolean(this.#mDownViewer[8]),
4477
+ screenX: this.#mDownViewer[1],
4478
+ screenY: this.#mDownViewer[2],
4479
+ bubbles: true,
4480
+ cancelable: true
4481
+ });
4482
+ this.dispatchEvent(evt);
4483
+ }
3344
4484
  this.dispatchEvent(evt);
3345
4485
  }
3346
4486
  if (this.#mUpViewer[0] !== 0) {
@@ -3411,17 +4551,22 @@ class Window extends EventTarget {
3411
4551
  const evt = this.#createKeyboardEvent("keyup", this.#kUpViewer);
3412
4552
  this.dispatchEvent(evt);
3413
4553
  }
3414
- if (this.#wFocusBlurViewer[0] !== 0) {
3415
- this.#wFocusBlurViewer[0] = 0;
4554
+ if (this.#wPropertiesViewer[4] !== 0) {
4555
+ this.#wPropertiesViewer[4] = 0;
3416
4556
  this.dispatchEvent(new Event("focus"));
3417
4557
  }
3418
- if (this.#wFocusBlurViewer[1] !== 0) {
3419
- this.#wFocusBlurViewer[1] = 0;
4558
+ if (this.#wPropertiesViewer[5] !== 0) {
4559
+ this.#wPropertiesViewer[5] = 0;
3420
4560
  this.dispatchEvent(new Event("blur"));
3421
4561
  }
3422
4562
  }
3423
4563
  maxFramerate = 0;
3424
4564
  #isFullscreen = false;
4565
+ addEventListener(type, callback, options) {
4566
+ if (!type || !callback)
4567
+ throw new TypeError(`Failed to execute 'addEventListener' on '${this.constructor.name}': 2 arguments required, but only ${Number(!!type) + Number(!!callback) + Number(!!options)} present.`);
4568
+ super.addEventListener(type, callback, options);
4569
+ }
3425
4570
  get fullscreen() {
3426
4571
  return this.#isFullscreen;
3427
4572
  }
@@ -3479,26 +4624,19 @@ class Window extends EventTarget {
3479
4624
  vsync: this.#vsync,
3480
4625
  nativePath: dlPath
3481
4626
  });
3482
- let pendingFrame = false;
3483
4627
  let shuttingDown = false;
4628
+ let pendingFrame = false;
3484
4629
  let lastFrame = performance.now();
3485
- render_thread.onmessage = (msg) => {
3486
- const frameSignal = msg.data;
3487
- if (frameSignal == 2) {
3488
- if (shuttingDown)
3489
- return;
4630
+ const loop = () => {
4631
+ if (this.#wPropertiesViewer[3] && !shuttingDown) {
3490
4632
  shuttingDown = true;
4633
+ WindowThread_default.unref?.();
3491
4634
  lib.symbols.destroy_window();
3492
4635
  lib.symbols.images_cleanup();
3493
4636
  process.exit(0);
4637
+ } else if (shuttingDown)
3494
4638
  return;
3495
- }
3496
- if (frameSignal === 1) {
3497
- lib.symbols.create_window(width, height, titleBuf);
3498
- }
3499
- };
3500
- const loop = () => {
3501
- lib.symbols.signal_frame_ready();
4639
+ this.#processEvents();
3502
4640
  const frameInterval = this.maxFramerate > 0 ? 1000 / this.maxFramerate : 0;
3503
4641
  const now = performance.now();
3504
4642
  const delta = now - lastFrame;
@@ -3507,34 +4645,33 @@ class Window extends EventTarget {
3507
4645
  lastFrame = now - delta % frameInterval;
3508
4646
  }
3509
4647
  if (!pendingFrame) {
3510
- pendingFrame = true;
3511
- setImmediate(() => {
3512
- const queueLen = requestedFrames.length;
3513
- if (queueLen > 0) {
3514
- const framesToProcess = requestedFrames;
3515
- requestedFrames = [];
3516
- for (let i = 0;i < queueLen; i++) {
3517
- framesToProcess[i](now);
3518
- }
4648
+ const queueLen = requestedFrames.length;
4649
+ if (queueLen > 0) {
4650
+ const framesToProcess = requestedFrames;
4651
+ requestedFrames = [];
4652
+ for (let i = 0;i < queueLen; i++) {
4653
+ framesToProcess[i](now);
3519
4654
  }
3520
- lib.symbols.canvas_flush_gpu();
3521
- pendingFrame = false;
3522
- });
4655
+ }
3523
4656
  }
4657
+ lib.symbols.canvas_flush_gpu();
3524
4658
  }
3525
- this.#processEvents();
3526
- setImmediate(loop);
4659
+ if (!this.#vsync)
4660
+ setImmediate(loop);
3527
4661
  };
3528
- setImmediate(loop);
3529
- } else {
3530
- let aaplLib = dlopen2(dlPath, {
3531
- setup_render_thread: {
3532
- args: ["int", "int", "cstring", "ptr", "bool"],
3533
- returns: "void"
4662
+ render_thread.onmessage = (msg) => {
4663
+ const frameSignal = msg.data;
4664
+ if (frameSignal === 0) {
4665
+ loop();
3534
4666
  }
3535
- });
4667
+ if (frameSignal === 1) {
4668
+ lib.symbols.create_window(width, height, titleBuf);
4669
+ }
4670
+ };
4671
+ loop();
4672
+ } else {
3536
4673
  const titleBuf = encoder.encode(`${title}\x00`);
3537
- aaplLib.symbols.setup_render_thread(width, height, titleBuf, 0, vsync);
4674
+ lib.symbols.setup_render_thread(width, height, titleBuf, 0, vsync);
3538
4675
  lib.symbols.create_window(width, height, titleBuf);
3539
4676
  const frameInterval = this.maxFramerate > 0 ? 1000 / this.maxFramerate : 0;
3540
4677
  let lastFrameTime = performance.now();
@@ -3548,6 +4685,7 @@ class Window extends EventTarget {
3548
4685
  const delta = now - lastFrameTime;
3549
4686
  if (frameInterval === 0 || delta >= frameInterval) {
3550
4687
  lastFrameTime = frameInterval > 0 ? now - delta % frameInterval : now;
4688
+ lib.symbols.update_window();
3551
4689
  this.#processEvents();
3552
4690
  if (requestedFrames.length > 0) {
3553
4691
  const framesToProcess = requestedFrames;
@@ -3556,26 +4694,26 @@ class Window extends EventTarget {
3556
4694
  framesToProcess[i](now);
3557
4695
  }
3558
4696
  }
3559
- lib.symbols.update_window();
3560
4697
  }
3561
4698
  setImmediate(loop);
3562
4699
  };
3563
- loop();
4700
+ setImmediate(loop);
3564
4701
  }
3565
4702
  }
3566
4703
  append(canvas) {
3567
- const canvasPtr = canvas._ptr;
3568
- if (canvasPtr == undefined) {
3569
- console.error("Canvas was not found");
3570
- return;
3571
- }
3572
- lib.symbols.canvas_append(canvasPtr);
3573
- }
3574
- requestAnimationFrame(callback) {
3575
4704
  setImmediate(() => {
3576
- requestedFrames.push(callback);
4705
+ const ctx2d = ctx2ds.get(canvas);
4706
+ const canvasPtr = ptrs.get(ctx2d);
4707
+ if (canvasPtr == undefined) {
4708
+ console.error("Canvas was not found");
4709
+ return;
4710
+ }
4711
+ lib.symbols.canvas_append(canvasPtr);
3577
4712
  });
3578
4713
  }
4714
+ requestAnimationFrame(callback) {
4715
+ requestedFrames.push(callback);
4716
+ }
3579
4717
  }
3580
4718
  {
3581
4719
  const proto = Window.prototype;
@@ -3594,32 +4732,343 @@ class Window extends EventTarget {
3594
4732
  }
3595
4733
  var rAf;
3596
4734
  rAf = function requestAnimationFrame(callback) {
3597
- setImmediate(() => {
3598
- requestedFrames.push(callback);
3599
- });
4735
+ requestedFrames.push(callback);
3600
4736
  };
3601
4737
  rAf.toString = () => `function requestAnimationFrame() { [native code] }`;
3602
4738
  var requestAnimationFrame = rAf;
3603
4739
  // BunCanvas/src/Audio.ts
3604
- var ptrs3 = new WeakMap;
4740
+ var registry = new FinalizationRegistry((ptr) => {
4741
+ lib.symbols.audio_destroy(ptr);
4742
+ });
3605
4743
  lib.symbols.audio_backend_init();
3606
4744
 
3607
- class Audio {
3608
- constructor(path) {
3609
- if (path) {
3610
- ptrs3.set(this, lib.symbols.audio_create(encoder.encode(`${path}\x00`)));
3611
- } else {
3612
- ptrs3.set(this, lib.symbols.audio_create());
4745
+ class MediaError {
4746
+ static MEDIA_ERR_ABORTED = 1;
4747
+ static MEDIA_ERR_NETWORK = 2;
4748
+ static MEDIA_ERR_DECODE = 3;
4749
+ static MEDIA_ERR_SRC_NOT_SUPPORTED = 4;
4750
+ code;
4751
+ message;
4752
+ constructor(code, message = "") {
4753
+ this.code = code;
4754
+ this.message = message;
4755
+ }
4756
+ }
4757
+
4758
+ class Audio extends EventTarget {
4759
+ static HAVE_NOTHING = 0;
4760
+ static HAVE_METADATA = 1;
4761
+ static HAVE_CURRENT_DATA = 2;
4762
+ static HAVE_FUTURE_DATA = 3;
4763
+ static HAVE_ENOUGH_DATA = 4;
4764
+ static NETWORK_EMPTY = 0;
4765
+ static NETWORK_IDLE = 1;
4766
+ static NETWORK_LOADING = 2;
4767
+ static NETWORK_NO_SOURCE = 3;
4768
+ #src = "";
4769
+ #currentSrc = "";
4770
+ #preload = "auto";
4771
+ #autoplay = false;
4772
+ #defaultMuted = false;
4773
+ #defaultPlaybackRate = 1;
4774
+ #preservesPitch = true;
4775
+ #crossOrigin = null;
4776
+ #error = null;
4777
+ #pollTimer = null;
4778
+ #lastReportedTime = 0;
4779
+ oncanplay = null;
4780
+ oncanplaythrough = null;
4781
+ ondurationchange = null;
4782
+ onended = null;
4783
+ onerror = null;
4784
+ onloadeddata = null;
4785
+ onloadedmetadata = null;
4786
+ onloadstart = null;
4787
+ onpause = null;
4788
+ onplay = null;
4789
+ onplaying = null;
4790
+ onratechange = null;
4791
+ onseeked = null;
4792
+ onseeking = null;
4793
+ ontimeupdate = null;
4794
+ onvolumechange = null;
4795
+ constructor(src) {
4796
+ super();
4797
+ const ptr = src ? lib.symbols.audio_create(encodeCString(src)) : lib.symbols.audio_create(null);
4798
+ ptrs.set(this, ptr);
4799
+ registry.register(this, ptr, this);
4800
+ if (src !== undefined) {
4801
+ this.#src = src;
4802
+ this.#syncLoadState();
4803
+ }
4804
+ }
4805
+ #ptr() {
4806
+ const ptr = ptrs.get(this);
4807
+ if (!ptr) {
4808
+ throw new DOMException("Audio instance has been destroyed", "InvalidStateError");
4809
+ }
4810
+ return ptr;
4811
+ }
4812
+ #emit(type) {
4813
+ const event = new Event(type);
4814
+ const handler = this[`on${type}`];
4815
+ if (typeof handler === "function") {
4816
+ handler.call(this, event);
4817
+ }
4818
+ this.dispatchEvent(event);
4819
+ }
4820
+ #syncLoadState() {
4821
+ const ptr = this.#ptr();
4822
+ this.#emit("loadstart");
4823
+ if (lib.symbols.audio_get_has_error(ptr) || !this.#src) {
4824
+ this.#currentSrc = "";
4825
+ if (this.#src) {
4826
+ this.#error = new MediaError(MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED, `Failed to load audio source: ${this.#src}`);
4827
+ this.#emit("error");
4828
+ }
4829
+ return;
4830
+ }
4831
+ this.#error = null;
4832
+ this.#currentSrc = this.#src;
4833
+ this.#emit("durationchange");
4834
+ this.#emit("loadedmetadata");
4835
+ this.#emit("loadeddata");
4836
+ this.#emit("canplay");
4837
+ this.#emit("canplaythrough");
4838
+ if (this.#autoplay) {
4839
+ this.play();
4840
+ }
4841
+ }
4842
+ #startPolling() {
4843
+ if (this.#pollTimer)
4844
+ return;
4845
+ this.#pollTimer = setInterval(() => {
4846
+ const ptr = ptrs.get(this);
4847
+ if (!ptr) {
4848
+ this.#stopPolling();
4849
+ return;
4850
+ }
4851
+ const now = lib.symbols.audio_get_current_time(ptr);
4852
+ if (now !== this.#lastReportedTime) {
4853
+ this.#lastReportedTime = now;
4854
+ this.#emit("timeupdate");
4855
+ }
4856
+ if (lib.symbols.audio_get_ended(ptr)) {
4857
+ this.#stopPolling();
4858
+ this.#emit("pause");
4859
+ this.#emit("ended");
4860
+ } else if (lib.symbols.audio_get_paused(ptr)) {
4861
+ this.#stopPolling();
4862
+ }
4863
+ }, 50);
4864
+ }
4865
+ #stopPolling() {
4866
+ if (this.#pollTimer) {
4867
+ clearInterval(this.#pollTimer);
4868
+ this.#pollTimer = null;
3613
4869
  }
3614
4870
  }
4871
+ get src() {
4872
+ return this.#src;
4873
+ }
3615
4874
  set src(v) {
3616
- lib.symbols.audio_set_src(encodeCString(v));
4875
+ this.#stopPolling();
4876
+ this.#src = String(v);
4877
+ lib.symbols.audio_set_src(this.#ptr(), encodeCString(this.#src));
4878
+ this.#syncLoadState();
4879
+ }
4880
+ get currentSrc() {
4881
+ return this.#currentSrc;
4882
+ }
4883
+ get preload() {
4884
+ return this.#preload;
4885
+ }
4886
+ set preload(v) {
4887
+ if (v === "none" || v === "metadata" || v === "auto" || v === "") {
4888
+ this.#preload = v;
4889
+ }
4890
+ }
4891
+ get crossOrigin() {
4892
+ return this.#crossOrigin;
4893
+ }
4894
+ set crossOrigin(v) {
4895
+ this.#crossOrigin = v;
4896
+ }
4897
+ get readyState() {
4898
+ return lib.symbols.audio_get_ready_state(this.#ptr());
4899
+ }
4900
+ get networkState() {
4901
+ if (!this.#src)
4902
+ return Audio.NETWORK_EMPTY;
4903
+ if (this.#error)
4904
+ return Audio.NETWORK_NO_SOURCE;
4905
+ return Audio.NETWORK_IDLE;
4906
+ }
4907
+ get error() {
4908
+ return this.#error;
4909
+ }
4910
+ load() {
4911
+ this.#stopPolling();
4912
+ lib.symbols.audio_load(this.#ptr());
4913
+ this.#syncLoadState();
4914
+ }
4915
+ canPlayType(type) {
4916
+ const mime = type.toLowerCase().split(";")[0].trim();
4917
+ switch (mime) {
4918
+ case "audio/wav":
4919
+ case "audio/wave":
4920
+ case "audio/x-wav":
4921
+ case "audio/mpeg":
4922
+ case "audio/mp3":
4923
+ case "audio/flac":
4924
+ case "audio/x-flac":
4925
+ case "audio/ogg":
4926
+ return "probably";
4927
+ case "application/ogg":
4928
+ return "maybe";
4929
+ default:
4930
+ return "";
4931
+ }
3617
4932
  }
3618
- play() {
3619
- lib.symbols.audio_play(ptrs3.get(this));
4933
+ async play() {
4934
+ const ptr = this.#ptr();
4935
+ if (!this.#src) {
4936
+ throw new DOMException("The element has no supported sources.", "NotSupportedError");
4937
+ }
4938
+ const wasPaused = this.paused;
4939
+ const ok = lib.symbols.audio_play(ptr);
4940
+ if (!ok) {
4941
+ this.#error = new MediaError(MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED, `Failed to play source: ${this.#src}`);
4942
+ this.#emit("error");
4943
+ throw new DOMException("The element has no supported sources.", "NotSupportedError");
4944
+ }
4945
+ if (wasPaused) {
4946
+ this.#emit("play");
4947
+ this.#emit("playing");
4948
+ }
4949
+ this.#startPolling();
4950
+ }
4951
+ pause() {
4952
+ const wasPaused = this.paused;
4953
+ lib.symbols.audio_pause(this.#ptr());
4954
+ this.#stopPolling();
4955
+ if (!wasPaused) {
4956
+ this.#emit("pause");
4957
+ }
3620
4958
  }
3621
4959
  stop() {
3622
- lib.symbols.audio_stop(ptrs3.get(this));
4960
+ const wasPaused = this.paused;
4961
+ lib.symbols.audio_stop(this.#ptr());
4962
+ this.#stopPolling();
4963
+ this.#lastReportedTime = 0;
4964
+ if (!wasPaused) {
4965
+ this.#emit("pause");
4966
+ }
4967
+ }
4968
+ fastSeek(time) {
4969
+ this.currentTime = time;
4970
+ }
4971
+ get currentTime() {
4972
+ return lib.symbols.audio_get_current_time(this.#ptr());
4973
+ }
4974
+ set currentTime(seconds) {
4975
+ if (!Number.isFinite(seconds)) {
4976
+ throw new TypeError("Failed to set 'currentTime': The provided double value is non-finite.");
4977
+ }
4978
+ const ptr = this.#ptr();
4979
+ this.#emit("seeking");
4980
+ lib.symbols.audio_set_current_time(ptr, seconds);
4981
+ this.#lastReportedTime = lib.symbols.audio_get_current_time(ptr);
4982
+ this.#emit("timeupdate");
4983
+ this.#emit("seeked");
4984
+ }
4985
+ get duration() {
4986
+ return lib.symbols.audio_get_duration(this.#ptr());
4987
+ }
4988
+ get paused() {
4989
+ return Boolean(lib.symbols.audio_get_paused(this.#ptr()));
4990
+ }
4991
+ get ended() {
4992
+ return Boolean(lib.symbols.audio_get_ended(this.#ptr()));
4993
+ }
4994
+ get seeking() {
4995
+ return false;
4996
+ }
4997
+ get volume() {
4998
+ return lib.symbols.audio_get_volume(this.#ptr());
4999
+ }
5000
+ set volume(v) {
5001
+ if (!Number.isFinite(v)) {
5002
+ throw new TypeError("Failed to set 'volume': The provided double value is non-finite.");
5003
+ }
5004
+ if (v < 0 || v > 1) {
5005
+ throw new DOMException("Failed to set 'volume': The volume provided is outside the range [0, 1].", "IndexSizeError");
5006
+ }
5007
+ lib.symbols.audio_set_volume(this.#ptr(), v);
5008
+ this.#emit("volumechange");
5009
+ }
5010
+ get muted() {
5011
+ return Boolean(lib.symbols.audio_get_muted(this.#ptr()));
5012
+ }
5013
+ set muted(v) {
5014
+ lib.symbols.audio_set_muted(this.#ptr(), Boolean(v));
5015
+ this.#emit("volumechange");
5016
+ }
5017
+ get defaultMuted() {
5018
+ return this.#defaultMuted;
5019
+ }
5020
+ set defaultMuted(v) {
5021
+ this.#defaultMuted = Boolean(v);
5022
+ this.muted = this.#defaultMuted;
5023
+ }
5024
+ get loop() {
5025
+ return Boolean(lib.symbols.audio_get_loop(this.#ptr()));
5026
+ }
5027
+ set loop(v) {
5028
+ lib.symbols.audio_set_loop(this.#ptr(), Boolean(v));
5029
+ }
5030
+ get autoplay() {
5031
+ return this.#autoplay;
5032
+ }
5033
+ set autoplay(v) {
5034
+ this.#autoplay = Boolean(v);
5035
+ if (this.#autoplay && this.paused && this.#src) {
5036
+ this.play();
5037
+ }
5038
+ }
5039
+ get playbackRate() {
5040
+ return lib.symbols.audio_get_playback_rate(this.#ptr());
5041
+ }
5042
+ set playbackRate(v) {
5043
+ if (!Number.isFinite(v)) {
5044
+ throw new TypeError("Failed to set 'playbackRate': The provided double value is non-finite.");
5045
+ }
5046
+ lib.symbols.audio_set_playback_rate(this.#ptr(), v);
5047
+ this.#emit("ratechange");
5048
+ }
5049
+ get defaultPlaybackRate() {
5050
+ return this.#defaultPlaybackRate;
5051
+ }
5052
+ set defaultPlaybackRate(v) {
5053
+ if (!Number.isFinite(v)) {
5054
+ throw new TypeError("Failed to set 'defaultPlaybackRate': The provided double value is non-finite.");
5055
+ }
5056
+ this.#defaultPlaybackRate = v;
5057
+ }
5058
+ get preservesPitch() {
5059
+ return this.#preservesPitch;
5060
+ }
5061
+ set preservesPitch(v) {
5062
+ this.#preservesPitch = Boolean(v);
5063
+ }
5064
+ dispose() {
5065
+ this.#stopPolling();
5066
+ const ptr = ptrs.get(this);
5067
+ if (ptr) {
5068
+ registry.unregister(this);
5069
+ ptrs.delete(this);
5070
+ lib.symbols.audio_destroy(ptr);
5071
+ }
3623
5072
  }
3624
5073
  }
3625
5074