webg

Appendix D: webg 3.0 API Catalog

This catalog helps locate public APIs in webg 3.0 by feature. Check settings, defaults, and exception conditions against the current implementation, samples, and headless tests.

For a first application, begin with 05_AppStructure.md. For renaming and architectural changes from earlier versions, see Appendix B: Migration to webg 3.0.

1. API Entry Points

webg 3.0 builds on the existing WebgApp and adds the application-oriented WebgSceneApp above it:

application code
  ├─ webg/app/index.js
  │    └─ WebgSceneApp / SceneDefinition / ScenePhysics / PbrRenderer
  └─ when direct control is needed
       └─ WebgApp.js, Shape.js, ComputePhysicsSpace.js, and other core modules

1.1 Import from SceneApp

Most applications import from the aggregate entry point:

import {
  WebgSceneApp,
  createWebgSceneApp,
  SceneDefinition,
  parseSceneYAML,
  ScenePhysics,
  PbrRenderer,
  WaterBody
} from "../../webg/app/index.js";

SceneFrame, backend, binding, and helper modules are internal to WebgSceneApp. For internal processing, see Chapter 9 and current webg/app/*.js.

2. WebgSceneApp

2.1 Create an App

const sceneApp = await createWebgSceneApp({
  project: "./scene.webg.yaml",
  camera: { target: [0.0, 1.0, 0.0], distance: 10.5 },
  physics: { enabled: true, paused: true }
});

sceneApp.start();

After create() completes, renderer and Compute-physics resources are available.

2.2 Options

Physics option fields:

Camera fields include target, distance, yaw, pitch, roll, minDistance, maxDistance, focusTarget, and focusTargetOffset. When DoF is active, focusTarget accepts a Node ID or Node.

2.3 Lifecycle and Diagnostics

The onReadback payload contains frameIndex, stateData, contacts, fixedSteps, and physics. contacts groups events into begin, stay, and end.

2.4 Standard Compute Particles

PBR-scene emissive particles use ComputeParticleEmitter. GPU computation handles initial values, movement, gravity, drag, and lifetime, and composites particles additively into the HDR image after transparency. Use rgba16float when registering with PBR. Set a display-format targetFormat when drawing directly to Canvas.

Generation options include preset: "spark" | "light" | "fountain", capacity (default 1024), seed (default 1), overflow: "reject" | "replace-oldest" (default reject), simulation: { gravity, drag }, and appearance: { colors, intensity, size }. colors contains two linear HDR RGB values; size is a radius range [min, max].

Emission settings combine position, lifetime: [min, max], and either velocity with velocitySpread, or direction, spreadAngle, and speed: [min, max]. Units are seconds, world units per second, and degrees. Burst count is an integer from 1 through capacity; up to 32 requests can be pending. reject reserves a contiguous free ring region per request. Capacity failure reasons include particle-capacity and command-capacity.

3. SceneDefinition and Project Manifests

WebgSceneApp uses the same data structure for SceneYAML and JSON project definitions. SceneDefinition.load() chooses YAML for .yaml and .yml, and JSON for .json. materialsUrl and physicsUrl follow the same extension rule. Original text and comments are preserved in source documents.

.yaml.gz, .yml.gz, and .json.gz are decompressed and passed to the same readers. compressSceneYAML(text), available from webg/app/index.js, is a serialization API that gzip-compresses UTF-8 source including comments.

3.1 SceneDefinition API

3.2 Top-Level Manifest Keys

Choose a scene source from scene/sceneUrl, modelAsset/modelAssetUrl, objects/objectSets, or createScene. When a ModelAsset is the source, objects connects its Nodes to project IDs and physics settings. A primitive scene combines materials or materialsUrl with inline physics.space.

particleEmitters is an array of standard Compute-particle settings with unique IDs. Provide optional emission with rate and emission conditions for continuous emission. See Chapters 9 and 26 for examples.

3.3 Primitive Objects

id: ball
shape: {type: sphere, radius: 0.5}
transform: {position: [0.0, 3.2, 0.0]}
material: ball-material
physics:
  bodyType: dynamic
  mass: 1.0
  material: {restitution: 0.18, friction: 0.36}

If physics.shape is omitted, the display shape is shared as the body shape. For a proxy collider, specify physics.shape and colliderRelation: "proxy" explicitly.

3.4 Object Sets

objectSets[] combines a prototype or variants with a placement:

Field Description
prototype Shared shape, transform, material, and physics
variants Multiple shape definitions keyed by id
variantPattern Choose variants per instance using cycle or range
placement.type Currently grid3d
placement.count Counts along X, Y, and Z
placement.origin Placement origin
placement.spacing Spacing between instances
placement.seed Reproducible seed for jitter
placement.jitter Per-axis placement variation
instancePattern cycle or range for transform and physics
overrides Overrides for the set or individual instances

4. PBR and Screen Effects

4.1 PbrRenderer API

For setWater(), surfaceEnabled and causticsEnabled default to false; quality is "low" or "high", defaulting to "high". Pause new frames while switching and resume after completion. ComputeEffectPipeline.setWater() has the same contract. With both features off, dedicated processing counts are zero and timing is null. ComputeEffectPipeline.getWaterStats() has the same contract.

For direct construction, pass an initialized WebGPU context with device and queue, and positive integer width and height. Ordinary applications let WebgSceneApp perform this setup.

The PbrRenderer used by WebgSceneApp runs PbrEnvironmentCompute on environment radiance to generate irradiance, specular mips, and a BRDF LUT on the GPU. A lower-level CPU-precomputed route combines PbrEnvironment with createProceduralEnvironmentData().

4.2 Renderer Manifest

profile: studio
width: 960
height: 640
environment:
  preset: dark-studio
  resolution: {width: 128, height: 64}
dof: {enabled: false}
pipeline:
  lighting: {ambient: 0.0, environmentIntensity: 0.42}
  ssao: {radius: 12.0, strength: 1.15, samples: 8}
  ssr: {intensity: 0.65, distance: 24.0, steps: 28}
  toneMap: {exposure: 1.0}

When environment lighting is enabled, set pipeline.lighting.ambient to 0.0. Photometric units require toneMap.exposureEv100. Choose either exposure or exposureEv100.

4.3 PBR Materials

Primitive materials[] can specify color, metallic, roughness, specular, occlusion, emissive, emissiveFactor, and alphaMode. External materials for authoring scenes combine assetMaterialId with pbr or preset.

Material value Meaning
color RGBA base color in the 0–1 range
metallic Metal contribution, 0–1
roughness PBR specular roughness, 0.04–1
specular Dielectric specular amount
occlusion Environment occlusion
emissive, emissiveFactor Linear HDR emission separate from lighting
alphaMode OPAQUE, MASK, or BLEND
flatShading, doubleSided Normal and back-face rendering settings

External-material preset can combine tile, appearance, scale, and uvMapping. uvMapping selects real-cuboid, real-sphere, or real-capsule.

4.4 WaterBody

Import from webg/WaterBody.js or webg/app/index.js. Connect water separately from the manifest using setWater(). See Chapter 35, samples/water/index.html, and samples/fantasy/main.js.

new WaterBody(options) stores the water region, waves, absorption, and receivers without creating GPU resources. Coordinates and distances use meters, time uses seconds, and absorption coefficients use inverse meters.

extent must cover width and depth; average water depth surfaceHeight - origin[1] must exceed amplitude. See Chapter 35 and current source for valid ranges.

Caustics approximate projection of a horizontal irradiance image under vertical incoming light. Surface display is for a finite horizontal region viewed from above; underwater-camera rendering is outside this path.

5. ScenePhysics and Physics APIs

5.1 ScenePhysics

const physics = new ScenePhysics({
  gpu: app.getGPU(),
  gravity: [0.0, -9.8, 0.0],
  fixedTimeStepMs: 8.3333333333,
  maxSubSteps: 8,
  solverIterations: 10,
  planes: [{ normal: [0.0, 1.0, 0.0], planeDistance: 0.0 }]
});

The default backend is compute; specify backend: "cpu" for comparison and verification.

Compute step() accepts options.commandEncoder and records GPU commands. CPU step() takes milliseconds and simulates on the CPU. WebgSceneApp abstracts the backend difference for application use.

5.2 ComputePhysicsSpace

Use ComputePhysicsSpace for advanced code that accesses GPU state directly.

Compute colliders are ComputeBoxCollider, ComputeSphereCollider, and ComputeCapsuleCollider. Set planes in ComputePhysicsSpace.planes with normal and planeDistance. The standard broad phase uses an XZ grid.

5.3 CPU PhysicsSpace

For direct access to existing CPU physics, import webg/PhysicsSpace.js.

6. WebgApp and Low-Level 3D APIs

6.1 WebgApp

WebgApp is the application foundation for GPU, Canvas, Screen, Space, camera, input, Message, and the update loop.

For compute-first frames, combine new WebgApp({ computeFrame: true }) with start({ onComputeFrame }). onComputeFrame records one frame containing Compute passes, Render passes, and queue submission. WebgSceneApp manages its own PBR and physics processing order.

6.2 Space, Node, and Shape

To create a Shape, generate geometry with Primitive, pass it to Shape.applyPrimitiveAsset(), then finalize GPU resources with Shape.endShape(). Use setMaterial() for one material or setMaterialAt() and triangle material indices for multiple materials.

6.3 Camera and Coordinates

The ordinary camera uses Reverse-Z; shadow maps use Standard-Z. Match depth format, clear value, compare function, and projection matrix to each convention.

7. Low-Level PBR, Compute Passes, and Data Assets

7.1 ComputePass Frame Rules

ComputePass.encode(commandEncoder, resources, options) records GPU commands. The caller submits them. Manage resources in this order:

  1. Create storage buffers, storage textures, and uniforms.
  2. Pass bindings to ComputePass.
  3. Record Compute commands with encode() into the same encoder.
  4. Record required Render passes.
  5. Submit once with queue.submit().
  6. Release resources with destroy() when the page ends.

Use rgba16float for HDR intermediates and a display format for the final Canvas target. Apply tone mapping once for final display.

7.2 Choose an Asset API

7.3 SceneAsset and ModelAsset I/O

Both inherit from DocumentAsset. They load a shared YAML/JSON data structure, then validate their respective asset contents.

To save an edited document with comments, pass updated YAML source to fromYAML(). toYAMLText() throws when parsed values change without a corresponding source update. To convert comment-bearing YAML to JSON, make the choice explicit with toJSONText(2, { allowCommentLoss: true }).

8. Joints, Colliders, and Physics Events

8.1 Joints

Distance Joint settings include bodyA, bodyB, localAnchorA, localAnchorB, distance, compliance, and collideConnected. Identify bodies by scene binding ID or Compute body ID; keep GPU slot indices internal.

8.2 Colliders

CPU colliders provide getAabb(), intersectRay(), overlapsAabb(), and overlapSphere(); infinite planes return no finite AABB. The Compute GPU solver supports Box, Sphere, Capsule, and Plane; a Capsule’s center line is local Y.

8.3 Contact Events

9. Common Usage Rules

9.1 Asynchronous Operations

WebgSceneApp.create(), createWebgSceneApp(), SceneDefinition.load(), PbrRenderer.waitUntilReady(), and asset load() methods return Promises. Start later drawing, physics, and material assignment after each Promise resolves.

9.2 Command Encoder and Submission

Compute physics, ComputePass, and PbrRenderer.encode() record work into a command encoder. Choose one owner for encoder creation and queue submission per frame. Keep Compute, readback, draw, and presentation ordered for that frame. In WebgSceneApp, SceneFrame owns this order.

9.3 Input Validation and Exceptions

Public APIs validate unknown keys, array lengths, numeric ranges, unsupported enums, and GPU-resource state at call time. Errors identify their input path, such as renderer.pipeline.ssao.samples or physics.bodies[2].shape, so the setting can be corrected directly.

9.4 Resource Lifecycle

The class that creates a GPU resource owns its resize() and destroy(). On shutdown, release frame, renderer, physics, scene, Shape, and additional-pass resources according to their ownership. If ownership is shared, specify the boundary in options.

10. Order for Finding an API

  1. Find the class and main methods in this catalog.
  2. Read the corresponding chapter for role, ordering, and input requirements.
  3. Inspect a WebgSceneApp example in samples/project_app/.
  4. Check sample README and SceneYAML/JSON for configuration format.
  5. Check headless_tests/ for boundaries and exception conditions.
  6. Use unittest/ or a browser to inspect GPU output and interaction.
  7. Confirm public methods and resource ownership in current webg/*.js.

This catalog identifies current 3.0 entry points and major low-level APIs. For exact profile values, schemas, and implementation limits, consult current source in webg/app/ and webg/, sample SceneYAML/JSON, and the corresponding tests.