File size: 18,904 Bytes
d72771b
95a7e69
 
 
d72771b
 
95a7e69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d72771b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95a7e69
 
 
 
 
 
d72771b
95a7e69
 
 
d72771b
 
95a7e69
 
 
d72771b
 
95a7e69
 
 
 
d72771b
 
 
 
 
 
 
 
 
 
85e0fe1
95a7e69
 
85e0fe1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d72771b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95a7e69
 
ef0afec
 
95a7e69
 
 
ef0afec
 
95a7e69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d72771b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95a7e69
 
d72771b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
// Materials for the Toon and Lit renderers (Lit's are also the robot's in 3DGS). Textures are drawn on
// canvases at load, but for a few photographs that Lit shows instead (assets/textures/, CC0 from Poly
// Haven, tools/make_textures.py). Environment geoms are matched by their MJCF material name
// (tools/make_kitchen.py, tools/make_decor.py); other geoms show their MuJoCo colour.
import * as THREE from "three";

const BASE = import.meta.env?.BASE_URL ?? "./";

// The photographs' mean colours (linear RGB), for the light baker: tools/make_textures.py prints them.
const PHOTO_MEANS = {
  wood_floor: [0.218, 0.117, 0.055],
  oak_veneer: [0.36, 0.211, 0.098],
  wool: [0.193, 0.18, 0.166],
};

const photos = {}; // name -> { image, textures }; textures by name, tile and unit
/** A photo texture for a look, its tiles `size` metres where the geometry's texture coordinates count `unit` metres. */
function photoTexture(name, size, unit) {
  const key = `${name}@${size}/${unit}`;
  if (!photos[key]) {
    const photo = (photos[name] ??= { image: null, textures: [] });
    if (!photo.loading) {
      photo.loading = new THREE.ImageLoader().load(`${BASE}textures/${name}.jpg`, (image) => {
        photo.image = image;
        for (const t of photo.textures) {
          t.image = image;
          t.needsUpdate = true;
        }
      });
    }
    const t = new THREE.Texture(); // drawn once its image is in
    t.wrapS = t.wrapT = THREE.RepeatWrapping;
    t.colorSpace = THREE.SRGBColorSpace;
    t.anisotropy = 8;
    t.repeat.set(unit / size, unit / size);
    if (photo.image) {
      t.image = photo.image;
      t.needsUpdate = true;
    }
    photo.textures.push(t);
    photos[key] = t;
  }
  return photos[key];
}

function canvasTexture(size, draw, { srgb = true } = {}) {
  const canvas = document.createElement("canvas");
  canvas.width = canvas.height = size;
  draw(canvas.getContext("2d"), size);
  const texture = new THREE.CanvasTexture(canvas);
  texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
  texture.anisotropy = 4;
  if (srgb) texture.colorSpace = THREE.SRGBColorSpace;
  return texture;
}

/** A small seeded random for repeatable textures. */
function rand(seed) {
  let s = seed;
  return () => ((s = (s * 16807) % 2147483647) - 1) / 2147483646;
}

function shade(hex, f) {
  const c = new THREE.Color(hex);
  return `#${c.multiplyScalar(f).getHexString()}`;
}

// Floor tile colours of MuJoCo-GS-Web's tabletop kitchen, sampled from its splat (tools/make_decor.py
// prints them): light and dark teal, cream and terracotta.
const KITCHEN_TILES = { teal: "#7aa8a8", darkTeal: "#4f6961", cream: "#d1c2ad", terracotta: "#b38c70" };

const TEXTURES = {
  planks: () =>
    canvasTexture(512, (g, n) => {
      const r = rand(7);
      const rows = 8;
      for (let i = 0; i < rows; i++) {
        let x = -r() * n;
        while (x < n) {
          const w = n * (0.45 + r() * 0.5);
          g.fillStyle = shade("#9c7350", 0.82 + r() * 0.3);
          g.fillRect(x, (i * n) / rows, w, n / rows);
          g.strokeStyle = "rgba(40,25,15,0.25)";
          for (let k = 0; k < 6; k++) {
            g.beginPath();
            const y = ((i + 0.1 + r() * 0.8) * n) / rows;
            g.moveTo(x, y);
            g.bezierCurveTo(x + w * 0.3, y + r() * 4 - 2, x + w * 0.6, y + r() * 4 - 2, x + w, y + r() * 2 - 1);
            g.lineWidth = 0.6;
            g.stroke();
          }
          g.fillStyle = "rgba(30,18,10,0.55)";
          g.fillRect(x, (i * n) / rows, 2, n / rows);
          x += w;
        }
        g.fillStyle = "rgba(30,18,10,0.6)";
        g.fillRect(0, (i * n) / rows, n, 2);
      }
    }),
  grain: () =>
    canvasTexture(256, (g, n) => {
      const r = rand(3);
      g.fillStyle = "#8a5f3e";
      g.fillRect(0, 0, n, n);
      for (let k = 0; k < 90; k++) {
        g.strokeStyle = `rgba(${r() < 0.5 ? "60,35,20" : "170,120,80"},${0.12 + r() * 0.15})`;
        g.lineWidth = 0.5 + r() * 1.5;
        g.beginPath();
        const y = r() * n;
        g.moveTo(0, y);
        g.bezierCurveTo(n * 0.3, y + r() * 8 - 4, n * 0.7, y + r() * 8 - 4, n, y + r() * 4 - 2);
        g.stroke();
      }
    }),
  // Wood grain on white, to tint with the geom's colour.
  grainTint: () =>
    canvasTexture(256, (g, n) => {
      const r = rand(31);
      g.fillStyle = "#ffffff";
      g.fillRect(0, 0, n, n);
      for (let k = 0; k < 70; k++) {
        g.strokeStyle = `rgba(90,60,40,${0.05 + r() * 0.12})`;
        g.lineWidth = 0.5 + r() * 1.5;
        g.beginPath();
        const y = r() * n;
        g.moveTo(0, y);
        g.bezierCurveTo(n * 0.3, y + r() * 8 - 4, n * 0.7, y + r() * 8 - 4, n, y + r() * 4 - 2);
        g.stroke();
      }
    }),
  marble: () =>
    canvasTexture(512, (g, n) => {
      const r = rand(11);
      g.fillStyle = "#ecebe7";
      g.fillRect(0, 0, n, n);
      for (let k = 0; k < 26; k++) {
        g.strokeStyle = `rgba(120,120,125,${0.06 + r() * 0.18})`;
        g.lineWidth = 0.4 + r() * 2.2;
        g.beginPath();
        let x = r() * n;
        let y = r() * n;
        g.moveTo(x, y);
        for (let s = 0; s < 8; s++) {
          x += (r() - 0.3) * 90;
          y += (r() - 0.5) * 90;
          g.lineTo(x, y);
        }
        g.stroke();
      }
    }),
  tile: () =>
    canvasTexture(256, (g, n) => {
      const r = rand(5);
      g.fillStyle = "#c9cdd0";
      g.fillRect(0, 0, n, n);
      const k = 4;
      for (let i = 0; i < k; i++)
        for (let j = 0; j < k; j++) {
          g.fillStyle = shade("#eef1f2", 0.94 + r() * 0.06);
          g.fillRect((i * n) / k + 2, (j * n) / k + 2, n / k - 4, n / k - 4);
        }
    }),
  // White square tiles with grey grout, to tint with the geom's colour.
  wallTiles: () =>
    canvasTexture(256, (g, n) => {
      const r = rand(19);
      g.fillStyle = "#c2c4c0";
      g.fillRect(0, 0, n, n);
      const k = 4;
      for (let i = 0; i < k; i++)
        for (let j = 0; j < k; j++) {
          g.fillStyle = shade("#ffffff", 0.95 + r() * 0.05);
          g.fillRect((i * n) / k + 2, (j * n) / k + 2, n / k - 4, n / k - 4);
        }
    }),
  // The tabletop kitchen's floor: teal tiles alternating with cream and terracotta ones, 4 x 4 per texture.
  kitchenTiles: () =>
    canvasTexture(512, (g, n) => {
      const r = rand(23);
      g.fillStyle = "#b9b1a5";
      g.fillRect(0, 0, n, n);
      const k = 4;
      const s = n / k;
      for (let i = 0; i < k; i++)
        for (let j = 0; j < k; j++) {
          const base = (i + j) % 2 ? (r() < 0.55 ? KITCHEN_TILES.cream : KITCHEN_TILES.terracotta) : r() < 0.8 ? KITCHEN_TILES.teal : KITCHEN_TILES.darkTeal;
          g.fillStyle = shade(base, 0.96 + r() * 0.06);
          g.fillRect(i * s + 2, j * s + 2, s - 4, s - 4);
        }
    }),
  // Speckled concrete on white, to tint.
  concrete: () =>
    canvasTexture(256, (g, n) => {
      const r = rand(29);
      g.fillStyle = "#ffffff";
      g.fillRect(0, 0, n, n);
      for (let k = 0; k < 2600; k++) {
        g.fillStyle = `rgba(${r() < 0.5 ? "0,0,0" : "255,255,255"},${r() * 0.08})`;
        const w = 1 + r() * 2.5;
        g.fillRect(r() * n, r() * n, w, w);
      }
    }),
  fabric: () =>
    canvasTexture(256, (g, n) => {
      const r = rand(13);
      g.fillStyle = "#6b7590";
      g.fillRect(0, 0, n, n);
      for (let y = 0; y < n; y += 2)
        for (let x = 0; x < n; x += 2) {
          g.fillStyle = `rgba(${r() < 0.5 ? "255,255,255" : "0,0,0"},${r() * 0.07})`;
          g.fillRect(x, y, 2, 2);
        }
    }),
  paint: () =>
    canvasTexture(128, (g, n) => {
      const r = rand(17);
      g.fillStyle = "#ffffff";
      g.fillRect(0, 0, n, n);
      for (let k = 0; k < 1400; k++) {
        g.fillStyle = `rgba(0,0,0,${r() * 0.025})`;
        g.fillRect(r() * n, r() * n, 2, 2);
      }
    }),
};

// Textures drawn on white: the geom's colour tints them. The others carry their own colours.
const TINTED = new Set(["paint", "grainTint", "wallTiles", "concrete"]);

const cache = {};
const texture = (name) => (cache[name] ??= TEXTURES[name]());

// MJCF material name -> look. `size` is the texture's tile in metres; `photo` (with its tile, `photoSize`)
// is the photograph Lit shows instead; `shell` marks walls and floors, which do not cast shadows (a key
// light outside a room would otherwise darken all of it); `small` marks small things, which neither cast
// shadows nor catch them in 3DGS (src/render/view.js). `bevel` (metres) rounds a box's edges less than the
// default (statics.js): 0 where several boxes make one surface, as a worktop round a sink, and the seams
// would show.
const LOOKS = {
  floor: { map: "planks", size: 1.6, roughness: 0.62, photo: "wood_floor", photoSize: 1.5 },
  wall: { map: "paint", size: 1.0, color: 0xece8e1, roughness: 0.92, bevel: 0 },
  tile: { map: "tile", size: 0.4, roughness: 0.35, bevel: 0 },
  cabinet: { map: "paint", size: 0.6, color: 0x8ea596, roughness: 0.55 },
  cabinet_door: { map: "paint", size: 0.6, color: 0x93ab9b, roughness: 0.5 },
  countertop: { map: "marble", size: 1.2, roughness: 0.25, bevel: 0 },
  plinth: { color: 0x3a3a3a, roughness: 0.8, bevel: 0 },
  steel: { color: 0xc8cacd, roughness: 0.28, metalness: 0.9, bevel: 0.002 },
  glass: { color: 0x15161a, roughness: 0.08, metalness: 0.1 },
  fridge: { color: 0xeeeeef, roughness: 0.3, metalness: 0.15 },
  fridge_inside: { color: 0xf4f7fb, roughness: 0.6, bevel: 0 },
  wood: { map: "grain", size: 0.5, roughness: 0.5, photo: "oak_veneer", photoSize: 0.9 },
  fabric: { map: "fabric", size: 0.3, roughness: 0.95, photo: "wool", photoSize: 0.5 },
  rug: { map: "fabric", size: 0.25, color: 0xd9cbb8, roughness: 1, photo: "wool", photoSize: 0.35 },
  apple: { roughness: 0.35 },
  orange: { roughness: 0.6 },
  banana: { roughness: 0.55 },
  can: { roughness: 0.25, metalness: 0.6 },
  mug: { roughness: 0.2 },
  bowl: { roughness: 0.2 },
  plate: { roughness: 0.2 },
  cup: { roughness: 0.3 },
  bottle: { roughness: 0.1 },
  // tools/make_decor.py: the tabletop kitchen
  // the kitchen's fixtures and details (tools/make_kitchen.py)
  floor_tile: { map: "kitchenTiles", size: 0.88, roughness: 0.5, shell: true, bevel: 0 },
  skirting: { roughness: 0.6, shell: true, bevel: 0.002 },
  microwave: { roughness: 0.35, metalness: 0.5 },
  microwave_window: { roughness: 0.05 },
  microwave_display: { emissive: 1, small: true },
  pan: { roughness: 0.3, metalness: 0.4, small: true },
  appliance_dark: { roughness: 0.3, metalness: 0.3, small: true },
  ceramic: { roughness: 0.25, small: true },
  towel: { roughness: 0.95, small: true },
  led: { emissive: 1, small: true },
  bulb: { emissive: 1.2, small: true },
  lamp_shade: { roughness: 0.4, metalness: 0.5, small: true },
  lamp_shade_light: { emissive: 0.5, roughness: 0.9 },
  window_glass: { roughness: 0.05, emissive: 0.55, shell: true },
  window_frame: { roughness: 0.5, shell: true },
  curtain: { map: "fabric", size: 0.3, roughness: 0.95 },
  picture_frame: { map: "grain", size: 0.3, roughness: 0.5, small: true },
  canvas_0: { map: "paint", size: 0.4, roughness: 0.9, small: true },
  canvas_1: { map: "paint", size: 0.4, roughness: 0.9, small: true },
  canvas_2: { map: "paint", size: 0.4, roughness: 0.9, small: true },
  cushion: { roughness: 0.95 },
  cushion_2: { roughness: 0.95 },
  throw: { roughness: 0.95 },
  placemat: { roughness: 0.95, small: true },
  vase: { roughness: 0.05, small: true },
  decor_base: { roughness: 0.9, shell: true },
  decor_floor: { map: "kitchenTiles", size: 0.88, roughness: 0.5, shell: true },
  decor_plaster: { map: "paint", size: 1.0, roughness: 0.95, shell: true },
  decor_tiles: { map: "wallTiles", size: 0.4, roughness: 0.25, shell: true },
  decor_frame: { roughness: 0.5 },
  decor_glass: { roughness: 0.05, emissive: 0.45, shell: true },
  decor_carcass: { roughness: 0.7 },
  decor_worktop: { map: "concrete", size: 0.8, roughness: 0.65 },
  decor_plinth: { roughness: 0.8 },
  decor_cabinet: { map: "paint", size: 0.6, roughness: 0.5 },
  decor_brass: { roughness: 0.35, metalness: 0.8, small: true },
  decor_wood: { map: "grainTint", size: 0.5, roughness: 0.55 },
  decor_bracket: { roughness: 0.5, metalness: 0.6, small: true },
  decor_ceramic: { roughness: 0.25, small: true },
  decor_steel: { roughness: 0.3, metalness: 0.85, small: true },
  decor_appliance: { roughness: 0.35, metalness: 0.6 },
  decor_dark: { roughness: 0.15, metalness: 0.2 },
  decor_panel: { roughness: 0.4 },
  decor_leaf: { roughness: 0.7, small: true },
  decor_glass_bottle: { roughness: 0.1, small: true },
  // the boxing ring
  decor_arena_floor: { roughness: 0.9, shell: true },
  decor_skirt: { roughness: 0.9, shell: true },
  decor_apron: { roughness: 0.8 },
  decor_mat: { map: "paint", size: 1.5, roughness: 0.85, shell: true },
  decor_steps: { roughness: 0.8 },
  decor_post: { roughness: 0.35, metalness: 0.7 },
  decor_pad: { roughness: 0.6 },
  decor_rope: { roughness: 0.5 },
  decor_tie: { roughness: 0.6, small: true },
};

/** The look for an MJCF material name, or null. */
export const lookFor = (name) => LOOKS[name] ?? null;

// The XLeRobot's finish in Lit, by its MJCF material (assets/robots/xlerobot/xlerobot.xml, whose colours
// Toon keeps): the IKEA RÅSKOG cart is powder-coated steel, matte; the arms, the head and the camera
// housings are printed charcoal plastic, matte, the servos moulded plastic a shade darker and a little
// less matte; the casters metal.
const ROBOT_LOOKS = {
  blue: { color: 0x5b7cae, roughness: 0.5, metalness: 0.55 },
  grey: { color: 0x9b9ea4, roughness: 0.38, metalness: 0.85 },
  motor: { color: 0x232427, roughness: 0.65, metalness: 0 },
  white: { color: 0x2c2d30, roughness: 0.78, metalness: 0 },
};

/** The robot's Lit finish for an MJCF material name, or null. */
export const robotLookFor = (name) => ROBOT_LOOKS[name] ?? null;

// Each texture's mean colour (linear RGB), for the light baker (tools/bake_light.mjs), which has no canvas
// to draw them with. Measured from the textures above, which are seeded: they come out the same each time.
const TEXTURE_MEANS = {
  planks: [0.309, 0.159, 0.074],
  grain: [0.249, 0.112, 0.047],
  grainTint: [0.953, 0.945, 0.939],
  marble: [0.834, 0.826, 0.794],
  tile: [0.797, 0.821, 0.83],
  wallTiles: [0.921, 0.922, 0.919],
  kitchenTiles: [0.369, 0.38, 0.321],
  concrete: [0.99, 0.99, 0.99],
  fabric: [0.149, 0.179, 0.277],
  paint: [0.99, 0.99, 0.99],
};

/** A surface's mean reflectance in Lit (linear RGB): its colour (linear) times its texture's mean. */
export function albedoOf(look, colour) {
  const m = (look?.photo && PHOTO_MEANS[look.photo]) || (look?.map && TEXTURE_MEANS[look.map]) || [1, 1, 1];
  return [colour.r * m[0], colour.g * m[1], colour.b * m[2]];
}

/** The colour a geom shows (linear): the look's own; white under a texture with its own colours; else `rgba` (sRGB). */
export function surfaceColour(look, rgba) {
  if (look?.color !== undefined) return new THREE.Color(look.color);
  if (look?.map && !TINTED.has(look.map)) return new THREE.Color(0xffffff);
  return new THREE.Color().setRGB(rgba[0], rgba[1], rgba[2], THREE.SRGBColorSpace);
}

let ramp = null;
/**
 * Toon shading: two tones with a soft terminator, looked up by half-Lambert (0 facing away, 0.5 grazing,
 * 1 facing the light). The shadow tone keeps some key light, so shading stays soft, as in cel animation.
 */
function toonRamp() {
  if (ramp) return ramp;
  const n = 64;
  const data = new Uint8Array(n * 4);
  for (let i = 0; i < n; i++) {
    const t = i / (n - 1);
    const s = Math.min(1, Math.max(0, (t - 0.47) / 0.14));
    const v = 0.5 + 0.5 * s * s * (3 - 2 * s);
    data.set([v * 255, v * 255, v * 255, 255], i * 4);
  }
  ramp = new THREE.DataTexture(data, n, 1, THREE.RGBAFormat);
  ramp.minFilter = ramp.magFilter = THREE.LinearFilter;
  ramp.generateMipmaps = false;
  ramp.needsUpdate = true;
  return ramp;
}

/**
 * A material in `style` ("toon" or "lit") for a geom with `look` (or null), coloured `color` (linear) or
 * by vertex colours. `role` sets defaults: the robot is a little glossy and metallic.
 */
export function makeMaterial(style, look, { color = new THREE.Color(0xffffff), vertexColors = false, opacity = 1, role = "env" } = {}) {
  const transparent = opacity < 1;
  // the geometry's texture coordinates count look.size metres (worldUVs)
  const map = style === "lit" && look?.photo ? photoTexture(look.photo, look.photoSize, look.size) : look?.map ? texture(look.map) : null;
  const common = { color, map, vertexColors, transparent, opacity, depthWrite: !transparent || opacity > 0.5 };
  if (style === "toon") {
    const m = new THREE.MeshToonMaterial({ ...common, gradientMap: toonRamp() });
    if (look?.emissive) {
      m.emissive = new THREE.Color(0xffffff);
      m.emissiveIntensity = look.emissive;
    }
    return m;
  }
  const robot = role === "robot";
  const m = new THREE.MeshStandardMaterial({
    ...common,
    roughness: look?.roughness ?? (robot ? 0.42 : 0.45),
    metalness: look?.metalness ?? (robot ? 0.12 : 0),
    envMapIntensity: robot ? 0.9 : 0.7,
  });
  if (look?.emissive) {
    m.emissive = new THREE.Color(0xffffff);
    m.emissiveIntensity = look.emissive;
  }
  return m;
}

/** The default floor (an MJCF plane without a look): a checker, warm for Lit, paper-like for Toon. */
export function floorMaterial(style) {
  const key = `floor_${style}`;
  cache[key] ??= canvasTexture(512, (g, n) => {
    const [a, b] = style === "toon" ? ["#e7e2d9", "#ddd7cc"] : ["#c8c3bb", "#d3cec6"];
    const cells = 8;
    const step = n / cells;
    for (let i = 0; i < cells; i++)
      for (let j = 0; j < cells; j++) {
        g.fillStyle = (i + j) % 2 ? a : b;
        g.fillRect(i * step, j * step, step, step);
      }
  });
  const map = cache[key];
  map.repeat.set(20, 20);
  return style === "toon" ? new THREE.MeshToonMaterial({ map, gradientMap: toonRamp() }) : new THREE.MeshStandardMaterial({ map, roughness: 0.95 });
}

/**
 * Texture coordinates in metres for a box or plane geometry, projected along each face's normal, so
 * textures keep their scale on boxes of any size (the UVs are in units of `tile` metres). On merged
 * world-space geometry the textures also line up across neighbouring boxes.
 */
export function worldUVs(geometry, tile) {
  const pos = geometry.attributes.position;
  const nrm = geometry.attributes.normal;
  const uv = new Float32Array(pos.count * 2);
  for (let i = 0; i < pos.count; i++) {
    const n = [Math.abs(nrm.getX(i)), Math.abs(nrm.getY(i)), Math.abs(nrm.getZ(i))];
    const p = [pos.getX(i), pos.getY(i), pos.getZ(i)];
    const axis = n[0] > n[1] && n[0] > n[2] ? 0 : n[1] > n[2] ? 1 : 2;
    const [a, b] = axis === 0 ? [1, 2] : axis === 1 ? [0, 2] : [0, 1];
    uv[2 * i] = p[a] / tile;
    uv[2 * i + 1] = p[b] / tile;
  }
  geometry.setAttribute("uv", new THREE.BufferAttribute(uv, 2));
  return geometry;
}