How to use Python for 3D modeling: Step-by-Step Techniques

published on 18 February 2024

Creating 3D models with code can seem daunting to those without a programming background.

However, Python makes the process incredibly approachable, even for beginners. With just a few key libraries, you can start scripting detailed 3D models in no time.

This guide will walk you through everything you need to know, from choosing the right Python 3D modeling tools to step-by-step tutorials for building your first models. You'll be rendering intricate 3D graphics before you know it!

Introduction to Python for 3D Modeling

Python is an incredibly versatile programming language that can be used for 3D modeling and computer-aided design (CAD) applications. With Python's extensive libraries and tools for 3D graphics and visualization, it provides a flexible and accessible way to create and manipulate 3D models.

Some of the key benefits of using Python for 3D modeling include:

  • Automation - Python makes it easy to automate repetitive modeling tasks, allowing you to work more efficiently. Common uses include batch processing models, parametric design, and creating customized workflows.

  • Rapid Prototyping - Python is great for quickly testing modeling concepts before investing time in more complex CAD software. Models can be visualized and shared easily.

  • Customization - Python gives you fine-grained control to customize modeling behaviors and build domain-specific tools tailored to your needs.

  • Interoperability - Python can read and write many standard 3D file formats like STL, STEP, and IGES for integration across modeling pipelines.

Some popular Python libraries used for 3D modeling and CAD work include:

  • CadQuery - High-level API for creating parametric CAD models. Great for programmers.
  • FreeCAD - General purpose CAD package with Python scripting interface. More user-friendly.
  • MeshPy - Tools for triangle mesh generation and 3D tetrahedral meshing.
  • PyVista - 3D plotting and mesh analysis via VTK.

Now let's explore key techniques for applying Python to 3D modeling workflows.

Exploring the Best Python 3D Library for Your Needs

When selecting a Python 3D modeling library, first consider your application area and specific use cases. Key criteria include:

  • Ease of Use - Is a simple, clean API available or is deeper programming knowledge expected?
  • Feature Set - Evaluate available modeling operations, file formats, and visualization tools.
  • Performance - Speed and scalability needs depend on model complexity.
  • Interoperability - Assess integration options with external CAD software if needed.

For example, CadQuery provides a high-level, easy-to-use API tailored for programmers to build parametric CAD models using Python scripting. It uses the OpenCASCADE geometry kernel and focuses specifically on CAD workflows.

In contrast, FreeCAD offers a more expansive general purpose CAD feature set through its Python API, including mesh operations, simulations, and documentation tools beyond just modeling. But it has a steeper learning curve.

So CadQuery may be preferable for rapid scripted CAD, while FreeCAD is better for advanced applications needing broader CAD capabilities.

Automating 3D Modeling Tasks with Python

Python is extremely useful for automating repetitive and time-consuming modeling steps. Common examples include:

  • Batch Processing Models - Automatically translate, rotate, scale or otherwise modify models in bulk.
  • Parametric CAD - Programmatically construct models based on key parameters and relationships for quick design iterations.
  • Custom Workflows - Script pipeline tools connecting modeling, analysis, and optimization tasks.

For instance, you could use Python to batch export multiple STEP files as STLs while standardizing materials and optimizing meshes for 3D printing. Or develop parametric CAD systems where models update on-the-fly based on logic relationships between dimensions and constraints.

Python's flexibility makes it straightforward to eliminate tedious manual operations in your modeling pipeline.

Running Python Code for 3D Modeling

To start scripting 3D models with Python, first install a Python distribution like Anaconda and your CAD library of choice. Many libraries have getting started tutorials, like CadQuery or FreeCAD.

Most Python CAD scripts follow this general workflow:

  1. Import the library - import cadquery, import FreeCAD, etc.
  2. Build modeling workspace - Instantiate document, create base shapes.
  3. Execute modeling operations - Extrude, fillet, add holes via library functions.
  4. Export model - Write model to file format like STEP, STL, etc.

For example, here is some CadQuery code to model a simple I-beam:

import cadquery as cq

# Modeling operations
beam = (cq.Workplane("XY")  
    .rect(10, 5)  
    .extrude(100)
)

# Export model  
beam.val().exportStep("IBeam.step")

Review library documentation to explore available modeling functionality. Execute scripts in IDEs like Jupyter notebooks or directly from the command line.

Viewing 3D Models with Python 3D Model Viewer Tools

When developing 3D models, it's crucial to visually inspect the output geometry. Some Python options for model viewing include:

  • CadQuery & FreeCAD Viewers - Built-in graphical views.
  • MeshPy, Trimesh, PyVista - Mesh analysis and point cloud visualization.
  • Matplotlib, Plotly - General purpose Python plotting for basic 3D.
  • IPython Interactive Widgets - Enable 3D manipulation in Jupyter notebooks.

For example, to view an STL model in CadQuery:

import cadquery as cq
result = cq.importers.importStep('sample.step')
show_object(result) 

The viewer supports pan, zoom, rotate, with configurable display properties. Additional controls are available in premium versions.

Integrated Python model viewing makes it easy to visually debug geometry scripting workflows.

Can you do 3D modeling with Python?

Python is an extremely versatile programming language that can be used for 3D modeling and rendering in a variety of ways. Here are some of the most popular options:

Using Python 3D Modeling Libraries

There are several Python libraries available specifically for generating and manipulating 3D models, such as:

  • PyMesh - Focuses on mesh generation and processing. Useful for tasks like cleaning up 3D scans.
  • Open3D - Provides data structures and algorithms for 3D data processing. Supports 3D model reconstruction.
  • Trimesh - Designed for loading and storing triangular meshes. Simplifies working with STL files and point clouds.

These libraries have functions to help construct 3D models programmatically using Python code. For example, you can script complex parametric models, generate 3D meshes from scratch, or process scanned 3D data.

Integrating Python with 3D Modeling Software

Many 3D modeling and CAD packages have Python APIs or plugins available, allowing Python to automate and extend their functionality:

  • FreeCAD - Open source CAD software that can be fully scripted in Python. The Python API allows creating custom tools, macros, and workflows.
  • Blender - Includes a Python API for writing scripts and addons that create models, set up scenes, add materials and textures, etc.
  • CADquery - Module for generating parametric CAD models. Integrates well with FreeCAD.

This makes Python a very capable tool for advanced modeling, rendering, and automation tasks.

Viewing and Converting 3D Models

There are Python libraries focused on loading, viewing, and converting various 3D file formats:

  • Trimesh can render a variety of 3D model files in an OpenGL window for quick visualization
  • numpy-stl provides utilities for working with STL files
  • PyVista can create plots and renderings from VTK datasets

In summary, Python has rich capabilities when it comes to working with 3D data, whether it's for procedural modeling, integrating with existing software, automation, or just loading and converting file types. The multitude of specialized Python libraries make practically any 3D task possible.

How to create 3D model step by step?

Creating 3D models from photos involves capturing images from different angles and using photogrammetry software to stitch them together into a 3D model. Here is a simplified step-by-step process:

Gather images

  • Take at least 20-30 photos of the object you want to model from all angles and distances. Ensure there is plenty of overlap between images.
  • Use a digital camera or smartphone camera. DSLR cameras work best for capturing intricate detail.
  • Ensure even, diffuse lighting without harsh shadows or glare.

Process images

  • Upload images into photogrammetry software like RealityCapture, Metashape or AliceVision.
  • The software will detect common points across the images and build a sparse point cloud.

Refine model

  • Review the initial model and mask out any unwanted background areas.
  • Let the software process further to build a dense point cloud and mesh.
  • Manually edit the model as needed to fix holes or imperfections.

Export model

  • Export the completed 3D model file into desired format like OBJ, STL or PLY.
  • The model can now be used for applications like 3D printing, AR/VR, animation, games etc.

With some practice, photogrammetry allows creating detailed 3D replicas of real-world objects completely digitally. The key is taking adequate photos and reviewing the model for errors.

How do you make a 3D shape in Python?

Python has excellent libraries for creating and displaying 3D graphics. The key ones are:

Matplotlib

Matplotlib is a popular Python plotting library that can generate simple 3D plots when using the mplot3d toolkit. Here is an example:

import numpy as np
from mpl_toolkits import mplot3d
import matplotlib.pyplot as plt

fig = plt.figure()
ax = plt.axes(projection='3d')

x = [1, 2, 3, 4] 
y = [3, 4, 5]
X, Y = np.meshgrid(x, y)
Z = X**2 + Y**2

ax.plot_surface(X, Y, Z)
plt.show()

This plots a 3D parabolic surface. The mplot3d toolkit handles generating the 3D plot.

CADQuery

CADQuery is a Python library for creating 3D CAD models programmatically. It is built on top of OpenCASCADE. Here is an example box shape:

import cadquery as cq

result = cq.Workplane("XY" ).box(3, 2, 1)
show_object(result)

CADQuery has an extensive API for advanced programmatic CAD modelling and working with common formats like STEP and IGES.

Blender

Blender is an open-source 3D computer graphics software. It has a Python API that allows you to create 3D scenes and models programmatically. Here is an example to create a cube mesh object:

import bpy
bpy.ops.mesh.primitive_cube_add()

The Blender Python API allows controlling most aspects of Blender programmatically.

So in summary, Matplotlib, CADQuery, and Blender's Python APIs are great choices for programmatic 3D modelling and visualization.

sbb-itb-ceaa4ed

Getting Started with FreeCAD & Python API

FreeCAD is a powerful open-source 3D modeling application that can be automated and customized using its Python API. This allows creating parametric models, automating repetitive tasks, and even building customized tools and workflows.

To get started with scripting FreeCAD using Python, you need to:

Installing FreeCAD and Setting Up the Python Environment

  1. Download and install the latest version of FreeCAD. Make sure to install the version that includes the Python integration.

  2. Set up a Python environment to work with the FreeCAD Python API. You can use the built-in Python console in FreeCAD, or an external Python IDE like PyCharm. Make sure the Python version matches what FreeCAD uses.

  3. Import the FreeCAD modules in your Python script - import FreeCAD and import Part to start working with the API.

With the setup complete, you can now start scripting FreeCAD using Python. Let's look at some basics of part scripting next.

FreeCAD Part Scripting Basics

The Part module in FreeCAD provides various tools for creating and manipulating geometrical shapes. Here are some important concepts:

  • Workplane: Defines a working plane to draw 2D sketches and extrusions. Created using Part.makePlane().

  • Shapes: Base class for all geometric shapes like cubes, spheres etc. Created from vertices and edges.

  • Extrusions: Used to give height to 2D sketches. Created using mySketch.extrude(distance)

  • Boolean operations: Combine shapes using union/difference/intersection operations.

For example, to create a simple I-beam with dimensions 100 x 200 x 8000 mm:

import Part

beamWidth = 100
beamHeight = 200 
beamLength = 8000

# Create a rectangle as the cross-section  
rect = Part.makePlane(beamWidth, beamHeight)

# Extrude to get beam  
beam = rect.extrude(beamLength)

This creates a parametric I-beam that can be modified by changing the dimensions.

Creating Your First 3D Model with FreeCAD Python Scripting

Let's create a simple box using FreeCAD scripting:

  1. Set up workplane to draw the base sketch
  2. Draw a rectangle in the workplane as the base
  3. Extrude the sketch to add height
  4. Create another box and subtract it using boolean difference to create a cavity

Here is the Python script:

import Part

# Workplane 
base = Part.makePlane(200,100) 

# Base sketch
rect =  base.makeRectangle(100, 50)  

# Extrude base sketch 
solid = rect.extrude(50)  

# Sketch for subtracting cavity
top = base.makePlane(100,50, FreeCAD.Vector(0,0,30))  
rect2 = top.makeRectangle(75, 25)

# Extrude & subtract  
solid = solid.cut(rect2.extrude(20))

This creates a hollow box with a cavity inside! You can keep building on these basics to create more complex models.

FreeCAD Tutorial: Advanced Modeling Techniques

As you get comfortable with the basics, you can explore more advanced modeling techniques like:

  • Sweeps: Create shapes by sweeping 2D sketches along a path
  • Lofts: Generate shapes by lofting between multiple sketches
  • Helix: Create spiral shapes
  • Fillets: Smooth sharp edges and corners
  • Patterns: Create repetitive patterns of a shape
  • Scripts: Automate repetitive modeling tasks
  • Assemblies: Build assemblies by combining multiple parts
  • Rendering: Generate photorealistic renders and animations

For example, the following script creates a parametric bolt using sweeps:

# Model a Bolt using Sweeps  

import Part

# Shaft
circleSketch = App.activeDocument().addObject('Sketcher::SketchObject','Sketch')
circleSketch.Placement = App.Placement(App.Vector(0.000000,0.000000,0.000000),App.Rotation(0.000000,0.000000,0.000000,1.000000))
circleSketch.addGeometry(Part.Circle(App.Vector(0.000000,0.000000,0.000000),App.Vector(0,0,1),10),False)

#Sweep shaft along helical path
shaft = circleSketch.Shape.extrude(App.Vector(0.000000,0.000000,50.000000))
shaft = shaft.makeHelix(360, 50.000000, 0.000000, False)  

# Head  
headSketch = App.activeDocument().addObject('Sketcher::SketchObject','Sketch001')
headSketch.Placement = App.Placement(App.Vector(0.000000,0.000000,50.000000),App.Rotation(0.000000,0.000000,0.000000,1.000000))
headSketch.addGeometry(Part.Circle(App.Vector(0.000000,0.000000,0.000000),App.Vector(0,0,1),20),False)

# Sweep head along straight path  
boltHead = headSketch.Shape.extrude(App.Vector(0.000000,0.000000,-20.000000))

# Union both parts
bolt = shaft.fuse(boltHead)

This covers the basics of getting started with the FreeCAD Python API. You can now start scripting your own models!

Command Line Modeling with CadQuery

CadQuery is a Python-based language for creating parametric 3D CAD models. By integrating with Python, it allows full programmatic control and automation for designing precise 3D models.

Introduction to CadQuery and Its Python Integration

CadQuery leverages the power of Python to enable scripting and automation of parametric CAD models. Here are some key things to know:

  • CadQuery is a domain-specific language that builds on top of Python to facilitate 3D modeling. It integrates tightly with Python APIs.
  • Scripts can be written to parameterize designs. Changes to parameters regenerate the 3D model automatically.
  • Complex shapes can be created through code rather than manual CAD modeling. Repetitive tasks can be automated.

This makes CadQuery ideal for programmatically generating 3D CAD models without traditional limitations.

CadQuery Examples: From Simple to Complex Models

CadQuery provides a range of examples demonstrating model creation, from simple shapes to intricate designs:

  • Simple shapes - Scripts for basic shapes like cubes, cylinders, spheres to learn the basics.
  • Mechanical parts - Models for screws, nuts, bolts, brackets show real-world utility.
  • Complex assemblies - Elaborate examples of engines, turbines reveal CadQuery's capabilities.

With the ability to parameterize and script entire designs, CadQuery enables creating elaborate 3D CAD models rapidly.

Experimenting with Polylines and Splines in CadQuery

CadQuery provides access to advanced modeling techniques like polylines and splines to define complex edges and shapes:

  • Polylines - Connected sequence of line segments, useful for angular routes.
  • Splines - Smooth curves passing through control points, ideal for organic shapes.

These can be leveraged in scripts to model intricacies like curved profiles, tapered edges, smooth contours, etc. far more efficiently.

Viewing Output DXF File and Example STL File

To use the 3D models created with CadQuery, they can be exported to standard file formats:

  • DXF - AutoCAD Drawing Exchange Format for 2D drawings and 3D wireframe geometry.
  • STL - Standard Tessellation Language format for 3D printing and other applications.

These files can be easily viewed and processed downstream using standard CAD and visualization software tools.

In summary, CadQuery coupled with Python enables unprecedented automation, precision, and flexibility in 3D modeling through scripting parametric designs programmatically.

Python 3D Rendering and Graphics Examples

Understanding Python 3D Rendering Techniques

Python has several libraries that can be used for 3D rendering, including FreeCAD, CadQuery, and PyVista. These provide tools to create 3D models programmatically and render them.

Some key techniques for 3D rendering with Python include:

  • Using modeling libraries like FreeCAD and CadQuery to construct 3D geometry procedurally via Python scripting. This involves combining primitive shapes, performing boolean operations, extruding profiles, etc.

  • Converting models to common exchange formats like IGES or STEP so they can be imported to other applications. Python libraries provide export capabilities.

  • Using dedicated 3D rendering libraries like PyVista to create scenes, position models, set up lighting and cameras, then render. This can generate still images or animations.

  • Viewing and manipulating models interactively with Python by integrating 3D viewports and controls, allowing inspection from all angles.

Overall, Python provides a versatile toolset for automating 3D modeling workflows, handling file conversions, setting up rendered scenes, and enabling interactive 3D visualization of designs.

Python 3D Graphics Example: Creating a Scene

Here is an example of using PyVista to set up and render a simple 3D scene with Python:

import pyvista as pv
from pyvista import examples

# Create plotting object 
plotter = pv.Plotter()

# Load model and position
model = examples.load_airplane()  
model.translate((-5, 0, 0))

# Add model to plotting scene
plotter.add_mesh(model)  

# Add box outline for context
box = pv.Box()
plotter.add_mesh(box, color='w')

# Set camera position
plotter.camera_position = [(6, 3, 8), (0, 0, 0), (0, 0, 1)]

# Render scene  
plotter.show()

This loads an airplane model, positions it in the scene, adds a box outline for context, sets up the camera, and renders an interactive view of the 3D scene. Many options exist to further customize the lighting, appearance, output format etc.

Helix Modeling and Viewing IGES Model

We can model a helix in CadQuery, then export it to IGES format:

import cadquery as cq

# Helix params
radius = 10
pitch = 5  
height = 50

# Construct Helix  
helix = cq.Workplane("XY" ).lineTo(0, height) \
           .helix(pitch, height, radius)

# Export IGES model  
helix.export('helix.igs')

The IGES file can then be opened with a Python 3D viewer to inspect:

import pyvistaqt as pvqt

# View IGES model
model = pvqt.BackgroundPlotter() 
model.load_iges('helix.igs')
model.show()  

This allows interactive viewing of the exported helix model from Python.

Viewing I Beam Example with Python 3D Model Viewer

To view a sample I beam model with Python:

import pyvista as pv
from pyvista import examples  

# Load I-beam model
ibeam = examples.load_ibeam()

# Create plotter
plotter = pv.PlotterITK()  

# Add model and display
plotter.add_mesh(ibeam)
plotter.show()

This loads the I beam model into a PyVista scene then launches the interactive viewer. We can pan, rotate and inspect the I beam from all angles. Advanced rendering effects could also be applied.

Using Python's 3D libraries enables rapid visualization for models created programmatically or loaded from standard exchange formats. This is useful for design, simulation and verification workflows.

Leveraging OpenCASCADE for Complex 3D CAD

OpenCASCADE is an open-source 3D modeling kernel that provides advanced CAD functionalities. Integrating OpenCASCADE with Python enables scripting precise and complex 3D models programmatically.

Introduction to OpenCASCADE and Python Integration

OpenCASCADE Technology (OCCT) is an open-source, multi-platform CAD kernel for developing complex 3D modeling applications and tools. The C++ libraries provide modeling capabilities like:

  • Advanced geometry operations - boolean operations, filleting, chamfers etc.
  • Topology data structure and algorithms
  • Visualization framework - for using various graphic drivers
  • Data exchange - import/export of CAD formats like STEP, IGES etc.

Python bindings like PythonOCC provide a handy way to script and automate OpenCASCADE using Python. Key benefits include:

  • Rapid prototyping of CAD models
  • Automating repetitive modeling tasks
  • Driving CAD through external data sources
  • Headless model generation and conversion

Overall, OpenCASCADE + PythonOCC allows developers to tap into the powerful CAD kernel via an easy-to-use, high-level scripting interface.

Scripting with OpenCASCADE for Precision 3D Models

OpenCASCADE enables creating precise CAD models programmatically by scripting. Some examples:

  • Design reusable parametric CAD components by scripting parameters.
  • Script complex surfaces like Bezier curves, splines etc.
  • Perform repetitive batch tasks like model cleanup and repair.
  • Generate customizable CAD templates from Python.

Key Python scripting techniques for precision CAD include:

  • Using available 3D primitives and operations from OCCT bindings.
  • Managing coordinate systems with placement and transformations.
  • Building complex topology by linking vertices, edges and wires.
  • Validating models using inbuilt validation tools.

Proper understanding of the topological data structure is critical for robust model scripting.

Exploring Workplanes and 3D Operations in OpenCASCADE

The notion of workplanes is essential to modeling with OpenCASCADE. Some ways to utilize workplanes:

  • Set up desired coordinate systems for further operations.
  • Sketch 2D profiles on standard planes or custom workplanes.
  • Execute 3D operations like extrusion, revolution with contextual workplane.
  • Position and align CAD models by working in specific workplane sub-spaces.

Common workplane operations through PythonOCC include:

  • Defining standard planes - XY, YZ, XZ
  • Building translated and rotated workplanes
  • Placing and aligning shapes in workplane contexts
  • Performing 3D operations like extrusion, fillet relative to active workplane.

Mastering workplanes unlocks the power of both 2D sketching and precise 3D modeling.

Advanced FreeCAD Scripting with OpenCASCADE

FreeCAD uses OpenCASCADE under the hood and allows advanced scripting leveraging its capabilities. Some examples:

  • Access low-level geometry like vertices, edges beyond basic shapes.
  • Build scripts agnostic of GUI constraints and reusability.
  • Drive model generation through spreadsheet data.
  • Headlessly batch process models for formatting and conversion.
  • Customize modeling workflows by scripting workbenches.

Key techniques for advanced FreeCAD scripting include:

  • Using FreeCAD as OpenCASCADE + Python scripting workspace.
  • Understanding technical details like application architecture, workbench structure etc.
  • Tapping into the lower-level OpenCASCADE APIs for advanced modeling.
  • Reusing modular scripts across GUI and headless workflows.

Robust understanding of the underlying OpenCASCADE architecture unlocks the full power of FreeCAD through versatile scripting.

Conclusion and Next Steps for Advancing Python 3D Modeling Skills

Python offers a versatile set of tools for 3D modeling, making it easier to automate repetitive tasks and customize modeling workflows. By following this guide, you should now have a basic understanding of how to:

  • Import and view 3D models using Python libraries like FreeCAD and cadquery
  • Script basic 3D shapes and operations using workplanes and CAD kernels
  • Output models to common file formats like STL for 3D printing

Here are some recommended next steps to continue advancing your Python 3D modeling skills:

  • Explore more complex CAD operations like lofts, sweeps, and assemblies
  • Try generating 3D models parametrically by varying input values
  • Learn how to create organic shapes using splines and surfaces
  • Integrate simulation and analysis tools like FEA or CFD
  • Contribute to open-source Python modeling libraries on GitHub
  • Look into GPU-accelerated libraries like PyVista for faster visualization

The world of design and manufacturing is rapidly adopting more automation, and knowing Python will let you tap into leading-edge technologies in fields like generative design, bio-modeling, and more. Keep practicing and you'll be well on your way!

Related posts

Read more