如何将 material 应用于 .glb/.gltf 网格?

How do I apply a material to a .glb/.gltf mesh?

我有一个 .glb 格式的模型,场景中没有任何编辑(只有网格)。如何使用 Python 应用 glb/gltf 网格的 material?尽管我可以使用其他库,但我正在使用 Pygltflib 和 Trimesh。

我只能笼统的回答,因为你没有提供任何代码,但原则上你会这样做:

material = Material() # Create a material
pbr = PbrMetallicRoughness() # Use PbrMetallicRoughness
pbr.baseColorFactor = [1.0, 0.0, 0.0, 1.0] # solid red
material.pbrMetallicRoughness = pbr

然后像那样向你的原语提供 material

primitive.material = 0

并且不要忘记将其添加到 gltf。与往常一样,如果您使用更多 materials,顺序当然很重要:

gltf.materials.append(material)

为了完整起见,这里是如何将带有“MASK”alphaMode 的双面红色金属粗糙度材料添加到三角形示例并将其另存为 .glb:

from pygltflib import *

# create gltf objects for a scene with a primitive triangle with indexed geometry
gltf = GLTF2()
scene = Scene()
mesh = Mesh()
material = Material()
primitive = Primitive()
node = Node()
buffer = Buffer()
bufferView1 = BufferView()
bufferView2 = BufferView()
accessor1 = Accessor()
accessor2 = Accessor()

# add data
buffer.uri = "data:application/octet-stream;base64,AAABAAIAAAAAAAAAAAAAAAAAAAAAAIA/AAAAAAAAAAAAAAAAAACAPwAAAAA="
buffer.byteLength = 44

bufferView1.buffer = 0
bufferView1.byteOffset = 0
bufferView1.byteLength = 6
bufferView1.target = ELEMENT_ARRAY_BUFFER

bufferView2.buffer = 0
bufferView2.byteOffset = 8
bufferView2.byteLength = 36
bufferView2.target = ARRAY_BUFFER

accessor1.bufferView = 0
accessor1.byteOffset = 0
accessor1.componentType = UNSIGNED_SHORT
accessor1.count = 3
accessor1.type = SCALAR
accessor1.max = [2]
accessor1.min = [0]

accessor2.bufferView = 1
accessor2.byteOffset = 0
accessor2.componentType = FLOAT
accessor2.count = 3
accessor2.type = VEC3
accessor2.max = [1.0, 1.0, 0.0]
accessor2.min = [0.0, 0.0, 0.0]

pbr = PbrMetallicRoughness() # Use PbrMetallicRoughness
pbr.baseColorFactor = [1.0, 0.0, 0.0, 1.0] # solid red
material.pbrMetallicRoughness = pbr
material.doubleSided = True # make material double sided
material.alphaMode = MASK   # to get around 'MATERIAL_ALPHA_CUTOFF_INVALID_MODE' warning

primitive.attributes.POSITION = 1
primitive.material = 0
node.mesh = 0
scene.nodes = [0]

# assemble into a gltf structure
gltf.scenes.append(scene)
gltf.meshes.append(mesh)
gltf.materials.append(material)
gltf.meshes[0].primitives.append(primitive)
gltf.nodes.append(node)
gltf.buffers.append(buffer)
gltf.bufferViews.append(bufferView1)
gltf.bufferViews.append(bufferView2)
gltf.accessors.append(accessor1)
gltf.accessors.append(accessor2)

gltf.convert_buffers(BufferFormat.BINARYBLOB) # Convert buffers to allow saving as .glb

# save to a .glb file
gltf.save("triangle.glb")