Tag: 3D Printing

PySLM Release – Version 0.6

After a long period, PySLM version 0.6 is released. This coincides with the intensity of commitments as a new academic at the University of Nottingham over the past year. The release has mainly focused on improvements and enhancements to the underlying codebase rather than the addition of entirely new features. There are several substantial changes to the underlying dependencies that contributes some improvements and performance throughout which PySLM users will benefit from.

Dependency changes

With the release of ClipperLib2 library, additional python bindings were exposed and released as a separate library in the PyClipr. These were created using the PyBind11 headers and provides the core functionality required to performing offsetting and clipping of path segments and hatch vectors. There are no substantial feature improvements inherited from the change, but a noticeable performance improvement can be observed. Another benefit is that PySLM does not require compilation via cython and is now a full source distribution available via PyPi repositories.

Another significant dependency change is the use of the manifold mesh Boolean library. This offers a substantial improvement to mesh manipulation operations, that are fundamental to successful support generation for use in metal L-PBF. The library provides robust intersection of water-tight meshes, that is also computationally efficient when compared to the prior PyClipr library which was based on the clipr library from over a decade ago. This significantly improves the quality of the volumes generated in BlockSupportBase and those derived from these such as those with the GridTrussSupport that provide perforations and teeth for metal L-PBF. Additionally, this removes an additional dependency that requires maintenance by myself, and is more cross-platform that what can be offered by the previous PyClipr library.

Further incremental changes, that will not affect users is migration to the Shapely 2.0 library and also Trimesh 4.0, which required some internal changes to maintain compatibility.

Support Generation Improvements:

The support generation has been improved to be more robust and reliable compared to the initial release in version 0.5.0. Further robustness checks are implemented in the ray-tracing method developed in version 0.5, for identifying correctly the support projection height maps which are used to identify boundaries of the support volume. Further use has been explored in applied research by TWI – see open access paper (An Interactive Web-Based Platform for Support Generation and Optimisation for Metal Laser Powder Bed Fusion) by Dimopoulos et al.

By default all BlockSupport‘s have smoothed boundaries by the use of spline fitting, which was previously only applied on self-intersecting supports. Smooth boundaries significantly improve the quality of the final GridBlockSupport, because the perforated grid truss skin can more smoothly conform to the boundary of the support volume.


Smoothed boundaries generated for all SupportVolumes for a complex part: including both self-intersecting supports and those only connected to the build-plate

As a recommendation to users, care must be taken to not smoothen the boundaries too much or these will not correctly conform to the original geometry causing the ray-projection algorithm to fail. A recommending starting point for the spline simplification factor is between 5-30, but is dependent on the relative part scale. Coinciding with the use of the manifold3d library, there is an appreciable improvement in the speed for generating the support volumes.

Another improvement is the more configurable parameters for Grid Truss Support generation. This includes further enhancement and control over the perforated teeth, across both upper and lower support volume surfaces. These are fully customisable by a user function, which ensure that a repeating shape is conformed in 3D across the surface profiles of the support volume.

Finally, a significant enhancement is correctly pre-sorting the scan vectors within the sliced support regions to take advantage of the line segments when scanning by the beam source. This significantly improves build productivity by minimising jumps across adjacent segments and ensures that the galvo-mirror movement remains mostly in the same direction.

A layer showing the order of scanning across all grid truss support generated for a complex topology optimised part. Jump distance is a total of 2056 mm with a total scan vector length 1377 mm.

Documentation Improvements

Further improvements to the inline documentation have been included alongside improvements and examples that are now provided on readthedocs. These provide basic information and guides for using PySLM, some of which is consolidated from these blog entries to aid new users using the library. Over time these will be further enhanced and amended to support researchers and users wishing to use PySLM in their work.

Conclusions & Change Log

The release has taken a while to release, but overall has received a level of polish and refinement that helps the release find use amongst more in commercially vested R&D projects and academic research. There are other developments still in the pipeline but much focus was on providing a long-term stable release for users. The full changelog can be found here.

GPU 3D Printing Slicer for DLP/Jetting using PySLM

Anycubic Digital Light Projection (DLP) 3D Printer System used for Slicing
Anycubic DLP 3D Printer System

Digital Light Projector (DLP) 3D Printers are an exceptionally productive technique for producing highly detailed (30<𝝁m) parts at high speeds at minimal costs.The CLIP process is a further enhancement in build speeds.

Briefly, the DLP process is similar to Stereolithography (SLA). It cures a vat of UV curable polymer material above a flexible transparent PTFE membrane. Instead of a single exposure (UV laser) into the resin, a monochrome LCD screen is used to mask the UV exposure source underneath. A greyscale bitmap image is used for each layer. Typically for most systems, after exposing the layer (1.5-3 s), the upper build-platform retracts, and mechanically pulls the cured layer away from the flexible membrane and the process is repeated. Surprisingly simple, but effective in cost and the production speed.

Additionally, bitmap based approaches are used amongst Material Jetting (MJ) technologies predominantly used within our research group CfAM, at Nottingham. Both DLP and Material Jetting offer high resolution between 30-100 𝝁m both in the XY slice plane dependent on the printer, and for Inkjet downwards of 1-10 𝝁m layer thickness depending on the choice of ink loading. Accordingly, these high resolutions are demanding to print. I came accustomed to using these printers in our CfAM lab at Nottingham on a recent project. The affordability of these printers is genuinely remarkable, owing to their mechanical simplicity.

Based on a previous post back in 2016 by Dr Matt Keeter, this is an excellent reference to an approach using WebGL implementation. Their post introduced the method, but the approach was obscured by its WebGL based implementation. Frutstratingly, I never came across an implementation for use in a research environment. These appraoches are most likely used in the free slicer software provided for desktop DLP 3D Printers.

DLP 3D Printer - Anycubic Mono 4k - Nottingham Lab
Anycubic Mono 4k DLP Printer at the University of Nottingham’s CfAM Lab loaded with a composite ink. 2022.

Interestingly, this approach can also be extended for generating 3D voxel models, by applying the project across multiple directions. However, the reliability of such method for non-manifold meshes would likely be limiting.

Method for Bitmap Slicing

The method is similar and use the same infrastructure to that used in the previous post for performing height map ray projection. Likewise, to provide a cross-platform compatibility, the use of Vispy and OpenGL 2.0 GLSL shaders are utilised within a single script. As such, the resolution of the output is limited to the maximum framebuffer size supported by the GPU driver on the system.

The approach for generating slices relies on having a connected watertight with surface triangles normals correctly orientated (fixable natively using Trimesh). The approach uses a combination of Stencil buffers integrated natively in GPU hardware.

By choosing an appropriate Z-clipping plane for the camera, the Stencil buffer is used to keep and discard rasterised triangles with the z-clipping range based on the Z-order. In order to determine if the fragments rendered are inside or outside the mesh. The render pipeline uses three passes:

  • Pass 1: stencil buffer increments on front facing fragments
  • Pass 2: stencil buffer decrements on back facing fragments
  • Pass 3: discard fragments where the stencil buffer is zero

During all the render passes, GL Depth tests are turned off. Typically in 3D Programs, triangles that are obscured from view of the 3D camera, or hidden behind other triangles are culled and the fragment is discarded prior to rendering . In this method, depth testing is turned off. The full approach is detailed further in the excerpt below inside the on_draw call.

def on_draw(self, event):

    with self._fbo:
        # Set the GL state
        gloo.set_state(blend=False, stencil_test=True, depth_test=False, polygon_offset_fill=False, cull_face=False)

        # Set the size of the framebuffer to fit the geometry with the correct aspect ratio
        gloo.set_viewport(0, 0, self._visSize[0], self._visSize[1])
        gloo.set_clear_stencil(0)
        gloo.set_clear_color((0.0, 0.0, 0.0, 0.0))
        
        # Clear the framebuffer
        gloo.clear()

        self.program['bounds'] = self.bbox[0,2], self.bbox[1,2]
        self.program['aspect'] = self.physical_size[1] /  self.physical_size[0]
        
        # The position of the slice position passed to the GLSL shader
        self.program['frac'] = self._z * 2.0 

        # Draw twice, adding and subtracting values in the stencil buffer

        # Render Pass 1 (Increment Stencil Buffers)
        gloo.set_stencil_func('always', 0, 0xff)
        gloo.set_stencil_op('keep', 'keep', 'incr', 'back')
        gloo.set_stencil_op('keep', 'keep', 'keep', 'front')
        self.program.draw('triangles', self.filled_buf)

        # Render Pass 2 (Decrease Stencil Buffers)
        gloo.set_stencil_op('keep', 'keep', 'decr', 'front')
        gloo.set_stencil_op('keep', 'keep', 'keep', 'back')
        self.program.draw('triangles', self.filled_buf)

        # Clear only the color buffer
        gloo.clear(color=True, depth=False, stencil=False)

        # Render Pass 3
        gloo.set_stencil_func('notequal', 0, 0xff)
        gloo.set_stencil_op('keep', 'keep', 'keep')
        self.program.draw('triangles', self.filled_buf)

        # Store the final framebuffer 
        self.rgb = _screenshot((0, 0, self._visSize[0], self._visSize[1]))

The GLSL shaders are not particularly interesting. Focus should be given to the Vertex shader, rather than the Fragment shader. This Vertex shader processes vertices of the mesh and applies the Model View Projection (MVP) transformation matrix onto the input mesh. The MVP matrix is chosen to scale the entire geometry so that it fits within the Z-clipping range of Z = -1 to +1, and is within the scope of rendering into Stencil buffer whilst using the 3D Orthographic Camera. Finally, the model is transformed based on a fractional range (0-1) to obtain the required Z-slicing plane. An epsilon value is provided for round-off purposes.

uniform   mat4 u_model; // Model transform matrix
uniform   mat4 u_view;
uniform   mat4 u_projection;

uniform  vec2 bounds; // Z bounds
uniform  float frac;  // Z fraction (0 to 1)
uniform  float aspect; // Aspect ratio

attribute vec3 a_position;

#define EPSILON 0.001

void main() {

    vec3 pos = a_position;
    
    // Ensure the bottom of the part is positioned to z=0 using the bottom bounding box
    pos.z -= bounds[0];
    
    // Scale the so that it fits within the clipping range (-1.0 < z < 1.0)
    pos.z *= -2.0/(bounds[1]-bounds[0]);
    
    // Adjust the position of  the verticies 
    pos.z -= frac;  
    gl_Position = u_projection * u_view * u_model * vec4(pos, 1.0);
    gl_Position.z += 1.0 - EPSILON;
}

The remainder of the script sets up the infrastructure for Vispy. This is performed within the initialisation call for the script. This methods sets up the correct OpenGL state, viewport size including the use of an off-screen render and specific selection of a separate Stencil framebuffer used to render onto. Both the vertex and fragment shaders are compiled and the transformation matrix is generated based on an Orthographic projection sized to the bounding box of the geometry.


    # Window Size
    shape = int(self._visSize[1]), int(self._visSize[0])

    # Create the render texture used by default in the pipeline
    self._rendertex = gloo.Texture2D((shape + (4,)), format='rgba', internalformat='rgba32f')
    
    # These are not used but are for reference
    #self._colorBuffer = gloo.RenderBuffer(self.shape, format='color')
    #self._depthRenderBuffer = gloo.RenderBuffer(shape, format='depth')

    # Create the stencil buffer (8 bit component)
    self._stencilRenderBuffer = gloo.RenderBuffer(shape, format='stencil')
    self._stencilRenderBuffer.resize(shape, format=gloo.gl.GL_STENCIL_INDEX8)

    # Create FBO, attach the color buffer and depth buffer
    self._fbo = gloo.FrameBuffer(self._rendertex)
    self._fbo.stencil_buffer=self._stencilRenderBuffer

    # Set the size of the view port based on the size of the window (the bounding box)
    gloo.set_viewport(0, 0, self.physical_size[0], self.physical_size[1])
    gloo.set_viewport(0, 0, self._visSize[0], self._visSize[1])

    # Create the initial orthographic view projection transformation based on the bounding box of the geometry
    self.projection = ortho(self.bbox[1, 0], self.bbox[0, 0], self.bbox[1, 1], self.bbox[0, 1], 2, 40)
    # Identity matrix
    self.model = np.eye(4, dtype=np.float32)

     # Set MVP variables for shaders
    self.program['u_projection'] = self.projection
    self.program['u_model'] = self.model
    self.program['u_view'] = self.view

Other operations are processing and the Trimesh and correctly transformed into the correct position:

The script was applied to a porous aerofoil structure with an XY resolution of 20 µm that was used previously on an Anycubic DLP system. Below is an example cross-section taken using this approach. Notice the high resolution

GPU 3D Printing Slicer used on an aerofoil structure

Conclusions

The overall approach may have a limited use by itself. Generally, the need to bespoke high resolution slices are limited at this stage. For reference, the full excerpt of the script is temporarily located here. In future, I will consider including this as another option within PySLM.

The source code can be found below or on GitHub:

Overhang and Support Structures in L-PBF (SLM) using PySLM: (Part III)

Following on from the previous post in Part II, this post will detail the methodology for ‘Grid Block’ support generation, which is one of the most commonly utilised support structure used especially in the selective laser melting process.

The definition of a volumetric block support region is illustrated shown below for an example topology optimised bracket. These are projected volume regions that extend vertically dowwards from the original overhang surface, that conforms exactly with the input mesh.

PySLM: Support Structures suitable for 3D Printing - The use of Volume Block Support Regions identified for overhang regions
Volume Block Support Structures extruded from overhang un-supported regions for a topology optimised bracket

Prior to starting this work, two approaches for generating ‘block‘ based support structures seem to exist. However, these approaches did not seem satisfactory especially when it came to their use using cost models.

The first approach identified, typically employed in FDM based processes, obtains the support or overhang regions and then generated a 2D polygon region that is the flattened or projection of this surface. The polygon is incrementally generated for each slice layer and a combination of boolean operations and offsetting operations are used to detect self intersections with existing geometry to modify its shape. It’s a robust method and can generate support features to aid manufacturing. The limitation of this approach is it cannot generate a volume, or an explicit mesh geometry. Rather a discretionary of the geometry containing slices representing the region with a sparse infill.

The second approach would appear to voxelise or generates a levelset of the geometry. Under support regions, the voxel grid is filled to create the in-fill support regions. The volume region can be re-constructed into a support structure and a truss structure can be generated inside. This method is not able to generate clean meshes of the support volume and requires a discretisation of the original geometry.

The following method proposed uses a hybrid mesh approach in order to generate clean meshes using fairly conventional boolean CSG library. The actual support structure generated uses relies on using 2D polygons to generate complex features such as perforation holes or structures.

Overall Support Module Structure Summary

The overall support module, in its current state for version 0.5, is split into the following structure. The generation of supports is performed by a utility ‘generator‘ class BaseSupportGenerator and incidentally their derived classes:

These classes perform the overhang and support analysis to extract the overhang surfaces. From the overhang surface, the support volumes are then generated using these to provide the inputs used to generate specific support objects that may have a specific style. For the objects representing the actual support structures, and regions, these are split into the following classes:

  • SupportStructure – Base class defining a part’s surface requiring support
  • BlockSupportBase – Generates support block volumes for providing a region to support
  • GridBlockSupport – Generates a support with a grid trust suitable for SLM

Overhang and Support Area Identification

The first step, widely available amongst all CAD and pre-processing software is overhang identification. Determining the face angles is a trivial process and in PySLM may be obtained using the following function pyslm.support.getSupportAngles. The function takes the trimesh object and calculates the dot product of the surface normal across the mesh. Upon obtaining the dot product, the angle between the vectors is calculated and for convenience is converted from rads to degrees. Further explanation is provided in a previous post.

# Normal to the Z Plane
v0 = np.array([[0., 0., -1.0]])

#Identify Support Angles
v1 = part.geometry.face_normals

# Calculate the angle (degrees) between the face normals and the Z-plane 
theta = np.arccos(np.clip(np.dot(v0, v1.T), -1.0, 1.0))
theta = np.degrees(theta).flatten()

Upon obtaining the surface angles, the overhang mesh regions can be extracting from the originating mesh, similar to that used in pyslm.support.getOverhangMesh. A comparison to a threshold overhang or support angle is made and used as a mask to extract the face indices from the mesh in order to obtain a new mesh. It is common that the overhang regions are disconnected. These can optionally be split using trimesh.split , which uses the internal connectivity of vertices in the mesh in a connected-component algorithm to isolate separate regions.

# Extract a list of faces that are below the critical overhangeAngle specified
supportFaceIds = np.argwhere(theta > 180 - overhangAngle).flatten()

# Create the overhang mesh by splitting the meshing when needed.
overhangMesh = trimesh.Trimesh(vertices=part.geometry.vertices,
                               faces=part.geometry.faces[supportFaceIds])
if splitMesh:
    return overhangMesh.split(only_watertight=False)

Splitting the mesh is far more convenient in terms of processing the support structures. It also improves the performance by reducing the projected area when performing ray intersections to identify an approximate volume.

For convenience, the overhang angles of any mesh can be show in 3D using the pyslm.visualise.visualiseOverhang function.

Identifying Support Volumes

Providing a robust method for obtaining the projected support volume is not a straightforward task, especially without sophisticated boolean operation tools. Through some experimentation with the given software libraries available, the following process offered a satisfactory result without a reasonably long computational cost.

Summary of method

The following operations are performed to generate block supports:

  1. Support regions (3D mesh surface) are separated into meshes
  2. Each support region mesh is flattened into a polygon and the contour is offset
  3. Surface region is extruded to z=0
  4. Intersection test using a Boolean Mesh Intersection operation is performed to check if self-intersection with part
  5. If self-intersection exist a ray-projection height map is created
    1. Side surfaces are removed from the intersection
    2. Ray projections are made separately on upward facing and downward facing faces and the height map is built up
  6. The gradient of the height-map is used to separate regions are extracted outlines of separate support regions
  7. For each support region:
    1. Triangulate the polygon regions into a mesh
    2. Rays are projected along Z in both directions from the mesh vertices to obtain the required extrusion height
    3. The triangulated polygon is extruded in both directions using the extrusions heights with an offset
  8. The extruded prisms are intersected with the original part mesh to obtain the final support volumes.

Flattening the Polygon Regions

The class BlockSupportGenerator encompasses the functionality for generating support volumes and the implementation resides in BlockSupportGenerator.identifySupportRegions.

Inside the function, the support regions are flattened into a polygon BaseSupportGenerator.flattenSupportRegion. This method extracts the outline or the boundary of the support region and flattens via projection by setting z=0along the coordinates. The paths are then translated into Shapely.Polygon objects.

""" Extract the outline of the overhang mesh region"""
poly = supportRegion.outline()

""" Convert the line to a 2D polygon"""
poly.vertices[:, 2] = 0.0

flattenPath, polygonTransform = poly.to_planar()
flattenPath.process()

flattenPath.apply_translation(polygonTransform[:2, 3]) 
polygon = flattenPath.polygons_full[0]

The polygon region is generated it provides the elementary building block for generating a support structure. This can be used to offset to prevent collision with self intersecting features. Internally, offsetting is useful to perform to regions so that any self-intersections with the geometry are clean.

Region Extrusion and Self-Intersection Check

The first pass of the proposed algorithm requires performing a boolean intersection to identify if there are any self-intersections. The polygon regions require extrusion. Near-net shape extrusion is accomplished using a custom function pyslm.support.extrudeFace. Unfortunately, this is not available within Trimesh, so instead it had to be implemented manually. This function extrudes a region of connected faces within a polygon, to set position or each individual face offset by an extruded distance.

# Extrude the surface to Z = 0
extrudedBlock = extrudeFace(supportSurface, None, 0)

# Extrude a triangle surface (Trimesh) based on the heights corresponding to each surface triangle
extrudedBlock = extrudeFace(surface, None, heightArray)

Having obtained an extruded prism from the support surface, a self-intersection test is performed with the original part. If no self-intersection takes place, this means the support structure has connectivity with the build platform. Under this situation, this drastically simplifies the number of steps required.

3D Printing Support Structure - Extrusion of a Support Structure from overhang region generated in PySLM
Example of an extruded mesh used for self-intersection tests

The intersection test requires a Boolean CSG operation. Quickly profiling a couple of tools available, from experience trying available solutions, the Cork Library was found to be both a reasonably accurate and high performance tool for manifold 3D geometries (i.e. those already required for 3D printing). The Nef Polyhedra implementation in the CGal library is renowned to be an accurate and robust implementation but slow. Due to these reasons, the PyCork library was created to provide a convenient wrapper across all platforms to perform this.

# Below is the expanded intersection operation used for intersecting a mesh
# cutMesh = pyslm.support.geometry.boolIntersect(part.geometry, extrudedMesh)

meshA = part.geometry
meshB = extrudedMesh

vertsOut, facesOut = pycork.intersection(meshA.vertices, meshA.faces, meshB.vertices, meshB.faces)

# Re-construct the Trimesh 
cutMesh = trimesh.Trimesh(vertices=vertsOut, faces=facesOut, process=True)

# Identify if there is a self-intersection
if cutMesh.volume < BlockSupportGenerator._intersectionVolumeTolerance: # 50
    # The support does not self intersect
else:
    # The support intersects with the original part

In the situation that there is no intersection (or the volume is approximately zero), the support volume simply extrudes towards the build-plate. If a self-intersection occurs with the part, further calculations are required to process the block support.

Self-Intersecting Support Structures

If the support-self intersects this is far more challenging problem to deal with. Through a lot of experimentation, the most reliable method determined involved using a form of ray-tracing to project the surfaces down. This has two benefits:

  • Separating support regions across different heights
  • Providing a robust method for generating cleaner support volumes with greater options to customise their behaviour

The ray projection test is useful generally, as it can also be used to provide a support generation map for the region, as shown in the previous post.

Originally the ray projection method was done using Trimesh.Ray, where rays are projected from each support face at a chosen ray projection resolution BlockSupportGenerator.rayProjectionResolution. A grid is formed with seed points for the rays and these are projected upwards and downwards onto the previous self intersected support mesh. The ray intersection test is performed on upward facing surfaces extracted from the existing intersected mesh, in the previous region.

Later this was updated to use a GLSL GPU process for identifying this at a much higher resolution at significant reduction in computational cost as discussed in a previous post.

From the ray projection map, individual support block regions can be separated based on taking a threshold of the image gradient, using the gradThreshold function. Using simple trigonometry, the threshold to determine disconnected regions in the intersecting support are determined by the resolution of the ray projected image and the overhang angle, with an added ‘fudge-factor‘ thrown in.

Regions are separated based on this threshold using the isocontour method offered in Skimage’sfind_contours function. This is useful because it can identify supports regions connected only to the build-platform (desirable) and self-intersecting regions with the original part. Additionally, self-intersecting support regions with difference heights can also be isolated. These are useful in some marginal scenarios, but were more simpler methods breakdown.

PySLM: 3D Printing DMLS Metal Support Structure - Ray Projection Map
Ray Projection Map of support region used for identifying and separating support regions. Note the relatively high resolution used by using the GPU Projection Map Technique
PySLM: 3D Printing. DMLS. Selective Laser Melting. Projection Mesh for Support Structure
A projected region extracted by extracting the contour isolevel from the projection map (left). The outline is transformed into absolute coordinate system for the part.

The regions are identified by taking a threshold based on the choice of overhang angle using the BlockSupportGenerator.gradThreshold.

def gradThreshold()
    return 5.0 * np.tan(np.deg2rad(overhangAngle)) * rayProjectionDistance

# Calculate the gradient of the ray-projected height map for the support region
vx, vy = np.gradient(heightMap)
grads = np.sqrt(vx ** 2 + vy ** 2)

# A blur is used to smooth the boundaries
grads = scipy.ndimage.filters.gaussian_filter(grads, sigma=BlockSupportGenerator._gausian_blur_sigma)

"""
Find the outlines of any regions of the height map which deviate significantly
"""
outlines = find_contours(grads, self.gradThreshold(self.rayProjectionResolution, self.overhangAngle),
                            mask=heightMap > 2)

# Transform the outlines from image to global coordinates system
outlinesTrans = []
for outline in outlines:
    outlinesTrans.append(outline * self.rayProjectionResolution + bbox[0, :2])

Once the outlines are obtained. The boundaries are created into polygons, offset, optionally smoothed and then translated into triangular meshes using triangulate_polygon. Care must be taken when using spline-fitting to smooth the boundary as this can result in profiles not conforming to the original overhang region. The triangulation procedure internally can use either the earbox-cut algorithm or constrained Delaunay via the Triangle Library. The points of the polygon mesh are projected upwards and downwards on a subset of the previous intersected mesh to located the approximate volume before performing the final boolean operation.

# Create the outline and simplify the polygon using spline fitting (via Scipy)
mergedPoly = trimesh.load_path(outline)
mergedPoly.merge_vertices(1)

# Simplification and smoothing of the boundary is perform to provide smoother boundaries for generating a truss structure later.
mergedPoly = mergedPoly.simplify_spline(self._splineSimplificationFactor)

outPolygons = mergedPoly.polygons_full

"""                
Triangulate the polygon into a planar mesh
"""
poly_tri = trimesh.creation.triangulate_polygon(bufferPoly, triangle_args='pa{:.3f}'.format(self.triangulationSpacing))

# Use a ray projection method onto the original geometry to identify upper and lower boundaries

coords = np.insert(poly_tri[0], 2, values=-1e-7, axis=1)
ray_dir = np.repeat([[0., 0., 1.]], coords.shape[0], axis=0)

# Find the first location of any triangles which intersect with the part
hitLoc, index_ray, index_tri = subregion.ray.intersects_location(ray_origins=coords,
                                                                    ray_directions=ray_dir,
                                                                    multiple_hits=False)

The same process is repeated, and an extruded prism is generated based on the ray-projection regions. Simplification of the interior triangulation is done in order to minimise the time to perform the intersection.

PySLM: 3D Printing. DMLS. Selective Laser Melting. Projection Mesh for Support Structure
The prismatic mesh extruded based on the ray-projection distances obtained.
PySLM: 3D Printing. DMLS. Selective Laser Melting. Projection Mesh for Support Structure
The prismatic mesh extruded based on the ray-projection distances obtained.

Finally, to obtain the ‘exact’ conforming intersected mesh, once again this is intersected with the previous mesh to obtain the final support volume region conforming to the original geometry.

As it can be observed, there are many steps to obtain the exactly conforming support volume with the original mesh. For the majority of most geometries that would be printed, this method is adequate, although not full-proof. There are a few cases where this algorithm will fail due to the use of a ray projection algorithm and relying on line-of-sight. For example, a continuous spiral or 3D helix structure with large connected surfaces will not be identifiable from the support generation algorithm. Without developing a specific mesh intersection library, it is difficult to identify alternative ways around this. Admittedly this is beyond my ability.

PySLM 0.5

PySLM 0.5 has had a long incarnation. It has been waiting in anticipation for the past year and delayed due to challenges with the coding and ensuring cross-compatibility. It is an exciting release and a testament to the relative maturity of the project. Already, it is fantastic to observe that it is providing a great positive contribution and benefit to the research in the Additive Manufacturing community. Once again, I wish to personally thank everyone’s support developing this along the way.

The highlight of the 0.5 release is the addition of the new Support Module. The Support Module provides the building-blocks and the infrastructure to identify and extract support volumes, and generate their support structures based on meshes provided as input. The module has been in development in the background for over two-three years and finally, reaching a level of maturity that was in a position to release into the public.

The tools include the usual and standard technique of extracting overhang surfaces, edges and points based on the on their facial connectivity which was discussed in a previous post. These surfaces are used as the input in a ray-tracing approach for identifying precise volumetric block support structures as shown above. Unlike most implementations available externally, these conform to the boundaries of the part, utilising a new boolean CSG library PyCork, which provides a cross-platform Python implementation of the Cork Library. Due to limitations in existing CSG approaches available, a fast GPU based ray-trace approach is utilised to project identified support surfaces and create a high-resolution projection height-map to locate self-intersections like below. Furthermore, these provide additional flexibility to create alternatives approaches, such as those suitable for other manufacturing processes e.g. point-support structures (e.g. in SLA) or tree like support structures.

GPU Generated Depth Projection Maps

Each support surface identifies self-intersections with the original part and those with the build platform. The regions are segmented using an image processing technique based on an overhang tolerance and transformed into polygon boundaries. Simplification is necessary and use a combination of the Douglas-Peucker algorithm within scikit image’s approximate_polygon function and b-spline fitting tool available in Scipy. The boundary simplification is useful to alleviate issues when encountering sharp features extracted from jagged edges in the support regions.

These volumetric regions provide the foundational elements for constructing sophisticated support structures, especially those used within SLM systems. To maximise productivity, provide greater control over controlling distortion due to residual stress, grid-truss based support structures have been utilised for over a decade in SLM. Unfortunately, I have yet an to come across a known implementation that exists both in literature nor open-source code to generate these structures. Below is an example of conformal grid-truss geometry generated for a complex topology optimised bracket component.

In the implementation, the grid truss structure is generated by taking cross-sections throughout the support volumes and using a geometric polygon operations offered by the ClipperLib. The truss is formed by generating hatch lines that are offset and union to create a truss. This approach provides flexibility to design different structures. Afterwards, 3D triangular meshes are generated from the polygon boundaries which are mapped back onto the original support volume. Doing this efficiently is challenging given the potential size and number of support structures that can be generated.

Under own testing, the implementation is reliable for most geometries, although there are few known cases where the algorithm will not work. It is acknowledged that the support module is not intended to be a direct replacement for commercial software, rather, provide a working reference that researchers and general users can understand, adapt and utilise in their own work/research or part of a pipeline.

An example script for generating a support structure can be found on the Github repository in examples/example_support_structure.py

The installation of PySLM 0.5 has soft-dependencies for using the support module due to the additional algorithms required. Please, ensure that these are all installed and that there is a working OpenGL 2.1 installation (via Vispy and PyQt5) on your system. The core functionality offered in PyQt5 may be utilised without these extra dependencies for those wanting a simplified installation.

Opportunities to explore:

There are many opportunities that are available to investigate using the new functionality available: e.g. lattice based support structures, alternative approaches support structures, novel scan strategies suitable for SLM. Parametric and optimisation of the support structure design – e.g. automated support generation. The tool will aid those working in modelling and simulation: optimisation of designs prior to printing to account for distortion, control of thermal history, globally optimise parts for build-cost-time models. It would be great to hear from anyone on their experience using this functionality.

Further improvements to PySLM

The remainder of the release has a few improvements and fixes to the core functionality and its documentation. It is important to highlight the analysis module for predicting build times – accounting for scan vector jump delays, jump speed, point exposure delays that have an incremental impact on the overall build time. Additionally, the release has been tested across all platforms (Windows, Linux, Mac OS X) and further testing and maturity of libSLM‘s translators continue: including a working implementation of EOS .sli format.

The full release log for PySLM 0.5 may be found in Changelog.MD

Overhang and Support Structures in L-PBF (SLM) using PySLM (Part I)

A key focus of the release of PySLM 0.5 was the introduction of support structure generation targeted for powder-bed fusion (PBF) processes such as Selective Laser Melting (SLM) and also Electron Beam Melting (EBM). The basic infrastructure for generating support structures was developed including overhang analysis, support projection maps and the calculating precise conforming volumes, that leads to demonstration of block ‘truss’ based supports.

It is a particularly exciting release, because it is the first implementation both open source but also explicitly documents in practice a potential method for generating support structures for these specific PBF processes that have commercially (albeit few choices) been available for over a decade.

The challenge of this specific problem was to provide a robust solution covering the majority of engineering cases – which led to the length of time taken to develop this feature. This included having to develop many additional functions, support routines and workarounds for the limited availability of a boolean CSG library for triangular meshes in Python whilst providing reasonable performance.

In the Support Structure, the geometry constructed consists of a grid and a boundary which features a polygon derived truss structure in order to support powder removal and control the stiffness of the structure. Below highlights the capability for generated truss-based support structure suitable for PBF process. Carefully observe that individual support blocks are separated when self-intersecting and precisely conform to the original geometry. The support volumes themselves interface with the original part, by performing an exact boolean intersection.

Truss based Support Structures  for Selective Laser Melting (SLM) or LPBF generated using PySLM
Support Structure Generation in PySLM 0.5 suitable for Selective Laser Melting. Separate support regions are generated for the part using a projection method and a truss based support structure is generated in a grid and along the boundary.

Within the support volumes generating a grid-truss support structure can be generated by taking 2D cross-sections and applying various polygon clipping techniques to generate the structure to create the truss. These trusses structure are particularly more efficient for scanning as these slice as individual scan vectors rather than a series of point exposure.

PySLM: Python 3D Printing support generation for selective laser melting - bottom view showing a grid truss support
A view from the bottom showing the grid truss support structure generated
PySLM: Slicing through a generated SLM Support Structure generated using PySLM.
A slice or cross-section taken through both the part and support structures. It can bee seen that the support structure is constructed from a grid which represented single linear scan vectors during scanning.

Future work intends to correctly hatch the support structure regions and integrate a multi-body slice and hatching procedure, but this is intended for inclusion in a future release, possibly PySLM 0.6.

Due to the implementation’s brevity, the proposed methodology will be split across multiple-posts. Anecdotally, work began on a support method over two years ago, intended to offer a more complete input towards deriving a cost model based on existing research in the literature – for further guidance refer to the following posts (Build time estimation).

Background on Support Structures

Support structures are a vital element to Additive Manufacturing. Despite the additional cost of post-processing support structures, these are useful and in some instances essential for successful manufacture of metal AM parts. Most 3D printed users will be very familiar with support generation: the tedious removal of additional structures in most AM processes (FDM, SLM, SLA, BJF, EBM) and the practical difficulty removing this material afterwards. SLS/HSS for polymer parts are largely immune from this manufacturing constraint and make it as a technology for every attractive and cost efficient to produce 3D printed parts without much specific knowledge from the designer. They serve a variety of purposes beyond geometrically supporting overhang surfaces, namely:

  • Anchor the part onto to the build platform before removal using Spark Erosion or Wire Electric Discharge Machining
  • Counter-act distortion in materials prone to residual stresses, when compensation factors cannot be used through AM build simulations
  • Provide a path to dissipate heat to prevent overheating of regions,
  • Provide structure to support forces exerted during post machining interfaces.

Even with the best intention for the engineer or technician to design these out, it is likely that these may need to be included. On-going development and research to adapt topology optimisation [1][2][3][4][5][6] to support ‘overhang constraints’ or specifically minimise boundaries with support angles that require support has progressed within recent years since the time of this post. Research has also considered using topology optimisation to structurally derive support structures based on an ‘inherent strain’ or distortion as an input [7]. Infact, are now available as design constraints within commercial Topology Optimisation software. However, momentarily these are currently not a complete or holistic solution. By their inclusion, there is a detriment to the overall performance of the solution optimsed. They also do not factor other objective functions such as minimising support material, overhang surfaces, part anisotropy and crucially the piece part cost [8][9]. In industrial applications, the part functionality or fundamental shape may make this challenging or penalise the algorithms. ‘Generative’ approaches, may globally optimise the part (including orientation) to minimise the requirements of support structures, but it is inevitable that some use is required. Geometrically, the quality or surface roughness of overhang or down-skin surfaces are improving through process optimisation of the laser parameters provide by the OEMs. There are indications that the choice of powder size and the layer thickness may improve the surface finish of these problematic regions.

Under some situations support structures can minimise the risk taken to manufacture parts first-time and ultimately reduce the cost of a supplier delivering the part to the customer. It also provides paths to dissipate excess heat generated which will become a further challenge to overcome with the adoption of multiple-laser SLM systems. Research has also proposed different support structures strategies for mitigating the effects of overheating and distortion in the SLM process [10], which included using topology optimisation to find thermally efficient support structures for heat transfer.

Support Structure Generation Capability in existing AM Pre-processing Software

For the specific area of interest for PySLM, it is a particular challenging requirement that remains to be overcome in selective laser melting and to a much lesser extent electron beam melting. The generation of support structures in FDM and SLA technologies is well established and available in consumer-led software for popular FDM printers such as Ultimaker Cura, Slic3r, SLA Formula’s Preform for SLA, or Chitubox for DLP . Fortunately, some of these software are opensource and provide some reference to how these are generated and successfully adopted across FDM 3D printing. Arguably, I have yet to delve into methods for how these are generated but it is expected the supports generated are similar to that used in metal AM . In metal additive manufacturing, commercial capability is available in both Materialise’s Magics SG/SG+ Module, Netfabb and to some existing OEM software. A reference and implementation of support generation for commercial or industrial led 3D printing especially in metal additive manufacturing is currently non-existent. These software are known to be relatively expensive to purchase and maintain.

Support Structure Generation in Research

In academic literature, the use of commerical software for support generation covers a couple of common research areas in the AM Literature including:

  • Part assessment: part buildability, overhang analysis
  • Process planning and optimisation: build-time prediction, build volume packing, cost modelling
  • Distortion and support minimisation: Numerical simulation to minimise distortion and support structure requirements
  • Lattice structures: minimising support structure requirements

Further overview of current work and research in Support Structures is also reported [11]. Specifically concerning about support generation in Laser PBF processes for these posts, support generation remains an outstanding challenge with the process.

Overhang Areas

Overhang areas are characterised as those prone to generate surfaces that do not conform to the intended geometry of the digital model. These usually result in with surfaces of high roughness / poor surface quality or formation of ‘dross’. These underlying regions may be susceptible to defect inclusions due to the localised overheating, due to the insulative behaviour of powder underneath the exposure zone. Fundamentally, Overhang areas correspond with the build-up of geometry inclined at shallow angles inclined against the build direction i.e. ‘overhang-angle’. It is dependent on many factors including the

  • machine system,
  • material alloy processed,
  • layer thickness,
  • optimisation of laser parameters (the down-skin parameter set).

Completely unsupported areas – those which do not have any solid material underneath, exasperate this effect. Under some situations, the support material become disconnected and dislodged by the powder spreading or re-coating mechanism, which in the extreme case may cause build-failure.

Mitigating the Effects of Distortion due to Residual stress

Some metal alloys are susceptible to the effects of residual stress generation, in particular Titanium. These stresses manifest with the manufactured part due to thermal-gradients. The effect of residual stress is that it generates internal forces causing distortion of the part. In the extreme situations, it can cause failure due of material due to stresses exceeding the material yield-point. During the build-process, it causes parts to ‘curl’ upwards. This can be somewhat mitigated to an extent using strong enough support structures in the correct place. It can be decided through the intuition the of the machine operator or now through the use of dedicated AM build simulation software. Various research has investigated the optimisation of support structures based on distortion of parts [12].

Much further could be discussed about the area of residual stress in detail but it can be further looked at within the literature. A future post may focus on this in greater detail.

Challenges Created by Support Structures

Amongst post-finishing requirements to achieve required tolerances of a manufactured part it contributes a significant cost to the end-part when they cannot be avoided.

Removal of metal supports is unpleasant and unsatisfactory stage of the manufacturing process. This is dependent on the hardness/strength of the material alloy and the type of supports utilised. They open up the myriad of variability from ‘hand-fettled‘ or ‘artisan’ finishes achieved through support – often referred as the artisanal craft of 3D printing. Even post machining the supports of is an additional process, that requires setup and also the time to prepare the part on the CNC machine. Perhaps, the utilisation of robotic CNC machining in the future will significantly reduce the cost of support removal as part of serial production. It would be fantastic to see some exploration integrating CNC machining of support removal directly from PySLM and is a move towards digital twins.

Support structure contribute the following (in)-direct intrinsic costs for a part produced by metal AM:

  • Indirect impact on functional performance by designing around overhang constraints
  • The additional time and cost for the designer to correctly generate the support – including simulation time
  • The direct cost of building the support structures on the system
  • The support removal time (machined or hand removed)
  • Direct impact on the e.g. total performance of the part due to this constraint e.g. surface roughness impacting fluid flow, fatigue performance

Aims of the PySLM Support Module for Support Structures

Support generation capability in PySLM aims to provide a working reference for other researchers to adopt amongst their work. Thus assist researcher’s understand and explore the generation of various types of common support structures employed in AM. Also, it will enable the entire AM ecosystem to have some capability that it can be adapted accordingly for their own wishes.

It does not intend to guarantee to provide a production ready support generation for metal AM parts without careful attention. In the future, this will expand to explore various approaches and further refine capability for PySLM to be a more comprehensive toolbox for use in AM research.

See the Next Post in the Support Structure Series

References

References
1 Serphos, M. R. (2014). Incorporating AM-specific Manufacturing Constraints into Topology Optimization. Delft University of Technology.
2 Leary, M., Merli, L., Torti, F., Mazur, M., & Brandt, M. (2014). Optimal Topology for Additive Manufacture: A method for enabling additive manufacture of support-free optimal structures. Materials & Design, 63, 678–690. https://doi.org/10.1016/j.matdes.2014.06.015
3 Gaynor, A. T., & Guest, J. K. (2016). Topology optimization considering overhang constraints: Eliminating sacrificial support material in additive manufacturing through design. Structural and Multidisciplinary Optimization, 54(5), 1157–1172. https://doi.org/10.1007/s00158-016-1551-x
4 Garaigordobil, A., Ansola, R., Santamaría, J., & Fernández de Bustos, I. (2018). A new overhang constraint for topology optimization of self-supporting structures in additive manufacturing. Structural and Multidisciplinary Optimization, 58(5), 2003–2017. https://doi.org/10.1007/s00158-018-2010-7
5 Gaynor, A. T. (2015). Topology Optimization Algorithms for Additive Manufacturing. Retrieved from https://jscholarship.library.jhu.edu/bitstream/handle/1774.2/38009/GAYNOR-DISSERTATION-2015.pdf
6 Allaire, G., Bihr, M., & Bogosel, B. (2020). Support optimization in additive manufacturing for geometric and thermo-mechanical constraints. Structural and Multidisciplinary Optimization, 61(6), 2377–2399. https://doi.org/10.1007/s00158-020-02551-1
7 Zhang, Z. D., Ibhadode, O., Ali, U., Dibia, C. F., Rahnama, P., Bonakdar, A., & Toyserkani, E. (2020). Topology optimization parallel-computing framework based on the inherent strain method for support structure design in laser powder-bed fusion additive manufacturing. International Journal of Mechanics and Materials in Design, 0123456789. https://doi.org/10.1007/s10999-020-09494-x
8 Brackett, D., Ashcroft, I., & Hague, R. (2011). Topology optimization for additive manufacturing. Solid Freeform Fabrication Symposium, 348–362. Retrieved from http://utwired.engr.utexas.edu/lff/symposium/proceedingsarchive/pubs/Manuscripts/2011/2011-27-Brackett.pdf
9 Brika, S. E., Mezzetta, J., Brochu, M., & Zhao, Y. F. (2017). Multi-Objective Build Orientation Optimization for Powder Bed Fusion by Laser. Volume 2: Additive Manufacturing; Materials, (August), V002T01A010. https://doi.org/10.1115/MSEC2017-2796
10 Paggi, U., Ranjan, R., Thijs, L., Ayas, C., Langelaar, M., van Keulen, F., & van Hooreweder, B. (2019). New support structures for reduced overheating on downfacing regions of direct metal printed parts. Solid Freeform Fabrication 2019: Proceedings of the 30th Annual International Solid Freeform Fabrication Symposium – An Additive Manufacturing Conference, SFF 2019, 1626–1640. Austin, Texas, USA.
11 Jiang, J., Xu, X., & Stringer, J. (2018). Support Structures for Additive Manufacturing: A Review. Journal of Manufacturing and Materials Processing, 2(4), 64. https://doi.org/10.3390/jmmp2040064
12 Krol, T. A., Zaeh, M. F., Seidel, C., & Muenchen, T. U. (2012). Optimization of supports in metal-based additive manufacturing by means of finite element models. SFF, 707–718.

PySLM: Geometric Hatch Overlap Check/Visualisation

Designing scan strategies for PBF techniques, we are not entirely aware of situations that arise where the powder-bed is not fully exposed due to a mismatch when scan vectors are not sufficiently overlapped. Typically, unoptimised placement of hatch vectors lead to the creation of irregular porosity or voids in L-PBF parts.

This can arise along the intersections between the contour and interior hatches, especially a long concave regions such as sharp corner features with acute angles.

The approach is not an efficient way to examine the presence of , but provides a representative view for checking this geometrically.

Method

The approach takes advantage of the relatively new Iterator classes available within the analysis module, which vastly simplifies the generation procedure for manipulating and examining existing scan vector geometry. Firstly, generate or alternatively import the Layer and its LayerGeometry groups to examine. The group of layers are passed to the ScanVectorIterator class, which will iterate across every scan vector from both ContourGeometry and HatchGeometry objects within a Layer. Single point exposures are not considered.

import pyslm.analysis
from shapely.geometry import LineString, Polygon, MultiPolygon
from shapely.ops import cascaded_union

scanIterator =  pyslm.analysis.ScanVectorIterator([layer])

After the creation of the ScanVectorIterator, this can be readily expedited to process across all scan vectors across the Layer. The basic process relies on converting each scan vector to a Shapely polygon objects and then processing them using the geometry tools available.

For this case we use Pythonic notation to compactly operate across each scan vector and collect them. We convert each scan vector to a Shapely LineString, which has a method to then offset or buffer.

# Laser Spot Radius
laserSpotRadius = 0.04

# Iterate across each scan vector and buffer than geometry
lines = [LineString(line).buffer(laserSpotRadius) for line in scanIterator]

After offseting all the lines, this can be easily visualised by conversion to a Shapely MultiPolygon.

# Merged the offset lines into a Shapely Multi-Polygon Collection
multiPoly = MultiPolygon(lines)
pyslm.visualise.plotPolygon(multiPoly)

The geometrical result is shown below. It is relatively quick to generate and plot individual scan vectors as shown below:

Geometrical overlap of scan vectors in SLM processed by PySLM
Overlap of hatch vectors represented by geometrically offsetting the individual scan vectors within a Layer.

Each scan vector that is offset is represented by a Shapely.Polygon. It is trivial to perform a boolean operation with the Shapely library. Although, it is recommended to use the more efficient, albeit still relatively slow, shapely.ops.cascaded_union function to merge multiple geometries together:

# Cascaded union is a more efficient boolean merge for multiple polygon entities
multiPolyMerged = cascaded_union(multiPoly)

pyslm.visualise.plotPolygon(multiPolyMerged)

The combined result is shown here with a slightly smaller hatch distance to exaggerate the effect and highlight regions where the laser beam may not sufficiently provide exposure to the powder bed:

Illustration of regions that may
Regions that have insufficient coverage observed after performing a boolean merge after the scan vectors have been offset

This post shares a relatively simple example exploration using geometrical operations and the iterator class to understand potential issues related to hatch overlaps.

Final Conclusions

Potentially, this check could be extended into 3D using morphological operations. This would provide a more qualitative examination of porosity generation as a result of Furthermore, the combined use of Neural Networks or reduce order models could provide a representative exposure area to provide the geometrical offset in 2D and provide a prediction for coverage spatially in 3D.

PySLM Version 0.3

PySLM version 0.3 was released last week to coincide with a large number requests from users of the library. The release is consists of many updates, fixes and examples accumulated across the last 6 months since last summer. Additional work was done to refine the release of the sister library libSLM and resolve some bugs that couldn’t be determined until exporting the machine files and testing on the machine, with acknowledgement of support from researchers who have got in touch. Many thanks for their assistance on this development journey.

The release notes can be found on github.

The original release was scheduled to include support generation, but this has been postponed for v0.4 to ensure that there was a underlying stable release of PySLM as reference to ensure users can utilise the library without waiting for the support structure element to stabilise.

A summary of notable features amongst fixes are as follows:

  • Added class geometry.utils.ModelValidator with functions to validates the inputs (models, layers) are consistent and coherent prior to exporting to machine build files using libSLM.
  • Added an alternative method BaseHatcher.clipContourLines for clipping a list of contour scan vectors. See the previous post about generating custom sinusoidal scan strategy using this method.
  • Added method hatching.simplifyBoundaries to simplify boundaries using Sci-kit Image method based on Douglas-Peucker algorithm.
  • Added a methodvisualise.visualiseOverhang to visualise overhangs – in preparation for support structure analysis
  • Added function argument index to visualise.plot in order to visualise the scan vector parameters (e.g. length, laser parameters, build style id)

Any requests for additional features or other improvements feel free to get in touch.