# Create 3D assets

URL: https://briq.cloud/docs/guides/create-3d-assets

> Create meshes, rendered previews and dimensioned CAD parts in a sandbox with Blender, FreeCAD, CadQuery and OpenSCAD.

Recipe:

- [3D sandbox](https://briq.cloud/cookbook/3d-sandbox.md): Blender, FreeCAD, CadQuery and OpenSCAD for creating 3D assets with scripts. Run Blender Python with briq_exec for meshes, materials, GLB and CPU renders; cad-python for dimensioned CAD and STEP/STL; freecad-python for FreeCAD documents; openscad for .scad models. Files stay in /work. CPU only; AutoCAD and native DWG tools are not included.

Create a model with a script, inspect its geometry and preview, then download the source and exports.
Use the [3D sandbox recipe](https://briq.cloud/cookbook/3d-sandbox).

```text
briq_run({ recipe: "3d-sandbox", name: "assets", volume: { gb: 10 } })
```

1. Write scripts and inputs under `/work` with `briq_files_put` or the run's `files` field.
2. Execute the script with `briq_exec`. Use `async: true` for rendering and long geometry operations.
3. Inspect a rendered preview and geometry checks. Keep source files alongside exports.
4. Download outputs. Stop the sandbox when finished; destroy it after saving the files you need.

## Choose a tool

| Task                                 | Tool           | Run                                                                                                      | Deliver                       |
| ------------------------------------ | -------------- | -------------------------------------------------------------------------------------------------------- | ----------------------------- |
| Meshes, materials, scenes, animation | Blender Python | `blender --background --factory-startup --disable-autoexec --python-exit-code 1 --python /work/model.py` | `.blend`, GLB, PNG            |
| Dimensioned parts                    | CadQuery       | `cad-python /work/part.py`                                                                               | Python source, STEP, STL      |
| FreeCAD documents and solid geometry | FreeCAD        | `freecad-python /work/part.py`                                                                           | Python source, `.FCStd`, STEP |
| Constructive solid geometry          | OpenSCAD       | `openscad -o /work/part.stl /work/part.scad`                                                             | `.scad`, STL                  |
| Mesh inspection                      | trimesh        | `cad-python /work/check.py`                                                                              | JSON measurements             |
| Drawing interchange                  | ezdxf          | `cad-python /work/drawing.py`                                                                            | DXF                           |

`cad-python` has CadQuery, trimesh, ezdxf, NumPy and Pillow.
Blender and FreeCAD use their own Python environments.
Run `sandbox-versions` to see installed versions.

## A Blender asset and preview

Save this as `/work/model.py`:

```python
from pathlib import Path
import bpy
from mathutils import Vector

out = Path('/work/output')
out.mkdir(parents=True, exist_ok=True)
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
bpy.ops.mesh.primitive_uv_sphere_add(segments=32, ring_count=16)
asset = bpy.context.object
asset.name = 'Asset'
bpy.ops.object.shade_smooth()
material = bpy.data.materials.new('Blue')
material.diffuse_color = (0.05, 0.3, 0.8, 1)
asset.data.materials.append(material)

bpy.ops.object.camera_add(location=(4, -4, 3))
camera = bpy.context.object
camera.rotation_euler = (
    Vector((0, 0, 0)) - camera.location
).to_track_quat('-Z', 'Y').to_euler()
scene = bpy.context.scene
scene.camera = camera
bpy.ops.object.light_add(type='AREA', location=(2, -3, 5))
bpy.context.object.data.energy = 500
bpy.context.object.data.shape = 'DISK'
bpy.context.object.data.size = 4
scene.render.engine = 'CYCLES'
scene.cycles.device = 'CPU'
scene.cycles.samples = 16
scene.render.resolution_x = 512
scene.render.resolution_y = 512
scene.render.resolution_percentage = 100
scene.render.image_settings.file_format = 'PNG'
scene.render.filepath = str(out / 'preview.png')

bpy.ops.object.select_all(action='DESELECT')
asset.select_set(True)
bpy.ops.export_scene.gltf(
    filepath=str(out / 'asset.glb'),
    export_format='GLB',
    use_selection=True,
)
bpy.ops.wm.save_as_mainfile(filepath=str(out / 'asset.blend'))
bpy.ops.render.render(write_still=True)
```

```text
briq_exec({
  briq: "bq_…",
  cmd: ["blender", "--background", "--factory-startup", "--disable-autoexec", "--python-exit-code", "1", "--python", "/work/model.py"],
  async: true
})
→ exec id
briq_exec_result({ briq: "bq_…", exec: "<exec id>" })
```

Keep the exec id. Read that job until it finishes; a status timeout does not stop the render.
Inspect `/work/output/preview.png` before accepting the asset.
`--python-exit-code 1` reports script exceptions as failures.

## A dimensioned CAD part

Save this as `/work/part.py`:

```python
from pathlib import Path
import cadquery as cq

out = Path('/work/output')
out.mkdir(parents=True, exist_ok=True)
# Dimensions in millimeters: 60 x 40 x 6, with an 8 mm through-hole.
part = cq.Workplane('XY').box(60, 40, 6).faces('>Z').workplane().hole(8)
assert part.val().isValid()
bounds = part.val().BoundingBox()
assert abs(bounds.xlen - 60) < 1e-6
assert abs(bounds.ylen - 40) < 1e-6
assert abs(bounds.zlen - 6) < 1e-6
cq.exporters.export(part, str(out / 'plate.step'))
cq.exporters.export(part, str(out / 'plate.stl'))
```

```text
briq_exec({ briq: "bq_…", cmd: ["cad-python", "/work/part.py"], async: true })
```

Keep the Python source for parameter edits. STEP transfers solid geometry; STL stores a mesh.
Record the units alongside STL files.

## Inspect the mesh

Save this as `/work/check.py`, then run it with `cad-python`:

```python
import json
import numpy as np
import trimesh

mesh = trimesh.load('/work/output/plate.stl', force='mesh')
assert mesh.is_watertight, 'mesh has open edges'
assert mesh.is_winding_consistent, 'mesh has inconsistent winding'
assert np.allclose(mesh.extents, [60, 40, 6], atol=0.01)
print(json.dumps({
    'units': 'mm',
    'dimensions': mesh.extents.tolist(),
    'triangles': len(mesh.faces),
    'watertight': bool(mesh.is_watertight),
}))
```

These checks cover bounds and topology. Review the shape, orientation and intended clearances separately.

## FreeCAD and OpenSCAD

A headless FreeCAD script uses geometry modules:

```python
import FreeCAD as App
import Part

doc = App.newDocument('Part')
obj = doc.addObject('PartDesign::Feature', 'Block')
obj.Shape = Part.makeBox(60, 40, 6)
doc.recompute()
assert obj.Shape.isValid()
doc.saveAs('/work/block.FCStd')
Part.export([obj], '/work/block.step')
```

Run it with `freecad-python /work/freecad_part.py`.
GUI workbenches and `FreeCADGui` need a desktop environment.

An OpenSCAD source file, `/work/part.scad`:

```scad
difference() {
  cube([60, 40, 6], center=true);
  cylinder(h=8, d=8, center=true, $fn=64);
}
```

Run `openscad -o /work/part.stl /work/part.scad` with `briq_exec`.

## Download the files

For a small preview:

```text
briq_files_get({ briq: "bq_…", path: "/work/output/preview.png" })
```

MCP file transfers accept 1 MB per file. For larger exports, use the CLI:

```bash
briq files-get bq_… /work/output/asset.blend --out asset.blend
briq files-get bq_… /work/output/asset.glb --out asset.glb
briq files-get bq_… /work/output/plate.step --out plate.step
```

Check `maxFileBytes` with `briq_quota` for the environment's streaming limit.
For larger artifacts, upload from the sandbox to your artifact storage.
See [CLI](https://briq.cloud/docs/cli) and [Secrets](https://briq.cloud/docs/concepts/secrets).

## When it does not start

* **`No module named bpy`**: run the script through `blender --python`, not `python`.
* **`No module named cadquery`**: use `cad-python`. Its environment is separate from the default Python.
* **`No module named FreeCAD`**: use `freecad-python`, which loads the packaged FreeCAD libraries.
* **A GPU or display error**: use CPU Cycles for renders. The sandbox has no GPU or desktop session.
* **The model exceeds available memory**: reduce subdivision, texture resolution or render samples; use a larger `size` when needed.

## Good to know

* `small` suits simple models. Use `medium` or `large` for detailed geometry and CPU rendering.
* `/work` survives sleep. A fork copies it; destroying the sandbox deletes it.
* AutoCAD is not supported on Linux. Native AutoCAD and DWG conversion are not in this image.
* Autodesk's [Automation API](https://aps.autodesk.com/automation-apis) can run AutoCAD scripts through a separate cloud integration.
* The image source and build instructions live in [briq-cloud/sandbox](https://github.com/briq-cloud/sandbox).
