Site Tools

Set Material Colors from Object Colors

Developer: RhinoScript
Summary: Demonstrates how to modify an object's material color to match it's display color.


The following RhinoScript demonstrates how to modify an object's material color so it matches it's display color. For objects who get their display color from their layer, then the layer's material color is modified to match the layer color. In doing this, objects will render with the same colors as they show up in Rhino when viewing in either wireframe or shaded mode.

See the RhinoScript help file for details on loading and running scripts.

 Option Explicit
 Sub SetMaterialColorsFromObjectColors
  ' Constants
  Const rhColorByLayer = 0
  Const rhColorByObject = 1
  ' Variables
  Dim aObjects, sObject
  Dim nColor, nSource
  Dim sLayer, nMaterial
  ' Get all objects in the document
  aObjects = Rhino.AllObjects
  If Not IsArray(aObjects) Then Exit Sub
  ' Process each object    
  For Each sObject In aObjects
    ' Get the object's color and color source
    nColor = Rhino.ObjectColor(sObject)
    nSource = Rhino.ObjectColorSource(sObject)
    nMaterial = -1
    ' If the object's color source is "by layer"
    ' then get the layer's material index. If the
    ' layer does not have a material, add one.    
    If (nSource = rhColorByLayer) Then
      sLayer = Rhino.ObjectLayer(sObject)
      nMaterial = Rhino.LayerMaterialIndex(sLayer)
      If( nMaterial < 0 ) Then
        nMaterial = Rhino.AddMaterialToLayer(sLayer)
      End If
    ' If the object's color source is "by object"
    ' then get the object's material index. If the
    ' object does not have a material, add one.    
    ElseIf (nSource = rhColorByObject) Then
      nMaterial = Rhino.ObjectMaterialIndex(sObject)
      If( nMaterial < 0 ) Then
        nMaterial = Rhino.AddMaterialToObject(sObject)
      End If
    End If
    ' Set the material color
    If (nMaterial >= 0) Then
      If (nColor <> Rhino.MaterialColor(nMaterial)) Then
        Rhino.MaterialColor nMaterial, nColor
      End If
    End If
  ' Redraw the document
 End Sub

developer/scriptsamples/setrendercolor.txt ยท Last modified: 2015/09/14 (external edit)