Skip to main content

A 3D grafics library based on turtle

Project description

๐Ÿข TurtleGL-3d

A 3D graphics library based on Python turtle and OpenGL-style rendering techniques.

An object-oriented, intuitive Python 3D graphics library based on the turtle library.


โœจ Features

  • ๐ŸŽฅ Camera System โ€” Independent camera object supporting perspective / cabinet / isometric / orthographic projection modes.
  • ๐ŸŽจ Scene Management โ€” Structured scene object supporting line, face, and texture data management.
  • ๐Ÿ“ 3D Function Plotting โ€” 3D function image plotting based on plot3d object.
  • ๐Ÿ“ฆ Volume Calculation โ€” Ray method volume calculation supporting multi-directional checks and partitioning acceleration.
  • ๐Ÿ–ผ๏ธ Texture Mapping โ€” Homography matrix-based texture mapping.
  • ๐ŸŒ— Shading & Normal โ€” Three rendering modes: material preview / shadow mode / normal preview.
  • ๐Ÿ“ OBJ Import โ€” Support for importing .obj 3D models with normal correction.
  • ๐ŸŽฌ Image & Video Export โ€” OpenCV-based image export and video compositing.
  • ๐Ÿ”„ Transform โ€” Spatial transformations: rotation, translation, scaling, etc.
  • ๐Ÿ“Š Depth Sorting โ€” Depth sorting algorithms for different projection modes.

๐Ÿ“ฆ Installation

pip install TurtleGL-3d

Dependencies

  • Python >= 3.8
  • numpy >= 1.24.4
  • opencv-python >= 4.12.0

๐Ÿš€ Quick Start

Basic Example: Drawing a Colorful Cube

import turtleGL

# Instantiate the camera
camera = turtleGL.camera()
camera.camera_position = [100, 100, 100]
camera.to_target([0, 0, 0])       # Face the origin
camera.camera_focal = 300          # Focal length
camera.type = 1                    # Perspective mode
camera.rend = 1                    # Shadow mode

# Instantiate the scene
scene = turtleGL.scene()
scene.face = [
    [[[50, 50, 0], [-50, 50, 0], [-50, -50, 0], [50, -50, 0]], '#FF0000'],
    [[[50, 50, 100], [-50, 50, 100], [-50, -50, 100], [50, -50, 100]], '#00FF00'],
    [[[50, 50, 0], [50, 50, 100], [50, -50, 100], [50, -50, 0]], '#0000FF'],
    [[[-50, 50, 0], [-50, -50, 0], [-50, -50, 100], [-50, 50, 100]], '#FFFF00'],
    [[[50, 50, 0], [-50, 50, 0], [-50, 50, 100], [50, 50, 100]], '#FF00FF'],
    [[[-50, -50, 0], [50, -50, 0], [50, -50, 100], [-50, -50, 100]], '#00FFFF'],
]

# Depth sorting and drawing
camera.draw_from_scene(scene.sort_all_avg(camera.camera_position))
camera.done()

Importing an OBJ Model

import turtleGL, math

camera = turtleGL.camera('OBJ Example')
camera.camera_position = [-101, -121, -150]
camera.to_target([0, 0, 50])
camera.camera_focal = 500
camera.ray = [1, 1, -1]
camera.type = 1
camera.rend = 1

scene = turtleGL.scene()
scene.import_obj('model.obj', 50, '#66ccff')  # Scale 50x, specify color
scene.check_obj_norm('model.obj')              # Correct normals
scene.generate_line('#ffffff')                  # Generate edges

# Rotation animation
for i in range(360):
    camera.clear()
    camera.camera_position = [150 * math.cos(math.radians(i)),
                               150 * math.sin(math.radians(i)),
                               150]
    camera.to_target([0, 0, 0])
    camera.draw_from_scene(scene.sort_all_avg(camera.camera_position))
    camera.update()

3D Function Plotting

import turtleGL

camera = turtleGL.camera('Plot3D Example')
camera.type = 0  # Cabinet mode

scene = turtleGL.plot3d()
scene.xlim = [-100, 100]
scene.ylim = [-100, 100]
scene.step = 10

def function(x, y):
    return 0.01 * (x**2 - y**2)

scene.generate_face(function)
scene.generate_line(function, color='#000000')
camera.draw_from_scene(scene.sort_all_cabin())
camera.done()

Volume Calculation

import turtleGL

camera = turtleGL.camera()
camera.camera_position = [10, 120, 10]
camera.to_target([0, 0, 0])
camera.camera_focal = 500
camera.type = 1
camera.rend = 1

scene = turtleGL.scene()
scene.import_obj('model.obj', 50, '#66ccff')
scene.check_obj_norm('model.obj')
scene.triangulation()       # Triangulation is required for volume calculation
scene.generate_line('#ff0000')

volume = turtleGL.volume()
volume.sample_distance = 5   # Sampling distance
volume.check = True          # Multi-directional check
volume.allow_edge = True     # Allow edge intersections
volume.volume(scene.face)    # Calculate volume

camera.draw_from_scene(scene.sort_line_avg(camera.camera_position))
for i in volume.points:
    camera.dot(i)
camera.done()

Texture Mapping & Image Export

import turtleGL

camera = turtleGL.camera('Texture Example')
camera.camera_position = [201, 201, 131]
camera.to_target([0, 0, 50])
camera.camera_focal = 500
camera.type = 1
camera.rend = 1

scene = turtleGL.scene()
scene.tex = [
    [[[50, 50, 100], [-50, 50, 100], [-50, -50, 100], [50, -50, 100]], 'grass_up.png'],
    [[[50, 50, 0], [-50, 50, 0], [-50, -50, 0], [50, -50, 0]], 'grass_bottom.png'],
]

# Render and export using OpenCV
camera.image_size = [700, 700]
camera.create_image('#ffffff')
camera.draw_from_scene_cv2(scene.sort_all_avg(camera.camera_position))
camera.imshow()       # Display
camera.imwrite('output.png')  # Save image

๐Ÿ“– API Reference

Camera Object

The camera object handles 3D to 2D projection and rendering.

Attributes

Attribute Type Default Description
camera_position [x,y,z] [0,0,0] Camera position
camera_direction [x,y,z] [0,0,1] Camera look direction
camera_rotation float 0 Camera rotation angle (radians), causing left/right tilt
camera_focal float 1 Focal length
point_behind_cam_type int 0 Handling method for points behind the camera (0/1/2/3)
point_behind_cam_allow_count int 0 Number of allowed behind-camera points during material rendering
ray [x,y,z] [0,0,-1] Light direction, used for shading
rend int 0 Rendering type: 0 material preview / 1 shadow mode / 2 normal preview
shade_value int 128 Multiply factor for shading (0-255)
pensize int 2 Pen size (only affects lines)
pencolor str '#000000' Pen color (only affects lines)
type int 1 Camera type: 0 cabinet / 1 perspective / 2 isometric / -1 orthographic
grating_size [x,y] [500,400] Raster rendering area size
grating_length int 1 Raster sampling step
image_size [x,y] [500,400] Export image size
image ndarray [] Currently stored OpenCV image

Handling Points Behind the Camera

Mode Description
0 No processing; points behind the camera appear in the opposite direction
1 Flip UV to bring points back to normal orientation
2 Use orthographic mode with small deviation
3 Use scaled orthographic perspective

Rendering Modes

Mode Description
0 โ€” Material Preview Faces display the specified color directly
1 โ€” Shadow Mode Shadows calculated based on angle between light direction and normal; backlit faces use the multiply factor
2 โ€” Normal Mode Normal direction cosine relative to camera direction > 0 displays blue, otherwise red

Methods

# Basic Setup
setposition([x,y,z])          # Set camera position
setdirection([x,y,z])         # Set camera direction
setfocal(x)                   # Set focal length
settype(x)                    # Set projection type (supports 'focal'/'cabin'/'isometric')
to_target([x,y,z])            # Point camera toward target
status()                      # Print current camera attributes

# Coordinate Mapping
pointfocal([x,y,z])           # Perspective: 3D โ†’ 2D mapping, returns [[u,v], bool]
pointcabinet([x,y,z])         # Cabinet: 3D โ†’ 2D mapping
pointisometric([x,y,z])       # Isometric: 3D โ†’ 2D mapping
pointorthografic([x,y,z])     # Orthographic: 3D โ†’ 2D mapping
pointfocal_inverse([u,v])     # Perspective: 2D โ†’ 3D inverse mapping

# Drawing (turtle rendering)
dot([x,y,z], color)           # Draw a single point
drawline(linedata)            # Draw an edge
drawface(facedata)            # Draw a face
drawtex(facedata)             # Draw texture
draw_from_scene(scenedata)    # Draw integrated data
draw_axis(l)                  # Draw coordinate axes
write(point, str)             # Write text at a 3D position

# Drawing (OpenCV rendering)
drawline_cv2(linedata)        # Draw edge with OpenCV
drawface_cv2(facedata)        # Draw face with OpenCV
drawtex_cv2(facedata)         # Draw texture with OpenCV
draw_from_scene_cv2(scenedata)# Draw integrated data with OpenCV

# Image Export
create_image(bgcolor)         # Initialize image (can be called repeatedly to clear)
imshow()                      # Display current image
imwrite(path)                 # Save image to file
capture(path, index)          # Capture frame by index (for video frames)
to_video(path, fps=30)        # Compose video

# Raster Algorithm (experimental)
grating(face)                 # Perform raster calculation
grating_cv2(face)             # Raster with OpenCV
show_grating_limit()          # Show rendering area border

# Utilities
tracer(t)                     # Control animation switch
delay()                       # Delay
clear()                       # Clear canvas
bgcolor(color)                # Set background color
update()                      # Update canvas
done()                        # Prevent window from closing automatically

Scene Object

The scene object stores line, face, and texture data, and supports spatial transformations and depth sorting.

Data Format

# Edge data
[[[x1,y1,z1], [x2,y2,z2]], '#RRGGBB']

# Face data (enter vertices in counterclockwise order; normal points outward)
[[[x1,y1,z1], [x2,y2,z2], ..., [xn,yn,zn]], '#RRGGBB']

# Texture data (4 vertices, color replaced by image path)
[[[x1,y1,z1], [x2,y2,z2], [x3,y3,z3], [x4,y4,z4]], 'texture.png']

Attributes

Attribute Description
line List of edge data
face List of face data
tex List of texture data
center Center point of the scene

Methods

# Add Data
addline([[x1,y1,z1],[x2,y2,z2],'#color'])   # Add an edge
addface([[x1,y1,z1],...,[xn,yn,zn],'#color'])# Add a face

# Import/Export
import_line(path)              # Import line data (CSV)
import_face(path)              # Import face data (CSV)
export_line(path)              # Export line data (CSV)
export_face(path)              # Export face data (CSV)

# OBJ Model
import_obj(path, scale, color) # Import OBJ model (random color if color is empty)
import_obj_normal(path)        # Import OBJ normal data
check_obj_norm(path)           # Correct face orientation based on normals
add_obj(filepath, scale, color)# Import OBJ and append to existing face data

# Spatial Transformations
rotate(rotate_vector, center)  # Rotate around center (rotation vector in radians)
move(move_vector)              # Translate
scale(scale_vector, center)    # Scale
rotate_edge()                  # Cycle edges (change triangulation partition)

# Depth Sorting โ€” Perspective/Orthographic Modes
sort_line_avg(camera_pos)      # Sort edges (modifies object attribute and returns)
sort_face_avg(camera_pos)      # Sort faces
sort_tex_avg(camera_pos)       # Sort textures
sort_all_avg(camera_pos)       # Sort all (returns data without modifying object)

# Depth Sorting โ€” Cabinet Mode
sort_line_cabin()              # Sort edges
sort_face_cabin()              # Sort faces
sort_tex_cabin()               # Sort textures
sort_all_cabin()               # Sort all

# Depth Sorting โ€” Isometric Mode
sort_line_isometric()          # Sort edges
sort_face_isometric()          # Sort faces
sort_tex_isometric()           # Sort textures
sort_all_isometric()           # Sort all

# Other
reverse_normvect(i)            # Reverse normal direction of the i-th face
generate_line(color)           # Generate edges from face data
triangulation()                # Triangulate faces
get_center()                   # Calculate and return the scene center point

Plot3D Object

Object for drawing 3D function graphs, similar to Scene but data generation depends on the target function.

Attributes

Attribute Default Description
xlim [-10, 10] X domain
ylim [-10, 10] Y domain
step 1 Sampling step
line [] Edge data
face [] Face data
center [0,0,0] Center point

Methods

generate_face(func, color=True)  # Generate face data for the function (auto color by height)
generate_line(func, color)       # Generate edge data for the function
rotate(rotate_vector, center)    # Rotate
move(move_vector)                # Translate
scale(scale_vector, center)      # Scale
# Same depth sorting methods as Scene

Volume Object

Volume calculation object using ray casting to determine if a point is inside a closed triangular mesh.

Attributes

Attribute Default Description
points [] List of interior points after calculation
sample_distance 1 Sampling grid spacing
grid_limit inf Threshold for enabling partitioning acceleration (triangle count)
check True Enable multi-directional check
allow_edge True Allow counting edge intersections

Methods

volume(scene_face_data)  # Calculate volume, return all interior points

โš ๏ธ The partitioning acceleration (grid_limit) is only recommended for convex polyhedra; irregular shapes may produce erroneous results.


๐Ÿงช Experimental: Rasterization

Raster algorithm is experimental and not yet stable.

scene.triangulation()             # Triangulate faces (raster mode only supports triangles)
camera.grating_size = [500, 400]  # Set rendering area size
camera.show_grating_limit()       # Show rendering area border
camera.grating(face)              # Execute raster calculation

In rendering mode rend=1, raster mode does not use shadow calculation but computes the light path.


๐ŸŽฌ Image & Video Export

Since turtle itself does not support image capture, the library provides OpenCV-based image/video export:

# Initialization
camera.image_size = [500, 400]
camera.create_image('#ffffff')    # Create image (can be called repeatedly to clear)

# Rendering
camera.draw_from_scene_cv2(scene_data)  # Render with OpenCV

# Export
camera.imwrite('output.png')     # Save image

# Video creation
camera.capture('frames', i)      # Save frames by index โ†’ ./frames/00000001.png
camera.to_video('frames')        # Compose video โ†’ frames.mp4

๐Ÿ“ Project Structure

turtleGL-3d/
โ”œโ”€โ”€ pyproject.toml
โ”œโ”€โ”€ setup.py
โ”œโ”€โ”€ LICENSE
โ”œโ”€โ”€ README.md
โ”œโ”€โ”€ README_zh.md
โ””โ”€โ”€ src/
    โ””โ”€โ”€ turtleGL/
        โ”œโ”€โ”€ __init__.py
        โ”œโ”€โ”€ src/
        โ”‚   โ”œโ”€โ”€ camera.py      # Camera object
        โ”‚   โ”œโ”€โ”€ scene.py       # Scene object
        โ”‚   โ”œโ”€โ”€ plot3d.py      # 3D function plot object
        โ”‚   โ””โ”€โ”€ volume.py      # Volume calculation object
        โ””โ”€โ”€ example/

๐Ÿ“„ License

This project is licensed under the Apache License 2.0 โ€” see the LICENSE file for details.


๐Ÿ”— Links

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

turtlegl_3d-1.2.7.tar.gz (40.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

turtlegl_3d-1.2.7-py3-none-any.whl (42.1 kB view details)

Uploaded Python 3

File details

Details for the file turtlegl_3d-1.2.7.tar.gz.

File metadata

  • Download URL: turtlegl_3d-1.2.7.tar.gz
  • Upload date:
  • Size: 40.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.6

File hashes

Hashes for turtlegl_3d-1.2.7.tar.gz
Algorithm Hash digest
SHA256 ef376b0a63c2c4fbe559febef98ede5ad70368b8ad894730f106e5982fa1c33f
MD5 25aec9a9875bdcfc8df79388aa66b68a
BLAKE2b-256 00742796939a4c08e0b139c904a3a2bf6310c05fbb1a6d38ae8a11339cde19ca

See more details on using hashes here.

File details

Details for the file turtlegl_3d-1.2.7-py3-none-any.whl.

File metadata

  • Download URL: turtlegl_3d-1.2.7-py3-none-any.whl
  • Upload date:
  • Size: 42.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.6

File hashes

Hashes for turtlegl_3d-1.2.7-py3-none-any.whl
Algorithm Hash digest
SHA256 e8a8d4c61b7e6604a6194a4ab08dcf6b38b1a2dc8f9d287a942ead7a8a31574f
MD5 7a1a9c5d61663a4bfe6c19f4a566539a
BLAKE2b-256 ff6c1b8a0f070b1dbb6e79853e9d8d8b6831f5f6fcdcc80a76a80936c1d79120

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page