Lesson 07-Babylon.js Basic Syntax and Usage

Getting Started with Babylon.js and Core Concepts

Introduction to Babylon.js

Babylon.js is a powerful, open-source 3D game and rendering engine designed for creating and displaying 3D content in web browsers. It leverages WebGL and WebGPU for efficient 3D rendering, enabling developers to build complex 3D applications, games, and animations.

Key Features

  • Open Source: Babylon.js is fully open-source, with all source code available on GitHub for modification.
  • Cross-Platform: Supports multiple platforms, including desktop browsers, mobile browsers, and some hybrid application frameworks.
  • Ease of Use: Offers a simple yet robust API, allowing developers to quickly get started and create 3D content.
  • Physics Engine: Includes a built-in physics engine supporting rigid body dynamics, collision detection, and more.
  • Rich Materials and Shaders: Supports various materials and shaders, including PBR (Physically Based Rendering), standard materials, and custom shaders.
  • Animation System: Supports skeletal animations, keyframe animations, path animations, and more.
  • Lighting and Shadows: Provides multiple light source types, shadow effects, and global illumination for advanced lighting.
  • Plugins and Extensions: Supports plugins and extensions to enhance functionality, such as particle systems and post-processing effects.
  • WebXR Support: Compatible with the WebXR standard, enabling virtual reality (VR) and augmented reality (AR) experiences.

Basic Application Example

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Babylon.js Example</title>
    <script src="https://cdn.babylonjs.com/babylon.js"></script>
</head>
<body>
    <canvas id="renderCanvas" style="width: 100%; height: 100%;"></canvas>
    <script>
        // Get canvas element
        const canvas = document.getElementById("renderCanvas");

        // Create Babylon engine
        const engine = new BABYLON.Engine(canvas, true);

        // Create scene function
        const createScene = () => {
            // Create a new scene
            const scene = new BABYLON.Scene(engine);

            // Create a camera
            const camera = new BABYLON.ArcRotateCamera("camera", Math.PI / 2, Math.PI / 2, 2, new BABYLON.Vector3(0, 0, 0), scene);
            camera.attachControl(canvas, true);

            // Create a light
            const light = new BABYLON.HemisphericLight("light", new BABYLON.Vector3(1, 1, 0), scene);

            // Create a sphere
            const sphere = BABYLON.MeshBuilder.CreateSphere("sphere", { diameter: 1 }, scene);

            return scene;
        };

        // Create scene
        const scene = createScene();

        // Run render loop
        engine.runRenderLoop(() => {
            scene.render();
        });

        // Handle window resize
        window.addEventListener("resize", () => {
            engine.resize();
        });
    </script>
</body>
</html>

Applications and Advantages

Application Scenarios

3D Game Development

  • Babylon.js provides comprehensive game development tools, including a physics engine, animation system, and particle system, suitable for various 3D game genres.
  • Supports complex game scenes and high-quality visuals for immersive gaming experiences.

Virtual Reality (VR) and Augmented Reality (AR)

  • Supports WebXR standards for creating VR and AR applications.
  • Ideal for virtual museums, exhibitions, shopping, education, and training.

Architecture and Interior Design

  • Offers robust 3D rendering for visualizing architectural models.
  • Suitable for architectural design, interior design, and real estate showcases.

Industrial and Product Visualization

  • Applicable to industrial design, product showcases, and mechanical simulations.
  • Provides detailed model rendering and interactivity for product demonstrations and training.

Education and Training

  • Enables rich 3D content creation for education and scientific visualization.
  • Suitable for teaching and training in physics, chemistry, biology, and more.

Data Visualization

  • Leverages powerful 3D rendering for three-dimensional data visualization.
  • Applicable to geographic information systems (GIS), scientific computing, and financial data.

Advertising and Marketing

  • Ideal for interactive ads, product showcases, and virtual try-ons.
  • Enhances user engagement with immersive experiences.

Advantages

Ease of Use

  • Provides a concise and powerful API for quick development of complex 3D content.
  • Comprehensive documentation and tutorials help developers address technical challenges.

High Performance

  • Highly optimized for efficient rendering across complex scenes.
  • Supports performance optimization techniques like instanced rendering and Level of Detail (LOD).

Cross-Platform Support

  • Compatible with desktop browsers, mobile browsers, and hybrid frameworks.
  • Ensures consistent user experiences across devices and operating systems.

Strong Community Support

  • Active community with forums, GitHub, and social media for assistance and knowledge sharing.
  • Community-contributed plugins and extensions enhance engine capabilities.

Comprehensive Features

  • Offers extensive 3D rendering features, including lighting, shadows, materials, and post-processing.
  • Built-in physics engine, animation system, and particle system for diverse applications.

Open Source and Free

  • Fully open-source with source code available on GitHub for modification.
  • Free to use for both individual developers and enterprise projects.

Official Documentation and Resource Navigation

Official Website and Documentation

Download and Installation

1. Visit the Babylon.js GitHub Repository

Start by visiting the Babylon.js GitHub page to download the latest version of the library:

2. Download the Latest Version

In the “Releases” section, locate the latest stable version. You’ll typically find files named babylon.js or babylon.min.js, which are the core Babylon.js library. Click the corresponding Download button.

3. Local Usage

Place the downloaded babylon.js or babylon.min.js file in your project folder, usually in the public or static directory, depending on your project structure.

4. Reference in HTML

In your HTML file, include the downloaded Babylon.js library using a <script> tag. For example, if the file is in the public directory:

<script src="path/to/babylon.min.js"></script>

Replace path/to/babylon.min.js with the actual file path.

5. Start Writing JavaScript

In your HTML file or an external JavaScript file, begin using the Babylon.js API to create 3D scenes. For example, create a simple 3D scene:

<script>
    var scene = new BABYLON.Scene(engine);
    // Other Babylon.js code...
</script>

6. Use a CDN

Alternatively, load Babylon.js via a Content Delivery Network (CDN) without downloading locally. For example, use the unpkg.com CDN:

<script src="https://cdn.jsdelivr.net/npm/babylonjs@latest/dist/babylon.min.js"></script>

7. Install via npm

If using Node.js and module bundlers (e.g., Webpack or Rollup), install Babylon.js via npm:

npm install babylonjs

Then import it in your JavaScript file:

import * as BABYLON from 'babylonjs';

Babylon.js Basic Syntax Knowledge

Babylon.js is a powerful 3D game engine that provides the foundational elements needed to create 3D scenes, including scenes, cameras, lights, 3D objects, basic geometries, materials, textures, animations, and a physics engine.

Scene

The scene is the core of the 3D world, containing all 3D objects, cameras, lights, and other elements. Here’s how to create a scene:

// Import Babylon.js library
import * as BABYLON from 'babylonjs';

// Create engine
const engine = new BABYLON.Engine(document.getElementById("renderCanvas"), true);

// Create scene
const scene = new BABYLON.Scene(engine);

Camera

Cameras define the viewpoint of the 3D world. Babylon.js offers various camera types, such as ArcRotateCamera and FreeCamera. Below is an example of an ArcRotateCamera:

// Create camera
const camera = new BABYLON.ArcRotateCamera("camera1",
    1, // alpha (rotation around Y-axis)
    1, // beta (rotation around X-axis)
    10, // radius (distance from target)
    new BABYLON.Vector3(0, 0, 0), // target (camera focus point)
    scene); // specify scene

// Set camera position
camera.setPosition(new BABYLON.Vector3(0, 5, -20));

// Set camera as the scene’s default
scene.activeCamera = camera;

Light

Lights add shadows and depth to a scene. Babylon.js supports various light types, including point lights, spotlights, and directional lights.

Point Light

// Create point light
const pointLight = new BABYLON.PointLight("pointLight",
    new BABYLON.Vector3(0, 10, 0), // light position
    scene); // specify scene

// Optional: Set light color and intensity
pointLight.color = new BABYLON.Color3(1, 1, 1); // white
pointLight.intensity = 1; // intensity

Spot Light

// Create spotlight
const spotLight = new BABYLON.SpotLight("spotLight",
    new BABYLON.Vector3(0, 10, 0), // light position
    new BABYLON.Vector3(0, -1, 0), // light direction
    scene); // specify scene

// Optional: Set light color, angle, and intensity
spotLight.color = new BABYLON.Color3(1, 1, 1); // white
spotLight.angle = Math.PI / 4; // beam angle
spotLight.intensity = 1; // intensity

Directional Light

// Create directional light
const directionalLight = new BABYLON.DirectionalLight("dirLight",
    new BABYLON.Vector3(-1, -1, -1), // light direction
    scene); // specify scene

// Optional: Set light color and intensity
directionalLight.color = new BABYLON.Color3(1, 1, 1); // white
directionalLight.intensity = 1; // intensity

3D Objects

Creating a 3D object involves the following steps:

  1. Create a geometry instance.
  2. Create a material instance.
  3. Create a Mesh object to combine the geometry and material.
  4. Add the Mesh to the scene.

Example: Creating a red sphere

// Create sphere geometry
const sphereGeometry = BABYLON.MeshBuilder.CreateSphere("sphere", { diameter: 2, segments: 32 }, scene);

// Create red material
const redMaterial = new BABYLON.StandardMaterial("redMat", scene);
redMaterial.diffuseColor = new BABYLON.Color3(1, 0, 0); // red

// Create sphere mesh
const sphereMesh = sphereGeometry; // MeshBuilder already creates the mesh
sphereMesh.material = redMaterial;

// Add sphere to scene with animation
scene.registerBeforeRender(() => {
    sphereMesh.position.y += 0.1; // rising animation
});

Basic Geometries

Box (Cube)

// Create box geometry
const boxSize = 2; // width, height, depth
const boxGeometry = BABYLON.MeshBuilder.CreateBox("box", { size: boxSize }, scene);

Sphere

// Create sphere geometry
const sphereRadius = 3;
const sphereSegments = 32; // subdivisions
const sphereGeometry = BABYLON.MeshBuilder.CreateSphere("sphere", { diameter: sphereRadius, segments: sphereSegments }, scene);

Cylinder

// Create cylinder geometry
const cylinderHeight = 5;
const cylinderDiameterTop = 2;
const cylinderDiameterBottom = 2;
const cylinderTessellation = 32; // number of segments
const cylinderGeometry = BABYLON.MeshBuilder.CreateCylinder("cylinder", { 
    height: cylinderHeight, 
    diameterTop: cylinderDiameterTop, 
    diameterBottom: cylinderDiameterBottom, 
    tessellation: cylinderTessellation 
}, scene);

Materials

Materials define the surface appearance of 3D objects. Babylon.js provides several material types, such as StandardMaterial and PBRMaterial.

Standard Material

// Create standard material
const standardMaterial = new BABYLON.StandardMaterial("standardMat", scene);

// Set colors
standardMaterial.diffuseColor = new BABYLON.Color3(1, 0, 0); // red
standardMaterial.specularColor = new BABYLON.Color3(1, 1, 1); // specular color
standardMaterial.emissiveColor = new BABYLON.Color3(0, 0, 0); // emissive color

// Apply material to geometry
boxGeometry.material = standardMaterial;

Texture (Textured Material)

Applying a texture to a standard material:

// Load texture
const texture = new BABYLON.Texture("./texture.jpg", scene);

// Apply texture to standard material
standardMaterial.diffuseTexture = texture;

PBR Material (Physically Based Rendering)

PBR materials offer realistic lighting effects, requiring parameters like metallic and roughness:

// Create PBR material
const pbrMaterial = new BABYLON.PBRMaterial("pbrMat", scene);

// Set base color and texture
pbrMaterial.albedoColor = new BABYLON.Color3(1, 1, 1);
pbrMaterial.albedoTexture = new BABYLON.Texture("path/to/albedoTexture.jpg", scene);

// Set metallic and roughness
pbrMaterial.metallic = 0.5;
pbrMaterial.roughness = 0.5;

// Apply to geometry
sphereGeometry.material = pbrMaterial;

Textures

Textures add detail and realism to 3D objects. Here’s an example of applying a texture:

// Load texture
const texture = new BABYLON.Texture("path/to/texture.jpg", scene);

// Apply texture to material
redMaterial.diffuseTexture = texture;

Animations

Babylon.js provides a robust animation system for animating 3D object properties. Here’s a simple rotation animation:

// Create rotation animation
const rotateAnim = new BABYLON.Animation(
    "rotate", 
    "rotation.y", 
    60, 
    BABYLON.Animation.ANIMATIONTYPE_FLOAT, 
    BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE
);
const keys = [
    { frame: 0, value: 0 },
    { frame: 100, value: Math.PI * 2 }
];
rotateAnim.setKeys(keys);

// Add animation to sphere
sphereMesh.animations = [rotateAnim];

// Start animation
scene.beginAnimation(sphereMesh, 0, 100, true);

Physics Engine

Babylon.js integrates Cannon.js and Oimo.js physics engines for collision detection and physical simulations. Below is an example of initializing physics and adding rigid bodies:

// Initialize physics engine
const physicsEngine = new BABYLON.CannonJSPlugin();
scene.enablePhysics(null, physicsEngine);

// Convert sphere to rigid body
sphereMesh.physicsImpostor = new BABYLON.PhysicsImpostor(
    sphereMesh, 
    BABYLON.PhysicsImpostor.SphereImpostor, 
    { mass: 1 }, 
    scene
);

// Add ground as static rigid body
const ground = BABYLON.MeshBuilder.CreatePlane("ground", { size: 100 }, scene);
ground.rotation.x = -Math.PI / 2; // make ground horizontal
ground.physicsImpostor = new BABYLON.PhysicsImpostor(
    ground, 
    BABYLON.PhysicsImpostor.PlaneImpostor, 
    { mass: 0 }, 
    scene
);

Babylon.js Advanced Materials and Post-Processing

Advanced Materials

Babylon.js offers a variety of advanced material options, each with specific use cases and properties that significantly enhance the visual expressiveness of a scene.

PBR Materials (Physically Based Rendering)

Anisotropic Material

Anisotropic materials simulate the varying light reflection of certain surfaces (e.g., metal or paint) in different directions.

const anisotropicMaterial = new BABYLON.PBRMaterial("anisotropicMat", scene);
anisotropicMaterial.albedoColor = new BABYLON.Color3(1, 0.5, 0.5);
anisotropicMaterial.metallic = 0.8;
anisotropicMaterial.roughness = 0.2;
anisotropicMaterial.anisotropy = 0.5;
ClearCoat Material

ClearCoat materials simulate a transparent coating effect, such as car paint.

const clearCoatMaterial = new BABYLON.PBRMaterial("clearCoatMat", scene);
clearCoatMaterial.albedoColor = new BABYLON.Color3(0.5, 0.5, 0.5);
clearCoatMaterial.metallic = 0.5;
clearCoatMaterial.roughness = 0.2;
clearCoatMaterial.clearcoat.intensity = 0.5;
clearCoatMaterial.clearcoat.roughness = 0.2;
Fur Material

Fur materials simulate fur or fuzzy effects, ideal for animals or grass.

const furMaterial = new BABYLON.FurMaterial("furMat", scene);
furMaterial.furColor = new BABYLON.Color3(0.5, 0.5, 0.5);
furMaterial.furLength = 0.1;
furMaterial.furAngle = 0;
furMaterial.furDensity = 1;
Grass Procedural Material

Procedurally generated grass effects, suitable for large-area coverage.

const grassProceduralMaterial = new BABYLON.GrassProceduralTexture("grassMat", 256, scene);
grassProceduralMaterial.grassBladeWidth = 0.1;
grassProceduralMaterial.grassBladeHeight = 1;
grassProceduralMaterial.randomizeFunction = BABYLON.GrassProceduralTexture.RandomizeFunction.Simplex;

Refraction Material

Refraction materials simulate the bending of light through transparent objects.

const refractionMaterial = new BABYLON.PBRMaterial("refractionMat", scene);
refractionMaterial.albedoColor = new BABYLON.Color3(0.5, 0.5, 0.5);
refractionMaterial.indexOfRefraction = 0.98;
Mirror Material

Mirror materials create reflective surfaces, such as mirrors or water.

const mirrorMaterial = new BABYLON.MirrorMaterial("mirrorMat", scene);
mirrorMaterial.mirrorPlane = new BABYLON.Plane(0, 1, 0, 0); // vertical mirror plane
mirrorMaterial.renderList = [sphere]; // list of objects to reflect

Post-Processing

Babylon.js’s post-processing allows you to apply effects to rendered frames, enhancing the visual quality of a scene. Examples include Bloom, Vignette Effect, and Color Grading.

Bloom Effect

Bloom highlights bright areas, creating a dreamy or glowing effect.

// Create Bloom effect
const bloomEffect = new BABYLON.BloomPostProcess("bloom", scene, 1.0, camera);
bloomEffect.threshold = 0.7;
bloomEffect.weight = 1.2;
bloomEffect.kernel = 64;

Vignette Effect

Vignette creates a gradual darkening at the image edges, mimicking old photo fading.

// Create Vignette post-process
const vignettePostProcess = new BABYLON.ImageProcessingPostProcess("vignette", 1.0, camera);
vignettePostProcess.vignetteEnabled = true;
vignettePostProcess.vignetteWeight = 0.8;
vignettePostProcess.vignetteColor = new BABYLON.Color4(0.5, 0.5, 0.5, 1);

Tone Mapping Effect

Tone mapping adjusts overall brightness and contrast to match human perception.

// Create Tone Mapping post-process
const toneMappingPostProcess = new BABYLON.TonemappingPostProcess("toneMapping", BABYLON.TonemappingOperator.Reinhard, 1.0, camera);

Depth of Field Effect

Depth of field simulates a camera’s focus, keeping the foreground sharp and blurring the background.

// Create Depth of Field post-process
const depthOfFieldPostProcess = new BABYLON.DepthOfFieldEffect({
    focalDistance: 10,
    lensSize: 1,
    fStop: 0.5,
}, scene, camera);

Outline Effect

Outline effects add contours to object edges, improving shape recognition.

// Create Outline post-process
const outlinePostProcess = new BABYLON.HighlightLayer("outline", scene);
outlinePostProcess.addMesh(sphere, new BABYLON.Color3(0, 0, 0));
outlinePostProcess.innerGlow = false;
outlinePostProcess.outerGlow = true;

Color Grading Effect

Color grading adjusts the overall tone and color balance of a scene.

// Create Color Grading post-process
const colorGradingPostProcess = new BABYLON.ColorGradingPostProcess("colorGrading", 1.0, camera);
colorGradingPostProcess.colorGradingTexture = new BABYLON.Texture("path/to/lut.png", scene);

Lens Flare Effect

Lens flare simulates camera lens glow under bright light.

// Create Lens Flare post-process
const lensFlareSystem = new BABYLON.LensFlareSystem("lensFlare", {
    emitter: new BABYLON.PointLight("light", new BABYLON.Vector3(0, 10, 0), scene)
}, scene);
lensFlareSystem.addFlare(new BABYLON.LensFlare(0.7, 0.5, new BABYLON.Color3(1, 1, 1), "path/to/flare1.png", lensFlareSystem));
lensFlareSystem.addFlare(new BABYLON.LensFlare(0.5, 0.3, new BABYLON.Color3(1, 0.5, 0), "path/to/flare2.png", lensFlareSystem));

Anti-Aliasing

Anti-aliasing reduces pixelation at image edges, improving quality.

// Use FXAA anti-aliasing
const fxaaPostProcess = new BABYLON.FXAAPostProcess("fxaa", 1.0, camera);

// Or use TAA anti-aliasing
const taaPostProcess = new BABYLON.TAARenderPass("taa", scene, camera);
taaPostProcess.timeStep = 0.01;

PostProcessPipeline (Custom Render Pipeline)

To combine multiple post-processing effects, create a custom render pipeline.

// Create custom render pipeline
const pipeline = new BABYLON.DefaultRenderingPipeline("customPipeline", true, scene, [camera]);
pipeline.bloomEnabled = true;
pipeline.bloomThreshold = 0.7;
pipeline.imageProcessingEnabled = true;
pipeline.imageProcessing.vignetteEnabled = true;
pipeline.imageProcessing.vignetteWeight = 0.8;

Dynamic Resolution

Dynamic resolution improves image quality without sacrificing performance.

// Create dynamic resolution post-process
const dynamicResPostProcess = new BABYLON.DynamicTexture("dynamicRes", { width: 512, height: 512 }, scene);
dynamicResPostProcess.scale = 2;
Share your love