Examples

Export "monkey" from Blender

This is a short description of the file 02_blender_monkey_script.py in the ITA21 repo.

Blender has a sample mesh that is quite useful for testing scripts. It is the head of a monkey, called "Suzanne" (don't ask me why). With the script below, we

  • create the monkey mesh as a bmesh and then convert it to a mesh data block,

  • extract the vertices and faces of the mesh,

  • make a COMPAS mesh from the extracted vertices and faces,

  • (optional) subdivide the COMPAS mesh,

  • (optional) visualize the COMPAS mesh with an artist, and

  • export the COMPAS mesh to a JSON file.

import os
import bpy
import bmesh
import compas
import compas_blender
from compas.datastructures import Mesh
from compas_blender.artists import MeshArtist

# clear all objects from the current Blender scene
compas_blender.clear()

# create the monkey bmesh
bm = bmesh.new()
bmesh.ops.create_monkey(bm)

# convert the bmesh to a Blender mesh data block
# (this is just how Blender works)
meshdata = bpy.data.meshes.new('Mesh')
bm.to_mesh(meshdata)
bm.free()

# get the vertices and the faces of the Blender mesh
# (in the future we will use a COMPAS function for this)
vertices = [list(vertex.co) for vertex in meshdata.vertices]
faces = [list(face.vertices) for face in meshdata.polygons]

# make a COMPAS mesh from vertices and faces
mesh = Mesh.from_vertices_and_faces(vertices, faces)

# optional: subdivide
mesh = mesh.subdivide(k=2)

# optional: use an artist to visualize the mesh
artist = MeshArtist(mesh)
artist.draw_mesh()

# export the mesh to JSON
compas.json_dump(mesh, os.path.expanduser('~/Code/ITA21/monkey.json'))

The result of this script should be something like this.

Add a box and visualize with View2

This is a short description of the file 03_view2_box-the-monkey.py in the ITA21 repo.

The exported monkey mesh can now be opened in any other environment for visualization or further processing. The script below can be executed in VS Code. The code has the following steps.

  • load the mesh data from the JSON file

  • (optional) subdivide the mesh

  • compute the bounding box and add as a geometric shape

  • (optional) visualize with the viewer

  • export the mesh and the box to a new JSON file

import compas
from compas.geometry import Box, Scale
from compas_view2.app import App

# load the mesh data
mesh = compas.json_load('monkey.json')

# optional: subdivide
# mesh = mesh.subdivide(k=2)

# add a box
# and give the monkey some breathing room
box = Box.from_bounding_box(mesh.bounding_box())
box.transform(Scale.from_factors([1.5, 1.5, 1.5]))

# visualize the mesh and the box with the viewer
viewer = App()
viewer.add(mesh)
viewer.add(box, opacity=0.5)
viewer.show()

# export the moonkey in the box
compas.json_dump([mesh, box], 'monkey-in-box.json')

The result should be something like this.

Last updated