hc-material-faces

Übersicht: Python & Blender


Objectives

In the last station we applied the material to the hole object. Now we select a few faces to color only parts of the object surface.

Instructions

Tasks:
  1. Create the colored cube without the script but in a classical Blender way with mouse and keyboard. Count the number of clicks!

  2. Create a cylinder and change the color of the top and bottom base.

  3. Create a chessboard like in this image:

    /blender-basics/h-material/chessboard.png
  4. Create an set of tokens for the game draughts (or checkers) an the board.

    /blender-basics/h-material/Boilly-Checkers-1803.jpg
    Louis-Léopold Boilly (1761–1845)
    Painting of a family game of checkers
    (»jeu des dames«) [1]

A colored cube

To be able to color of one or more faces, select them. At first the script:

blender-basics/h-material/colored-cube.py (Source)

#!bpy
"""
Name: 'colored_cube.py'
Blender: 2.7x
Group: 'Material'
Tooltip: 'Colored faces'
"""
import bpy

red = bpy.data.materials.new('Red')
blue = bpy.data.materials.new('Blue')
yellow = bpy.data.materials.new('Yellow')


def setColor(obj, material, color):
    material.diffuse_color = color
    material.specular_hardness = 200
    obj.data.materials.append(material)


def colored_cube():
    """ A three colored cube """

    bpy.ops.mesh.primitive_cube_add(location=(0, 0, 0))
    ob = bpy.context.object
    ob.name = 'my colored cube'

    setColor(ob, red, (1, 0, 0))
    setColor(ob, yellow, (1, 1, 0))
    setColor(ob, blue, (0, 0, 1))

    # apply the colors
    for face in ob.data.polygons:
        face.material_index = face.index % 3

if __name__ == '__main__':
    bpy.ops.object.select_by_type(type='MESH')
    bpy.ops.object.delete()
    colored_cube()

Name the colors

Every color should have a name. This is the first Step.

blender-basics/h-material/colored-cube.py (Source)

red = bpy.data.materials.new('Red')
blue = bpy.data.materials.new('Blue')
yellow = bpy.data.materials.new('Yellow')

Add the materials

This is little bit tricky, to add a color for each face. Step by step:

  • All faces of an object (a cube has six) are saved in a list of polygons.

  • In a for loop wie iterate over this list.

  • The index number from the list is divided by three with the modulo operator.

    So we get three possible results 0, 1 or 2.

  • Each number is connected with a color.

  • Finally the color number is assigned to the material index, because materials are also managed with an index.

blender-basics/h-material/colored-cube.py (Source)

    # apply the colors
    for face in ob.data.polygons:
hint: In old tutorials before 2.68 faces are selected from a list named faces. Now the new list and name is polygons.

Result

/blender-basics/h-material/faces-colored-200.png

Commentaar