Cascade Studio Documentation

repository·master·Indexed 23 days ago

https://github.com/zalo/cascadestudio

A browser-based, live-scripted CAD IDE and kernel leveraging OpenCASCADE (OCCT 8.0). It allows developers to create, visualize, and export 3D models using JavaScript or OpenSCAD. The project includes the `cascade-core` npm package for embedding the headless CAD modeling engine into web applications, featuring a comprehensive standard library for primitives, sketching, booleans, and geometric measurements.

Tokens
11.4K
Snippets
18
Records
61
Agent score
78%

What's inside Cascade Studio

  1. Overview of Cascade Studio

    master

    Cascade Studio is a full live-scripted CAD kernel and IDE running in the browser. It allows users to create 3D models using code (JavaScript or OpenSCAD) with features ranging from simple primitives and CSG to complex operations like revolves, sweeps, and fillets. It exposes the full power of the OpenCASCADE (OCCT 8.0) kernel while providing a concise standard library for ease of use.

    Key Capabilities:

    • Modeling: Use a powerful standard library for primitives, booleans, sweeps, lofts, fillets, etc.
    • Sketching: A Sketch API for drawing in XY, XZ, or YZ planes.
    • Selection: A Selector API to query specific edges and faces.
    • Measurement: Built-in functions for Volume(), SurfaceArea(), and CenterOfMass().
    • Dual Modes: Switch between JavaScript and OpenSCAD editors.
    • Interoperability: Import .STEP/.IGES/.STL files and export to .STEP/.STL/.OBJ.
    • Extensibility: Use the cascade-core npm package to embed the CAD engine in your own web applications.
  2. Core Modeling APIs and Concepts

    master

    Cascade Studio provides several specialized APIs for programmatic 3D modeling:

    Sketch API

    Allows drawing sketches on specific planes. You can specify the plane using a parameter like new Sketch([x,y], 'XZ') to draw in the XZ plane.

    Selector API

    Used for querying specific geometric entities like edges and faces within a shape. For example, you can find indices of faces that are parallel to a specific vector and have a maximum value in a certain direction: Edges(shape).parallel([0,0,1]).max([0,0,1]).indices()

    Measurement Functions

    Provides geometric analysis for shapes:

    • Volume(): Returns the volume of the shape.
    • SurfaceArea(): Returns the surface area.
    • CenterOfMass(): Returns the center of mass.

    OpenCASCADE Access

    For advanced users, the full OpenCASCADE kernel is accessible via the oc. namespace.

  3. Quick Start: Install and Run Cascade Studio

    master

    To set up the Cascade Studio development environment and run the browser-based IDE locally, follow these steps:

    1. Install dependencies.
    2. Build the project (this builds cascade-core first, then cascade-studio).
    3. Serve the built distribution using a local HTTP server.

    After running these commands, open http://localhost:8080 in your browser.

    npm install
    npm run build
    npx http-server ./packages/cascade-studio/dist -p 8080 -c-1
  4. Quick Start with CascadeEngine

    master

    To use cascade-core, initialize a CascadeEngine with the path to your worker file, initialize it, and then evaluate CAD code. The engine returns mesh data that can be rendered using WebGL frameworks like Three.js or Babylon.js.

    Important: You must copy cascade-worker.js, cascadestudio.wasm, and the fonts/ directory from node_modules/cascade-core/dist/ to your project's static assets directory for the engine to function.

    import { CascadeEngine } from 'cascade-core';
    
    const engine = new CascadeEngine({ workerUrl: './cascade-worker.js' });
    await engine.init();
    
    const result = await engine.evaluate(`
      let box = Box(20, 20, 20);
      FilletEdges(box, 3, Edges(box).max([0,0,1]).indices());
    `, { guiState: { 'Cache?': true } });
    
    // result.meshData = { faces: [...], edges: [...] }
    // Render with Three.js, Babylon.js, or any WebGL framework
  5. Use cascade-core in your own project

    master

    The cascade-core package provides the CAD engine as a standalone library without GUI dependencies. It is designed to be used in your own applications (e.g., rendering with Three.js or Babylon.js).

    To use it, instantiate CascadeEngine, initialize it, and use engine.evaluate() to run CAD code. The result contains meshData (faces and edges) which can be passed to a WebGL framework.

    import { CascadeEngine } from 'cascade-core';
    
    const engine = new CascadeEngine({ workerUrl: './cascade-worker.js' });
    await engine.init();
    
    const result = await engine.evaluate(`
      let box = Box(20, 20, 20);
      FilletEdges(box, 3, Edges(box).max([0,0,1]).indices());
    `, { guiState: { 'Cache?': true } });
    
    // result.meshData = { faces: [...], edges: [...] }
  6. Run Playwright tests

    master

    The repository includes a Playwright test suite that covers primitives, transforms, booleans, operations, selectors, OpenSCAD, and exports.

    Note: WebGL rendering in headless mode requires specific flags (--use-gl=angle --use-angle=swiftshader) which are pre-configured in playwright.config.js.

    npm run build
    npx playwright test
  7. Manage scene shapes and external imports

    master

    The CAD engine uses two global variables to manage objects for rendering:

    • sceneShapes: An array of oc.TopoDS_Shape objects that are rendered in the view. When creating new shapes or importing files, you must push them to this array to make them visible.
    • externalShapes: A dictionary storing imported STEP and IGES files, keyed by their filename. To render an imported file, push it from this dictionary into sceneShapes.

    Example of rendering an imported STEP file:

    sceneShapes.push(externalShapes['myStep.step']);
  8. Understand the CascadeStudioWorker lifecycle and message handling

    master

    The CascadeStudioWorker is the main entry point for the CAD engine running in a background Web Worker. It orchestrates the OpenCascade WASM environment, manages the modeling history, and handles the evaluation of user CAD code.

    Core Responsibilities

    • Initialization: Loads opencascade.js, opentype.js, and potpack, and initializes the OpenCascade WebAssembly module.
    • Code Evaluation: Uses eval() to execute user-provided CAD code within a controlled environment, populating self.sceneShapes and maintaining a modelHistory.
    • Rendering Pipeline: Combines shapes into a TopoDS_Compound and uses ShapeToMesh to triangulate faces and edges for 3D viewport rendering.
    • Console Forwarding: Overrides console.log and console.error to forward messages from the worker thread to the main thread via postMessage.

    Message Handlers

    The worker responds to specific message types via self.messageHandlers:

    • Evaluate: Executes user code. Expects a payload containing code and GUIState.
    • combineAndRenderShapes: Aggregates all shapes in sceneShapes into a single mesh for rendering. Expects maxDeviation and sceneOptions in the payload.
    • meshHistoryStep: Reconstructs and meshes a specific step from the modeling history (used for timeline scrubbing). Expects stepIndex and maxDeviation in the payload.
  9. How the modeling history timeline works

    master

    The modeling history timeline is a visual representation of the CAD operations performed. It allows users to 'scrub' through time to see intermediate states of the model.

    Key Concepts:

    • Steps: Each step in the timeline represents a single function call in the script. The timeline uses an iconMap to display specific icons (e.g., for Sphere, for Union) based on the fnName provided in the metadata.
    • Scrubbing: Users can click and drag across the timeline track to move between steps.
    • Lazy Triangulation: To save memory, intermediate steps are not kept as full meshes. When a user scrubs to a history step, the environment requests the specific mesh data for that step from the engine via app.engine.meshHistoryStep(stepIndex, meshRes).
    • Caching: Once a history step is triangulated, it is cached in _historyMeshCache to make subsequent scrubs to that step instantaneous.