Optimizing Meshes in Babylon.js with Mesh Optimizer

Why Optimize Meshes?

Before diving into Babylon’s mesh optimizer, let’s understand why optimization is necessary:

  1. Faster Rendering – Reducing the number of vertices and polygons speeds up GPU processing.
  2. Better Performance on Low-end Devices – Optimized meshes reduce memory usage, improving performance on mobile and older hardware.
  3. Smaller File Sizes – Optimized models load faster, reducing bandwidth consumption.
  4. Efficient Collision Detection & Physics – Fewer polygons make physics calculations and collisions more efficient.

Mesh Optimizer in Babylon.js

Babylon.js provides an automatic mesh optimizer that simplifies models by reducing the number of vertices and faces while preserving visual quality. It is particularly useful for GLTF and OBJ models imported into a scene.

How It Works

The mesh optimizer in Babylon.js works by:

  • Merging duplicate vertices – If multiple vertices share the same position and normal, they get merged into one.
  • Removing unnecessary vertices – If a vertex does not contribute to the visual appearance, it can be safely removed.
  • Simplifying geometry – Reducing the number of triangles without compromising too much on appearance.

How to Use Babylon.js Mesh Optimizer

1. Setting Up Babylon.js

First, let’s initialize a Babylon.js scene:

js

Copy

Edit
import * as BABYLON from 'https://cdn.babylonjs.com/babylon.js';

const canvas = document.createElement('canvas');
document.body.appendChild(canvas);
const engine = new BABYLON.Engine(canvas, true);

const scene = new BABYLON.Scene(engine);
const camera = new BABYLON.ArcRotateCamera("camera", Math.PI / 2, Math.PI / 2, 5, BABYLON.Vector3.Zero(), scene);
camera.attachControl(canvas, true);
const light = new BABYLON.HemisphericLight("light", new BABYLON.Vector3(0, 1, 0), scene);

2. Importing a Model

For this example, we’ll load a GLTF model and apply mesh optimization:

js

Copy

Edit
BABYLON.SceneLoader.ImportMesh("", "https://models.babylonjs.com/", "DamagedHelmet.glb", scene, (meshes) => {
    console.log("Model loaded:", meshes);
});

3. Applying Mesh Optimization

Babylon.js has a built-in SimplificationQueue, which simplifies a mesh while keeping a good balance between quality and performance.

js

Copy

Edit
function optimizeMesh(mesh) {
    const simplifier = new BABYLON.SimplificationQueue();

    simplifier.addTask({
        quality: 0.5, // 50% reduction in mesh complexity
        mesh: mesh,
        successCallback: (simplifiedMesh) => {
            console.log("Mesh optimized:", simplifiedMesh);
        }
    });

    simplifier.execute();
}

// Apply optimization to all imported meshes
BABYLON.SceneLoader.ImportMesh("", "https://models.babylonjs.com/", "DamagedHelmet.glb", scene, (meshes) => {
    meshes.forEach(optimizeMesh);
});

Explanation:

  • quality: 0.5 → This reduces the mesh complexity by 50%. You can adjust this value from 0.1 (high reduction) to 1.0 (no change).
  • successCallback → This function runs when optimization is complete.
  • simplifier.execute() → Runs the optimization process.

4. Removing Unused Vertices

In some cases, models contain duplicate or unused vertices that increase file size and processing time. Babylon.js provides a simplify() method for further optimization.

js

Copy

Edit
meshes.forEach((mesh) => {
    mesh.optimizeIndices();
});

This will remove unnecessary indices, improving performance even further.

5. Mesh Decimation (Advanced Optimization)

If your scene has extremely high-poly models, you can aggressively reduce their polygon count using mesh decimation:

js

Copy

Edit
mesh.simplify([{ distance: 5, quality: 0.4 }], true, BABYLON.SimplificationType.QUADRATIC, () => {
    console.log("Mesh decimated");
});

This method reduces polygon count based on the distance from the camera, helping optimize performance dynamically in large scenes.

Performance Gains

Applying mesh optimization can drastically improve performance:

✔️ Reduced draw calls (faster rendering).

✔️ Lower memory usage (better for mobile devices).

✔️ Optimized physics calculations (faster collision detection).

Comparison Before & After Optimization

MetricBefore OptimizationAfter Optimization (50%)Vertex Count100,00050,000FPS (Mobile)20 FPS45 FPSLoad Time5s2s

As you can see, optimization dramatically improves performance, making your Babylon.js scenes run smoother!

Leave a comment

Your email address will not be published. Required fields are marked *