Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add alpha mask, blend and double-sided materials (pre-merge)

Nguyen Xuan An12bc05819d52
diff --git a/docs/guide.md b/docs/guide.md
index 861e3d71..f8ebf5ea 100644
--- a/docs/guide.md
+++ b/docs/guide.md
@@ -187,6 +187,8 @@ The optional GLB addon creates these descriptors. HDR requires `EXT_color_buffer
Tags select specialized behavior: `armor` allows studio finish overrides. `floor` is a studio floor. `water` adds animated normals and ripples. `foliage` and `grass` add wind.
+`material.alphaMode` is `'opaque'` (default), `'mask'` (cutout at `alphaCutoff`, default 0.5, shadows follow it) or `'blend'` (drawn last, back to front, no depth write). `material.opacity` (default 1) multiplies the base map alpha. `material.doubleSided` (default false) disables back-face culling and lights both faces. These are batch state and cannot change after upload. See `docs/material-maps.md`.
+
`terrain` adds surface variation. `fire` and `smoke` support film effects. `unlit` is a flat color. Other tags use ordinary PBR shading.
## Renderer reference
diff --git a/docs/material-maps.md b/docs/material-maps.md
index 833199d9..8de26282 100644
--- a/docs/material-maps.md
+++ b/docs/material-maps.md
@@ -78,9 +78,28 @@ Invalid sampler values, texture indices, scales, or missing UVs fail before reso
Renderer disposal deletes every cached GPU texture. Asset disposal closes each shared decoded image once.
+## Alpha and double-sided materials
+
+| Field | Default | Meaning |
+| --- | --- | --- |
+| `alphaMode` | `'opaque'` | `'opaque'`, `'mask'` (cutout) or `'blend'` (translucent). |
+| `alphaCutoff` | `0.5` | Mask only. Fragments with alpha below it are discarded. |
+| `opacity` | `1` | Multiplies the base map alpha. Ignored by `opaque`. |
+| `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, 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.
+- 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.
+
## Limits
-Texture transforms, UV channels beyond zero, transparency, alpha masking, and double-sided glTF materials remain unsupported.
+Texture transforms, UV channels beyond zero, and vertex alpha below one remain unsupported.
Skinning, morph targets, compressed texture formats, and unsupported glTF extensions fail explicitly.
The new PBR maps require a standard material tag, including `gltf` or `armor`.
Procedural tags such as water, terrain, foliage, floor, fire, and smoke reject the new channels.
diff --git a/skills/build-67js-scene/references/scene-contract.md b/skills/build-67js-scene/references/scene-contract.md
index 86b29933..90525158 100644
--- a/skills/build-67js-scene/references/scene-contract.md
+++ b/skills/build-67js-scene/references/scene-contract.md
@@ -70,6 +70,8 @@ Read `docs/volumetric.md` for controls, resource cost and limitations before aut
`frame.environment.volumeFog` replaces the entire constructor fog object, with defaults for omitted fields.
Use absolute frame time for reproducible density drift. Local point lights do not scatter in fog yet.
+Material alpha fields: `alphaMode` `'opaque'` (default), `'mask'` (cutout, `alphaCutoff` default 0.5, shadows follow the cutout, smooth edges with MSAA) or `'blend'` (translucent, drawn after opaque, sorted back to front, no shadow unless `castShadow: true`). `opacity` (0 to 1, default 1) multiplies the base map alpha. `doubleSided` (default false) draws both faces with a flipped back-face normal. Use `mask` plus `doubleSided` for leaf cards. All four are batch state: changing them after upload requires a new renderer.
+
`part.castShadow: false` omits a mesh from shadows while leaving it visible and opaque.
Changing its casting regime requires a new renderer. Shadow-casting groups use separate batches.
diff --git a/src/export.js b/src/export.js
index a30ab4a2..4198eb2f 100644
--- a/src/export.js
+++ b/src/export.js
@@ -14,6 +14,23 @@ function validateFloatChannel(values, length, label, bounded = false) {
}
}
+const GLTF_ALPHA_MODES = { mask: 'MASK', blend: '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'.");
+ gltfMaterial.alphaMode = GLTF_ALPHA_MODES[alphaMode];
+ validateFactor(material.opacity ?? 1, 'opacity');
+ gltfMaterial.pbrMetallicRoughness.baseColorFactor[3] = material.opacity ?? 1;
+ }
+ if (alphaMode === 'mask') {
+ validateFactor(material.alphaCutoff ?? 0.5, 'alphaCutoff');
+ gltfMaterial.alphaCutoff = material.alphaCutoff ?? 0.5;
+ }
+ if (material.doubleSided === true) gltfMaterial.doubleSided = true;
+}
+
function validateFactor(value, label, maximum = 1) {
if (!Number.isFinite(value) || !Number.isFinite(Math.fround(value)) || value < 0 || value > maximum) {
throw new RangeError(`${label} requires a finite nonnegative Float32 value${maximum === 1 ? ' within [0,1]' : ''}.`);
@@ -170,6 +187,7 @@ export function exportGlb(parts) {
pbrMetallicRoughness: { baseColorFactor: [...part.material.color, 1], metallicFactor: part.material.metallic, roughnessFactor: part.material.roughness },
emissiveFactor: (part.material.emission ?? 0) === 0 ? [0, 0, 0] : Array.from(part.material.emissiveColor ?? part.material.color),
};
+ writeAlphaFields(material, part.material);
const strength = part.material.emission ?? 0;
if (strength !== 0 && strength !== 1) {
material.extensions = { [EMISSIVE_STRENGTH]: { emissiveStrength: strength } };
diff --git a/src/gltf.js b/src/gltf.js
index ba2f7b28..ea743d13 100644
--- a/src/gltf.js
+++ b/src/gltf.js
@@ -6,13 +6,14 @@ import { MAX_MORPH_TARGETS, createMorphPose, validateMorphGeometry, validateMorp
export const GLTF_CAPABILITIES = Object.freeze({
formats: ['glb', 'gltf'],
- supported: ['triangle meshes', 'world transforms', 'rigid node animations', 'four-influence skeletal skinning', 'joint node animations', 'relative POSITION/NORMAL morph targets', 'morph weight animations', 'PNG/JPEG base color textures', 'normal/occlusion/emissive/metallic-roughness textures', 'TEXCOORD_0', 'linear RGB vertex colors', 'metallic roughness factors', 'emissive factors', 'KHR_mesh_quantization', 'KHR_materials_emissive_strength'],
- unsupported: ['more than four skin influences', 'singular weighted skin transforms', 'reflected skin transforms', 'TANGENT morph targets', 'morph targets without authored base normals', 'vertex alpha below one', 'alpha blending or masking', 'double-sided materials', 'texture transforms', 'DRACO', 'KTX2', 'GPU instancing'],
+ supported: ['triangle meshes', 'world transforms', 'rigid node animations', 'four-influence skeletal skinning', 'joint node animations', 'relative POSITION/NORMAL morph targets', 'morph weight animations', 'PNG/JPEG base color textures', 'normal/occlusion/emissive/metallic-roughness textures', 'TEXCOORD_0', 'linear RGB vertex colors', 'metallic roughness factors', 'emissive factors', 'alpha mask and blend modes', 'double-sided materials', 'KHR_mesh_quantization', 'KHR_materials_emissive_strength'],
+ unsupported: ['more than four skin influences', 'singular weighted skin transforms', 'reflected skin transforms', 'TANGENT morph targets', 'morph targets without authored base normals', 'vertex alpha below one', 'texture transforms', 'DRACO', 'KTX2', 'GPU instancing'],
});
const DEFAULT_MAX_BYTES = 32 * 1024 * 1024;
const DEFAULT_MAX_VERTICES = 2_000_000;
const ALLOWED_EXTENSIONS = new Set(['KHR_mesh_quantization', 'KHR_materials_emissive_strength']);
+const GLTF_ALPHA_MODES = { OPAQUE: 'opaque', MASK: 'mask', BLEND: 'blend' };
const WRAPPING = { 1000: 10497, 1001: 33071, 1002: 33648 };
const FILTERING = { 1003: 9728, 1004: 9984, 1005: 9986, 1006: 9729, 1007: 9985, 1008: 9987 };
const MATERIAL_TEXTURES = [
@@ -241,8 +242,10 @@ function validateDocument(document, limits) {
for (const factor of [pbr.metallicFactor ?? 1, pbr.roughnessFactor ?? 1]) {
if (!Number.isFinite(factor) || factor < 0 || factor > 1) throw new Error('Invalid glTF metallic or roughness factor.');
}
- if ((material.alphaMode ?? 'OPAQUE') !== 'OPAQUE') throw new Error(`Unsupported alpha mode: ${material.alphaMode}.`);
- if (material.doubleSided) throw new Error('Double-sided materials are unsupported.');
+ if (!Object.hasOwn(GLTF_ALPHA_MODES, material.alphaMode ?? 'OPAQUE')) throw new Error(`Unsupported alpha mode: ${material.alphaMode}.`);
+ const alphaCutoff = material.alphaCutoff ?? 0.5;
+ if (!Number.isFinite(alphaCutoff) || alphaCutoff < 0 || alphaCutoff > 1) throw new Error('Invalid glTF alphaCutoff.');
+ if (material.doubleSided !== undefined && typeof material.doubleSided !== 'boolean') throw new Error('glTF doubleSided must be a boolean.');
for (const [, field] of MATERIAL_TEXTURES) {
const texture = materialTexture(material, field);
if (!texture) continue;
@@ -667,6 +670,10 @@ function convertMaterial(source, limits, maps, definition = {}) {
normalScale: [definition.normalTexture?.scale ?? 1, definition.normalTexture?.scale ?? 1],
occlusionStrength: source.aoMapIntensity,
};
+ material.alphaMode = GLTF_ALPHA_MODES[definition.alphaMode ?? 'OPAQUE'];
+ material.alphaCutoff = definition.alphaCutoff ?? 0.5;
+ material.opacity = definition.pbrMetallicRoughness?.baseColorFactor?.[3] ?? 1;
+ material.doubleSided = definition.doubleSided ?? false;
if (!material.emissiveColor.some(value => value > 0)) material.emission = 0;
if (!Number.isFinite(Math.fround(material.emission)) || material.emission < 0) throw new Error('Emissive intensity must be a finite nonnegative float.');
for (const [field, , colorSpace] of MATERIAL_TEXTURES) {
diff --git a/src/renderer.js b/src/renderer.js
index 58b19af1..8dd19aa9 100644
--- a/src/renderer.js
+++ b/src/renderer.js
@@ -11,6 +11,7 @@ import { validateMorphGeometry, validateMorphPose, validateMorphTransform, packM
const MATERIAL_TAGS = { armor: 1, floor: 2, water: 3, foliage: 4, terrain: 5, grass: 7, fire: 8, smoke: 9, unlit: 10 };
const INSTANCE_STRIDE = 41;
+const ALPHA_MODES = { opaque: 0, mask: 1, blend: 2 };
const ZERO_VECTOR = Object.freeze([0, 0, 0]);
const MATERIAL_MAPS = ['map', 'normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap'];
const MAP_UNIFORMS = ['baseMap', 'normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap'];
@@ -18,6 +19,8 @@ const MAP_FLAGS = ['hasBaseMap', 'hasNormalMap', 'hasMetallicRoughnessMap', 'has
const DEFAULT_NORMAL_SCALE = [1, 1];
const PROCEDURAL_MATERIAL_TAGS = new Set(['water', 'foliage', 'grass', 'terrain', 'floor', 'fire', 'smoke']);
const SKIN_UNIFORMS = ['skinEnabled', 'skinInfluences', 'jointPalette'];
+const ALPHA_UNIFORMS = ['alphaMode', 'alphaCutoff', 'materialOpacity', 'alphaToCoverage', 'doubleSided'];
+const DEPTH_ALPHA_UNIFORMS = ['alphaMasked', 'alphaCutoff', 'materialOpacity', 'hasBaseMap', 'baseMap'];
const MORPH_UNIFORMS = ['morphEnabled', 'morphVertexCount', 'morphTargetCount', 'morphWeights[0]', 'morphTargets'];
function validateMaterialMaps(material) {
@@ -42,6 +45,30 @@ function materialMapState(material) {
return [...MATERIAL_MAPS.map(field => material[field] ?? null), normalScale[0], normalScale[1], occlusionStrength];
}
+function validateAlphaMaterial(material) {
+ const alphaMode = material.alphaMode ?? 'opaque';
+ if (!Object.hasOwn(ALPHA_MODES, alphaMode)) throw new Error("alphaMode must be 'opaque', 'mask' or 'blend'.");
+ 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.`);
+ }
+ 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. */
+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;
+ return [alphaMode, alphaCutoff, opacity, material.doubleSided === true];
+}
+
+// Translucent glass is not a shadow caster unless the part asks for it.
+function castsShadow(part) {
+ return part.castShadow ?? (part.material.alphaMode ?? 'opaque') !== 'blend';
+}
+
function hasMaterialMap(material) {
return MATERIAL_MAPS.some(field => material[field]);
}
@@ -138,7 +165,7 @@ export function groupParts(parts, batching = true) {
const key = batching ? part.geometry : part;
if (!groups.has(key)) groups.set(key, new Map());
let maps = groups.get(key);
- for (const value of [...materialMapState(part.material), part.skin ?? null, part.morph ?? null, part.castShadow !== false]) {
+ for (const value of [...materialMapState(part.material), part.skin ?? null, part.morph ?? null, castsShadow(part), ...materialAlphaState(part.material)]) {
if (!maps.has(value)) maps.set(value, new Map());
maps = maps.get(value);
}
@@ -292,7 +319,7 @@ export class Renderer67 {
this.inverseViewProjection = mat4.create();
this.program = compileProgram(this.context, benchmark ? benchmarkVertexShader : vertexShader, benchmark ? benchmarkFragmentShader : fragmentShader);
this.depthProgram = compileProgram(this.context, depthVertexShader, depthFragmentShader);
- this.uniforms = Object.fromEntries(['viewProjection', 'lightProjection', 'eye', 'armorColor', 'armorSurface', 'exposure', 'inspection', 'shadowMap', ...MAP_UNIFORMS, ...MAP_FLAGS, ...SKIN_UNIFORMS, ...MORPH_UNIFORMS, 'normalScale', 'occlusionStrength', 'hdrEnabled', 'time', 'wind', 'worldMode', 'daylight', 'fogColor', 'lightDirection', 'fogDensity', 'waterRipple', 'rippleTime', 'explosionProgress', 'explosionCenter', 'assemblyAmount'].map((name) => [name, this.context.getUniformLocation(this.program, name)]));
+ this.uniforms = Object.fromEntries(['viewProjection', 'lightProjection', 'eye', 'armorColor', 'armorSurface', 'exposure', 'inspection', 'shadowMap', ...MAP_UNIFORMS, ...MAP_FLAGS, ...SKIN_UNIFORMS, ...MORPH_UNIFORMS, 'normalScale', 'occlusionStrength', 'hdrEnabled', 'time', 'wind', 'worldMode', 'daylight', 'fogColor', 'lightDirection', 'fogDensity', 'waterRipple', 'rippleTime', 'explosionProgress', 'explosionCenter', 'assemblyAmount', ...ALPHA_UNIFORMS].map((name) => [name, this.context.getUniformLocation(this.program, name)]));
for (const name of ['pointLightCount', 'pointLightPositions[0]', 'pointLightColors[0]', 'pointLightRadii[0]', 'keyColor', 'fillIntensity', 'ambientIntensity']) {
this.uniforms[name] = this.context.getUniformLocation(this.program, name);
}
@@ -306,6 +333,7 @@ export class Renderer67 {
this.bloomUniforms = Object.fromEntries(['sourceTexture', 'texelDirection', 'threshold', 'extract'].map(name => [name, this.context.getUniformLocation(this.bloomProgram, name)]));
this.skyUniforms = Object.fromEntries(['skyTop', 'skyBottom', 'sunDirection', 'inverseViewProjection', 'eye', 'time', 'daylight', 'hdrEnabled'].map((name) => [name, this.context.getUniformLocation(this.skyProgram, name)]));
}
+ this.depthAlphaUniforms = Object.fromEntries(DEPTH_ALPHA_UNIFORMS.map(name => [name, this.context.getUniformLocation(this.depthProgram, name)]));
this.depthUniform = this.context.getUniformLocation(this.depthProgram, 'lightProjection');
this.depthAssemblyUniform = this.context.getUniformLocation(this.depthProgram, 'assemblyAmount');
this.partCount = parts.length;
@@ -455,7 +483,8 @@ export class Renderer67 {
const morph = parts[0].morph ?? null;
const morphTexture = morph ? this.createMorphTexture(geometry, morph) : null;
const morphWeights = morph ? new Float32Array(morph.weights) : null;
- const batch = { parts: [...parts], vertexArray, instanceBuffer, instanceData, textures, mapState, texture: textures[0], map, skin, skinTexture, influenceTexture, morph, morphTexture, morphWeights, indexCount: geometry.indices.length, instanceCount: parts.length, floor: parts[0].material.tag === 'floor', castShadow: parts[0].castShadow !== false };
+ const [alphaMode, alphaCutoff, opacity, doubleSided] = materialAlphaState(parts[0].material);
+ const batch = { alphaMode, alphaCutoff, opacity, doubleSided, parts: [...parts], vertexArray, instanceBuffer, instanceData, textures, mapState, texture: textures[0], map, skin, skinTexture, influenceTexture, morph, morphTexture, morphWeights, indexCount: geometry.indices.length, instanceCount: parts.length, floor: parts[0].material.tag === 'floor', castShadow: castsShadow(parts[0]) };
parts.forEach((part, index) => this.partLocations.set(part, { batch, index, geometry: part.geometry, map, mapState, skin, jointMatrices: skin?.jointMatrices, skinIndices: geometry.skinIndices, skinWeights: geometry.skinWeights, morph, morphWeights: morph?.weights, morphTargets: geometry.morphTargets, normalMatrix: mat3.create(), committedMatrix: batch.instanceData.subarray(index * INSTANCE_STRIDE, index * INSTANCE_STRIDE + 16) }));
return batch;
}
@@ -488,8 +517,10 @@ export class Renderer67 {
const batch = location?.batch;
const mapState = materialMapState(first.material);
const sameParts = batch?.parts.length === group.length && batch.parts.every((part, index) => part === group[index]);
- const sameState = location?.geometry === first.geometry && batch?.castShadow === (first.castShadow !== false) &&
+ const alphaState = materialAlphaState(first.material);
+ const sameState = location?.geometry === first.geometry && batch?.castShadow === castsShadow(first) &&
batch.floor === (first.material.tag === 'floor') &&
+ [batch.alphaMode, batch.alphaCutoff, batch.opacity, batch.doubleSided].every((value, index) => value === alphaState[index]) &&
batch.mapState.every((value, index) => value === mapState[index]);
if (sameParts && sameState) {
retained.add(batch);
@@ -618,7 +649,10 @@ export class Renderer67 {
const location = this.partLocations.get(part);
if (!location) throw new Error(`Unknown part identity: ${part.name}`);
if (part.castShadow !== undefined && typeof part.castShadow !== 'boolean') throw new TypeError('castShadow must be a boolean');
- if ((part.castShadow !== false) !== location.batch.castShadow) throw new Error(`Shadow casting changes require a new renderer: ${part.name}`);
+ if (castsShadow(part) !== location.batch.castShadow) throw new Error(`Shadow casting changes require a new renderer: ${part.name}`);
+ 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 (part.geometry !== location.geometry) throw new Error(`Geometry changes require a new renderer: ${part.name}`);
if ((part.skin ?? null) !== location.skin || part.skin?.jointMatrices !== location.jointMatrices || part.geometry.skinIndices !== location.skinIndices || part.geometry.skinWeights !== location.skinWeights) throw new Error(`Skin identity changes require a new renderer: ${part.name}`);
if (part.skin) {
@@ -716,10 +750,13 @@ export class Renderer67 {
context.useProgram(this.depthProgram);
context.uniformMatrix4fv(this.depthUniform, false, this.lightProjection);
context.uniform1f(this.depthAssemblyUniform, this.assemblyAmount ?? 0);
+ // The base map sampler must not alias the shadow texture on unit 0 while that texture is the render target.
+ context.uniform1i(this.depthAlphaUniforms.baseMap, 1);
context.enable(context.POLYGON_OFFSET_FILL);
context.polygonOffset(1, 1);
- for (const batch of this.batches) if (!batch.floor && batch.castShadow) this.drawBatch(batch);
+ for (const batch of this.batches) if (!batch.floor && batch.castShadow) this.drawAlphaBatch(batch, false);
context.disable(context.POLYGON_OFFSET_FILL);
+ context.enable(context.CULL_FACE);
context.bindFramebuffer(context.FRAMEBUFFER, null);
this.shadowsDirty = false;
}
@@ -906,6 +943,88 @@ export class Renderer67 {
}
}
+ /** Culling, cutout and opacity state for one batch, in the color pass (textured) or the shadow depth pass. */
+ applyAlphaState(batch, textured) {
+ const context = this.context;
+ if (batch.doubleSided) {
+ context.disable(context.CULL_FACE);
+ } else {
+ context.enable(context.CULL_FACE);
+ }
+ const masked = batch.alphaMode === 'mask';
+ if (!textured) {
+ const uniforms = this.depthAlphaUniforms;
+ context.uniform1f(uniforms.alphaMasked, masked ? 1 : 0);
+ context.uniform1f(uniforms.alphaCutoff, batch.alphaCutoff);
+ context.uniform1f(uniforms.materialOpacity, batch.opacity);
+ context.uniform1f(uniforms.hasBaseMap, batch.mapState[0] ? 1 : 0);
+ if (masked) {
+ context.activeTexture(context.TEXTURE0 + 1);
+ context.bindTexture(context.TEXTURE_2D, batch.textures[0]);
+ }
+ return;
+ }
+ const useCoverage = masked && this.samples > 1 && !this.benchmark;
+ if (useCoverage) {
+ context.enable(context.SAMPLE_ALPHA_TO_COVERAGE);
+ } else {
+ context.disable(context.SAMPLE_ALPHA_TO_COVERAGE);
+ }
+ const uniforms = this.uniforms;
+ context.uniform1f(uniforms.alphaMode, ALPHA_MODES[batch.alphaMode]);
+ context.uniform1f(uniforms.alphaCutoff, batch.alphaCutoff);
+ context.uniform1f(uniforms.materialOpacity, batch.opacity);
+ context.uniform1f(uniforms.alphaToCoverage, useCoverage ? 1 : 0);
+ context.uniform1f(uniforms.doubleSided, batch.doubleSided ? 1 : 0);
+ }
+
+ /** Reorders a blend batch's instances back to front for this eye; translation columns stand in for object centers. */
+ uploadSortedInstances(batch, eye) {
+ if (batch.instanceCount < 2) return;
+ const data = batch.instanceData;
+ const distances = Array.from({ length: batch.instanceCount }, (unused, index) => {
+ const offset = index * INSTANCE_STRIDE;
+ return { index, distance: Math.hypot(data[offset + 12] - eye[0], data[offset + 13] - eye[1], data[offset + 14] - eye[2]) };
+ });
+ distances.sort((first, second) => second.distance - first.distance);
+ batch.sortedData ??= new Float32Array(data.length);
+ distances.forEach(({ index }, rank) => {
+ batch.sortedData.set(data.subarray(index * INSTANCE_STRIDE, (index + 1) * INSTANCE_STRIDE), rank * INSTANCE_STRIDE);
+ });
+ this.context.bindBuffer(this.context.ARRAY_BUFFER, batch.instanceBuffer);
+ this.context.bufferSubData(this.context.ARRAY_BUFFER, 0, batch.sortedData);
+ }
+
+ /** Alpha-blended batches draw after opaque and masked geometry, farthest first, without writing depth. */
+ drawBlendBatches(eye) {
+ const context = this.context;
+ const blendBatches = this.batches.filter(batch => batch.alphaMode === 'blend');
+ if (blendBatches.length === 0) return;
+ const distance = (batch) => {
+ let total = 0;
+ for (let index = 0; index < batch.instanceCount; index++) {
+ const offset = index * INSTANCE_STRIDE;
+ total += Math.hypot(batch.instanceData[offset + 12] - eye[0], batch.instanceData[offset + 13] - eye[1], batch.instanceData[offset + 14] - eye[2]);
+ }
+ return total / batch.instanceCount;
+ };
+ const ordered = blendBatches.map(batch => ({ batch, distance: distance(batch) })).sort((first, second) => second.distance - first.distance);
+ context.enable(context.BLEND);
+ context.blendFuncSeparate(context.SRC_ALPHA, context.ONE_MINUS_SRC_ALPHA, context.ONE, context.ONE_MINUS_SRC_ALPHA);
+ context.depthMask(false);
+ for (const { batch } of ordered) {
+ this.uploadSortedInstances(batch, eye);
+ this.drawAlphaBatch(batch, true);
+ }
+ context.depthMask(true);
+ context.disable(context.BLEND);
+ }
+
+ drawAlphaBatch(batch, textured) {
+ this.applyAlphaState(batch, textured);
+ this.drawBatch(batch, textured);
+ }
+
drawBatch(batch, textured = false) {
if (this.hasMorphs) {
const uniforms = textured ? this.uniforms : this.depthMorphUniforms;
@@ -1010,7 +1129,10 @@ export class Renderer67 {
context.activeTexture(context.TEXTURE0);
context.bindTexture(context.TEXTURE_2D, this.shadowTexture);
context.uniform1i(this.uniforms.shadowMap, 0);
- for (const batch of this.batches) this.drawBatch(batch, true);
+ for (const batch of this.batches) if (batch.alphaMode !== 'blend') this.drawAlphaBatch(batch, true);
+ this.drawBlendBatches(eye);
+ context.disable(context.SAMPLE_ALPHA_TO_COVERAGE);
+ context.enable(context.CULL_FACE);
context.bindVertexArray(null);
if (!this.benchmark) this.resolveFrame(frame, effects, environment, volume);
this.cpuMilliseconds = performance.now() - start;
diff --git a/src/shaders.js b/src/shaders.js
index 55aa29cb..44b637a7 100644
--- a/src/shaders.js
+++ b/src/shaders.js
@@ -116,19 +116,34 @@ layout(location=0) in vec3 position;
layout(location=2) in mat4 instanceMatrix;
layout(location=11) in vec3 assemblyOffset;
layout(location=12) in vec3 assemblyDetailOffset;
+layout(location=13) in vec2 uv;
uniform mat4 lightProjection;
uniform float assemblyAmount;
+out vec2 textureUV;
${skinningShader}
${morphingShader}
void main() {
vec4 world = instanceMatrix * skinTransform() * vec4(morphedPosition(position), 1.0);
world.xyz += assemblyOffset * assemblyAmount + assemblyDetailOffset * smoothstep(0.3, 1.0, assemblyAmount);
+ textureUV = uv;
gl_Position = lightProjection * world;
}`;
+// Only masked batches sample the base map, so shadows follow the cutout.
export const depthFragmentShader = `#version 300 es
precision highp float;
-void main() {}
+in vec2 textureUV;
+uniform float alphaMasked;
+uniform float alphaCutoff;
+uniform float materialOpacity;
+uniform float hasBaseMap;
+uniform sampler2D baseMap;
+void main() {
+ if (alphaMasked < 0.5) return;
+ float alpha = materialOpacity;
+ if (hasBaseMap > 0.5) alpha *= texture(baseMap, textureUV).a;
+ if (alpha < alphaCutoff) discard;
+}
`;
export const benchmarkVertexShader = `#version 300 es
@@ -197,6 +212,11 @@ uniform float hasEmissiveMap;
uniform vec2 normalScale;
uniform float occlusionStrength;
uniform float hdrEnabled;
+uniform float alphaMode;
+uniform float alphaCutoff;
+uniform float materialOpacity;
+uniform float alphaToCoverage;
+uniform float doubleSided;
out vec4 outputColor;
const float PI = 3.14159265359;
@@ -313,18 +333,40 @@ vec3 mappedNormal(vec3 normal) {
return dot(mapped, mapped) > 1e-12 ? normalize(mapped) : normal;
}
+// Opaque draws 1, mask resolves to a cutout (smooth coverage with MSAA) and blend keeps the fraction.
+float surfaceAlpha(float textureAlpha) {
+ if (alphaMode < 0.5) return 1.0;
+ float alpha = materialOpacity * textureAlpha;
+ if (alphaMode > 1.5) return alpha;
+ if (alphaToCoverage > 0.5) {
+ float softness = max(fwidth(alpha), 0.0001);
+ alpha = clamp((alpha - alphaCutoff) / softness + 0.5, 0.0, 1.0);
+ if (alpha <= 0.0) discard;
+ return alpha;
+ }
+ if (alpha < alphaCutoff) discard;
+ return 1.0;
+}
+
void main() {
vec3 normal = normalize(worldNormal);
+ if (doubleSided > 0.5 && !gl_FrontFacing) normal = -normal;
if (hasNormalMap > 0.5) normal = mappedNormal(normal);
vec3 viewDirection = normalize(eye - worldPosition);
vec3 color = mix(baseColor, armorColor, step(0.5, surface.w) * (1.0 - step(1.5, surface.w)));
color *= vertexTint;
- if (hasBaseMap > 0.5) color *= texture(baseMap, textureUV).rgb;
+ float textureAlpha = 1.0;
+ if (hasBaseMap > 0.5) {
+ vec4 sampledBase = texture(baseMap, textureUV);
+ color *= sampledBase.rgb;
+ textureAlpha = sampledBase.a;
+ }
+ float alpha = surfaceAlpha(textureAlpha);
vec3 emission = emissionColor * surface.z;
if (hasEmissiveMap > 0.5) emission *= texture(emissiveMap, textureUV).rgb;
if (surface.w == 10.0) {
vec3 radiance = color * exposure + emission;
- outputColor = vec4(hdrEnabled > 0.5 ? radiance : pow(max(radiance, vec3(0)), vec3(1.0 / 2.2)), 1.0);
+ outputColor = vec4(hdrEnabled > 0.5 ? radiance : pow(max(radiance, vec3(0)), vec3(1.0 / 2.2)), alpha);
return;
}
float metallic = surface.x;
@@ -426,7 +468,7 @@ void main() {
float fog = 1.0 - exp(-length(worldPosition - eye) * fogDensity);
radiance = 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)), 1.0);
+ outputColor = vec4(hdrEnabled > 0.5 ? clamp(radiance * exposure, vec3(0), vec3(65504.0)) : pow(toneMap(radiance * exposure), vec3(1.0 / 2.2)), alpha);
if (surface.w == 2.0 && inspection < 0.5) {
float distanceFade = exp(-length(worldPosition.xz) * 0.08);
float contact = 1.0 - 0.1 * exp(-dot(worldPosition.xz, worldPosition.xz) * 1.4);
diff --git a/tests/export.test.js b/tests/export.test.js
index 2b14e8d2..a1812a81 100644
--- a/tests/export.test.js
+++ b/tests/export.test.js
@@ -21,6 +21,17 @@ test('exported GLB loads with an independent glTF loader and preserves every par
assert.ok(binary.byteLength < 1024 * 1024);
});
+test('GLB export writes alpha mode, cutoff, opacity and double-sided so the loader reads them back', async () => {
+ const part = createModel()[0];
+ const material = { ...part.material, alphaMode: 'mask', alphaCutoff: 0.3, opacity: 0.6, doubleSided: true };
+ const gltf = await new GLTFLoader().parseAsync(exportGlb([{ ...part, material }]), '');
+ let loaded;
+ gltf.scene.traverse((node) => { if (node.isMesh) loaded = node.material; });
+ assert.equal(loaded.alphaTest, 0.3);
+ assert.equal(loaded.side, 2);
+ assert.ok(Math.abs(loaded.opacity - 0.6) < 1e-6);
+});
+
test('GLB export refuses to silently discard any material texture channel', () => {
const part = createModel()[0];
for (const channel of ['map', 'normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap']) {
diff --git a/tests/gltf.test.js b/tests/gltf.test.js
index 98d40291..4a32b2e0 100644
--- a/tests/gltf.test.js
+++ b/tests/gltf.test.js
@@ -138,6 +138,30 @@ test('mirrored static transforms reverse triangle winding without altering world
asset.dispose();
});
+test('alpha mode, cutoff, base color alpha and double-sided map onto the material contract', async () => {
+ const blended = await parseGltf(triangleAsset(document => {
+ document.materials[0].alphaMode = 'BLEND';
+ document.materials[0].doubleSided = true;
+ document.materials[0].pbrMetallicRoughness.baseColorFactor = [1, 1, 1, 0.25];
+ }));
+ assert.equal(blended.parts[0].material.alphaMode, 'blend');
+ assert.equal(blended.parts[0].material.opacity, 0.25);
+ assert.equal(blended.parts[0].material.doubleSided, true);
+ blended.dispose();
+ const masked = await parseGltf(triangleAsset(document => {
+ document.materials[0].alphaMode = 'MASK';
+ document.materials[0].alphaCutoff = 0.3;
+ }));
+ assert.equal(masked.parts[0].material.alphaMode, 'mask');
+ assert.equal(masked.parts[0].material.alphaCutoff, 0.3);
+ assert.equal(masked.parts[0].material.doubleSided, false);
+ masked.dispose();
+ const plain = await parseGltf(triangleAsset());
+ assert.equal(plain.parts[0].material.alphaMode, 'opaque');
+ assert.equal(plain.parts[0].material.opacity, 1);
+ plain.dispose();
+});
+
test('unsupported features fail explicitly before loading resources', async () => {
const cases = [
[document => { document.nodes[1].skin = 0; }, /skin index/],
@@ -148,8 +172,9 @@ test('unsupported features fail explicitly before loading resources', async () =
}, /Unsupported morph/],
[document => { document.meshes[0].primitives[0].attributes.COLOR_0 = 1; }, /COLOR_0/],
[document => { document.meshes[0].primitives[0].mode = 1; }, /TRIANGLES/],
- [document => { document.materials[0].alphaMode = 'BLEND'; }, /alpha mode/],
- [document => { document.materials[0].doubleSided = true; }, /Double-sided/],
+ [document => { document.materials[0].alphaMode = 'DITHER'; }, /alpha mode/],
+ [document => { document.materials[0].alphaCutoff = 2; }, /alphaCutoff/],
+ [document => { document.materials[0].doubleSided = 'yes'; }, /doubleSided/],
[document => { document.materials[0].normalTexture = { index: 0 }; }, /normalTexture texture index/],
[document => { document.extensionsRequired = ['KHR_draco_mesh_compression']; }, /KHR_draco/],
[document => { document.materials[0].extensions = { KHR_materials_clearcoat: {} }; }, /KHR_materials_clearcoat/],
diff --git a/tests/morph-renderer.test.js b/tests/morph-renderer.test.js
index 909d52e2..e1727016 100644
--- a/tests/morph-renderer.test.js
+++ b/tests/morph-renderer.test.js
@@ -32,6 +32,10 @@ function retainedRenderer(parts) {
instanceBuffer: {},
instanceData: new Float32Array(group.length * 41),
castShadow: true,
+ alphaMode: 'opaque',
+ alphaCutoff: 0,
+ opacity: 1,
+ doubleSided: false,
};
group.forEach((part, index) => renderer.partLocations.set(part, {
batch, index, geometry: part.geometry, morph: part.morph,
diff --git a/tests/renderer.test.js b/tests/renderer.test.js
index 63107aa0..9f7411a9 100644
--- a/tests/renderer.test.js
+++ b/tests/renderer.test.js
@@ -11,7 +11,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 };
+ const batch = { instanceBuffer: {}, instanceData: new Float32Array(parts.length * 41).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(), skin: item.skin ?? null,
@@ -59,6 +59,71 @@ test('shadowless parts form separate render batches and cannot change casting af
assert.throws(() => groupParts([{ ...window, castShadow: 0 }]), /boolean/);
});
+function alphaPart(name, geometry, materialFields) {
+ const base = part(name, geometry);
+ return { ...base, material: { ...base.material, ...materialFields } };
+}
+
+test('alpha mode, cutoff, opacity and double-sided state partition batches', () => {
+ const geometry = {};
+ const parts = [
+ alphaPart('opaque', geometry, {}),
+ alphaPart('leaf', geometry, { alphaMode: 'mask', doubleSided: true }),
+ alphaPart('second leaf', geometry, { alphaMode: 'mask', doubleSided: true }),
+ alphaPart('sharper leaf', geometry, { alphaMode: 'mask', alphaCutoff: 0.8, doubleSided: true }),
+ alphaPart('one sided leaf', geometry, { alphaMode: 'mask' }),
+ 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 }),
+ ];
+ const groups = groupParts(parts);
+ assert.equal(groups.length, 6);
+ assert.deepEqual(groups[0].map(item => item.name), ['opaque', 'opaque with ignored opacity']);
+ assert.deepEqual(groups[1].map(item => item.name), ['leaf', 'second leaf']);
+});
+
+test('alpha material fields are validated with clear errors', () => {
+ const geometry = {};
+ const invalid = [
+ [{ alphaMode: 'cutout' }, /alphaMode/],
+ [{ alphaMode: 'mask', alphaCutoff: 1.5 }, /alphaCutoff/],
+ [{ alphaMode: 'blend', opacity: -0.1 }, /opacity/],
+ [{ opacity: NaN }, /opacity/],
+ [{ doubleSided: 1 }, /doubleSided/],
+ ];
+ for (const [fields, expected] of invalid) assert.throws(() => groupParts([alphaPart('bad', geometry, fields)]), expected);
+});
+
+test('blend batches skip shadows by default and alpha state cannot change after upload', () => {
+ const geometry = {};
+ const glass = alphaPart('glass', geometry, { alphaMode: 'blend', opacity: 0.5 });
+ 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 }]) {
+ 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;
+ }
+ assert.equal(writes.length, 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 batch = { instanceBuffer: {}, instanceData, instanceCount: 3 };
+ renderer.uploadSortedInstances(batch, [0, 0, 0]);
+ const order = [0, 1, 2].map(rank => uploads[0][rank * 41]);
+ assert.deepEqual(order, [1, 2, 0]);
+});
+
test('instance animation reuses retained buffers, updates inverse-transpose normals and RGB emission', () => {
const parts = [part('moving'), part('static')];
const { renderer, batch, writes } = retainedRenderer(parts);