Skip to content

Instantly share code, notes, and snippets.

@CGArtPython
Created September 11, 2023 07:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CGArtPython/5b230013a62c1a2083e66fc7932ef8b6 to your computer and use it in GitHub Desktop.
Save CGArtPython/5b230013a62c1a2083e66fc7932ef8b6 to your computer and use it in GitHub Desktop.
Creating a pyramid from scratch using the Bmesh Blender Python module. (video tutorial here: https://youtu.be/N3U2noAHgBo)
import bpy
import bmesh
obj_name = "my_shape"
# create the mesh data
mesh_data = bpy.data.meshes.new(f"{obj_name}_data")
# create the mesh object using the mesh data
mesh_obj = bpy.data.objects.new(obj_name, mesh_data)
# add the mesh object into the scene
bpy.context.scene.collection.objects.link(mesh_obj)
# create a new bmesh
bm = bmesh.new()
# create a list of vertex coordinates
vert_coords = [
(1.0, 1.0, 0.0),
(1.0, -1.0, 0.0),
(-1.0, -1.0, 0.0),
(-1.0, 1.0, 0.0),
(0.0, 0.0, 1.0),
]
# create and add a vertices
for coord in vert_coords:
bm.verts.new(coord)
# create a list of vertex indices that are part of a given face
face_vert_indices = [
(0, 1, 2, 3),
(4, 1, 0),
(4, 2, 1),
(4, 3, 2),
(4, 0, 3),
]
bm.verts.ensure_lookup_table()
for vert_indices in face_vert_indices:
bm.faces.new([bm.verts[index] for index in vert_indices])
# writes the bmesh data into the mesh data
bm.to_mesh(mesh_data)
# [Optional] update the mesh data (helps with redrawing the mesh in the viewport)
mesh_data.update()
# clean up/free memory that was allocated for the bmesh
bm.free()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment