@luma.gl/graph 10.0.0-alpha.11 → 10.0.0-alpha.13

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.
Files changed (131) hide show
  1. package/LICENSE +4 -4
  2. package/THIRD-PARTY-NOTICES.md +19 -0
  3. package/dist/arrow/gpu/arrow-gpu-vector-adapters.cjs +6 -6
  4. package/dist/arrow/gpu/arrow-gpu-vector-adapters.d.ts.map +1 -1
  5. package/dist/arrow/gpu/arrow-gpu-vector-adapters.js +16 -6
  6. package/dist/arrow/gpu/arrow-gpu-vector-adapters.js.map +1 -1
  7. package/dist/arrow/gpu/arrow-gpu-vector-conversion.cjs +3 -2
  8. package/dist/arrow/gpu/arrow-gpu-vector-conversion.d.ts.map +1 -1
  9. package/dist/arrow/gpu/arrow-gpu-vector-conversion.js +3 -2
  10. package/dist/arrow/gpu/arrow-gpu-vector-conversion.js.map +1 -1
  11. package/dist/arrow/index.cjs.map +2 -2
  12. package/dist/arrow/internal.cjs.map +2 -2
  13. package/dist/dist.dev.js +2148 -454
  14. package/dist/dist.min.js +437 -123
  15. package/dist/experimental/index.cjs.map +1 -1
  16. package/dist/experimental/simulation/index.cjs.map +1 -1
  17. package/dist/gpu-core/compiled-gpu-graph.cjs +15 -0
  18. package/dist/gpu-core/compiled-gpu-graph.d.ts +1 -0
  19. package/dist/gpu-core/compiled-gpu-graph.d.ts.map +1 -1
  20. package/dist/gpu-core/compiled-gpu-graph.js +15 -0
  21. package/dist/gpu-core/compiled-gpu-graph.js.map +1 -1
  22. package/dist/gpu-core/gpu-command-graph.cjs +9 -0
  23. package/dist/gpu-core/gpu-command-graph.d.ts +2 -0
  24. package/dist/gpu-core/gpu-command-graph.d.ts.map +1 -1
  25. package/dist/gpu-core/gpu-command-graph.js +9 -0
  26. package/dist/gpu-core/gpu-command-graph.js.map +1 -1
  27. package/dist/gpu-core/gpu-expression-plan.cjs +4 -0
  28. package/dist/gpu-core/gpu-expression-plan.d.ts.map +1 -1
  29. package/dist/gpu-core/gpu-expression-plan.js +5 -0
  30. package/dist/gpu-core/gpu-expression-plan.js.map +1 -1
  31. package/dist/gpu-core/gpu-graph-compiler.cjs +48 -0
  32. package/dist/gpu-core/gpu-graph-compiler.d.ts +1 -0
  33. package/dist/gpu-core/gpu-graph-compiler.d.ts.map +1 -1
  34. package/dist/gpu-core/gpu-graph-compiler.js +50 -0
  35. package/dist/gpu-core/gpu-graph-compiler.js.map +1 -1
  36. package/dist/gpu-core/gpu-group-aggregation.cjs +7 -15
  37. package/dist/gpu-core/gpu-group-aggregation.d.ts.map +1 -1
  38. package/dist/gpu-core/gpu-group-aggregation.js +7 -18
  39. package/dist/gpu-core/gpu-group-aggregation.js.map +1 -1
  40. package/dist/gpu-core/gpu-reduction.cjs +6 -14
  41. package/dist/gpu-core/gpu-reduction.d.ts.map +1 -1
  42. package/dist/gpu-core/gpu-reduction.js +6 -15
  43. package/dist/gpu-core/gpu-reduction.js.map +1 -1
  44. package/dist/gpu-core/gpu-semantic-aggregation-operation.cjs +112 -0
  45. package/dist/gpu-core/gpu-semantic-aggregation-operation.d.ts +71 -0
  46. package/dist/gpu-core/gpu-semantic-aggregation-operation.d.ts.map +1 -0
  47. package/dist/gpu-core/gpu-semantic-aggregation-operation.js +92 -0
  48. package/dist/gpu-core/gpu-semantic-aggregation-operation.js.map +1 -0
  49. package/dist/gpu-core/gpu-shader-pass-kernel.cjs +267 -0
  50. package/dist/gpu-core/gpu-shader-pass-kernel.d.ts +29 -0
  51. package/dist/gpu-core/gpu-shader-pass-kernel.d.ts.map +1 -0
  52. package/dist/gpu-core/gpu-shader-pass-kernel.js +260 -0
  53. package/dist/gpu-core/gpu-shader-pass-kernel.js.map +1 -0
  54. package/dist/gpu-core/gpu-shader-pass-operation.cjs +85 -0
  55. package/dist/gpu-core/gpu-shader-pass-operation.d.ts +32 -0
  56. package/dist/gpu-core/gpu-shader-pass-operation.d.ts.map +1 -0
  57. package/dist/gpu-core/gpu-shader-pass-operation.js +74 -0
  58. package/dist/gpu-core/gpu-shader-pass-operation.js.map +1 -0
  59. package/dist/gpu-core/index.cjs +8 -0
  60. package/dist/gpu-core/index.cjs.map +3 -3
  61. package/dist/gpu-core/index.d.ts +4 -0
  62. package/dist/gpu-core/index.d.ts.map +1 -1
  63. package/dist/gpu-core/index.js +2 -0
  64. package/dist/gpu-core/index.js.map +1 -1
  65. package/dist/gpu-data/cpu-gpu-vector-transfer.cjs +7 -2
  66. package/dist/gpu-data/cpu-gpu-vector-transfer.d.ts.map +1 -1
  67. package/dist/gpu-data/cpu-gpu-vector-transfer.js +9 -6
  68. package/dist/gpu-data/cpu-gpu-vector-transfer.js.map +1 -1
  69. package/dist/gpu-data/gpu-data-buffer-props.cjs +41 -0
  70. package/dist/gpu-data/gpu-data-buffer-props.d.ts +5 -0
  71. package/dist/gpu-data/gpu-data-buffer-props.d.ts.map +1 -0
  72. package/dist/gpu-data/gpu-data-buffer-props.js +19 -0
  73. package/dist/gpu-data/gpu-data-buffer-props.js.map +1 -0
  74. package/dist/gpu-data/index.cjs.map +3 -3
  75. package/dist/gpu-dggs/benchmarks.cjs.map +1 -1
  76. package/dist/gpu-graph/index.cjs +5 -0
  77. package/dist/gpu-graph/index.cjs.map +3 -3
  78. package/dist/gpu-graph/index.d.ts +2 -0
  79. package/dist/gpu-graph/index.d.ts.map +1 -1
  80. package/dist/gpu-graph/index.js +1 -0
  81. package/dist/gpu-graph/index.js.map +1 -1
  82. package/dist/gpu-graph-algorithms/benchmarks.cjs.map +1 -1
  83. package/dist/gpu-graph-algorithms/index.cjs.map +1 -1
  84. package/dist/gpu-physics/index.cjs.map +1 -1
  85. package/dist/gpu-project/benchmarks.cjs.map +2 -2
  86. package/dist/gpu-project/crs.cjs.map +2 -2
  87. package/dist/gpu-project/graph.cjs.map +3 -3
  88. package/dist/gpu-project/index.cjs.map +2 -2
  89. package/dist/gpu-simple-graph/compiled-gpu-expression-graph.cjs +53 -5
  90. package/dist/gpu-simple-graph/compiled-gpu-expression-graph.d.ts +3 -1
  91. package/dist/gpu-simple-graph/compiled-gpu-expression-graph.d.ts.map +1 -1
  92. package/dist/gpu-simple-graph/compiled-gpu-expression-graph.js +58 -5
  93. package/dist/gpu-simple-graph/compiled-gpu-expression-graph.js.map +1 -1
  94. package/dist/gpu-simple-graph/index.cjs.map +3 -3
  95. package/dist/gpu-sql/gpu-sql.cjs +112 -100
  96. package/dist/gpu-sql/gpu-sql.d.ts +1 -1
  97. package/dist/gpu-sql/gpu-sql.d.ts.map +1 -1
  98. package/dist/gpu-sql/gpu-sql.js +120 -102
  99. package/dist/gpu-sql/gpu-sql.js.map +1 -1
  100. package/dist/gpu-sql/index.cjs.map +2 -2
  101. package/dist/gpu-tables/index.cjs.map +2 -2
  102. package/dist/gpu-tables/table/gpu-table.cjs +2 -2
  103. package/dist/gpu-tables/table/gpu-table.d.ts.map +1 -1
  104. package/dist/gpu-tables/table/gpu-table.js +2 -2
  105. package/dist/gpu-tables/table/gpu-table.js.map +1 -1
  106. package/dist/index.cjs +8 -0
  107. package/dist/index.cjs.map +3 -3
  108. package/dist/index.d.ts +4 -0
  109. package/dist/index.d.ts.map +1 -1
  110. package/dist/index.js +2 -0
  111. package/dist/index.js.map +1 -1
  112. package/package.json +10 -8
  113. package/src/arrow/gpu/arrow-gpu-vector-adapters.ts +17 -6
  114. package/src/arrow/gpu/arrow-gpu-vector-conversion.ts +3 -2
  115. package/src/gpu-core/compiled-gpu-graph.ts +18 -0
  116. package/src/gpu-core/gpu-command-graph.ts +10 -0
  117. package/src/gpu-core/gpu-expression-plan.ts +6 -0
  118. package/src/gpu-core/gpu-graph-compiler.ts +61 -0
  119. package/src/gpu-core/gpu-group-aggregation.ts +38 -50
  120. package/src/gpu-core/gpu-reduction.ts +32 -42
  121. package/src/gpu-core/gpu-semantic-aggregation-operation.ts +150 -0
  122. package/src/gpu-core/gpu-shader-pass-kernel.ts +307 -0
  123. package/src/gpu-core/gpu-shader-pass-operation.ts +103 -0
  124. package/src/gpu-core/index.ts +8 -0
  125. package/src/gpu-data/cpu-gpu-vector-transfer.ts +10 -7
  126. package/src/gpu-data/gpu-data-buffer-props.ts +25 -0
  127. package/src/gpu-graph/index.ts +9 -0
  128. package/src/gpu-simple-graph/compiled-gpu-expression-graph.ts +59 -5
  129. package/src/gpu-sql/gpu-sql.ts +130 -103
  130. package/src/gpu-tables/table/gpu-table.ts +2 -1
  131. package/src/index.ts +11 -0
package/dist/dist.dev.js CHANGED
@@ -68,10 +68,13 @@ var __exports__ = (() => {
68
68
  GPUExpressionOperation: () => GPUExpressionOperation,
69
69
  GPUGraph: () => GPUGraph,
70
70
  GPUGraphCompiler: () => GPUGraphCompiler,
71
+ GPUGraphGroupAggregation: () => GPUGraphGroupAggregation,
72
+ GPUGraphReduction: () => GPUGraphReduction,
71
73
  GPUGraphScalar: () => GPUGraphScalar,
72
74
  GPUGraphTexture: () => GPUGraphTexture,
73
75
  GPUGraphTextureView: () => GPUGraphTextureView,
74
76
  GPUGraphVector: () => GPUGraphVector,
77
+ GPUShaderPassOperation: () => GPUShaderPassOperation,
75
78
  GPUUploadOperation: () => GPUUploadOperation,
76
79
  GraphBufferHandle: () => GraphBufferHandle,
77
80
  GraphDataView: () => GraphDataView,
@@ -709,7 +712,148 @@ var __exports__ = (() => {
709
712
  return `${id}-${count}`;
710
713
  }
711
714
 
715
+ // ../core/src/api/utils/assert.ts
716
+ function assert3(condition, message) {
717
+ if (!condition) {
718
+ const error = new Error(message ?? "luma.gl assertion failed.");
719
+ Error.captureStackTrace?.(error, assert3);
720
+ throw error;
721
+ }
722
+ }
723
+
712
724
  // ../core/src/api/adapter/resources/resource.ts
725
+ var Resource = class {
726
+ _owner = null;
727
+ _ownedResources = /* @__PURE__ */ new Set();
728
+ _state = "live";
729
+ _destroyingOwnedResources = false;
730
+ _destroyRequested = false;
731
+ /** The resource responsible for destroying this resource, or null for caller-managed lifetime. */
732
+ get owner() {
733
+ return this._owner;
734
+ }
735
+ /** A snapshot of this resource's children. Mutating the snapshot cannot change ownership. */
736
+ get ownedResources() {
737
+ return Array.from(this._ownedResources);
738
+ }
739
+ /** Whether destruction has completed, including when cleanup reported an error. */
740
+ get destroyed() {
741
+ return this._state === "destroyed";
742
+ }
743
+ /** Transfer exclusive ownership, or return lifetime responsibility to the caller with null. */
744
+ transferOwnershipTo(owner) {
745
+ assert3(this._state === "live" && !this._destroyingOwnedResources);
746
+ assert3(!this._owner || this._owner.canChangeOwnership());
747
+ assert3(!owner || owner.canChangeOwnership());
748
+ for (let ancestor = owner; ancestor; ancestor = ancestor._owner) {
749
+ assert3(ancestor !== this);
750
+ }
751
+ if (owner !== this._owner) {
752
+ this._owner?._ownedResources.delete(this);
753
+ this._owner = owner;
754
+ owner?._ownedResources.add(this);
755
+ }
756
+ return this;
757
+ }
758
+ /** Destroy children before this resource. Subclasses implement hooks instead of overriding. */
759
+ destroy() {
760
+ if (this._state !== "live") {
761
+ return;
762
+ }
763
+ if (this._destroyingOwnedResources) {
764
+ this._destroyRequested = true;
765
+ return;
766
+ }
767
+ this._destroyRequested = false;
768
+ this._state = "destroying";
769
+ this._owner?._ownedResources.delete(this);
770
+ this._owner = null;
771
+ const errors = [];
772
+ try {
773
+ try {
774
+ this.onBeforeDestroy();
775
+ } catch (error) {
776
+ errors.push(error);
777
+ }
778
+ this.destroyChildren(errors);
779
+ try {
780
+ this.onDestroy();
781
+ } catch (error) {
782
+ errors.push(error);
783
+ }
784
+ } finally {
785
+ this._state = "destroyed";
786
+ }
787
+ if (errors.length) {
788
+ throw new AggregateError(errors, "Resource cleanup failed");
789
+ }
790
+ }
791
+ /** @deprecated Use destroy(). */
792
+ delete() {
793
+ this.destroy();
794
+ return this;
795
+ }
796
+ /** @deprecated Use resource.transferOwnershipTo(this). */
797
+ attachResource(resource) {
798
+ resource.transferOwnershipTo(this);
799
+ }
800
+ /** @deprecated Use resource.transferOwnershipTo(null). Only detaches a child owned by this. */
801
+ detachResource(resource) {
802
+ if (resource._owner === this) {
803
+ resource.transferOwnershipTo(null);
804
+ }
805
+ }
806
+ /** @deprecated Check resource.owner and call resource.destroy(). */
807
+ destroyAttachedResource(resource) {
808
+ if (resource._owner === this) {
809
+ resource.destroy();
810
+ }
811
+ }
812
+ /** @deprecated Destroy individually owned resources, or destroy the owner. */
813
+ destroyAttachedResources() {
814
+ if (this._state !== "live" || this._destroyingOwnedResources) {
815
+ return;
816
+ }
817
+ const errors = [];
818
+ this.destroyChildren(errors);
819
+ if (this._destroyRequested) {
820
+ try {
821
+ this.destroy();
822
+ } catch (error) {
823
+ errors.push(error);
824
+ }
825
+ }
826
+ if (errors.length) {
827
+ throw new AggregateError(errors, "Resource cleanup failed");
828
+ }
829
+ }
830
+ /** Stop activity before children are destroyed. Errors are collected; this hook cannot veto cleanup. */
831
+ onBeforeDestroy() {
832
+ }
833
+ /** Release this resource's own state after its children have been destroyed. */
834
+ onDestroy() {
835
+ }
836
+ canChangeOwnership() {
837
+ return this._state === "live" && !this._destroyingOwnedResources;
838
+ }
839
+ destroyChildren(errors) {
840
+ this._destroyingOwnedResources = true;
841
+ try {
842
+ for (const resource of this._ownedResources) {
843
+ try {
844
+ resource.destroy();
845
+ } catch (error) {
846
+ errors.push(error);
847
+ }
848
+ }
849
+ } finally {
850
+ this._ownedResources.clear();
851
+ this._destroyingOwnedResources = false;
852
+ }
853
+ }
854
+ };
855
+
856
+ // ../core/src/api/adapter/resources/device-resource.ts
713
857
  var CPU_HOTSPOT_PROFILER_MODULE = "cpu-hotspot-profiler";
714
858
  var RESOURCE_COUNTS_STATS = "GPU Resource Counts";
715
859
  var LEGACY_RESOURCE_COUNTS_STATS = "Resource Counts";
@@ -765,7 +909,7 @@ var __exports__ = (() => {
765
909
  ]);
766
910
  var ORDERED_STATS_CACHE = /* @__PURE__ */ new WeakMap();
767
911
  var ORDERED_STAT_NAME_SET_CACHE = /* @__PURE__ */ new WeakMap();
768
- var Resource = class {
912
+ var DeviceResource = class extends Resource {
769
913
  /** Default properties for resource */
770
914
  static defaultProps = {
771
915
  id: "undefined",
@@ -788,14 +932,10 @@ var __exports__ = (() => {
788
932
  userData = {};
789
933
  /** The device that this resource is associated with - TODO can we remove this dup? */
790
934
  _device;
791
- /** Whether this resource has been destroyed */
792
- destroyed = false;
793
935
  /** For resources that allocate GPU memory */
794
936
  allocatedBytes = 0;
795
937
  /** Stats bucket currently holding the tracked allocation */
796
938
  allocatedBytesName = null;
797
- /** Attached resources will be destroyed when this resource is destroyed. Tracks auto-created "sub" resources. */
798
- _attachedResources = /* @__PURE__ */ new Set();
799
939
  /** Whether luma.gl created and owns the underlying resource handle. */
800
940
  get ownsHandle() {
801
941
  return (this.props.handle === void 0 || this.props.handle === null) && !this.isHandleBorrowed;
@@ -805,9 +945,10 @@ var __exports__ = (() => {
805
945
  return Boolean(this.props._isHandleBorrowed);
806
946
  }
807
947
  /**
808
- * Create a new Resource. Called from Subclass
948
+ * Create a new DeviceResource. Called from Subclass
809
949
  */
810
950
  constructor(device, props, defaultProps) {
951
+ super();
811
952
  if (!device) {
812
953
  throw new Error("no device");
813
954
  }
@@ -819,20 +960,6 @@ var __exports__ = (() => {
819
960
  this.userData = this.props.userData || {};
820
961
  this.addStats();
821
962
  }
822
- /**
823
- * destroy can be called on any resource to release it before it is garbage collected.
824
- */
825
- destroy() {
826
- if (this.destroyed) {
827
- return;
828
- }
829
- this.destroyResource();
830
- }
831
- /** @deprecated Use destroy() */
832
- delete() {
833
- this.destroy();
834
- return this;
835
- }
836
963
  /**
837
964
  * Combines a map of user props and default props, only including props from defaultProps
838
965
  * @returns returns a map of overridden default props
@@ -840,46 +967,19 @@ var __exports__ = (() => {
840
967
  getProps() {
841
968
  return this.props;
842
969
  }
843
- // ATTACHED RESOURCES
844
- /**
845
- * Attaches a resource. Attached resources are auto destroyed when this resource is destroyed
846
- * Called automatically when sub resources are auto created but can be called by application
847
- */
848
- attachResource(resource) {
849
- this._attachedResources.add(resource);
850
- }
851
- /**
852
- * Detach an attached resource. The resource will no longer be auto-destroyed when this resource is destroyed.
853
- */
854
- detachResource(resource) {
855
- this._attachedResources.delete(resource);
856
- }
857
- /**
858
- * Destroys a resource (only if owned), and removes from the owned (auto-destroy) list for this resource.
859
- */
860
- destroyAttachedResource(resource) {
861
- if (this._attachedResources.delete(resource)) {
862
- resource.destroy();
863
- }
864
- }
865
- /** Destroy all owned resources. Make sure the resources are no longer needed before calling. */
866
- destroyAttachedResources() {
867
- for (const resource of this._attachedResources) {
868
- resource.destroy();
869
- }
870
- this._attachedResources = /* @__PURE__ */ new Set();
970
+ /** Backend cleanup. Override this instead of destroy(); children are already destroyed. */
971
+ destroyHandle() {
871
972
  }
872
- // PROTECTED METHODS
873
- /** Perform all destroy steps. Can be called by derived resources when overriding destroy() */
874
- destroyResource() {
875
- if (this.destroyed) {
876
- return;
973
+ /** Complete device bookkeeping even when backend cleanup fails. */
974
+ onDestroy() {
975
+ try {
976
+ this.destroyHandle();
977
+ } finally {
978
+ this.trackDeallocatedMemory();
979
+ this.removeStats();
877
980
  }
878
- this.destroyAttachedResources();
879
- this.removeStats();
880
- this.destroyed = true;
881
981
  }
882
- /** Called by .destroy() to track object destruction. Subclass must call if overriding destroy() */
982
+ /** Track object destruction after backend cleanup. */
883
983
  removeStats() {
884
984
  const profiler = getCpuHotspotProfiler(this._device);
885
985
  const startTime = profiler ? getTimestamp() : 0;
@@ -1057,7 +1157,7 @@ var __exports__ = (() => {
1057
1157
  let prototype = Object.getPrototypeOf(resource);
1058
1158
  while (prototype) {
1059
1159
  const parentPrototype = Object.getPrototypeOf(prototype);
1060
- if (!parentPrototype || parentPrototype === Resource.prototype) {
1160
+ if (!parentPrototype || parentPrototype === DeviceResource.prototype) {
1061
1161
  return getPrototypeToStringTag(prototype) || resource[Symbol.toStringTag] || resource.constructor.name;
1062
1162
  }
1063
1163
  prototype = parentPrototype;
@@ -1076,7 +1176,7 @@ var __exports__ = (() => {
1076
1176
  }
1077
1177
 
1078
1178
  // ../core/src/api/adapter/resources/buffer.ts
1079
- var Buffer3 = class _Buffer extends Resource {
1179
+ var Buffer3 = class _Buffer extends DeviceResource {
1080
1180
  /** Index buffer */
1081
1181
  static INDEX = 16;
1082
1182
  /** Vertex buffer */
@@ -1157,7 +1257,7 @@ var __exports__ = (() => {
1157
1257
  }
1158
1258
  }
1159
1259
  static defaultProps = {
1160
- ...Resource.defaultProps,
1260
+ ...DeviceResource.defaultProps,
1161
1261
  handle: void 0,
1162
1262
  usage: 0,
1163
1263
  // Buffer.COPY_DST | Buffer.COPY_SRC
@@ -1193,7 +1293,19 @@ var __exports__ = (() => {
1193
1293
  }
1194
1294
 
1195
1295
  // ../core/src/shadertypes/data-types/decode-data-types.ts
1296
+ var dataTypeInfoCache = /* @__PURE__ */ new Map();
1196
1297
  function getDataTypeInfo(type) {
1298
+ const cached = dataTypeInfoCache.get(type);
1299
+ if (cached) {
1300
+ return cached;
1301
+ }
1302
+ const decoded = Object.freeze(decodeDataTypeInfo(type));
1303
+ if (Object.hasOwn(NORMALIZED_TYPE_MAP, type)) {
1304
+ dataTypeInfoCache.set(type, decoded);
1305
+ }
1306
+ return decoded;
1307
+ }
1308
+ function decodeDataTypeInfo(type) {
1197
1309
  const normalized = type.includes("norm");
1198
1310
  const integer = !normalized && !type.startsWith("float");
1199
1311
  const signed = type.startsWith("s");
@@ -1534,40 +1646,33 @@ var __exports__ = (() => {
1534
1646
  return this.isCompressed(format) && !format.endsWith("-webgl") ? WEBGPU_CREATE_FILTER2 : 0;
1535
1647
  }
1536
1648
  /** Computes the memory layout for a texture, in particular including row byte alignment */
1537
- computeMemoryLayout(opts) {
1538
- return computeTextureMemoryLayout(opts);
1649
+ computeMemoryLayout(opts, result) {
1650
+ return computeTextureMemoryLayout(opts, result);
1539
1651
  }
1540
1652
  };
1541
1653
  var textureFormatDecoder = new TextureFormatDecoder();
1542
- function computeTextureMemoryLayout({
1543
- format,
1544
- width,
1545
- height,
1546
- depth,
1547
- byteAlignment
1548
- }) {
1654
+ function computeTextureMemoryLayout({ format, width, height, depth, byteAlignment }, result = {}) {
1549
1655
  const formatInfo = textureFormatDecoder.getInfo(format);
1656
+ const { bytesPerPixel, blockHeight = 1, compressed = false } = formatInfo;
1657
+ const bytesPerRow = getTextureBytesPerRow(formatInfo, width, byteAlignment);
1658
+ const rowsPerImage = compressed ? Math.ceil(height / blockHeight) : height;
1659
+ result.bytesPerPixel = bytesPerPixel;
1660
+ result.bytesPerRow = bytesPerRow;
1661
+ result.rowsPerImage = rowsPerImage;
1662
+ result.depthOrArrayLayers = depth;
1663
+ result.bytesPerImage = bytesPerRow * rowsPerImage;
1664
+ result.byteLength = result.bytesPerImage * depth;
1665
+ return result;
1666
+ }
1667
+ function getTextureBytesPerRow(formatInfo, width, byteAlignment) {
1550
1668
  const {
1551
1669
  bytesPerPixel,
1552
1670
  bytesPerBlock = bytesPerPixel,
1553
1671
  blockWidth = 1,
1554
- blockHeight = 1,
1555
1672
  compressed = false
1556
1673
  } = formatInfo;
1557
1674
  const blockColumns = compressed ? Math.ceil(width / blockWidth) : width;
1558
- const blockRows = compressed ? Math.ceil(height / blockHeight) : height;
1559
- const unpaddedBytesPerRow = blockColumns * bytesPerBlock;
1560
- const bytesPerRow = Math.ceil(unpaddedBytesPerRow / byteAlignment) * byteAlignment;
1561
- const rowsPerImage = blockRows;
1562
- const byteLength = bytesPerRow * rowsPerImage * depth;
1563
- return {
1564
- bytesPerPixel,
1565
- bytesPerRow,
1566
- rowsPerImage,
1567
- depthOrArrayLayers: depth,
1568
- bytesPerImage: bytesPerRow * rowsPerImage,
1569
- byteLength
1570
- };
1675
+ return Math.ceil(blockColumns * bytesPerBlock / byteAlignment) * byteAlignment;
1571
1676
  }
1572
1677
  function getTextureFormatCapabilities(format) {
1573
1678
  const info = getTextureFormatDefinition(format);
@@ -1589,7 +1694,18 @@ var __exports__ = (() => {
1589
1694
  formatCapabilities.filter &&= !isDepthStencil && !isSigned && !isInteger && !isWebGLSpecific;
1590
1695
  return formatCapabilities;
1591
1696
  }
1697
+ var textureFormatInfoCache = /* @__PURE__ */ new Map();
1592
1698
  function getTextureFormatInfo(format) {
1699
+ let formatInfo = textureFormatInfoCache.get(format);
1700
+ if (!formatInfo) {
1701
+ const decoded = decodeTextureFormatInfo(format);
1702
+ decoded.bitsPerChannel = Object.freeze([...decoded.bitsPerChannel]);
1703
+ formatInfo = Object.freeze(decoded);
1704
+ textureFormatInfoCache.set(format, formatInfo);
1705
+ }
1706
+ return formatInfo;
1707
+ }
1708
+ function decodeTextureFormatInfo(format) {
1593
1709
  let formatInfo = getTextureFormatInfoUsingTable(format);
1594
1710
  if (textureFormatDecoder.isCompressed(format)) {
1595
1711
  formatInfo.channels = "rgb";
@@ -1729,9 +1845,9 @@ var __exports__ = (() => {
1729
1845
  }
1730
1846
 
1731
1847
  // ../core/src/api/adapter/resources/sampler.ts
1732
- var Sampler = class _Sampler extends Resource {
1848
+ var Sampler = class _Sampler extends DeviceResource {
1733
1849
  static defaultProps = {
1734
- ...Resource.defaultProps,
1850
+ ...DeviceResource.defaultProps,
1735
1851
  type: "color-sampler",
1736
1852
  addressModeU: "clamp-to-edge",
1737
1853
  addressModeV: "clamp-to-edge",
@@ -1756,8 +1872,24 @@ var __exports__ = (() => {
1756
1872
  return props;
1757
1873
  }
1758
1874
  };
1875
+ function setTextureSampler(texture, sampler) {
1876
+ const nextSampler = sampler instanceof Sampler ? sampler : texture.device.createSampler(sampler);
1877
+ if (nextSampler === texture.sampler) {
1878
+ return;
1879
+ }
1880
+ if (!(sampler instanceof Sampler)) {
1881
+ nextSampler.transferOwnershipTo(texture);
1882
+ }
1883
+ const previousSampler = texture.sampler;
1884
+ texture.sampler = nextSampler;
1885
+ if (previousSampler?.owner === texture) {
1886
+ previousSampler.destroy();
1887
+ }
1888
+ }
1759
1889
 
1760
1890
  // ../core/src/api/adapter/resources/texture.ts
1891
+ var textureLayoutScratchPool = [];
1892
+ var emptyTextureReadOptions = Object.freeze({});
1761
1893
  var BASE_DIMENSIONS = {
1762
1894
  "1d": "1d",
1763
1895
  "2d": "2d",
@@ -1766,7 +1898,7 @@ var __exports__ = (() => {
1766
1898
  "cube-array": "2d",
1767
1899
  "3d": "3d"
1768
1900
  };
1769
- var Texture2 = class _Texture extends Resource {
1901
+ var Texture2 = class _Texture extends DeviceResource {
1770
1902
  /** The texture can be bound for use as a sampled texture in a shader */
1771
1903
  static SAMPLE = 4;
1772
1904
  /** The texture can be bound for use as a storage texture in a shader */
@@ -1854,7 +1986,7 @@ var __exports__ = (() => {
1854
1986
  }
1855
1987
  /** Set sampler props associated with this texture */
1856
1988
  setSampler(sampler) {
1857
- this.sampler = sampler instanceof Sampler ? sampler : this.device.createSampler(sampler);
1989
+ setTextureSampler(this, sampler);
1858
1990
  }
1859
1991
  /**
1860
1992
  * Copy raw image data (bytes) into the texture.
@@ -1876,17 +2008,24 @@ var __exports__ = (() => {
1876
2008
  * Calculates the memory layout of the texture, required when reading and writing data.
1877
2009
  * @return the backend-aligned linear layout, in particular bytesPerRow which includes any required padding for buffer copy/read paths
1878
2010
  */
1879
- computeMemoryLayout(options_ = {}) {
1880
- const options = this._normalizeTextureReadOptions(options_);
1881
- const { width = this.width, height = this.height, depthOrArrayLayers = this.depth } = options;
1882
- const { format, byteAlignment } = this;
1883
- return textureFormatDecoder.computeMemoryLayout({
1884
- format,
1885
- width,
1886
- height,
1887
- depth: depthOrArrayLayers,
1888
- byteAlignment
1889
- });
2011
+ /** The optional result is caller-owned; internal scratch never escapes this call. */
2012
+ computeMemoryLayout(options_ = emptyTextureReadOptions, result) {
2013
+ const scratch = textureLayoutScratchPool.pop() || {
2014
+ readOptions: {},
2015
+ layoutOptions: {}
2016
+ };
2017
+ try {
2018
+ const options = this._normalizeTextureReadOptions(options_, scratch.readOptions);
2019
+ const layoutOptions = scratch.layoutOptions;
2020
+ layoutOptions.format = this.format;
2021
+ layoutOptions.width = options.width;
2022
+ layoutOptions.height = options.height;
2023
+ layoutOptions.depth = options.depthOrArrayLayers;
2024
+ layoutOptions.byteAlignment = this.byteAlignment;
2025
+ return textureFormatDecoder.computeMemoryLayout(layoutOptions, result);
2026
+ } finally {
2027
+ textureLayoutScratchPool.push(scratch);
2028
+ }
1890
2029
  }
1891
2030
  /**
1892
2031
  * Read the contents of a texture into a GPU Buffer.
@@ -1995,59 +2134,57 @@ var __exports__ = (() => {
1995
2134
  });
1996
2135
  }
1997
2136
  }
1998
- _normalizeCopyImageDataOptions(options_) {
1999
- const { data, depth, ...writeOptions } = options_;
2000
- const options = this._normalizeTextureWriteOptions({
2001
- ...writeOptions,
2002
- depthOrArrayLayers: writeOptions.depthOrArrayLayers ?? depth
2003
- });
2004
- return { data, depth: options.depthOrArrayLayers, ...options };
2137
+ /** The optional result is caller-owned scratch storage; every result field is overwritten. */
2138
+ _normalizeCopyImageDataOptions(options_, result = {}) {
2139
+ const { data, depth, depthOrArrayLayers } = options_;
2140
+ this._normalizeTextureWriteOptions(options_, result);
2141
+ if (depthOrArrayLayers === void 0 && depth !== void 0) {
2142
+ const mipDepth = this.dimension === "3d" ? Math.max(1, this.depth >> result.mipLevel) : this.depth;
2143
+ result.depthOrArrayLayers = Math.min(depth, mipDepth - result.z);
2144
+ }
2145
+ result.data = data;
2146
+ result.depth = result.depthOrArrayLayers;
2147
+ return result;
2005
2148
  }
2006
- _normalizeCopyExternalImageOptions(options_) {
2007
- const optionsWithoutUndefined = _Texture._omitUndefined(options_);
2008
- const mipLevel = optionsWithoutUndefined.mipLevel ?? 0;
2009
- const mipLevelSize = this._getMipLevelSize(mipLevel);
2149
+ _normalizeCopyExternalImageOptions(options_, result = {}) {
2150
+ const { width, height } = options_;
2010
2151
  const size = this.device.getExternalImageSize(options_.image);
2011
- const options = {
2012
- ..._Texture.defaultCopyExternalImageOptions,
2013
- ...mipLevelSize,
2014
- ...size,
2015
- ...optionsWithoutUndefined
2016
- };
2017
- options.width = Math.min(options.width, mipLevelSize.width - options.x);
2018
- options.height = Math.min(options.height, mipLevelSize.height - options.y);
2019
- options.depth = Math.min(options.depth, mipLevelSize.depthOrArrayLayers - options.z);
2152
+ const options = _Texture._normalizeOptions(
2153
+ options_,
2154
+ _Texture.defaultCopyExternalImageOptions,
2155
+ result
2156
+ );
2157
+ const mipWidth = Math.max(1, this.width >> options.mipLevel);
2158
+ const mipHeight = this.baseDimension === "1d" ? 1 : Math.max(1, this.height >> options.mipLevel);
2159
+ const mipDepth = this.dimension === "3d" ? Math.max(1, this.depth >> options.mipLevel) : this.depth;
2160
+ options.width = Math.min(width ?? size.width, mipWidth - options.x);
2161
+ options.height = Math.min(height ?? size.height, mipHeight - options.y);
2162
+ options.depth = Math.min(options.depth, mipDepth - options.z);
2020
2163
  return options;
2021
2164
  }
2022
- _normalizeCopyElementImageOptions(options_) {
2023
- const optionsWithoutUndefined = _Texture._omitUndefined(options_);
2024
- const mipLevel = optionsWithoutUndefined.mipLevel ?? 0;
2025
- const mipLevelSize = this._getMipLevelSize(mipLevel);
2026
- const options = {
2027
- ..._Texture.defaultCopyElementImageOptions,
2028
- ...mipLevelSize,
2029
- ...optionsWithoutUndefined
2030
- };
2031
- options.width = Math.min(options.width, mipLevelSize.width - options.x);
2032
- options.height = Math.min(options.height, mipLevelSize.height - options.y);
2033
- options.depth = Math.min(options.depth, mipLevelSize.depthOrArrayLayers - options.z);
2165
+ _normalizeCopyElementImageOptions(options_, result = {}) {
2166
+ const options = _Texture._normalizeOptions(
2167
+ options_,
2168
+ _Texture.defaultCopyElementImageOptions,
2169
+ result
2170
+ );
2171
+ const mipWidth = Math.max(1, this.width >> options.mipLevel);
2172
+ const mipHeight = this.baseDimension === "1d" ? 1 : Math.max(1, this.height >> options.mipLevel);
2173
+ const mipDepth = this.dimension === "3d" ? Math.max(1, this.depth >> options.mipLevel) : this.depth;
2174
+ options.width = Math.min(options.width ?? mipWidth, mipWidth - options.x);
2175
+ options.height = Math.min(options.height ?? mipHeight, mipHeight - options.y);
2176
+ options.depth = Math.min(options.depth, mipDepth - options.z);
2034
2177
  return options;
2035
2178
  }
2036
- _normalizeTextureReadOptions(options_) {
2037
- const optionsWithoutUndefined = _Texture._omitUndefined(options_);
2038
- const mipLevel = optionsWithoutUndefined.mipLevel ?? 0;
2039
- const mipLevelSize = this._getMipLevelSize(mipLevel);
2040
- const options = {
2041
- ..._Texture.defaultTextureReadOptions,
2042
- ...mipLevelSize,
2043
- ...optionsWithoutUndefined
2044
- };
2045
- options.width = Math.min(options.width, mipLevelSize.width - options.x);
2046
- options.height = Math.min(options.height, mipLevelSize.height - options.y);
2047
- options.depthOrArrayLayers = Math.min(
2048
- options.depthOrArrayLayers,
2049
- mipLevelSize.depthOrArrayLayers - options.z
2050
- );
2179
+ _normalizeTextureReadOptions(options_, result = {}) {
2180
+ const { depthOrArrayLayers } = options_;
2181
+ const options = _Texture._normalizeOptions(options_, _Texture.defaultTextureReadOptions, result);
2182
+ const mipWidth = Math.max(1, this.width >> options.mipLevel);
2183
+ const mipHeight = this.baseDimension === "1d" ? 1 : Math.max(1, this.height >> options.mipLevel);
2184
+ const mipDepth = this.dimension === "3d" ? Math.max(1, this.depth >> options.mipLevel) : this.depth;
2185
+ options.width = Math.min(options.width ?? mipWidth, mipWidth - options.x);
2186
+ options.height = Math.min(options.height ?? mipHeight, mipHeight - options.y);
2187
+ options.depthOrArrayLayers = Math.min(depthOrArrayLayers ?? mipDepth, mipDepth - options.z);
2051
2188
  return options;
2052
2189
  }
2053
2190
  /**
@@ -2102,31 +2239,15 @@ var __exports__ = (() => {
2102
2239
  throw new Error(`${this} color readback does not support format ${this.format}`);
2103
2240
  }
2104
2241
  }
2105
- _normalizeTextureWriteOptions(options_) {
2106
- const optionsWithoutUndefined = _Texture._omitUndefined(options_);
2107
- const mipLevel = optionsWithoutUndefined.mipLevel ?? 0;
2108
- const mipLevelSize = this._getMipLevelSize(mipLevel);
2109
- const options = {
2110
- ..._Texture.defaultTextureWriteOptions,
2111
- ...mipLevelSize,
2112
- ...optionsWithoutUndefined
2113
- };
2114
- options.width = Math.min(options.width, mipLevelSize.width - options.x);
2115
- options.height = Math.min(options.height, mipLevelSize.height - options.y);
2116
- options.depthOrArrayLayers = Math.min(
2117
- options.depthOrArrayLayers,
2118
- mipLevelSize.depthOrArrayLayers - options.z
2119
- );
2120
- const layout = textureFormatDecoder.computeMemoryLayout({
2121
- format: this.format,
2122
- width: options.width,
2123
- height: options.height,
2124
- depth: options.depthOrArrayLayers,
2125
- byteAlignment: this.byteAlignment
2126
- });
2127
- const minimumBytesPerRow = layout.bytesPerPixel * options.width;
2128
- options.bytesPerRow = optionsWithoutUndefined.bytesPerRow ?? layout.bytesPerRow;
2129
- options.rowsPerImage = optionsWithoutUndefined.rowsPerImage ?? options.height;
2242
+ _normalizeTextureWriteOptions(options_, result = {}) {
2243
+ const { byteOffset = 0, bytesPerRow, rowsPerImage } = options_;
2244
+ this._normalizeTextureReadOptions(options_, result);
2245
+ const options = result;
2246
+ options.byteOffset = byteOffset;
2247
+ const formatInfo = this.device.getTextureFormatInfo(this.format);
2248
+ const minimumBytesPerRow = formatInfo.bytesPerPixel * options.width;
2249
+ options.bytesPerRow = bytesPerRow ?? getTextureBytesPerRow(formatInfo, options.width, this.byteAlignment);
2250
+ options.rowsPerImage = rowsPerImage ?? options.height;
2130
2251
  if (options.bytesPerRow < minimumBytesPerRow) {
2131
2252
  throw new Error(
2132
2253
  `bytesPerRow (${options.bytesPerRow}) must be at least ${minimumBytesPerRow} for ${this.format}`
@@ -2137,7 +2258,7 @@ var __exports__ = (() => {
2137
2258
  `rowsPerImage (${options.rowsPerImage}) must be at least ${options.height} for ${this.format}`
2138
2259
  );
2139
2260
  }
2140
- const bytesPerPixel = this.device.getTextureFormatInfo(this.format).bytesPerPixel;
2261
+ const { bytesPerPixel } = formatInfo;
2141
2262
  if (bytesPerPixel && options.bytesPerRow % bytesPerPixel !== 0) {
2142
2263
  throw new Error(
2143
2264
  `bytesPerRow (${options.bytesPerRow}) must be a multiple of bytesPerPixel (${bytesPerPixel}) for ${this.format}`
@@ -2165,13 +2286,15 @@ var __exports__ = (() => {
2165
2286
  }
2166
2287
  return allocatedByteLength * this.samples;
2167
2288
  }
2168
- static _omitUndefined(options) {
2169
- return Object.fromEntries(
2170
- Object.entries(options).filter(([, value]) => value !== void 0)
2171
- );
2289
+ /** Fill every declared field, resetting stale scratch values without allocating entries or spreads. */
2290
+ static _normalizeOptions(options, defaults, result) {
2291
+ for (const key in defaults) {
2292
+ result[key] = options[key] === void 0 ? defaults[key] : options[key];
2293
+ }
2294
+ return result;
2172
2295
  }
2173
2296
  static defaultProps = {
2174
- ...Resource.defaultProps,
2297
+ ...DeviceResource.defaultProps,
2175
2298
  data: null,
2176
2299
  dimension: "2d",
2177
2300
  format: "rgba8unorm",
@@ -2245,19 +2368,6 @@ var __exports__ = (() => {
2245
2368
  mipLevel: 0,
2246
2369
  aspect: "all"
2247
2370
  };
2248
- static defaultTextureWriteOptions = {
2249
- byteOffset: 0,
2250
- bytesPerRow: void 0,
2251
- rowsPerImage: void 0,
2252
- x: 0,
2253
- y: 0,
2254
- z: 0,
2255
- width: void 0,
2256
- height: void 0,
2257
- depthOrArrayLayers: 1,
2258
- mipLevel: 0,
2259
- aspect: "all"
2260
- };
2261
2371
  };
2262
2372
 
2263
2373
  // ../core/src/dynamic/dynamic-buffer/dynamic-buffer.ts
@@ -5253,6 +5363,15 @@ var __exports__ = (() => {
5253
5363
  validateGraphBufferDescriptor(descriptor, this.device);
5254
5364
  return this.addBuffer(new GraphBufferHandle(this, descriptor, true));
5255
5365
  }
5366
+ /** Choose a compiler-owned resource name without treating diagnostic labels as unique. @internal */
5367
+ getUniqueResourceId(label) {
5368
+ let id = label;
5369
+ let suffix = 1;
5370
+ while (this.buffers.has(id) || this.textures.has(id) || this.externalTextures.has(id)) {
5371
+ id = `${label}-${suffix++}`;
5372
+ }
5373
+ return id;
5374
+ }
5256
5375
  /**
5257
5376
  * Creates one typed range over a graph buffer.
5258
5377
  *
@@ -6674,7 +6793,7 @@ var __exports__ = (() => {
6674
6793
  };
6675
6794
 
6676
6795
  // src/gpu-core/compiled-gpu-graph.ts
6677
- var import_core22 = __toESM(require_core(), 1);
6796
+ var import_core25 = __toESM(require_core(), 1);
6678
6797
 
6679
6798
  // src/gpu-core/gpu-texture-plan.ts
6680
6799
  var import_core10 = __toESM(require_core(), 1);
@@ -7164,6 +7283,52 @@ var __exports__ = (() => {
7164
7283
  }
7165
7284
  };
7166
7285
 
7286
+ // src/gpu-core/graph-vector-view-utils.ts
7287
+ function getGraphVectorData(vector) {
7288
+ return vector instanceof GraphVectorView ? vector.data : [vector];
7289
+ }
7290
+ function alignGraphVectorViews(graph, vectors) {
7291
+ const length = vectors[0]?.length ?? 0;
7292
+ if (vectors.some((vector) => vector.length !== length)) {
7293
+ throw new Error("Aligned vectors must have equal logical lengths");
7294
+ }
7295
+ const chunks = vectors.map(getGraphVectorData);
7296
+ const indices = vectors.map(() => 0);
7297
+ const offsets = vectors.map(() => 0);
7298
+ const result = [];
7299
+ let position = 0;
7300
+ while (position < length) {
7301
+ for (let index = 0; index < chunks.length; index++) {
7302
+ while (chunks[index][indices[index]]?.length === offsets[index]) {
7303
+ indices[index]++;
7304
+ offsets[index] = 0;
7305
+ }
7306
+ }
7307
+ const current = chunks.map((data, index) => data[indices[index]]);
7308
+ const span = Math.min(...current.map((data, index) => data.length - offsets[index]));
7309
+ const aligned = [];
7310
+ for (let index = 0; index < current.length; index++) {
7311
+ const data = current[index];
7312
+ const matchingIndex = current.findIndex(
7313
+ (candidate, candidateIndex) => candidateIndex < index && candidate === data && offsets[candidateIndex] === offsets[index]
7314
+ );
7315
+ aligned.push(
7316
+ matchingIndex >= 0 ? aligned[matchingIndex] : offsets[index] === 0 && span === data.length ? data : graph.createDataView(data.buffer, {
7317
+ format: data.format,
7318
+ length: span,
7319
+ byteOffset: data.byteOffset + offsets[index] * data.byteStride,
7320
+ byteStride: data.byteStride,
7321
+ rowByteLength: data.rowByteLength
7322
+ })
7323
+ );
7324
+ }
7325
+ result.push(aligned);
7326
+ for (let index = 0; index < offsets.length; index++) offsets[index] += span;
7327
+ position += span;
7328
+ }
7329
+ return result;
7330
+ }
7331
+
7167
7332
  // src/gpu-core/gpu-command-dispatch-metadata.ts
7168
7333
  function setGPUComputeDispatchWorkgroups(node, workgroups) {
7169
7334
  const [x, y, z] = workgroups;
@@ -7418,66 +7583,1092 @@ var __exports__ = (() => {
7418
7583
  }) : data[0];
7419
7584
  }
7420
7585
 
7421
- // src/gpu-core/graph-vector-view-utils.ts
7422
- function getGraphVectorData(vector) {
7423
- return vector instanceof GraphVectorView ? vector.data : [vector];
7424
- }
7425
- function alignGraphVectorViews(graph, vectors) {
7426
- const length = vectors[0]?.length ?? 0;
7427
- if (vectors.some((vector) => vector.length !== length)) {
7428
- throw new Error("Aligned vectors must have equal logical lengths");
7429
- }
7430
- const chunks = vectors.map(getGraphVectorData);
7431
- const indices = vectors.map(() => 0);
7432
- const offsets = vectors.map(() => 0);
7433
- const result = [];
7434
- let position = 0;
7435
- while (position < length) {
7436
- for (let index = 0; index < chunks.length; index++) {
7437
- while (chunks[index][indices[index]]?.length === offsets[index]) {
7438
- indices[index]++;
7439
- offsets[index] = 0;
7440
- }
7441
- }
7442
- const current = chunks.map((data, index) => data[indices[index]]);
7443
- const span = Math.min(...current.map((data, index) => data.length - offsets[index]));
7444
- const aligned = [];
7445
- for (let index = 0; index < current.length; index++) {
7446
- const data = current[index];
7447
- const matchingIndex = current.findIndex(
7448
- (candidate, candidateIndex) => candidateIndex < index && candidate === data && offsets[candidateIndex] === offsets[index]
7449
- );
7450
- aligned.push(
7451
- matchingIndex >= 0 ? aligned[matchingIndex] : offsets[index] === 0 && span === data.length ? data : graph.createDataView(data.buffer, {
7452
- format: data.format,
7453
- length: span,
7454
- byteOffset: data.byteOffset + offsets[index] * data.byteStride,
7455
- byteStride: data.byteStride,
7456
- rowByteLength: data.rowByteLength
7457
- })
7458
- );
7459
- }
7460
- result.push(aligned);
7461
- for (let index = 0; index < offsets.length; index++) offsets[index] += span;
7462
- position += span;
7463
- }
7464
- return result;
7465
- }
7466
-
7467
7586
  // src/gpu-core/gpu-subgroup-utils.ts
7468
7587
  function getGPUShaderSubgroupStrategy(device, options = {}) {
7469
7588
  const supportsSubgroups = device.features?.has("subgroups");
7470
7589
  const supportsRequiredLanguageFeatures = !options.requiresSubgroupId || device.wgslLanguageFeatures?.has("subgroup_id");
7471
7590
  return supportsSubgroups && supportsRequiredLanguageFeatures ? "subgroups" : "portable";
7472
7591
  }
7592
+ function getSubgroupBallotHelpersWGSL() {
7593
+ return (
7594
+ /* wgsl */
7595
+ `
7596
+ fn getFirstBallotLane(mask: vec4<u32>) -> u32 {
7597
+ if (mask.x != 0u) { return firstTrailingBit(mask.x); }
7598
+ if (mask.y != 0u) { return 32u + firstTrailingBit(mask.y); }
7599
+ if (mask.z != 0u) { return 64u + firstTrailingBit(mask.z); }
7600
+ if (mask.w != 0u) { return 96u + firstTrailingBit(mask.w); }
7601
+ return 0u;
7602
+ }
7473
7603
 
7474
- // src/gpu-core/gpu-scan.ts
7475
- var SCAN_WORKGROUP_SIZE = 256;
7476
- var MAXIMUM_SCAN_SUBGROUP_COUNT = 64;
7477
- function getGPUScanStrategy(device, segmented = false) {
7478
- return segmented ? "portable" : getGPUShaderSubgroupStrategy(device, { requiresSubgroupId: true });
7604
+ fn getBallotLaneCount(mask: vec4<u32>) -> u32 {
7605
+ return countOneBits(mask.x) + countOneBits(mask.y) +
7606
+ countOneBits(mask.z) + countOneBits(mask.w);
7607
+ }
7608
+
7609
+ fn getBallotPrefixLaneCount(mask: vec4<u32>, invocation: u32) -> u32 {
7610
+ let word = invocation >> 5u;
7611
+ let bit = invocation & 31u;
7612
+ var count = 0u;
7613
+ if (word > 0u) { count += countOneBits(mask.x); }
7614
+ if (word > 1u) { count += countOneBits(mask.y); }
7615
+ if (word > 2u) { count += countOneBits(mask.z); }
7616
+ let lowerBits = (1u << bit) - 1u;
7617
+ return count + countOneBits(mask[word] & lowerBits);
7618
+ }`
7619
+ );
7479
7620
  }
7480
- var GPUScan = class {
7621
+ function getSubgroupCoalescedAtomicAddWGSL(acceptedExpression, keyExpression, atomicArrayName, maximumDistinctKeyCount) {
7622
+ return (
7623
+ /* wgsl */
7624
+ `
7625
+ var subgroupPending = ${acceptedExpression};
7626
+ for (var subgroupGroup = 0u; subgroupGroup < ${maximumDistinctKeyCount}u; subgroupGroup++) {
7627
+ let pendingBallot = subgroupBallot(subgroupPending);
7628
+ let hasPending = any(pendingBallot != vec4<u32>(0u));
7629
+ let leaderInvocation = getFirstBallotLane(pendingBallot);
7630
+ let leaderKey = subgroupShuffle(${keyExpression}, leaderInvocation);
7631
+ let matchingKey = hasPending && subgroupPending && ${keyExpression} == leaderKey;
7632
+ let matchingBallot = subgroupBallot(matchingKey);
7633
+ if (hasPending && subgroupInvocationId == leaderInvocation) {
7634
+ atomicAdd(&${atomicArrayName}[leaderKey], getBallotLaneCount(matchingBallot));
7635
+ }
7636
+ subgroupPending = subgroupPending && !matchingKey;
7637
+ }`
7638
+ );
7639
+ }
7640
+
7641
+ // src/gpu-core/gpu-group-aggregation.ts
7642
+ var GROUP_AGGREGATION_WORKGROUP_SIZE = 256;
7643
+ var MAXIMUM_LOCAL_GROUP_COUNT = 256;
7644
+ var MAXIMUM_SUBGROUP_COALESCED_GROUP_COUNT = 16;
7645
+ var UINT32_BYTE_LENGTH3 = Uint32Array.BYTES_PER_ELEMENT;
7646
+ var GPUGroupAggregation = class {
7647
+ /** Prefix for generated graph node IDs. */
7648
+ id;
7649
+ /** Packed group keys or ordered group-key vector. */
7650
+ keys;
7651
+ /** Optional packed values with the same logical length as keys. */
7652
+ values;
7653
+ /** Caller-owned dense group result. */
7654
+ output;
7655
+ /** Optional source-aligned row selection. */
7656
+ mask;
7657
+ /** Group statistic computed by this aggregation. */
7658
+ operation;
7659
+ /** Creates and validates a dense group-aggregation description. */
7660
+ constructor(props) {
7661
+ this.id = props.id ?? "gpu-group-aggregation";
7662
+ this.keys = props.keys;
7663
+ this.values = props.values;
7664
+ this.output = props.output;
7665
+ this.mask = props.mask;
7666
+ this.operation = props.operation ?? "count";
7667
+ for (const [chunkIndex, chunk] of getGroupChunks(this.keys).entries()) {
7668
+ validateScalarInputView(chunk, "uint32", `${this.id} keys chunk ${chunkIndex}`);
7669
+ }
7670
+ if (this.output.length === 0) {
7671
+ throw new Error(`${this.id} output must contain at least one group`);
7672
+ }
7673
+ if (!["count", "sum", "min", "max", "mean"].includes(this.operation)) {
7674
+ throw new Error(`${this.id} operation must be count, sum, min, max, or mean`);
7675
+ }
7676
+ if (this.operation === "count") {
7677
+ validatePackedUint32View(this.output, `${this.id} count output`);
7678
+ if (this.values) {
7679
+ throw new Error(`${this.id} count operation must not provide values`);
7680
+ }
7681
+ } else {
7682
+ validatePackedView(this.output, ["float32"], `${this.id} statistic output`);
7683
+ if (!this.values) {
7684
+ throw new Error(`${this.id} ${this.operation} operation requires values`);
7685
+ }
7686
+ for (const [chunkIndex, chunk] of getValueChunks(this.values).entries()) {
7687
+ validateScalarInputView(chunk, "float32", `${this.id} values chunk ${chunkIndex}`);
7688
+ }
7689
+ validateMatchingInputs(this.keys, this.values, `${this.id} keys and values`);
7690
+ if (this.operation === "mean" && this.keys.length > 4294967295) {
7691
+ throw new Error(`${this.id} mean input length must fit in uint32 group counts`);
7692
+ }
7693
+ }
7694
+ if (getGroupChunks(this.keys).some((chunk) => chunk.buffer === this.output.buffer)) {
7695
+ throw new Error(`${this.id} keys and output must use separate buffers`);
7696
+ }
7697
+ if (this.values && getValueChunks(this.values).some((chunk) => chunk.buffer === this.output.buffer)) {
7698
+ throw new Error(`${this.id} values and output must use separate buffers`);
7699
+ }
7700
+ if (this.mask) {
7701
+ for (const [chunkIndex, chunk] of getGroupChunks(this.mask).entries()) {
7702
+ validateScalarInputView(chunk, "uint32", `${this.id} mask chunk ${chunkIndex}`);
7703
+ if (chunk.buffer === this.output.buffer) {
7704
+ throw new Error(`${this.id} mask and output must use separate buffers`);
7705
+ }
7706
+ }
7707
+ validateMatchingInputs(this.keys, this.mask, `${this.id} keys and mask`);
7708
+ }
7709
+ }
7710
+ /**
7711
+ * Adds initialization, one accumulation pass per non-empty source chunk, and any required
7712
+ * finalization.
7713
+ *
7714
+ * This method declares work only and does not submit or read back commands.
7715
+ */
7716
+ getCommandNodes(graph) {
7717
+ const nodes = [];
7718
+ let keyChunks = getGroupChunks(this.keys);
7719
+ let maskChunks = this.mask ? getGroupChunks(this.mask) : void 0;
7720
+ let valueChunks = this.values ? getValueChunks(this.values) : void 0;
7721
+ if (keyChunks.some((chunk) => chunk.buffer.graph !== graph) || maskChunks?.some((chunk) => chunk.buffer.graph !== graph) || valueChunks?.some((chunk) => chunk.buffer.graph !== graph) || this.output.buffer.graph !== graph) {
7722
+ throw new Error(`${this.id} views must belong to the target graph`);
7723
+ }
7724
+ if (this.values) {
7725
+ const spans = alignGraphVectorViews(graph, [this.keys, this.values, this.mask ?? this.keys]);
7726
+ keyChunks = spans.map(([keys]) => keys);
7727
+ valueChunks = spans.map(([, values]) => values);
7728
+ maskChunks = this.mask ? spans.map(([, , mask]) => mask) : void 0;
7729
+ } else if (this.mask) {
7730
+ const spans = alignGraphVectorViews(graph, [this.keys, this.mask]);
7731
+ keyChunks = spans.map(([keys]) => keys);
7732
+ maskChunks = spans.map(([, mask]) => mask);
7733
+ }
7734
+ if (this.operation === "count") {
7735
+ const output2 = this.output;
7736
+ nodes.push(...addClearGroupsPass(graph, this.id, output2));
7737
+ const accumulationPath = output2.length <= MAXIMUM_LOCAL_GROUP_COUNT ? "local" : "global";
7738
+ for (let chunkIndex = 0; chunkIndex < keyChunks.length; chunkIndex++) {
7739
+ const keys = keyChunks[chunkIndex];
7740
+ if (keys.length === 0) continue;
7741
+ nodes.push(
7742
+ ...addGroupCountPass(graph, {
7743
+ id: this.keys instanceof GraphVectorView || keyChunks.length > 1 ? `${this.id}-chunk-${chunkIndex}-${accumulationPath}` : `${this.id}-${accumulationPath}`,
7744
+ keys,
7745
+ output: output2,
7746
+ mask: maskChunks?.[chunkIndex],
7747
+ dispatchLayout: getGPUGroupAggregationDispatchLayout(
7748
+ keys.length,
7749
+ graph.device.limits.maxComputeWorkgroupsPerDimension
7750
+ )
7751
+ })
7752
+ );
7753
+ }
7754
+ return nodes;
7755
+ }
7756
+ const output = this.output;
7757
+ const operation = this.operation;
7758
+ const counts = operation === "mean" ? createTransientView(graph, `${this.id}-counts`, "uint32", output.length) : void 0;
7759
+ nodes.push(...addInitializeGroupStatisticsPass(graph, this.id, output, operation, counts));
7760
+ for (let chunkIndex = 0; chunkIndex < keyChunks.length; chunkIndex++) {
7761
+ const keys = keyChunks[chunkIndex];
7762
+ if (keys.length === 0) continue;
7763
+ nodes.push(
7764
+ ...addGroupStatisticPass(graph, {
7765
+ id: this.keys instanceof GraphVectorView || keyChunks.length > 1 ? `${this.id}-chunk-${chunkIndex}` : this.id,
7766
+ keys,
7767
+ values: valueChunks[chunkIndex],
7768
+ mask: maskChunks?.[chunkIndex],
7769
+ output,
7770
+ operation,
7771
+ counts,
7772
+ dispatchLayout: getGPUGroupAggregationDispatchLayout(
7773
+ keys.length,
7774
+ graph.device.limits.maxComputeWorkgroupsPerDimension
7775
+ )
7776
+ })
7777
+ );
7778
+ }
7779
+ if (operation !== "sum") {
7780
+ nodes.push(...addFinalizeGroupStatisticsPass(graph, this.id, output, operation, counts));
7781
+ }
7782
+ return nodes;
7783
+ }
7784
+ };
7785
+ function validateScalarInputView(view, format, name) {
7786
+ if (view.format !== format || view.rowByteLength !== UINT32_BYTE_LENGTH3 || view.byteStride < UINT32_BYTE_LENGTH3 || view.byteStride % UINT32_BYTE_LENGTH3 !== 0 || view.byteOffset % UINT32_BYTE_LENGTH3 !== 0) {
7787
+ throw new Error(`${name} must be a uint32-aligned scalar ${format} GPU data view`);
7788
+ }
7789
+ }
7790
+ function getScalarStride(view) {
7791
+ return view.byteStride / UINT32_BYTE_LENGTH3;
7792
+ }
7793
+ function getGroupChunks(input) {
7794
+ return input instanceof GraphVectorView ? input.data : [input];
7795
+ }
7796
+ function getValueChunks(input) {
7797
+ return input instanceof GraphVectorView ? input.data : [input];
7798
+ }
7799
+ function validateMatchingInputs(keys, paired, label) {
7800
+ if (keys.length !== paired.length) {
7801
+ throw new Error(`${label} lengths must match`);
7802
+ }
7803
+ }
7804
+ function addClearGroupsPass(graph, id, output) {
7805
+ const nodes = [];
7806
+ const dispatchLayout = getGPUGroupAggregationDispatchLayout(
7807
+ output.length,
7808
+ graph.device.limits.maxComputeWorkgroupsPerDimension
7809
+ );
7810
+ const source = (
7811
+ /* wgsl */
7812
+ `
7813
+ const GROUP_COUNT: u32 = ${output.length}u;
7814
+ const OUTPUT_OFFSET: u32 = ${getViewElementOffset(output)}u;
7815
+ @group(0) @binding(0) var<storage, read_write> outputCounts: array<atomic<u32>>;
7816
+
7817
+ @compute @workgroup_size(${GROUP_AGGREGATION_WORKGROUP_SIZE})
7818
+ fn main(
7819
+ @builtin(local_invocation_index) localInvocationIndex: u32,
7820
+ @builtin(workgroup_id) workgroupId: vec3<u32>
7821
+ ) {
7822
+ ${getBoundedInvocationIndexSource(dispatchLayout, GROUP_AGGREGATION_WORKGROUP_SIZE)}
7823
+ if (index < GROUP_COUNT) {
7824
+ atomicStore(&outputCounts[OUTPUT_OFFSET + index], 0u);
7825
+ }
7826
+ }`
7827
+ );
7828
+ nodes.push(
7829
+ ...addKernelPass(graph, {
7830
+ id: `${id}-clear`,
7831
+ source,
7832
+ resources: [{ buffer: output, usage: "storage-write" }],
7833
+ bindings: { outputCounts: output },
7834
+ dispatchSize: dispatchLayout
7835
+ })
7836
+ );
7837
+ return nodes;
7838
+ }
7839
+ function addGroupCountPass(graph, props) {
7840
+ const nodes = [];
7841
+ const local = props.output.length <= MAXIMUM_LOCAL_GROUP_COUNT;
7842
+ const useSubgroups = local && props.output.length <= MAXIMUM_SUBGROUP_COALESCED_GROUP_COUNT && getGPUShaderSubgroupStrategy(graph.device) === "subgroups";
7843
+ const maskBinding = props.mask ? "@group(0) @binding(1) var<storage, read> selectionMask: array<u32>;" : "";
7844
+ const outputBinding = props.mask ? 2 : 1;
7845
+ const maskCondition = props.mask ? `selectionMask[${getViewElementOffset(props.mask)}u + index * ${getScalarStride(props.mask)}u] != 0u` : "true";
7846
+ const localAccumulation = useSubgroups ? getSubgroupCoalescedAtomicAddWGSL(
7847
+ "accepted",
7848
+ "groupIndex",
7849
+ "localCounts",
7850
+ props.output.length
7851
+ ) : " if (accepted) { atomicAdd(&localCounts[groupIndex], 1u); }";
7852
+ const accumulation = local ? `${localAccumulation}
7853
+ workgroupBarrier();
7854
+ if (lane < GROUP_COUNT) {
7855
+ atomicAdd(&outputCounts[OUTPUT_OFFSET + lane], atomicLoad(&localCounts[lane]));
7856
+ }` : "if (accepted) { atomicAdd(&outputCounts[OUTPUT_OFFSET + groupIndex], 1u); }";
7857
+ const source = (
7858
+ /* wgsl */
7859
+ `
7860
+ ${useSubgroups ? "enable subgroups;" : ""}
7861
+ const ELEMENT_COUNT: u32 = ${props.keys.length}u;
7862
+ const GROUP_COUNT: u32 = ${props.output.length}u;
7863
+ const KEYS_OFFSET: u32 = ${getViewElementOffset(props.keys)}u;
7864
+ const KEYS_STRIDE: u32 = ${getScalarStride(props.keys)}u;
7865
+ const OUTPUT_OFFSET: u32 = ${getViewElementOffset(props.output)}u;
7866
+ @group(0) @binding(0) var<storage, read> groupKeys: array<u32>;
7867
+ ${maskBinding}
7868
+ @group(0) @binding(${outputBinding}) var<storage, read_write> outputCounts: array<atomic<u32>>;
7869
+ ${local ? `var<workgroup> localCounts: array<atomic<u32>, ${props.output.length}>;` : ""}
7870
+ ${useSubgroups ? getSubgroupBallotHelpersWGSL() : ""}
7871
+
7872
+ @compute @workgroup_size(${GROUP_AGGREGATION_WORKGROUP_SIZE}) fn main(
7873
+ @builtin(workgroup_id) workgroupId: vec3<u32>,
7874
+ @builtin(local_invocation_id) localId: vec3<u32>${useSubgroups ? ",\n @builtin(subgroup_invocation_id) subgroupInvocationId: u32" : ""}
7875
+ ) {
7876
+ let workgroupIndex = (workgroupId.z * ${props.dispatchLayout.y}u + workgroupId.y) * ${props.dispatchLayout.x}u + workgroupId.x;
7877
+ let index = workgroupIndex * ${GROUP_AGGREGATION_WORKGROUP_SIZE}u + localId.x;
7878
+ let lane = localId.x;
7879
+ ${local ? "if (lane < GROUP_COUNT) { atomicStore(&localCounts[lane], 0u); }\n workgroupBarrier();" : ""}
7880
+ var accepted = false;
7881
+ var groupIndex = 0u;
7882
+ if (index < ELEMENT_COUNT && ${maskCondition}) {
7883
+ groupIndex = groupKeys[KEYS_OFFSET + index * KEYS_STRIDE];
7884
+ accepted = groupIndex < GROUP_COUNT;
7885
+ }
7886
+ ${accumulation}
7887
+ }`
7888
+ );
7889
+ const resources = [
7890
+ { buffer: props.keys, usage: "storage-read" },
7891
+ ...props.mask ? [{ buffer: props.mask, usage: "storage-read" }] : [],
7892
+ { buffer: props.output, usage: "storage-read-write" }
7893
+ ];
7894
+ nodes.push(
7895
+ ...addKernelPass(graph, {
7896
+ id: props.id,
7897
+ source,
7898
+ resources,
7899
+ bindings: {
7900
+ groupKeys: props.keys,
7901
+ ...props.mask ? { selectionMask: props.mask } : {},
7902
+ outputCounts: props.output
7903
+ },
7904
+ dispatchSize: props.dispatchLayout
7905
+ })
7906
+ );
7907
+ return nodes;
7908
+ }
7909
+ function addInitializeGroupStatisticsPass(graph, id, output, operation, counts) {
7910
+ const nodes = [];
7911
+ const dispatchLayout = getGPUGroupAggregationDispatchLayout(
7912
+ output.length,
7913
+ graph.device.limits.maxComputeWorkgroupsPerDimension
7914
+ );
7915
+ const initialBits = operation === "min" ? "0xffffffffu" : "0u";
7916
+ const countBinding = counts ? "@group(0) @binding(1) var<storage, read_write> outputCounts: array<atomic<u32>>;" : "";
7917
+ const countInitialization = counts ? `atomicStore(&outputCounts[${getViewElementOffset(counts)}u + index], 0u);` : "";
7918
+ const source = (
7919
+ /* wgsl */
7920
+ `
7921
+ const GROUP_COUNT: u32 = ${output.length}u;
7922
+ const OUTPUT_OFFSET: u32 = ${getViewElementOffset(output)}u;
7923
+ @group(0) @binding(0) var<storage, read_write> outputValues: array<atomic<u32>>;
7924
+ ${countBinding}
7925
+ @compute @workgroup_size(${GROUP_AGGREGATION_WORKGROUP_SIZE}) fn main(
7926
+ @builtin(local_invocation_index) localInvocationIndex: u32,
7927
+ @builtin(workgroup_id) workgroupId: vec3<u32>
7928
+ ) {
7929
+ ${getBoundedInvocationIndexSource(dispatchLayout, GROUP_AGGREGATION_WORKGROUP_SIZE)}
7930
+ if (index < GROUP_COUNT) {
7931
+ atomicStore(&outputValues[OUTPUT_OFFSET + index], ${initialBits});
7932
+ ${countInitialization}
7933
+ }
7934
+ }`
7935
+ );
7936
+ nodes.push(
7937
+ ...addKernelPass(graph, {
7938
+ id: operation === "sum" ? `${id}-clear` : `${id}-initialize`,
7939
+ source,
7940
+ resources: [
7941
+ { buffer: output, usage: "storage-write" },
7942
+ ...counts ? [{ buffer: counts, usage: "storage-write" }] : []
7943
+ ],
7944
+ bindings: { outputValues: output, ...counts ? { outputCounts: counts } : {} },
7945
+ dispatchSize: dispatchLayout
7946
+ })
7947
+ );
7948
+ return nodes;
7949
+ }
7950
+ function addGroupStatisticPass(graph, props) {
7951
+ const nodes = [];
7952
+ const useSubgroups = props.output.length <= MAXIMUM_SUBGROUP_COALESCED_GROUP_COUNT && getGPUShaderSubgroupStrategy(graph.device) === "subgroups";
7953
+ const maskBinding = props.mask ? "@group(0) @binding(2) var<storage, read> selectionMask: array<u32>;" : "";
7954
+ const outputBinding = props.mask ? 3 : 2;
7955
+ const countsBinding = props.counts ? `@group(0) @binding(${outputBinding + 1}) var<storage, read_write> outputCounts: array<atomic<u32>>;` : "";
7956
+ const maskCondition = props.mask ? `selectionMask[${getViewElementOffset(props.mask)}u + index * ${getScalarStride(props.mask)}u] != 0u` : "true";
7957
+ const accumulation = useSubgroups ? getSubgroupStatisticAggregationWGSL(props.operation, props.output.length, props.counts) : ` if (accepted) {
7958
+ ${getFloatAggregationCall(props.operation, "groupIndex")}
7959
+ ${props.counts ? `atomicAdd(&outputCounts[${getViewElementOffset(props.counts)}u + groupIndex], 1u);` : ""}
7960
+ }`;
7961
+ const source = (
7962
+ /* wgsl */
7963
+ `
7964
+ ${useSubgroups ? "enable subgroups;" : ""}
7965
+ const ELEMENT_COUNT: u32 = ${props.keys.length}u;
7966
+ const GROUP_COUNT: u32 = ${props.output.length}u;
7967
+ const KEYS_OFFSET: u32 = ${getViewElementOffset(props.keys)}u;
7968
+ const VALUES_OFFSET: u32 = ${getViewElementOffset(props.values)}u;
7969
+ const KEYS_STRIDE: u32 = ${getScalarStride(props.keys)}u;
7970
+ const VALUES_STRIDE: u32 = ${getScalarStride(props.values)}u;
7971
+ const OUTPUT_OFFSET: u32 = ${getViewElementOffset(props.output)}u;
7972
+ @group(0) @binding(0) var<storage, read> groupKeys: array<u32>;
7973
+ @group(0) @binding(1) var<storage, read> inputValues: array<f32>;
7974
+ ${maskBinding}
7975
+ @group(0) @binding(${outputBinding}) var<storage, read_write> outputValues: array<atomic<u32>>;
7976
+ ${countsBinding}
7977
+
7978
+ ${getFloatAggregationFunction(props.operation)}
7979
+ ${useSubgroups ? getSubgroupBallotHelpersWGSL() : ""}
7980
+
7981
+ @compute @workgroup_size(${GROUP_AGGREGATION_WORKGROUP_SIZE}) fn main(
7982
+ @builtin(workgroup_id) workgroupId: vec3<u32>,
7983
+ @builtin(local_invocation_id) localId: vec3<u32>${useSubgroups ? ",\n @builtin(subgroup_invocation_id) subgroupInvocationId: u32" : ""}
7984
+ ) {
7985
+ let workgroupIndex = (workgroupId.z * ${props.dispatchLayout.y}u + workgroupId.y) * ${props.dispatchLayout.x}u + workgroupId.x;
7986
+ let index = workgroupIndex * ${GROUP_AGGREGATION_WORKGROUP_SIZE}u + localId.x;
7987
+ var accepted = false;
7988
+ var groupIndex = 0u;
7989
+ var value = 0.0;
7990
+ if (index < ELEMENT_COUNT && ${maskCondition}) {
7991
+ groupIndex = groupKeys[KEYS_OFFSET + index * KEYS_STRIDE];
7992
+ value = inputValues[VALUES_OFFSET + index * VALUES_STRIDE];
7993
+ let finiteValue = value == value && abs(value) <= 3.402823466e+38;
7994
+ accepted = groupIndex < GROUP_COUNT && finiteValue;
7995
+ }
7996
+ ${accumulation}
7997
+ }`
7998
+ );
7999
+ const resources = [
8000
+ { buffer: props.keys, usage: "storage-read" },
8001
+ { buffer: props.values, usage: "storage-read" },
8002
+ ...props.mask ? [{ buffer: props.mask, usage: "storage-read" }] : [],
8003
+ { buffer: props.output, usage: "storage-read-write" },
8004
+ ...props.counts ? [{ buffer: props.counts, usage: "storage-read-write" }] : []
8005
+ ];
8006
+ nodes.push(
8007
+ ...addKernelPass(graph, {
8008
+ id: `${props.id}-${props.operation}`,
8009
+ source,
8010
+ resources,
8011
+ bindings: {
8012
+ groupKeys: props.keys,
8013
+ inputValues: props.values,
8014
+ ...props.mask ? { selectionMask: props.mask } : {},
8015
+ outputValues: props.output,
8016
+ ...props.counts ? { outputCounts: props.counts } : {}
8017
+ },
8018
+ dispatchSize: props.dispatchLayout
8019
+ })
8020
+ );
8021
+ return nodes;
8022
+ }
8023
+ function addFinalizeGroupStatisticsPass(graph, id, output, operation, counts) {
8024
+ const nodes = [];
8025
+ const dispatchLayout = getGPUGroupAggregationDispatchLayout(
8026
+ output.length,
8027
+ graph.device.limits.maxComputeWorkgroupsPerDimension
8028
+ );
8029
+ const countBinding = counts ? "@group(0) @binding(1) var<storage, read> outputCounts: array<u32>;" : "";
8030
+ const finalizeStatement = operation === "mean" ? `let count = outputCounts[${getViewElementOffset(counts)}u + index];
8031
+ if (count == 0u) {
8032
+ outputValues[OUTPUT_OFFSET + index] = 0x7fc00000u;
8033
+ } else {
8034
+ let sum = bitcast<f32>(outputValues[OUTPUT_OFFSET + index]);
8035
+ outputValues[OUTPUT_OFFSET + index] = bitcast<u32>(sum / f32(count));
8036
+ }` : `let orderedValue = outputValues[OUTPUT_OFFSET + index];
8037
+ if (orderedValue == ${operation === "min" ? "0xffffffffu" : "0u"}) {
8038
+ outputValues[OUTPUT_OFFSET + index] = 0x7fc00000u;
8039
+ } else {
8040
+ outputValues[OUTPUT_OFFSET + index] = bitcast<u32>(decodeOrderedFloat(orderedValue));
8041
+ }`;
8042
+ const decodeFunction = operation === "mean" ? "" : `fn decodeOrderedFloat(value: u32) -> f32 {
8043
+ let bits = select(~value, value ^ 0x80000000u, (value & 0x80000000u) != 0u);
8044
+ return bitcast<f32>(bits);
8045
+ }`;
8046
+ const source = (
8047
+ /* wgsl */
8048
+ `
8049
+ const GROUP_COUNT: u32 = ${output.length}u;
8050
+ const OUTPUT_OFFSET: u32 = ${getViewElementOffset(output)}u;
8051
+ @group(0) @binding(0) var<storage, read_write> outputValues: array<u32>;
8052
+ ${countBinding}
8053
+ ${decodeFunction}
8054
+ @compute @workgroup_size(${GROUP_AGGREGATION_WORKGROUP_SIZE}) fn main(
8055
+ @builtin(local_invocation_index) localInvocationIndex: u32,
8056
+ @builtin(workgroup_id) workgroupId: vec3<u32>
8057
+ ) {
8058
+ ${getBoundedInvocationIndexSource(dispatchLayout, GROUP_AGGREGATION_WORKGROUP_SIZE)}
8059
+ if (index < GROUP_COUNT) {
8060
+ ${finalizeStatement}
8061
+ }
8062
+ }`
8063
+ );
8064
+ nodes.push(
8065
+ ...addKernelPass(graph, {
8066
+ id: `${id}-finalize`,
8067
+ source,
8068
+ resources: [
8069
+ { buffer: output, usage: "storage-read-write" },
8070
+ ...counts ? [{ buffer: counts, usage: "storage-read" }] : []
8071
+ ],
8072
+ bindings: { outputValues: output, ...counts ? { outputCounts: counts } : {} },
8073
+ dispatchSize: dispatchLayout
8074
+ })
8075
+ );
8076
+ return nodes;
8077
+ }
8078
+ function getFloatAggregationFunction(operation) {
8079
+ if (operation === "min" || operation === "max") {
8080
+ return `fn encodeOrderedFloat(value: f32) -> u32 {
8081
+ let bits = bitcast<u32>(value);
8082
+ return select(bits ^ 0x80000000u, ~bits, (bits & 0x80000000u) != 0u);
8083
+ }`;
8084
+ }
8085
+ return `fn atomicAddFloat(destination: ptr<storage, atomic<u32>, read_write>, value: f32) {
8086
+ var oldBits = atomicLoad(destination);
8087
+ loop {
8088
+ let newBits = bitcast<u32>(bitcast<f32>(oldBits) + value);
8089
+ let result = atomicCompareExchangeWeak(destination, oldBits, newBits);
8090
+ if (result.exchanged) { break; }
8091
+ oldBits = result.old_value;
8092
+ }
8093
+ }`;
8094
+ }
8095
+ function getFloatAggregationCall(operation, groupIndex, valueExpression = "value") {
8096
+ if (operation === "min" || operation === "max") {
8097
+ const atomicOperation = operation === "min" ? "atomicMin" : "atomicMax";
8098
+ return `${atomicOperation}(&outputValues[OUTPUT_OFFSET + ${groupIndex}], encodeOrderedFloat(${valueExpression}));`;
8099
+ }
8100
+ return `atomicAddFloat(&outputValues[OUTPUT_OFFSET + ${groupIndex}], ${valueExpression});`;
8101
+ }
8102
+ function getSubgroupStatisticAggregationWGSL(operation, groupCount, counts) {
8103
+ const orderedOperation = operation === "min" || operation === "max";
8104
+ const selectedValue = orderedOperation ? `select(${operation === "min" ? "0xffffffffu" : "0u"}, encodeOrderedFloat(value), matchingKey)` : "select(0.0, value, matchingKey)";
8105
+ const collective = operation === "min" ? "subgroupMin(selectedValue)" : operation === "max" ? "subgroupMax(selectedValue)" : "subgroupAdd(selectedValue)";
8106
+ const aggregationCall = orderedOperation ? `${operation === "min" ? "atomicMin" : "atomicMax"}(&outputValues[OUTPUT_OFFSET + leaderKey], aggregatedValue);` : getFloatAggregationCall(operation, "leaderKey", "aggregatedValue");
8107
+ return (
8108
+ /* wgsl */
8109
+ `
8110
+ var subgroupPending = accepted;
8111
+ for (var subgroupGroup = 0u; subgroupGroup < ${groupCount}u; subgroupGroup++) {
8112
+ let pendingBallot = subgroupBallot(subgroupPending);
8113
+ let hasPending = any(pendingBallot != vec4<u32>(0u));
8114
+ let leaderInvocation = getFirstBallotLane(pendingBallot);
8115
+ let leaderKey = subgroupShuffle(groupIndex, leaderInvocation);
8116
+ let matchingKey = hasPending && subgroupPending && groupIndex == leaderKey;
8117
+ let matchingBallot = subgroupBallot(matchingKey);
8118
+ let selectedValue = ${selectedValue};
8119
+ let aggregatedValue = ${collective};
8120
+ if (hasPending && subgroupInvocationId == leaderInvocation) {
8121
+ ${aggregationCall}
8122
+ ${counts ? `atomicAdd(&outputCounts[${getViewElementOffset(counts)}u + leaderKey], getBallotLaneCount(matchingBallot));` : ""}
8123
+ }
8124
+ subgroupPending = subgroupPending && !matchingKey;
8125
+ }`
8126
+ );
8127
+ }
8128
+ function getGPUGroupAggregationDispatchLayout(elementCount, maxComputeWorkgroupsPerDimension) {
8129
+ return getBoundedDispatchLayout(
8130
+ "GPUGroupAggregation",
8131
+ elementCount,
8132
+ GROUP_AGGREGATION_WORKGROUP_SIZE,
8133
+ maxComputeWorkgroupsPerDimension
8134
+ );
8135
+ }
8136
+ function addKernelPass(graph, props) {
8137
+ const { x, y, z } = props.dispatchSize ?? { x: props.dispatchCount ?? 1, y: 1, z: 1 };
8138
+ const maximumWorkgroupCount = x * y * z;
8139
+ const node = createGPUComputeCommandNode({
8140
+ id: props.id,
8141
+ resources: props.resources,
8142
+ workload: {
8143
+ operation: "GPUGroupAggregation",
8144
+ commandCount: 1,
8145
+ maximumWorkgroupCount,
8146
+ maximumInvocationCount: maximumWorkgroupCount * GROUP_AGGREGATION_WORKGROUP_SIZE
8147
+ },
8148
+ compile: ({ device }) => {
8149
+ const kernel = new Kernel(device, {
8150
+ id: props.id,
8151
+ source: props.source,
8152
+ shaderLayout: {
8153
+ bindings: Object.keys(props.bindings).map((name, location) => ({
8154
+ name,
8155
+ type: "storage",
8156
+ group: 0,
8157
+ location
8158
+ }))
8159
+ }
8160
+ });
8161
+ return {
8162
+ encode: ({ computePass, getBuffer }) => {
8163
+ const bindings = {};
8164
+ for (const [name, view] of Object.entries(props.bindings)) {
8165
+ bindings[name] = getViewBinding(view, getBuffer);
8166
+ }
8167
+ kernel.dispatch(computePass, { bindings, x, y, z });
8168
+ },
8169
+ destroy: () => kernel.destroy()
8170
+ };
8171
+ }
8172
+ });
8173
+ return [setGPUComputeDispatchWorkgroups(node, [x, y, z])];
8174
+ }
8175
+
8176
+ // src/gpu-core/gpu-reduction.ts
8177
+ var REDUCTION_WORKGROUP_SIZE = 256;
8178
+ var SCALAR_FORMATS = ["uint32", "sint32", "float32"];
8179
+ function getGPUReductionStrategy(device) {
8180
+ return getGPUShaderSubgroupStrategy(device, { requiresSubgroupId: true });
8181
+ }
8182
+ var GPUReduction = class {
8183
+ /** Prefix for generated graph node and transient resource IDs. */
8184
+ id;
8185
+ /** Scalar input chunk or vector. */
8186
+ input;
8187
+ /** Optional source-aligned row selection. */
8188
+ mask;
8189
+ /** Caller-owned result view. */
8190
+ output;
8191
+ /** Aggregate computed by this reduction. */
8192
+ operation;
8193
+ /**
8194
+ * Creates and validates a graph-native reduction description.
8195
+ *
8196
+ * @throws If views are not packed 32-bit scalar data, formats differ, the output has the wrong
8197
+ * length, or input and output use the same physical graph buffer.
8198
+ */
8199
+ constructor(props) {
8200
+ this.id = props.id ?? "gpu-reduction";
8201
+ this.input = props.input;
8202
+ this.mask = props.mask;
8203
+ this.output = props.output;
8204
+ this.operation = props.operation;
8205
+ for (const [chunkIndex, input] of getReductionInputs(this.input).entries()) {
8206
+ const name = this.input instanceof GraphVectorView ? ` input chunk ${chunkIndex}` : " input";
8207
+ validatePackedView(input, SCALAR_FORMATS, `${this.id}${name}`);
8208
+ if (input.format !== this.input.format) {
8209
+ throw new Error(`${this.id}${name} format must match the input format`);
8210
+ }
8211
+ }
8212
+ validatePackedView(this.output, SCALAR_FORMATS, `${this.id} output`);
8213
+ if (this.input.format !== this.output.format) {
8214
+ throw new Error(`${this.id} input and output formats must match`);
8215
+ }
8216
+ if (!["sum", "min", "max", "extent"].includes(this.operation)) {
8217
+ throw new Error(`${this.id} operation must be sum, min, max, or extent`);
8218
+ }
8219
+ const outputLength = this.operation === "extent" ? 2 : 1;
8220
+ if (this.output.length !== outputLength) {
8221
+ throw new Error(`${this.id} ${this.operation} output must contain ${outputLength} row(s)`);
8222
+ }
8223
+ if (getReductionInputs(this.input).some((input) => input.buffer === this.output.buffer)) {
8224
+ throw new Error(`${this.id} inputs and output must use separate buffers`);
8225
+ }
8226
+ if (this.mask) {
8227
+ for (const [chunkIndex, mask] of getReductionMasks(this.mask).entries()) {
8228
+ validatePackedUint32View(mask, `${this.id} mask chunk ${chunkIndex}`);
8229
+ if (mask.buffer === this.output.buffer) {
8230
+ throw new Error(`${this.id} mask and output must use separate buffers`);
8231
+ }
8232
+ }
8233
+ if (this.input.length !== this.mask.length) {
8234
+ throw new Error(`${this.id} input and mask lengths must match`);
8235
+ }
8236
+ }
8237
+ }
8238
+ /**
8239
+ * Adds hierarchical reduction passes and graph-owned scratch to a command graph.
8240
+ *
8241
+ * Empty inputs add a one-thread clear pass. A single non-empty chunk is reduced directly.
8242
+ * Multiple non-empty chunks are reduced independently, then their partial rows are merged. A
8243
+ * final pass converts an invalid floating-point min/max/extent result to zero and writes the
8244
+ * caller-owned output.
8245
+ *
8246
+ * @param graph Mutable graph that owns all input/output handles and generated scratch.
8247
+ */
8248
+ getCommandNodes(graph) {
8249
+ const nodes = [];
8250
+ let inputs = getReductionInputs(this.input);
8251
+ let masks = this.mask ? getReductionMasks(this.mask) : void 0;
8252
+ if (inputs.some((input) => input.buffer.graph !== graph) || masks?.some((mask) => mask.buffer.graph !== graph) || this.output.buffer.graph !== graph) {
8253
+ throw new Error(`${this.id} views must belong to the target graph`);
8254
+ }
8255
+ if (this.mask) {
8256
+ const spans = alignGraphVectorViews(graph, [this.input, this.mask]);
8257
+ inputs = spans.map(([input]) => input);
8258
+ masks = spans.map(([, mask]) => mask);
8259
+ }
8260
+ const nonEmptyInputs = inputs.map((input, chunkIndex) => ({ input, mask: masks?.[chunkIndex] })).filter(({ input }) => input.length > 0);
8261
+ if (nonEmptyInputs.length === 0) {
8262
+ nodes.push(...addClearReductionPass(graph, this.id, this.output));
8263
+ return nodes;
8264
+ }
8265
+ const valuesPerRow = this.operation === "extent" ? 2 : 1;
8266
+ const needsValidity = this.operation !== "sum" && (this.input.format === "float32" || Boolean(this.mask));
8267
+ let reductionResult;
8268
+ if (nonEmptyInputs.length === 1) {
8269
+ reductionResult = addReductionLevels(graph, {
8270
+ id: this.id,
8271
+ format: this.input.format,
8272
+ operation: this.operation,
8273
+ inputValues: nonEmptyInputs[0].input,
8274
+ inputValidity: nonEmptyInputs[0].mask,
8275
+ inputLength: nonEmptyInputs[0].input.length,
8276
+ valuesPerRow,
8277
+ firstLevel: true,
8278
+ needsValidity
8279
+ });
8280
+ nodes.push(...reductionResult.nodes);
8281
+ } else {
8282
+ const partialValues = createTransientView(
8283
+ graph,
8284
+ `${this.id}-chunk-values`,
8285
+ this.input.format,
8286
+ nonEmptyInputs.length * valuesPerRow
8287
+ );
8288
+ const partialValidity = needsValidity ? createTransientView(graph, `${this.id}-chunk-validity`, "uint32", nonEmptyInputs.length) : void 0;
8289
+ nonEmptyInputs.forEach(({ input, mask }, partialIndex) => {
8290
+ nodes.push(
8291
+ ...addReductionLevels(graph, {
8292
+ id: `${this.id}-chunk-${partialIndex}`,
8293
+ format: this.input.format,
8294
+ operation: this.operation,
8295
+ inputValues: input,
8296
+ inputValidity: mask,
8297
+ inputLength: input.length,
8298
+ valuesPerRow,
8299
+ firstLevel: true,
8300
+ needsValidity,
8301
+ finalValues: createPackedSubview(
8302
+ graph,
8303
+ partialValues,
8304
+ partialIndex * valuesPerRow,
8305
+ valuesPerRow
8306
+ ),
8307
+ finalValidity: partialValidity ? createPackedSubview(graph, partialValidity, partialIndex, 1) : void 0
8308
+ }).nodes
8309
+ );
8310
+ });
8311
+ reductionResult = addReductionLevels(graph, {
8312
+ id: `${this.id}-merge`,
8313
+ format: this.input.format,
8314
+ operation: this.operation,
8315
+ inputValues: partialValues,
8316
+ inputValidity: partialValidity,
8317
+ inputLength: nonEmptyInputs.length,
8318
+ valuesPerRow,
8319
+ firstLevel: false,
8320
+ needsValidity
8321
+ });
8322
+ nodes.push(...reductionResult.nodes);
8323
+ }
8324
+ nodes.push(
8325
+ ...addFinalizeReductionPass(graph, {
8326
+ id: `${this.id}-finalize`,
8327
+ format: this.input.format,
8328
+ inputValues: reductionResult.values,
8329
+ inputValidity: reductionResult.validity,
8330
+ output: this.output,
8331
+ valuesPerRow
8332
+ })
8333
+ );
8334
+ return nodes;
8335
+ }
8336
+ };
8337
+ function addReductionLevels(graph, props) {
8338
+ const nodes = [];
8339
+ let currentValues = props.inputValues;
8340
+ let currentValidity = props.inputValidity;
8341
+ let currentLength = props.inputLength;
8342
+ let levelIndex = 0;
8343
+ while (currentLength > 1 || levelIndex === 0) {
8344
+ const nextLength = Math.ceil(currentLength / REDUCTION_WORKGROUP_SIZE);
8345
+ const isLastLevel = nextLength === 1;
8346
+ const nextValues = isLastLevel && props.finalValues ? props.finalValues : createTransientView(
8347
+ graph,
8348
+ `${props.id}-level-${levelIndex}-values`,
8349
+ props.format,
8350
+ nextLength * props.valuesPerRow
8351
+ );
8352
+ const nextValidity = props.needsValidity ? isLastLevel && props.finalValidity ? props.finalValidity : createTransientView(
8353
+ graph,
8354
+ `${props.id}-level-${levelIndex}-validity`,
8355
+ "uint32",
8356
+ nextLength
8357
+ ) : void 0;
8358
+ nodes.push(
8359
+ ...addReductionLevelPass(graph, {
8360
+ id: `${props.id}-level-${levelIndex}`,
8361
+ format: props.format,
8362
+ operation: props.operation,
8363
+ inputValues: currentValues,
8364
+ inputValidity: currentValidity,
8365
+ outputValues: nextValues,
8366
+ outputValidity: nextValidity,
8367
+ inputLength: currentLength,
8368
+ valuesPerRow: props.valuesPerRow,
8369
+ firstLevel: props.firstLevel && levelIndex === 0
8370
+ })
8371
+ );
8372
+ currentValues = nextValues;
8373
+ currentValidity = nextValidity;
8374
+ currentLength = nextLength;
8375
+ levelIndex++;
8376
+ }
8377
+ return { values: currentValues, validity: currentValidity, nodes };
8378
+ }
8379
+ function createPackedSubview(graph, view, elementOffset, length) {
8380
+ return graph.createDataView(view.buffer, {
8381
+ format: view.format,
8382
+ length,
8383
+ byteOffset: view.byteOffset + elementOffset * view.rowByteLength
8384
+ });
8385
+ }
8386
+ function getReductionInputs(input) {
8387
+ return input instanceof GraphVectorView ? input.data : [input];
8388
+ }
8389
+ function getReductionMasks(mask) {
8390
+ return mask instanceof GraphVectorView ? mask.data : [mask];
8391
+ }
8392
+ function addReductionLevelPass(graph, props) {
8393
+ const nodes = [];
8394
+ const dispatchLayout = getBoundedDispatchLayout(
8395
+ "GPUReduction",
8396
+ props.inputLength,
8397
+ REDUCTION_WORKGROUP_SIZE,
8398
+ graph.device.limits.maxComputeWorkgroupsPerDimension
8399
+ );
8400
+ const shaderType = getShaderType(props.format);
8401
+ const zero = getZeroLiteral(props.format);
8402
+ const isSum = props.operation === "sum";
8403
+ const isExtent = props.operation === "extent";
8404
+ const validityBinding = props.inputValidity ? "@group(0) @binding(1) var<storage, read> inputValidity: array<u32>;" : "";
8405
+ const outputValuesBinding = props.inputValidity ? 2 : 1;
8406
+ const outputValidityBinding = outputValuesBinding + 1;
8407
+ const finiteExpression = props.format === "float32" ? "value == value && abs(value) <= 3.402823466e+38" : "true";
8408
+ const normalizeMaskedFloatSum = props.firstLevel && props.inputValidity && props.format === "float32" && isSum ? "\n if (valid == 0u) { value = 0.0; secondValue = 0.0; }" : "";
8409
+ const readRawValue = `value = inputValues[INPUT_OFFSET + index];
8410
+ secondValue = value;
8411
+ valid = select(0u, 1u, ${finiteExpression});${normalizeMaskedFloatSum}`;
8412
+ const readFirst = props.firstLevel ? props.inputValidity ? `if (inputValidity[VALIDITY_OFFSET + index] != 0u) {
8413
+ ${readRawValue}
8414
+ }` : readRawValue : `value = inputValues[INPUT_OFFSET + index * VALUES_PER_ROW];
8415
+ secondValue = inputValues[INPUT_OFFSET + index * VALUES_PER_ROW + ${isExtent ? "1u" : "0u"}];
8416
+ ${props.inputValidity ? "valid = inputValidity[VALIDITY_OFFSET + index];" : "valid = 1u;"}`;
8417
+ const combine = isSum ? "firstScratch[lane] = firstScratch[lane] + firstScratch[lane + stride];" : `let rightValid = validityScratch[lane + stride];
8418
+ if (rightValid != 0u) {
8419
+ if (validityScratch[lane] == 0u) {
8420
+ firstScratch[lane] = firstScratch[lane + stride];
8421
+ secondScratch[lane] = secondScratch[lane + stride];
8422
+ } else {
8423
+ firstScratch[lane] = ${props.operation === "max" ? "max" : "min"}(firstScratch[lane], firstScratch[lane + stride]);
8424
+ secondScratch[lane] = ${isExtent ? "max" : props.operation === "max" ? "max" : "min"}(secondScratch[lane], secondScratch[lane + stride]);
8425
+ }
8426
+ validityScratch[lane] = 1u;
8427
+ }`;
8428
+ const strategy = getGPUReductionStrategy(graph.device);
8429
+ const reductionSource = strategy === "subgroups" ? getSubgroupReductionSource({
8430
+ format: props.format,
8431
+ operation: props.operation,
8432
+ combine
8433
+ }) : getPortableReductionSource(combine);
8434
+ const source = (
8435
+ /* wgsl */
8436
+ `
8437
+ ${strategy === "subgroups" ? "enable subgroups;\nrequires subgroup_id;" : ""}
8438
+ const ELEMENT_COUNT: u32 = ${props.inputLength}u;
8439
+ const VALUES_PER_ROW: u32 = ${props.valuesPerRow}u;
8440
+ const INPUT_OFFSET: u32 = ${getViewElementOffset(props.inputValues)}u;
8441
+ ${props.inputValidity ? `const VALIDITY_OFFSET: u32 = ${getViewElementOffset(props.inputValidity)}u;` : ""}
8442
+ const OUTPUT_OFFSET: u32 = ${getViewElementOffset(props.outputValues)}u;
8443
+ ${props.outputValidity ? `const OUTPUT_VALIDITY_OFFSET: u32 = ${getViewElementOffset(props.outputValidity)}u;` : ""}
8444
+ @group(0) @binding(0) var<storage, read> inputValues: array<${shaderType}>;
8445
+ ${validityBinding}
8446
+ @group(0) @binding(${outputValuesBinding}) var<storage, read_write> outputValues: array<${shaderType}>;
8447
+ ${props.outputValidity ? `@group(0) @binding(${outputValidityBinding}) var<storage, read_write> outputValidity: array<u32>;` : ""}
8448
+ var<workgroup> firstScratch: array<${shaderType}, ${REDUCTION_WORKGROUP_SIZE}>;
8449
+ var<workgroup> secondScratch: array<${shaderType}, ${REDUCTION_WORKGROUP_SIZE}>;
8450
+ var<workgroup> validityScratch: array<u32, ${REDUCTION_WORKGROUP_SIZE}>;
8451
+
8452
+ @compute @workgroup_size(${REDUCTION_WORKGROUP_SIZE}) fn main(
8453
+ @builtin(local_invocation_index) localInvocationIndex: u32,
8454
+ ${strategy === "subgroups" ? "@builtin(subgroup_invocation_id) subgroupInvocationId: u32,\n @builtin(subgroup_size) subgroupSize: u32,\n @builtin(subgroup_id) subgroupId: u32," : ""}
8455
+ @builtin(workgroup_id) workgroupId: vec3<u32>
8456
+ ) {
8457
+ ${getBoundedInvocationIndexSource(dispatchLayout, REDUCTION_WORKGROUP_SIZE)}
8458
+ if (workgroupIndex >= ${Math.ceil(props.inputLength / REDUCTION_WORKGROUP_SIZE)}u) {
8459
+ return;
8460
+ }
8461
+ let lane = localInvocationIndex;
8462
+ var value = ${zero};
8463
+ var secondValue = ${zero};
8464
+ var valid = 0u;
8465
+ if (index < ELEMENT_COUNT) {
8466
+ ${readFirst}
8467
+ }
8468
+ ${reductionSource}
8469
+ if (lane == 0u) {
8470
+ outputValues[OUTPUT_OFFSET + workgroupIndex * VALUES_PER_ROW] = firstScratch[0];
8471
+ ${isExtent ? "outputValues[OUTPUT_OFFSET + workgroupIndex * VALUES_PER_ROW + 1u] = secondScratch[0];" : ""}
8472
+ ${props.outputValidity ? "outputValidity[OUTPUT_VALIDITY_OFFSET + workgroupIndex] = validityScratch[0];" : ""}
8473
+ }
8474
+ }`
8475
+ );
8476
+ const resources = [
8477
+ { buffer: props.inputValues, usage: "storage-read" },
8478
+ ...props.inputValidity ? [{ buffer: props.inputValidity, usage: "storage-read" }] : [],
8479
+ { buffer: props.outputValues, usage: "storage-write" },
8480
+ ...props.outputValidity ? [{ buffer: props.outputValidity, usage: "storage-write" }] : []
8481
+ ];
8482
+ const bindings = { inputValues: props.inputValues };
8483
+ if (props.inputValidity) bindings["inputValidity"] = props.inputValidity;
8484
+ bindings["outputValues"] = props.outputValues;
8485
+ if (props.outputValidity) bindings["outputValidity"] = props.outputValidity;
8486
+ nodes.push(
8487
+ ...addKernelPass2(graph, {
8488
+ id: props.id,
8489
+ source,
8490
+ resources,
8491
+ bindings,
8492
+ dispatchLayout
8493
+ })
8494
+ );
8495
+ return nodes;
8496
+ }
8497
+ function getPortableReductionSource(combine) {
8498
+ return `firstScratch[lane] = value;
8499
+ secondScratch[lane] = secondValue;
8500
+ validityScratch[lane] = valid;
8501
+ workgroupBarrier();
8502
+ var stride = ${REDUCTION_WORKGROUP_SIZE / 2}u;
8503
+ loop {
8504
+ if (lane < stride) {
8505
+ ${combine}
8506
+ }
8507
+ workgroupBarrier();
8508
+ if (stride == 1u) { break; }
8509
+ stride = stride / 2u;
8510
+ }`;
8511
+ }
8512
+ function getSubgroupReductionSource(props) {
8513
+ const firstCollective = getSubgroupCollective(
8514
+ props.format,
8515
+ props.operation === "extent" ? "min" : props.operation,
8516
+ "value",
8517
+ "valid"
8518
+ );
8519
+ const secondCollective = getSubgroupCollective(
8520
+ props.format,
8521
+ props.operation === "extent" ? "max" : props.operation,
8522
+ "secondValue",
8523
+ "valid"
8524
+ );
8525
+ return `let subgroupValid = subgroupMax(valid);
8526
+ let subgroupFirst = ${firstCollective};
8527
+ let subgroupSecond = ${secondCollective};
8528
+ if (subgroupInvocationId == 0u) {
8529
+ firstScratch[subgroupId] = subgroupFirst;
8530
+ secondScratch[subgroupId] = subgroupSecond;
8531
+ validityScratch[subgroupId] = subgroupValid;
8532
+ }
8533
+ workgroupBarrier();
8534
+ let subgroupCount = ${REDUCTION_WORKGROUP_SIZE}u / subgroupSize;
8535
+ if (subgroupCount > 1u) {
8536
+ var stride = subgroupCount / 2u;
8537
+ loop {
8538
+ if (lane < stride) {
8539
+ ${props.combine}
8540
+ }
8541
+ workgroupBarrier();
8542
+ if (stride == 1u) { break; }
8543
+ stride = stride / 2u;
8544
+ }
8545
+ }`;
8546
+ }
8547
+ function getSubgroupCollective(format, operation, value, validity) {
8548
+ if (operation === "sum") {
8549
+ return `subgroupAdd(${value})`;
8550
+ }
8551
+ const identity = getReductionIdentity(format, operation);
8552
+ const collective = operation === "min" ? "subgroupMin" : "subgroupMax";
8553
+ return `${collective}(select(${identity}, ${value}, ${validity} != 0u))`;
8554
+ }
8555
+ function getReductionIdentity(format, operation) {
8556
+ if (format === "uint32") {
8557
+ return operation === "min" ? "4294967295u" : "0u";
8558
+ }
8559
+ if (format === "sint32") {
8560
+ return operation === "min" ? "2147483647" : "(-2147483647 - 1)";
8561
+ }
8562
+ return operation === "min" ? "3.402823466e+38" : "-3.402823466e+38";
8563
+ }
8564
+ function addFinalizeReductionPass(graph, props) {
8565
+ const nodes = [];
8566
+ const shaderType = getShaderType(props.format);
8567
+ const zero = getZeroLiteral(props.format);
8568
+ const outputLines = Array.from({ length: props.valuesPerRow }, (_, index) => {
8569
+ const value = `inputValues[INPUT_OFFSET + ${index}u]`;
8570
+ return `outputValues[OUTPUT_OFFSET + ${index}u] = ${props.inputValidity ? `select(${zero}, ${value}, valid)` : value};`;
8571
+ }).join("\n ");
8572
+ const source = (
8573
+ /* wgsl */
8574
+ `
8575
+ const INPUT_OFFSET: u32 = ${getViewElementOffset(props.inputValues)}u;
8576
+ const OUTPUT_OFFSET: u32 = ${getViewElementOffset(props.output)}u;
8577
+ ${props.inputValidity ? `const VALIDITY_OFFSET: u32 = ${getViewElementOffset(props.inputValidity)}u;` : ""}
8578
+ @group(0) @binding(0) var<storage, read> inputValues: array<${shaderType}>;
8579
+ ${props.inputValidity ? "@group(0) @binding(1) var<storage, read> inputValidity: array<u32>;" : ""}
8580
+ @group(0) @binding(${props.inputValidity ? 2 : 1}) var<storage, read_write> outputValues: array<${shaderType}>;
8581
+ @compute @workgroup_size(1) fn main() {
8582
+ ${props.inputValidity ? "let valid = inputValidity[VALIDITY_OFFSET] != 0u;" : ""}
8583
+ ${outputLines}
8584
+ }`
8585
+ );
8586
+ nodes.push(
8587
+ ...addKernelPass2(graph, {
8588
+ id: props.id,
8589
+ source,
8590
+ resources: [
8591
+ { buffer: props.inputValues, usage: "storage-read" },
8592
+ ...props.inputValidity ? [{ buffer: props.inputValidity, usage: "storage-read" }] : [],
8593
+ { buffer: props.output, usage: "storage-write" }
8594
+ ],
8595
+ bindings: {
8596
+ inputValues: props.inputValues,
8597
+ ...props.inputValidity ? { inputValidity: props.inputValidity } : {},
8598
+ outputValues: props.output
8599
+ },
8600
+ dispatchCount: 1
8601
+ })
8602
+ );
8603
+ return nodes;
8604
+ }
8605
+ function addClearReductionPass(graph, id, output) {
8606
+ const nodes = [];
8607
+ const passId = `${id}-clear`;
8608
+ const shaderType = getShaderType(output.format);
8609
+ const zero = getZeroLiteral(output.format);
8610
+ nodes.push(
8611
+ ...addKernelPass2(graph, {
8612
+ id: passId,
8613
+ source: `const OUTPUT_OFFSET: u32 = ${getViewElementOffset(output)}u;
8614
+ @group(0) @binding(0) var<storage, read_write> outputValues: array<${shaderType}>;
8615
+ @compute @workgroup_size(1) fn main() {
8616
+ for (var index = 0u; index < ${output.length}u; index++) { outputValues[OUTPUT_OFFSET + index] = ${zero}; }
8617
+ }`,
8618
+ resources: [{ buffer: output, usage: "storage-write" }],
8619
+ bindings: { outputValues: output },
8620
+ dispatchCount: 1
8621
+ })
8622
+ );
8623
+ return nodes;
8624
+ }
8625
+ function addKernelPass2(graph, props) {
8626
+ const { x, y, z } = props.dispatchLayout ?? { x: props.dispatchCount ?? 1, y: 1, z: 1 };
8627
+ const node = createGPUComputeCommandNode({
8628
+ id: props.id,
8629
+ resources: props.resources,
8630
+ compile: ({ device }) => {
8631
+ const bindingNames = Object.keys(props.bindings);
8632
+ const kernel = new Kernel(device, {
8633
+ id: props.id,
8634
+ source: props.source,
8635
+ shaderLayout: {
8636
+ bindings: bindingNames.map((name, location) => ({
8637
+ name,
8638
+ type: "storage",
8639
+ group: 0,
8640
+ location
8641
+ }))
8642
+ }
8643
+ });
8644
+ return {
8645
+ encode: ({ computePass, getBuffer }) => {
8646
+ const bindings = {};
8647
+ for (const [name, view] of Object.entries(props.bindings)) {
8648
+ bindings[name] = getViewBinding(view, getBuffer);
8649
+ }
8650
+ kernel.dispatch(computePass, { bindings, x, y, z });
8651
+ },
8652
+ destroy: () => kernel.destroy()
8653
+ };
8654
+ }
8655
+ });
8656
+ return [setGPUComputeDispatchWorkgroups(node, [x, y, z])];
8657
+ }
8658
+ function getShaderType(format) {
8659
+ return format === "uint32" ? "u32" : format === "sint32" ? "i32" : "f32";
8660
+ }
8661
+ function getZeroLiteral(format) {
8662
+ return format === "uint32" ? "0u" : format === "sint32" ? "0" : "0.0";
8663
+ }
8664
+
8665
+ // src/gpu-core/gpu-scan.ts
8666
+ var SCAN_WORKGROUP_SIZE = 256;
8667
+ var MAXIMUM_SCAN_SUBGROUP_COUNT = 64;
8668
+ function getGPUScanStrategy(device, segmented = false) {
8669
+ return segmented ? "portable" : getGPUShaderSubgroupStrategy(device, { requiresSubgroupId: true });
8670
+ }
8671
+ var GPUScan = class {
7481
8672
  /** Prefix for generated graph node and transient resource IDs. */
7482
8673
  id;
7483
8674
  /** Packed unsigned source data or ordered source vector. */
@@ -7635,8 +8826,8 @@ var __exports__ = (() => {
7635
8826
  mode: props.mode,
7636
8827
  segmentFlags: chunk.segmentFlags,
7637
8828
  outputSegmentPrefixes: chunkSegmentPrefixes?.[partialIndex],
7638
- finalSum: createPackedSubview(graph, chunkTotals, partialIndex),
7639
- finalSegmentFlag: chunkSegmentFlags ? createPackedSubview(graph, chunkSegmentFlags, partialIndex) : void 0,
8829
+ finalSum: createPackedSubview2(graph, chunkTotals, partialIndex),
8830
+ finalSegmentFlag: chunkSegmentFlags ? createPackedSubview2(graph, chunkSegmentFlags, partialIndex) : void 0,
7640
8831
  maxComputeWorkgroupsPerDimension
7641
8832
  })
7642
8833
  );
@@ -7765,7 +8956,7 @@ var __exports__ = (() => {
7765
8956
  }
7766
8957
  return nodes;
7767
8958
  }
7768
- function createPackedSubview(graph, view, index) {
8959
+ function createPackedSubview2(graph, view, index) {
7769
8960
  return graph.createDataView(view.buffer, {
7770
8961
  format: "uint32",
7771
8962
  length: 1,
@@ -8667,6 +9858,16 @@ ${countBinding}
8667
9858
  const arena = getGPUValueArena(graph);
8668
9859
  return new GPUScalar(arena, arena.allocate(id, format));
8669
9860
  }
9861
+ function getGPUScalarWGSLType(format) {
9862
+ switch (format) {
9863
+ case "float32":
9864
+ return "f32";
9865
+ case "uint32":
9866
+ return "u32";
9867
+ case "sint32":
9868
+ return "i32";
9869
+ }
9870
+ }
8670
9871
  function getGPUScalarWGSLLoad(scalar, arenaExpression = "gpuValues") {
8671
9872
  const word = `${arenaExpression}[${scalar.wordOffset}u]`;
8672
9873
  switch (scalar.format) {
@@ -9469,7 +10670,7 @@ fn reduceValue(value: f32, lane: u32, subgroupInvocationId: u32, subgroupSize: u
9469
10670
 
9470
10671
  // src/gpu-core/gpu-gather.ts
9471
10672
  var GATHER_WORKGROUP_SIZE = 256;
9472
- var UINT32_BYTE_LENGTH3 = Uint32Array.BYTES_PER_ELEMENT;
10673
+ var UINT32_BYTE_LENGTH4 = Uint32Array.BYTES_PER_ELEMENT;
9473
10674
  var GPUGather = class {
9474
10675
  id;
9475
10676
  source;
@@ -9501,7 +10702,7 @@ fn reduceValue(value: f32, lane: u32, subgroupInvocationId: u32, subgroupSize: u
9501
10702
  if (getGraphVectorData(this.output).some((chunk) => inputBuffers.has(chunk.buffer))) {
9502
10703
  throw new Error(`${this.id} output must use a separate buffer`);
9503
10704
  }
9504
- this.wordsPerRow = getGPUVectorFormatInfo(this.source.format).byteLength / UINT32_BYTE_LENGTH3;
10705
+ this.wordsPerRow = getGPUVectorFormatInfo(this.source.format).byteLength / UINT32_BYTE_LENGTH4;
9505
10706
  }
9506
10707
  getCommandNodes(graph) {
9507
10708
  return getGatherCommandNodes(graph, this);
@@ -9557,7 +10758,7 @@ fn reduceValue(value: f32, lane: u32, subgroupInvocationId: u32, subgroupSize: u
9557
10758
  commandCount: 1,
9558
10759
  maximumWorkgroupCount: dispatchLayout.x * dispatchLayout.y * dispatchLayout.z,
9559
10760
  maximumInvocationCount: dispatchLayout.x * dispatchLayout.y * dispatchLayout.z * GATHER_WORKGROUP_SIZE,
9560
- readByteLength: sourceView ? indices.length * (UINT32_BYTE_LENGTH3 + sourceView.rowByteLength) : 0,
10761
+ readByteLength: sourceView ? indices.length * (UINT32_BYTE_LENGTH4 + sourceView.rowByteLength) : 0,
9561
10762
  writeByteLength: indices.length * destination.rowByteLength
9562
10763
  },
9563
10764
  resources: [
@@ -9623,7 +10824,7 @@ fn reduceValue(value: f32, lane: u32, subgroupInvocationId: u32, subgroupSize: u
9623
10824
  throw new Error(`${name} must use a fixed-width GPU data format`);
9624
10825
  }
9625
10826
  const formatInfo = getGPUVectorFormatInfo(view.format);
9626
- if ((packed ? view.byteStride !== formatInfo.byteLength : view.byteStride < formatInfo.byteLength || view.byteStride % UINT32_BYTE_LENGTH3 !== 0) || view.rowByteLength !== formatInfo.byteLength || view.byteOffset % UINT32_BYTE_LENGTH3 !== 0 || view.rowByteLength % UINT32_BYTE_LENGTH3 !== 0) {
10827
+ if ((packed ? view.byteStride !== formatInfo.byteLength : view.byteStride < formatInfo.byteLength || view.byteStride % UINT32_BYTE_LENGTH4 !== 0) || view.rowByteLength !== formatInfo.byteLength || view.byteOffset % UINT32_BYTE_LENGTH4 !== 0 || view.rowByteLength % UINT32_BYTE_LENGTH4 !== 0) {
9627
10828
  throw new Error(`${name} must be packed, uint32-aligned GPU data with 32-bit-word rows`);
9628
10829
  }
9629
10830
  }
@@ -9652,7 +10853,7 @@ fn main(
9652
10853
  ${source ? `
9653
10854
  let sourceIndex = indices[INDEX_OFFSET + index];
9654
10855
  if (sourceIndex >= SOURCE_ROW_OFFSET && sourceIndex - SOURCE_ROW_OFFSET < SOURCE_LENGTH) {
9655
- let sourceBase = SOURCE_OFFSET + (sourceIndex - SOURCE_ROW_OFFSET) * ${source.byteStride / UINT32_BYTE_LENGTH3}u;
10856
+ let sourceBase = SOURCE_OFFSET + (sourceIndex - SOURCE_ROW_OFFSET) * ${source.byteStride / UINT32_BYTE_LENGTH4}u;
9656
10857
  for (var word = 0u; word < WORDS_PER_ROW; word++) {
9657
10858
  outputWords[outputBase + word] = sourceWords[sourceBase + word];
9658
10859
  }
@@ -10370,6 +11571,7 @@ ${cooperative ? `var<workgroup> scratch: array<f32, ${workgroupSize}>;` : ""}
10370
11571
  capabilities;
10371
11572
  lowerings;
10372
11573
  compactionIndex = 0;
11574
+ aggregationIndex = 0;
10373
11575
  constructor(device, lowerings = []) {
10374
11576
  this.device = device;
10375
11577
  this.capabilities = Object.freeze({
@@ -10393,6 +11595,7 @@ ${cooperative ? `var<workgroup> scratch: array<f32, ${workgroupSize}>;` : ""}
10393
11595
  }
10394
11596
  compile(program, bindings = {}) {
10395
11597
  this.compactionIndex = 0;
11598
+ this.aggregationIndex = 0;
10396
11599
  program = program.clone();
10397
11600
  for (const vector of program.vectors) {
10398
11601
  const binding = bindings.vectors?.[vector.id];
@@ -10570,6 +11773,54 @@ ${cooperative ? `var<workgroup> scratch: array<f32, ${workgroupSize}>;` : ""}
10570
11773
  return [
10571
11774
  { type: "vector-upload", lower: lowerGPUUpload },
10572
11775
  { type: "vector-copy", lower: lowerGPUCopy },
11776
+ {
11777
+ type: "group-aggregation",
11778
+ lower: (operation, context) => {
11779
+ const { props } = operation;
11780
+ const id = `${operation.id}-${this.aggregationIndex++}`;
11781
+ const keys = context.resolveVector(props.keys);
11782
+ const mask = props.mask ? context.resolveVector(props.mask) : void 0;
11783
+ if (props.operation === "count") {
11784
+ context.graph.add(
11785
+ new GPUGroupAggregation({
11786
+ id,
11787
+ keys,
11788
+ mask,
11789
+ operation: "count",
11790
+ output: getAggregationOutput(context.resolveVector(props.output))
11791
+ })
11792
+ );
11793
+ } else {
11794
+ context.graph.add(
11795
+ new GPUGroupAggregation({
11796
+ id,
11797
+ keys,
11798
+ mask,
11799
+ operation: props.operation,
11800
+ values: context.resolveVector(props.values),
11801
+ output: getAggregationOutput(context.resolveVector(props.output))
11802
+ })
11803
+ );
11804
+ }
11805
+ }
11806
+ },
11807
+ {
11808
+ type: "reduction",
11809
+ lower: (operation, context) => {
11810
+ const { props } = operation;
11811
+ context.graph.add(
11812
+ new GPUReduction({
11813
+ id: `${operation.id}-${this.aggregationIndex++}`,
11814
+ input: context.resolveVector(props.input),
11815
+ mask: props.mask ? context.resolveVector(props.mask) : void 0,
11816
+ operation: props.operation,
11817
+ output: getAggregationOutput(
11818
+ context.resolveVector(props.output)
11819
+ )
11820
+ })
11821
+ );
11822
+ }
11823
+ },
10573
11824
  {
10574
11825
  type: "compaction",
10575
11826
  lower: (operation, context) => {
@@ -10929,9 +12180,82 @@ ${cooperative ? `var<workgroup> scratch: array<f32, ${workgroupSize}>;` : ""}
10929
12180
  }
10930
12181
  return lengths;
10931
12182
  }
12183
+ function getAggregationOutput(output) {
12184
+ (0, import_core18.assert)(output.data.length === 1);
12185
+ return output.data[0];
12186
+ }
10932
12187
 
10933
12188
  // src/gpu-core/gpu-expression-plan.ts
12189
+ var import_core20 = __toESM(require_core(), 1);
12190
+
12191
+ // src/gpu-core/gpu-shader-pass-operation.ts
10934
12192
  var import_core19 = __toESM(require_core(), 1);
12193
+ var GPUShaderPassOperation = class {
12194
+ type = "shader-pass";
12195
+ id;
12196
+ fragmentSource;
12197
+ inputs;
12198
+ samplers;
12199
+ parameters;
12200
+ output;
12201
+ outputDescriptor;
12202
+ constructor(props) {
12203
+ this.id = props.id ?? `${props.output}-shader-pass`;
12204
+ this.fragmentSource = props.fragmentSource;
12205
+ this.inputs = Object.freeze({ ...props.inputs });
12206
+ this.parameters = Object.freeze({ ...props.parameters });
12207
+ this.samplers = Object.freeze(
12208
+ Object.fromEntries(
12209
+ Object.entries(props.samplers ?? {}).map(([name, sampler]) => [
12210
+ name,
12211
+ Object.freeze({ ...sampler })
12212
+ ])
12213
+ )
12214
+ );
12215
+ this.output = props.output;
12216
+ const descriptor = props.outputDescriptor;
12217
+ (0, import_core19.assert)(
12218
+ descriptor.extent && (descriptor.dimension ?? "2d") === "2d" && (descriptor.mipLevels ?? 1) === 1 && (descriptor.samples ?? 1) === 1
12219
+ );
12220
+ this.outputDescriptor = gpuGraph.texture({
12221
+ ...descriptor,
12222
+ dimension: "2d",
12223
+ mipLevels: 1,
12224
+ samples: 1
12225
+ });
12226
+ const bindings = [...Object.keys(this.inputs), ...Object.keys(this.samplers)];
12227
+ (0, import_core19.assert)(new Set(bindings).size === bindings.length);
12228
+ for (const name of [...bindings, ...Object.keys(this.parameters)])
12229
+ (0, import_core19.assert)(
12230
+ /^[A-Za-z][A-Za-z0-9_]*$/.test(name) && !["parameters", "shade", "vertexMain", "fragmentMain"].includes(name) && !name.startsWith("GraphShaderPass")
12231
+ );
12232
+ for (const sampler of Object.values(this.samplers))
12233
+ (0, import_core19.assert)((sampler.type ?? "color-sampler") === "color-sampler");
12234
+ }
12235
+ get contract() {
12236
+ return {
12237
+ values: [
12238
+ ...Object.values(this.inputs).map((value) => ({
12239
+ value,
12240
+ access: "read",
12241
+ textureUsage: "sampled"
12242
+ })),
12243
+ ...Object.values(this.parameters).map((value) => ({ value, access: "read" })),
12244
+ { value: this.output, access: "write", textureUsage: "render-attachment" }
12245
+ ],
12246
+ outputs: ({ getValue }) => {
12247
+ for (const name of Object.values(this.inputs)) {
12248
+ const input = getValue(name);
12249
+ (0, import_core19.assert)(
12250
+ input.type === "texture" && (input.dimension ?? "2d") === "2d" && (input.samples ?? 1) === 1
12251
+ );
12252
+ }
12253
+ for (const name of Object.values(this.parameters)) (0, import_core19.assert)(getValue(name).type === "scalar");
12254
+ return { [this.output]: this.outputDescriptor };
12255
+ }
12256
+ };
12257
+ }
12258
+ };
10935
12259
 
10936
12260
  // ../../node_modules/@math.gl/core/dist/expressions/vendor/jsep/runtime.js
10937
12261
  var Hooks = class {
@@ -12142,6 +13466,9 @@ ${cooperative ? `var<workgroup> scratch: array<f32, ${workgroupSize}>;` : ""}
12142
13466
  operation.operations.forEach(flatten);
12143
13467
  else {
12144
13468
  if (operation instanceof GPUCompositeOperation) {
13469
+ const containsShaderPass = (child) => child instanceof GPUShaderPassOperation || child instanceof GPUCompositeOperation && child.operations.some(containsShaderPass);
13470
+ if (operation.operations.some(containsShaderPass))
13471
+ throw new Error("Shader-pass operations inside control flow are not supported");
12145
13472
  const containsExpression = (child) => child instanceof GPUExpressionOperation || child instanceof GPUCompositeOperation && child.operations.some(containsExpression);
12146
13473
  if (operation.operations.some(containsExpression))
12147
13474
  throw new Error("Expression operations inside control flow are not supported");
@@ -12273,7 +13600,7 @@ ${cooperative ? `var<workgroup> scratch: array<f32, ${workgroupSize}>;` : ""}
12273
13600
  const declarations = [...this.scalars, ...this.vectors, ...this.textures];
12274
13601
  const explicit = declarations.some((value) => value.role === "input" || value.role === "state");
12275
13602
  const grouped = explicit || Object.values(supplied).some(
12276
- (value) => value !== void 0 && typeof value === "object" && !(value instanceof GPUVector) && !(value instanceof CPUVector) && !(value instanceof import_core19.Texture) && !(value instanceof import_core19.TextureView)
13603
+ (value) => value !== void 0 && typeof value === "object" && !(value instanceof GPUVector) && !(value instanceof CPUVector) && !(value instanceof import_core20.Texture) && !(value instanceof import_core20.TextureView)
12277
13604
  );
12278
13605
  if (!grouped) {
12279
13606
  for (const name of Object.keys(supplied))
@@ -12548,7 +13875,7 @@ ${cooperative ? `var<workgroup> scratch: array<f32, ${workgroupSize}>;` : ""}
12548
13875
  const outputs = /* @__PURE__ */ Object.create(null);
12549
13876
  for (const name of this.program.outputs) {
12550
13877
  const value = this.textures?.values.get(name) ?? this.values.get(name);
12551
- if (!(value instanceof GPUVector || value instanceof import_core19.Texture || value instanceof import_core19.TextureView))
13878
+ if (!(value instanceof GPUVector || value instanceof import_core20.Texture || value instanceof import_core20.TextureView))
12552
13879
  throw new Error(`Output ${name} has no materialized resource`);
12553
13880
  outputs[name] = value;
12554
13881
  }
@@ -12576,7 +13903,7 @@ ${cooperative ? `var<workgroup> scratch: array<f32, ${workgroupSize}>;` : ""}
12576
13903
  new GPUData({
12577
13904
  buffer: device.createBuffer({
12578
13905
  byteLength: Math.max(1, length) * getGPUExpressionRowInfo(format).components * 4,
12579
- usage: import_core19.Buffer.STORAGE | import_core19.Buffer.VERTEX | import_core19.Buffer.COPY_SRC | import_core19.Buffer.COPY_DST
13906
+ usage: import_core20.Buffer.STORAGE | import_core20.Buffer.VERTEX | import_core20.Buffer.COPY_SRC | import_core20.Buffer.COPY_DST
12580
13907
  }),
12581
13908
  format,
12582
13909
  length,
@@ -12603,7 +13930,7 @@ ${cooperative ? `var<workgroup> scratch: array<f32, ${workgroupSize}>;` : ""}
12603
13930
  }
12604
13931
  }
12605
13932
  function validateWritableTarget(name, target, values) {
12606
- const getBuffer = (chunk) => chunk.buffer instanceof import_core19.Buffer ? chunk.buffer : chunk.buffer.buffer;
13933
+ const getBuffer = (chunk) => chunk.buffer instanceof import_core20.Buffer ? chunk.buffer : chunk.buffer.buffer;
12607
13934
  const ranges = /* @__PURE__ */ new Map();
12608
13935
  for (const chunk of target.data) {
12609
13936
  if (chunk.length === 0) continue;
@@ -12627,7 +13954,7 @@ ${cooperative ? `var<workgroup> scratch: array<f32, ${workgroupSize}>;` : ""}
12627
13954
  }
12628
13955
 
12629
13956
  // src/gpu-core/gpu-expression-kernel.ts
12630
- var import_core20 = __toESM(require_core(), 1);
13957
+ var import_core21 = __toESM(require_core(), 1);
12631
13958
 
12632
13959
  // src/gpu-core/gpu-expression-cast.ts
12633
13960
  var GPU_EXPRESSION_SHADER_TYPES = { float32: "f32", sint32: "i32", uint32: "u32" };
@@ -12836,49 +14163,447 @@ fn main(@builtin(workgroup_id) workgroup: vec3u, @builtin(num_workgroups) dimens
12836
14163
  buffer: arena.buffer,
12837
14164
  usage: this.outputIsScalar ? "storage-read-write" : "storage-read"
12838
14165
  }
12839
- ] : []
12840
- ];
12841
- return [
12842
- setGPUComputeDispatchWorkgroups(
12843
- createGPUComputeCommandNode({
12844
- id: `${this.plan.operation.id}-chunk-${chunkIndex}`,
12845
- resources,
12846
- compile: ({ device }) => {
12847
- const data = new Uint32Array(Math.ceil((this.vectorNames.length + 2) / 4) * 4);
12848
- data.set([
12849
- output.length,
12850
- getViewElementOffset(output),
12851
- ...inputs.map(getViewElementOffset)
12852
- ]);
12853
- const metadataBuffer = device.createBuffer({ data, usage: import_core20.Buffer.UNIFORM });
12854
- return {
12855
- encode: ({ computePass, getBuffer }) => {
12856
- const bindings = { metadata: metadataBuffer };
12857
- inputs.forEach((input, index) => {
12858
- bindings[`input${index}`] = getViewBinding(input, getBuffer);
12859
- });
12860
- if (outputVector) bindings["outputValues"] = getViewBinding(output, getBuffer);
12861
- if (arena) bindings["gpuValues"] = getBuffer(arena.buffer);
12862
- this.kernel.dispatch(computePass, { bindings, x, y, z: 1 });
12863
- },
12864
- destroy: () => metadataBuffer.destroy()
12865
- };
12866
- }
12867
- }),
12868
- [x, y, 1]
14166
+ ] : []
14167
+ ];
14168
+ return [
14169
+ setGPUComputeDispatchWorkgroups(
14170
+ createGPUComputeCommandNode({
14171
+ id: `${this.plan.operation.id}-chunk-${chunkIndex}`,
14172
+ resources,
14173
+ compile: ({ device }) => {
14174
+ const data = new Uint32Array(Math.ceil((this.vectorNames.length + 2) / 4) * 4);
14175
+ data.set([
14176
+ output.length,
14177
+ getViewElementOffset(output),
14178
+ ...inputs.map(getViewElementOffset)
14179
+ ]);
14180
+ const metadataBuffer = device.createBuffer({ data, usage: import_core21.Buffer.UNIFORM });
14181
+ return {
14182
+ encode: ({ computePass, getBuffer }) => {
14183
+ const bindings = { metadata: metadataBuffer };
14184
+ inputs.forEach((input, index) => {
14185
+ bindings[`input${index}`] = getViewBinding(input, getBuffer);
14186
+ });
14187
+ if (outputVector) bindings["outputValues"] = getViewBinding(output, getBuffer);
14188
+ if (arena) bindings["gpuValues"] = getBuffer(arena.buffer);
14189
+ this.kernel.dispatch(computePass, { bindings, x, y, z: 1 });
14190
+ },
14191
+ destroy: () => metadataBuffer.destroy()
14192
+ };
14193
+ }
14194
+ }),
14195
+ [x, y, 1]
14196
+ )
14197
+ ];
14198
+ });
14199
+ addGPUCommandNodes(context.graph, nodes);
14200
+ context.recordDecision({
14201
+ operationId: this.plan.operation.id,
14202
+ operationType: "expression",
14203
+ lowering: "webgpu-expression",
14204
+ reason: "shape-independent expression shader with execution-time chunk dimensions"
14205
+ });
14206
+ }
14207
+ destroy() {
14208
+ this.kernel.destroy();
14209
+ }
14210
+ };
14211
+
14212
+ // src/gpu-core/gpu-shader-pass-kernel.ts
14213
+ var import_core23 = __toESM(require_core(), 1);
14214
+
14215
+ // src/execution/compute/render-kernel.ts
14216
+ var import_core22 = __toESM(require_core(), 1);
14217
+ var RenderKernel = class _RenderKernel {
14218
+ /** Creates a render kernel while allowing the backend to compile its pipeline asynchronously. */
14219
+ static async createAsync(device, props) {
14220
+ const ownsCompilation = !import_core22.PipelineFactory.getAsyncCompilation(device);
14221
+ const asyncCompilation = ownsCompilation ? import_core22.PipelineFactory.beginAsyncCompilation(device) : import_core22.PipelineFactory.getAsyncCompilation(device);
14222
+ let kernel;
14223
+ try {
14224
+ kernel = new _RenderKernel(device, props);
14225
+ } finally {
14226
+ if (ownsCompilation) import_core22.PipelineFactory.endAsyncCompilation(device, asyncCompilation);
14227
+ }
14228
+ try {
14229
+ if (ownsCompilation) {
14230
+ await Promise.all(asyncCompilation);
14231
+ } else {
14232
+ await kernel._pipelineInitialization;
14233
+ }
14234
+ return kernel;
14235
+ } catch (error) {
14236
+ kernel.destroy();
14237
+ throw error;
14238
+ }
14239
+ }
14240
+ device;
14241
+ id;
14242
+ vertexSource;
14243
+ fragmentSource;
14244
+ pipelineFactory;
14245
+ shaderFactory;
14246
+ vertexShader;
14247
+ fragmentShader;
14248
+ pipeline;
14249
+ _pipelineInitialization;
14250
+ _destroyed = false;
14251
+ drawDefaults;
14252
+ constructor(device, props) {
14253
+ if (device.type !== "webgpu" && device.type !== "webgl") {
14254
+ throw new Error("RenderKernel requires WebGL or WebGPU");
14255
+ }
14256
+ if (device.type === "webgl" && !props.fragmentSource) {
14257
+ throw new Error("WebGL RenderKernel requires a fragment shader");
14258
+ }
14259
+ const {
14260
+ vertexSource,
14261
+ fragmentSource,
14262
+ pipelineFactory,
14263
+ shaderFactory,
14264
+ debugShaders,
14265
+ ...pipelineProps
14266
+ } = props;
14267
+ this.device = device;
14268
+ this.drawDefaults = {
14269
+ parameters: props.parameters ?? {},
14270
+ topology: props.topology ?? "triangle-list"
14271
+ };
14272
+ this.id = props.id ?? "render-kernel";
14273
+ this.vertexSource = vertexSource;
14274
+ this.fragmentSource = fragmentSource;
14275
+ this.pipelineFactory = pipelineFactory ?? import_core22.PipelineFactory.getDefaultPipelineFactory(device);
14276
+ this.shaderFactory = shaderFactory ?? import_core22.ShaderFactory.getDefaultShaderFactory(device);
14277
+ this.vertexShader = this.shaderFactory.createShader({
14278
+ id: `${this.id}-vertex`,
14279
+ stage: "vertex",
14280
+ source: this.vertexSource,
14281
+ debugShaders
14282
+ });
14283
+ this.fragmentShader = this.fragmentSource ? this.shaderFactory.createShader({
14284
+ id: `${this.id}-fragment`,
14285
+ stage: "fragment",
14286
+ source: this.fragmentSource,
14287
+ debugShaders
14288
+ }) : null;
14289
+ const renderPipelineProps = {
14290
+ ...pipelineProps,
14291
+ vs: this.vertexShader,
14292
+ fs: this.fragmentShader
14293
+ };
14294
+ const asyncCompilation = import_core22.PipelineFactory.getAsyncCompilation(device);
14295
+ if (asyncCompilation) {
14296
+ const pipelineInitialization = this.pipelineFactory.createRenderPipelineAsync(renderPipelineProps);
14297
+ this._pipelineInitialization = pipelineInitialization;
14298
+ asyncCompilation.push(
14299
+ pipelineInitialization.then((pipeline) => {
14300
+ this.pipeline = pipeline;
14301
+ return pipeline;
14302
+ })
14303
+ );
14304
+ } else {
14305
+ this.pipeline = this.pipelineFactory.createRenderPipeline(renderPipelineProps);
14306
+ }
14307
+ }
14308
+ /** Applies per-draw bindings/vertex state and records a direct draw. */
14309
+ draw(renderPass, options) {
14310
+ const { bindings = {}, vertexArray, ...drawOptions } = options;
14311
+ this._setPipeline(renderPass, bindings, vertexArray);
14312
+ return renderPass.draw(
14313
+ this.device.type === "webgl" ? {
14314
+ ...this.drawDefaults,
14315
+ ...drawOptions,
14316
+ isInstanced: drawOptions.isInstanced ?? drawOptions.instanceCount !== void 0
14317
+ } : drawOptions
14318
+ );
14319
+ }
14320
+ /** Applies per-draw state and records a non-indexed indirect draw. */
14321
+ drawIndirect(renderPass, options) {
14322
+ if (this.device.type !== "webgpu")
14323
+ throw new Error("Indirect drawing is only supported in WebGPU");
14324
+ const { bindings = {}, vertexArray, indirectBuffer, indirectOffset = 0 } = options;
14325
+ this._setPipeline(renderPass, bindings, vertexArray);
14326
+ renderPass.drawIndirect(indirectBuffer, indirectOffset);
14327
+ }
14328
+ /** Applies per-draw state and records an indexed indirect draw. */
14329
+ drawIndexedIndirect(renderPass, options) {
14330
+ if (this.device.type !== "webgpu")
14331
+ throw new Error("Indirect drawing is only supported in WebGPU");
14332
+ const { bindings = {}, vertexArray, indirectBuffer, indirectOffset = 0 } = options;
14333
+ this._setPipeline(renderPass, bindings, vertexArray);
14334
+ renderPass.drawIndexedIndirect(indirectBuffer, indirectOffset);
14335
+ }
14336
+ destroy() {
14337
+ if (this._destroyed) return;
14338
+ if (this.pipeline) this.pipelineFactory.release(this.pipeline);
14339
+ this.shaderFactory.release(this.vertexShader);
14340
+ if (this.fragmentShader) this.shaderFactory.release(this.fragmentShader);
14341
+ this._destroyed = true;
14342
+ }
14343
+ _setPipeline(renderPass, bindings, vertexArray) {
14344
+ renderPass.setPipeline(this.pipeline);
14345
+ renderPass.setBindings(bindings);
14346
+ renderPass.setVertexArray(vertexArray);
14347
+ }
14348
+ };
14349
+
14350
+ // src/gpu-core/gpu-shader-pass-kernel.ts
14351
+ var VERTEX_SOURCE = `
14352
+ struct GraphShaderPassVertex {
14353
+ @builtin(position) position: vec4<f32>,
14354
+ @location(0) textureCoordinates: vec2<f32>
14355
+ };
14356
+ @vertex fn vertexMain(@builtin(vertex_index) index: u32) -> GraphShaderPassVertex {
14357
+ let position = vec2<f32>(f32((index << 1u) & 2u), f32(index & 2u));
14358
+ var result: GraphShaderPassVertex;
14359
+ result.position = vec4<f32>(position * 2.0 - 1.0, 0.0, 1.0);
14360
+ result.textureCoordinates = vec2<f32>(position.x, 1.0 - position.y);
14361
+ return result;
14362
+ }`;
14363
+ var GPUShaderPassKernel = class {
14364
+ constructor(device, operation, program) {
14365
+ this.device = device;
14366
+ this.operation = operation;
14367
+ (0, import_core23.assert)(device.type === "webgpu");
14368
+ this.parameterFormats = Object.values(operation.parameters).map((name) => {
14369
+ const scalar = program.scalars.find((value) => value.id === name);
14370
+ (0, import_core23.assert)(scalar);
14371
+ return scalar.format;
14372
+ });
14373
+ this.parameterByteLength = Math.ceil(this.parameterFormats.length / 4) * 16;
14374
+ for (const name of Object.values(operation.inputs)) {
14375
+ const input = program.textures.find((texture) => texture.id === name);
14376
+ const info = device.getTextureFormatInfo(input.format);
14377
+ (0, import_core23.assert)(
14378
+ !info.integer && info.attachment !== "depth" && info.attachment !== "depth-stencil" && device.getTextureFormatCapabilities(input.format).filter
14379
+ );
14380
+ }
14381
+ const outputInfo = device.getTextureFormatInfo(operation.outputDescriptor.format);
14382
+ (0, import_core23.assert)(
14383
+ !outputInfo.integer && device.getTextureFormatCapabilities(operation.outputDescriptor.format).render
14384
+ );
14385
+ const shaderBindings = [
14386
+ ...Object.keys(operation.inputs).map((name, location) => ({
14387
+ name,
14388
+ location,
14389
+ group: 0,
14390
+ type: "texture",
14391
+ viewDimension: "2d",
14392
+ sampleType: "float"
14393
+ })),
14394
+ ...Object.keys(operation.samplers).map((name, index) => ({
14395
+ name,
14396
+ location: Object.keys(operation.inputs).length + index,
14397
+ group: 0,
14398
+ type: "sampler"
14399
+ }))
14400
+ ];
14401
+ let binding = 0;
14402
+ const declarations = [
14403
+ ...Object.keys(operation.inputs).map(
14404
+ (name) => `@group(0) @binding(${binding++}) var ${name}: texture_2d<f32>;`
14405
+ ),
14406
+ ...Object.keys(operation.samplers).map(
14407
+ (name) => `@group(0) @binding(${binding++}) var ${name}: sampler;`
14408
+ )
14409
+ ];
14410
+ if (this.parameterFormats.length) {
14411
+ shaderBindings.push({ name: "parameters", location: binding, group: 0, type: "uniform" });
14412
+ declarations.push(
14413
+ `struct GraphShaderPassParameters {${Object.keys(operation.parameters).map((name, index) => `${name}: ${getGPUScalarWGSLType(this.parameterFormats[index])}`).join(
14414
+ ","
14415
+ )}};
14416
+ @group(0) @binding(${binding}) var<uniform> parameters: GraphShaderPassParameters;`
14417
+ );
14418
+ }
14419
+ try {
14420
+ this.kernel = new RenderKernel(device, {
14421
+ id: operation.id,
14422
+ vertexSource: VERTEX_SOURCE,
14423
+ fragmentSource: `${declarations.join("\n")}
14424
+ ${operation.fragmentSource}
14425
+
14426
+ @fragment fn fragmentMain(@location(0) textureCoordinates: vec2<f32>) -> @location(0) vec4<f32> {
14427
+ return shade(textureCoordinates);
14428
+ }`,
14429
+ vertexEntryPoint: "vertexMain",
14430
+ fragmentEntryPoint: "fragmentMain",
14431
+ topology: "triangle-list",
14432
+ shaderLayout: { attributes: [], bindings: shaderBindings },
14433
+ colorAttachmentFormats: [operation.outputDescriptor.format],
14434
+ parameters: { depthWriteEnabled: false }
14435
+ });
14436
+ this.vertexArray = device.createVertexArray({
14437
+ shaderLayout: this.kernel.pipeline.shaderLayout,
14438
+ bufferLayout: []
14439
+ });
14440
+ for (const [name, props] of Object.entries(operation.samplers))
14441
+ this.samplers[name] = device.createSampler(props);
14442
+ } catch (error) {
14443
+ this.destroy();
14444
+ throw error;
14445
+ }
14446
+ }
14447
+ device;
14448
+ operation;
14449
+ kernel;
14450
+ vertexArray;
14451
+ samplers = /* @__PURE__ */ Object.create(null);
14452
+ parameterFormats;
14453
+ parameterByteLength;
14454
+ /** Validate selected view geometry before either executor records commands. */
14455
+ validateTextures(textures) {
14456
+ for (const name of [...Object.values(this.operation.inputs), this.operation.output]) {
14457
+ const binding = textures.get(name);
14458
+ (0, import_core23.assert)(binding);
14459
+ const info = getTextureBindingInfo(binding);
14460
+ (0, import_core23.assert)(
14461
+ info.texture.device === this.device && info.dimension === "2d" && info.depth === 1 && info.samples === 1
14462
+ );
14463
+ if (name === this.operation.output) (0, import_core23.assert)(info.mipLevels === 1);
14464
+ }
14465
+ }
14466
+ /** Full graph lowers to ordinary resource-tracked copy and render nodes. */
14467
+ lower(context) {
14468
+ const operation = this.operation;
14469
+ const inputs = Object.fromEntries(
14470
+ Object.entries(operation.inputs).map(([name, value]) => [
14471
+ name,
14472
+ context.resolveTextureView(value)
14473
+ ])
14474
+ );
14475
+ const output = context.resolveTextureView(operation.output);
14476
+ const parameters = this.parameterFormats.length ? context.graph.createTransientBuffer({
14477
+ id: context.graph.getUniqueResourceId(`${operation.id}-parameters`),
14478
+ byteLength: this.parameterByteLength,
14479
+ usage: import_core23.Buffer.UNIFORM | import_core23.Buffer.COPY_DST
14480
+ }) : void 0;
14481
+ if (parameters) {
14482
+ const sources = Object.values(operation.parameters).map(
14483
+ (name) => context.resolveScalar(name).view
14484
+ );
14485
+ context.graph.addCopyPass({
14486
+ id: `${operation.id}-parameters`,
14487
+ resources: [
14488
+ ...sources.map((buffer) => ({ buffer, usage: "copy-source" })),
14489
+ { buffer: parameters, usage: "copy-destination" }
14490
+ ],
14491
+ compile: () => ({
14492
+ encode: ({ commandEncoder, getBuffer }) => {
14493
+ sources.forEach(
14494
+ (source, index) => commandEncoder.copyBufferToBuffer({
14495
+ sourceBuffer: getBuffer(source),
14496
+ sourceOffset: source.byteOffset,
14497
+ destinationBuffer: getBuffer(parameters),
14498
+ destinationOffset: index * 4,
14499
+ size: 4
14500
+ })
14501
+ );
14502
+ }
14503
+ })
14504
+ });
14505
+ }
14506
+ context.graph.addRenderPass({
14507
+ id: operation.id,
14508
+ resources: [
14509
+ ...Object.values(inputs).map((texture) => ({ texture, usage: "sampled" })),
14510
+ ...parameters ? [{ buffer: parameters, usage: "uniform" }] : []
14511
+ ],
14512
+ attachments: { colorAttachments: [output] },
14513
+ compile: () => ({
14514
+ getRenderPassProps: () => ({ clearColor: [0, 0, 0, 0], clearDepth: false }),
14515
+ encode: ({ renderPass, getTextureView, getBuffer }) => this.draw(
14516
+ renderPass,
14517
+ Object.fromEntries(
14518
+ Object.entries(inputs).map(([name, view]) => [name, getTextureView(view)])
14519
+ ),
14520
+ parameters ? getBuffer(parameters) : void 0
12869
14521
  )
12870
- ];
14522
+ })
12871
14523
  });
12872
- addGPUCommandNodes(context.graph, nodes);
12873
- context.recordDecision({
12874
- operationId: this.plan.operation.id,
12875
- operationType: "expression",
12876
- lowering: "webgpu-expression",
12877
- reason: "shape-independent expression shader with execution-time chunk dimensions"
14524
+ }
14525
+ /** SimpleGraph owns only per-invocation framebuffer/uniform wrappers, never bound textures. */
14526
+ prepare(textures, values) {
14527
+ this.validateTextures(textures);
14528
+ const inputs = Object.fromEntries(
14529
+ Object.entries(this.operation.inputs).map(([name, value]) => [name, textures.get(value)])
14530
+ );
14531
+ const output = textures.get(this.operation.output);
14532
+ const info = getTextureBindingInfo(output);
14533
+ const data = new Uint8Array(this.parameterByteLength);
14534
+ const view = new DataView(data.buffer);
14535
+ const parameterValues = Object.values(this.operation.parameters).map((name, index) => {
14536
+ const value = values.get(name);
14537
+ (0, import_core23.assert)(value !== void 0);
14538
+ if (typeof value === "number") {
14539
+ switch (this.parameterFormats[index]) {
14540
+ case "float32":
14541
+ view.setFloat32(index * 4, value, true);
14542
+ break;
14543
+ case "sint32":
14544
+ view.setInt32(index * 4, value, true);
14545
+ break;
14546
+ case "uint32":
14547
+ view.setUint32(index * 4, value, true);
14548
+ break;
14549
+ }
14550
+ } else (0, import_core23.assert)(value.length === 1 && value.data.length === 1);
14551
+ return value;
12878
14552
  });
14553
+ const parameters = data.byteLength ? this.device.createBuffer({ data, usage: import_core23.Buffer.UNIFORM | import_core23.Buffer.COPY_DST }) : void 0;
14554
+ let framebuffer;
14555
+ try {
14556
+ framebuffer = this.device.createFramebuffer({
14557
+ width: info.width,
14558
+ height: info.height,
14559
+ colorAttachments: [output]
14560
+ });
14561
+ } catch (error) {
14562
+ parameters?.destroy();
14563
+ throw error;
14564
+ }
14565
+ return {
14566
+ encode: (commandEncoder) => {
14567
+ this.validateTextures(textures);
14568
+ if (parameters)
14569
+ parameterValues.forEach((value, index) => {
14570
+ if (!(value instanceof GPUVector)) return;
14571
+ const chunk = value.data[0];
14572
+ const buffer = chunk.buffer instanceof import_core23.Buffer ? chunk.buffer : chunk.buffer.buffer;
14573
+ commandEncoder.copyBufferToBuffer({
14574
+ sourceBuffer: buffer,
14575
+ sourceOffset: chunk.byteOffset,
14576
+ destinationBuffer: parameters,
14577
+ destinationOffset: index * 4,
14578
+ size: 4
14579
+ });
14580
+ });
14581
+ const pass = commandEncoder.beginRenderPass({
14582
+ framebuffer,
14583
+ clearColor: [0, 0, 0, 0],
14584
+ clearDepth: false
14585
+ });
14586
+ try {
14587
+ this.draw(pass, inputs, parameters);
14588
+ } finally {
14589
+ pass.end();
14590
+ }
14591
+ },
14592
+ destroy: () => {
14593
+ framebuffer.destroy();
14594
+ parameters?.destroy();
14595
+ }
14596
+ };
12879
14597
  }
12880
14598
  destroy() {
12881
- this.kernel.destroy();
14599
+ for (const sampler of Object.values(this.samplers)) sampler.destroy();
14600
+ this.vertexArray?.destroy();
14601
+ this.kernel?.destroy();
14602
+ }
14603
+ draw(renderPass, inputs, parameters) {
14604
+ const bindings = { ...inputs, ...this.samplers };
14605
+ if (parameters) bindings["parameters"] = parameters;
14606
+ this.kernel.draw(renderPass, { vertexArray: this.vertexArray, vertexCount: 3, bindings });
12882
14607
  }
12883
14608
  };
12884
14609
 
@@ -12917,17 +14642,17 @@ fn main(@builtin(workgroup_id) workgroup: vec3u, @builtin(num_workgroups) dimens
12917
14642
  };
12918
14643
 
12919
14644
  // src/gpu-core/gpu-cpu-execution.ts
12920
- var import_core21 = __toESM(require_core(), 1);
14645
+ var import_core24 = __toESM(require_core(), 1);
12921
14646
  var GPUCPUExecution = class {
12922
14647
  constructor(device, program, compileStage) {
12923
14648
  this.device = device;
12924
14649
  this.program = program;
12925
14650
  this.compileStage = compileStage;
12926
- (0, import_core21.assert)(!program.textures.length && !program.vectors.some((value) => value.role === "state"));
14651
+ (0, import_core24.assert)(!program.textures.length && !program.vectors.some((value) => value.role === "state"));
12927
14652
  const declarations = [...program.scalars, ...program.vectors];
12928
14653
  const addInput = (graph, name) => {
12929
14654
  const declaration = declarations.find((value) => value.id === name);
12930
- (0, import_core21.assert)(declaration);
14655
+ (0, import_core24.assert)(declaration);
12931
14656
  const vector = program.vectors.find((value) => value.id === name);
12932
14657
  if (vector)
12933
14658
  graph.addInput(
@@ -12949,7 +14674,7 @@ fn main(@builtin(workgroup_id) workgroup: vec3u, @builtin(num_workgroups) dimens
12949
14674
  this.stages.push(operation);
12950
14675
  continue;
12951
14676
  }
12952
- (0, import_core21.assert)("contract" in operation && operation.contract);
14677
+ (0, import_core24.assert)("contract" in operation && operation.contract);
12953
14678
  const inputs = operation.contract.values.filter((use) => use.access !== "write").map((use) => typeof use.value === "string" ? use.value : use.value.id);
12954
14679
  const outputs = operation.contract.values.filter((use) => use.access !== "read").map((use) => typeof use.value === "string" ? use.value : use.value.id);
12955
14680
  const graph = new GPUGraph();
@@ -12983,13 +14708,13 @@ fn main(@builtin(workgroup_id) workgroup: vec3u, @builtin(num_workgroups) dimens
12983
14708
  stages = [];
12984
14709
  async run(bindings, locations = {}) {
12985
14710
  for (const [name, location] of Object.entries(locations))
12986
- (0, import_core21.assert)(this.program.outputs.includes(name) && (location === "cpu" || location === "gpu"));
14711
+ (0, import_core24.assert)(this.program.outputs.includes(name) && (location === "cpu" || location === "gpu"));
12987
14712
  const cpu = /* @__PURE__ */ new Map();
12988
14713
  for (const declaration of [...this.program.vectors, ...this.program.scalars].filter(
12989
14714
  (value) => value.role === "input"
12990
14715
  )) {
12991
14716
  const value = bindings[declaration.id];
12992
- (0, import_core21.assert)(value !== void 0);
14717
+ (0, import_core24.assert)(value !== void 0);
12993
14718
  if (!(value instanceof CPUVector)) {
12994
14719
  const graph = new GPUGraph();
12995
14720
  const vector = this.program.vectors.find((vector2) => vector2.id === declaration.id);
@@ -13011,11 +14736,11 @@ fn main(@builtin(workgroup_id) workgroup: vec3u, @builtin(num_workgroups) dimens
13011
14736
  new GPUExpressionProgram(graph, { outputs: [] }).prepare(this.device, { [declaration.id]: value }).finish();
13012
14737
  }
13013
14738
  if (value instanceof CPUVector) {
13014
- (0, import_core21.assert)(value.data.every((chunk) => !chunk.nullBitmap && !chunk.valueOffsets));
13015
- (0, import_core21.assert)(value.format === declaration.format);
14739
+ (0, import_core24.assert)(value.data.every((chunk) => !chunk.nullBitmap && !chunk.valueOffsets));
14740
+ (0, import_core24.assert)(value.format === declaration.format);
13016
14741
  const vector = this.program.vectors.find((vector2) => vector2.id === declaration.id);
13017
- (0, import_core21.assert)(vector && (vector.length === void 0 || vector.length === value.length));
13018
- (0, import_core21.assert)(
14742
+ (0, import_core24.assert)(vector && (vector.length === void 0 || vector.length === value.length));
14743
+ (0, import_core24.assert)(
13019
14744
  !vector.chunkLengths || vector.chunkLengths.length === value.data.length && vector.chunkLengths.every((length, index) => length === value.data[index].length)
13020
14745
  );
13021
14746
  cpu.set(declaration.id, value);
@@ -13027,7 +14752,7 @@ fn main(@builtin(workgroup_id) workgroup: vec3u, @builtin(num_workgroups) dimens
13027
14752
  let value = cpu.get(name);
13028
14753
  if (!value) {
13029
14754
  const gpu = values[name];
13030
- (0, import_core21.assert)(gpu instanceof GPUVector);
14755
+ (0, import_core24.assert)(gpu instanceof GPUVector);
13031
14756
  const read = await readCPUVector(gpu);
13032
14757
  value = makeCPUVector(
13033
14758
  read.format,
@@ -13070,11 +14795,11 @@ fn main(@builtin(workgroup_id) workgroup: vec3u, @builtin(num_workgroups) dimens
13070
14795
  inputs[localName] = typeof cpuValue !== "number" && this.program.scalars.some((scalar) => scalar.id === name) ? cpuValue.pack()[0] : cpuValue;
13071
14796
  }
13072
14797
  const outputs2 = await stage.execute({ inputs });
13073
- (0, import_core21.assert)(Object.keys(outputs2).length === Object.keys(stage.outputs).length);
14798
+ (0, import_core24.assert)(Object.keys(outputs2).length === Object.keys(stage.outputs).length);
13074
14799
  for (const name of Object.keys(stage.outputs)) {
13075
14800
  const descriptor = this.program.vectors.find((vector) => vector.id === name);
13076
14801
  const result = outputs2[name];
13077
- (0, import_core21.assert)(result);
14802
+ (0, import_core24.assert)(result);
13078
14803
  const arrays = "chunks" in result ? result.chunks.map((chunk) => chunk.values) : [result];
13079
14804
  const upload = new GPUUploadOperation({
13080
14805
  output: name,
@@ -13082,8 +14807,8 @@ fn main(@builtin(workgroup_id) workgroup: vec3u, @builtin(num_workgroups) dimens
13082
14807
  data: arrays
13083
14808
  });
13084
14809
  const length = upload.chunkLengths.reduce((total, count) => total + count, 0);
13085
- (0, import_core21.assert)(descriptor.length === void 0 || descriptor.length === length);
13086
- (0, import_core21.assert)(
14810
+ (0, import_core24.assert)(descriptor.length === void 0 || descriptor.length === length);
14811
+ (0, import_core24.assert)(
13087
14812
  !descriptor.chunkLengths || descriptor.chunkLengths.length === arrays.length && descriptor.chunkLengths.every(
13088
14813
  (count, index) => count === upload.chunkLengths[index]
13089
14814
  )
@@ -13125,7 +14850,7 @@ fn main(@builtin(workgroup_id) workgroup: vec3u, @builtin(num_workgroups) dimens
13125
14850
  }
13126
14851
  };
13127
14852
  async function readCPUVector(vector) {
13128
- (0, import_core21.assert)(vector.format);
14853
+ (0, import_core24.assert)(vector.format);
13129
14854
  const info = getGPUVectorFormatInfo(vector.format);
13130
14855
  const ValueType = info.signedDataType === "float32" ? Float32Array : info.signedDataType === "uint32" ? Uint32Array : Int32Array;
13131
14856
  const chunks = [];
@@ -13169,7 +14894,7 @@ fn main(@builtin(workgroup_id) workgroup: vec3u, @builtin(num_workgroups) dimens
13169
14894
  }
13170
14895
  function getCPUView(vector) {
13171
14896
  const format = vector.format;
13172
- (0, import_core21.assert)(/^(float32|sint32|uint32)(x[234])?$/.test(format));
14897
+ (0, import_core24.assert)(/^(float32|sint32|uint32)(x[234])?$/.test(format));
13173
14898
  const info = getGPUVectorFormatInfo(format);
13174
14899
  const ValueType = info.signedDataType === "float32" ? Float32Array : info.signedDataType === "uint32" ? Uint32Array : Int32Array;
13175
14900
  const chunks = vector.data.map((chunk) => {
@@ -13208,6 +14933,10 @@ fn main(@builtin(workgroup_id) workgroup: vec3u, @builtin(num_workgroups) dimens
13208
14933
  this.stageLowerings = lowerings ?? options.lowerings ?? [];
13209
14934
  this.compiler = new GPUGraphCompiler(device, [
13210
14935
  ...lowerings ?? options.lowerings ?? [],
14936
+ {
14937
+ type: "shader-pass",
14938
+ lower: (operation, context) => this.shaderPasses.get(operation).lower(context)
14939
+ },
13211
14940
  {
13212
14941
  type: "expression",
13213
14942
  lower: (operation, context) => this.kernels.get(operation).lower(context)
@@ -13224,6 +14953,12 @@ fn main(@builtin(workgroup_id) workgroup: vec3u, @builtin(num_workgroups) dimens
13224
14953
  try {
13225
14954
  for (const plan of this.program.expressions)
13226
14955
  this.kernels.set(plan.operation, new GPUExpressionKernel(device, this.program, plan));
14956
+ for (const operation of this.program.operations)
14957
+ if (operation instanceof GPUShaderPassOperation)
14958
+ this.shaderPasses.set(
14959
+ operation,
14960
+ new GPUShaderPassKernel(device, operation, this.program)
14961
+ );
13227
14962
  } catch (error) {
13228
14963
  this.destroy();
13229
14964
  throw error;
@@ -13234,12 +14969,13 @@ fn main(@builtin(workgroup_id) workgroup: vec3u, @builtin(num_workgroups) dimens
13234
14969
  stageLowerings;
13235
14970
  compiler;
13236
14971
  kernels = /* @__PURE__ */ new Map();
14972
+ shaderPasses = /* @__PURE__ */ new Map();
13237
14973
  destroyed = false;
13238
14974
  runningCPU = false;
13239
14975
  cpuExecution;
13240
14976
  outputLocations;
13241
14977
  async run(supplied, options = {}) {
13242
- (0, import_core22.assert)(!this.destroyed && !this.runningCPU);
14978
+ (0, import_core25.assert)(!this.destroyed && !this.runningCPU);
13243
14979
  const suppliedInputs = "inputs" in supplied ? supplied.inputs : supplied;
13244
14980
  const useCPU = this.program.operations.some((operation) => operation instanceof GPUCPUOperation) || Object.values(this.outputLocations).includes("cpu") || Object.values(suppliedInputs ?? {}).some((value) => value instanceof CPUVector);
13245
14981
  if (!this.cpuExecution && useCPU)
@@ -13250,7 +14986,7 @@ fn main(@builtin(workgroup_id) workgroup: vec3u, @builtin(num_workgroups) dimens
13250
14986
  );
13251
14987
  if (useCPU && this.cpuExecution) {
13252
14988
  const resolved = this.program.resolveBindings(supplied, options);
13253
- (0, import_core22.assert)(
14989
+ (0, import_core25.assert)(
13254
14990
  !resolved.options.outputTargets || Object.keys(resolved.options.outputTargets).length === 0
13255
14991
  );
13256
14992
  this.runningCPU = true;
@@ -13277,7 +15013,7 @@ fn main(@builtin(workgroup_id) workgroup: vec3u, @builtin(num_workgroups) dimens
13277
15013
  }
13278
15014
  /** Bind one invocation without encoding or submitting commands. */
13279
15015
  prepare(supplied, options = {}) {
13280
- (0, import_core22.assert)(!this.destroyed);
15016
+ (0, import_core25.assert)(!this.destroyed);
13281
15017
  if (this.program.operations.some((operation) => operation instanceof GPUCPUOperation) || Object.values(this.outputLocations).includes("cpu"))
13282
15018
  throw new Error("CPU operations require asynchronous run(), not prepare()");
13283
15019
  const resolvedBindings = this.program.resolveBindings(supplied, options);
@@ -13286,6 +15022,8 @@ fn main(@builtin(workgroup_id) workgroup: vec3u, @builtin(num_workgroups) dimens
13286
15022
  const invocation = this.program.prepare(this.device, bindings, options, true);
13287
15023
  let executable;
13288
15024
  try {
15025
+ for (const kernel of this.shaderPasses.values())
15026
+ kernel.validateTextures(invocation.textures.values);
13289
15027
  const resolved = new GPUGraph();
13290
15028
  for (const scalar of this.program.scalars) resolved.scalar(scalar.id, scalar.format);
13291
15029
  const vectors = /* @__PURE__ */ Object.create(null);
@@ -13363,7 +15101,7 @@ fn main(@builtin(workgroup_id) workgroup: vec3u, @builtin(num_workgroups) dimens
13363
15101
  }
13364
15102
  executable = compilation.graph.compile();
13365
15103
  return new PreparedGPUGraphExecution(this.device, invocation, executable, () => {
13366
- (0, import_core22.assert)(!this.destroyed);
15104
+ (0, import_core25.assert)(!this.destroyed);
13367
15105
  });
13368
15106
  } catch (error) {
13369
15107
  executable?.destroy();
@@ -13372,8 +15110,10 @@ fn main(@builtin(workgroup_id) workgroup: vec3u, @builtin(num_workgroups) dimens
13372
15110
  }
13373
15111
  }
13374
15112
  destroy() {
13375
- (0, import_core22.assert)(!this.runningCPU);
15113
+ (0, import_core25.assert)(!this.runningCPU);
13376
15114
  this.cpuExecution?.destroy();
15115
+ for (const kernel of this.shaderPasses.values()) kernel.destroy();
15116
+ this.shaderPasses.clear();
13377
15117
  for (const kernel of this.kernels.values()) kernel.destroy();
13378
15118
  this.kernels.clear();
13379
15119
  this.destroyed = true;
@@ -13397,7 +15137,7 @@ fn main(@builtin(workgroup_id) workgroup: vec3u, @builtin(num_workgroups) dimens
13397
15137
  destroyed = false;
13398
15138
  /** Append commands once to a caller-owned encoder; never finish or submit it. */
13399
15139
  encode(commandEncoder) {
13400
- (0, import_core22.assert)(!this.destroyed && !this.encoded && commandEncoder.device === this.device);
15140
+ (0, import_core25.assert)(!this.destroyed && !this.encoded && commandEncoder.device === this.device);
13401
15141
  this.checkProgram();
13402
15142
  this.encoded = true;
13403
15143
  this.executable.encode(commandEncoder, { parameters: void 0 });
@@ -13583,6 +15323,95 @@ fn main(@builtin(workgroup_id) workgroup: vec3u, @builtin(num_workgroups) dimens
13583
15323
  return trees.reduce((count, tree) => count + 1 + countOperations(tree.children ?? []), 0);
13584
15324
  }
13585
15325
 
15326
+ // src/gpu-core/gpu-semantic-aggregation-operation.ts
15327
+ var import_core26 = __toESM(require_core(), 1);
15328
+ var GPUGraphGroupAggregation = class {
15329
+ /** Semantic operation discriminator. */
15330
+ type = "group-aggregation";
15331
+ /** Stable operation identifier. */
15332
+ id;
15333
+ /** Immutable logical operation arguments. */
15334
+ props;
15335
+ /** Describe grouped reduction without allocating or reading GPU storage. */
15336
+ constructor(props) {
15337
+ (0, import_core26.assert)(
15338
+ props.groupCount === void 0 || Number.isSafeInteger(props.groupCount) && props.groupCount > 0
15339
+ );
15340
+ this.id = props.id ?? `${getGPUOperationValueName(props.output)}-group-aggregation`;
15341
+ this.props = Object.freeze({ ...props });
15342
+ }
15343
+ /** Logical dependencies and optional inferred output shape. */
15344
+ get contract() {
15345
+ const { keys, mask, output, groupCount } = this.props;
15346
+ const values = this.props.operation === "count" ? void 0 : this.props.values;
15347
+ return {
15348
+ outputs: ({ getValue }) => {
15349
+ for (const input of [keys, mask]) {
15350
+ if (input) {
15351
+ const descriptor = getValue(getGPUOperationValueName(input));
15352
+ (0, import_core26.assert)(descriptor.type === "vector" && descriptor.format === "uint32");
15353
+ }
15354
+ }
15355
+ if (values) {
15356
+ const descriptor = getValue(getGPUOperationValueName(values));
15357
+ (0, import_core26.assert)(descriptor.type === "vector" && descriptor.format === "float32");
15358
+ }
15359
+ return {
15360
+ [getGPUOperationValueName(output)]: gpuGraph.vector(
15361
+ this.props.operation === "count" ? "uint32" : "float32",
15362
+ { length: groupCount }
15363
+ )
15364
+ };
15365
+ },
15366
+ values: [
15367
+ { value: keys, access: "read" },
15368
+ ...values ? [{ value: values, access: "read" }] : [],
15369
+ ...mask ? [{ value: mask, access: "read" }] : [],
15370
+ { value: output, access: "write" }
15371
+ ]
15372
+ };
15373
+ }
15374
+ };
15375
+ var GPUGraphReduction = class {
15376
+ /** Semantic operation discriminator. */
15377
+ type = "reduction";
15378
+ /** Stable operation identifier. */
15379
+ id;
15380
+ /** Immutable logical operation arguments. */
15381
+ props;
15382
+ /** Describe a scalar reduction without allocating or reading GPU storage. */
15383
+ constructor(props) {
15384
+ this.id = props.id ?? `${getGPUOperationValueName(props.output)}-reduction`;
15385
+ this.props = Object.freeze({ ...props });
15386
+ }
15387
+ /** Infer a packed one-row result, or two rows for extent. */
15388
+ get contract() {
15389
+ const { input, mask, output, operation } = this.props;
15390
+ return {
15391
+ outputs: ({ getValue }) => {
15392
+ const descriptor = getValue(getGPUOperationValueName(input));
15393
+ (0, import_core26.assert)(descriptor.type === "vector");
15394
+ const { format } = descriptor;
15395
+ (0, import_core26.assert)(format === "uint32" || format === "sint32" || format === "float32");
15396
+ if (mask) {
15397
+ const selection = getValue(getGPUOperationValueName(mask));
15398
+ (0, import_core26.assert)(selection.type === "vector" && selection.format === "uint32");
15399
+ }
15400
+ return {
15401
+ [getGPUOperationValueName(output)]: gpuGraph.vector(format, {
15402
+ length: operation === "extent" ? 2 : 1
15403
+ })
15404
+ };
15405
+ },
15406
+ values: [
15407
+ { value: input, access: "read" },
15408
+ ...mask ? [{ value: mask, access: "read" }] : [],
15409
+ { value: output, access: "write" }
15410
+ ]
15411
+ };
15412
+ }
15413
+ };
15414
+
13586
15415
  // src/gpu-core/gpu-command-graph-autotuner.ts
13587
15416
  var PROFILE_VERSION = 1;
13588
15417
  var GPUCommandGraphAutotuner = class {
@@ -14279,143 +16108,8 @@ fn main(@builtin(workgroup_id) workgroup: vec3u, @builtin(num_workgroups) dimens
14279
16108
  };
14280
16109
  }
14281
16110
 
14282
- // src/execution/compute/render-kernel.ts
14283
- var import_core23 = __toESM(require_core(), 1);
14284
- var RenderKernel = class _RenderKernel {
14285
- /** Creates a render kernel while allowing the backend to compile its pipeline asynchronously. */
14286
- static async createAsync(device, props) {
14287
- const ownsCompilation = !import_core23.PipelineFactory.getAsyncCompilation(device);
14288
- const asyncCompilation = ownsCompilation ? import_core23.PipelineFactory.beginAsyncCompilation(device) : import_core23.PipelineFactory.getAsyncCompilation(device);
14289
- let kernel;
14290
- try {
14291
- kernel = new _RenderKernel(device, props);
14292
- } finally {
14293
- if (ownsCompilation) import_core23.PipelineFactory.endAsyncCompilation(device, asyncCompilation);
14294
- }
14295
- try {
14296
- if (ownsCompilation) {
14297
- await Promise.all(asyncCompilation);
14298
- } else {
14299
- await kernel._pipelineInitialization;
14300
- }
14301
- return kernel;
14302
- } catch (error) {
14303
- kernel.destroy();
14304
- throw error;
14305
- }
14306
- }
14307
- device;
14308
- id;
14309
- vertexSource;
14310
- fragmentSource;
14311
- pipelineFactory;
14312
- shaderFactory;
14313
- vertexShader;
14314
- fragmentShader;
14315
- pipeline;
14316
- _pipelineInitialization;
14317
- _destroyed = false;
14318
- drawDefaults;
14319
- constructor(device, props) {
14320
- if (device.type !== "webgpu" && device.type !== "webgl") {
14321
- throw new Error("RenderKernel requires WebGL or WebGPU");
14322
- }
14323
- if (device.type === "webgl" && !props.fragmentSource) {
14324
- throw new Error("WebGL RenderKernel requires a fragment shader");
14325
- }
14326
- const {
14327
- vertexSource,
14328
- fragmentSource,
14329
- pipelineFactory,
14330
- shaderFactory,
14331
- debugShaders,
14332
- ...pipelineProps
14333
- } = props;
14334
- this.device = device;
14335
- this.drawDefaults = {
14336
- parameters: props.parameters ?? {},
14337
- topology: props.topology ?? "triangle-list"
14338
- };
14339
- this.id = props.id ?? "render-kernel";
14340
- this.vertexSource = vertexSource;
14341
- this.fragmentSource = fragmentSource;
14342
- this.pipelineFactory = pipelineFactory ?? import_core23.PipelineFactory.getDefaultPipelineFactory(device);
14343
- this.shaderFactory = shaderFactory ?? import_core23.ShaderFactory.getDefaultShaderFactory(device);
14344
- this.vertexShader = this.shaderFactory.createShader({
14345
- id: `${this.id}-vertex`,
14346
- stage: "vertex",
14347
- source: this.vertexSource,
14348
- debugShaders
14349
- });
14350
- this.fragmentShader = this.fragmentSource ? this.shaderFactory.createShader({
14351
- id: `${this.id}-fragment`,
14352
- stage: "fragment",
14353
- source: this.fragmentSource,
14354
- debugShaders
14355
- }) : null;
14356
- const renderPipelineProps = {
14357
- ...pipelineProps,
14358
- vs: this.vertexShader,
14359
- fs: this.fragmentShader
14360
- };
14361
- const asyncCompilation = import_core23.PipelineFactory.getAsyncCompilation(device);
14362
- if (asyncCompilation) {
14363
- const pipelineInitialization = this.pipelineFactory.createRenderPipelineAsync(renderPipelineProps);
14364
- this._pipelineInitialization = pipelineInitialization;
14365
- asyncCompilation.push(
14366
- pipelineInitialization.then((pipeline) => {
14367
- this.pipeline = pipeline;
14368
- return pipeline;
14369
- })
14370
- );
14371
- } else {
14372
- this.pipeline = this.pipelineFactory.createRenderPipeline(renderPipelineProps);
14373
- }
14374
- }
14375
- /** Applies per-draw bindings/vertex state and records a direct draw. */
14376
- draw(renderPass, options) {
14377
- const { bindings = {}, vertexArray, ...drawOptions } = options;
14378
- this._setPipeline(renderPass, bindings, vertexArray);
14379
- return renderPass.draw(
14380
- this.device.type === "webgl" ? {
14381
- ...this.drawDefaults,
14382
- ...drawOptions,
14383
- isInstanced: drawOptions.isInstanced ?? drawOptions.instanceCount !== void 0
14384
- } : drawOptions
14385
- );
14386
- }
14387
- /** Applies per-draw state and records a non-indexed indirect draw. */
14388
- drawIndirect(renderPass, options) {
14389
- if (this.device.type !== "webgpu")
14390
- throw new Error("Indirect drawing is only supported in WebGPU");
14391
- const { bindings = {}, vertexArray, indirectBuffer, indirectOffset = 0 } = options;
14392
- this._setPipeline(renderPass, bindings, vertexArray);
14393
- renderPass.drawIndirect(indirectBuffer, indirectOffset);
14394
- }
14395
- /** Applies per-draw state and records an indexed indirect draw. */
14396
- drawIndexedIndirect(renderPass, options) {
14397
- if (this.device.type !== "webgpu")
14398
- throw new Error("Indirect drawing is only supported in WebGPU");
14399
- const { bindings = {}, vertexArray, indirectBuffer, indirectOffset = 0 } = options;
14400
- this._setPipeline(renderPass, bindings, vertexArray);
14401
- renderPass.drawIndexedIndirect(indirectBuffer, indirectOffset);
14402
- }
14403
- destroy() {
14404
- if (this._destroyed) return;
14405
- if (this.pipeline) this.pipelineFactory.release(this.pipeline);
14406
- this.shaderFactory.release(this.vertexShader);
14407
- if (this.fragmentShader) this.shaderFactory.release(this.fragmentShader);
14408
- this._destroyed = true;
14409
- }
14410
- _setPipeline(renderPass, bindings, vertexArray) {
14411
- renderPass.setPipeline(this.pipeline);
14412
- renderPass.setBindings(bindings);
14413
- renderPass.setVertexArray(vertexArray);
14414
- }
14415
- };
14416
-
14417
16111
  // src/gpu-core/gpu-compaction-operation.ts
14418
- var import_core24 = __toESM(require_core(), 1);
16112
+ var import_core27 = __toESM(require_core(), 1);
14419
16113
  var GPUCompactionOperation = class {
14420
16114
  type = "compaction";
14421
16115
  id;
@@ -14430,9 +16124,9 @@ fn main(@builtin(workgroup_id) workgroup: vec3u, @builtin(num_workgroups) dimens
14430
16124
  outputs: ({ getValue }) => {
14431
16125
  for (const name of [input, flags]) {
14432
16126
  const value = getValue(name);
14433
- (0, import_core24.assert)(value.type === "vector" && value.format === "uint32");
16127
+ (0, import_core27.assert)(value.type === "vector" && value.format === "uint32");
14434
16128
  }
14435
- (0, import_core24.assert)(output !== count);
16129
+ (0, import_core27.assert)(output !== count);
14436
16130
  return { [output]: gpuGraph.vector("uint32"), [count]: gpuGraph.scalar("uint32") };
14437
16131
  },
14438
16132
  values: [