Repository navigation
Description
Summary
A Mesh samples its texture with exactly the UVs its geometry carries. There is no way to scale, offset or rotate them at draw time, and no way to map a texture by world position. Every case that needs one bakes it into the vertex data by hand:
- tiling a texture across a long plank or a big floor;
- scrolling water, lava or a conveyor belt;
- the same model with its texture at different scales;
- a texture continuing seamlessly across boxes of different sizes.
Proposal: a UV transform as a material setting on every Mesh (and InstancedMesh, GLTFModel, GLTFScene), applied in the shader, plus an optional world-space mapping mode.
The same transform is what quantized glTF needs. KHR_mesh_quantization stores positions, normals and texture coordinates as 8- or 16-bit integers, which makes a model's download much smaller. The usual tool for it, gltfpack, quantizes texture coordinates by default and maps them back with KHR_texture_transform. So reading quantized models correctly is part of this ticket too.
What it makes possible
With the settings proposed below (names to be settled in review):
Tiling a texture to an object's size. A 2048 × 2048 floor with a 64 px stone texture, without building a subdivided plane:
const floor = new Mesh(0, 0, { model: "plane", texture: "stone", width: 2048, height: 2048 });
floor.uvScale.set(32, 32); // 2048 / 64: one stone tile every 64 unitsScrolling textures: water, lava, a conveyor belt, clouds on a sky dome, a waterfall. Free per frame, since only a uniform changes:
update(dt) {
this.belt.uvOffset.x = (this.belt.uvOffset.x + dt * 0.0005) % 1; // the belt runs
this.river.uvOffset.y -= dt * 0.0002; // the river flows
}A flipbook on a mesh: an animated screen, a fire in a fireplace, a flag, frames of a sprite sheet played on one quad:
// a 4 × 4 sheet of 16 frames
screen.uvScale.set(1 / 4, 1 / 4);
const frame = Math.floor(time / 80) % 16;
screen.uvOffset.set((frame % 4) / 4, Math.floor(frame / 4) / 4);One atlas, many looks: crates, signs or posters that each show a different region of a single texture, so they share one material, and with automatic instancing (#1890), one draw.
Rotating textures: a radar sweep, a clock dial, a spinning vortex or portal, a rotating saw blade, all without rotating the mesh itself:
dial.uvPivot.set(0.5, 0.5);
dial.uvRotation += dt * 0.001;Same model, different scale of detail: one rock or wall model used small and large, its texture tiled more on the large one so it doesn't look blown up.
World-space mapping (uvMapping: "world"): no UVs needed at all.
- Prototype or blockout levels built from scaled boxes, where every surface shows the same texel density, as with the Slingshot's planks and blocks.
- Terrain and cliffs, where vertex UVs stretch on steep slopes.
- Procedural geometry (
TriangleMesh3d, generated meshes) that has no UVs. - Moving platforms whose texture should stay put in the world (
"world") or move with them ("triplanar", local space).
glTF assets that tile or offset their textures through KHR_texture_transform (common in exports from Blender and other tools) draw as authored instead of untiled.
Smaller models. A model run through gltfpack (quantized vertex data, about half the size of 32-bit floats or less) loads and draws as the original does. Today it loads with no error and draws wrong.
What happens today
- The mesh shaders take the vertex UVs (
aRegion) straight to the varying (vRegion = aRegioninvideo/webgl/shaders/mesh.vert, and the same invideo/webgpu/shaders/mesh.wgsl). The fragment shaders sample the base texture, thealphaMapand thenormalMapwith them untouched (mesh.frag,mesh-lit.frag,mesh-lit.wgsl). textureRepeatsets the wrap mode per mesh, so UVs outside[0, 1]already tile. But nothing produces such UVs except the geometry itself.- The glTF loader does not read
KHR_texture_transform, so an asset that offsets or tiles its textures through that extension draws untiled. - The glTF loader reads 8- and 16-bit vertex data, but ignores the accessor's
normalizedflag forPOSITION,NORMALandTEXCOORD_0(readAccessorinloader/parsers/gltf.js). It only scales normalized values for colours, instance rotations and skin weights. So a quantized model loads with no error and looks wrong:- normalized texture coordinates arrive as raw integers (0 to 65535 instead of 0 to 1);
- normalized normals arrive unscaled, which breaks the lighting;
- and the texture transform gltfpack adds to undo the UV quantization is ignored (above).
KHR_mesh_quantizationis listed in the file'sextensionsRequired, but the loader never reads that list.
Examples that work around it today:
- Slingshot,
meshes/box.ts: computes each face's UVs from the box's size (size / 64), so the wood grain keeps its scale on boxes of every size. It's 118 lines that build a box by hand largely for this. - Slingshot,
meshes/backdrop.ts: sets the backdrop's UVs so its texture repeats across a wall of any width.
Proposal
1. A UV transform, per mesh
New Mesh settings and properties, read every frame like tint:
| setting | default | meaning |
|---|---|---|
uvScale |
[1, 1] |
how many times the texture repeats across the UVs; [4, 1] tiles it four times along U |
uvOffset |
[0, 0] |
shifts the texture, in UV units: animating it scrolls the texture |
uvRotation |
0 |
turns the texture, in radians, about uvPivot |
uvPivot |
[0, 0] |
the point it turns about |
- The vertex shader applies
uv' = R·(uv·scale − pivot) + pivot + offset(in the orderKHR_texture_transformdefines). It's one small matrix, amat3packed into the existing per-draw uniforms (WebGLuTintblock, WebGPUuMesh), so it costs nothing when left at identity. - The base texture,
alphaMapandnormalMapall read the transformed UVs. - Normal maps need no tangent change:
mesh-lit.fragrebuilds the tangent frame from screen-space derivatives of the UV (dFdx/dFdy), so a rotated or scaled UV gives the right frame automatically. - Tiling needs a repeat wrap. A
uvScaleabove 1 withtextureRepeat: "no-repeat"would stretch the edge texels. When a UV transform is set andtextureRepeatisn't, it should default to"repeat", and the skill should say so. InstancedMesh: the transform belongs to the set. A per-instance offset (an atlas frame per instance, or a scroll phase) can come frominstanceDatain a custom shader.
2. glTF KHR_texture_transform
Read the extension on baseColorTexture (and normalTexture / emissiveTexture where melonJS uses them) into the settings above, in loader/parsers/gltf.js, alongside KHR_materials_unlit and KHR_materials_emissive_strength. texCoord overrides that select a second UV set can stay unsupported, with a console note.
3. Quantized glTF (KHR_mesh_quantization)
Read quantized vertex data correctly, in loader/parsers/gltf.js:
normalizedaccessors: scale them as the glTF spec defines, forPOSITION,NORMALandTEXCOORD_0(and the other attributes the loader reads):c / 127orc / 32767(clamped at −1) for signed bytes and shorts,c / 255orc / 65535for unsigned. The colour, rotation and weight paths already do this; one shared helper should serve them all.- Integer, not normalized: positions stored as plain integers are correct as they are, because the node's transform scales them back. They just need converting to floats.
- The UV transform: gltfpack's quantized texture coordinates rely on
KHR_texture_transform(section 2) to map back onto the texture. - Decode on load first. The first version converts quantized data to 32-bit floats as it loads. That keeps the download saving, and every existing path works unchanged: picking (
Mesh#intersectRay), bounds, skinning,TriangleMesh3d.fromMesh()and physics. Keeping the integers on the GPU (to save GPU memory too) can come later, since it needs vertex layouts with integer attributes. extensionsRequired: read it.KHR_mesh_quantizationandKHR_texture_transformare then supported. An extension that is required but not supported (Draco, meshopt, Basis textures) fails with a clear error that names it and suggests re-exporting, instead of a generic accessor or image error.
4. World-space mapping (triplanar)
A mode where the texture is projected along the three axes and blended by the surface normal, instead of read from the vertex UVs:
| setting | default | meaning |
|---|---|---|
uvMapping |
"uv" |
"uv" (the vertex UVs), "triplanar" (projected in the mesh's own space, so the texture moves and turns with it), or "world" (projected in world space, so the texture stays put as the mesh moves) |
uvScale |
reused: world units per repeat, e.g. [1/64, 1/64] for one repeat every 64 units |
|
triplanarSharpness |
1 |
how sharply the three projections blend at the edges |
"world"covers the Slingshot's case: every plank, box and floor tiles at the same scale, whatever its size, with no UVs at all. It also suits prototype levels made of scaled boxes, and terrain.- It needs the world-space position and normal in the fragment shader, which the lit path already has (
mesh-lit.vertpasses both for lighting). The unlit path would need them added. - A normal map under triplanar mapping needs the projected tangent frame per axis; the first version can apply triplanar mapping to the base texture only, and document it.
Not in scope
- A second UV set (
TEXCOORD_1), and lightmaps. - Per-texture transforms beyond what
KHR_texture_transformgives the base, normal and emissive textures. - Decoding meshopt or Draco compression, and Basis (KTX2) textures in glTF: they get the clear error from section 3.
- Keeping quantized vertex data as integers on the GPU.
Done when
uvScale,uvOffset,uvRotationanduvPivotwork onMesh,InstancedMesh,GLTFModelandGLTFScene, on WebGL 2 and on WebGPU, for the base texture,alphaMapandnormalMap. Tests compare rendered pixels against UVs transformed by hand.- Changing them at run time takes effect on the next frame with no geometry re-upload, so scrolling a texture costs nothing.
KHR_texture_transformis read from glTF materials, with a test asset that offsets and scales its texture.- A model quantized with
gltfpack(its default settings) loads and renders like the original. Tests read a quantized and an unquantized copy of the same model and compare their positions, normals and texture coordinates, and their rendered pixels. - A glTF file that requires an unsupported extension fails with an error naming it.
uvMapping: "world"and"triplanar"tile the base texture by position. A test checks two boxes of different sizes show the same texel density.- The Slingshot's boxes use
uvMapping: "world"instead of computing their UVs. - An example shows the transform at work: a scrolling river or conveyor belt, a flipbook screen and a world-mapped blockout.
- The
melonjs-3d-assetsskill says quantized files are supported (with the gltfpack command to make them) and which compression extensions are not, and themelonjs-3dskill documents the settings, with a scrolling-texture sample, the need fortextureRepeat: "repeat", and symptom rows (a tiled texture stretched at its edges; a scrolling texture that jumps). - A line under Added in the changelog.
Activity
[-]UV transform on meshes: uvScale / uvOffset / uvRotation, and world-space (triplanar) texture mapping[/-][+]UV transform on meshes: uvScale / uvOffset / uvRotation, world-space (triplanar) mapping, and quantized glTF[/+]