Forum Discussion

🚨 This forum is archived and read-only. To submit a forum post, please visit our new Developer Forum. 🚨
waynecochran's avatar
1 year ago
Solved

Creating a mesh programatically

Given an array of vertices, normals, texture coordinates, and a triangle index list, how do I create a mesh that that I can load into an ECS Entity? 
  • dav-s's avatar
    1 year ago

    Hi!

    There are a couple of different pieces of this, so I will break them down in two parts.

    Creating a custom SceneMesh

    The SceneMesh is the actual object that represents the geometry that we are rendering. It is usually managed for you when interacting with the ECS but behind the scenes, we are creating SceneMeshes and SceneObjects in Systems.

    If you just want to create the mesh, you can use SceneMesh.meshWithMaterials(). This let's you set the positions, normals, UVs, vertex colors, indices, material ranges, and SceneMaterials as arrays.

    Alternatively, you can create a SceneMesh using our TriangleMesh API (which is used in our Media Player Sample: https://github.com/meta-quest/Meta-Spatial-SDK-Samples/blob/1931b9d04f2e4979f005316127c39e926e44a1fe/MediaPlayerSample/app/src/main/java/com/meta/spatial/samples/mediaplayersample/MediaPlayerSampleActivity.kt#L316). This has a very similar API with meshWithMaterials() but is a little more verbose.

    Attaching the SceneMesh to ECS

    Once we know how to create a SceneMesh, there are a number of ways to add it to our ECS. 
    One of the more simple ways is to use mesh creators. These allow you to create your mesh on-demand when you add a Mesh component to your entity with a matching "mesh://..." URI. For example, in your case, you can register a mesh creator like this:
    // in the app's onCreate()
    registerMeshCreator("mesh://myCustomMesh") {
        SceneMesh.meshWithMaterials(...)
    }
    // later in your code, we create an instance of it
    val myEntity = Entity.create(Mesh(Uri.parse("mesh://myCustomMesh"))

    Alternatively, you can use the MeshManager.setMeshForEntityDirectly() although it is less recommended. Your code would look something like this:

    systemManager
       .findSystem<MeshCreationSystem>()
       .meshManager
       .setMeshForEntityDirectly(myEntity, mySceneMesh)

    Hope this helps!