laymur 0.25.0 → 0.25.1

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.
@@ -1,3 +1,4 @@
1
+ import type { WebGLRenderer } from "three";
1
2
  import { UILayer } from "../layers/UILayer/UILayer.js";
2
3
  import type { UILayerElement } from "./shared.js";
3
4
  import type { UIExpression } from "./UIExpression.js";
@@ -8,6 +9,15 @@ import type { UIExpression } from "./UIExpression.js";
8
9
  * @throws If value is not finite or exceeds safe range
9
10
  */
10
11
  export declare function assertValidNumber(value: number, subject: string): void;
12
+ /**
13
+ * Validates a shader fits the vertex attribute budget of the device. A program over the budget
14
+ * fails to link, which three.js only logs, and its mesh is not drawn.
15
+ * @param renderer Renderer the shader is drawn with
16
+ * @param required Number of vertex attribute locations the shader uses
17
+ * @param subject Value name for error messages
18
+ * @throws If required exceeds the renderer's MAX_VERTEX_ATTRIBS
19
+ */
20
+ export declare function assertVertexAttributeBudget(renderer: WebGLRenderer, required: number, subject: string): void;
11
21
  /**
12
22
  * Validates value is positive (>= EPSILON).
13
23
  * @param value Number to validate
@@ -17,6 +17,22 @@ export function assertValidNumber(value, subject) {
17
17
  }
18
18
  }
19
19
  }
20
+ /**
21
+ * Validates a shader fits the vertex attribute budget of the device. A program over the budget
22
+ * fails to link, which three.js only logs, and its mesh is not drawn.
23
+ * @param renderer Renderer the shader is drawn with
24
+ * @param required Number of vertex attribute locations the shader uses
25
+ * @param subject Value name for error messages
26
+ * @throws If required exceeds the renderer's MAX_VERTEX_ATTRIBS
27
+ */
28
+ export function assertVertexAttributeBudget(renderer, required, subject) {
29
+ if (process.env.NODE_ENV !== "production") {
30
+ const available = renderer.capabilities.maxAttributes;
31
+ if (required > available) {
32
+ throw new Error(`${subject}: shader needs ${required} vertex attributes, the device supports ${available}`);
33
+ }
34
+ }
35
+ }
20
36
  /**
21
37
  * Validates value is positive (>= EPSILON).
22
38
  * @param value Number to validate
@@ -1,13 +1,18 @@
1
1
  import { InstancedBufferAttribute, InstancedBufferGeometry, ShaderMaterial } from "three";
2
2
  import { UITransparencyMode } from "../../UITransparencyMode.js";
3
3
  import type { GLProperty, UIProperty } from "../shared.js";
4
+ import type { PackedLayout } from "./UIGenericInstancedPlane.Layout.js";
4
5
  export declare const INSTANCED_PLANE_GEOMETRY: InstancedBufferGeometry;
5
6
  export declare const CAPACITY_STEP = 4;
6
7
  export declare const INITIAL_CAPACITY = 1;
7
8
  export declare function writePropertyToArray(value: UIProperty, array: Float32Array, offset: number): void;
8
- export declare function buildEmptyInstancedBufferAttribute(value: UIProperty, capacity: number): InstancedBufferAttribute;
9
- export declare function buildMaterial(source: string, uniformProperties: Record<string, GLProperty>, varyingProperties: Record<string, GLProperty>, transparency: UITransparencyMode): ShaderMaterial;
10
- export declare function reconstructValue(referenceValue: UIProperty, array: Float32Array, offset: number): UIProperty;
9
+ export declare const BUILTIN_TRANSFORM = "instanceTransform";
10
+ export declare const BUILTIN_VISIBILITY = "instanceVisibility";
11
+ export declare const BUILTIN_BLEND = "instanceBlend";
12
+ export declare const BUILTIN_HSL = "instanceHSL";
13
+ export declare function buildPlaneLayout(varyingProperties: Record<string, GLProperty>): PackedLayout;
14
+ export declare function buildPackedAttribute(itemSize: number, capacity: number): InstancedBufferAttribute;
15
+ export declare function buildMaterial(source: string, uniformProperties: Record<string, GLProperty>, layout: PackedLayout, transparency: UITransparencyMode): ShaderMaterial;
11
16
  /**
12
17
  * Shift buffer region within the same array.
13
18
  * Uses copyWithin for efficient memory moves with correct overlap handling.
@@ -2,6 +2,7 @@ import { DoubleSide, Float32BufferAttribute, InstancedBufferAttribute, Instanced
2
2
  import { UIColor } from "../../color/UIColor.js";
3
3
  import { UITransparencyMode } from "../../UITransparencyMode.js";
4
4
  import { buildGenericPlaneFragmentShader, resolveGLSLTypeInfo } from "../shared.js";
5
+ import { buildPackedAttributeDeclarations, buildPackedFieldSpec, buildPackedLayout, resolvePackedField, } from "./UIGenericInstancedPlane.Layout.js";
5
6
  export const INSTANCED_PLANE_GEOMETRY = (() => {
6
7
  const geometry = new InstancedBufferGeometry();
7
8
  const indices = new Uint16Array([0, 2, 1, 2, 3, 1]);
@@ -48,17 +49,50 @@ export function writePropertyToArray(value, array, offset) {
48
49
  array[offset] = value;
49
50
  }
50
51
  }
51
- export function buildEmptyInstancedBufferAttribute(value, capacity) {
52
- const info = resolveGLSLTypeInfo(value);
53
- if (!info.instantiable) {
54
- throw new Error(`buildEmptyInstancedBufferAttribute.value: cannot create instanced attribute for non-instantiable type`);
52
+ export const BUILTIN_TRANSFORM = "instanceTransform";
53
+ export const BUILTIN_VISIBILITY = "instanceVisibility";
54
+ export const BUILTIN_BLEND = "instanceBlend";
55
+ export const BUILTIN_HSL = "instanceHSL";
56
+ /**
57
+ * Builtin fields only the vertex shader reads. Every other field, builtin blend and HSL included,
58
+ * is passed on to the fragment shader as a p_* varying.
59
+ */
60
+ const BUILTIN_VERTEX_ONLY = [BUILTIN_TRANSFORM, BUILTIN_VISIBILITY];
61
+ /**
62
+ * The transform is a Matrix4, but the plane is a unit quad at z = 0 and every element transform
63
+ * is affine: the z basis column only ever multiplies 0 and the bottom row is always (0, 0, 0, 1).
64
+ * Only the x basis, y basis and translation columns are stored, without their w components, and
65
+ * the shader applies them as mat3(xBasis, yBasis, translation) * vec3(position.xy, 1.0).
66
+ * Translation z is the zIndex, see TRANSFORM_ZINDEX_OFFSET.
67
+ */
68
+ const BUILTIN_TRANSFORM_SPEC = {
69
+ name: BUILTIN_TRANSFORM,
70
+ glslTypeName: "mat3",
71
+ flatSize: 16,
72
+ columns: [
73
+ { sourceOffset: 0, size: 3 },
74
+ { sourceOffset: 4, size: 3 },
75
+ { sourceOffset: 12, size: 3 },
76
+ ],
77
+ };
78
+ export function buildPlaneLayout(varyingProperties) {
79
+ const specs = [
80
+ BUILTIN_TRANSFORM_SPEC,
81
+ buildPackedFieldSpec(BUILTIN_VISIBILITY, resolveGLSLTypeInfo("number")),
82
+ buildPackedFieldSpec(BUILTIN_BLEND, resolveGLSLTypeInfo("number")),
83
+ buildPackedFieldSpec(BUILTIN_HSL, resolveGLSLTypeInfo("Vector3")),
84
+ ];
85
+ for (const name in varyingProperties) {
86
+ specs.push(buildPackedFieldSpec(name, varyingProperties[name].glslTypeInfo));
55
87
  }
56
- return new InstancedBufferAttribute(new Float32Array(capacity * info.bufferSize), info.bufferSize);
88
+ return buildPackedLayout(specs);
89
+ }
90
+ export function buildPackedAttribute(itemSize, capacity) {
91
+ return new InstancedBufferAttribute(new Float32Array(capacity * itemSize), itemSize);
57
92
  }
58
- export function buildMaterial(source, uniformProperties, varyingProperties, transparency) {
93
+ export function buildMaterial(source, uniformProperties, layout, transparency) {
59
94
  const uniforms = {};
60
95
  const uniformDeclarations = [];
61
- const attributeDeclarations = [];
62
96
  const varyingDeclarations = [];
63
97
  const vertexAssignments = [];
64
98
  for (const name in uniformProperties) {
@@ -68,15 +102,17 @@ export function buildMaterial(source, uniformProperties, varyingProperties, tran
68
102
  };
69
103
  uniformDeclarations.push(`uniform ${glslTypeInfo.glslTypeName} p_${name};`);
70
104
  }
71
- for (const name in varyingProperties) {
72
- const { glslTypeInfo } = varyingProperties[name];
73
- attributeDeclarations.push(`attribute ${glslTypeInfo.glslTypeName} a_${name};`);
74
- varyingDeclarations.push(`varying ${glslTypeInfo.glslTypeName} p_${name};`);
75
- vertexAssignments.push(`p_${name} = a_${name};`);
105
+ for (const [name, field] of layout.fields) {
106
+ if (BUILTIN_VERTEX_ONLY.includes(name)) {
107
+ continue;
108
+ }
109
+ varyingDeclarations.push(`varying ${field.glslTypeName} p_${name};`);
110
+ vertexAssignments.push(`p_${name} = ${field.expression};`);
76
111
  }
112
+ const visibility = resolvePackedField(layout, BUILTIN_VISIBILITY).expression;
113
+ const transform = resolvePackedField(layout, BUILTIN_TRANSFORM).expression;
77
114
  const vertexShader = `
78
- // User attributes
79
- ${attributeDeclarations.join("\n")}
115
+ ${buildPackedAttributeDeclarations(layout).join("\n")}
80
116
 
81
117
  // Uniforms
82
118
  ${uniformDeclarations.join("\n")}
@@ -85,11 +121,10 @@ export function buildMaterial(source, uniformProperties, varyingProperties, tran
85
121
  varying vec3 p_position;
86
122
  varying vec2 p_uv;
87
123
 
88
- // User varyings
89
124
  ${varyingDeclarations.join("\n")}
90
125
 
91
126
  void main() {
92
- if (a_instanceVisibility < 0.5) {
127
+ if (${visibility} < 0.5) {
93
128
  gl_Position = vec4(2.0, 2.0, 2.0, 1.0);
94
129
  return;
95
130
  }
@@ -99,7 +134,8 @@ export function buildMaterial(source, uniformProperties, varyingProperties, tran
99
134
  p_position = position;
100
135
  p_uv = uv;
101
136
 
102
- gl_Position = projectionMatrix * a_instanceTransform * vec4(position, 1.0);
137
+ vec3 worldPosition = ${transform} * vec3(position.xy, 1.0);
138
+ gl_Position = projectionMatrix * vec4(worldPosition, 1.0);
103
139
  }
104
140
  `;
105
141
  const alphaTestValue = 0.0075;
@@ -119,34 +155,6 @@ export function buildMaterial(source, uniformProperties, varyingProperties, tran
119
155
  premultipliedAlpha,
120
156
  });
121
157
  }
122
- export function reconstructValue(referenceValue, array, offset) {
123
- if (typeof referenceValue === "number") {
124
- return array[offset];
125
- }
126
- if (referenceValue instanceof Vector2) {
127
- return new Vector2(array[offset], array[offset + 1]);
128
- }
129
- if (referenceValue instanceof Vector3) {
130
- return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
131
- }
132
- if (referenceValue instanceof Vector4) {
133
- return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
134
- }
135
- if (referenceValue instanceof UIColor) {
136
- return new UIColor().setGLSLColor(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
137
- }
138
- if (referenceValue instanceof Matrix3) {
139
- const matrix = new Matrix3();
140
- matrix.fromArray(array, offset);
141
- return matrix;
142
- }
143
- if (referenceValue instanceof Matrix4) {
144
- const matrix = new Matrix4();
145
- matrix.fromArray(array, offset);
146
- return matrix;
147
- }
148
- throw new Error(`reconstructValue.referenceValue: cannot reconstruct value for type`);
149
- }
150
158
  /**
151
159
  * Shift buffer region within the same array.
152
160
  * Uses copyWithin for efficient memory moves with correct overlap handling.
@@ -0,0 +1,52 @@
1
+ import type { GLTypeInfo } from "../shared.js";
2
+ export interface PackedColumnSpec {
3
+ sourceOffset: number;
4
+ size: number;
5
+ }
6
+ /**
7
+ * A field to be packed. Its value is flattened into flatSize floats, and each column takes size
8
+ * (1..4) of them starting at sourceOffset. Columns are listed in the order the GLSL constructor of
9
+ * glslTypeName takes them, which is how the vertex shader reassembles the field.
10
+ */
11
+ export interface PackedFieldSpec {
12
+ name: string;
13
+ glslTypeName: string;
14
+ flatSize: number;
15
+ columns: readonly PackedColumnSpec[];
16
+ }
17
+ /**
18
+ * A column placed into the packed attribute attributeIndex, starting at its component
19
+ * componentOffset.
20
+ */
21
+ export interface PackedColumn extends PackedColumnSpec {
22
+ attributeIndex: number;
23
+ componentOffset: number;
24
+ }
25
+ /**
26
+ * A field placed into packed attributes. Expression is the GLSL that reads it back from them in
27
+ * the vertex shader.
28
+ */
29
+ export interface PackedField {
30
+ glslTypeName: string;
31
+ columns: readonly PackedColumn[];
32
+ expression: string;
33
+ }
34
+ /**
35
+ * attributeSizes holds the item size (1..4) of each packed attribute. Two layouts with an equal
36
+ * signature place every field identically, so buffers can be copied between their planes as is.
37
+ */
38
+ export interface PackedLayout {
39
+ attributeSizes: readonly number[];
40
+ fields: ReadonlyMap<string, PackedField>;
41
+ signature: string;
42
+ }
43
+ export declare function packedAttributeName(attributeIndex: number): string;
44
+ export declare function buildPackedFieldSpec(name: string, glslTypeInfo: GLTypeInfo): PackedFieldSpec;
45
+ /**
46
+ * Places the columns of the given fields into packed attributes, first fit by decreasing size;
47
+ * with sizes of 1..4 and bins of 4 that takes the minimal number of attributes. Ties are broken by
48
+ * field name and column index, so the result does not depend on the order the fields come in.
49
+ */
50
+ export declare function buildPackedLayout(specs: readonly PackedFieldSpec[]): PackedLayout;
51
+ export declare function resolvePackedField(layout: PackedLayout, name: string): PackedField;
52
+ export declare function buildPackedAttributeDeclarations(layout: PackedLayout): string[];
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Packing of per-instance fields into vertex attributes.
3
+ *
4
+ * A vertex attribute location holds at most a vec4, and an attribute of any smaller type still
5
+ * takes a whole location, while devices commonly offer only 16 locations. Declaring one attribute
6
+ * per field therefore spends most of that budget on padding. Instead every field is cut into
7
+ * columns of 1..4 floats (a matrix into its columns, anything else into a single column), and the
8
+ * columns are bin-packed into as few attributes as possible. The vertex shader reassembles each
9
+ * field from swizzles of the packed attributes.
10
+ *
11
+ * The layout is a pure function of the set of fields, independent of their declaration order, so
12
+ * planes built from the same fields always share a layout and their buffers can be merged or split
13
+ * by plain copies.
14
+ */
15
+ const PACKED_ATTRIBUTE_CAPACITY = 4;
16
+ const PACKED_ATTRIBUTE_TYPES = ["float", "vec2", "vec3", "vec4"];
17
+ const SWIZZLE_COMPONENTS = "xyzw";
18
+ export function packedAttributeName(attributeIndex) {
19
+ return `a_packed${attributeIndex}`;
20
+ }
21
+ export function buildPackedFieldSpec(name, glslTypeInfo) {
22
+ const { glslTypeName, bufferSize, columnCount, instantiable } = glslTypeInfo;
23
+ if (!instantiable) {
24
+ throw new Error(`buildPackedFieldSpec.glslTypeInfo: "${name}" (${glslTypeName}) is not instantiable`);
25
+ }
26
+ const columnSize = bufferSize / columnCount;
27
+ const columns = [];
28
+ for (let i = 0; i < columnCount; i++) {
29
+ columns.push({ sourceOffset: i * columnSize, size: columnSize });
30
+ }
31
+ return { name, glslTypeName, flatSize: bufferSize, columns };
32
+ }
33
+ function compareNames(a, b) {
34
+ return a < b ? -1 : a > b ? 1 : 0;
35
+ }
36
+ /**
37
+ * Places the columns of the given fields into packed attributes, first fit by decreasing size;
38
+ * with sizes of 1..4 and bins of 4 that takes the minimal number of attributes. Ties are broken by
39
+ * field name and column index, so the result does not depend on the order the fields come in.
40
+ */
41
+ export function buildPackedLayout(specs) {
42
+ const entries = [];
43
+ const names = new Set();
44
+ for (const spec of specs) {
45
+ if (names.has(spec.name)) {
46
+ throw new Error(`buildPackedLayout.specs: duplicate field "${spec.name}"`);
47
+ }
48
+ names.add(spec.name);
49
+ for (let i = 0; i < spec.columns.length; i++) {
50
+ const { sourceOffset, size } = spec.columns[i];
51
+ if (size < 1 || size > PACKED_ATTRIBUTE_CAPACITY || sourceOffset + size > spec.flatSize) {
52
+ throw new Error(`buildPackedLayout.specs: invalid column ${i} of field "${spec.name}"`);
53
+ }
54
+ entries.push({ spec, columnIndex: i });
55
+ }
56
+ }
57
+ entries.sort((a, b) => b.spec.columns[b.columnIndex].size - a.spec.columns[a.columnIndex].size ||
58
+ compareNames(a.spec.name, b.spec.name) ||
59
+ a.columnIndex - b.columnIndex);
60
+ const attributeSizes = [];
61
+ const placements = new Map();
62
+ for (const { spec, columnIndex } of entries) {
63
+ const column = spec.columns[columnIndex];
64
+ let attributeIndex = attributeSizes.findIndex((used) => used + column.size <= PACKED_ATTRIBUTE_CAPACITY);
65
+ if (attributeIndex === -1) {
66
+ attributeIndex = attributeSizes.length;
67
+ attributeSizes.push(0);
68
+ }
69
+ let placed = placements.get(spec);
70
+ if (placed === undefined) {
71
+ placed = new Array(spec.columns.length);
72
+ placements.set(spec, placed);
73
+ }
74
+ placed[columnIndex] = {
75
+ sourceOffset: column.sourceOffset,
76
+ size: column.size,
77
+ attributeIndex,
78
+ componentOffset: attributeSizes[attributeIndex],
79
+ };
80
+ attributeSizes[attributeIndex] += column.size;
81
+ }
82
+ const fields = new Map();
83
+ const signatureParts = [];
84
+ for (const spec of [...specs].sort((a, b) => compareNames(a.name, b.name))) {
85
+ const columns = placements.get(spec) ?? [];
86
+ const columnExpressions = columns.map(({ attributeIndex, componentOffset, size }) => {
87
+ const attributeName = packedAttributeName(attributeIndex);
88
+ return size === attributeSizes[attributeIndex]
89
+ ? attributeName
90
+ : `${attributeName}.${SWIZZLE_COMPONENTS.slice(componentOffset, componentOffset + size)}`;
91
+ });
92
+ const expression = columnExpressions.length === 1
93
+ ? columnExpressions[0]
94
+ : `${spec.glslTypeName}(${columnExpressions.join(", ")})`;
95
+ fields.set(spec.name, { glslTypeName: spec.glslTypeName, columns, expression });
96
+ const sourceOffsets = columns.map(({ sourceOffset }) => sourceOffset).join(",");
97
+ signatureParts.push(`${spec.name}:${spec.glslTypeName}[${sourceOffsets}]=${expression}`);
98
+ }
99
+ return { attributeSizes, fields, signature: signatureParts.join(";") };
100
+ }
101
+ export function resolvePackedField(layout, name) {
102
+ const field = layout.fields.get(name);
103
+ if (field === undefined) {
104
+ throw new Error(`resolvePackedField.name: unknown field "${name}"`);
105
+ }
106
+ return field;
107
+ }
108
+ export function buildPackedAttributeDeclarations(layout) {
109
+ return layout.attributeSizes.map((size, index) => `attribute ${PACKED_ATTRIBUTE_TYPES[size - 1]} ${packedAttributeName(index)};`);
110
+ }
@@ -1,35 +1,25 @@
1
- import { InstancedBufferAttribute, Matrix4, Mesh, Vector3 } from "three";
2
- import { arePropertiesPartiallyCompatible, cloneGLProperties, cloneProperty, extractZIndexFromBuffer, resolveGLSLTypeInfo, resolvePropertyUniform, } from "../shared.js";
3
- import { buildEmptyInstancedBufferAttribute, buildMaterial, CAPACITY_STEP, copyBetweenBuffers, INITIAL_CAPACITY, INSTANCED_PLANE_GEOMETRY, reconstructValue, shiftBufferRegion, writePropertyToArray, } from "./UIGenericInstancedPlane.Internal.js";
1
+ import { Mesh } from "three";
2
+ import { assertVertexAttributeBudget } from "../../asserts.js";
3
+ import { arePropertiesPartiallyCompatible, cloneGLProperties, resolvePropertyUniform, TRANSFORM_ZINDEX_OFFSET, } from "../shared.js";
4
+ import { BUILTIN_BLEND, BUILTIN_HSL, BUILTIN_TRANSFORM, BUILTIN_VISIBILITY, buildMaterial, buildPackedAttribute, buildPlaneLayout, CAPACITY_STEP, copyBetweenBuffers, INITIAL_CAPACITY, INSTANCED_PLANE_GEOMETRY, shiftBufferRegion, writePropertyToArray, } from "./UIGenericInstancedPlane.Internal.js";
5
+ import { packedAttributeName, resolvePackedField } from "./UIGenericInstancedPlane.Layout.js";
6
+ const TEMP_FIELD_VALUES = new Float32Array(16);
4
7
  /**
5
8
  * Instanced shader plane mesh for batched rendering.
6
9
  *
7
10
  * Operates on indices, not handlers. Registry manages handler->index mapping.
8
11
  * Elements are ordered by zIndex (ascending) within the buffer.
9
12
  *
13
+ * Per-instance data (the builtin transform, visibility, blend and HSL plus every instantiable
14
+ * property) is packed into as few vertex attributes as possible, see
15
+ * UIGenericInstancedPlane.Layout.ts. The zIndex is read back from the packed transform.
16
+ *
10
17
  * @internal
11
18
  */
12
19
  export class UIGenericInstancedPlane extends Mesh {
13
20
  constructor(source, properties, transparency, initialCapacity = INITIAL_CAPACITY) {
14
21
  const uniformProperties = {};
15
- const varyingProperties = {
16
- instanceVisibility: {
17
- value: 1,
18
- glslTypeInfo: resolveGLSLTypeInfo("number"),
19
- },
20
- instanceTransform: {
21
- value: new Matrix4().identity(),
22
- glslTypeInfo: resolveGLSLTypeInfo("Matrix4"),
23
- },
24
- instanceBlend: {
25
- value: 1,
26
- glslTypeInfo: resolveGLSLTypeInfo("number"),
27
- },
28
- instanceHSL: {
29
- value: new Vector3(0, 1, 0),
30
- glslTypeInfo: resolveGLSLTypeInfo("Vector3"),
31
- },
32
- };
22
+ const varyingProperties = {};
33
23
  for (const name in properties) {
34
24
  const descriptor = properties[name];
35
25
  if (descriptor.glslTypeInfo.instantiable) {
@@ -39,9 +29,13 @@ export class UIGenericInstancedPlane extends Mesh {
39
29
  uniformProperties[name] = descriptor;
40
30
  }
41
31
  }
32
+ const layout = buildPlaneLayout(varyingProperties);
42
33
  const instancedGeometry = INSTANCED_PLANE_GEOMETRY.clone();
43
- const shaderMaterial = buildMaterial(source, uniformProperties, varyingProperties, transparency);
34
+ const shaderMaterial = buildMaterial(source, uniformProperties, layout, transparency);
44
35
  super(instancedGeometry, shaderMaterial);
36
+ this.onBeforeRenderInternal = (renderer) => {
37
+ assertVertexAttributeBudget(renderer, this.vertexAttributeCount, this.vertexAttributeSubject);
38
+ };
45
39
  this.frustumCulled = false;
46
40
  this.matrixAutoUpdate = false;
47
41
  this.matrixWorldAutoUpdate = false;
@@ -49,17 +43,32 @@ export class UIGenericInstancedPlane extends Mesh {
49
43
  this.transparency = transparency;
50
44
  this.instancedGeometry = instancedGeometry;
51
45
  this.shaderMaterial = shaderMaterial;
46
+ this.properties = properties;
52
47
  this.uniformProperties = uniformProperties;
53
- this.varyingProperties = varyingProperties;
54
- this.propertyBuffers = new Map();
48
+ this.layout = layout;
49
+ this.packedAttributes = [];
50
+ this.transformField = resolvePackedField(layout, BUILTIN_TRANSFORM);
51
+ this.visibilityField = resolvePackedField(layout, BUILTIN_VISIBILITY);
52
+ this.blendField = resolvePackedField(layout, BUILTIN_BLEND);
53
+ this.hslField = resolvePackedField(layout, BUILTIN_HSL);
54
+ const zIndexColumn = this.transformField.columns.find(({ sourceOffset, size }) => sourceOffset <= TRANSFORM_ZINDEX_OFFSET && TRANSFORM_ZINDEX_OFFSET < sourceOffset + size);
55
+ if (zIndexColumn === undefined) {
56
+ throw new Error(`UIGenericInstancedPlane.constructor: transform layout lacks the zIndex`);
57
+ }
58
+ this.zIndexAttributeIndex = zIndexColumn.attributeIndex;
59
+ this.zIndexComponentOffset =
60
+ zIndexColumn.componentOffset + TRANSFORM_ZINDEX_OFFSET - zIndexColumn.sourceOffset;
61
+ this.vertexAttributeCount =
62
+ Object.keys(INSTANCED_PLANE_GEOMETRY.attributes).length + layout.attributeSizes.length;
63
+ this.vertexAttributeSubject = `UIGenericInstancedPlane.onBeforeRender.properties (${Object.keys(varyingProperties).join(", ")})`;
64
+ this.onBeforeRender = this.onBeforeRenderInternal;
55
65
  this.capacity = Math.max(Math.ceil(initialCapacity / CAPACITY_STEP) * CAPACITY_STEP, CAPACITY_STEP);
56
66
  this.instancesCountInternal = 0;
57
67
  this.instancedGeometry.instanceCount = 0;
58
- for (const name in this.varyingProperties) {
59
- const { value } = this.varyingProperties[name];
60
- const attribute = buildEmptyInstancedBufferAttribute(value, this.capacity);
61
- this.instancedGeometry.setAttribute(`a_${name}`, attribute);
62
- this.propertyBuffers.set(name, attribute);
68
+ for (let i = 0; i < layout.attributeSizes.length; i++) {
69
+ const attribute = buildPackedAttribute(layout.attributeSizes[i], this.capacity);
70
+ this.instancedGeometry.setAttribute(packedAttributeName(i), attribute);
71
+ this.packedAttributes.push(attribute);
63
72
  }
64
73
  for (const name in this.uniformProperties) {
65
74
  const { value } = this.uniformProperties[name];
@@ -83,7 +92,11 @@ export class UIGenericInstancedPlane extends Mesh {
83
92
  if (index < this.instancesCountInternal) {
84
93
  this.shiftBuffersRight(index, 1);
85
94
  }
86
- this.writeToBuffers(index, properties, transform, visibility, blend, hsl);
95
+ this.writeField(index, this.transformField, transform.elements);
96
+ this.writeVisibility(index, visibility);
97
+ this.writeBlend(index, blend);
98
+ this.writeHSL(index, hsl);
99
+ this.writeProperties(index, properties);
87
100
  this.instancesCountInternal++;
88
101
  this.instancedGeometry.instanceCount = this.instancesCountInternal;
89
102
  }
@@ -105,141 +118,60 @@ export class UIGenericInstancedPlane extends Mesh {
105
118
  if (index < 0 || index >= this.instancesCountInternal) {
106
119
  throw new Error(`UIGenericInstancedPlane.setPropertiesAt.index: out of bounds (index=${index}, count=${this.instancesCountInternal})`);
107
120
  }
108
- for (const name in properties) {
109
- const { value, glslTypeInfo } = properties[name];
110
- if (glslTypeInfo.instantiable) {
111
- const attribute = this.resolveAttribute(name);
112
- const offset = index * attribute.itemSize;
113
- writePropertyToArray(value, attribute.array, offset);
114
- attribute.needsUpdate = true;
115
- }
116
- else {
117
- const uniform = resolvePropertyUniform(name, this.shaderMaterial);
118
- uniform.value = value;
119
- this.shaderMaterial.uniformsNeedUpdate = true;
120
- }
121
- }
121
+ this.writeProperties(index, properties);
122
122
  }
123
123
  /** Update transform at given index */
124
124
  setTransformAt(index, transform) {
125
125
  if (index < 0 || index >= this.instancesCountInternal) {
126
126
  throw new Error(`UIGenericInstancedPlane.setTransformAt.index: out of bounds (index=${index}, count=${this.instancesCountInternal})`);
127
127
  }
128
- const attribute = this.resolveAttribute("instanceTransform");
129
- const array = attribute.array;
130
- const offset = index * 16;
131
- const elements = transform.elements;
132
- for (let j = 0; j < 16; j++) {
133
- array[offset + j] = elements[j];
134
- }
135
- attribute.needsUpdate = true;
128
+ this.writeField(index, this.transformField, transform.elements);
136
129
  }
137
130
  /** Update visibility at given index */
138
131
  setVisibilityAt(index, visible) {
139
132
  if (index < 0 || index >= this.instancesCountInternal) {
140
133
  throw new Error(`UIGenericInstancedPlane.setVisibilityAt.index: out of bounds (index=${index}, count=${this.instancesCountInternal})`);
141
134
  }
142
- const attribute = this.resolveAttribute("instanceVisibility");
143
- const array = attribute.array;
144
- array[index] = visible ? 1 : 0;
145
- attribute.needsUpdate = true;
135
+ this.writeVisibility(index, visible);
146
136
  }
147
137
  /** Update blend factor at given index (1 = normal over, 0 = additive) */
148
138
  setBlendAt(index, blend) {
149
139
  if (index < 0 || index >= this.instancesCountInternal) {
150
140
  throw new Error(`UIGenericInstancedPlane.setBlendAt.index: out of bounds (index=${index}, count=${this.instancesCountInternal})`);
151
141
  }
152
- const attribute = this.resolveAttribute("instanceBlend");
153
- const array = attribute.array;
154
- array[index] = blend;
155
- attribute.needsUpdate = true;
142
+ this.writeBlend(index, blend);
156
143
  }
157
144
  /** Update HSL adjustment at given index (hue in turns, saturation multiplier, lightness offset) */
158
145
  setHSLAt(index, hsl) {
159
146
  if (index < 0 || index >= this.instancesCountInternal) {
160
147
  throw new Error(`UIGenericInstancedPlane.setHSLAt.index: out of bounds (index=${index}, count=${this.instancesCountInternal})`);
161
148
  }
162
- const attribute = this.resolveAttribute("instanceHSL");
163
- const array = attribute.array;
164
- const offset = index * 3;
165
- array[offset] = hsl.h;
166
- array[offset + 1] = hsl.s;
167
- array[offset + 2] = hsl.l;
168
- attribute.needsUpdate = true;
169
- }
170
- /**
171
- * Extract complete instance data at given index.
172
- * Returns cloned data safe for external use.
173
- */
174
- extractDataAt(index) {
175
- if (index < 0 || index >= this.instancesCountInternal) {
176
- throw new Error(`UIGenericInstancedPlane.extractDataAt.index: out of bounds (index=${index}, count=${this.instancesCountInternal})`);
177
- }
178
- const properties = {};
179
- for (const name in this.uniformProperties) {
180
- const prop = this.uniformProperties[name];
181
- properties[name] = {
182
- value: cloneProperty(prop.value),
183
- glslTypeInfo: prop.glslTypeInfo,
184
- };
185
- }
186
- for (const name in this.varyingProperties) {
187
- if (name === "instanceVisibility" ||
188
- name === "instanceTransform" ||
189
- name === "instanceBlend" ||
190
- name === "instanceHSL") {
191
- continue;
192
- }
193
- const { value, glslTypeInfo } = this.varyingProperties[name];
194
- const attribute = this.propertyBuffers.get(name);
195
- const array = attribute.array;
196
- const offset = index * attribute.itemSize;
197
- properties[name] = {
198
- value: reconstructValue(value, array, offset),
199
- glslTypeInfo,
200
- };
201
- }
202
- const transformAttribute = this.propertyBuffers.get("instanceTransform");
203
- const transformArray = transformAttribute.array;
204
- const transform = new Matrix4();
205
- transform.fromArray(transformArray, index * 16);
206
- const visibilityAttribute = this.propertyBuffers.get("instanceVisibility");
207
- const visibilityArray = visibilityAttribute.array;
208
- const visibility = visibilityArray[index] >= 0.5;
209
- return {
210
- source: this.source,
211
- properties,
212
- transform,
213
- visibility,
214
- transparency: this.transparency,
215
- };
149
+ this.writeHSL(index, hsl);
216
150
  }
217
151
  /** Get zIndex at given index (from transform buffer) */
218
152
  getZIndexAt(index) {
219
153
  if (index < 0 || index >= this.instancesCountInternal) {
220
154
  throw new Error(`UIGenericInstancedPlane.getZIndexAt.index: out of bounds (index=${index}, count=${this.instancesCountInternal})`);
221
155
  }
222
- const attribute = this.propertyBuffers.get("instanceTransform");
223
- return extractZIndexFromBuffer(attribute.array, index);
156
+ const attribute = this.packedAttributes[this.zIndexAttributeIndex];
157
+ return attribute.array[index * attribute.itemSize + this.zIndexComponentOffset];
224
158
  }
225
159
  /**
226
160
  * Merge another instanced plane into this one (append).
227
161
  * Other plane becomes empty after merge.
228
162
  */
229
163
  merge(other) {
164
+ if (other.layout.signature !== this.layout.signature) {
165
+ throw new Error(`UIGenericInstancedPlane.merge.other: incompatible attribute layout`);
166
+ }
230
167
  if (other.instancesCountInternal === 0) {
231
168
  return;
232
169
  }
233
170
  this.ensureCapacity(this.instancesCountInternal + other.instancesCountInternal);
234
- for (const [name, thisAttribute] of this.propertyBuffers) {
235
- const otherAttribute = other.propertyBuffers.get(name);
236
- if (!otherAttribute) {
237
- throw new Error(`UIGenericInstancedPlane.merge: missing attribute ${name} in source`);
238
- }
171
+ for (let i = 0; i < this.packedAttributes.length; i++) {
172
+ const thisAttribute = this.packedAttributes[i];
239
173
  const itemSize = thisAttribute.itemSize;
240
- const srcArray = otherAttribute.array;
241
- const dstArray = thisAttribute.array;
242
- copyBetweenBuffers(srcArray, 0, dstArray, this.instancesCountInternal * itemSize, other.instancesCountInternal * itemSize);
174
+ copyBetweenBuffers(other.packedAttributes[i].array, 0, thisAttribute.array, this.instancesCountInternal * itemSize, other.instancesCountInternal * itemSize);
243
175
  thisAttribute.needsUpdate = true;
244
176
  }
245
177
  this.instancesCountInternal += other.instancesCountInternal;
@@ -257,19 +189,12 @@ export class UIGenericInstancedPlane extends Mesh {
257
189
  throw new Error(`UIGenericInstancedPlane.split.atIndex: must be in range (0, count) (atIndex=${atIndex}, count=${this.instancesCountInternal})`);
258
190
  }
259
191
  const tailCount = this.instancesCountInternal - atIndex;
260
- const newPlane = new UIGenericInstancedPlane(this.source, cloneGLProperties({
261
- ...this.uniformProperties,
262
- ...this.varyingProperties,
263
- }), this.transparency, tailCount);
264
- for (const [name, thisAttribute] of this.propertyBuffers) {
265
- const newAttribute = newPlane.propertyBuffers.get(name);
266
- if (!newAttribute) {
267
- throw new Error(`UIGenericInstancedPlane.split: missing attribute ${name} in new plane`);
268
- }
192
+ const newPlane = new UIGenericInstancedPlane(this.source, cloneGLProperties(this.properties), this.transparency, tailCount);
193
+ for (let i = 0; i < this.packedAttributes.length; i++) {
194
+ const thisAttribute = this.packedAttributes[i];
195
+ const newAttribute = newPlane.packedAttributes[i];
269
196
  const itemSize = thisAttribute.itemSize;
270
- const srcArray = thisAttribute.array;
271
- const dstArray = newAttribute.array;
272
- copyBetweenBuffers(srcArray, atIndex * itemSize, dstArray, 0, tailCount * itemSize);
197
+ copyBetweenBuffers(thisAttribute.array, atIndex * itemSize, newAttribute.array, 0, tailCount * itemSize);
273
198
  newAttribute.needsUpdate = true;
274
199
  }
275
200
  newPlane.instancesCountInternal = tailCount;
@@ -282,18 +207,20 @@ export class UIGenericInstancedPlane extends Mesh {
282
207
  * Check if this plane can accept elements with given parameters.
283
208
  */
284
209
  isCompatibleWith(source, properties, transparency) {
285
- if (this.source !== source) {
286
- return false;
287
- }
288
- if (this.transparency !== transparency) {
289
- return false;
290
- }
291
- const result = arePropertiesPartiallyCompatible({ ...this.uniformProperties, ...this.varyingProperties }, properties);
292
- return result;
210
+ return (this.source === source &&
211
+ this.transparency === transparency &&
212
+ arePropertiesPartiallyCompatible(this.properties, properties));
293
213
  }
294
- /** Get all properties configuration (for compatibility checks) */
295
- getProperties() {
296
- return { ...this.uniformProperties, ...this.varyingProperties };
214
+ /**
215
+ * Check if another plane can be merged into this one: same shader source and transparency, same
216
+ * attribute layout and the same uniform values.
217
+ */
218
+ canMerge(other) {
219
+ return (this.source === other.source &&
220
+ this.transparency === other.transparency &&
221
+ this.layout.signature === other.layout.signature &&
222
+ arePropertiesPartiallyCompatible(this.uniformProperties, other.uniformProperties) &&
223
+ arePropertiesPartiallyCompatible(other.uniformProperties, this.uniformProperties));
297
224
  }
298
225
  /** Remove all instances, reset to empty state */
299
226
  clearInstances() {
@@ -304,29 +231,32 @@ export class UIGenericInstancedPlane extends Mesh {
304
231
  destroy() {
305
232
  this.instancedGeometry.dispose();
306
233
  this.shaderMaterial.dispose();
307
- this.propertyBuffers.clear();
234
+ this.packedAttributes.length = 0;
308
235
  }
309
236
  ensureCapacity(requiredCapacity) {
310
237
  if (requiredCapacity <= this.capacity) {
311
238
  return;
312
239
  }
313
240
  const newCapacity = Math.ceil(requiredCapacity / CAPACITY_STEP) * CAPACITY_STEP;
314
- for (const [name, oldAttribute] of this.propertyBuffers) {
315
- const itemSize = oldAttribute.itemSize;
316
- const newArray = new Float32Array(newCapacity * itemSize);
317
- newArray.set(oldAttribute.array);
318
- const newAttribute = new InstancedBufferAttribute(newArray, itemSize);
319
- this.instancedGeometry.setAttribute(`a_${name}`, newAttribute);
320
- this.propertyBuffers.set(name, newAttribute);
241
+ for (let i = 0; i < this.packedAttributes.length; i++) {
242
+ const oldAttribute = this.packedAttributes[i];
243
+ const newAttribute = buildPackedAttribute(oldAttribute.itemSize, newCapacity);
244
+ newAttribute.array.set(oldAttribute.array);
245
+ this.instancedGeometry.setAttribute(packedAttributeName(i), newAttribute);
246
+ this.packedAttributes[i] = newAttribute;
321
247
  }
322
248
  this.capacity = newCapacity;
249
+ // three.js caches the drawable instance count from the attribute sizes on the first render and
250
+ // only resets it on dispose; without this a grown plane keeps drawing the old capacity
251
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- private three.js field
252
+ this.instancedGeometry._maxInstanceCount = newCapacity;
323
253
  }
324
254
  shiftBuffersRight(fromIndex, delta) {
325
255
  const elementsToMove = this.instancesCountInternal - fromIndex;
326
256
  if (elementsToMove <= 0) {
327
257
  return;
328
258
  }
329
- for (const attribute of this.propertyBuffers.values()) {
259
+ for (const attribute of this.packedAttributes) {
330
260
  shiftBufferRegion(attribute.array, attribute.itemSize, fromIndex, elementsToMove, delta);
331
261
  attribute.needsUpdate = true;
332
262
  }
@@ -336,42 +266,17 @@ export class UIGenericInstancedPlane extends Mesh {
336
266
  if (elementsToMove <= 0) {
337
267
  return;
338
268
  }
339
- for (const attribute of this.propertyBuffers.values()) {
269
+ for (const attribute of this.packedAttributes) {
340
270
  shiftBufferRegion(attribute.array, attribute.itemSize, fromIndex, elementsToMove, -delta);
341
271
  attribute.needsUpdate = true;
342
272
  }
343
273
  }
344
- writeToBuffers(index, properties, transform, visibility, blend, hsl) {
345
- const visibilityAttribute = this.resolveAttribute("instanceVisibility");
346
- visibilityAttribute.array[index] = visibility ? 1 : 0;
347
- visibilityAttribute.needsUpdate = true;
348
- const blendAttribute = this.resolveAttribute("instanceBlend");
349
- blendAttribute.array[index] = blend;
350
- blendAttribute.needsUpdate = true;
351
- const hslAttribute = this.resolveAttribute("instanceHSL");
352
- const hslArray = hslAttribute.array;
353
- const hslOffset = index * 3;
354
- hslArray[hslOffset] = hsl.h;
355
- hslArray[hslOffset + 1] = hsl.s;
356
- hslArray[hslOffset + 2] = hsl.l;
357
- hslAttribute.needsUpdate = true;
358
- const transformAttribute = this.resolveAttribute("instanceTransform");
359
- const transformArray = transformAttribute.array;
360
- const transformOffset = index * 16;
361
- const elements = transform.elements;
362
- for (let j = 0; j < 16; j++) {
363
- transformArray[transformOffset + j] = elements[j];
364
- }
365
- transformAttribute.needsUpdate = true;
274
+ writeProperties(index, properties) {
366
275
  for (const name in properties) {
367
276
  const { value, glslTypeInfo } = properties[name];
368
277
  if (glslTypeInfo.instantiable) {
369
- const attribute = this.propertyBuffers.get(name);
370
- if (attribute) {
371
- const offset = index * attribute.itemSize;
372
- writePropertyToArray(value, attribute.array, offset);
373
- attribute.needsUpdate = true;
374
- }
278
+ writePropertyToArray(value, TEMP_FIELD_VALUES, 0);
279
+ this.writeField(index, resolvePackedField(this.layout, name), TEMP_FIELD_VALUES);
375
280
  }
376
281
  else {
377
282
  const uniform = resolvePropertyUniform(name, this.shaderMaterial);
@@ -380,11 +285,29 @@ export class UIGenericInstancedPlane extends Mesh {
380
285
  }
381
286
  }
382
287
  }
383
- resolveAttribute(name) {
384
- const attribute = this.propertyBuffers.get(name);
385
- if (attribute === undefined) {
386
- throw new Error(`UIGenericInstancedPlane.resolveAttribute.name: unknown attribute "${name}"`);
288
+ writeVisibility(index, visibility) {
289
+ TEMP_FIELD_VALUES[0] = visibility ? 1 : 0;
290
+ this.writeField(index, this.visibilityField, TEMP_FIELD_VALUES);
291
+ }
292
+ writeBlend(index, blend) {
293
+ TEMP_FIELD_VALUES[0] = blend;
294
+ this.writeField(index, this.blendField, TEMP_FIELD_VALUES);
295
+ }
296
+ writeHSL(index, hsl) {
297
+ TEMP_FIELD_VALUES[0] = hsl.h;
298
+ TEMP_FIELD_VALUES[1] = hsl.s;
299
+ TEMP_FIELD_VALUES[2] = hsl.l;
300
+ this.writeField(index, this.hslField, TEMP_FIELD_VALUES);
301
+ }
302
+ writeField(index, field, values) {
303
+ for (const { attributeIndex, componentOffset, sourceOffset, size } of field.columns) {
304
+ const attribute = this.packedAttributes[attributeIndex];
305
+ const array = attribute.array;
306
+ const offset = index * attribute.itemSize + componentOffset;
307
+ for (let i = 0; i < size; i++) {
308
+ array[offset + i] = values[sourceOffset + i];
309
+ }
310
+ attribute.needsUpdate = true;
387
311
  }
388
- return attribute;
389
312
  }
390
313
  }
@@ -396,7 +396,7 @@ export class UIPlaneRegistry {
396
396
  const rightMinZ = right.getZIndexAt(0);
397
397
  if (leftMaxZ < rightMinZ &&
398
398
  !this.hasObjectBetween(leftMaxZ, rightMinZ) &&
399
- left.isCompatibleWith(right.source, right.getProperties(), right.transparency)) {
399
+ left.canMerge(right)) {
400
400
  const indexOffset = left.instancesCount;
401
401
  left.merge(right);
402
402
  this.remapHandlersAfterMerge(right, left, indexOffset);
@@ -1,6 +1,5 @@
1
1
  import type { IUniform, ShaderMaterial } from "three";
2
2
  import { Matrix3, Matrix4, Texture, Vector2, Vector3, Vector4 } from "three";
3
- import type { UITransparencyMode } from "../UITransparencyMode.js";
4
3
  import { UIColor } from "../color/UIColor.js";
5
4
  export type UIProperty = Texture | UIColor | Vector2 | Vector3 | Vector4 | Matrix3 | Matrix4 | number;
6
5
  export type UIPropertyName = "Texture" | "UIColor" | "Vector2" | "Vector3" | "Vector4" | "Matrix3" | "Matrix4" | "number";
@@ -10,20 +9,18 @@ export type UIPropertyCopyFrom = UIColor & Vector2 & Vector3 & Vector4 & Matrix3
10
9
  export interface GLTypeInfo {
11
10
  glslTypeName: string;
12
11
  bufferSize: number;
12
+ /**
13
+ * Number of columns, each holding bufferSize / columnCount floats: one per column of a matrix,
14
+ * one for a scalar or vector, none for a non-instantiable type. As a vertex attribute the type
15
+ * takes one location per column.
16
+ */
17
+ columnCount: number;
13
18
  instantiable: boolean;
14
19
  }
15
20
  export interface GLProperty {
16
21
  value: UIProperty;
17
22
  glslTypeInfo: GLTypeInfo;
18
23
  }
19
- export interface PlaneData {
20
- source: string;
21
- properties: Record<string, GLProperty>;
22
- transform: Matrix4;
23
- visibility: boolean;
24
- transparency: UITransparencyMode;
25
- }
26
- /** Per-instance HSL adjustment in shader space (matches the instanceHSL attribute). */
27
24
  export interface HSLAdjustment {
28
25
  /** Hue shift in turns (degrees / 360); wrapped with fract() in the shader. */
29
26
  h: number;
@@ -39,8 +36,11 @@ export declare function convertUIPropertiesToGLProperties(uiProperties: Record<s
39
36
  export declare function cloneProperty<T extends UIProperty>(property: T): T;
40
37
  export declare function cloneProperties(properties: Record<string, UIProperty>): Record<string, UIProperty>;
41
38
  export declare function cloneGLProperties(properties: Record<string, GLProperty>): Record<string, GLProperty>;
39
+ /**
40
+ * Index of the zIndex in Matrix4.elements: the zIndex is carried in translation z rather than as a
41
+ * separate field.
42
+ */
43
+ export declare const TRANSFORM_ZINDEX_OFFSET = 14;
42
44
  /** Extracts zIndex from transform matrix (translation.z component) */
43
45
  export declare function extractZIndex(transform: Matrix4): number;
44
- /** Extracts zIndex from transform buffer at given instance index */
45
- export declare function extractZIndexFromBuffer(buffer: Float32Array, instanceIndex: number): number;
46
46
  export declare function buildGenericPlaneFragmentShader(uniformDeclarations: string[], varyingDeclarations: string[], source: string, alphaTestValue: number, usePremultipliedAlpha: boolean): string;
@@ -4,36 +4,43 @@ import { checkSRGBSupport } from "../webglCapabilities.js";
4
4
  const GLSL_TYPE_INFO_FLOAT = Object.freeze({
5
5
  glslTypeName: "float",
6
6
  bufferSize: 1,
7
+ columnCount: 1,
7
8
  instantiable: true,
8
9
  });
9
10
  const GLSL_TYPE_INFO_SAMPLER2D = Object.freeze({
10
11
  glslTypeName: "sampler2D",
11
12
  bufferSize: -1,
13
+ columnCount: 0,
12
14
  instantiable: false,
13
15
  });
14
16
  const GLSL_TYPE_INFO_VEC2 = Object.freeze({
15
17
  glslTypeName: "vec2",
16
18
  bufferSize: 2,
19
+ columnCount: 1,
17
20
  instantiable: true,
18
21
  });
19
22
  const GLSL_TYPE_INFO_VEC3 = Object.freeze({
20
23
  glslTypeName: "vec3",
21
24
  bufferSize: 3,
25
+ columnCount: 1,
22
26
  instantiable: true,
23
27
  });
24
28
  const GLSL_TYPE_INFO_VEC4 = Object.freeze({
25
29
  glslTypeName: "vec4",
26
30
  bufferSize: 4,
31
+ columnCount: 1,
27
32
  instantiable: true,
28
33
  });
29
34
  const GLSL_TYPE_INFO_MAT3 = Object.freeze({
30
35
  glslTypeName: "mat3",
31
36
  bufferSize: 9,
37
+ columnCount: 3,
32
38
  instantiable: true,
33
39
  });
34
40
  const GLSL_TYPE_INFO_MAT4 = Object.freeze({
35
41
  glslTypeName: "mat4",
36
42
  bufferSize: 16,
43
+ columnCount: 4,
37
44
  instantiable: true,
38
45
  });
39
46
  export function resolveGLSLTypeInfo(value) {
@@ -167,13 +174,14 @@ export function cloneGLProperties(properties) {
167
174
  }
168
175
  return result;
169
176
  }
177
+ /**
178
+ * Index of the zIndex in Matrix4.elements: the zIndex is carried in translation z rather than as a
179
+ * separate field.
180
+ */
181
+ export const TRANSFORM_ZINDEX_OFFSET = 14;
170
182
  /** Extracts zIndex from transform matrix (translation.z component) */
171
183
  export function extractZIndex(transform) {
172
- return transform.elements[14];
173
- }
174
- /** Extracts zIndex from transform buffer at given instance index */
175
- export function extractZIndexFromBuffer(buffer, instanceIndex) {
176
- return buffer[instanceIndex * 16 + 14];
184
+ return transform.elements[TRANSFORM_ZINDEX_OFFSET];
177
185
  }
178
186
  export function buildGenericPlaneFragmentShader(uniformDeclarations, varyingDeclarations, source, alphaTestValue, usePremultipliedAlpha) {
179
187
  return `
@@ -5,6 +5,8 @@ export declare class UIInstancedParticle extends Mesh {
5
5
  readonly propertyBuffers: Record<string, InstancedBufferAttribute>;
6
6
  private readonly instancedGeometry;
7
7
  private readonly shaderMaterial;
8
+ private readonly vertexAttributeCount;
9
+ private readonly vertexAttributeSubject;
8
10
  private capacity;
9
11
  constructor(sources: string[], uniforms: Record<string, GLProperty>, varyings: Record<string, GLTypeInfo>, expectedCapacity: number, capacityStep: number);
10
12
  get instanceCount(): number;
@@ -14,4 +16,5 @@ export declare class UIInstancedParticle extends Mesh {
14
16
  drop(): void;
15
17
  destroy(): void;
16
18
  private ensureCapacity;
19
+ private readonly onBeforeRenderInternal;
17
20
  }
@@ -1,4 +1,5 @@
1
1
  import { InstancedBufferAttribute, Mesh, StreamDrawUsage } from "three";
2
+ import { assertVertexAttributeBudget } from "../../core/miscellaneous/asserts.js";
2
3
  import { resolvePropertyUniform } from "../../core/miscellaneous/generic-plane/shared.js";
3
4
  import { BUILTIN_OFFSET_AGE, BUILTIN_OFFSET_LIFETIME } from "../miscellaneous/miscellaneous.js";
4
5
  import { buildParticleMaterial, INSTANCED_PARTICLE_GEOMETRY } from "./UIInstancedParticle.Internal.js";
@@ -9,6 +10,9 @@ export class UIInstancedParticle extends Mesh {
9
10
  super(instancedGeometry, shaderMaterial);
10
11
  this.capacityStep = capacityStep;
11
12
  this.propertyBuffers = {};
13
+ this.onBeforeRenderInternal = (renderer) => {
14
+ assertVertexAttributeBudget(renderer, this.vertexAttributeCount, this.vertexAttributeSubject);
15
+ };
12
16
  this.frustumCulled = false;
13
17
  this.matrixAutoUpdate = false;
14
18
  this.matrixWorldAutoUpdate = false;
@@ -16,6 +20,13 @@ export class UIInstancedParticle extends Mesh {
16
20
  this.instancedGeometry.instanceCount = 0;
17
21
  this.shaderMaterial = shaderMaterial;
18
22
  this.capacity = Math.max(Math.ceil(expectedCapacity / this.capacityStep) * this.capacityStep, this.capacityStep);
23
+ let vertexAttributeCount = Object.keys(INSTANCED_PARTICLE_GEOMETRY.attributes).length;
24
+ for (const name in varyings) {
25
+ vertexAttributeCount += varyings[name].columnCount;
26
+ }
27
+ this.vertexAttributeCount = vertexAttributeCount;
28
+ this.vertexAttributeSubject = `UIInstancedParticle.onBeforeRender.properties (${Object.keys(varyings).join(", ")})`;
29
+ this.onBeforeRender = this.onBeforeRenderInternal;
19
30
  for (const name in varyings) {
20
31
  const { bufferSize } = varyings[name];
21
32
  const attribute = new InstancedBufferAttribute(new Float32Array(this.capacity * bufferSize), bufferSize);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "laymur",
3
- "version": "0.25.0",
3
+ "version": "0.25.1",
4
4
  "description": "Constraint-based UI library for Three.js mobile advertisements",
5
5
  "keywords": [
6
6
  "ui",