Quick Start with BabylonJS
Get up and running with Bitbybit and BabylonJS in under 2 minutes!
Fastest Way: Use NPX Scaffolding
npx @bitbybit-dev/create-app my-project --engine babylonjs
cd my-project
npm install
npm run dev
This creates a complete project with Vite, TypeScript, and all three CAD kernels (OCCT, JSCAD, Manifold) pre-configured.
Check out the Getting Started with BabylonJS page for an overview of all integration approaches including visual editors and runners.
Manual Setup (Alternative)
If you prefer to set up the project manually or integrate into an existing project, follow these steps.
The @bitbybit-dev/babylonjs package conveniently includes @babylonjs/core as a dependency, so you don't need to install it separately.
Prerequisites
- Node.js and npm (or yarn) installed.
- A basic understanding of TypeScript and BabylonJS.
Example on Bitbybit Github Repo
1. Project Setup with Vite
First, create a new Vite project with a TypeScript template:
npm create vite@latest my-bitbybit-babylonjs-app -- --template vanilla-ts
# or: yarn create vite my-bitbybit-babylonjs-app --template vanilla-ts
cd my-bitbybit-babylonjs-app
Next, install the Bitbybit BabylonJS package:
npm install @bitbybit-dev/babylonjs
# or: yarn add @bitbybit-dev/babylonjs
@bitbybit-dev/babylonjs: The main library for integrating Bitbybit with BabylonJS. It also installs these main packages listed below.@babylonjs/core: Provides the main 3D engine to be used with this demo.@bitbybit-dev/core: Collects all kernel web worker libraries into a coherent Bitbybit base. It also includes some higher-level functionality.@bitbybit-dev/occt-worker: Provides the OpenCascade (OCCT) geometry kernel running in a Web Worker.@bitbybit-dev/jscad-worker: Provides the JSCAD geometry kernel running in a Web Worker.@bitbybit-dev/manifold-worker: Provides the Manifold geometry kernel running in a Web Worker.@bitbybit-dev/occt: Communicates with the OCCT worker and contains the main logic of the OCCT geometry kernel. It can also be used in non-web-worker environments.@bitbybit-dev/jscad: Communicates with the JSCAD worker and contains the main logic of the JSCAD geometry kernel. It can also be used in non-web-worker environments.@bitbybit-dev/manifold: Communicates with the Manifold worker and contains the main logic of the Manifold geometry kernel. It can also be used in non-web-worker environments.@bitbybit-dev/base: Contains base geometry types and functions, such as vector operations, matrix transformations, math, and list helpers, usable across all kernels.
2. HTML Structure
Modify your index.html file in the project root to include a <canvas> element where the BabylonJS scene will be rendered:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Bitbybit & BabylonJS Example</title>
</head>
<body>
<canvas id="babylon-canvas"></canvas>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
This is a standard HTML setup. The key parts are:
<canvas id="babylon-canvas"></canvas>: This is where our 3D scene will be drawn.<script type="module" src="/src/main.ts"></script>: This loads our main TypeScript application logic.
3. Main Application Logic (main.ts)
Replace the content of src/main.ts with the following:
import './style.css'; // Basic styling
import {
BitByBitBase,
Inputs,
initBitByBit,
initBabylonJS,
type InitBitByBitOptions,
} from '@bitbybit-dev/babylonjs';
// --- 1. Main Application Entry Point ---
start();
async function start() {
// Initialize BabylonJS scene using Bitbybit's helper function
const sceneOptions = new Inputs.BabylonJSScene.InitBabylonJSDto();
sceneOptions.canvasId = 'babylon-canvas';
sceneOptions.sceneSize = 10;
sceneOptions.enableShadows = true;
sceneOptions.enableGround = true;
sceneOptions.groundColor = '#333333';
const { scene, engine } = initBabylonJS(sceneOptions);
// Create an instance of BitByBitBase for BabylonJS
const bitbybit = new BitByBitBase();
// --- 2. Configure and Initialize Kernels ---
// Users can control which kernels are loaded.
// The initBitByBit helper function handles all worker setup automatically
// by loading the kernels from CDN.
const options: InitBitByBitOptions = {
enableOCCT: true,
enableJSCAD: true,
enableManifold: true,
};
// Initialize Bitbybit with the selected kernels
await initBitByBit(scene, bitbybit, options);
// --- 3. Create Geometry with Active Kernels ---
if (options.enableOCCT) {
await createOCCTGeometry(bitbybit, '#ff0000'); // Red
}
if (options.enableManifold) {
await createManifoldGeometry(bitbybit, '#00ff00'); // Green
}
if (options.enableJSCAD) {
await createJSCADGeometry(bitbybit, '#0000ff'); // Blue
}
// Start the BabylonJS render loop
engine.runRenderLoop(() => {
if (scene.activeCamera) {
scene.render();
}
});
}
// --- 4. Geometry Creation Functions (Examples) ---
async function createOCCTGeometry(bitbybit: BitByBitBase, color: string) {
console.log('Creating OCCT geometry...');
const cubeOptions = new Inputs.OCCT.CubeDto();
cubeOptions.size = 2.5;
cubeOptions.center = [0, 1.25, 0];
const cube = await bitbybit.occt.shapes.solid.createCube(cubeOptions);
const filletOptions = new Inputs.OCCT.FilletDto<Inputs.OCCT.TopoDSShapePointer>();
filletOptions.shape = cube;
filletOptions.radius = 0.4;
const roundedCube = await bitbybit.occt.fillets.filletEdges(filletOptions);
const drawOptions = new Inputs.Draw.DrawOcctShapeOptions();
drawOptions.edgeWidth = 0.5;
drawOptions.faceColour = color;
drawOptions.drawVertices = true;
drawOptions.vertexSize = 0.05;
drawOptions.vertexColour = '#ffffff';
await bitbybit.draw.drawAnyAsync({
entity: roundedCube,
options: drawOptions,
});
console.log('OCCT geometry created and drawn.');
}
async function createManifoldGeometry(bitbybit: BitByBitBase, color: string) {
console.log('Creating Manifold geometry...');
const sphereOptions = new Inputs.Manifold.SphereDto();
sphereOptions.radius = 1.5;
sphereOptions.circularSegments = 32;
const sphere = await bitbybit.manifold.manifold.shapes.sphere(sphereOptions);
const cubeOptions = new Inputs.Manifold.CubeDto();
cubeOptions.size = 2.5;
const cube = await bitbybit.manifold.manifold.shapes.cube(cubeOptions);
const diffedShape = await bitbybit.manifold.manifold.booleans.differenceTwo({
manifold1: cube,
manifold2: sphere,
});
const translationOptions = new Inputs.Manifold.TranslateDto<Inputs.Manifold.ManifoldPointer>();
translationOptions.manifold = diffedShape;
translationOptions.vector = [0, 1.25, -4]; // Position below OCCT
const movedShape = await bitbybit.manifold.manifold.transforms.translate(
translationOptions
);
const drawOptions = new Inputs.Draw.DrawManifoldOrCrossSectionOptions();
drawOptions.faceColour = color;
await bitbybit.draw.drawAnyAsync({
entity: movedShape,
options: drawOptions,
});
console.log('Manifold geometry created and drawn.');
}
async function createJSCADGeometry(bitbybit: BitByBitBase, color: string) {
console.log('Creating JSCAD geometry...');
const geodesicSphereOptions = new Inputs.JSCAD.GeodesicSphereDto();
geodesicSphereOptions.radius = 1.5;
geodesicSphereOptions.center = [0, 1.5, 4]; // Position above OCCT
const geodesicSphere = await bitbybit.jscad.shapes.geodesicSphere(
geodesicSphereOptions
);
const sphereOptions = new Inputs.JSCAD.SphereDto();
sphereOptions.radius = 1;
sphereOptions.center = [0, 3, 4.5];
const simpleSphere = await bitbybit.jscad.shapes.sphere(sphereOptions);
const unionOptions = new Inputs.JSCAD.BooleanTwoObjectsDto();
unionOptions.first = geodesicSphere;
unionOptions.second = simpleSphere;
const unionShape = await bitbybit.jscad.booleans.unionTwo(unionOptions);
const drawOptions = new Inputs.Draw.DrawBasicGeometryOptions();
drawOptions.colours = color;
await bitbybit.draw.drawAnyAsync({
entity: unionShape,
options: drawOptions,
});
console.log('JSCAD geometry created and drawn.');
}
Explanation of main.ts:
-
Imports:
BitByBitBase,Inputs,initBitByBit,initBabylonJS, andInitBitByBitOptions: Core components from@bitbybit-dev/babylonjs.Inputsprovides DTOs (Data Transfer Objects) for specifying parameters for geometry operations and scene configuration.initBitByBitis the helper function that handles all kernel initialization automatically,initBabylonJSsets up the BabylonJS scene, andInitBitByBitOptionsis the type for kernel configuration options.
-
start()function (Main Entry Point):- Uses
Inputs.BabylonJSScene.InitBabylonJSDto()to configure scene options like canvas ID, scene size, shadows, and ground settings. - Calls
initBabylonJS(sceneOptions)to set up the complete BabylonJS environment (engine, scene, camera, lights) with a single function call. - Creates an instance of
BitByBitBasefrom the@bitbybit-dev/babylonjspackage. options: This object is key. By settingenableOCCT,enableJSCAD, andenableManifoldtotrueorfalse, you control which kernels Bitbybit attempts to initialize. This allows for optimizing load times and resource usage if not all kernels are needed.initBitByBit(): This helper function handles all the complexity of initializing Bitbybit with the selected kernels. It automatically creates web workers, loads kernel WASM files from CDN, and waits for all selected kernels to be ready. You simply pass the scene, the bitbybit instance, and your options.- Conditionally calls geometry creation functions (
createOCCTGeometry,createManifoldGeometry,createJSCADGeometry) based on which kernels were enabled. - Starts the BabylonJS render loop using
engine.runRenderLoop(...).
- Uses
-
Geometry Creation Functions (
createOCCTGeometry,createManifoldGeometry,createJSCADGeometry):- These are example functions illustrating how to use Bitbybit's core geometry API (e.g.,
bitbybit.occt.*,bitbybit.manifold.*,bitbybit.jscad.*). InputsDTOs: You'll notice the use ofInputs.OCCT.CubeDto(),Inputs.Manifold.SphereDto(), etc. These objects are used to pass parameters to Bitbybit's geometry creation and modification functions. They provide type safety and often mirror the inputs you'd find in a visual programming environment. Intellisense (auto-completion in your IDE) will be very helpful here.- Drawing: After creating a geometric entity,
bitbybit.draw.drawAnyAsync()(from@bitbybit-dev/babylonjs) is used to render it into the BabylonJS scene. Different kernels might have slightly different drawing option DTOs (e.g.,DrawOcctShapeOptions,DrawManifoldOrCrossSectionOptions,DrawBasicGeometryOptions), butdrawAnyAsynchandles many common cases. The OCCT draw options now support additional properties likeedgeWidth,drawVertices,vertexSize, andvertexColour.
- These are example functions illustrating how to use Bitbybit's core geometry API (e.g.,
4. Basic Styling (Optional)
Create an src/style.css file if you haven't already:
body {
margin: 0;
overflow: hidden; /* Prevent scrollbars from canvas */
background-color: #1a1c1f; /* Match canvas background for seamless look */
}
#babylon-canvas {
display: block;
width: 100vw;
height: 100vh;
touch-action: none; /* Recommended for BabylonJS pointer events */
}
5. Running the Application
npm run dev
# or: yarn dev
Vite will start a development server. You should see a browser window open with your BabylonJS scene. If all kernels were enabled, you'll see three distinct shapes:
- A red, filleted cube (OCCT) at the origin.
- A green, subtracted shape (Manifold) positioned below the OCCT shape.
- A blue, unioned sphere shape (JSCAD) positioned above the OCCT shape.
Check your browser's developer console for logs indicating the initialization status of each kernel and any errors.
Live Demo (StackBlitz)
You can explore and interact with a live example of this setup on StackBlitz.
Key Takeaways
- Vite Simplifies Setup: Vite handles module resolution effectively for a smooth development experience.
initBitByBit()for Easy Initialization: TheinitBitByBit()helper function handles all the complexity of creating web workers and loading kernel WASM files from CDN. You simply configure which kernels to enable. If you need to host assets on your own infrastructure, see Self-Hosting Assets.InitBitByBitOptionsfor Control: You have fine-grained control over which geometry kernels are loaded, allowing you to tailor the application to specific needs and optimize performance.- Asynchronous Operations: Most Bitbybit operations are
asyncbecause they communicate with Web Workers, ensuring the main thread remains responsive. InputsDTOs: Use these typed objects to configure geometry operations, promoting code clarity and type safety.- Modular Design: The
@bitbybit-dev/babylonjspackage seamlessly integrates Bitbybit's powerful geometry kernels and functionalities with your BabylonJS applications.
This setup provides a robust foundation for building sophisticated 3D CAD applications in the browser with Bitbybit and BabylonJS.
