### Locate SolidPython Examples Directory Source: https://github.com/solidcode/solidpython/blob/master/Doc/index.md Prints the absolute path to the SolidPython examples directory. This is useful for learning how SolidPython works by examining provided examples. ```python import os, solid; print(os.path.dirname(solid.__file__) + '/examples') ``` -------------------------------- ### Install SolidPython from GitHub Source: https://github.com/solidcode/solidpython/blob/master/Doc/index.md Instructions for installing the development version of SolidPython directly from its GitHub repository using pip. ```bash pip install git+https://github.com/SolidCode/SolidPython.git ``` -------------------------------- ### Install SolidPython using pip Source: https://github.com/solidcode/solidpython/blob/master/README.rst Provides instructions for installing the SolidPython library using pip, the Python package installer. It includes commands for installing the latest release from PyPI and the development version from GitHub. ```bash pip install solidpython ``` ```bash pip install git+https://github.com/SolidCode/SolidPython.git ``` -------------------------------- ### Install SolidPython using pip Source: https://github.com/solidcode/solidpython/blob/master/Doc/index.md Instructions for installing the latest release of SolidPython from PyPI using pip. It also mentions the option of using sudo and recommends virtual environments for dependency management. ```bash pip install solidpython ``` -------------------------------- ### Install Jupyter Renderer (Bash) Source: https://github.com/solidcode/solidpython/blob/master/README.rst Installs the ViewSCAD package for rendering SolidPython or OpenSCAD code in Jupyter notebooks. Additional installation steps may be required, refer to the ViewSCAD repository. ```bash pip install viewscad ``` -------------------------------- ### SolidPython Operator Syntax Examples Source: https://context7.com/solidcode/solidpython/llms.txt Demonstrates the use of Python operators (+, -, *) for constructive solid geometry operations like union, difference, and intersection with SolidPython objects. ```python from solid import cube, sphere, scad_render # Pythonic operator syntax (equivalent to above) pythonic = cube(20, center=True) - sphere(r=13) # Complex combination using operators base = cube([30, 30, 5], center=True) hole = cylinder(r=5, h=10, center=True) cutout = cube([25, 10, 10], center=True) # Union with +, difference with -, intersection with * result = base - hole - cutout # Intersection example box = cube(20, center=True) ball = sphere(r=15) rounded_cube = box * ball # Keeps only overlapping volume print(scad_render(result)) ``` -------------------------------- ### Generate OpenSCAD Code from Python Source: https://github.com/solidcode/solidpython/blob/master/README.rst Demonstrates how to use SolidPython to create OpenSCAD objects like differences between shapes and render them to SCAD code. It shows a basic example of creating a cube and a sphere and subtracting the sphere from the cube. ```python from solid import * from solid.utils import * d = difference()( cube(10), sphere(15) ) print(scad_render(d)) ``` -------------------------------- ### Generate OpenSCAD Code from Python (Advanced) Source: https://github.com/solidcode/solidpython/blob/master/Doc/index.md This example showcases more complex SolidPython usage, combining geometric primitives and transformations using operator overloading. It utilizes the 'solid' and 'solid.utils' modules to create a more concise representation of the desired OpenSCAD structure. ```python from solid import * from solid.utils import * d = cube(5) + right(5)(sphere(5)) - cylinder(r=2, h=6) ``` -------------------------------- ### Generate Animated OpenSCAD File with SolidPython Source: https://context7.com/solidcode/solidpython/llms.txt This example demonstrates how to create an animated OpenSCAD file using `scad_render_animated_file`. It defines a function `animate_assembly` that takes a time parameter (`_time`) and returns a union of shapes whose properties (rotation, position, scale) change over time. The `scad_render_animated_file` function generates the animation sequence. ```python from solid import scad_render_animated_file, cube, sphere, cylinder from solid import translate, rotate, union from math import sin, cos, pi def animate_assembly(_time=0): """ Function called for each animation frame. _time ranges from 0 to 1 over the animation cycle. """ # Rotate a cube based on time angle = _time * 360 rotating_cube = rotate([0, 0, angle])( cube([20, 5, 5], center=True) ) # Oscillate a sphere up and down z_offset = 15 * sin(_time * 2 * pi) bouncing_sphere = translate([0, 0, 10 + z_offset])( sphere(r=5) ) # Grow and shrink a cylinder scale_factor = 0.5 + 0.5 * sin(_time * 2 * pi) pulsing_cylinder = translate([25, 0, 0])( cylinder(r=8 * scale_factor, h=10, center=True) ) return union()(rotating_cube, bouncing_sphere, pulsing_cylinder) # Generate animated SCAD file # Open in OpenSCAD and enable View -> Animate scad_render_animated_file( func_to_animate=animate_assembly, steps=60, # Number of frames in animation back_and_forth=True, # Reverse animation at end filepath='animation.scad' ) # In OpenSCAD: # 1. Open the generated file # 2. View -> Animate # 3. Set FPS (e.g., 30) and Steps (e.g., 60) ``` -------------------------------- ### Draw Arcs with SolidPython Source: https://github.com/solidcode/solidpython/blob/master/Doc/index.md Demonstrates how to draw arcs using the `arc` and `arc_inverted` functions in SolidPython. These functions allow specifying radius, start, and end degrees for creating curved shapes. ```python from solid import arc # Draws an arc of radius 10 counterclockwise from 90 to 210 degrees. arcs = arc(rad=10, start_degrees=90, end_degrees=210) # Draws the portion of a 10x10 square NOT in a 90 degree circle of radius 10. arc_inverted_shape = arc_inverted(rad=10, start_degrees=0, end_degrees=90) ``` -------------------------------- ### Combine Shapes and Operations in SolidPython Source: https://github.com/solidcode/solidpython/blob/master/README.rst Illustrates a more complex SolidPython example combining multiple shapes and operations like addition (union), translation, and subtraction. This snippet shows how to create a cube, add a translated sphere, and subtract a cylinder. ```python from solid import * from solid.utils import * d = cube(5) + right(5)(sphere(5)) - cylinder(r=2, h=6) # To generate the OpenSCAD code: # print(scad_render(d)) # To save to a file: # scad_render_to_file(d, 'output.scad') ``` -------------------------------- ### Create a bottle profile using Catmull-Rom splines Source: https://context7.com/solidcode/solidpython/llms.txt Demonstrates creating a 2D bottle profile using Catmull-Rom splines and mirroring the result to form a complete 3D-ready polygon. ```python def bottle_shape(width=4, height=10): neck_width = width * 0.4 neck_height = height * 0.2 w2, nw2, h, nh = width/2, neck_width/2, height, neck_height profile_pts = [ Point2(nw2, h), Point2(nw2, h - nh), Point2(w2, h - nh - h/6), Point2(w2, 0.5), Point2(w2 - 0.5, 0), Point2(0, 0), ] half_profile = catmull_rom_points(profile_pts, close_loop=False) half_profile.insert(0, Point2(0, h)) half = polygon(half_profile) return half + mirror([1, 0])(half) bottle = bottle_shape() scad_render_to_file(bottle, filepath='splines_example.scad') ``` -------------------------------- ### Importing SolidPython modules Source: https://github.com/solidcode/solidpython/blob/master/Doc/index.md Demonstrates the standard way to import SolidPython and its utility functions at the beginning of a Python script. It highlights that importing 'solid.utils' is optional but recommended for enhanced functionality. ```python from solid import * from solid.utils import * # Not required, but the utils module is useful ``` -------------------------------- ### Importing and Using OpenSCAD Modules Source: https://github.com/solidcode/solidpython/blob/master/README.rst Demonstrates how to import external OpenSCAD files as Python modules or via global namespace inclusion. This allows calling SCAD modules directly from Python code. ```scad module box(w,h,d){ cube([w,h,d]); } ``` ```python from solid import * # Import as module scadfile = import_scad('/path/to/scadfile.scad') b = scadfile.box(2,4,6) scad_render_to_file(b, 'out_file.scad') # Include in global namespace use('/path/to/scadfile.scad') b = box(2,4,6) scad_render_to_file(b, 'out_file.scad') ``` -------------------------------- ### OpenSCAD vs SolidPython Syntax Source: https://github.com/solidcode/solidpython/blob/master/Doc/index.md Compares the syntax for creating a 'difference' operation in both raw OpenSCAD and SolidPython. It illustrates how SolidPython uses parentheses and commas to represent blocks, contrasting with OpenSCAD's curly braces. ```openscad difference(){ cube(10); sphere(15); } ``` ```python d = difference()( cube(10), # Note the comma between each element! sphere(15) ) ``` -------------------------------- ### Define Parts and Generate BOM with SolidPython Source: https://context7.com/solidcode/solidpython/llms.txt Demonstrates how to use the @bom_part decorator to attach metadata to geometric parts. It includes an assembly function to combine parts and methods to generate formatted BOM reports in text or CSV formats. ```python @bom_part("M3x12 Socket Head Cap Screw", per_unit_price=0.15, currency="USD", Supplier="McMaster-Carr", Part_Number="91290A117") def m3x12_screw(): head = cylinder(r=2.75, h=3) shaft = cylinder(r=1.5, h=12) return union()(head, translate([0, 0, -12])(shaft)) def assembly(): b = bracket() for x in [-15, 0, 15]: b += translate([x, 0, 2.5])(m3x12_screw()) b += translate([x, 0, -2.5 - 2.4])(m3_nut()) return b model = assembly() scad_render_to_file(model, filepath='assembly.scad', file_header='$fn=32;') bom_report = bill_of_materials(model) print(bom_report) ``` -------------------------------- ### SolidPython Utility Function: up() Source: https://github.com/solidcode/solidpython/blob/master/Doc/index.md Demonstrates the use of the `up()` utility function from `solid.utils` for translating objects vertically. It offers a more readable alternative to `translate([0,0,z])`. ```python up(10)( cylinder() ) ``` -------------------------------- ### Basic OpenSCAD Structure in SolidPython Source: https://github.com/solidcode/solidpython/blob/master/README.rst Explains the fundamental difference in syntax between OpenSCAD and SolidPython for defining code blocks. OpenSCAD uses curly braces {}, while SolidPython uses parentheses () with comma-separated arguments. ```python from solid import * # SolidPython equivalent of OpenSCAD's difference(){ # cube(10); # sphere(15); # } d = difference()( cube(10), sphere(15) ) ``` -------------------------------- ### Import OpenSCAD Libraries in SolidPython Source: https://context7.com/solidcode/solidpython/llms.txt Shows how to integrate external OpenSCAD files and libraries into a SolidPython project. Covers the use of import_scad for modular access, as well as use() and include() for global namespace integration. ```python from solid.objects import import_scad, use, include # Import a single .scad file my_lib = import_scad('/path/to/my_library.scad') # Import an entire directory mcad = import_scad('MCAD') # Use and include for global scope use('/path/to/library.scad') include('/path/to/library.scad') ``` -------------------------------- ### Generate OpenSCAD Code from Python (Basic) Source: https://github.com/solidcode/solidpython/blob/master/Doc/index.md This snippet demonstrates the basic functionality of SolidPython, converting a simple Python expression involving a cube and a sphere into OpenSCAD code. It requires the 'solid' library and uses 'scad_render' to output the SCAD string. ```python from solid import * d = difference()( cube(10), sphere(15) ) print(scad_render(d)) ``` -------------------------------- ### Generate Bezier curves and polygons Source: https://context7.com/solidcode/solidpython/llms.txt Shows how to define cubic Bezier curves using control points to create smooth shapes or extract raw points for custom geometry. ```python bezier_controls = [ Point2(0, 0), Point2(1, 3), Point2(3, 3), Point2(4, 0), ] bezier_shape = bezier_polygon( bezier_controls, subdivisions=30, extrude_height=3, show_controls=True ) curve_pts = bezier_points(bezier_controls, subdivisions=25) curve_pts.extend([Point2(3, -2), Point2(1, -2)]) custom_shape = polygon(curve_pts) + control_points(bezier_controls) scad_render_to_file(bezier_shape, filepath='bezier_example.scad') ``` -------------------------------- ### Generate Splines with SolidPython Source: https://github.com/solidcode/solidpython/blob/master/Doc/index.md Shows how to create Catmull-Rom and Bezier curves using functions from `solid.splines`. It requires the `euclid3` library for point definitions and `solid.translate` for positioning. ```python from solid import translate from solid.splines import catmull_rom_polygon, bezier_polygon from euclid3 import Point2 points = [ Point2(0,0), Point2(1,1), Point2(2,1), Point2(2,-1) ] # Generate a Catmull-Rom polygon through control points. shape = catmull_rom_polygon(points, show_controls=True) # Generate a Bezier polygon with specified subdivisions. bezier_shape = translate([3,0,0])(bezier_polygon(points, subdivisions=20)) ``` -------------------------------- ### SolidPython Scale and Mirror Transformations Source: https://context7.com/solidcode/solidpython/llms.txt Illustrates scaling SolidPython objects uniformly or non-uniformly and mirroring them across a plane using the `scale` and `mirror` functions. These functions return callables that apply the transformation. ```python from solid import cube, sphere, scale, mirror, scad_render box = cube(10, center=True) # Scale uniformly scaled = scale([2, 2, 2])(box) # Scale non-uniformly stretched = scale([3, 1, 0.5])(box) # Mirror across the YZ plane (reflect in X) mirrored = mirror([1, 0, 0])(box) print(scad_render(stretched)) ``` -------------------------------- ### Import OpenSCAD Code with use() Source: https://github.com/solidcode/solidpython/blob/master/Doc/index.md Imports OpenSCAD code using the `use()` statement, which places modules into the global namespace. This can be an alternative to `import_scad()`, though it may pollute the global scope. ```python from solid import * # use() puts the module `box()` into the global namespace use('/path/to/scadfile.scad') b = box(2,4,6) scad_render_to_file(b, 'out_file.scad') ``` -------------------------------- ### Render SolidPython Object to SCAD File Source: https://context7.com/solidcode/solidpython/llms.txt The `scad_render_to_file` function renders a SolidPython object to a specified file path. It supports options to include the original Python source code as comments and to add a custom file header, which is useful for setting OpenSCAD variables like `$fn` for resolution. ```python from solid import scad_render_to_file, cylinder, union, translate SEGMENTS = 48 # Create a simple assembly base = cylinder(r=20, h=5, center=True) pillar = translate([0, 0, 5])(cylinder(r=5, h=20)) assembly = union()(base, pillar) # Write to file with custom resolution setting file_path = scad_render_to_file( assembly, filepath='my_model.scad', file_header=f'$fn = {SEGMENTS};', include_orig_code=True # Appends Python source as comments ) print(f"SCAD file written to: {file_path}") ``` -------------------------------- ### SolidPython Animation Rendering Source: https://github.com/solidcode/solidpython/blob/master/Doc/index.md Shows how to render animated OpenSCAD scenes using SolidPython's `scad_render_animated_file()` function, leveraging OpenSCAD's special `$t` variable for animation. ```python # See solid/examples/animation_example.py for more details. ``` -------------------------------- ### Recursive Directory Import Source: https://github.com/solidcode/solidpython/blob/master/README.rst Shows how to import entire OpenSCAD libraries, such as MCAD, to access multiple namespaces within a single Python object. ```python from solid import * mcad = import_scad('MCAD') mount = mcad.motors.stepper_motor_mount(nema_standard=17) scad_render_to_file(mount, 'motor_mount_file.scad') ``` -------------------------------- ### Create Arcs and Fillets with SolidPython Utilities Source: https://context7.com/solidcode/solidpython/llms.txt Utilizes the solid.utils module to generate arc segments and inverted arcs. These are essential for creating rounded edges and fillets in parametric 3D models. ```python from solid.utils import arc, arc_inverted # Create a standard arc quarter_arc = arc(rad=20, start_degrees=0, end_degrees=90, segments=32) # Create an inverted arc for fillets fillet = arc_inverted(rad=5, start_degrees=0, end_degrees=90) ``` -------------------------------- ### Import OpenSCAD Code with solid.import_scad() Source: https://github.com/solidcode/solidpython/blob/master/Doc/index.md Imports OpenSCAD code from a specified file path. Relative paths are resolved against OpenSCAD library directories. This function can also recursively import entire directories. ```python from solid import * scadfile = import_scad('/path/to/scadfile.scad') b = scadfile.box(2,4,6) scad_render_to_file(b, 'out_file.scad') ``` ```python from solid import * # MCAD is OpenSCAD's most common utility library: https://github.com/openscad/MCAD # If it's installed for OpenSCAD (on MacOS, at: ``$HOME/Documents/OpenSCAD/libraries``) mcad = import_scad('MCAD') # MCAD contains about 15 separate packages, each included as its own namespace print(dir(mcad)) # => ['bearing', 'bitmap', 'boxes', etc...] mount = mcad.motors.stepper_motor_mount(nema_standard=17) scad_render_to_file(mount, 'motor_mount_file.scad') ``` -------------------------------- ### SolidPython Basic Operators for CSG Source: https://github.com/solidcode/solidpython/blob/master/Doc/index.md Demonstrates the use of overloaded basic operators (+ for union, - for difference, * for intersection) in SolidPython, providing a more concise syntax for Constructive Solid Geometry operations. ```python c = cylinder(r=10, h=5) + cylinder(r=2, h=30) c = cylinder(r=10, h=5) c -= cylinder(r=2, h=30) ``` -------------------------------- ### SolidPython Directional Utilities Source: https://context7.com/solidcode/solidpython/llms.txt Introduces intuitive directional transformation functions (`up`, `down`, `left`, `right`, `forward`, `back`) from `solid.utils` that simplify common `translate` operations. ```python from solid import cube, cylinder, union from solid.utils import up, down, left, right, forward, back base = cube([30, 30, 5], center=True) pillar = cylinder(r=3, h=20) # Stack objects using directional functions assembly = union()( base, up(2.5)(pillar), # Move up (positive Z) up(2.5)(right(10)(pillar)), # Move up and right (positive X) up(2.5)(left(10)(pillar)), # Move up and left (negative X) up(2.5)(forward(10)(pillar)), # Move up and forward (positive Y) up(2.5)(back(10)(pillar)), # Move up and back (negative Y) ) # Directional functions can be chained complex_move = up(20)(right(15)(forward(10)(cube(5)))) ``` -------------------------------- ### SolidPython Color Application Source: https://context7.com/solidcode/solidpython/llms.txt Demonstrates how to apply colors to SolidPython objects for visualization in OpenSCAD's preview mode using the `color` function. It supports RGB values, RGBA values, CSS color names, and hex codes. ```python from solid import cube, cylinder, color, union, translate, scad_render # Color using RGB values (0-1 range) red_cube = color([1, 0, 0])(cube(10)) # Color with alpha (transparency) transparent_blue = color([0, 0, 1, 0.5])(sphere(r=8)) # Color using CSS color names green_cylinder = color("green")(cylinder(r=5, h=20)) # Hex color codes also work orange_box = color("#FFA500")(cube(15, center=True)) assembly = union()( red_cube, translate([15, 0, 0])(green_cylinder), translate([30, 0, 0])(orange_box) ) print(scad_render(assembly)) ``` -------------------------------- ### Rotate Extrusion with SolidPython Source: https://context7.com/solidcode/solidpython/llms.txt Creates a solid of revolution by rotating a 2D profile around the Z-axis. Supports full or partial revolutions. Requires the 'solid' library. ```python from solid import polygon, rotate_extrude, scad_render, translate # Profile for a vase (must be in positive X, will rotate around Z) vase_profile = [ [20, 0], # base [22, 5], [15, 30], # narrow waist [25, 50], # wide top [23, 55], [18, 55], # inner lip [20, 50], # inner wall follows outer [12, 30], [18, 5], [15, 0] # base inner ] profile_2d = polygon(vase_profile) # Full 360-degree revolution vase = rotate_extrude(segments=120)(profile_2d) # Partial revolution (180 degrees) half_vase = rotate_extrude(angle=180, segments=60)(profile_2d) print(scad_render(vase)) ``` -------------------------------- ### Generate Splines with SolidPython (Python) Source: https://github.com/solidcode/solidpython/blob/master/README.rst Generates smooth Catmull-Rom curves and Bezier curves using functions from solid.splines. Requires the euclid3 library for Point2 objects. Demonstrates creating a polygon shape from control points. ```python from solid import translate from solid.splines import catmull_rom_polygon, bezier_polygon from euclid3 import Point2 points = [ Point2(0,0), Point2(1,1), Point2(2,1), Point2(2,-1) ] shape = catmull_rom_polygon(points, show_controls=True) bezier_shape = translate([3,0,0])(bezier_polygon(points, subdivisions=20)) ``` -------------------------------- ### Render SolidPython Object to OpenSCAD String Source: https://context7.com/solidcode/solidpython/llms.txt The `scad_render` function converts a SolidPython object tree into a string of valid OpenSCAD code. This is the primary method for generating the final SCAD output from Python definitions. It takes a SolidPython object as input and returns its OpenSCAD representation. ```python from solid import scad_render, cube, sphere, difference # Create a simple shape: cube with spherical cavity shape = difference()( cube(10, center=True), sphere(r=6) ) # Render to OpenSCAD code string scad_code = scad_render(shape) print(scad_code) # Output: # difference(){ # cube(size = 10, center = true); # sphere(r = 6.0000000000); # } ``` -------------------------------- ### SolidPython Hole and Part Management Source: https://context7.com/solidcode/solidpython/llms.txt Explains and demonstrates the `hole()` and `part()` modifiers for managing negative space and object interactions. `hole()` ensures an object is always subtracted, while `part()` allows objects to fill holes. ```python from solid import cylinder, cube, union, scad_render_to_file from solid.objects import hole, part from solid.utils import up, right, FORWARD_VEC from solid import rotate def pipe_with_hole(): """Create a pipe where the inner void stays empty during unions""" pipe_od = 12 # outer diameter pipe_id = 10 # inner diameter length = 30 outer = cylinder(r=pipe_od, h=length, center=True) inner = cylinder(r=pipe_id, h=length + 2, center=True) # Mark inner cylinder as a hole - it will always be subtracted pipe = outer + hole()(inner) return pipe def intersecting_pipes(): """Two pipes that share a continuous internal void""" pipe_a = pipe_with_hole() pipe_b = rotate(a=90, v=FORWARD_VEC)(pipe_with_hole()) # The holes remain empty at the intersection return pipe_a + pipe_b def bolt_in_hole(): """Demonstrate part() to allow objects inside holes""" # Create a block with an explicit hole block = cube(20, center=True) hole_cyl = cylinder(r=3, h=25, center=True) block_with_hole = block - hole()(hole_cyl) # Mark the block as a "part" so bolts can be inserted block_part = part()(block_with_hole) # Create a bolt that fits in the hole bolt = cylinder(r=2, h=30, center=True) bolt += up(12)(cylinder(r=4, h=3, center=True)) # bolt head # The bolt appears inside the hole because block is a "part" return block_part + bolt assembly = intersecting_pipes() + right(50)(bolt_in_hole()) scad_render_to_file(assembly, filepath='holes_example.scad', file_header='$fn=120;') ``` -------------------------------- ### Render 3D Text Labels with solid.utils.label Source: https://github.com/solidcode/solidpython/blob/master/Doc/index.md Converts a multi-line string into a 3D OpenSCAD object. It allows customization of font, alignment, spacing, and extrusion depth. ```python from solid.utils import label # Create a 3D label object text_obj = label( a_str="Hello SolidPython", width=20, size=12, depth=1.0, font="Arial" ) ``` -------------------------------- ### Geometric Utilities for Vector Math and Filleting Source: https://github.com/solidcode/solidpython/blob/master/Doc/index.md Provides utility functions for 2D vector cross products, determining turn direction, and applying fillets to polygon corners. These tools facilitate complex geometric manipulations within SolidPython. ```python from solid.utils import cross_2d, direction_of_bend, fillet_2d # Calculate cross product of two 2D vectors val = cross_2d((1, 0), (0, 1)) # Determine if a sequence of points turns left or right turn = direction_of_bend((0,0), (1,1), (2,0)) # Apply a fillet to a polygon corner rounded_poly = fillet_2d(three_point_sets=[((0,0), (1,1), (2,0))], orig_poly=my_poly, fillet_rad=0.5) ``` -------------------------------- ### Utility Functions for Transformations Source: https://github.com/solidcode/solidpython/blob/master/README.rst SolidPython provides utility functions like up(), down(), left(), and right() to make spatial transformations more readable compared to standard translate() calls. ```python up(10)(cylinder()) # Equivalent to translate([0,0,10])(cylinder()) ``` -------------------------------- ### Analyze OpenSCAD difference operation structure Source: https://github.com/solidcode/solidpython/blob/master/TODO_SolidPython.txt This snippet demonstrates the structure of a difference operation in OpenSCAD, showing how unions and transformations are nested. It highlights a known issue where parent transforms of hole objects are incorrectly placed in the positive section of the generated code. ```openscad $fn = 12; difference() { union() { union(); union() { translate(v = [0, 0, 2.5000000000]) { cube(center = true, size = [50, 50, 5]); } translate(v = [18.0000000000, 18.0000000000]) { } } } union(){ union(){ translate(v = [18.0000000000, 18.0000000000]){ union() { translate(v = [0, 0, -0.0050000000]) { cylinder(h = 5.0100000000, r = 2.5000000000, center = false); } } } } } } ``` -------------------------------- ### Catmull-Rom Spline Polygon with SolidPython Source: https://context7.com/solidcode/solidpython/llms.txt Generates a smooth polygon using Catmull-Rom splines through specified control points. Supports subdivisions, extrusion, and visualization of control points. Requires 'solid' and 'euclid3' libraries. ```python from euclid3 import Point2, Vector2 from solid import scad_render_to_file, polygon, mirror from solid.splines import catmull_rom_polygon, catmull_rom_points, control_points # Define control points control_pts = [ Point2(0, 0), Point2(1, 2), Point2(3, 2), Point2(4, 0), ] # Simple closed polygon through all points simple_shape = catmull_rom_polygon(control_pts) # With more options detailed_shape = catmull_rom_polygon( control_pts, subdivisions=30, # More subdivisions = smoother curve extrude_height=5, # Extrude to 3D show_controls=True, # Show red markers at control points center=True # Center the extrusion vertically ) # Get just the points for custom processing curve_points = catmull_rom_points(control_pts, subdivisions=20, close_loop=True) custom_polygon = polygon(curve_points) # Open curve with custom tangents open_curve = catmull_rom_points( control_pts, subdivisions=20, close_loop=False, start_tangent=Vector2(-1, 1), # Affects curve start direction end_tangent=Vector2(1, -1) # Affects curve end direction ) ``` -------------------------------- ### Extrude Along Path with SolidPython Source: https://context7.com/solidcode/solidpython/llms.txt Sweeps a 2D shape along an arbitrary 3D path. Supports scaling, rotation, and custom transforms along the path. Requires 'solid' and 'euclid3' libraries. ```python from math import cos, sin, pi, tau from euclid3 import Point2, Point3 from solid import scad_render_to_file from solid.utils import extrude_along_path, frange def star_shape(num_points=5, outer_rad=10, inner_rad=5): """Create a star-shaped cross section""" points = [] for i in range(2 * num_points): rad = outer_rad if i % 2 == 0 else inner_rad angle = tau / (2 * num_points) * i points.append(Point3(rad * cos(angle), rad * sin(angle), 0)) return points def circular_path(radius=50, num_points=120): """Create a circular path in the XY plane""" return [ Point3(radius * cos(a), radius * sin(a), 0) for a in frange(0, tau, num_steps=num_points) ] def helix_path(radius=30, height=60, turns=3, num_points=200): """Create a helical path""" return [ Point3( radius * cos(turns * tau * i / num_points), radius * sin(turns * tau * i / num_points), height * i / num_points ) for i in range(num_points) ] # Basic extrusion along circular path shape = star_shape() path = circular_path() ring = extrude_along_path(shape_pts=shape, path_pts=path, connect_ends=True) # Extrusion with scaling (grows from 0.5x to 1.5x) scales = [0.5 + i / len(path) for i in range(len(path))] scaled_ring = extrude_along_path(shape, path, scales=scales, connect_ends=True) # Extrusion with rotation (one full twist) twisted = extrude_along_path(shape, path, rotations=[360], connect_ends=True) # Extrusion along helix with 2D scaling helix = helix_path() xy_scales = [Point2(1 + 0.3*cos(6*tau*i/len(helix)), 1 + 0.3*sin(6*tau*i/len(helix))) for i in range(len(helix))] spring = extrude_along_path( shape_pts=star_shape(num_points=6, outer_rad=8, inner_rad=4), path_pts=helix, scales=xy_scales, cap_ends=True ) scad_render_to_file(ring, filepath='path_extrude.scad') ``` -------------------------------- ### Managing Negative Space with hole() Source: https://github.com/solidcode/solidpython/blob/master/README.rst The hole() function simplifies the creation of voids within parts, ensuring that specified geometry remains empty regardless of subsequent additions. ```python outer = cylinder(r=pipe_od, h=seg_length) inner = cylinder(r=pipe_id, h=seg_length) pipe_a = outer - hole()(inner) ``` -------------------------------- ### Create Cylinder/Cone Source: https://context7.com/solidcode/solidpython/llms.txt The `cylinder` function generates a cylinder or a cone. For a standard cylinder, specify radius (`r`) and height (`h`). For a cone or frustum, use `r1` for the bottom radius and `r2` for the top radius. The `center` parameter can be used to center the cylinder vertically. ```python from solid import cylinder, scad_render # Simple cylinder pipe = cylinder(r=10, h=30) # Centered cylinder centered_pipe = cylinder(r=10, h=30, center=True) # Cone (different top and bottom radii) cone = cylinder(r1=15, r2=5, h=25) # High-resolution cylinder smooth_pipe = cylinder(r=10, h=30, segments=120) print(scad_render(cone)) # Output: cylinder(r1 = 15, r2 = 5, h = 25); ``` -------------------------------- ### Create Cube/Rectangular Prism Source: https://context7.com/solidcode/solidpython/llms.txt The `cube` function generates a cube or rectangular prism. It can create a simple cube by specifying a single dimension or a rectangular prism with separate dimensions for length, width, and height. The `center` parameter can be used to position the object's origin at its center. ```python from solid import cube, scad_render # Simple cube with side length 10 simple_cube = cube(10) # Rectangular prism with specific dimensions, centered box = cube([20, 10, 5], center=True) print(scad_render(box)) # Output: cube(size = [20, 10, 5], center = true); ``` -------------------------------- ### SolidPython Translate Transformation Source: https://context7.com/solidcode/solidpython/llms.txt Shows how to move SolidPython objects in 3D space using the `translate` function. It takes a vector and returns a callable that applies the translation to a given object. ```python from solid import cube, translate, scad_render box = cube(10) # Move 20 units in X, 15 in Y, 5 in Z moved_box = translate([20, 15, 5])(box) print(scad_render(moved_box)) ``` -------------------------------- ### Generate 3D Screw Thread with solid.screw_thread.thread Source: https://github.com/solidcode/solidpython/blob/master/Doc/index.md Creates a 3D screw thread by sweeping a 2D polygon outline along a spiral path. It calculates a single complex polyhedron and supports custom parameters for pitch, radius, and necking. ```python from solid.screw_thread import thread # Define a simple triangular cross-section outline = [(0, 0), (2, 1), (0, 2)] # Generate the screw thread object my_screw = thread( outline_pts=outline, inner_rad=10.0, pitch=5.0, length=20.0, external=True ) ``` -------------------------------- ### Linear Extrusion with SolidPython Source: https://context7.com/solidcode/solidpython/llms.txt Extrudes a 2D shape along the Z-axis. Supports options for height, twist, scaling, and extrusion of text. Requires the 'solid' library. ```python from solid import polygon, linear_extrude, scad_render, text # Simple linear extrusion star_points = [ [0, 10], [2, 4], [10, 4], [4, 0], [6, -8], [0, -3], [-6, -8], [-4, 0], [-10, 4], [-2, 4] ] star_2d = polygon(star_points) star_3d = linear_extrude(height=20)(star_2d) # Extrusion with twist (360 degrees over the height) twisted_star = linear_extrude(height=30, twist=360, slices=100)(star_2d) # Extrusion with scaling (tapers from 1x to 0.5x) tapered_star = linear_extrude(height=25, scale=0.5)(star_2d) # 3D text label = linear_extrude(height=2)( text("Hello", size=10, font="Liberation Sans") ) print(scad_render(twisted_star)) ``` -------------------------------- ### Generate internal and external screw threads Source: https://context7.com/solidcode/solidpython/llms.txt Utilizes the screw_thread module to sweep profiles along a helix, supporting both standard cylindrical and tapered threads. ```python tooth_height = 2 tooth_depth = 1.5 thread_profile = default_thread_section(tooth_height, tooth_depth) external_screw = thread( outline_pts=thread_profile, inner_rad=8, pitch=2.5, length=25, external=True ) internal_thread = thread( outline_pts=thread_profile, inner_rad=8 + tooth_depth, pitch=2.5, length=10 + EPSILON, external=False ) threaded_nut = difference()(cylinder(r=15, h=10, segments=6), internal_thread) scad_render_to_file(external_screw, filepath='screw_thread.scad', file_header='$fn=48;') ``` -------------------------------- ### Project 3D Point/Vector to 2D in SolidPython Source: https://github.com/solidcode/solidpython/blob/master/Doc/index.md Converts a 3D point or vector (Point3 or Vector3) into its 2D equivalent (Point2 or Vector2) by simply discarding the Z coordinate. This is useful for 2D projections or when Z is irrelevant. ```python from solid.utils import project_to_2D from solid import Point3, Vector3 p3 = Point3(1, 2, 3) v3 = Vector3(4, 5, 6) # Project a Point3 to Point2 p2 = project_to_2D(p3) print(f"Projected Point3 {p3} to {p2}") # Project a Vector3 to Vector2 v2 = project_to_2D(v3) print(f"Projected Vector3 {v3} to {v2}") ``` -------------------------------- ### Create Box with Rounded Interior Corners using SolidPython Source: https://context7.com/solidcode/solidpython/llms.txt This snippet defines a function `box_with_fillets` that creates a rectangular box with rounded interior corners. It uses `polygon` to define the basic rectangle and `arc_inverted` with `translate` to add the fillet material to each corner. The resulting shape is then extruded and saved to an OpenSCAD file. ```python from solid import polygon, translate, arc_inverted, union, linear_extrude from solid import scad_render_to_file def box_with_fillets(width, height, fillet_rad): # Basic rectangle box = polygon([ [0, 0], [width, 0], [width, height], [0, height] ]) # Add fillet material to each corner corners = [ translate([fillet_rad, fillet_rad])( arc_inverted(fillet_rad, 180, 270) ), translate([width - fillet_rad, fillet_rad])( arc_inverted(fillet_rad, 270, 360) ), translate([width - fillet_rad, height - fillet_rad])( arc_inverted(fillet_rad, 0, 90) ), translate([fillet_rad, height - fillet_rad])( arc_inverted(fillet_rad, 90, 180) ), ] return box + union()(*corners) filleted_box = linear_extrude(10)(box_with_fillets(40, 30, 5)) scad_render_to_file(filleted_box, filepath='fillets.scad', file_header='$fn=32;') ``` -------------------------------- ### Generate Solid Polygon from 2D Path in SolidPython Source: https://github.com/solidcode/solidpython/blob/master/Doc/index.md Directly returns an OpenSCAD `polygon()` object representing an area with a specified width around a given set of points. It simplifies the process compared to `path_2d` when the goal is to create a renderable polygon. ```python from solid.utils import path_2d_polygon from solid import Point2, polygon points = [Point2(0, 0), Point2(10, 0), Point2(10, 10), Point2(0, 10)] width = 2.0 # Create a polygon object with a width around the points solid_polygon = path_2d_polygon(points, width=width, closed=True) # To render this, you would typically use OpenSCAD's polygon function # For demonstration, we'll just print the type print(f"Generated object type: {type(solid_polygon)}") # If you were to use it in OpenSCAD code: # poly = polygon(path_2d_polygon(points, width=width, closed=True)) # print(poly.openscad()) ``` -------------------------------- ### Draw Arc in Python Source: https://github.com/solidcode/solidpython/blob/master/README.rst Draws an arc using the arc() function. Specifies radius and start/end degrees for counterclockwise drawing. Dependencies: SolidPython library. ```python from solid import arc arc(rad=10, start_degrees=90, end_degrees=210) ``` -------------------------------- ### SolidPython Rotate Transformation Source: https://context7.com/solidcode/solidpython/llms.txt Demonstrates rotating SolidPython objects around the origin or a specified axis using the `rotate` function. It supports single angle rotation, rotation around a vector, and Euler angles. ```python from solid import cylinder, rotate, scad_render pipe = cylinder(r=5, h=30) # Rotate 45 degrees around Z axis rotated_z = rotate(a=45)(pipe) # Rotate around specific axis rotated_axis = rotate(a=90, v=[1, 0, 0])(pipe) # 90 degrees around X # Rotate with Euler angles [X, Y, Z] rotated_euler = rotate(a=[45, 30, 60])(pipe) print(scad_render(rotated_axis)) ``` -------------------------------- ### Create 3D Polyhedron Source: https://context7.com/solidcode/solidpython/llms.txt The `polyhedron` function constructs a 3D polyhedron from a list of vertices and a list of faces. Each face is defined by the indices of the vertices that form it, typically in counter-clockwise order when viewed from the outside. The `convexity` parameter can affect rendering behavior. ```python from solid import polyhedron, scad_render # Define a simple pyramid points = [ [0, 0, 0], # 0: base corner [10, 0, 0], # 1: base corner [10, 10, 0], # 2: base corner [0, 10, 0], # 3: base corner [5, 5, 10] # 4: apex ] # Define faces (vertices in counter-clockwise order when viewed from outside) faces = [ [0, 1, 2, 3], # base [0, 4, 1], # front [1, 4, 2], # right [2, 4, 3], # back [3, 4, 0] # left ] pyramid = polyhedron(points=points, faces=faces, convexity=2) print(scad_render(pyramid)) ``` -------------------------------- ### Operator Overloading for CSG Operations Source: https://github.com/solidcode/solidpython/blob/master/README.rst SolidPython supports standard Python operators (+, -, *) to represent union, difference, and intersection operations, simplifying complex geometry definitions. ```python c = cylinder(r=10, h=5) + cylinder(r=2, h=30) # Union c -= cylinder(r=2, h=30) # Difference ``` -------------------------------- ### Create Sphere Source: https://context7.com/solidcode/solidpython/llms.txt The `sphere` function creates a spherical object. It can be defined by its radius (`r`) or diameter (`d`). Additional parameters like `segments` can be used to control the resolution of the sphere in the generated OpenSCAD code. ```python from solid import sphere, scad_render # Sphere with radius 15 ball = sphere(r=15) # Sphere with diameter 30 and higher resolution detailed_ball = sphere(d=30, segments=96) print(scad_render(detailed_ball)) # Output: sphere(d = 30, $fn = 96); ``` -------------------------------- ### Create 2D Path Polygon in SolidPython Source: https://github.com/solidcode/solidpython/blob/master/Doc/index.md Generates a list of points defining a path of a given width around a sequence of input points. This is suitable for creating polygons. If `closed` is True, the resulting polygon will have a hole, requiring special handling when using the `polygon()` function. ```python from solid.utils import path_2d from solid import Point2 points = [Point2(0, 0), Point2(10, 0), Point2(10, 10)] width = 1.0 # Create a path for an open shape path_points_open = path_2d(points, width=width, closed=False) print(f"Path points (open): {path_points_open}") # Create a path for a closed shape (will have a hole) path_points_closed = path_2d(points, width=width, closed=True) print(f"Path points (closed): {path_points_closed}") ```