laymur 0.25.1 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/README.md +41 -5
  2. package/dist/core/elements/UIAnchor/UIAnchor.d.ts +2 -2
  3. package/dist/core/elements/UIAnchor/UIAnchor.js +3 -2
  4. package/dist/core/elements/UIDummy/UIDummy.Internal.d.ts +3 -0
  5. package/dist/core/elements/UIDummy/UIDummy.d.ts +32 -0
  6. package/dist/core/elements/UIDummy/UIDummy.js +101 -2
  7. package/dist/core/elements/UIElement/UIElement.d.ts +23 -1
  8. package/dist/core/elements/UIElement/UIElement.js +50 -3
  9. package/dist/core/elements/UIGraphics/UIGraphics.js +2 -2
  10. package/dist/core/elements/UIProgress/UIProgress.js +2 -5
  11. package/dist/core/elements/UIScene/UIScene.js +3 -2
  12. package/dist/core/elements/UIText/UIText.js +2 -2
  13. package/dist/core/index.d.ts +53 -4
  14. package/dist/core/index.js +15 -2
  15. package/dist/core/layers/UILayer/UILayer.d.ts +11 -1
  16. package/dist/core/layers/UILayer/UILayer.js +37 -2
  17. package/dist/core/miscellaneous/UIAffineMatrix3.d.ts +13 -0
  18. package/dist/core/miscellaneous/UIAffineMatrix3.js +13 -0
  19. package/dist/core/miscellaneous/area/UIArea.d.ts +10 -1
  20. package/dist/core/miscellaneous/area/UIArea.js +4 -1
  21. package/dist/core/miscellaneous/area/UIAreaCircle.d.ts +1 -0
  22. package/dist/core/miscellaneous/area/UIAreaCircle.js +0 -1
  23. package/dist/core/miscellaneous/area/UIAreaPolygon.d.ts +1 -0
  24. package/dist/core/miscellaneous/area/UIAreaPolygon.js +0 -1
  25. package/dist/core/miscellaneous/area/UIAreaRectangle.d.ts +1 -0
  26. package/dist/core/miscellaneous/area/UIAreaRectangle.js +0 -1
  27. package/dist/core/miscellaneous/area/UIAreaRoundedRectangle.d.ts +1 -0
  28. package/dist/core/miscellaneous/area/UIAreaRoundedRectangle.js +0 -1
  29. package/dist/core/miscellaneous/asserts.d.ts +9 -0
  30. package/dist/core/miscellaneous/asserts.js +16 -0
  31. package/dist/core/miscellaneous/color/UIColor.js +1 -0
  32. package/dist/core/miscellaneous/generic-plane/UIGenericInstancedPlane/UIGenericInstancedPlane.Internal.d.ts +17 -3
  33. package/dist/core/miscellaneous/generic-plane/UIGenericInstancedPlane/UIGenericInstancedPlane.Internal.js +88 -26
  34. package/dist/core/miscellaneous/generic-plane/UIGenericInstancedPlane/UIGenericInstancedPlane.Layout.d.ts +9 -0
  35. package/dist/core/miscellaneous/generic-plane/UIGenericInstancedPlane/UIGenericInstancedPlane.Layout.js +29 -6
  36. package/dist/core/miscellaneous/generic-plane/UIGenericInstancedPlane/UIGenericInstancedPlane.js +51 -11
  37. package/dist/core/miscellaneous/generic-plane/UIGenericPlaneRegistry/UIGenericPlaneRegistry.Internal.d.ts +2 -0
  38. package/dist/core/miscellaneous/generic-plane/UIGenericPlaneRegistry/UIGenericPlaneRegistry.js +47 -6
  39. package/dist/core/miscellaneous/generic-plane/shared.d.ts +15 -3
  40. package/dist/core/miscellaneous/generic-plane/shared.js +38 -7
  41. package/dist/core/miscellaneous/generic-plane/varyingPacking.d.ts +46 -0
  42. package/dist/core/miscellaneous/generic-plane/varyingPacking.js +170 -0
  43. package/dist/core/miscellaneous/mask/UIMask.Internal.d.ts +61 -0
  44. package/dist/core/miscellaneous/mask/UIMask.Internal.js +56 -0
  45. package/dist/core/miscellaneous/mask/UIMask.d.ts +84 -0
  46. package/dist/core/miscellaneous/mask/UIMask.js +265 -0
  47. package/dist/core/miscellaneous/mask/UIMaskMaterialPatch.d.ts +50 -0
  48. package/dist/core/miscellaneous/mask/UIMaskMaterialPatch.js +233 -0
  49. package/dist/core/miscellaneous/mask-function/UIProgressMaskFunction.d.ts +10 -1
  50. package/dist/core/miscellaneous/mask-function/UIProgressMaskFunction.js +7 -1
  51. package/dist/core/miscellaneous/mask-function/UIProgressMaskFunctionCircular.d.ts +2 -0
  52. package/dist/core/miscellaneous/mask-function/UIProgressMaskFunctionCircular.js +0 -1
  53. package/dist/core/miscellaneous/mask-function/UIProgressMaskFunctionDirectional.d.ts +2 -0
  54. package/dist/core/miscellaneous/mask-function/UIProgressMaskFunctionDirectional.js +0 -1
  55. package/dist/core/miscellaneous/micro/UIMicro.Internal.d.ts +3 -0
  56. package/dist/core/miscellaneous/micro/UIMicro.Internal.js +1 -0
  57. package/dist/core/miscellaneous/micro/UIMicro.d.ts +18 -1
  58. package/dist/core/miscellaneous/micro/UIMicro.js +23 -2
  59. package/dist/core/miscellaneous/resize-policy/UIResizePolicy.d.ts +16 -1
  60. package/dist/core/miscellaneous/resize-policy/UIResizePolicy.js +8 -2
  61. package/dist/core/miscellaneous/texture/UITextureView.d.ts +2 -1
  62. package/dist/core/miscellaneous/texture/UITextureView.js +3 -2
  63. package/dist/core/shaders/UIMask.d.ts +15 -0
  64. package/dist/core/shaders/UIMask.js +45 -0
  65. package/dist/core/wrappers/UIInputWrapper/UIInputWrapper.Internal.d.ts +0 -1
  66. package/dist/core/wrappers/UISceneWrapper/UISceneWrapper.Internal.d.ts +2 -0
  67. package/dist/core/wrappers/UISceneWrapper/UISceneWrapper.d.ts +1 -0
  68. package/dist/core/wrappers/UISceneWrapper/UISceneWrapper.js +3 -0
  69. package/dist/core/wrappers/UISolverWrapper/UISolverWrapper.Internal.d.ts +0 -1
  70. package/dist/debug/index.d.ts +2 -0
  71. package/dist/particles/behaviorModules/UIBehaviorDirectionalGravity.d.ts +7 -0
  72. package/dist/particles/behaviorModules/UIBehaviorDirectionalGravity.js +0 -2
  73. package/dist/particles/behaviorModules/UIBehaviorModule.d.ts +7 -1
  74. package/dist/particles/behaviorModules/UIBehaviorModule.js +2 -1
  75. package/dist/particles/behaviorModules/UIBehaviorPointGravity.d.ts +7 -0
  76. package/dist/particles/behaviorModules/UIBehaviorPointGravity.js +0 -2
  77. package/dist/particles/behaviorModules/UIBehaviorScaleOscillation.d.ts +7 -0
  78. package/dist/particles/behaviorModules/UIBehaviorScaleOscillation.js +0 -2
  79. package/dist/particles/behaviorModules/UIBehaviorScaleOverLife.d.ts +7 -0
  80. package/dist/particles/behaviorModules/UIBehaviorScaleOverLife.js +0 -2
  81. package/dist/particles/behaviorModules/UIBehaviorTorqueDamping.d.ts +7 -0
  82. package/dist/particles/behaviorModules/UIBehaviorTorqueDamping.js +0 -2
  83. package/dist/particles/behaviorModules/UIBehaviorTorqueNoise.d.ts +7 -0
  84. package/dist/particles/behaviorModules/UIBehaviorTorqueNoise.js +0 -2
  85. package/dist/particles/behaviorModules/UIBehaviorVelocityDamping.d.ts +7 -0
  86. package/dist/particles/behaviorModules/UIBehaviorVelocityDamping.js +0 -2
  87. package/dist/particles/behaviorModules/UIBehaviorVelocityNoise.d.ts +7 -0
  88. package/dist/particles/behaviorModules/UIBehaviorVelocityNoise.js +0 -2
  89. package/dist/particles/elements/UIEmitter.Internal.d.ts +7 -0
  90. package/dist/particles/elements/UIEmitter.d.ts +1 -8
  91. package/dist/particles/index.d.ts +5 -0
  92. package/dist/particles/index.js +3 -0
  93. package/dist/particles/instancedParticle/UIInstancedParticle.Internal.d.ts +11 -2
  94. package/dist/particles/instancedParticle/UIInstancedParticle.Internal.js +101 -72
  95. package/dist/particles/instancedParticle/UIInstancedParticle.d.ts +1 -0
  96. package/dist/particles/instancedParticle/UIInstancedParticle.js +4 -2
  97. package/dist/particles/renderingModules/UIRenderingColorOverLife.d.ts +4 -0
  98. package/dist/particles/renderingModules/UIRenderingColorOverLife.js +0 -2
  99. package/dist/particles/renderingModules/UIRenderingColorOverVelocity.d.ts +4 -0
  100. package/dist/particles/renderingModules/UIRenderingColorOverVelocity.js +0 -2
  101. package/dist/particles/renderingModules/UIRenderingModule.d.ts +10 -1
  102. package/dist/particles/renderingModules/UIRenderingModule.js +3 -1
  103. package/dist/particles/renderingModules/UIRenderingTexture.d.ts +4 -0
  104. package/dist/particles/spawnModules/UISpawnModule.d.ts +13 -1
  105. package/dist/particles/spawnModules/UISpawnModule.js +3 -1
  106. package/dist/particles/spawnModules/UISpawnOffset.d.ts +7 -0
  107. package/dist/particles/spawnModules/UISpawnOffset.js +0 -2
  108. package/dist/particles/spawnModules/UISpawnRandomLifetime.d.ts +7 -0
  109. package/dist/particles/spawnModules/UISpawnRandomLifetime.js +0 -2
  110. package/dist/particles/spawnModules/UISpawnRandomRotation.d.ts +7 -0
  111. package/dist/particles/spawnModules/UISpawnRandomRotation.js +0 -2
  112. package/dist/particles/spawnModules/UISpawnRandomScale.d.ts +7 -0
  113. package/dist/particles/spawnModules/UISpawnRandomScale.js +0 -2
  114. package/dist/particles/spawnModules/UISpawnRandomTorque.d.ts +7 -0
  115. package/dist/particles/spawnModules/UISpawnRandomTorque.js +0 -2
  116. package/dist/particles/spawnModules/UISpawnRandomVelocity.d.ts +7 -0
  117. package/dist/particles/spawnModules/UISpawnRandomVelocity.js +0 -2
  118. package/dist/particles/spawnModules/UISpawnRectangle.d.ts +7 -0
  119. package/dist/particles/spawnModules/UISpawnRectangle.js +0 -2
  120. package/package.json +1 -1
@@ -1,5 +1,6 @@
1
1
  import { Matrix3, Matrix4, Texture, Vector2, Vector3, Vector4 } from "three";
2
2
  import { UIColor } from "../color/UIColor.js";
3
+ import { UIAffineMatrix3 } from "../UIAffineMatrix3.js";
3
4
  import { checkSRGBSupport } from "../webglCapabilities.js";
4
5
  const GLSL_TYPE_INFO_FLOAT = Object.freeze({
5
6
  glslTypeName: "float",
@@ -37,6 +38,13 @@ const GLSL_TYPE_INFO_MAT3 = Object.freeze({
37
38
  columnCount: 3,
38
39
  instantiable: true,
39
40
  });
41
+ const GLSL_TYPE_INFO_AFFINE_MAT3 = Object.freeze({
42
+ glslTypeName: "mat3",
43
+ bufferSize: 6,
44
+ columnCount: 3,
45
+ instantiable: true,
46
+ affine: true,
47
+ });
40
48
  const GLSL_TYPE_INFO_MAT4 = Object.freeze({
41
49
  glslTypeName: "mat4",
42
50
  bufferSize: 16,
@@ -60,6 +68,8 @@ export function resolveGLSLTypeInfo(value) {
60
68
  return GLSL_TYPE_INFO_VEC4;
61
69
  case "Matrix3":
62
70
  return GLSL_TYPE_INFO_MAT3;
71
+ case "UIAffineMatrix3":
72
+ return GLSL_TYPE_INFO_AFFINE_MAT3;
63
73
  case "Matrix4":
64
74
  return GLSL_TYPE_INFO_MAT4;
65
75
  default:
@@ -85,6 +95,9 @@ export function resolveGLSLTypeInfo(value) {
85
95
  if (value === Vector4) {
86
96
  return GLSL_TYPE_INFO_VEC4;
87
97
  }
98
+ if (value === UIAffineMatrix3) {
99
+ return GLSL_TYPE_INFO_AFFINE_MAT3;
100
+ }
88
101
  if (value === Matrix3) {
89
102
  return GLSL_TYPE_INFO_MAT3;
90
103
  }
@@ -111,6 +124,9 @@ export function resolveGLSLTypeInfo(value) {
111
124
  if (value instanceof Vector4) {
112
125
  return GLSL_TYPE_INFO_VEC4;
113
126
  }
127
+ if (value instanceof UIAffineMatrix3) {
128
+ return GLSL_TYPE_INFO_AFFINE_MAT3;
129
+ }
114
130
  if (value instanceof Matrix3) {
115
131
  return GLSL_TYPE_INFO_MAT3;
116
132
  }
@@ -133,7 +149,9 @@ export function arePropertiesPartiallyCompatible(full, partial) {
133
149
  }
134
150
  const infoFull = full[key].glslTypeInfo;
135
151
  const infoPartial = partial[key].glslTypeInfo;
136
- if (infoFull.glslTypeName !== infoPartial.glslTypeName) {
152
+ // An affine mat3 and a full one share the GLSL type but not the layout
153
+ if (infoFull.glslTypeName !== infoPartial.glslTypeName ||
154
+ infoFull.bufferSize !== infoPartial.bufferSize) {
137
155
  return false;
138
156
  }
139
157
  if (!infoFull.instantiable && full[key].value !== partial[key].value) {
@@ -183,21 +201,27 @@ export const TRANSFORM_ZINDEX_OFFSET = 14;
183
201
  export function extractZIndex(transform) {
184
202
  return transform.elements[TRANSFORM_ZINDEX_OFFSET];
185
203
  }
186
- export function buildGenericPlaneFragmentShader(uniformDeclarations, varyingDeclarations, source, alphaTestValue, usePremultipliedAlpha) {
204
+ /**
205
+ * Builds the fragment shader of a plane. The p_* fields the source reads are plain globals,
206
+ * filled from the packed varyings at the start of main (see varyingPacking.ts).
207
+ * @param fieldDeclarations Packed varying and p_* global declarations
208
+ * @param fieldAssignments Statements filling the p_* globals from the packed varyings
209
+ */
210
+ export function buildGenericPlaneFragmentShader(uniformDeclarations, fieldDeclarations, fieldAssignments, source, alphaTestValue, usePremultipliedAlpha, maskSource) {
187
211
  return `
188
212
  // Defines
189
213
  #define PI 3.14159265359
190
214
  #define SRGB_SUPPORTED ${checkSRGBSupport() ? "1" : "0"}
215
+ ${maskSource === undefined ? "" : "#define LAYMUR_MASK_DERIVATIVES"}
191
216
 
192
217
  // Uniforms
193
218
  ${uniformDeclarations.join("\n")}
194
219
 
195
- // Builtin varyings
196
- varying vec3 p_position;
197
- varying vec2 p_uv;
220
+ // Packed varyings and the fields read from them
221
+ ${fieldDeclarations.join("\n")}
198
222
 
199
- // User varyings
200
- ${varyingDeclarations.join("\n")}
223
+ // The unit quad position equals its uv
224
+ #define p_position vec3(p_uv, 0.0)
201
225
 
202
226
  #include <alphahash_pars_fragment>
203
227
 
@@ -270,9 +294,14 @@ export function buildGenericPlaneFragmentShader(uniformDeclarations, varyingDecl
270
294
  return hslToRgb(hsl);
271
295
  }
272
296
 
297
+ // Mask coverage, masked planes only
298
+ ${maskSource ?? ""}
299
+
273
300
  // Source must define vec4 draw() function
274
301
  ${source}
275
302
  void main() {
303
+ ${fieldAssignments.join("\n")}
304
+
276
305
  vec4 diffuseColor = draw();
277
306
 
278
307
  // Skip the HSL roundtrip entirely for the default (identity) case.
@@ -280,6 +309,8 @@ export function buildGenericPlaneFragmentShader(uniformDeclarations, varyingDecl
280
309
  diffuseColor.rgb = applyInstanceHSL(diffuseColor.rgb);
281
310
  }
282
311
 
312
+ ${maskSource === undefined ? "" : "diffuseColor.a *= laymurMaskCoverage(p_instanceMaskLocal, p_instanceMaskShape, p_instanceMaskMode);"}
313
+
283
314
  if (diffuseColor.a <= ${alphaTestValue.toFixed(8)}) {
284
315
  discard;
285
316
  }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Packing of varyings into as few vec4 rows as possible.
3
+ *
4
+ * The varying budget (MAX_VARYING_VECTORS: at least 8 on WebGL1, 15 on WebGL2) is counted in
5
+ * rows of four components, and drivers lay varyings out with the GLSL ES reference algorithm:
6
+ * a vec3 or a mat3 column leaves its fourth component to floats only, so vec3 + vec2 already
7
+ * takes two rows. Instead every field is cut into scalars and placed into packed vec4 varyings
8
+ * by the shader generator itself, which takes exactly ceil(components / 4) rows. Fields are
9
+ * kept contiguous where they fit, so most reads stay plain swizzles.
10
+ *
11
+ * Packing changes nothing for interpolation: varyings are interpolated per component. The
12
+ * fragment shader reassembles each field once, which costs a few register moves.
13
+ *
14
+ * The row count is exact, so the budget can be checked before the program fails to link.
15
+ */
16
+ /** A value passed from the vertex to the fragment shader */
17
+ export interface VaryingFieldSpec {
18
+ /** Name the fragment shader knows the field by; only used to key the result */
19
+ name: string;
20
+ glslTypeName: string;
21
+ /**
22
+ * Vertex shader expressions of the scalar components, in the order the GLSL constructor of
23
+ * glslTypeName takes them (column-major for matrices)
24
+ */
25
+ components: readonly string[];
26
+ /** A mat3 given as three columns of two, the bottom row taken as (0, 0, 1) */
27
+ affine?: boolean;
28
+ }
29
+ export interface PackedVaryings {
30
+ /** Number of varying rows (vec4 locations) taken */
31
+ rowCount: number;
32
+ /** Varying declarations, the same for both shaders */
33
+ declarations: string[];
34
+ /** Vertex shader statements writing the packed varyings */
35
+ vertexAssignments: string[];
36
+ /** Fragment shader expression reassembling each field, by field name */
37
+ fragmentExpressions: Map<string, string>;
38
+ }
39
+ export declare function packedVaryingName(row: number): string;
40
+ /** Whether the code mentions the identifier as a whole word */
41
+ export declare function isIdentifierReferenced(code: string, identifier: string): boolean;
42
+ /**
43
+ * Packs the fields into vec4 varyings. The layout depends on the fields and their order only.
44
+ * @throws If a field has an unsupported type or a wrong number of components
45
+ */
46
+ export declare function packVaryings(fields: readonly VaryingFieldSpec[]): PackedVaryings;
@@ -0,0 +1,170 @@
1
+ /**
2
+ * Packing of varyings into as few vec4 rows as possible.
3
+ *
4
+ * The varying budget (MAX_VARYING_VECTORS: at least 8 on WebGL1, 15 on WebGL2) is counted in
5
+ * rows of four components, and drivers lay varyings out with the GLSL ES reference algorithm:
6
+ * a vec3 or a mat3 column leaves its fourth component to floats only, so vec3 + vec2 already
7
+ * takes two rows. Instead every field is cut into scalars and placed into packed vec4 varyings
8
+ * by the shader generator itself, which takes exactly ceil(components / 4) rows. Fields are
9
+ * kept contiguous where they fit, so most reads stay plain swizzles.
10
+ *
11
+ * Packing changes nothing for interpolation: varyings are interpolated per component. The
12
+ * fragment shader reassembles each field once, which costs a few register moves.
13
+ *
14
+ * The row count is exact, so the budget can be checked before the program fails to link.
15
+ */
16
+ const ROW_CAPACITY = 4;
17
+ const ROW_TYPES = ["float", "vec2", "vec3", "vec4"];
18
+ const SWIZZLE_COMPONENTS = "xyzw";
19
+ /** Number of components and column size of the GLSL types a varying field may have */
20
+ const TYPE_SHAPES = {
21
+ float: { size: 1, columnSize: 1 },
22
+ vec2: { size: 2, columnSize: 2 },
23
+ vec3: { size: 3, columnSize: 3 },
24
+ vec4: { size: 4, columnSize: 4 },
25
+ mat2: { size: 4, columnSize: 2 },
26
+ mat3: { size: 9, columnSize: 3 },
27
+ mat4: { size: 16, columnSize: 4 },
28
+ };
29
+ const AFFINE_SHAPE = { size: 6, columnSize: 2 };
30
+ export function packedVaryingName(row) {
31
+ return `v_packed${row}`;
32
+ }
33
+ /** Whether the code mentions the identifier as a whole word */
34
+ export function isIdentifierReferenced(code, identifier) {
35
+ return new RegExp(`\\b${identifier}\\b`).test(code);
36
+ }
37
+ /**
38
+ * Splits `base.xyz`-style scalar expressions into runs that can be read with one swizzle.
39
+ * Expressions that are not a swizzle of a single component stay on their own.
40
+ */
41
+ function groupSwizzles(expressions, fullSizes) {
42
+ const groups = [];
43
+ let base;
44
+ let letters = "";
45
+ const flush = () => {
46
+ if (base !== undefined) {
47
+ const isWhole = fullSizes.get(base) === letters.length && SWIZZLE_COMPONENTS.startsWith(letters);
48
+ groups.push(isWhole ? base : `${base}.${letters}`);
49
+ }
50
+ base = undefined;
51
+ letters = "";
52
+ };
53
+ for (const expression of expressions) {
54
+ const match = /^([A-Za-z_]\w*(?:\[\d+\])*)\.([xyzw])$/.exec(expression);
55
+ if (match === null) {
56
+ flush();
57
+ groups.push(expression);
58
+ continue;
59
+ }
60
+ const [, expressionBase, letter] = match;
61
+ const expected = base === undefined
62
+ ? undefined
63
+ : SWIZZLE_COMPONENTS[SWIZZLE_COMPONENTS.indexOf(letters[letters.length - 1]) + 1];
64
+ if (expressionBase === base && letter === expected) {
65
+ letters += letter;
66
+ }
67
+ else {
68
+ flush();
69
+ base = expressionBase;
70
+ letters = letter;
71
+ }
72
+ }
73
+ flush();
74
+ return groups;
75
+ }
76
+ function buildConstructor(glslTypeName, groups, size) {
77
+ // A single group of the right size already has the right type, unless a matrix is built
78
+ if (groups.length === 1 && !glslTypeName.startsWith("mat")) {
79
+ return groups[0];
80
+ }
81
+ return size === 1 ? groups[0] : `${glslTypeName}(${groups.join(", ")})`;
82
+ }
83
+ /**
84
+ * Packs the fields into vec4 varyings. The layout depends on the fields and their order only.
85
+ * @throws If a field has an unsupported type or a wrong number of components
86
+ */
87
+ export function packVaryings(fields) {
88
+ const chunks = [];
89
+ let total = 0;
90
+ fields.forEach((field, fieldIndex) => {
91
+ const shape = field.affine === true && field.glslTypeName === "mat3"
92
+ ? AFFINE_SHAPE
93
+ : TYPE_SHAPES[field.glslTypeName];
94
+ if (shape === undefined) {
95
+ throw new Error(`packVaryings.fields: unsupported type ${field.glslTypeName} of "${field.name}"`);
96
+ }
97
+ if (field.components.length !== shape.size) {
98
+ throw new Error(`packVaryings.fields: "${field.name}" needs ${shape.size} components, got ${field.components.length}`);
99
+ }
100
+ for (let offset = 0; offset < shape.size; offset += shape.columnSize) {
101
+ chunks.push({ fieldIndex, offset, size: shape.columnSize });
102
+ }
103
+ total += shape.size;
104
+ });
105
+ // Largest chunks first, ties in declaration order, so the layout is deterministic
106
+ const order = chunks
107
+ .map((chunk, index) => ({ chunk, index }))
108
+ .sort((a, b) => b.chunk.size - a.chunk.size || a.index - b.index);
109
+ const rowCount = Math.ceil(total / ROW_CAPACITY);
110
+ const used = new Array(rowCount).fill(0);
111
+ const slots = fields.map((field) => new Array(field.components.length));
112
+ for (const { chunk } of order) {
113
+ const fieldSlots = slots[chunk.fieldIndex];
114
+ // Best fit keeps a chunk whole and leaves the larger gaps for the larger chunks
115
+ let bestRow = -1;
116
+ for (let row = 0; row < rowCount; row++) {
117
+ const free = ROW_CAPACITY - used[row];
118
+ if (free >= chunk.size && (bestRow === -1 || free < ROW_CAPACITY - used[bestRow])) {
119
+ bestRow = row;
120
+ }
121
+ }
122
+ if (bestRow !== -1) {
123
+ for (let i = 0; i < chunk.size; i++) {
124
+ fieldSlots[chunk.offset + i] = { row: bestRow, component: used[bestRow] + i };
125
+ }
126
+ used[bestRow] += chunk.size;
127
+ continue;
128
+ }
129
+ // No room for the whole chunk: spread it over the remaining components; rowCount rows
130
+ // always have room for all of them
131
+ let i = 0;
132
+ for (let row = 0; row < rowCount && i < chunk.size; row++) {
133
+ while (used[row] < ROW_CAPACITY && i < chunk.size) {
134
+ fieldSlots[chunk.offset + i] = { row, component: used[row] };
135
+ used[row]++;
136
+ i++;
137
+ }
138
+ }
139
+ }
140
+ const rowSources = used.map((size) => new Array(size));
141
+ fields.forEach((field, fieldIndex) => {
142
+ slots[fieldIndex].forEach(({ row, component }, componentIndex) => {
143
+ rowSources[row][component] = field.components[componentIndex];
144
+ });
145
+ });
146
+ const declarations = [];
147
+ const vertexAssignments = [];
148
+ const rowSizes = new Map();
149
+ for (let row = 0; row < rowCount; row++) {
150
+ const name = packedVaryingName(row);
151
+ const size = used[row];
152
+ const type = ROW_TYPES[size - 1];
153
+ rowSizes.set(name, size);
154
+ declarations.push(`varying ${type} ${name};`);
155
+ vertexAssignments.push(`${name} = ${buildConstructor(type, groupSwizzles(rowSources[row], new Map()), size)};`);
156
+ }
157
+ const fragmentExpressions = new Map();
158
+ fields.forEach((field, fieldIndex) => {
159
+ const references = slots[fieldIndex].map(({ row, component }) => rowSizes.get(packedVaryingName(row)) === 1
160
+ ? packedVaryingName(row)
161
+ : `${packedVaryingName(row)}.${SWIZZLE_COMPONENTS[component]}`);
162
+ if (field.affine === true) {
163
+ const columns = [0, 2, 4].map((start) => groupSwizzles(references.slice(start, start + 2), rowSizes).join(", "));
164
+ fragmentExpressions.set(field.name, `mat3(vec3(${columns[0]}, 0.0), vec3(${columns[1]}, 0.0), vec3(${columns[2]}, 1.0))`);
165
+ return;
166
+ }
167
+ fragmentExpressions.set(field.name, buildConstructor(field.glslTypeName, groupSwizzles(references, rowSizes), field.components.length));
168
+ });
169
+ return { rowCount, declarations, vertexAssignments, fragmentExpressions };
170
+ }
@@ -0,0 +1,61 @@
1
+ import type { UIInsetsConfig } from "../insets/UIInsets.Internal.js";
2
+ /** Shape a mask cuts out of the rectangle of its source */
3
+ export declare enum UIMaskShape {
4
+ /** Rectangle, optionally with rounded corners (see `radius`) */
5
+ RECTANGLE = 0,
6
+ /** Ellipse inscribed into the rectangle; a circle when the rectangle is a square */
7
+ ELLIPSE = 1
8
+ }
9
+ /** Configuration options for UIMask */
10
+ export interface UIMaskOptions {
11
+ /** Shape cut out of the source rectangle */
12
+ shape: UIMaskShape;
13
+ /** Corner radius of RECTANGLE in world units, clamped to half of the smaller side */
14
+ radius: number;
15
+ /**
16
+ * Width of the soft edge in world units, laid inside the shape so nothing leaks out of it.
17
+ * 0 keeps a hard edge, still antialiased over about a pixel.
18
+ */
19
+ softness: number;
20
+ /** Insets shrinking the source rectangle, in world units */
21
+ padding: UIInsetsConfig;
22
+ /** Whether the mask keeps the outside of the shape instead of the inside */
23
+ inverted: boolean;
24
+ /** Whether the micro transform of the source moves the mask, when the source has one */
25
+ useMicro: boolean;
26
+ /** Whether masked elements also stop catching input outside the visible part */
27
+ clipInput: boolean;
28
+ }
29
+ export declare const MASK_DEFAULT_SHAPE = UIMaskShape.RECTANGLE;
30
+ export declare const MASK_DEFAULT_RADIUS = 0;
31
+ export declare const MASK_DEFAULT_SOFTNESS = 0;
32
+ export declare const MASK_DEFAULT_INVERTED = false;
33
+ export declare const MASK_DEFAULT_USE_MICRO = true;
34
+ export declare const MASK_DEFAULT_CLIP_INPUT = true;
35
+ /**
36
+ * Number of floats in the packed mask data:
37
+ * - [0..2] first row of the layer -> mask-local affine map
38
+ * - [3..5] second row of that map
39
+ * - [6..9] half width, half height, corner radius, softness (world units)
40
+ * - [10] mode: shape + 2 when inverted
41
+ *
42
+ * Mask-local space is centered on the mask, its axes follow the source rotation and its units
43
+ * are world units, so distances and softness stay isotropic.
44
+ */
45
+ export declare const MASK_DATA_SIZE = 11;
46
+ export declare const MASK_DATA_ROW0_OFFSET = 0;
47
+ export declare const MASK_DATA_ROW1_OFFSET = 3;
48
+ export declare const MASK_DATA_SHAPE_OFFSET = 6;
49
+ export declare const MASK_DATA_MODE_OFFSET = 10;
50
+ /**
51
+ * Translation that puts every point of an empty mask (a source collapsed to no area) far
52
+ * outside its zero-sized shape, in world units
53
+ */
54
+ export declare const MASK_EMPTY_OFFSET = 1000000;
55
+ /** Mode value of an external material patch with no mask applied */
56
+ export declare const MASK_MODE_DISABLED = -1;
57
+ /**
58
+ * Signed distance from a mask-local point to the shape boundary, negative inside. Matches the
59
+ * GLSL laymurMaskDistance in sign; for the ellipse neither is the exact distance.
60
+ */
61
+ export declare function computeMaskDistance(localX: number, localY: number, halfWidth: number, halfHeight: number, radius: number, shape: UIMaskShape): number;
@@ -0,0 +1,56 @@
1
+ /** Shape a mask cuts out of the rectangle of its source */
2
+ export var UIMaskShape;
3
+ (function (UIMaskShape) {
4
+ /** Rectangle, optionally with rounded corners (see `radius`) */
5
+ UIMaskShape[UIMaskShape["RECTANGLE"] = 0] = "RECTANGLE";
6
+ /** Ellipse inscribed into the rectangle; a circle when the rectangle is a square */
7
+ UIMaskShape[UIMaskShape["ELLIPSE"] = 1] = "ELLIPSE";
8
+ })(UIMaskShape || (UIMaskShape = {}));
9
+ export const MASK_DEFAULT_SHAPE = UIMaskShape.RECTANGLE;
10
+ export const MASK_DEFAULT_RADIUS = 0;
11
+ export const MASK_DEFAULT_SOFTNESS = 0;
12
+ export const MASK_DEFAULT_INVERTED = false;
13
+ export const MASK_DEFAULT_USE_MICRO = true;
14
+ export const MASK_DEFAULT_CLIP_INPUT = true;
15
+ /**
16
+ * Number of floats in the packed mask data:
17
+ * - [0..2] first row of the layer -> mask-local affine map
18
+ * - [3..5] second row of that map
19
+ * - [6..9] half width, half height, corner radius, softness (world units)
20
+ * - [10] mode: shape + 2 when inverted
21
+ *
22
+ * Mask-local space is centered on the mask, its axes follow the source rotation and its units
23
+ * are world units, so distances and softness stay isotropic.
24
+ */
25
+ export const MASK_DATA_SIZE = 11;
26
+ export const MASK_DATA_ROW0_OFFSET = 0;
27
+ export const MASK_DATA_ROW1_OFFSET = 3;
28
+ export const MASK_DATA_SHAPE_OFFSET = 6;
29
+ export const MASK_DATA_MODE_OFFSET = 10;
30
+ /**
31
+ * Translation that puts every point of an empty mask (a source collapsed to no area) far
32
+ * outside its zero-sized shape, in world units
33
+ */
34
+ export const MASK_EMPTY_OFFSET = 1e6;
35
+ /** Mode value of an external material patch with no mask applied */
36
+ export const MASK_MODE_DISABLED = -1;
37
+ /**
38
+ * Signed distance from a mask-local point to the shape boundary, negative inside. Matches the
39
+ * GLSL laymurMaskDistance in sign; for the ellipse neither is the exact distance.
40
+ */
41
+ export function computeMaskDistance(localX, localY, halfWidth, halfHeight, radius, shape) {
42
+ if (shape === UIMaskShape.ELLIPSE) {
43
+ if (halfWidth <= 0 || halfHeight <= 0) {
44
+ return Infinity;
45
+ }
46
+ const nx = localX / halfWidth;
47
+ const ny = localY / halfHeight;
48
+ // The input test only needs the sign; the smaller axis keeps the units sensible
49
+ return (Math.sqrt(nx * nx + ny * ny) - 1) * Math.min(halfWidth, halfHeight);
50
+ }
51
+ const qx = Math.abs(localX) - halfWidth + radius;
52
+ const qy = Math.abs(localY) - halfHeight + radius;
53
+ const outsideX = Math.max(qx, 0);
54
+ const outsideY = Math.max(qy, 0);
55
+ return (Math.sqrt(outsideX * outsideX + outsideY * outsideY) + Math.min(Math.max(qx, qy), 0) - radius);
56
+ }
@@ -0,0 +1,84 @@
1
+ import type { UIDummy } from "../../elements/UIDummy/UIDummy.js";
2
+ import type { UILayer } from "../../layers/UILayer/UILayer.js";
3
+ import { UIInsets } from "../insets/UIInsets.js";
4
+ import type { UIMaskOptions } from "./UIMask.Internal.js";
5
+ import { UIMaskShape } from "./UIMask.Internal.js";
6
+ /**
7
+ * Analytic mask that follows the rectangle of a source element or layer.
8
+ *
9
+ * Elements are masked by assigning the mask to their `mask` property; one mask can serve any
10
+ * number of elements of the same layer. The mask is computed in the shader, so edges can be
11
+ * soft, masked elements keep batching together and no stencil buffer is needed. With
12
+ * `clipInput` the masked part of an element stops catching input as well.
13
+ *
14
+ * Lifetime follows the rules of constraints: destroying the source destroys the mask, and a
15
+ * destroyed mask is taken off every element it masked.
16
+ */
17
+ export declare class UIMask {
18
+ readonly source: UIDummy | UILayer;
19
+ /** Insets shrinking the source rectangle, in world units */
20
+ readonly padding: UIInsets;
21
+ /** Layer of the source; only elements of this layer can use the mask */
22
+ readonly layer: UILayer;
23
+ private shapeInternal;
24
+ private radiusInternal;
25
+ private softnessInternal;
26
+ private invertedInternal;
27
+ private useMicroInternal;
28
+ private clipInputInternal;
29
+ private readonly consumers;
30
+ private readonly dataInternal;
31
+ private versionInternal;
32
+ private destroyedInternal;
33
+ /**
34
+ * Creates a new UIMask instance.
35
+ *
36
+ * @param source - Element or layer whose rectangle the mask follows
37
+ * @param options - Configuration options
38
+ * @throws If the source is destroyed
39
+ */
40
+ constructor(source: UIDummy | UILayer, options?: Partial<UIMaskOptions>);
41
+ /** Whether the mask is destroyed, by its own `destroy` or together with its source */
42
+ get destroyed(): boolean;
43
+ /** Shape cut out of the source rectangle */
44
+ get shape(): UIMaskShape;
45
+ /** Corner radius of RECTANGLE in world units */
46
+ get radius(): number;
47
+ /** Width of the soft edge in world units, laid inside the shape */
48
+ get softness(): number;
49
+ /** Whether the mask keeps the outside of the shape instead of the inside */
50
+ get inverted(): boolean;
51
+ /** Whether the micro transform of the source moves the mask */
52
+ get useMicro(): boolean;
53
+ /** Whether masked elements also stop catching input outside the visible part */
54
+ get clipInput(): boolean;
55
+ /** Elements masked by this mask */
56
+ get elements(): readonly UIDummy[];
57
+ /** Shape cut out of the source rectangle */
58
+ set shape(value: UIMaskShape);
59
+ /** Corner radius of RECTANGLE in world units */
60
+ set radius(value: number);
61
+ /** Width of the soft edge in world units, laid inside the shape */
62
+ set softness(value: number);
63
+ /** Whether the mask keeps the outside of the shape instead of the inside */
64
+ set inverted(value: boolean);
65
+ /** Whether the micro transform of the source moves the mask */
66
+ set useMicro(value: boolean);
67
+ /** Whether masked elements also stop catching input outside the visible part */
68
+ set clipInput(value: boolean);
69
+ /**
70
+ * Whether a point is in the visible part of the mask; the boundary is the shape itself,
71
+ * without the soft edge.
72
+ * @param x X in layer coordinates
73
+ * @param y Y in layer coordinates
74
+ * @throws If the mask is destroyed
75
+ */
76
+ containsPoint(x: number, y: number): boolean;
77
+ /**
78
+ * Takes the mask off every element and removes it from its layer.
79
+ * Does nothing if the mask is already destroyed.
80
+ */
81
+ destroy(): void;
82
+ private computeData;
83
+ private assertNotDestroyed;
84
+ }