Creating objects and meshes with python (Example Code)

Here is a simple script written and tested in Blender 2.79 that creates a box intended to be a wood board of the given dimensions. I noticed quite some time ago that vertice creation should keep in mind face creation as the order determines the orientation of the normals when not specifically programmed.

Hope this helps others.

#
# Wood board creation script for Blender
#
# Copyright 2017-2019 (c) Jorge Joaquin Pareja
#
# License: GNU Public License Version 2
#
# 1/16 in = 0.0015875
# 1in = 0.0254 blender units
# 1ft = 0.30480 blender units
#
#
import bpy

inch = 0.0254
foot = inch * 12

def CreateBoard(height, width, length, locate=[0,0,0]):
    '''
        Create a wood board.

        Perameters:
            height: the height in inches
             width: the width in inches
            length: the length in feet
            locate: the location to place the board (3 perameters x,y,z)

        Example:
            CreateBoard(2,4,12,(0,0,0))
            
            creates a two by four board twelve feet long at 0,0,0.
    '''
    me = bpy.data.meshes.new('mBoard')
    ob = bpy.data.objects.new('oBoard', me)
    ob.location = ((locate)) #((0,0,0))
    ob.show_name = True
    bpy.context.scene.objects.link(ob)
    
    verts = ((0,0,0),                               # Vert 0
             (0,foot*length,0),                     # Vert 1
             (width*inch,foot*length,0),            # Vert 2
             (width*inch, 0, 0),                    # Vert 3
             (0,0,inch*height),                     # Vert 4
             (0,length*foot,inch*height),           # Vert 5
             (width*inch,length*foot,inch*height),  # Vert 6
             (width*inch, 0, inch*height))          # Vert 7

    faces = ((0,1,2),   # Tri-Face 1
             (2,3,0),   # Tri-Face 2
             (4,6,5),   # Tri-Face 3
             (4,7,6),   # Tri-Face 4
             (4,0,7),   # Tri-Face 5
             (7,0,3),   # Tri-Face 6
             (0,4,1),   # Tri-Face 7
             (4,5,1),   # Tri-Face 8
             (1,5,2),   # Tri-Face 9
             (5,6,2),   # Tri-Face 10
             (6,7,3),   # Tri-Face 11
             (3,2,6))   # Tri-Face 12
    
    me.from_pydata(verts, [], faces)
    
    # Update mesh with new data
    me.update(calc_edges=True)

# the following is just for testing
if __name__ == "__main__":
    CreateBoard(2,4,12,(1,1,0)) # Create a 2x4, 12 feet long in the center of the world

1 Like

this is using the old API not using BMesh data
which won’t be there in 2.8

also if you look at the box it has triangles on faces
it should be only with quad faces

nice example anyway

for primitive addon with Bmesh look at the script Templates in text editor of blender

happy bl