Batch-create simple Rhino materials from Grasshopper

Cobbled together this little script by picking apart this from Nathan along with some help from ChatGPT

Takes a button, list of file paths (image files), and list of names.

Batch creates super basic materials with just the images applied

If I ever get to spend more time on this, I’d like to add more deliberate default settings. WCS-box mapping, maybe use ‘custom’ type instead of PBR. Possibly editable from GH input.

But figured I’d share this for now because I may never get around to all that.

import Rhino as rh
import Rhino.Render as rr
import Rhino.DocObjects as rd
import scriptcontext as sc
import os.path

image_path = x
material_name = y

if button:
    # Get the Rhino document context
    doc = rh.RhinoDoc.ActiveDoc

    # Check if the image file exists
    if not image_path or not os.path.isfile(image_path):
        print("Invalid or missing image file.")
    else:
        # Create a bitmap texture for the color channel
        bitmap_texture_type_guid = rr.ContentUuids.BitmapTextureType
        main_texture = rr.RenderContentType.NewContentFromTypeId(bitmap_texture_type_guid)
        main_texture.Filename = image_path
        main_simulated_texture = main_texture.SimulatedTexture(rr.RenderTexture.TextureGeneration.Allow)

        # Create a new PBR material
        pbr_material_type_guid = rr.ContentUuids.PhysicallyBasedMaterialType
        pbr_rm = rr.RenderContentType.NewContentFromTypeId(pbr_material_type_guid)

        # Simulate the material to get the PhysicallyBasedMaterial
        sim = pbr_rm.SimulatedMaterial(rr.RenderTexture.TextureGeneration.Allow)
        pbr = sim.PhysicallyBased

        # Set the base color texture
        pbr.SetTexture(main_simulated_texture.Texture(), rd.TextureType.PBR_BaseColor)

        # Convert it back to RenderMaterial
        new_pbr = rr.RenderMaterial.FromMaterial(pbr.Material, doc)

        # Set the name for the new material
        new_pbr.Name = material_name

        # Add the material to the document
        doc.RenderMaterials.Add(new_pbr)

        print("Created new material with image texture and name: {}".format(material_name))
else:
    print("Press the button to execute the script.")
2 Likes