### Start Development Server Source: https://github.com/babylonjs/babylon-lite/blob/master/lab/index.html Use this command to start the Vite development server for live scene serving. ```bash pnpm dev ``` -------------------------------- ### Install and Run Babylon Lite Development Server Source: https://github.com/babylonjs/babylon-lite/blob/master/README.md Follow these steps to install dependencies, set up Playwright browsers, and start the development server for Babylon Lite. Open http://localhost:5174 to view the scene gallery. ```bash pnpm install pnpm exec playwright install pnpm dev:lab ``` -------------------------------- ### End-to-End Scene and HUD Setup Source: https://github.com/babylonjs/babylon-lite/blob/master/docs/lite/architecture/32-sprites.md Example demonstrating the setup of a 3D scene with depth-hosted sprites and a separate HUD overlay. This illustrates how to manage different sprite layer types. ```typescript const engine = await createEngine(canvas); const scene = createSceneContext(engine); addToScene(scene, createDirectionalLight([0, -1, 0])); addToScene(scene, await loadGltf(engine, "world.glb")); const trees = createAxisLockedBillboardSystem(treeAtlas, [0, 1, 0]); addAxisLockedBillboardSystem(scene, trees); // Depth-hosted anchored labels: same Sprite2DLayer factory, depth:"test" // routes it through addDepthHostedSpriteLayer → sprite-renderable, drawn // inside the scene's 3D pass. const labels = createSprite2DLayer(labelAtlas, { depth: "test" }); addAnchoredSprite2D(labels, { anchor: createWorldAnchor([0, 1.8, 0]), sizePx: [128, 32], frame: "name-bg", }); addDepthHostedSpriteLayer(scene, labels); await registerScene(scene); // HUD overlay: separate Sprite2DLayer with depth:"none", drawn by a // separate SpriteRenderer registered AFTER the scene so it draws on top. // `addToScene` is never called for HUD layers — they have no business // in the 3D pass. const hud = createSprite2DLayer(hudAtlas, { depth: "none" }); addSprite2DIndex(hud, { positionPx: [16, 16], sizePx: [200, 32], frame: "score" }); const hudRenderer = createSpriteRenderer(engine, { layers: [hud], clear: false }); registerSpriteRenderer(hudRenderer); // Tie HUD lifetime to the scene — disposeScene fires this and frees the GPU buffers. onSceneDispose(scene, () => disposeSpriteRenderer(hudRenderer)); await startEngine(engine); ``` -------------------------------- ### Example Scene Bundle Analysis Source: https://github.com/babylonjs/babylon-lite/blob/master/GUIDANCE.md A concrete example of how to run the bundle analysis tool for a specific scene, 'scene7'. ```bash pnpm run analyze-bundle scene7 ``` -------------------------------- ### Usage Example Source: https://github.com/babylonjs/babylon-lite/blob/master/docs/lite/architecture/20-loader-babylon.md Example of loading a .babylon scene and adding its contents to the scene. ```typescript const result = await loadBabylon(engine, "https://example.com/scene.babylon"); addToScene(scene, result); // entities[], clearColor, animationGroups dispatched into scene ``` -------------------------------- ### Create and Start Babylon.js Lite Scene Source: https://github.com/babylonjs/babylon-lite/blob/master/GUIDANCE.md This snippet demonstrates the basic setup for creating a Babylon.js scene, loading assets, adding components like lights and cameras, and starting the engine. Ensure the canvas element is available in the DOM. ```typescript async function main(): Promise { const engine = await createEngine(canvas); const scene = createSceneContext(engine); addToScene(scene, await loadGltf(engine, "https://playground.babylonjs.com/scenes/BoomBox.glb")); await loadEnvironment(scene, ".../environment.env"); // Components are plain data — scene is the owner const light = createHemisphericLight([0, 1, 0], 0.7); addToScene(scene, light); const camera = createDefaultCamera(scene); camera.alpha += Math.PI; // Materials own their renderable builders — no explicit pipeline building await registerScene(scene); // builds deferred work, partitions renderables await startEngine(engine); // resolves after first frame rendered; renders all registered scenes } ``` -------------------------------- ### Run Lab for Comparison Source: https://github.com/babylonjs/babylon-lite/blob/master/packages/babylon-lite-compat/CONTRIBUTING.md Start the lab development server to compare scenes from the /compat/ and /lite/ directories. ```sh pnpm --filter lab dev ``` -------------------------------- ### Environment Manifest Structure Example Source: https://github.com/babylonjs/babylon-lite/blob/master/docs/lite/architecture/00-overview.md Provides an example of the relevant fields within the JSON manifest of a .env file. ```json { "width": 256, "imageType": "image/png", "irradiance": { "x": [...], "y": [...], ... "xy": [...] }, "specular": { "lodGenerationScale": 0.8, "mipmaps": [ { "position": 0, "length": 12345 }, ... ] } } ``` -------------------------------- ### Quick Start Babylon Lite Scene Source: https://github.com/babylonjs/babylon-lite/blob/master/packages/babylon-lite/README.md Initialize a Babylon Lite engine, create a scene, load a glTF model, add a light and camera, and start the rendering loop. ```typescript import { createEngine, createSceneContext, createDefaultCamera, createHemisphericLight, addToScene, loadGltf, registerScene, startEngine } from "@babylonjs/lite"; async function main(): Promise { const canvas = document.getElementById("renderCanvas") as HTMLCanvasElement; const engine = await createEngine(canvas); const scene = createSceneContext(engine); addToScene(scene, await loadGltf(engine, "https://playground.babylonjs.com/scenes/BoomBox.glb")); addToScene(scene, createHemisphericLight([0, 1, 0], 1.0)); createDefaultCamera(scene); await registerScene(scene); await startEngine(engine); } main().catch(console.error); ``` -------------------------------- ### Migration Path Example Source: https://github.com/babylonjs/babylon-lite/blob/master/packages/babylon-lite-compat/README.md Illustrates the intended migration path from core Babylon.js to babylon-lite using the compat layer. ```text @babylonjs/core → @babylonjs/lite-compat → babylon-lite (native) ``` -------------------------------- ### Install Babylon Lite Source: https://github.com/babylonjs/babylon-lite/blob/master/docs/lite/01-getting-started.md Install the Babylon Lite package using npm. This is the only package needed for the runtime. ```bash npm install @babylonjs/lite ``` -------------------------------- ### Babylon Lite Scene Setup Source: https://github.com/babylonjs/babylon-lite/blob/master/docs/lite/00-welcome.md Scene setup in Babylon Lite using standalone functions and plain data. Imports are tree-shakable functions. ```typescript import { createEngine, createSceneContext, createDefaultCamera, createHemisphericLight, loadGltf, loadEnvironment, addToScene, attachControl, registerScene, startEngine, } from "@babylonjs/lite"; const engine = await createEngine(canvas); const scene = createSceneContext(engine); addToScene(scene, createHemisphericLight([0, 1, 0], 1.0)); addToScene(scene, await loadGltf(engine, "https://playground.babylonjs.com/scenes/BoomBox.glb")); await loadEnvironment(scene, "https://assets.babylonjs.com/core/environments/environmentSpecular.env", { groundTextureUrl: "https://assets.babylonjs.com/core/environments/backgroundGround.png", skyboxUrl: "https://assets.babylonjs.com/core/environments/backgroundSkybox.dds", skyboxSize: 1000, }); const cam = createDefaultCamera(scene); attachControl(cam, canvas, scene); await registerScene(scene); await startEngine(engine); ``` -------------------------------- ### Register Scene with Shadow Support Source: https://github.com/babylonjs/babylon-lite/blob/master/docs/lite/architecture/28-frame-graph.md Installs an internal ShadowTask before the default 'scene' render task. This is a setup step for shadow rendering. ```typescript await registerSceneWithShadowSupport(scene); ``` -------------------------------- ### Babylon.js Scene Setup Source: https://github.com/babylonjs/babylon-lite/blob/master/docs/lite/00-welcome.md Standard scene setup in Babylon.js using classes and methods. Requires importing core components and loaders. ```typescript import { WebGPUEngine } from "@babylonjs/core/Engines/webgpuEngine"; import "@babylonjs/core/Helpers/sceneHelpers"; import { HemisphericLight } from "@babylonjs/core/Lights/hemisphericLight"; import { SceneLoader } from "@babylonjs/core/Loading/sceneLoader"; import { CubeTexture } from "@babylonjs/core/Materials/Textures/cubeTexture"; import { Vector3 } from "@babylonjs/core/Maths/math.vector"; import { Scene } from "@babylonjs/core/scene"; import "@babylonjs/loaders/glTF"; const engine = new WebGPUEngine(canvas, { antialias: true, adaptToDeviceRatio: true }); await engine.initAsync(); const scene = new Scene(engine); const light = new HemisphericLight("hemi", new Vector3(0, 1, 0), scene); light.intensity = 1.0; await SceneLoader.ImportMeshAsync("", "https://playground.babylonjs.com/scenes/", "BoomBox.glb", scene); scene.environmentTexture = new CubeTexture("https://assets.babylonjs.com/core/environments/environmentSpecular.env", scene); scene.createDefaultCamera(true, true, true); scene.createDefaultEnvironment({ createSkybox: true, createGround: true, skyboxSize: 1000 }); engine.runRenderLoop(() => scene.render()); ``` -------------------------------- ### Initialize Babylon Lite Engine and Scene Source: https://github.com/babylonjs/babylon-lite/blob/master/packages/babylon-lite-compat/README.md Basic setup for creating a WebGPU engine, initializing it, and creating a scene with a camera, light, and a simple box mesh. ```typescript import { WebGPUEngine, Scene, ArcRotateCamera, HemisphericLight, MeshBuilder, StandardMaterial, Vector3, Color3 } from "@babylonjs/lite-compat"; const engine = new WebGPUEngine(canvas); await engine.initAsync(); const scene = new Scene(engine); const camera = new ArcRotateCamera("cam", -Math.PI / 2, Math.PI / 2.5, 5, new Vector3(0, 0, 0), scene); camera.attachControl(canvas, true); new HemisphericLight("light", new Vector3(0, 1, 0), scene); const box = MeshBuilder.CreateBox("box", { size: 1 }, scene); const mat = new StandardMaterial("mat", scene); mat.diffuseColor = new Color3(1, 0, 0); box.material = mat; engine.runRenderLoop(() => scene.render()); ``` -------------------------------- ### Running Unit Tests with Vitest Source: https://github.com/babylonjs/babylon-lite/blob/master/README.md Instructions for setting up and running pure logic tests that do not require a browser or GPU. Ensure Vitest is installed and configured. ```bash # 1. Create test file # tests/lite/unit/my-feature.test.ts # 2. Use vitest APIs # describe('my feature', () => { # it('should work', () => { # expect(true).toBe(true); # }); # }); # 3. Run tests pnpm exec vitest run ``` -------------------------------- ### Pure-2D SpriteRenderer Setup Source: https://github.com/babylonjs/babylon-lite/blob/master/docs/lite/architecture/32-sprites.md Initialize and run a pure-2D application using SpriteRenderer. This setup bypasses the scene graph and is suitable for applications that only require 2D sprite rendering. ```typescript import { createEngine, loadSpriteAtlas, createSprite2DLayer, addSprite2DIndex, createSpriteRenderer, registerSpriteRenderer, startEngine } from "@babylonjs/lite"; const engine = await createEngine(canvas); const atlas = await loadSpriteAtlas(engine, "sprites.png", { gridSize: [32, 32] }); const layer = createSprite2DLayer(atlas); addSprite2DIndex(layer, { positionPx: [100, 200], sizePx: [64, 64], frame: 0 }); const sr = createSpriteRenderer(engine, { layers: [layer], clearValue: { r: 0, g: 0, b: 0, a: 1 }, }); registerSpriteRenderer(sr); await startEngine(engine); ``` -------------------------------- ### Start Babylon Lite Generation Source: https://github.com/babylonjs/babylon-lite/blob/master/lab/index.html Initiates the generation process for a given target. This function handles the initial fetch request to the generation API and sets up polling for status updates. It disables relevant buttons during the process and displays a starting message. ```javascript function generateTabContent(target) { var cfg = TAB_GEN_CONFIG[target]; if (!cfg) return; var btn = _genEl(target, "btn"); var msg = _genEl(target, "msg"); var regenBtn = _genToolbarBtn(target); var spinner = _genEl(target, "spinner"); var logbar = _genEl(target, "logbar"); _genActive[target] = true; _showGenBlock(target, true); if (btn) btn.disabled = true; if (regenBtn) regenBtn.disabled = true; if (msg) msg.innerHTML = "Generating " + cfg.label + " — running " + cfg.command + "…"; if (spinner) spinner.textContent = "⏳ Starting…"; if (logbar) logbar.style.display = "none"; _setGenLog(target, "Starting " + cfg.command + "…"); fetch("/lab-api/generate?target=" + target, { method: "POST" }) .then(function (r) { return r.json().catch(function () { return { started: false, error: "HTTP " + r.status }; }); }) .then(function (res) { if (!res || !res.started) { _stopGenHeartbeat(target); if (btn) btn.disabled = false; if (regenBtn) regenBtn.disabled = false; if (spinner) spinner.textContent = ""; if (logbar) logbar.style.display = "flex"; _setGenLog(target, (res && res.error) || "Could not start generation."); return; } _startGenPolling(target); }) .catch(function (err) { _stopGenHeartbeat(target); if (btn) btn.disabled = false; if (regenBtn) regenBtn.disabled = false; if (spinner) spinner.textContent = ""; if (logbar) logbar.style.display = "flex"; _setGenLog(target, "Request failed: " + err); }); } ``` -------------------------------- ### HTML Canvas Setup Source: https://github.com/babylonjs/babylon-lite/blob/master/lab/lite/bundle-scene40.html Basic HTML structure for a Babylon.js application, including a canvas element for rendering. ```html ``` -------------------------------- ### Effect Wrapper and Renderer Setup Source: https://github.com/babylonjs/babylon-lite/blob/master/docs/lite/architecture/00-overview.md Functions for creating and managing fullscreen effect passes. Use `setEffectUniforms` and `setEffectTexture` to configure effects. ```typescript createEffectWrapper(engine: Engine, options: EffectWrapperOptions): EffectWrapper ``` ```typescript setEffectUniforms(wrapper: EffectWrapper, data: ArrayBuffer | ArrayBufferView | Record): void ``` ```typescript setEffectTexture(wrapper: EffectWrapper, bindingNameOrIndex: string | number, texture: Texture2D): void ``` ```typescript createEffectRenderer(engine: Engine, effect: EffectWrapper, options?: EffectRendererOptions): EffectRenderer ``` ```typescript registerEffectRenderer(renderer: EffectRenderer): void ``` ```typescript unregisterEffectRenderer(renderer: EffectRenderer): void ``` ```typescript disposeEffectRenderer(renderer: EffectRenderer): void ``` ```typescript createEffectRenderTask(config: EffectRenderTaskConfig, engine: Engine, scene: SceneContext): EffectRenderTask ``` ```typescript disposeEffectWrapper(wrapper: EffectWrapper): void ``` -------------------------------- ### Thin Instance Buffer Setup Source: https://github.com/babylonjs/babylon-lite/blob/master/docs/lite/03-porting-guide.md Babylon Lite uses `setThinInstances` and `setThinInstanceColors` with raw Float32Array data for thin instances, avoiding the need for Babylon.js Matrix objects. ```typescript // ❌ Babylon.js const matrices = new Float32Array(count * 16); // ... fill with Matrix values ... mesh.thinInstanceSetBuffer("matrix", matrices, 16); mesh.thinInstanceSetBuffer("color", colors, 4); // ✅ Babylon Lite const matrices = new Float32Array(count * 16); // ... fill directly (column-major 4x4) ... setThinInstances(mesh, matrices, count); setThinInstanceColors(mesh, colors); addToScene(scene, mesh); ``` -------------------------------- ### Engine Initialization Sequence Steps Source: https://github.com/babylonjs/babylon-lite/blob/master/docs/lite/architecture/22-engine.md Outlines the key steps involved in initializing the Babylon.js Lite engine, from requesting WebGPU resources to configuring the swap chain. ```text 1. Adapter request: navigator.gpu.requestAdapter({ powerPreference: 'high-performance' }) — throws if WebGPU unavailable. 2. Device request: adapter.requestDevice({ requiredFeatures }) — optionally enables `float32-filterable` if supported. 3. Canvas context: canvas.getContext('webgpu') — throws if context unavailable. 4. Swap chain configure: context.configure({ device, format, alphaMode }) where format = navigator.gpu.getPreferredCanvasFormat() and alphaMode = options?.alphaMode ?? "opaque". 5. MSAA: Defaults to `msaaSamples = 4`, or `1` when requested. 6. Rendering contexts: Initializes an empty `_renderingContexts` list. Scenes and other renderers register themselves with the engine. ``` -------------------------------- ### Start Sprite Animation Manager Source: https://github.com/babylonjs/babylon-lite/blob/master/docs/lite/architecture/32-sprites.md Starts the update loop for a SpriteAnimationManager. ```APIDOC ## startSpriteAnimationManager ### Description Starts the update loop for a SpriteAnimationManager. ### Method `startSpriteAnimationManager(manager: SpriteAnimationManager): void` ### Parameters - **manager** (SpriteAnimationManager) - The manager to start. ``` -------------------------------- ### Build Bundle Scenes Source: https://github.com/babylonjs/babylon-lite/blob/master/README.md Run this command to generate the necessary bundle scenes, which resolves 404 errors for '/bundle/manifest.json'. ```bash pnpm build:bundle-scenes ``` -------------------------------- ### Get Generation Element Source: https://github.com/babylonjs/babylon-lite/blob/master/lab/index.html Helper function to get a DOM element associated with a generation target, optionally with a suffix. ```javascript function _genEl(target, suffix) { return document.getElementById("gen-" + target + (suffix ? "-" + suffix : "")); } ``` -------------------------------- ### Build Standalone Showcase Demos Source: https://github.com/babylonjs/babylon-lite/blob/master/lab/index.html Regenerates the sizes for standalone showcase demos built on Babylon Lite. These demos are production-bundled to show their shipped size. ```bash pnpm build:bundle-demos ``` -------------------------------- ### Start Generation Heartbeat Source: https://github.com/babylonjs/babylon-lite/blob/master/lab/index.html Starts a periodic timer to update the spinner with elapsed time. Prevents the UI from appearing frozen during long generation processes. ```javascript function _startGenHeartbeat(target) { if (_genHeartbeat[target]) return; _genStart[target] = Date.now(); var paint = function () { var sp = _genEl(target, "spinner"); if (sp) sp.textContent = "⏳ Running… " + _fmtElapsed(Date.now() - _genStart[target]); }; paint(); _genHeartbeat[target] = setInterval(paint, 1000); } ``` -------------------------------- ### glTF Loader Pipeline Overview Source: https://github.com/babylonjs/babylon-lite/blob/master/docs/lite/architecture/04-loaders.md Illustrates the step-by-step process of loading a glTF asset, from fetching the file to creating mesh and animation data, including feature module integration and texture caching. ```text fetch(url) → ArrayBuffer ↓ parseGlbContainer(buffer) ↓ { json, binChunk: DataView } ↓ loadFeatureModules(json) // dynamic imports, e.g. KHR_texture_basisu ├── preMesh hooks // Draco, KTX2 strided FLOAT accessor decode, etc. └── material hooks // feature-owned texture/material/metadata overrides ↓ extractAllMeshes(json, binChunk) // for each node with mesh ├── resolveAccessor() × N // positions, normals, tangents, UVs, indices ├── extractMaterial() // PBR factors + textures │ └── resolveImage() × 5 // parallel image decode └── computeNodeWorldMatrix() // recursive parent chain + RH→LH root ↓ GltfMeshData[] ↓ uploadMeshes(device, meshDatas) ├── uploadTexture() × 4 // → Texture2D objects (cached per bitmap + sRGB) ├── runMatExts() // feature-owned material overrides, e.g. KTX2 textures ├── createBufferFromData() × 5 // pos, norm, tan, uv, idx ├── computeWorldBounds() // world-space AABB └── assemble PbrMaterialProps // { baseColorTexture, normalTexture, ormTexture, emissiveTexture?, _buildGroup: pbrGroupBuilder } ↓ Mesh[] + root TransformNode ↓ createAnimationGroups(json, ...) // extract glTF animations → AnimationGroup[] ↓ AssetContainer { entities: [root], animationGroups } → returned to caller; addToScene() dispatches entities + registers animation ticks ``` -------------------------------- ### Show Bundle Files Source: https://github.com/babylonjs/babylon-lite/blob/master/lab/index.html Initiates the process of displaying bundle files for a given scene. It fetches necessary JSON data (bundle info, manifests) and prepares local and master data for comparison. ```javascript window.showBundleFiles = function (scene) { var cfg = (window.SCENE_CONFIG || []).filter(function (c) { return "scene" + c.id === scene; })[0]; var title = cfg ? cfg.name : scene; document.getElementById("bf-title").textContent = title; document.getElementById("bf-subtitle").textContent = "loading…"; var body = document.getElementById("bf-body"); body.innerHTML = '
Loading…
'; document.getElementById("bf-overlay").classList.add("active"); Promise.all([ loadJson("/bundle/bundle-info/" + scene + ".json"), loadJson("/bundle/manifest.json"), loadJson("/bundle/master-bundle-info/" + scene + ".json"), loadJson("/bundle/master-manifest.json"), ]).then(function (results) { var info = results[0]; var manifest = results[1] || {}; var masterInfo = results[2]; var masterManifest = results[3]; var localData = prepareBundleSourceData("Local", info, manifest, scene); var masterData = prepareBundleSourceData("Master", masterInfo, masterManifest, scene); if (!localData && !masterData) { body.innerHTML = '
No bundle info available. '; ``` -------------------------------- ### Basic HTML and CSS for Canvas Setup Source: https://github.com/babylonjs/babylon-lite/blob/master/lab/lite/scene37.html Sets up the basic HTML structure and CSS styling for a full-screen canvas element, commonly used for WebGL applications like Babylon.js. ```html Scene 37 - Sheen Wood Leather Sofa ``` -------------------------------- ### Render Loop Start and Frame Rendering Source: https://github.com/babylonjs/babylon-lite/blob/master/docs/lite/architecture/22-engine.md Defines the structure for starting the engine's render loop using `requestAnimationFrame` and handling the first frame resolution. It also shows how to stop the loop. ```javascript registerScene(scene): adds scene as a RenderingContext startEngine(engine): return new Promise(resolve => { renderFn = (now) => { resizeEngine(engine); deltaMs = now - prev renderFrame(engine, deltaMs); resolve() // first frame only prev = now animFrameId = requestAnimationFrame(renderFn); }; animFrameId = requestAnimationFrame(renderFn); }) stopEngine(engine): cancelAnimationFrame(animFrameId); animFrameId = 0; renderFn = null; ``` -------------------------------- ### Sound State Machine Source: https://github.com/babylonjs/babylon-lite/blob/master/docs/lite/architecture/41-audio-engine.md Details the state transitions for a sound instance, including Stopped, Starting, Started, Stopping, and Stopped states, with branches for Paused and FailedToStart. The onEnded event fires when the last instance concludes. ```javascript Stopped → Starting → Started → (Stopping) → Stopped, with Paused and FailedToStart branches — identical to soundState.ts. onEnded fires when the last instance ends (non-looping full play, or explicit stop). ``` -------------------------------- ### Initialize and Load Scene in Babylon.js Source: https://github.com/babylonjs/babylon-lite/blob/master/docs/lite/03-porting-guide.md This snippet demonstrates the standard Babylon.js method for initializing the engine, creating a scene, loading a glTF model, and setting up lighting and environment. ```typescript const engine = new WebGPUEngine(canvas); await engine.initAsync(); const scene = new Scene(engine); scene.clearColor = new Color4(0.2, 0.2, 0.3, 1); const light = new HemisphericLight("h", new Vector3(0, 1, 0), scene); light.intensity = 1.0; await SceneLoader.ImportMeshAsync("", baseUrl, "BoomBox.glb", scene); const envTex = new CubeTexture(envUrl, scene); scene.environmentTexture = envTex; scene.createDefaultCamera(true, true, true); scene.createDefaultEnvironment({ skyboxSize: 1000 }); engine.runRenderLoop(() => scene.render()); ``` -------------------------------- ### Pure 2D Sprite Renderer Setup Source: https://github.com/babylonjs/babylon-lite/blob/master/docs/lite/architecture/32-sprites.md Initializes a SpriteRenderer for a pure 2D application without a SceneContext. This setup involves creating an engine, loading a sprite atlas, creating a layer, adding sprites, and registering the renderer. ```typescript const engine = await createEngine(canvas); const atlas = await loadSpriteAtlas(engine, "sprites.png", { gridSize: [32, 32] }); const layer = createSprite2DLayer(atlas); sprite2DIndex(layer, { positionPx: [100, 200], sizePx: [64, 64], frame: 0 }); const sr = createSpriteRenderer(engine, { layers: [layer], clearValue: { r: 0, g: 0, b: 0, a: 1 }, }); registerSpriteRenderer(sr); await startEngine(engine); ``` -------------------------------- ### Material Stencil Usage Example Source: https://github.com/babylonjs/babylon-lite/blob/master/docs/lite/architecture/40-material-stencil.md Illustrates how to configure a material to write to the stencil buffer using `compare: "always"` and `passOp: "increment-clamp"`. This example shows how a 'writer' material increments the stencil value where it draws. ```typescript // Mask/test without a dynamic reference: a **writer** uses `compare: "always"` + `passOp: "increment-clamp"` // (stencil 0 → 1 where it draws); a **tester** uses `compare: "equal"`, which passes only where the stencil is // still the render pass's default reference of `0` (i.e. NOT written). ``` -------------------------------- ### Initialize Demos Grid Source: https://github.com/babylonjs/babylon-lite/blob/master/lab/index.html Renders the demos grid by iterating over a provided 'demos' array. It generates HTML for each demo card, including images, titles, descriptions, tags, and hide buttons. Requires helper functions like 'renderHideBtn', 'escapeAttr', 'normalizeSearchText', and 'renderDemoFilterPills'. ```javascript function initDemosGrid(demos) { var grid = document.getElementById("demos-grid"); if (!grid) return; grid.innerHTML = (demos || []).map(function (d) { var demoKey = "demo-" + d.slug; var tags = d.tags || []; var searchAttr = escapeAttr(normalizeSearchText([demoKey, d.slug, d.name, d.description, tags.join(" ")].join(" "))); return ( '' + renderHideBtn(demoKey) + '
' + '' + escapeAttr(d.name) + '' + '
' + '
' + '

' + escapeAttr(d.name) + '

' + '

' + escapeAttr(d.description) + '

' + renderBadges(tags, DEMO_TAG_LABELS) + '
' + '
' ); }).join(""); renderDemoFilterPills(demos); } ``` -------------------------------- ### startAnimationManager Source: https://github.com/babylonjs/babylon-lite/blob/master/docs/lite/architecture/07-animation.md Starts the animation playback for all animations managed by an AnimationManager. ```APIDOC ## startAnimationManager ### Description Starts the animation playback for all animations managed by an AnimationManager. ### Parameters - **manager** (AnimationManager) - The animation manager. ``` -------------------------------- ### Engine and Render Loop Initialization Source: https://github.com/babylonjs/babylon-lite/blob/master/docs/lite/03-porting-guide.md Babylon Lite uses `startEngine` which returns a promise resolving after the first frame, whereas Babylon.js uses `runRenderLoop` with a callback. ```typescript // ❌ Babylon.js const engine = new WebGPUEngine(canvas); await engine.initAsync(); const scene = new Scene(engine); // ... setup ... engine.runRenderLoop(() => scene.render()); // ✅ Babylon Lite const engine = await createEngine(canvas); const scene = createSceneContext(engine); // ... setup ... await startEngine(engine); ``` -------------------------------- ### Load Bundle Manifests Source: https://github.com/babylonjs/babylon-lite/blob/master/lab/index.html Fetches the main bundle manifest and an optional master manifest, then updates the bundle summary. ```javascript function loadBundleManifest() { Promise.all(\[ fetch("/bundle/manifest.json?t=" + Date.now(), { cache: "no-store" }).then(function (r) { return r.json(); }), fetchOptionalJson("/bundle/master-manifest.json"), \] ) .then(function (r) { var manifest = r\[0\]; var masterManifest = r\[1\]; setBundleMasterStatus(masterManifest); updateBundleSummary(manifest, masterManifest); var bjsCount = 0; for (var scene in manifest) { if (!manifest.hasOwnProperty(scene)) continue; var sizes = manifest\[scene\]; var masterSizes = masterManifest && masterManifest\[scene\]; var card = document.querySelector('\\[data-scene="' + scene + '"\\] .size-info'); if (!card) continue; var html = '
; ``` -------------------------------- ### Stop Static Sound Source: https://github.com/babylonjs/babylon-lite/blob/master/docs/lite/architecture/41-audio-engine.md Stops the playback of a static sound and resets its playback position to the start. ```typescript export function stopSound(sound: StaticSound): void; ``` -------------------------------- ### Build and Run Parity Tests on Cloud Source: https://github.com/babylonjs/babylon-lite/blob/master/TESTING.md Build bundle scenes and execute parity tests using cloud configurations. Requires BrowserStack credentials to be set. ```sh pnpm build:bundle-scenes pnpm test:parity-cloud ``` -------------------------------- ### Get Regeneration Toolbar Button Source: https://github.com/babylonjs/babylon-lite/blob/master/lab/index.html Retrieves the regeneration button element from the toolbar for a given target. ```javascript function _genToolbarBtn(target) { return document.getElementById(target + "-regen-btn"); } ``` -------------------------------- ### Get View Matrix Source: https://github.com/babylonjs/babylon-lite/blob/master/docs/lite/01-getting-started.md Behavior functions, such as `getViewMatrix`, operate on data objects and are separate from the object definitions. ```typescript getViewMatrix(camera); ``` -------------------------------- ### Run Unit Tests (GPU-free) Source: https://github.com/babylonjs/babylon-lite/blob/master/packages/babylon-lite-compat/CONTRIBUTING.md Execute unit tests for math, observables, engine/scene APIs, and bundler resolver without requiring a GPU. ```sh pnpm exec vitest run --project compat ``` -------------------------------- ### Scene-Based Sprite Animation Setup Source: https://github.com/babylonjs/babylon-lite/blob/master/docs/lite/architecture/32-sprites.md Demonstrates how to set up sprite animations attached to a Babylon.js scene. This involves creating a scene context, loading a sprite atlas, creating a sprite layer, and attaching animations to the scene's render loop. ```typescript const scene = createSceneContext(engine); const atlas = await loadSpriteAtlas(engine, "sprites.png", { gridSize: [32, 32] }); const layer = createSprite2DLayer(atlas, { depth: "test" }); addDepthHostedSpriteLayer(scene, layer); const animMgr = createSpriteAnimationManager(); attachSpriteAnimationsToScene(scene, animMgr); const handle = addSprite2D(layer, { positionPx: [100, 200], sizePx: [64, 64], frame: 0 }); playSprite2DAnimation(animMgr, handle, 0, 7, true, 100); // 8-frame loop at 100ms/frame ``` -------------------------------- ### Initialize and Load Scene in Babylon Lite Source: https://github.com/babylonjs/babylon-lite/blob/master/docs/lite/03-porting-guide.md This snippet shows the Babylon Lite approach to creating an engine, scene context, loading glTF models, and setting up the environment. ```typescript const engine = await createEngine(canvas); const scene = createSceneContext(engine); addToScene(scene, await loadGltf(engine, "BoomBox.glb")); await loadEnvironment(scene, envUrl, { skyboxUrl: "skybox.dds", skyboxSize: 1000, groundTextureUrl: "ground.png", brdfUrl: "/brdf-lut.png", }); const cam = createDefaultCamera(scene); attachControl(cam, canvas, scene); addToScene(scene, createHemisphericLight([0, 1, 0], 1.0)); await startEngine(engine); ``` -------------------------------- ### Get Performance Regression Label Source: https://github.com/babylonjs/babylon-lite/blob/master/lab/index.html Generates a display label for a performance regression, showing the delta percentage or 'inconclusive'. ```javascript function perfRegLabel(e) { return perfRegVerdict(e) === "inconclusive" ? "inconclusive" : fmtDelta(e.avgDeltaPct); } ``` -------------------------------- ### Create a Basic Babylon.js Lite Scene Source: https://github.com/babylonjs/babylon-lite/blob/master/docs/lite/01-getting-started.md This snippet shows the core structure for a minimal Babylon.js Lite application. It initializes the engine, scene, camera, light, and a sphere with a PBR material. Follow the 'create → add → register → start' pattern. ```typescript import { createEngine, createSceneContext, createArcRotateCamera, attachControl, createHemisphericLight, createSphere, createPbrMaterial, addToScene, registerScene, startEngine, } from "@babylonjs/lite"; const canvas = document.getElementById("renderCanvas") as HTMLCanvasElement; // 1. Engine const engine = await createEngine(canvas); // 2. Scene const scene = createSceneContext(engine); // Camera (plain data) — set it on the scene, then attach input handling const camera = createArcRotateCamera(-Math.PI / 2, Math.PI / 2.5, 4, { x: 0, y: 0, z: 0 }); scene.camera = camera; attachControl(camera, canvas, scene); // Light addToScene(scene, createHemisphericLight([0, 1, 0], 1.0)); // A sphere with a simple PBR material const sphere = createSphere(engine, { segments: 16, diameter: 2 }); sphere.material = createPbrMaterial({ baseColorFactor: [0.9, 0.1, 0.1, 1], metallicFactor: 0.1, roughnessFactor: 0.4 }); addToScene(scene, sphere); // 3. Register (after everything is added) await registerScene(scene); // 4. Start the render loop await startEngine(engine); ``` ```html ``` -------------------------------- ### Get Master Lookups Source: https://github.com/babylonjs/babylon-lite/blob/master/lab/index.html Retrieves or computes lookup tables for master chunk and module bytes. Caches the result for performance. ```javascript function getMasterLookups() { if (state.source !== "local" || !state.sources.master) return null; if (state.masterLookups) return state.masterLookups; var chunkBytes = {}; var moduleBytes = {}; var chunks = state.sources.master.info.chunks || []; for (var i = 0; i < chunks.length; i++) { chunkBytes[chunkSortKey(chunks[i].file)] = chunks[i].bytes; } buildModuleList(chunks).forEach(function (m) { moduleBytes[m.id] = m.bytes; }); state.masterLookups = { chunkBytes: chunkBytes, moduleBytes: moduleBytes }; return state.masterLookups; } ``` -------------------------------- ### Build Publishable Distribution Source: https://github.com/babylonjs/babylon-lite/blob/master/packages/babylon-lite-compat/CONTRIBUTING.md Create the distributable files for the @babylonjs/lite-compat package, including ESM and .d.ts files. ```sh pnpm --filter @babylonjs/lite-compat build ``` -------------------------------- ### Get Float Frequency Data Source: https://github.com/babylonjs/babylon-lite/blob/master/docs/lite/architecture/41-audio-engine.md Retrieves the frequency data of a sound or audio bus as an array of 32-bit floating-point numbers. ```typescript export function getFloatFrequencyData(sound: StaticSound | AudioBus, out: Float32Array): void; ``` -------------------------------- ### Create and Load PBR Material Source: https://github.com/babylonjs/babylon-lite/blob/master/docs/lite/architecture/06-pbr-material.md Demonstrates manual creation of a PBR material with various texture and layer properties, and shows how materials are automatically built when loading glTF models. Ensure textures are loaded before assigning them. ```typescript // Manual creation const mat = createPbrMaterial({ baseColorTexture: await loadTexture2D(engine, "albedo.png"), normalTexture: await loadTexture2D(engine, "normal.png"), ormTexture: await loadTexture2D(engine, "orm.png"), clearCoat: { isEnabled: true, intensity: 1, roughness: 0.1 }, sheen: { isEnabled: true, color: [1, 1, 1], roughness: 0.5 }, }); // From glTF (automatic — loadGltf() builds PbrMaterialProps internally) addToScene(scene, await loadGltf(engine, "model.glb")); ``` -------------------------------- ### Create Audio Engine Async Source: https://github.com/babylonjs/babylon-lite/blob/master/docs/lite/architecture/41-audio-engine.md Asynchronously creates an instance of the audio engine. Options can configure the audio context, parameter ramp duration, initial volume, and interaction-based resumption. ```typescript export function createAudioEngineAsync(options?: AudioEngineOptions): Promise; ``` -------------------------------- ### Get Byte Frequency Data Source: https://github.com/babylonjs/babylon-lite/blob/master/docs/lite/architecture/41-audio-engine.md Retrieves the frequency data of a sound or audio bus as an array of unsigned 8-bit integers. ```typescript export function getByteFrequencyData(sound: StaticSound | AudioBus, out: Uint8Array): void; ``` -------------------------------- ### Pure-2D Sprite Animation Setup Source: https://github.com/babylonjs/babylon-lite/blob/master/docs/lite/architecture/32-sprites.md Illustrates setting up sprite animations for a pure-2D rendering context without direct scene attachment. This requires manually creating a sprite renderer and attaching animations to it. ```typescript // Pure-2D with manual update const sr = createSpriteRenderer(engine, { layers: [layer] }); const binding = attachSpriteAnimationsToRenderer(sr, animMgr); // Animation now updates before sprite uploads ``` -------------------------------- ### Get Picked UV Source: https://github.com/babylonjs/babylon-lite/blob/master/docs/lite/architecture/18-picking.md Interpolates the UV coordinates at the picked point using barycentric coordinates. This is useful for texture mapping. ```typescript /** Interpolate the UV at the picked point using barycentric coords. */ function getPickedUV(info: PickingInfo): [number, number] | null; ``` -------------------------------- ### Capture Golden Reference Image Commands Source: https://github.com/babylonjs/babylon-lite/blob/master/CONTRIBUTING.md Bash commands to start the development server and capture the golden reference image for a scene. ```bash # Start the dev server pnpm dev:lab # In another terminal, capture the golden pnpm exec tsx scripts/capture-golden.ts --scene N ```