Create Mesh Async¶
If the mesh you’re creating is huge, you might want to create it asynchronously. In this example, we will create a simple mesh with a single quad. Let’s implement a mesh generator in a separate file:
// quad_mesh.das
require engine.gen_geometry.mesh_structures
[mesh_generator]
def generate_quad_mesh(width : float = 1., height : float = 1.) : MeshGeometry {
var vertices = [float3(0, 0, 0), float3(0, height, 0), float3(width, height, 0), float3(width, 0, 0)]
var normals = [float3(0, 0, -1), float3(0, 0, -1), float3(0, 0, -1), float3(0, 0, -1)]
var uvs = [float2(0, 0), float2(0, height), float2(width, height), float2(width, 0)]
var triangles = [uint3(0u, 1u, 2u), uint3(2u, 3u, 0u)]
return <- MeshGeometry(vertices <- vertices, normals <- normals, uv <- uvs, triangles <- triangles)
}
We require the engine.gen_geometry.mesh_structures module that contains MeshGeometry type and [mesh_generator] annotation.
Note that you must not require engine.core - the script will not compile, and it is not needed anyway.
The [mesh_generator] function annotation is necessary so the function can be found and correctly processed by the engine.
Only one function per file is allowed to have this annotation.
A module-level var of a generator, or of a module it requires, starts each run as declared (an array is empty), so a cache there lives for one run.
Inside the function, we define the vertices and triangles of the quad.
The vertices are defined by three arrays - positions (vertices), normal vectors (normals) and corresponding uv coordinates (uv).
The triangles are defined as an array of uint3, each containing the indices of the vertices that form a triangle.
All of these parameters are bundled into MeshGeometry struct and returned.
A generator may also return a csg model instead, see Constructive geometry in a generator.
Now let’s show how to use this generator in your game script:
// main.das
let mesh = generate_mesh("%file/quad_mesh.das", (height = 5.))
generate_mesh takes the path to the generator and a named tuple of parameters.
Note that you can skip including your generator (with require quad_mesh) - you need to just pass raw file path.
Default arguments are supported, so in this example the generator function will be called as generate_quad_mesh(1., 5.).
generate_mesh returns MeshId that will correspond to the generated mesh as soon as it is done.
Data formats in a generator¶
The ban on engine.core above does not rule out every engine module. A generator may also require
engine.format.json_core, engine.format.xml_core
and engine.format.compress_core, so it can build geometry directly
from data another program authored - a map from a tile editor, a level export, a description written
by your own tooling. Describe the format as a struct, parse it with from_json or from_xml,
and unpack it with decompress first if it arrives compressed:
// level_mesh.das
require engine.gen_geometry.mesh_structures
require engine.format.json_core
struct Block {
position : float3
size : float3
}
struct Level {
blocks : array<Block>
}
[mesh_generator]
def generate_level_mesh(exported : string) : MeshGeometry {
var level : Level
from_json(exported, level)
// build MeshGeometry from level.blocks
}
Pass the exported file’s contents as a parameter:
// main.das
let mesh = generate_mesh("%file/level_mesh.das", (exported = levelFileContents))
Constructive geometry in a generator¶
A generator may also require the geometry modules csg, surf, sdf and scene
and return a csg Solid or a scene Node instead of MeshGeometry.
The engine builds the model after the call:
// generators/plate_mesh.das
require csg
require engine.gen_geometry.mesh_structures
[mesh_generator]
def build(size : float = 2.0; hole : float = 0.3) : Solid {
return box(size, 0.2, size) - cylinder(hole, 1.0)
}
The result is one merged mesh with the default material: the nodes of a scene Node tree are joined.
A generator that requires one of these modules belongs in a generators/ folder: the game does not
have them, and the scripts of that folder are not auto-required into the game.
The functions of these modules and the rules that make a model build are in
Geometry modules.
Model generators¶
A mesh generator gives one mesh with one material. A model generator gives a whole model:
several meshes and materials, a tree of nodes and colliders. Mark its function with
[model_generator] and return a ModelGeometry:
// generators/crate.das
options gen2
require engine.gen_geometry.model_structures
require engine.primitives.cube_mesh_geometry
[model_generator]
def crate(size : float = 1.0) : ModelGeometry {
var model : ModelGeometry
var cube <- create_cube_mesh_geometry(size, size, size)
model.meshes |> emplace(cube)
model.materials |> push(ModelMaterial(name = "wood", color = float4(0.6, 0.4, 0.2, 1.0), roughness = 0.8))
var root = ModelNode(name = "crate")
root.parts |> push(ModelPart(mesh = 0, material = 0))
root.shapes |> push(convex_shape())
model.nodes |> emplace(root)
return <- model
}
The rules of a mesh generator apply: one annotated function per file, no engine.core,
default arguments. Put the generators in a generators/ folder: the scripts there are not
auto-required into the game, so a generator may require csg and the other geometry modules,
which the game program does not have.
A generator requires a helper beside it by its module name (require part_helper);
a game script requires a plain das helper from there by its path from the project root
(require generators.units).
generate_model returns a PrefabId at once. Instantiate it at once and keep the
NodeId: the node is empty now, and the model fills it when it is ready:
// main.das
var crate : NodeId
[export]
def on_initialize() {
crate = instantiate_prefab(generate_model("%file/generators/crate.das", (size = 2.0)),
NodeData(position = float3(0, 1, 0)))
}
The node keeps its NodeId. With no name in NodeData, it has the name of the generator file
in lower case (crate) until the model comes. The NodeData fields that you did not set then
take the values of the prefab root: the model root, or, when the model root has more than one part
left, an empty parent with the name of the model root at the origin, with no rotation and scale 1.
An instance keeps the prefab alive. With no instance, keep the returned id in a global variable:
the resource GC removes a prefab that nothing holds once its on_ready, if any, was called.
The game can add components and child nodes to the node before the model comes. They stay, and the nodes of the model come after them:
class Health : Component {
value : int = 100
}
[export]
def on_initialize() {
crate = instantiate_prefab(generate_model("%file/generators/crate.das"), NodeData(name = "crate"))
crate.add_component(new Health())
create_node(NodeData(name = "label", parent = crate))
// the model ready: Health stays, get_child(crate, 0) is still "label"
}
A Mesh or a Collider that the game added is the exception when the prefab root has one too:
it takes the mesh or the shapes and the fields of the prefab root.
on_ready is optional. It gets the prefab when the model is ready, and an instance made there is
complete at once. If the generation fails, it gets PrefabId(), the error is in the log and the
early instances stay empty:
generate_model("%file/generators/crate.das", (size = 2.0), @(prefab : PrefabId) {
if (prefab == PrefabId()) {
print("no crate: see the log")
return
}
crate = instantiate_prefab(prefab, NodeData(position = float3(0, 1, 0)))
})
generate_model(path, on_ready) calls the generator with the default values of all its
arguments.
In editor-driven calls (cheat and console command handlers, in-game ImGui callbacks, editor tools)
instantiate_prefab refuses the id until the model is ready, so instantiate it in on_ready:
[cheat]
def spawn_crate() {
generate_model("%file/generators/crate.das", @(prefab : PrefabId) {
if (prefab != PrefabId()) {
instantiate_prefab(prefab, NodeData(position = float3(0, 1, 0)))
}
})
}
Nodes. nodes[0] is the root, with parent = -1; the parent of every other node is an
earlier node. position, rotation and scale are relative to the parent. A node draws its
parts: each ModelPart names a mesh and a material (-1 for the default material).
Each part becomes a scene node of its own. The child nodes go under the first part, and a root
with several parts gets an empty parent. A part whose mesh has no triangles is left out and gives
no scene node: the first part left takes the children and the collider, and “several parts”
counts the parts left. A node with no parts left is an empty node: its primitive shapes stay on
it, and a mesh_shape() or convex_shape() is dropped with a warning.
Materials. A ModelMaterial is the standard_metallic_shader with color (sRGB, its
alpha is the opacity of a transparent material), metalness, roughness, twoSided and
transparent. Its name must be unique in the model. texture is the path of an albedo
texture asset, as request_texture takes it; color tints it. asset is the path of a
.material asset, which the parts use as is: of the other fields only name is used.
A texture or an asset that is not an asset of the project fails the generation.
Colliders. A node gets a collider only when you ask for one: push shapes into
ModelNode.shapes. An empty list gives no collider, and a node gets nothing from its parent.
The shapes are in the local space of the node. They have the names and the arguments of the
shapes of a Collider component: box_shape, sphere_shape, cylinder_shape and
capsule_shape, where axis is AxisDirection.XAxis, YAxis or ZAxis:
wheel.shapes |> push(cylinder_shape(radius = 0.3, height = 0.2, axis = AxisDirection.ZAxis))
mesh_shape() is a triangle mesh and convex_shape() a convex hull, made from all the meshes
of the node; a node has one of the two at most. Several shapes make one compound collider, and a
mesh_shape() can be one of them. The collider sits on the scene node of the first part left of
the node, or on the node itself when it has no parts left. A size, a radius or a height that is not
finite and positive fails the generation, and so do more shapes on a node than a Collider takes
(physJolt/maxShapesInCollider in the settings, 100 by default).
Lifetime. The meshes, materials and the prefab of a generated model exist only at runtime; they have no asset files. Generate the model when the game starts. A saved prefab does not keep an instance of a generated model: serializing one logs errors and leaves an empty node.
Edits while the game runs. Save or delete a generator file, or save, rename or delete a project file that it requires, while the game runs (in the editor, or in a player started on the project folder), and the engine runs the generator again for each live mesh and model that it made, with the same arguments. The game does not reload, and the ids stay:
[export]
def on_initialize() {
crate = instantiate_prefab(generate_model("%file/generators/crate.das"), NodeData(name = "crate"))
crate.add_component(new Health())
create_node(NodeData(name = "label", parent = crate))
}
// save generators/crate.das: on_initialize does not run again, crate keeps its NodeId,
// Health and "label"; the nodes of the old model go, the new ones come after "label"
A mesh keeps its MeshId, and its nodes draw the new mesh. A model keeps its PrefabId. The
Mesh and Collider of the instance node follow the new model: they change, or go when the
new model has none. A node that the game put under a node of the model goes with that node.
on_ready is not called again. When the new run fails, the engine logs the error, and the old
mesh or model stays; a model whose first generation failed fills its early instances once an edit
fixes the generator. A mesh that the game changed with update_mesh after its generation is not
generated again.
When a generator or a file that it requires is renamed or deleted, its meshes and models keep
their content and the engine logs an error; they are generated again when a file is back at that
path. A file that the game requires too (require generators.units) also
reloads the game when you save it, as any game script does.
CSG models¶
A model generator may also return a csg Solid or a scene Node. The engine builds the
model after the call and keeps the look of each face:
// generators/lamp.das
options gen2
require csg
require scene
require material
require engine.gen_geometry.model_structures
[model_generator]
def lamp(height : float = 1.5) : Node {
material(5, "steel").look("metallic")
let base = node("base", box(1.0, 0.2, 1.0).rgb(0.2, 0.2, 0.2)).collider(mesh_shape())
base.child("pole", cylinder(0.05, height).at(0.0, 0.1 + height * 0.5, 0.0).mat(5), pivot(float3(0.0, 0.1, 0.0)))
return base
}
A Solid gives one model node, named after the generator file. A scene Node tree gives
a model node for each scene node, with its local transform; return the root of the tree.
The modules csg, scene, material, sdf and surf are described in
Geometry modules.
The model has one material for each material id or material row with each of its face colors, and each model node gets one mesh for each material of its faces. The material id of a face with no material row picks the look:
Id |
Look |
Material |
|---|---|---|
0 |
paint |
the face color, roughness 0.35 |
1 |
chrome |
metal, its own color, roughness 0.05 |
2 |
matte |
the face color, roughness 0.9 |
3 |
glass |
the face color, roughness 0.05, transparent and two-sided |
4 |
metallic |
metal, the face color, roughness 0.35 |
An id past these with no material row is shaded as paint. A face whose id has a material row takes
the row’s look instead: its .look(name), or the look that the row’s name names, or paint.
A material with no row is named after its look and its face color in sRGB at 5 bits per channel:
paint_ff7b00, matte_ff7b00; chrome has no color in its name. An id past the five looks
with no row is named mat<id> and its color: mat9_e6e6e6. A material of a row has the row’s
name, and also the color when the faces of the row have several colors. A name that is already
taken gets a numeric suffix. The default face color 0.8
gives e6e6e6.
A row of the material module, material(id, name), gives the faces of its id
the row’s name, its .look(name) (one of the five looks), its .diffuse(r, g, b), which
scales the face color, .two_sided(), and the albedo texture (.tex(path)) when it is
an asset of the project. A row whose faces have more than one color gets a material for each
color, with the color in its name (hull_ff7b00).
A model has 64 materials at most. Past that, a further color of a kept row or look takes the nearest kept color of it, the faces of a row or look that is not kept take the first material, and a warning tells how many. A result with more than 500000 triangles fails the generation.
Colliders are explicit here too: call .collider(shape) on a scene node, with the shapes of
ModelNode.shapes. The shape is in the pivot frame of the node:
body.child("wheel", wheel_solid(), pivot_y(axle, float3(0.0, 0.0, 1.0))).collider(cylinder_shape(radius = 0.3, height = 0.2))
Each call adds a shape to one compound collider. A node with no call gets no collider, and a
Solid has none. A shape that the physics cannot take, or a second mesh_shape() or
convex_shape() on a node, fails the generation with an error at the line of the call.