Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add alphaMode 'add' and per-instance opacity for blend and add parts

Nguyen Xuan An3cb559203aaf
diff --git a/changes/586-additive.md b/changes/586-additive.md
new file mode 100644
index 00000000..d5ab1a24
--- /dev/null
+++ b/changes/586-additive.md
@@ -0,0 +1 @@
+Materials accept `alphaMode: 'add'` for additive glow, and the opacity of blend and add parts changes each frame through `updateParts` without a new batch. (#586)
diff --git a/changes/586-additive.size.md b/changes/586-additive.size.md
new file mode 100644
index 00000000..cc630904
--- /dev/null
+++ b/changes/586-additive.size.md
@@ -0,0 +1,9 @@
+- entry:core: additive blend mode and per-instance opacity (one more instance float), about 256 bytes gzip; sparks, trails and glow need both.
+- scene:lit-box: the same renderer code, which lives in the core renderer.
+- goal:lit-box: 279 bytes for additive blending and per-part opacity; an agent-facing VFX capability (issue 586).
+- scene:gltf-box: the same renderer code.
+- scene:gltf-box+lazy: same code as scene:gltf-box.
+- goal:gltf-box: 275 bytes for the same capability.
+- scene:agent-scene: the same renderer code plus the recipe alphaMode list.
+- scene:agent-scene+lazy: same code as scene:agent-scene.
+- goal:agent-scene: 301 bytes for the same capability.
diff --git a/docs/agent-scene.md b/docs/agent-scene.md
index 0312bfd9..85f67e90 100644
--- a/docs/agent-scene.md
+++ b/docs/agent-scene.md
@@ -107,7 +107,7 @@ The defaults are `surface`, `[0.5, 0.5, 0.5]`, `0`, `0.5`, `0`, opacity `1`, `op
The tag can be `surface`, `unlit`, `liquid`, `foam`, `water`, `foliage` or `grass` (the last two sway in `environment.wind`) and remains fixed during editing.
`liquid` refracts and tints what lies behind it: its color is the light one metre lets through, so `[0.56, 0.84, 0.88]` is clear water. `foam` draws soft blended droplets.
`water` is a flat mirror sheet (a plane or thin box). The largest one sets the water level: everything below it fades by `exp(-absorption * depth)` per colour channel (`absorption` is RGB per metre), and its shadows are lifted and softened with depth times `turbidity` (0 clear to 1 murky). `waterPreset` fills both: `lake` (default), `sea` or `river`. A shadow on the surface is faint and never darkens the reflection; give the sheet an `opacity` below one when the bed should show. The sun's leg to a bed is bent at n = 1.33 and absorbed over `depth / cos(theta_t)`, so a clear lake keeps little shadow contrast on a bed 4 m down, and a murky river keeps about a quarter.
-Any `opacity` below one draws the material blended after opaque geometry, which suits glass, windows and visors. `alphaMode` accepts `opaque` or `blend`; cutout masking needs a texture and is not available in procedural recipes.
+Any `opacity` below one draws the material blended after opaque geometry, which suits glass, windows and visors. `alphaMode` accepts `opaque`, `blend` or `add` (additive light for sparks, trails and glow); cutout masking needs a texture and is not available in procedural recipes.
`doubleSided` draws and lights both faces of thin sheets.
Changing the tag, opacity, blending, sidedness or pattern replaces the affected parts in the renderer; color, metallic, roughness and emission edits keep them.
Set liquid optics with `environment.liquid`: `thickness`, `ior`, `refraction`, `scattering`, `foamOpacity` and `foamSoftness`.
diff --git a/docs/material-maps.md b/docs/material-maps.md
index 5316040e..3e733cc6 100644
--- a/docs/material-maps.md
+++ b/docs/material-maps.md
@@ -103,20 +103,21 @@ Renderer disposal deletes every cached GPU texture. Asset disposal closes each s
| Field | Default | Meaning |
| --- | --- | --- |
-| `alphaMode` | `'opaque'` | `'opaque'`, `'mask'` (cutout) or `'blend'` (translucent). |
+| `alphaMode` | `'opaque'` | `'opaque'`, `'mask'` (cutout), `'blend'` (translucent) or `'add'` (additive light). |
| `alphaCutoff` | `0.5` | Mask only. Fragments with alpha below it are discarded. |
-| `opacity` | `1` | Multiplies the base map alpha. Ignored by `opaque`. |
+| `opacity` | `1` | Multiplies the base map alpha. Ignored by `opaque`. For `blend` and `add` it is a per-part value that `updateParts` may change every frame. |
| `doubleSided` | `false` | Draws both faces and flips the normal on back faces so each side lights correctly. |
Final alpha is the base map alpha (when `material.map` is set) times `opacity`. Vertex colors stay RGB.
- `mask` discards below `alphaCutoff` in the color pass and in the shadow pass, so shadows follow the cutout shape. With MSAA the edge uses alpha-to-coverage, sharpened by `fwidth`, so leaf edges stay smooth.
- `blend` draws after all opaque and masked batches. Texels with alpha 1 (opacity 1) are drawn first as a cutout that writes depth, so an opaque baked mesh hides what lies behind it in any order; the translucent texels then blend with depth writes off. Batches sort back to front by their mean distance to the eye, and instances inside one batch sort by translation distance each frame. Intersecting translucent surfaces and large meshes can still show ordering artifacts. Blend parts skip shadows unless `castShadow: true` is set, and then they cast a fully opaque shadow.
-- `alphaMode`, `alphaCutoff`, `opacity` and `doubleSided` are batch state like `castShadow`. Parts that differ never share a draw call, and `updateParts` rejects changes after upload. Rebuild the renderer to change them.
+- `add` draws after all opaque, masked and blend batches with blending `SRC_ALPHA, ONE`: the colour times opacity is added to the frame, so overlaps brighten and opacity 0 adds nothing. It tests depth, writes none, needs no sorting and skips shadows unless `castShadow: true` is set. Fog fades additive light to black instead of mixing it toward the fog colour, so distant sparks dim rather than glow as fog. Additive parts do not occlude bounce, sky-visibility or closed-room checks, like blend parts.
+- `alphaMode`, `alphaCutoff`, `doubleSided` and, for `mask`, `opacity` are batch state like `castShadow`. Parts that differ never share a draw call, and `updateParts` rejects changes after upload. Rebuild the renderer to change them. The opacity of `blend` and `add` parts is stored per instance (the last float of each instance), so parts that differ only in opacity share one batch and `updateParts` changes it without a rebuild; a fading trail or particle needs one part, not one per opacity step.
- Invalid values (unknown mode, cutoff or opacity outside zero to one, a non-boolean `doubleSided`) throw.
- The benchmark preset ignores alpha.
-glTF import maps `alphaMode` MASK and BLEND, `alphaCutoff`, `doubleSided` and `baseColorFactor[3]` (to `opacity`) onto these fields, and keeps the base color texture alpha. `exportGlb` writes them back.
+glTF import maps `alphaMode` MASK and BLEND, `alphaCutoff`, `doubleSided` and `baseColorFactor[3]` (to `opacity`) onto these fields, and keeps the base color texture alpha. `exportGlb` writes them back. glTF has no additive blending, so an `add` material is exported as `BLEND` and loads back as `blend`.
## Moss layer
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index 54cd20a7..6cbdcefc 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -85,7 +85,7 @@ export const MATERIAL_GRAPH_NODES = Object.freeze({
});
// Recipe textures are opaque patterns, so cutout masking has nothing to cut.
-export const RECIPE_ALPHA_MODES = Object.freeze(['opaque', 'blend']);
+export const RECIPE_ALPHA_MODES = Object.freeze(['opaque', 'blend', 'add']);
// Named lighting setups (see lighting-setups.js) and the occlusion strength that recipes get when they set none.
export const LIGHTING_SETUP_NAMES = Object.freeze(['daylight', 'overcast', 'sunset', 'studio']);
diff --git a/src/agent-scene.js b/src/agent-scene.js
index 736cf89b..2e1aebaa 100644
--- a/src/agent-scene.js
+++ b/src/agent-scene.js
@@ -230,8 +230,8 @@ function materialFrom(value) {
if (!RECIPE_ALPHA_MODES.includes(requestedAlphaMode)) {
throw new RangeError(`alphaMode must be one of ${RECIPE_ALPHA_MODES.join(', ')}.`);
}
- // The renderer ignores opacity on opaque surfaces, so any opacity below one means blending.
- result.alphaMode = result.opacity < 1 ? 'blend' : requestedAlphaMode;
+ // The renderer ignores opacity on opaque surfaces, so any opacity below one means blending (additive stays additive).
+ result.alphaMode = result.opacity < 1 && requestedAlphaMode === 'opaque' ? 'blend' : requestedAlphaMode;
result.doubleSided = defaultValue(value.doubleSided, false);
if (typeof result.doubleSided !== 'boolean') {
throw new TypeError('doubleSided must be boolean.');
diff --git a/src/closed-room.js b/src/closed-room.js
index 256c08bf..153eb98e 100644
--- a/src/closed-room.js
+++ b/src/closed-room.js
@@ -83,7 +83,7 @@ function hitsFrontFace(corners, offset, origin, direction) {
* has more than CLOSED_ROOM_MAXIMUM_TRIANGLES triangles. `worldMatrices` maps a part's name to its world matrix.
*/
export function closedRoomShare(parts, worldMatrices) {
- const triangles = worldTriangles(parts.filter(part => part.material?.alphaMode !== 'blend'), worldMatrices);
+ const triangles = worldTriangles(parts.filter(part => !['blend', 'add'].includes(part.material?.alphaMode)), worldMatrices);
if (!triangles) {
return null;
}
@@ -111,7 +111,7 @@ export const SKY_OPENNESS_RAYS = 32;
*/
export function skyOpenness(parts, point) {
const worldMatrices = new Map(parts.map(part => [part.name, part.matrix]));
- const triangles = worldTriangles(parts.filter(part => part.material?.alphaMode !== 'blend'), worldMatrices);
+ const triangles = worldTriangles(parts.filter(part => !['blend', 'add'].includes(part.material?.alphaMode)), worldMatrices);
if (!triangles) {
return null;
}
@@ -148,7 +148,7 @@ export function skyGridSize(minimum, maximum) {
*/
export function skyVisibilityGrid(parts, minimum, maximum) {
const worldMatrices = new Map(parts.map(part => [part.name, part.matrix]));
- const triangles = worldTriangles(parts.filter(part => part.material?.alphaMode !== 'blend'), worldMatrices);
+ const triangles = worldTriangles(parts.filter(part => !['blend', 'add'].includes(part.material?.alphaMode)), worldMatrices);
if (!triangles) {
return null;
}
diff --git a/src/export.js b/src/export.js
index 315c5ed3..5417e4da 100644
--- a/src/export.js
+++ b/src/export.js
@@ -19,12 +19,13 @@ function validateFloatChannel(values, length, label, bounded = false) {
}
}
-const GLTF_ALPHA_MODES = { mask: 'MASK', blend: 'BLEND' };
+// glTF has no additive blending, so an add material is written as BLEND and loads back as blend.
+const GLTF_ALPHA_MODES = { mask: 'MASK', blend: 'BLEND', add: 'BLEND' };
function writeAlphaFields(gltfMaterial, material) {
const alphaMode = material.alphaMode ?? 'opaque';
if (alphaMode !== 'opaque') {
- if (!Object.hasOwn(GLTF_ALPHA_MODES, alphaMode)) throw new Error("alphaMode must be 'opaque', 'mask' or 'blend'.");
+ if (!Object.hasOwn(GLTF_ALPHA_MODES, alphaMode)) throw new Error("alphaMode must be 'opaque', 'mask', 'blend' or 'add'.");
gltfMaterial.alphaMode = GLTF_ALPHA_MODES[alphaMode];
validateFactor(material.opacity ?? 1, 'opacity');
gltfMaterial.pbrMetallicRoughness.baseColorFactor[3] = material.opacity ?? 1;
diff --git a/src/fitted-closed-room.js b/src/fitted-closed-room.js
index 6066d347..e022ff25 100644
--- a/src/fitted-closed-room.js
+++ b/src/fitted-closed-room.js
@@ -54,7 +54,7 @@ function partsNearTheRest(parts, worldMatrices) {
* CLOSED_ROOM_MAXIMUM_TRIANGLES triangles. Null when nothing is left to test. `worldMatrices` maps a part's name to its world matrix.
*/
export function fittedClosedRoomShare(parts, worldMatrices) {
- const kept = lightestParts(parts.filter(part => part.material?.alphaMode !== 'blend'));
+ const kept = lightestParts(parts.filter(part => !['blend', 'add'].includes(part.material?.alphaMode)));
const share = closedRoomShare(kept, worldMatrices);
if (share === null || share >= CLOSED_ROOM_SHARE) {
return share;
diff --git a/src/floor-sky-visibility.js b/src/floor-sky-visibility.js
index e83ad08e..0343c056 100644
--- a/src/floor-sky-visibility.js
+++ b/src/floor-sky-visibility.js
@@ -47,7 +47,7 @@ function hasPlainMesh(part) {
}
function isFloorMaterial(material) {
- return !material || (material.alphaMode !== 'blend' && material.alphaMode !== 'mask' && !(material.transmission > 0) && !EXCLUDED_TAGS.has(material.tag));
+ return !material || (!['blend', 'add', 'mask'].includes(material.alphaMode) && !(material.transmission > 0) && !EXCLUDED_TAGS.has(material.tag));
}
// The share of a part's triangle area whose world normal points up: a slab with a roof and a floor side counts half.
@@ -212,7 +212,7 @@ export function applyFloorSkyVisibility(parts, { raysPerTexel = FLOOR_SKY_RAYS,
if (floorIndices.length === 0) return unchanged('no floor');
// Every opaque part blocks sky, floors included: a floor above another one (a gallery, a bridge) hides it, and a floor never
// blocks its own texels because the rays leave from its top face.
- const occluders = parts.filter(part => part.material?.alphaMode !== 'blend');
+ const occluders = parts.filter(part => !['blend', 'add'].includes(part.material?.alphaMode));
if (occluders.length < 2) return unchanged('nothing above the floor');
// A closed room has no sky to see: its walls and lamps give the light, and the shader's room term already handles it.
const roomShare = closedRoomShare(parts, new Map(parts.map(part => [part.name, part.matrix])));
diff --git a/src/fog-bounce.js b/src/fog-bounce.js
index bfa49cc9..42bb2c51 100644
--- a/src/fog-bounce.js
+++ b/src/fog-bounce.js
@@ -20,7 +20,7 @@ const GOLDEN_ANGLE =Math.PI * (3 - Math.sqrt(5));
* `lighting` holds `pointLights`, `keyColor` and `lightDirection`, as the light bake takes them.
*/
export function fogBounceGrid(parts, size, minimum, maximum, lighting) {
- const surfaces = parts.filter(part => part.material?.alphaMode !== 'blend');
+ const surfaces = parts.filter(part => !['blend', 'add'].includes(part.material?.alphaMode));
let world;
let lights;
try {
diff --git a/src/ground-bounce.js b/src/ground-bounce.js
index 572e667f..7f90646d 100644
--- a/src/ground-bounce.js
+++ b/src/ground-bounce.js
@@ -47,7 +47,7 @@ function textureMeanAlbedo(map) {
}
function groundAlbedo(material) {
- const surface = !material.graph && material.alphaMode !== 'blend' && !(material.transmission > 0) && !EXCLUDED_TAGS.has(material.tag)
+ const surface = !material.graph && !['blend', 'add'].includes(material.alphaMode) && !(material.transmission > 0) && !EXCLUDED_TAGS.has(material.tag)
if (!surface || !Array.isArray(material.color) || (material.metallic ?? 0) > GROUND_MAXIMUM_METALLIC) {
return null
}
@@ -206,7 +206,7 @@ export function findRoomSurface(parts) {
let area = 0
const albedoSum = [0, 0, 0]
for (const part of parts) {
- if (part.material?.alphaMode === 'blend') {
+ if (['blend', 'add'].includes(part.material?.alphaMode)) {
continue
}
const partArea = areaFacing(part, middle)
diff --git a/src/renderer.js b/src/renderer.js
index b17ffb44..10da0a64 100644
--- a/src/renderer.js
+++ b/src/renderer.js
@@ -25,10 +25,17 @@ import { deformationSupport, requireDeformationSupport, texturedReplaceSupport,
const SHADOW_MAP_SIZE = 2048;
// Liquid and foam see the resolved opaque scene, so they draw in their own pass after it.
const TRANSLUCENT_TAGS = new Set(['liquid', 'foam']);
-const INSTANCE_STRIDE = 41;
+// The 42nd float is the opacity of a blend or add part, so parts that differ only in opacity share a batch.
+const INSTANCE_STRIDE = 42;
+const OPACITY_OFFSET = 41;
// Shaders get this in place of an infinite attenuation distance, which is not a safe uniform value.
const MAX_FINITE_DISTANCE = 3e38;
-const ALPHA_MODES = { opaque: 0, mask: 1, blend: 2 };
+const ALPHA_MODES = { opaque: 0, mask: 1, blend: 2, add: 3 };
+
+/** Blend and add draw after the opaque loop, sorted, without writing depth. */
+function isTranslucentMode(alphaMode) {
+ return alphaMode === 'blend' || alphaMode === 'add';
+}
const ZERO_VECTOR = Object.freeze([0, 0, 0]);
const MATERIAL_MAPS = ['map', 'normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap'];
const MAP_UNIFORMS = ['baseMap', 'normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap'];
@@ -184,7 +191,7 @@ function lightMapState(material) {
function validateAlphaMaterial(material) {
const alphaMode = material.alphaMode ?? 'opaque';
- if (!Object.hasOwn(ALPHA_MODES, alphaMode)) throw new Error("alphaMode must be 'opaque', 'mask' or 'blend'.");
+ if (!Object.hasOwn(ALPHA_MODES, alphaMode)) throw new Error("alphaMode must be 'opaque', 'mask', 'blend' or 'add'.");
for (const field of ['alphaCutoff', 'opacity']) {
const value = material[field] ?? 1;
if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > 1) throw new Error(`${field} must be a number within zero and one.`);
@@ -192,21 +199,27 @@ function validateAlphaMaterial(material) {
if (material.doubleSided !== undefined && typeof material.doubleSided !== 'boolean') throw new TypeError('doubleSided must be a boolean');
}
-/** Alpha settings that every instance of one draw call must share. Fields that a mode ignores are normalized away. */
+/** Opacity of one instance: blend and add parts carry it per instance, so it never splits a batch. */
+function instanceOpacity(material) {
+ const alphaMode = material.alphaMode ?? 'opaque';
+ return isTranslucentMode(alphaMode) ? (material.opacity ?? 1) + (material.opacityBias ?? 0) : 1;
+}
+
+/** Alpha settings that every instance of one draw call must share. Fields that a mode ignores, and the per-instance opacity, are normalized away. */
function materialAlphaState(material) {
validateAlphaMaterial(material);
const alphaMode = material.alphaMode ?? 'opaque';
const alphaCutoff = alphaMode === 'mask' ? material.alphaCutoff ?? 0.5 : 0;
- const opacity = alphaMode === 'opaque' ? 1 : (material.opacity ?? 1) + (material.opacityBias ?? 0);
+ const opacity = alphaMode === 'mask' ? (material.opacity ?? 1) + (material.opacityBias ?? 0) : 1;
return [alphaMode, alphaCutoff, opacity, material.doubleSided === true];
}
// A decal or depth layer draws with a scoped polygon offset so it wins against the surface it lies on (z-fighting).
// Larger layers win over smaller ones; geometry never moves.
-// Translucent glass is not a shadow caster unless the part asks for it.
+// Translucent glass and additive light are not shadow casters unless the part asks for it.
function castsShadow(part) {
- return part.castShadow ?? (part.material.alphaMode ?? 'opaque') !== 'blend';
+ return part.castShadow ?? !isTranslucentMode(part.material.alphaMode ?? 'opaque');
}
function hasMaterialMap(material) {
@@ -266,6 +279,7 @@ function packInstance(data, index, part, normalMatrix) {
copyVector3(data, offset + 32, part.assembly?.offset ?? ZERO_VECTOR);
copyVector3(data, offset + 35, part.assembly?.detailOffset ?? ZERO_VECTOR);
copyVector3(data, offset + 38, material.emissiveColor ?? material.color);
+ data[offset + OPACITY_OFFSET] = instanceOpacity(material);
}
// The objectId mode of RENDER_PASS_MODES in render-passes.js.
@@ -275,7 +289,7 @@ function isCullable(parts) {
const first = parts[0];
if (first.skin || first.morph) return false;
if (DEFORMING_TAGS.has(first.material.tag) && !SWAYING_TAGS.has(first.material.tag)) return false;
- if (renderPass(first.material) !== 'opaque' || materialAlphaState(first.material)[0] === 'blend') return false;
+ if (renderPass(first.material) !== 'opaque' || isTranslucentMode(materialAlphaState(first.material)[0])) return false;
return parts.every(part => !part.assembly || part.crowd);
}
@@ -736,7 +750,7 @@ export class Renderer67 {
finishMainProgram(pendingProgram) {
this.program = finishProgram(this.context, pendingProgram);
- this.uniforms = Object.fromEntries(['materialDielectric', 'materialCoat', 'materialSheen', 'materialAnisotropy', 'materialIridescence', 'lightLinkMask', 'boxMapScale', 'boxMapAxis', 'lightMap', 'lightMapScale', 'hasLightMap', 'viewProjection', 'lightProjection', 'eye', 'armorColor', 'armorSurface', 'exposure', 'inspection', 'shadowMap', 'shadowBiasPerSlope', ...MAP_UNIFORMS, ...MAP_FLAGS, ...SKIN_UNIFORMS, ...MORPH_UNIFORMS, 'normalScale', 'occlusionStrength', 'materialMoss', ...SPLAT_UNIFORMS, 'hdrEnabled', 'time', 'wind', 'worldMode', 'daylight', 'fogColor', 'lightDirection', 'fogDensity', 'waterRipple', 'rippleTime', 'explosionProgress', 'explosionCenter', 'assemblyAmount', 'renderPassMode', 'renderPassDepthRange', 'renderPassObjectBase', 'baseColor', 'surface', 'instanceEmission', 'boxNormalMatrix', ...ALPHA_UNIFORMS].map((name) => [name, this.context.getUniformLocation(this.program, name)]));
+ this.uniforms = Object.fromEntries(['materialDielectric', 'materialCoat', 'materialSheen', 'materialAnisotropy', 'materialIridescence', 'lightLinkMask', 'boxMapScale', 'boxMapAxis', 'lightMap', 'lightMapScale', 'hasLightMap', 'viewProjection', 'lightProjection', 'eye', 'armorColor', 'armorSurface', 'exposure', 'inspection', 'shadowMap', 'shadowBiasPerSlope', ...MAP_UNIFORMS, ...MAP_FLAGS, ...SKIN_UNIFORMS, ...MORPH_UNIFORMS, 'normalScale', 'occlusionStrength', 'materialMoss', ...SPLAT_UNIFORMS, 'hdrEnabled', 'time', 'wind', 'worldMode', 'daylight', 'fogColor', 'lightDirection', 'fogDensity', 'waterRipple', 'rippleTime', 'explosionProgress', 'explosionCenter', 'assemblyAmount', 'renderPassMode', 'renderPassDepthRange', 'renderPassObjectBase', 'baseColor', 'surface', 'instanceEmission', 'instanceOpacity', 'boxNormalMatrix', ...ALPHA_UNIFORMS].map((name) => [name, this.context.getUniformLocation(this.program, name)]));
for (const name of LIGHT_UNIFORMS) {
this.uniforms[name] = this.context.getUniformLocation(this.program, name);
}
@@ -926,7 +940,7 @@ export class Renderer67 {
this.attribute(10, 4, stride * 4, 112);
this.attribute(11, 3, stride * 4, 128);
this.attribute(12, 3, stride * 4, 140);
- this.attribute(15, 3, stride * 4, 152);
+ this.attribute(15, 4, stride * 4, 152);
}
createCullingState(parts) {
@@ -1235,7 +1249,7 @@ export class Renderer67 {
if (!materialUnchanged) {
const alphaState = materialAlphaState(part.material);
const batchAlphaState = [location.batch.alphaMode, location.batch.alphaCutoff, location.batch.opacity, location.batch.doubleSided];
- if (alphaState.some((value, index) => value !== batchAlphaState[index])) throw new Error(`Alpha mode, cutoff, opacity and double-sided changes require a new renderer: ${part.name}`);
+ if (alphaState.some((value, index) => value !== batchAlphaState[index])) throw new Error(`Alpha mode, cutoff, double-sided and mask opacity changes require a new renderer (blend and add opacity may change): ${part.name}`);
}
if (part.geometry !== location.geometry) throw new Error(`Geometry changes require a new renderer: ${part.name}`);
if (!materialUnchanged && renderPass(part.material) !== batchPass(location.batch)) throw new Error(`Moving a part into or out of the liquid or foam pass requires replaceParts: ${part.name}`);
@@ -1520,7 +1534,7 @@ export class Renderer67 {
/** Whether a batch is drawn by the opaque loop, and so by render passes. Its parts take object IDs in this order. */
drawsInOpaqueLoop(batch) {
- return batchPass(batch) === 'opaque' && batch.alphaMode !== 'blend';
+ return batchPass(batch) === 'opaque' && !isTranslucentMode(batch.alphaMode);
}
// Compiled and allocated on first use, so scenes without occlusion pay nothing.
@@ -2005,12 +2019,22 @@ export class Renderer67 {
this.context.bufferSubData(this.context.ARRAY_BUFFER, 0, batch.sortedData);
}
- /** Alpha-blended batches draw after opaque and masked geometry, farthest first, without writing depth. */
+ /** Whether any instance of a blend batch is fully opaque, and so has opaque texels to draw as a cutout first. */
+ hasOpaqueInstance(batch) {
+ for (let index = 0; index < batch.instanceCount; index++) {
+ if (batch.instanceData[index * INSTANCE_STRIDE + OPACITY_OFFSET] >= 0.999) return true;
+ }
+ return false;
+ }
+
+ /** Alpha-blended batches draw after opaque and masked geometry, farthest first, without writing depth. Additive batches draw last. */
drawBlendBatches(frame) {
const context = this.context;
const eye = frame.eye;
const blendBatches = this.batches.filter(batch => batch.alphaMode === 'blend' && batchPass(batch) === 'opaque');
- if (blendBatches.length === 0) return;
+ // Light adds in any order, so additive batches need no sort.
+ const addBatches = this.batches.filter(batch => batch.alphaMode === 'add' && batchPass(batch) === 'opaque');
+ if (blendBatches.length === 0 && addBatches.length === 0) return;
// The liquid and foam pass may have switched program, texture unit 0 and the viewport.
context.bindFramebuffer(context.FRAMEBUFFER, this.multisampleFramebuffer);
context.viewport(0, 0, this.canvas.width, this.canvas.height);
@@ -2031,7 +2055,7 @@ export class Renderer67 {
// Fully opaque texels (most of a baked scene exported as BLEND) draw first as a cutout that writes depth, so they hide
// whatever lies behind them in any draw order. The blend pass below then shades only the translucent texels (depth LESS).
for (const { batch } of ordered) {
- if (batch.opacity >= 0.999) this.drawAlphaBatch({ ...batch, alphaMode: 'mask', alphaCutoff: 0.999 }, true);
+ if (this.hasOpaqueInstance(batch)) this.drawAlphaBatch({ ...batch, alphaMode: 'mask', alphaCutoff: 0.999 }, true);
}
context.enable(context.BLEND);
context.blendFuncSeparate(context.SRC_ALPHA, context.ONE_MINUS_SRC_ALPHA, context.ONE, context.ONE_MINUS_SRC_ALPHA);
@@ -2040,6 +2064,11 @@ export class Renderer67 {
this.uploadSortedInstances(batch, eye);
this.drawAlphaBatch(batch, true);
}
+ if (addBatches.length > 0) {
+ // Source colour times opacity is added to the frame; the destination alpha is kept.
+ context.blendFuncSeparate(context.SRC_ALPHA, context.ONE, context.ZERO, context.ONE);
+ for (const batch of addBatches) this.drawAlphaBatch(batch, true);
+ }
context.depthMask(true);
this.applyDepthLayer(0);
context.disable(context.BLEND);
@@ -2061,6 +2090,7 @@ export class Renderer67 {
context.uniform3f(this.uniforms.baseColor, data[25], data[26], data[27]);
context.uniform4f(this.uniforms.surface, data[28], data[29], data[30], data[31]);
context.uniform4f(this.uniforms.instanceEmission, data[38], data[39], data[40], 0);
+ context.uniform1f(this.uniforms.instanceOpacity, data[OPACITY_OFFSET]);
if (this.shaderFeatures.has('boxMapScale')) context.uniformMatrix3fv(this.uniforms.boxNormalMatrix, false, data.subarray(16, 25));
}
diff --git a/src/shaders.js b/src/shaders.js
index a0effe95..7a3e39c3 100644
--- a/src/shaders.js
+++ b/src/shaders.js
@@ -62,7 +62,7 @@ layout(location=11) in vec3 assemblyOffset;
layout(location=12) in vec3 assemblyDetailOffset;
layout(location=13) in vec4 uvSets;
layout(location=14) in vec4 vertexColor;
-layout(location=15) in vec3 instanceEmissive;
+layout(location=15) in vec4 instanceEmissive;
uniform mat4 viewProjection;
uniform mat4 lightProjection;
uniform float time;
@@ -75,6 +75,7 @@ out vec3 worldPosition, worldNormal;
flat out vec3 baseColor;
flat out vec4 surface;
flat out vec4 instanceEmission;
+flat out float instanceOpacity;
flat out mat3 boxNormalMatrix;
#endif
#ifdef VERTEX_COLORS
@@ -116,7 +117,8 @@ void main() {
lightmapUV = uvSets.zw;
#ifdef INSTANCED
baseColor = instanceColor;
- instanceEmission = vec4(instanceEmissive, gl_InstanceID);
+ instanceEmission = vec4(instanceEmissive.rgb, gl_InstanceID);
+ instanceOpacity = instanceEmissive.w;
surface = instanceSurface;
#endif
#ifdef VERTEX_COLORS
@@ -213,11 +215,13 @@ in vec3 worldPosition, worldNormal;
flat in vec3 baseColor;
flat in vec4 surface;
flat in vec4 instanceEmission;
+flat in float instanceOpacity;
flat in mat3 boxNormalMatrix;
#else
uniform vec3 baseColor;
uniform vec4 surface;
uniform vec4 instanceEmission;
+uniform float instanceOpacity;
uniform mat3 boxNormalMatrix;
#endif
#ifdef VERTEX_COLORS
@@ -480,10 +484,10 @@ vec3 mappedNormal(vec3 normal) {
${featureCode("libraries")}
-${featureCode("worldMossFunction")}// Opaque draws 1, mask resolves to a cutout (smooth coverage with MSAA) and blend keeps the fraction.
+${featureCode("worldMossFunction")}// Opaque draws 1, mask resolves to a cutout (smooth coverage with MSAA), blend and add keep the fraction (per instance opacity times the batch one).
float surfaceAlpha(float textureAlpha) {
if (!USES_ALPHA_MODE) return 1.0;
- float alpha = materialOpacity * textureAlpha;
+ float alpha = materialOpacity * instanceOpacity * textureAlpha;
if (alphaMode > 1.5) return alpha;
if (alphaToCoverage > 0.5) {
float softness = max(fwidth(alpha), 0.0001);
@@ -697,7 +701,8 @@ ${featureCode("afterEmission")}${featureCode("worldAfterEmission")} if (TAG_FLO
radiance = mix(radiance, vec3(0.018, 0.022, 0.026), fog);
}
${featureCode("worldFinal")} float fog = 1.0 - exp(-length(worldPosition - eye) * fogDensity);
- radiance = mix(radiance, fogColor, fog * worldMode);
+ // Additive light fades to black through fog; mixing it toward the fog colour would add a glow of fog.
+ radiance = alphaMode > 2.5 ? radiance * (1.0 - fog * worldMode) : mix(radiance, fogColor, fog * worldMode);
if (inspection > 0.5) radiance = normal * 0.5 + 0.5;
outputColor = vec4(hdrEnabled > 0.5 ? clamp(radiance * exposure, vec3(0), vec3(65504.0)) : pow(toneMap(radiance * exposure), vec3(1.0 / 2.2)), alpha);
if (TAG_FLOOR && inspection < 0.5) {
diff --git a/src/sun-bounce.js b/src/sun-bounce.js
index 6e528ec4..78f9ec8b 100644
--- a/src/sun-bounce.js
+++ b/src/sun-bounce.js
@@ -34,7 +34,7 @@ const KEY_THRESHOLD = 1e-3;
const EXCLUDED_TAGS = new Set(['liquid', 'foam', 'unlit', 'fire', 'smoke']);
function isBounceSurface(part) {
- return part.material?.alphaMode !== 'blend' && !((part.material?.emission ?? 0) > 0) && !EXCLUDED_TAGS.has(part.material?.tag);
+ return !['blend', 'add'].includes(part.material?.alphaMode) && !((part.material?.emission ?? 0) > 0) && !EXCLUDED_TAGS.has(part.material?.tag);
}
function sunOf(environment) {
diff --git a/tests/agent-scene.test.js b/tests/agent-scene.test.js
index 7adb4594..2b7ad9bd 100644
--- a/tests/agent-scene.test.js
+++ b/tests/agent-scene.test.js
@@ -638,3 +638,15 @@ test('a recipe without a materials or geometries list reads them as empty, and t
assert.deepEqual(bare.materials, []);
assert.throws(() => createAgentScene({ format: '67js.scene', schemaVersion: 1 }), /nodes/);
});
+
+test("recipe materials accept alphaMode 'add' and keep it when opacity is below one", () => {
+ assert.ok(AGENT_SCENE_CAPABILITIES.alphaModes.includes('add'));
+ const input = recipe();
+ input.materials.push({ id: 'spark', color: [1, 0.6, 0.2], emission: 4, alphaMode: 'add' });
+ input.materials.push({ id: 'faint spark', color: [1, 0.6, 0.2], alphaMode: 'add', opacity: 0.4 });
+ const exported = createAgentScene(input).exportRecipe();
+ assert.equal(exported.materials.find(material => material.id === 'spark').alphaMode, 'add');
+ assert.equal(exported.materials.find(material => material.id === 'faint spark').alphaMode, 'add');
+ input.materials.push({ id: 'bad', color: [1, 1, 1], alphaMode: 'multiply' });
+ assert.throws(() => createAgentScene(input), /alphaMode must be one of opaque, blend, add/);
+});
diff --git a/tests/crowd-skinning.test.js b/tests/crowd-skinning.test.js
index 32b98ea6..0ea57f10 100644
--- a/tests/crowd-skinning.test.js
+++ b/tests/crowd-skinning.test.js
@@ -147,10 +147,10 @@ test('the renderer culls crowd instances with the bound of the whole clip, and r
assert.equal(culling.levelGeometries.length, 3);
const projection = mat4.perspective(mat4.create(), Math.PI / 4, 16 / 9, 0.5, 200);
const viewProjection = mat4.multiply(mat4.create(), projection, mat4.lookAt(mat4.create(), [0, 2, 12], [0, 1, 0], [0, 1, 0]));
- const instanceData = new Float32Array(batch.length * 41);
- batch.forEach((part, index) => instanceData.set(part.matrix, index * 41));
+ const instanceData = new Float32Array(batch.length * 42);
+ batch.forEach((part, index) => instanceData.set(part.matrix, index * 42));
const selection = selectInstances(new InstanceSelection(batch.length, 3), {
- instanceData, instanceCount: batch.length, stride: 41, bounds: culling.bounds, levelErrors: culling.levelErrors,
+ instanceData, instanceCount: batch.length, stride: 42, bounds: culling.bounds, levelErrors: culling.levelErrors,
planes: extractFrustumPlanes(viewProjection, new Float32Array(24)), viewProjection, pixelsPerUnit: 540 / 2 * projection[5], pixelError: 1,
});
assert.equal(selection.visibleCount, 1, 'only the instance in front of the camera draws');
diff --git a/tests/export.test.js b/tests/export.test.js
index 649db4b6..ed59692e 100644
--- a/tests/export.test.js
+++ b/tests/export.test.js
@@ -292,3 +292,13 @@ test('GLB Float32 rotated nonuniform, reflected and tiny TRS transforms roundtri
}
}
});
+
+test('GLB export writes an additive material as BLEND because glTF has no additive mode', async () => {
+ const part = createModel()[0];
+ const material = { ...part.material, alphaMode: 'add', opacity: 0.5 };
+ const gltf = await new GLTFLoader().parseAsync(exportGlb([{ ...part, material }]), '');
+ let loaded;
+ gltf.scene.traverse((node) => { if (node.isMesh) loaded = node.material; });
+ assert.equal(loaded.transparent, true);
+ assert.ok(Math.abs(loaded.opacity - 0.5) < 1e-6);
+});
diff --git a/tests/film.test.js b/tests/film.test.js
index e6030575..c8e979b7 100644
--- a/tests/film.test.js
+++ b/tests/film.test.js
@@ -91,7 +91,7 @@ test('sets keep shared geometry, valid surfaces and the 384 MiB target budget',
const geometries = new Set(scene.parts.map(part => part.geometry));
// Two shared garment contours replace rectangular collars and lapels.
assert.ok(geometries.size <= 15);
- let geometryBytes = scene.parts.length * 41 * 4;
+ let geometryBytes = scene.parts.length * 42 * 4;
for (const geometry of geometries) {
geometryBytes += geometry.positions.byteLength + geometry.normals.byteLength + geometry.indices.byteLength;
geometryBytes += geometry.colors?.byteLength ?? 0;
diff --git a/tests/morph-renderer.test.js b/tests/morph-renderer.test.js
index 8a801d4a..b2130b2f 100644
--- a/tests/morph-renderer.test.js
+++ b/tests/morph-renderer.test.js
@@ -31,7 +31,7 @@ function retainedRenderer(parts) {
morphTexture: { info: validateMorphGeometry(first.geometry, first.morph) },
morphWeights: new Float32Array(first.morph.weights),
instanceBuffer: {},
- instanceData: new Float32Array(group.length * 41),
+ instanceData: new Float32Array(group.length * 42),
castShadow: true,
alphaMode: 'opaque',
alphaCutoff: 0,
diff --git a/tests/render-culling.test.js b/tests/render-culling.test.js
index 0da56d25..9cb50e5a 100644
--- a/tests/render-culling.test.js
+++ b/tests/render-culling.test.js
@@ -6,7 +6,7 @@ import { generateGeometryLods } from '../src/mesh-lod.js';
import { Renderer67 } from '../src/renderer.js';
import { InstanceSelection, chooseLevel, extractFrustumPlanes, geometryBoundingSphere, selectInstances } from '../src/render-culling.js';
-const STRIDE = 41;
+const STRIDE = 42;
const CANVAS_HEIGHT = 540;
function cameraMatrices(eye = [0, 0, 10], target = [0, 0, 0]) {
diff --git a/tests/renderer.test.js b/tests/renderer.test.js
index cac714cb..13ac6531 100644
--- a/tests/renderer.test.js
+++ b/tests/renderer.test.js
@@ -13,7 +13,7 @@ function part(name, geometry = {}, map) {
function retainedRenderer(parts) {
const writes = [];
const renderer = Object.create(Renderer67.prototype);
- const batch = { instanceBuffer: {}, instanceData: new Float32Array(parts.length * 41).fill(7), castShadow: true, alphaMode: 'opaque', alphaCutoff: 0, opacity: 1, doubleSided: false };
+ const batch = { instanceBuffer: {}, instanceData: new Float32Array(parts.length * 42).fill(7), castShadow: true, alphaMode: 'opaque', alphaCutoff: 0, opacity: 1, doubleSided: false };
renderer.context = { ARRAY_BUFFER: 34962, bindBuffer() {}, bufferSubData(target, offset, data) { writes.push({ target, offset, data: Array.from(data) }); } };
renderer.partLocations = new Map(parts.map((item, index) => [item, {
batch, index, geometry: item.geometry, map: item.material.map ?? null, normalMatrix: mat3.create(), layerState: materialLayerState(item.material), skin: item.skin ?? null,
@@ -83,7 +83,7 @@ function alphaPart(name, geometry, materialFields) {
return { ...base, material: { ...base.material, ...materialFields } };
}
-test('alpha mode, cutoff, opacity and double-sided state partition batches', () => {
+test('alpha mode, cutoff and double-sided state partition batches, while blend and add opacity does not', () => {
const geometry = {};
const parts = [
alphaPart('opaque', geometry, {}),
@@ -94,9 +94,13 @@ test('alpha mode, cutoff, opacity and double-sided state partition batches', ()
alphaPart('glass', geometry, { alphaMode: 'blend', opacity: 0.3 }),
alphaPart('faint glass', geometry, { alphaMode: 'blend', opacity: 0.1 }),
alphaPart('opaque with ignored opacity', geometry, { opacity: 0.2 }),
+ alphaPart('spark', geometry, { alphaMode: 'add', opacity: 0.5 }),
+ alphaPart('flare', geometry, { alphaMode: 'add', opacity: 1 }),
];
const groups = groupParts(parts);
assert.equal(groups.length, 6);
+ assert.deepEqual(groups.find(group => group[0].name === 'glass').map(item => item.name), ['glass', 'faint glass'], 'two blend parts with different opacity share a batch');
+ assert.deepEqual(groups.find(group => group[0].name === 'spark').map(item => item.name), ['spark', 'flare'], 'add parts share a batch whatever their opacity');
assert.deepEqual(groups[0].map(item => item.name), ['opaque', 'opaque with ignored opacity']);
assert.deepEqual(groups[1].map(item => item.name), ['leaf', 'second leaf']);
});
@@ -119,11 +123,10 @@ test('blend batches skip shadows by default and alpha state cannot change after
assert.equal(groupParts([glass, { ...glass, castShadow: true }]).length, 2);
const { renderer, batch, writes } = retainedRenderer([glass]);
batch.alphaMode = 'blend';
- batch.opacity = 0.5;
batch.castShadow = false;
renderer.updateParts([glass]);
assert.equal(writes.length, 1);
- for (const change of [{ alphaMode: 'mask' }, { opacity: 0.6 }, { doubleSided: true }]) {
+ for (const change of [{ alphaMode: 'mask' }, { alphaMode: 'add' }, { doubleSided: true }]) {
glass.material = { ...glass.material, ...change };
assert.throws(() => renderer.updateParts([glass]), /require a new renderer/);
glass.material = alphaPart('glass', geometry, { alphaMode: 'blend', opacity: 0.5 }).material;
@@ -131,15 +134,49 @@ test('blend batches skip shadows by default and alpha state cannot change after
assert.equal(writes.length, 1);
});
+test('updateParts changes the opacity of blend and add parts without a new batch', () => {
+ const geometry = {};
+ for (const alphaMode of ['blend', 'add']) {
+ const trail = alphaPart('trail', geometry, { alphaMode, opacity: 0.5 });
+ const { renderer, batch, writes } = retainedRenderer([trail]);
+ batch.alphaMode = alphaMode;
+ batch.castShadow = false;
+ for (const opacity of [0.25, 0.75, 0]) {
+ trail.material = { ...trail.material, opacity };
+ renderer.updateParts([trail]);
+ assert.equal(batch.instanceData[41], opacity, `${alphaMode} opacity reaches the instance data`);
+ }
+ assert.equal(writes.length, 3);
+ }
+ const leaf = alphaPart('leaf', geometry, { alphaMode: 'mask', opacity: 0.5 });
+ const { renderer, batch } = retainedRenderer([leaf]);
+ batch.alphaMode = 'mask';
+ batch.opacity = 0.5;
+ leaf.material = { ...leaf.material, opacity: 0.6 };
+ assert.throws(() => renderer.updateParts([leaf]), /require a new renderer/);
+});
+
+test('opaque and mask parts keep an instance opacity of one', () => {
+ for (const fields of [{}, { alphaMode: 'mask', opacity: 0.4 }]) {
+ const item = alphaPart('solid', {}, fields);
+ const { renderer, batch } = retainedRenderer([item]);
+ batch.alphaMode = item.material.alphaMode ?? 'opaque';
+ batch.opacity = fields.opacity ?? 1;
+ batch.alphaCutoff = fields.alphaMode === 'mask' ? 0.5 : 0;
+ renderer.updateParts([item]);
+ assert.equal(batch.instanceData[41], 1);
+ }
+});
+
test('blend instances upload back to front by distance to the eye', () => {
const uploads = [];
const renderer = Object.create(Renderer67.prototype);
renderer.context = { ARRAY_BUFFER: 34962, bindBuffer() {}, bufferSubData(target, offset, data) { uploads.push(Array.from(data)); } };
- const instanceData = new Float32Array(3 * 41);
- [1, 9, 4].forEach((distance, index) => { instanceData[index * 41 + 14] = -distance; instanceData[index * 41] = index; });
+ const instanceData = new Float32Array(3 * 42);
+ [1, 9, 4].forEach((distance, index) => { instanceData[index * 42 + 14] = -distance; instanceData[index * 42] = index; });
const batch = { instanceBuffer: {}, instanceData, instanceCount: 3 };
renderer.uploadSortedInstances(batch, [0, 0, 0]);
- const order = [0, 1, 2].map(rank => uploads[0][rank * 41]);
+ const order = [0, 1, 2].map(rank => uploads[0][rank * 42]);
assert.deepEqual(order, [1, 2, 0]);
});
@@ -538,6 +575,7 @@ test('blend batches draw their opaque texels with depth writes before the blende
const state = { depthMask: true, blend: false };
const context = new Proxy({}, {
get(target, name) {
+ if (name === 'blendFuncSeparate') return (...functions) => blendFunctions.push(functions.join());
if (name === 'depthMask') return (value) => { state.depthMask = value; };
if (name === 'enable') return (capability) => { if (capability === 'BLEND') state.blend = true; };
if (name === 'disable') return (capability) => { if (capability === 'BLEND') state.blend = false; };
@@ -545,22 +583,28 @@ test('blend batches draw their opaque texels with depth writes before the blende
return () => {};
},
});
+ const blendFunctions = [];
+ context.blendFuncSeparate = (...functions) => blendFunctions.push(functions.join());
const renderer = Object.create(Renderer67.prototype);
renderer.context = context;
renderer.uniforms = { shadowMap: 'shadowMap' };
renderer.canvas = { width: 4, height: 4 };
- const baked = { alphaMode: 'blend', alphaCutoff: 0, opacity: 1, instanceCount: 1, instanceData: new Float32Array(41) };
- const glass = { alphaMode: 'blend', alphaCutoff: 0, opacity: 0.3, instanceCount: 1, instanceData: new Float32Array(41) };
- renderer.batches = [baked, glass];
+ const baked = { alphaMode: 'blend', alphaCutoff: 0, opacity: 1, instanceCount: 1, instanceData: new Float32Array(42).fill(1) };
+ const glass = { alphaMode: 'blend', alphaCutoff: 0, opacity: 1, instanceCount: 1, instanceData: new Float32Array(42).fill(0.3) };
+ const glow = { alphaMode: 'add', alphaCutoff: 0, opacity: 1, instanceCount: 1, instanceData: new Float32Array(42).fill(0.8) };
+ renderer.batches = [glow, baked, glass];
renderer.uploadSortedInstances = () => {};
renderer.drawAlphaBatch = (batch) => {
- draws.push({ opacity: batch.opacity, depthMask: state.depthMask, blend: state.blend, alphaMode: batch.alphaMode, alphaCutoff: batch.alphaCutoff });
+ draws.push({ opacity: batch.instanceData[41], blendFunction: blendFunctions.at(-1), depthMask: state.depthMask, blend: state.blend, alphaMode: batch.alphaMode, alphaCutoff: batch.alphaCutoff });
};
renderer.drawBlendBatches({ eye: [0, 0, 0] });
- assert.equal(draws.length, 3);
- assert.deepEqual(draws[0], { opacity: 1, depthMask: true, blend: false, alphaMode: 'mask', alphaCutoff: 0.999 });
- assert.ok(draws.slice(1).every(draw => draw.blend && !draw.depthMask && draw.alphaMode === 'blend'));
- assert.equal(draws.filter(draw => draw.opacity === 0.3).length, 1, 'a translucent material has no opaque texels to draw first');
+ assert.equal(draws.length, 4);
+ assert.deepEqual(draws[0], { opacity: 1, blendFunction: undefined, depthMask: true, blend: false, alphaMode: 'mask', alphaCutoff: 0.999 });
+ assert.ok(draws.slice(1).every(draw => draw.blend && !draw.depthMask));
+ assert.deepEqual(draws.map(draw => draw.alphaMode), ['mask', 'blend', 'blend', 'add'], 'add draws after every blend batch');
+ assert.equal(draws[3].blendFunction, 'SRC_ALPHA,ONE,ZERO,ONE', 'add sums source and frame');
+ assert.equal(draws[1].blendFunction, 'SRC_ALPHA,ONE_MINUS_SRC_ALPHA,ONE,ONE_MINUS_SRC_ALPHA');
+ assert.equal(draws.filter(draw => draw.opacity === Math.fround(0.3)).length, 1, 'a translucent material has no opaque texels to draw first');
assert.equal(baked.alphaCutoff, 0);
});
diff --git a/tests/update-parts-fast-path.test.js b/tests/update-parts-fast-path.test.js
index af7e25e7..ceabdf62 100644
--- a/tests/update-parts-fast-path.test.js
+++ b/tests/update-parts-fast-path.test.js
@@ -13,7 +13,7 @@ function createPart(name, material = {}) {
function createRenderer(parts) {
const renderer = Object.create(Renderer67.prototype);
- const batch = { instanceBuffer: {}, instanceData: new Float32Array(parts.length * 41), castShadow: true, alphaMode: 'opaque', alphaCutoff: 0, opacity: 1, doubleSided: false, pass: 'opaque' };
+ const batch = { instanceBuffer: {}, instanceData: new Float32Array(parts.length * 42), castShadow: true, alphaMode: 'opaque', alphaCutoff: 0, opacity: 1, doubleSided: false, pass: 'opaque' };
renderer.context = { ARRAY_BUFFER: 34962, bindBuffer() {}, bufferSubData() {} };
renderer.partLocations = new Map(parts.map((part, index) => [part, {
batch, index, geometry: GEOMETRY, map: null, normalMatrix: mat3.create(), layerState: materialLayerState({}), skin: null,
@@ -56,10 +56,10 @@ test('matrix, colour, emission and roughness changes update through the fast pat
parts[1].material.roughness = 0.6;
parts[1].material.emission = 2;
assert.equal(renderer.updateParts(parts), 2);
- assert.equal(batch.instanceData[41 + 12], 5);
- assert.deepEqual(Array.from(batch.instanceData.subarray(41 + 25, 41 + 28)).map(value => Math.round(value * 10)), [9, 8, 7]);
- assert.equal(Math.round(batch.instanceData[41 + 29] * 10), 6);
- assert.equal(batch.instanceData[41 + 30], 2);
+ assert.equal(batch.instanceData[42 + 12], 5);
+ assert.deepEqual(Array.from(batch.instanceData.subarray(42 + 25, 42 + 28)).map(value => Math.round(value * 10)), [9, 8, 7]);
+ assert.equal(Math.round(batch.instanceData[42 + 29] * 10), 6);
+ assert.equal(batch.instanceData[42 + 30], 2);
});
test('rejections still throw after the fast path has been taken', () => {