cam.simple#

BlenderCAM ‘simple.py’ © 2012 Vilem Novak

Various helper functions, less complex than those found in the ‘utils’ files.

Functions#

tuple_add(t, t1)

Add two tuples as vectors.

tuple_sub(t, t1)

Subtract two tuples element-wise.

tuple_mul(t, c)

Multiply each element of a tuple by a given number.

tuple_length(t)

Get the length of a vector represented as a tuple.

timinginit()

Initialize timing metrics.

timingstart(tinf)

Start timing by recording the current time.

timingadd(tinf)

Update the timing information.

timingprint(tinf)

Print the timing information.

progress(text[, n])

Report progress during script execution.

activate(o)

Makes an object active in Blender.

dist2d(v1, v2)

Calculate the distance between two points in 2D space.

delob(ob)

Delete an object in Blender for multiple uses.

dupliob(o, pos)

Helper function for visualizing cutter positions in bullet simulation.

addToGroup(ob, groupname)

Add an object to a specified group in Blender.

compare(v1, v2, vmiddle, e)

Comparison for optimization of paths.

isVerticalLimit(v1, v2, limit)

Test Path Segment on Verticality Threshold for protect_vertical option.

getCachePath(o)

Get the cache path for a given object.

getSimulationPath()

Get the simulation path for temporary camera files.

safeFileName(name)

Generate a safe file name from the given string.

strInUnits(x[, precision])

Convert a value to a string representation in the current unit system.

select_multiple(name)

Select multiple objects in the scene based on their names.

join_multiple(name)

Join multiple objects and rename the final object.

remove_multiple(name)

Remove multiple objects from the scene based on their name prefix.

deselect()

Deselect all objects in the current Blender context.

make_active(name)

Make an object active in the Blender scene.

active_name(name)

Change the name of the active object in Blender.

rename(name, name2)

Rename an object and make it active.

union(name)

Perform a boolean union operation on objects.

intersect(name)

Perform an intersection operation on a curve object.

difference(name, basename)

Perform a boolean difference operation on objects.

duplicate([x, y])

Duplicate an active object or move it based on the provided coordinates.

mirrorx()

Mirror the active object along the x-axis.

mirrory()

Mirror the active object along the Y axis.

move([x, y])

Move the active object in the 3D space by applying a translation.

rotate(angle)

Rotate the active object by a specified angle.

remove_doubles()

Remove duplicate vertices from the selected curve object.

add_overcut(diametre[, overcut])

Add overcut to the active object.

add_bound_rectangle(xmin, ymin, xmax, ymax[, name])

Add a bounding rectangle to a curve.

add_rectangle(width, height[, center_x, center_y])

Add a rectangle to the scene.

active_to_coords()

Convert the active object to a list of its vertex coordinates.

active_to_shapely_poly()

Convert the active object to a Shapely polygon.

subdivide_short_lines(co)

Subdivide all polylines to have at least three points.

Module Contents#

tuple_add(t, t1)[source]#

Add two tuples as vectors.

This function takes two tuples, each representing a vector in three- dimensional space, and returns a new tuple that is the element-wise sum of the two input tuples. It assumes that both tuples contain exactly three numeric elements.

Parameters:
  • t (tuple) – A tuple containing three numeric values representing the first vector.

  • t1 (tuple) – A tuple containing three numeric values representing the second vector.

Returns:

A tuple containing three numeric values that represent the sum of the

input vectors.

Return type:

tuple

tuple_sub(t, t1)[source]#

Subtract two tuples element-wise.

This function takes two tuples of three elements each and performs an element-wise subtraction, treating the tuples as vectors. The result is a new tuple containing the differences of the corresponding elements from the input tuples.

Parameters:
  • t (tuple) – A tuple containing three numeric values.

  • t1 (tuple) – A tuple containing three numeric values.

Returns:

A tuple containing the results of the element-wise subtraction.

Return type:

tuple

tuple_mul(t, c)[source]#

Multiply each element of a tuple by a given number.

This function takes a tuple containing three elements and a numeric value, then multiplies each element of the tuple by the provided number. The result is returned as a new tuple containing the multiplied values.

Parameters:
  • t (tuple) – A tuple containing three numeric values.

  • c (numeric) – A number by which to multiply each element of the tuple.

Returns:

A new tuple containing the results of the multiplication.

Return type:

tuple

tuple_length(t)[source]#

Get the length of a vector represented as a tuple.

This function takes a tuple as input, which represents the coordinates of a vector, and returns its length by creating a Vector object from the tuple. The length is calculated using the appropriate mathematical formula for vector length.

Parameters:

t (tuple) – A tuple representing the coordinates of the vector.

Returns:

The length of the vector.

Return type:

float

timinginit()[source]#

Initialize timing metrics.

This function sets up the initial state for timing functions by returning a list containing two zero values. These values can be used to track elapsed time or other timing-related metrics in subsequent operations.

Returns:

A list containing two zero values, representing the initial timing metrics.

Return type:

list

timingstart(tinf)[source]#

Start timing by recording the current time.

This function updates the second element of the provided list with the current time in seconds since the epoch. It is useful for tracking the start time of an operation or process.

Parameters:

tinf (list) – A list where the second element will be updated with the current time.

timingadd(tinf)[source]#

Update the timing information.

This function updates the first element of the tinf list by adding the difference between the current time and the second element of the list. It is typically used to track elapsed time in a timing context.

Parameters:

tinf (list) – A list where the first element is updated with the

timingprint(tinf)[source]#

Print the timing information.

This function takes a tuple containing timing information and prints it in a formatted string. It specifically extracts the first element of the tuple, which is expected to represent time, and appends the string ‘seconds’ to it before printing.

Parameters:

tinf (tuple) – A tuple where the first element is expected to be a numeric value representing time.

Returns:

This function does not return any value; it only prints output to the

console.

Return type:

None

progress(text, n=None)[source]#

Report progress during script execution.

This function outputs a progress message to the standard output. It is designed to work for background operations and provides a formatted string that includes the specified text and an optional numeric progress value. If the numeric value is provided, it is formatted as a percentage.

Parameters:
  • text (str) – The message to display as progress.

  • n (float?) – A float representing the progress as a fraction (0.0 to 1.0). If not provided, no percentage will be displayed.

Returns:

This function does not return a value; it only prints

to the standard output.

Return type:

None

activate(o)[source]#

Makes an object active in Blender.

This function sets the specified object as the active object in the current Blender scene. It first deselects all objects, then selects the given object and makes it the active object in the view layer. This is useful for operations that require a specific object to be active, such as transformations or modifications.

Parameters:

o (bpy.types.Object) – The Blender object to be activated.

dist2d(v1, v2)[source]#

Calculate the distance between two points in 2D space.

This function computes the Euclidean distance between two points represented by their coordinates in a 2D plane. It uses the Pythagorean theorem to calculate the distance based on the differences in the x and y coordinates of the points.

Parameters:
  • v1 (tuple) – A tuple representing the coordinates of the first point (x1, y1).

  • v2 (tuple) – A tuple representing the coordinates of the second point (x2, y2).

Returns:

The Euclidean distance between the two points.

Return type:

float

delob(ob)[source]#

Delete an object in Blender for multiple uses.

This function activates the specified object and then deletes it using Blender’s built-in operations. It is designed to facilitate the deletion of objects within the Blender environment, ensuring that the object is active before performing the deletion operation.

Parameters:

ob (Object) – The Blender object to be deleted.

dupliob(o, pos)[source]#

Helper function for visualizing cutter positions in bullet simulation.

This function duplicates the specified object and resizes it according to a predefined scale factor. It also removes any existing rigidbody properties from the duplicated object and sets its location to the specified position. This is useful for managing multiple cutter positions in a bullet simulation environment.

Parameters:
  • o (Object) – The object to be duplicated.

  • pos (Vector) – The new position to place the duplicated object.

addToGroup(ob, groupname)[source]#

Add an object to a specified group in Blender.

This function activates the given object and checks if the specified group exists in Blender’s data. If the group does not exist, it creates a new group with the provided name. If the group already exists, it links the object to that group.

Parameters:
  • ob (Object) – The object to be added to the group.

  • groupname (str) – The name of the group to which the object will be added.

compare(v1, v2, vmiddle, e)[source]#

Comparison for optimization of paths.

This function compares two vectors and checks if the distance between a calculated vector and a reference vector is less than a specified threshold. It normalizes the vector difference and scales it by the length of another vector to determine if the resulting vector is within the specified epsilon value.

Parameters:
  • v1 (Vector) – The first vector for comparison.

  • v2 (Vector) – The second vector for comparison.

  • vmiddle (Vector) – The middle vector used for calculating the reference vector.

  • e (float) – The threshold value for comparison.

Returns:

True if the distance is less than the threshold,

otherwise False.

Return type:

bool

isVerticalLimit(v1, v2, limit)[source]#

Test Path Segment on Verticality Threshold for protect_vertical option.

This function evaluates the verticality of a path segment defined by two points, v1 and v2, based on a specified limit. It calculates the angle between the vertical vector and the vector formed by the two points. If the angle is within the defined limit, it adjusts the vertical position of either v1 or v2 to ensure that the segment adheres to the verticality threshold.

Parameters:
  • v1 (tuple) – A 3D point represented as a tuple (x, y, z).

  • v2 (tuple) – A 3D point represented as a tuple (x, y, z).

  • limit (float) – The angle threshold for determining verticality.

Returns:

The adjusted 3D points v1 and v2 after evaluating the verticality.

Return type:

tuple

getCachePath(o)[source]#

Get the cache path for a given object.

This function constructs a cache path based on the current Blender file’s filepath and the name of the provided object. It retrieves the base name of the file, removes the last six characters, and appends a specified directory and the object’s name to create a complete cache path.

Parameters:

o (Object) – The Blender object for which the cache path is being generated.

Returns:

The constructed cache path as a string.

Return type:

str

getSimulationPath()[source]#

Get the simulation path for temporary camera files.

This function retrieves the file path of the current Blender project and constructs a new path for temporary camera files by appending ‘temp_cam’ to the directory of the current file. The constructed path is returned as a string.

Returns:

The path to the temporary camera directory.

Return type:

str

safeFileName(name)[source]#

Generate a safe file name from the given string.

This function takes a string input and removes any characters that are not considered valid for file names. The valid characters include letters, digits, and a few special characters. The resulting string can be used safely as a file name for exporting purposes.

Parameters:

name (str) – The input string to be sanitized into a safe file name.

Returns:

A sanitized version of the input string that contains only valid characters for a file name.

Return type:

str

strInUnits(x, precision=5)[source]#

Convert a value to a string representation in the current unit system.

This function takes a numeric value and converts it to a string formatted according to the unit system set in the Blender context. If the unit system is metric, the value is converted to millimeters. If the unit system is imperial, the value is converted to inches. The precision of the output can be specified.

Parameters:
  • x (float) – The numeric value to be converted.

  • precision (int?) – The number of decimal places to round to. Defaults to 5.

Returns:

The string representation of the value in the appropriate units.

Return type:

str

select_multiple(name)[source]#

Select multiple objects in the scene based on their names.

This function deselects all objects in the current Blender scene and then selects all objects whose names start with the specified prefix. It iterates through all objects in the scene and checks if their names begin with the given string. If they do, those objects are selected; otherwise, they are deselected.

Parameters:

name (str) – The prefix used to select objects in the scene.

join_multiple(name)[source]#

Join multiple objects and rename the final object.

This function selects multiple objects in the Blender context, joins them into a single object, and renames the resulting object to the specified name. It is assumed that the objects to be joined are already selected in the Blender interface.

Parameters:

name (str) – The new name for the joined object.

remove_multiple(name)[source]#

Remove multiple objects from the scene based on their name prefix.

This function deselects all objects in the current Blender scene and then iterates through all objects. If an object’s name starts with the specified prefix, it selects that object and deletes it from the scene. This is useful for operations that require removing multiple objects with a common naming convention.

Parameters:

name (str) – The prefix of the object names to be removed.

deselect()[source]#

Deselect all objects in the current Blender context.

This function utilizes the Blender Python API to deselect all objects in the current scene. It is useful for clearing selections before performing other operations on objects. Raises: None

make_active(name)[source]#

Make an object active in the Blender scene.

This function takes the name of an object and sets it as the active object in the current Blender scene. It first deselects all objects, then selects the specified object and makes it active, allowing for further operations to be performed on it.

Parameters:

name (str) – The name of the object to be made active.

active_name(name)[source]#

Change the name of the active object in Blender.

This function sets the name of the currently active object in the Blender context to the specified name. It directly modifies the name attribute of the active object, allowing users to rename objects programmatically.

Parameters:

name (str) – The new name to assign to the active object.

rename(name, name2)[source]#

Rename an object and make it active.

This function renames an object in the Blender context and sets it as the active object. It first calls the make_active function to ensure the object is active, then updates the name of the active object to the new name provided.

Parameters:
  • name (str) – The current name of the object to be renamed.

  • name2 (str) – The new name to assign to the active object.

union(name)[source]#

Perform a boolean union operation on objects.

This function selects multiple objects that start with the given name, performs a boolean union operation on them using Blender’s operators, and then renames the resulting object to the specified name. After the operation, it removes the original objects that were used in the union process.

Parameters:

name (str) – The base name of the objects to be unioned.

intersect(name)[source]#

Perform an intersection operation on a curve object.

This function selects multiple objects based on the provided name and then executes a boolean operation to create an intersection of the selected objects. The resulting intersection is then named accordingly.

Parameters:

name (str) – The name of the object(s) to be selected for the intersection.

difference(name, basename)[source]#

Perform a boolean difference operation on objects.

This function selects a series of objects specified by name and performs a boolean difference operation with the object specified by basename. After the operation, the resulting object is renamed to ‘booleandifference’. The original objects specified by name are deleted after the operation.

Parameters:
  • name (str) – The name of the series of objects to select for the operation.

  • basename (str) – The name of the base object to perform the boolean difference with.

duplicate(x=0.0, y=0.0)[source]#

Duplicate an active object or move it based on the provided coordinates.

This function duplicates the currently active object in Blender. If both x and y are set to their default values (0), the object is duplicated in place. If either x or y is non-zero, the object is duplicated and moved by the specified x and y offsets.

Parameters:
  • x (float) – The x-coordinate offset for the duplication. Defaults to 0.

  • y (float) – The y-coordinate offset for the duplication. Defaults to 0.

mirrorx()[source]#

Mirror the active object along the x-axis.

This function utilizes Blender’s operator to mirror the currently active object in the 3D view along the x-axis. It sets the orientation to global and applies the transformation based on the specified orientation matrix and constraint axis.

mirrory()[source]#

Mirror the active object along the Y axis.

This function uses Blender’s operator to perform a mirror transformation on the currently active object in the scene. The mirroring is done with respect to the global coordinate system, specifically along the Y axis. This can be useful for creating symmetrical objects or for correcting the orientation of an object in a 3D environment. Raises: None

move(x=0.0, y=0.0)[source]#

Move the active object in the 3D space by applying a translation.

This function translates the active object in Blender’s 3D view by the specified x and y values. It uses Blender’s built-in operations to perform the translation and then applies the transformation to the object’s location.

Parameters:
  • x (float) – The distance to move the object along the x-axis. Defaults to 0.0.

  • y (float) – The distance to move the object along the y-axis. Defaults to 0.0.

rotate(angle)[source]#

Rotate the active object by a specified angle.

This function modifies the rotation of the currently active object in the Blender context by setting its Z-axis rotation to the given angle. After updating the rotation, it applies the transformation to ensure that the changes are saved to the object’s data.

Parameters:

angle (float) – The angle in radians to rotate the active object around the Z-axis.

remove_doubles()[source]#

Remove duplicate vertices from the selected curve object.

This function utilizes the Blender Python API to remove duplicate vertices from the currently selected curve object in the Blender environment. It is essential for cleaning up geometry and ensuring that the curve behaves as expected without unnecessary complexity.

add_overcut(diametre, overcut=True)[source]#

Add overcut to the active object.

This function adds an overcut to the currently active object in the Blender context. If the overcut parameter is set to True, it performs a series of operations including creating a curve overcut with the specified diameter, deleting the original object, and renaming the new object to match the original. The function also ensures that any duplicate vertices are removed from the resulting object.

Parameters:
  • diametre (float) – The diameter to be used for the overcut.

  • overcut (bool) – A flag indicating whether to apply the overcut. Defaults to True.

add_bound_rectangle(xmin, ymin, xmax, ymax, name='bounds_rectangle')[source]#

Add a bounding rectangle to a curve.

This function creates a rectangle defined by the minimum and maximum x and y coordinates provided as arguments. The rectangle is added to the scene at the center of the defined bounds. The resulting rectangle is named according to the ‘name’ parameter.

Parameters:
  • xmin (float) – The minimum x-coordinate of the rectangle.

  • ymin (float) – The minimum y-coordinate of the rectangle.

  • xmax (float) – The maximum x-coordinate of the rectangle.

  • ymax (float) – The maximum y-coordinate of the rectangle.

  • name (str) – The name of the resulting rectangle object. Defaults to ‘bounds_rectangle’.

add_rectangle(width, height, center_x=True, center_y=True)[source]#

Add a rectangle to the scene.

This function creates a rectangle in the 3D space using the specified width and height. The rectangle can be centered at the origin or offset based on the provided parameters. If center_x or center_y is set to True, the rectangle will be positioned at the center of the specified dimensions; otherwise, it will be positioned based on the offsets.

Parameters:
  • width (float) – The width of the rectangle.

  • height (float) – The height of the rectangle.

  • center_x (bool?) – If True, centers the rectangle along the x-axis. Defaults to True.

  • center_y (bool?) – If True, centers the rectangle along the y-axis. Defaults to True.

active_to_coords()[source]#

Convert the active object to a list of its vertex coordinates.

This function duplicates the currently active object in the Blender context, converts it to a mesh, and extracts the X and Y coordinates of its vertices. After extracting the coordinates, it removes the temporary mesh object created during the process. The resulting list contains tuples of (x, y) coordinates for each vertex in the active object.

Returns:

A list of tuples, each containing the X and Y coordinates of the vertices from the active object.

Return type:

list

active_to_shapely_poly()[source]#

Convert the active object to a Shapely polygon.

This function retrieves the coordinates of the currently active object and converts them into a Shapely Polygon data structure. It is useful for geometric operations and spatial analysis using the Shapely library.

Returns:

A Shapely Polygon object created from the active object’s coordinates.

Return type:

Polygon

subdivide_short_lines(co)[source]#

Subdivide all polylines to have at least three points.

This function iterates through the splines of a curve, checks if they are not bezier and if they have less or equal to two points. If so, each spline is subdivided to get at least three points.

Parameters:

co (Object) – A curve object to be analyzed and modified.