MeshFormer / ply2glb.py
NCJ's picture
copy from dev
57a1960 verified
import bpy
import sys
# Clear the scene
bpy.ops.object.select_all(action="SELECT")
bpy.ops.object.delete(use_global=False)
# Load mesh.ply
ply_path = sys.argv[-1]
bpy.ops.wm.ply_import(filepath=ply_path)
# Create a new material
material = bpy.data.materials.new(name="New_Material")
material.use_nodes = True
# Assign the material to the object
obj = bpy.context.selected_objects[0]
if obj.data.materials:
obj.data.materials[0] = material
else:
obj.data.materials.append(material)
# Add a Vertex Color node and link it
nodes = material.node_tree.nodes
links = material.node_tree.links
# Clear default nodes
for node in nodes:
nodes.remove(node)
# Create nodes
output_node = nodes.new(type="ShaderNodeOutputMaterial")
vertex_color_node = nodes.new(type="ShaderNodeVertexColor")
principled_bsdf = nodes.new(type="ShaderNodeBsdfPrincipled")
# Set the vertex color layer name
vertex_color_node.layer_name = "Col"
# Arrange nodes
vertex_color_node.location = (-300, 0)
principled_bsdf.location = (0, 0)
output_node.location = (300, 0)
# Link nodes
links.new(vertex_color_node.outputs["Color"], principled_bsdf.inputs["Base Color"])
links.new(principled_bsdf.outputs["BSDF"], output_node.inputs["Surface"])
# Rotate the object
bpy.context.object.rotation_euler[2] = 1.57079
# Export the scene to a glTF file
glb_path = ply_path.replace(".ply", ".glb")
bpy.ops.export_scene.gltf(filepath=glb_path, export_format="GLB")
# Free up memory
bpy.ops.wm.read_factory_settings(use_empty=True)