feat: enhance material creation to ensure Principled BSDF node exists and apply materials to exported objects

This commit is contained in:
MayaTheShy
2025-11-08 23:13:04 -05:00
parent a0a6371c29
commit fd6b9ec645

View File

@@ -1,5 +1,6 @@
import bpy import bpy
import os import os
import traceback
# Clear existing objects # Clear existing objects
bpy.ops.object.select_all(action='SELECT') bpy.ops.object.select_all(action='SELECT')
@@ -11,91 +12,122 @@ os.makedirs(output_dir, exist_ok=True)
def create_material(name, base_color): def create_material(name, base_color):
"""Create a PBR material with the specified base color (RGBA)""" """Create a PBR material with the specified base color (RGBA)"""
mat = bpy.data.materials.new(name=name) try:
mat.use_nodes = True mat = bpy.data.materials.new(name=name)
nodes = mat.node_tree.nodes mat.use_nodes = True
nodes = mat.node_tree.nodes
# Find the Principled BSDF node (should be created by default)
bsdf = None # Find the Principled BSDF node (should be created by default)
for node in nodes: bsdf = None
if node.type == 'BSDF_PRINCIPLED': for node in nodes:
bsdf = node if node.type == 'BSDF_PRINCIPLED':
break bsdf = node
break
# If not found, create it
if not bsdf: # If not found, create it
bsdf = nodes.new(type='ShaderNodeBsdfPrincipled') if not bsdf:
bsdf = nodes.new(type='ShaderNodeBsdfPrincipled')
# Set material properties
bsdf.inputs['Base Color'].default_value = base_color # Set material properties
bsdf.inputs['Roughness'].default_value = 0.5 bsdf.inputs['Base Color'].default_value = base_color
bsdf.inputs['Metallic'].default_value = 0.1 bsdf.inputs['Roughness'].default_value = 0.5
bsdf.inputs['Metallic'].default_value = 0.1
return mat
print(f" Created material '{name}' with color {base_color}")
return mat
except Exception as e:
print(f"ERROR creating material: {e}")
traceback.print_exc()
return None
print("Creating GREEN sphere...") try:
# Create and export UV Sphere with GREEN material print("Creating GREEN sphere...")
bpy.ops.mesh.primitive_uv_sphere_add(segments=32, ring_count=16, radius=0.5, location=(0, 0, 0)) # Create and export UV Sphere with GREEN material
sphere = bpy.context.active_object bpy.ops.mesh.primitive_uv_sphere_add(segments=32, ring_count=16, radius=0.5, location=(0, 0, 0))
sphere.name = "Sphere" sphere = bpy.context.active_object
sphere.select_set(True) sphere.name = "Sphere"
bpy.context.view_layer.objects.active = sphere sphere.select_set(True)
bpy.ops.object.shade_smooth() bpy.context.view_layer.objects.active = sphere
# Apply green material bpy.ops.object.shade_smooth()
green_mat = create_material("SphereMaterial", (0.2, 1.0, 0.2, 1.0)) # Green
sphere.data.materials.append(green_mat) # Apply green material
sphere_path = os.path.join(output_dir, "sphere.glb") green_mat = create_material("SphereMaterial", (0.2, 1.0, 0.2, 1.0)) # Green
bpy.ops.export_scene.gltf( if green_mat:
filepath=sphere_path, sphere.data.materials.append(green_mat)
export_format='GLB',
use_selection=True sphere_path = os.path.join(output_dir, "sphere.glb")
) print(f" Exporting to {sphere_path}...")
print(f"✓ Exported sphere.glb (GREEN) to {sphere_path}") bpy.ops.export_scene.gltf(
filepath=sphere_path,
export_format='GLB',
use_selection=True
)
print(f"✓ Exported sphere.glb (GREEN)")
except Exception as e:
print(f"ERROR with sphere: {e}")
traceback.print_exc()
print("Creating RED cube...") try:
# Delete sphere and create cube with RED material print("\nCreating RED cube...")
bpy.ops.object.delete(use_global=False) # Delete sphere and create cube with RED material
bpy.ops.mesh.primitive_cube_add(size=1.0, location=(0, 0, 0)) bpy.ops.object.delete(use_global=False)
cube = bpy.context.active_object bpy.ops.mesh.primitive_cube_add(size=1.0, location=(0, 0, 0))
cube.name = "Cube" cube = bpy.context.active_object
cube.select_set(True) cube.name = "Cube"
bpy.context.view_layer.objects.active = cube cube.select_set(True)
bpy.ops.object.shade_smooth() bpy.context.view_layer.objects.active = cube
# Apply red material bpy.ops.object.shade_smooth()
red_mat = create_material("CubeMaterial", (1.0, 0.2, 0.2, 1.0)) # Red
cube.data.materials.append(red_mat) # Apply red material
cube_path = os.path.join(output_dir, "cube.glb") red_mat = create_material("CubeMaterial", (1.0, 0.2, 0.2, 1.0)) # Red
bpy.ops.export_scene.gltf( if red_mat:
filepath=cube_path, cube.data.materials.append(red_mat)
export_format='GLB',
use_selection=True cube_path = os.path.join(output_dir, "cube.glb")
) print(f" Exporting to {cube_path}...")
print(f"✓ Exported cube.glb (RED) to {cube_path}") bpy.ops.export_scene.gltf(
filepath=cube_path,
export_format='GLB',
use_selection=True
)
print(f"✓ Exported cube.glb (RED)")
except Exception as e:
print(f"ERROR with cube: {e}")
traceback.print_exc()
print("Creating BLUE icosphere...") try:
# Delete cube and create ico sphere for the "model" placeholder with BLUE material print("\nCreating BLUE icosphere...")
bpy.ops.object.delete(use_global=False) # Delete cube and create ico sphere for the "model" placeholder with BLUE material
bpy.ops.mesh.primitive_ico_sphere_add(subdivisions=2, radius=0.5, location=(0, 0, 0)) bpy.ops.object.delete(use_global=False)
ico = bpy.context.active_object bpy.ops.mesh.primitive_ico_sphere_add(subdivisions=2, radius=0.5, location=(0, 0, 0))
ico.name = "IcoSphere" ico = bpy.context.active_object
ico.select_set(True) ico.name = "IcoSphere"
bpy.context.view_layer.objects.active = ico ico.select_set(True)
bpy.ops.object.shade_smooth() bpy.context.view_layer.objects.active = ico
# Apply blue material bpy.ops.object.shade_smooth()
blue_mat = create_material("IcoSphereMaterial", (0.2, 0.2, 1.0, 1.0)) # Blue
ico.data.materials.append(blue_mat) # Apply blue material
model_path = os.path.join(output_dir, "model.glb") blue_mat = create_material("IcoSphereMaterial", (0.2, 0.2, 1.0, 1.0)) # Blue
bpy.ops.export_scene.gltf( if blue_mat:
filepath=model_path, ico.data.materials.append(blue_mat)
export_format='GLB',
use_selection=True model_path = os.path.join(output_dir, "model.glb")
) print(f" Exporting to {model_path}...")
print(f"✓ Exported model.glb (BLUE) to {model_path}") bpy.ops.export_scene.gltf(
filepath=model_path,
export_format='GLB',
use_selection=True
)
print(f"✓ Exported model.glb (BLUE)")
except Exception as e:
print(f"ERROR with icosphere: {e}")
traceback.print_exc()
print("\n" + "="*60) print("\n" + "="*60)
print("ALL PRIMITIVE MODELS WITH COLORS EXPORTED SUCCESSFULLY!") print("EXPORT COMPLETE!")
print("="*60) print("="*60)
print(f" RED Cube: {os.path.join(output_dir, 'cube.glb')}") print(f"Output directory: {output_dir}")
print(f" GREEN Sphere: {os.path.join(output_dir, 'sphere.glb')}") print(" - cube.glb (RED)")
print(f" BLUE IcoSphere: {os.path.join(output_dir, 'model.glb')}") print(" - sphere.glb (GREEN)")
print(" - model.glb (BLUE)")
print("="*60) print("="*60)