For more context here is a minimal RealityKit view to reproduce the test setup.
var body: some View {
RealityView { content in
let material = SimpleMaterial(color: .systemPink, isMetallic: false)
let mesh = MeshResource.generateSphere(radius: 1)
// MeshResource.generateSphere creates a model with this name
let model0 = mesh.contents.instances["MeshModel-0"]
let modelName = model0!.model
// This implementation tries to create a new MeshResource vs MeshResource.replace()
var instances: [MeshResource.Instance] = []
let instanceCount = 20
for i in 1...instanceCount {
let translation: SIMD3<Float> = [Float.random(in: 0...1),
Float.random(in: 0...1),
Float.random(in: 0...1)]
// Nothing in the docuementation indicates what the id needs to be.
let instance = MeshResource.Instance(
id: "MeshModel-\(i)",
model: modelName,
at: Transform(
scale: [0.05, 0.05, 0.05],
translation: translation).matrix)
instances.append(instance)
}
var contents = MeshResource.Contents()
contents.models = mesh.contents.models
contents.instances = MeshInstanceCollection(instances)
do {
let finalMesh = try await MeshResource(from: contents)
var spheres = ModelEntity(mesh: finalMesh, materials: [material])
content.add(spheres)
} catch {
print("failed to create mesh resource \(error.localizedDescription)")
}
}
}
Here is a screenshot of the RealityKit trace.
Maybe there is some specific requirements on a usdz file that will trigger RealityKit to used instanced rendering.