Create Your Custom Mesh

Occasionally, you may want to create your own mesh. In this example, we will create a simple mesh with a single quad. Let’s first show the code and then explain it:

require engine.gen_geometry.mesh_structures

def create_quad_mesh() : MeshId {
    var vertices = [float3(0, 0, 0), float3(0, 1, 0), float3(1, 1, 0), float3(1, 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, 1), float2(1, 1), float2(1, 0)]

    // two-sided quad
    var triangles = [uint3(0u, 1u, 2u), uint3(2u, 3u, 0u), uint3(0u, 2u, 1u), uint3(2u, 0u, 3u)]

    return create_mesh(MeshGeometry(vertices <- vertices, normals <- normals, uv <- uvs, triangles <- triangles))
}

First, we require the module that contains all the types and functions we need. Then, we define a function that generates a quad mesh. Inside the function, we define the vertices and triangles of the quad. It’s a two-sided quad, so you can use only half of the triangles if you want a single-sided quad. The vertices are defined as an array of Vertex objects, where each Vertex object contains the position, normal, and texture coordinate of a vertex. The triangles are defined as an array of uint3 objects, where each uint3 object contains the indices of the vertices that form a triangle. In any mesh you create, you need to define the vertices and indices that make up the mesh. Finally, we create a MeshData object with the generated vertices and indices and pass it to the create_mesh function.

Now let’s show how to generate this mesh in your game script:

let mesh = create_quad_mesh()
let node = create_node()
add_component(node, new Mesh(meshId = mesh))