Textures & Materials

How to upload a texture and apply it to a standard material. This example uses a PNG image.

Transport

You are viewing: Browser (WASM) · Switch

In the browser, use a canvas with id vulfram-canvas.

Key steps

1. Load the image into bytes.

2. Send it with uploadBuffer using image-data.

3. Create the texture with source: { type: 'buffer', bufferId }.

4. Attach the texture to the standard material (baseTexId).

Browser tip

Place stone.png in static/textures to access it at /textures/stone.png.

The live demo on this page uses an embedded texture so it works out of the box.

Full example

ts
import {
  initEngine,
  createWorld,
  createWindow,
  createEntity,
  createCamera,
  createLight,
  createGeometry,
  createMaterial,
  createModel,
  createTexture,
  uploadBuffer,
  updateTransform,
  tick,
} from '@vulfram/engine';
import { initWasmTransport, transportWasm } from '@vulfram/transport-wasm';

const WINDOW_ID = 1;
const IMAGE_BUFFER_ID = 1;

async function boot() {
  await initWasmTransport();
  initEngine({ transport: transportWasm });
  createWorld(WINDOW_ID);
  createWindow(WINDOW_ID, {
    title: 'Textures & Materials',
    size: [1100, 700],
    position: [0, 0],
    canvasId: 'vulfram-canvas',
  });

  const camera = createEntity(WINDOW_ID);
  updateTransform(WINDOW_ID, camera, {
    position: [0, 2.5, 9],
    rotation: [0, 0, 0, 1],
    scale: [1, 1, 1],
  });
  createCamera(WINDOW_ID, camera, { kind: 'perspective', near: 0.1, far: 100.0 });

  const light = createEntity(WINDOW_ID);
  updateTransform(WINDOW_ID, light, { position: [2, 4, 6], rotation: [0, 0, 0, 1], scale: [1, 1, 1] });
  createLight(WINDOW_ID, light, { kind: 'point', intensity: 16, range: 30 });

  const response = await fetch('/textures/stone.png');
  const bytes = new Uint8Array(await response.arrayBuffer());
  uploadBuffer(IMAGE_BUFFER_ID, 'image-data', bytes);

  const textureId = createTexture(WINDOW_ID, {
    source: { type: 'buffer', bufferId: IMAGE_BUFFER_ID },
    srgb: true,
  });

  const materialId = createMaterial(WINDOW_ID, {
    kind: 'standard',
    options: {
      type: 'standard',
      content: {
        baseColor: [1, 1, 1, 1],
        surfaceType: 'opaque',
        baseTexId: textureId,
        baseSampler: 'linear-repeat',
        flags: 0,
      },
    },
  });

  const geom = createGeometry(WINDOW_ID, { type: 'primitive', shape: 'cube' });
  const model = createEntity(WINDOW_ID);
  updateTransform(WINDOW_ID, model, { position: [0, 0, 0], rotation: [0, 0, 0, 1], scale: [2, 2, 2] });
  createModel(WINDOW_ID, model, { geometryId: geom, materialId });

  let last = performance.now();
  function frame(now: number) {
    const delta = now - last;
    last = now;
    tick(now, delta);
    requestAnimationFrame(frame);
  }
  requestAnimationFrame(frame);
}

boot().catch(console.error);
Live demo canvas