How To Run A Scale Tool In Fusion Api: A Guide

Yes, you can absolutely run a scale tool in the Fusion API. This guide shows you how to do it using code. We will explore the steps for Fusion API automation of scaling operations within your designs.

Introduction to Scaling in Fusion 360 API

Programmatic scaling in Fusion is a key task for many design automation projects. When you need to resize components or bodies precisely, using the API is much faster than doing it by hand. This process lets you build Fusion API custom commands or powerful Fusion 360 add-in scale functionality.

This guide focuses on using the Solids workspace to scale geometry. We assume you have basic knowledge of running Fusion API commands and accessing the active design document.

Setting Up the Environment for API Scaling

Before you can start running Fusion API commands for scaling, you need the right setup. This involves getting access to the main application objects and the specific component you want to change.

Accessing Necessary API Objects

To start any Fusion API macro execution, you need three main objects:

  1. The main application instance.
  2. The active document.
  3. The root component of that document.

Here is simple code to get these pieces. This is the starting point for automating tool execution Fusion.

import adsk.core, adsk.fusion import traceback def run(context): ui = None try: app = adsk.core.Application.get() ui = app.userInterface design = app.activeProduct rootComp = design.rootComponent if not design or not rootComp: ui.messageBox(‘No active design found.’) return # Proceed to scaling logic here… except: if ui: ui.messageBox(‘Failed:\n{}’.format(traceback.format_exc()))

Identifying the Target Geometry

Scaling affects geometry. You need to tell the API exactly what to scale. This is usually a component, a body, or a collection of selected entities. For simple scaling, targeting a Component is often best.

If you are controlling Fusion API tools via an add-in, you might identify the target component by name or by iterating through the hierarchy.

Example: Finding a Component by Name

def find_component(rootComp, component_name): # Recursive search function for childComp in rootComp.occurrences: if childComp.name == component_name: return childComp.component found = find_component(childComp.component, component_name) if found: return found return None

The Core Mechanism: Using the Transform Operation

In the Fusion API, scaling is part of the broader Transform functionality, not a standalone “Scale” command object like in the UI. You use the TransformManager to apply scale factors.

The TransformManager and Scale Transformation

The TransformManager controls how geometry moves, rotates, and scales. To scale, you need to build a transformation matrix that represents the desired scale factor.

Required Imports

Make sure you have these at the top of your script:

import adsk.core, adsk.fusion

Building the Scale Matrix

A scale matrix is a 4×4 matrix. If you want uniform scaling (same factor on X, Y, and Z), the matrix looks like this:

1 0 0 0
0 S 0 0
0 0 S 0
0 0 0 1

Where ‘S’ is your scale factor (e.g., 2.0 for doubling the size, 0.5 for halving it).

The Fusion API uses adsk.core.Matrix4D to build this.

# Define the scale factor scale_factor = 2.0 # Double the size # Create a new 4×4 identity matrix transform = adsk.core.Matrix4D.create() # Set the diagonal elements to the scale factor for X, Y, and Z transform.setToScale(scale_factor, scale_factor, scale_factor)

Note on Matrix Initialization: While you can manually set the matrix elements, the dedicated setToScale() method is cleaner and less error-prone for simple CAD API scaling operations.

Defining the Center Point of Scaling

Where does the scaling happen from? This is crucial. If you scale relative to the origin (0,0,0), everything moves. If you scale relative to the component’s center, it scales in place.

You define the center point using an adsk.core.Point3D.

Getting the Center Point

If you are scaling a component, you usually want the bounding box center of that component.

# Assuming ‘targetComponent’ is the component object you found earlier bbox = targetComponent.visualBoundingBox center_point = bbox.center

If you need a specific coordinate for the center:

# Example: Scale around the design origin (0,0,0) origin = adsk.core.Point3D.create(0, 0, 0) scale_center = origin

Executing the Scale Operation

Now we combine the matrix, the center point, and the target geometry using the TransformManager.

Step-by-Step Execution Flow

  1. Get the TransformManager from the design.
  2. Gather the list of items to scale (Components, Bodies, Sketches, etc.).
  3. Define the scale transformation matrix.
  4. Define the center point for the transformation.
  5. Call the apply method.

Scaling a Component (Most Common Use Case)

Scaling a component scales everything inside it (bodies, sketches, other components).

def scale_component(rootComp, component_name, scale_factor): ui = adsk.core.Application.get().userInterface design = adsk.core.Application.get().activeProduct # 1. Find the target component occurrence # This requires a helper function similar to find_component above, # but we need the *Occurrence* for transformation if we are moving # the instance in the root assembly. Let’s focus on scaling the geometry within the component itself first. # A simpler approach for manipulating internal geometry might be needed, # but for standard assembly scaling, we transform the occurrence. # For simplicity, let’s assume we are scaling the geometry *inside* the component definition, # or we are scaling a body directly. # — Scaling a specific Body — body = None # Assume ‘body’ object has been found earlier # 2. Prepare Transformation Matrix transform = adsk.core.Matrix4D.create() transform.setToScale(scale_factor, scale_factor, scale_factor) # 3. Define Scale Center (Using Component Bounding Box Center as example) # We need a representative point. If scaling a body, use its center. scale_center = body.boundingBox.center # 4. Apply the Transformation transformManager = design.transformManager # The apply method takes the geometry, the matrix, and the center point. # For scaling geometry in place, the center point is critical. transformManager.applyTransform(body, transform, scale_center) ui.messageBox(f”Body scaled by factor {scale_factor}”)

Handling Collections of Geometry

Often, you need to scale multiple entities at once (e.g., all bodies in a component). You pass a list of targets to the transformation manager.

# Example of scaling all bodies within a component definition target_component_def = targetComponent.definition bodies_to_scale = target_component_def.bodies if bodies_to_scale.count > 0: scale_factor = 0.75 # Shrink to 75% transform = adsk.core.Matrix4D.create() transform.setToScale(scale_factor, scale_factor, scale_factor) # Calculate an average center point for the group (approximation for in-place scaling) total_x, total_y, total_z = 0, 0, 0 count = 0 for body in bodies_to_scale: center = body.boundingBox.center total_x += center.x total_y += center.y total_z += center.z count += 1 if count > 0: avg_center = adsk.core.Point3D.create(total_x / count, total_y / count, total_z / count) # Apply to all bodies simultaneously transformManager.applyTransform(bodies_to_scale, transform, avg_center) app.activeViewport.refresh() print(f”Successfully scaled {count} bodies.”)

Scaling in Context: Assembly vs. Component Definition

This is one of the trickiest parts of controlling Fusion API tools. When you scale geometry, are you changing the definition of the part, or are you changing the instance (occurrence) in the assembly?

1. Scaling the Component Definition (Master Part)

If you scale the geometry within the component’s definition, every instance (occurrence) of that component in your entire design updates instantly. This is usually what you want if you are changing the base size of a part.

To scale the definition, you access properties from targetComponent.definition. The geometry objects (bodies, sketches) obtained from the definition are what you pass to applyTransform.

2. Scaling the Component Occurrence (Assembly Instance)

If you scale the occurrence, only that specific instance in the assembly changes size. The base part definition remains untouched. This is useful for making one specific instance larger or smaller than its brethren.

To scale the occurrence, you must use the Occurrence.transform property or apply the transformation directly to the occurrence itself if the API allows for transformation of the instance matrix. However, direct scaling often targets the underlying geometry via the definition unless you are manipulating assembly constraints.

For programmatic scaling, it is often cleaner to scale the geometry within the definition, as the API transformation tools are primarily designed to manipulate the actual geometry entities (bodies, faces, etc.).

Advanced Scaling Techniques: Non-Uniform Scaling

Sometimes you need to stretch or compress an object along only one or two axes. This is non-uniform scaling.

Creating the Non-Uniform Matrix

You simply provide different factors for X, Y, and Z when creating the matrix.

1 0 0 0
0 $S_x$ 0 0
0 0 $S_y$ 0
0 0 0 1

In the API:

scale_x = 3.0 # Stretch three times along X scale_y = 1.0 # Keep Y the same scale_z = 0.5 # Compress to half along Z non_uniform_transform = adsk.core.Matrix4D.create() non_uniform_transform.setToScale(scale_x, scale_y, scale_z)

Applying Non-Uniform Scaling

The application process remains the same, but you must choose the scale center carefully. If you scale non-uniformly relative to the center of the object, it will stretch outward from that center.

If you need to stretch an object along its own local axis (e.g., stretch a cylinder along its length), you must first calculate the transformation matrix relative to that local axis system, which involves more complex matrix math (rotation to align axes, scaling, then rotating back). For most Fusion API automation scripts, scaling relative to the world origin or the object’s bounding box center is sufficient.

Working with Sketches During Scaling

Scaling bodies is straightforward, but scaling sketches requires extra care. A sketch is defined by its constraints and dimensions, not just its raw coordinates.

Issues with Scaling Sketches Directly

If you try to scale a sketch entity (like a line or an arc) using the TransformManager, you change its endpoints’ coordinates. This often breaks the sketch constraints or makes the sketch move away from the associated 3D geometry.

Recommended Practice for Sketches

If you scale the parent component’s body, and the sketch is fixed to that body, the sketch may move or distort depending on how it was created.

For robust Fusion 360 scripting scale of sketches:

  1. Scale the Parent Component: If the sketch is part of a component being scaled uniformly, the sketch often scales correctly with the body geometry.
  2. Edit Dimensions (Preferred): If you need a controlled change, it is better to find the relevant sketch dimension object and modify its value directly.

Modifying a Sketch Dimension

def scale_sketch_dimension(sketch_dimension, new_value): try: # Ensure the dimension is editable if sketch_dimension.isDriven: print(“Dimension is driven and cannot be changed directly.”) return sketch_dimension.parameter.value = new_value print(f”Dimension changed to {new_value}”) except Exception as e: print(f”Error changing dimension: {e}”)

If your overall goal is to scale the entire model by a factor, scaling the components and bodies using the TransformManager is usually the way to go. Scaling dimensions is better for fine-tuning or parameter-driven changes.

Best Practices for Robust API Scaling

To ensure your scripts are reliable for running Fusion API commands, follow these practices.

Transaction Management

Any geometric change operation should be wrapped in a Transaction. This allows Fusion 360 to undo the entire operation in one step if something goes wrong.

app = adsk.core.Application.get() design = app.activeProduct transaction = design.transactions.add(“Scale Operation”) try: # — Your transformation code here — transformManager.applyTransform(…) # Success transaction.do() print(“Scaling complete and transaction committed.”) except: # Failure transaction.cancel() app.userInterface.messageBox(“Scaling failed. Reverting changes.”) # Log traceback for debugging

Dealing with Components in Assemblies

When programmatic scaling in Fusion involves assemblies, be careful about which definition you are targeting.

Goal Target Object Effect
Change the size of one specific instance in the assembly. Target the Occurrence‘s geometry/transform. Only that instance scales.
Change the size of the master part, affecting all uses. Target the ComponentDefinition‘s geometry. All instances update.

If you are automating tool execution Fusion for assembly manipulation, look for the Occurrence object first, and then access its geometry via the definition if direct manipulation of the occurrence geometry isn’t supported or desired.

Refreshing the View

After large or complex transformations, the viewport might not update immediately. For immediate visual feedback, especially in testing Fusion API macro execution, force a refresh:

app.activeViewport.refresh()

Example Scenario: Scaling the Entire Design

A common request is to scale the entire active design uniformly by a factor of 0.5 (halving the size).

This requires iterating through all top-level bodies in the root component definition.

def scale_entire_design(scale_factor): app = adsk.core.Application.get() ui = app.userInterface design = app.activeProduct rootCompDef = design.rootComponent.definition transformManager = design.transformManager if not rootCompDef: ui.messageBox(“Could not access root component definition.”) return # 1. Gather all geometry (Bodies) all_bodies = rootCompDef.bodies if all_bodies.count == 0: ui.messageBox(“No bodies found to scale.”) return # 2. Prepare Transformation scale_matrix = adsk.core.Matrix4D.create() scale_matrix.setToScale(scale_factor, scale_factor, scale_factor) # 3. Calculate Average Center (Crucial for in-place scaling of a collection) total_x, total_y, total_z = 0, 0, 0 # We need to calculate the bounding box of the *entire* set of bodies # Fusion API doesn’t offer a collective bounding box easily, so we aggregate. first_body = all_bodies.item(0) bbox = first_body.boundingBox for i in range(1, all_bodies.count): current_body = all_bodies.item(i) # Expand the existing bounding box to include the new body’s box bbox.expand(current_body.boundingBox) scale_center = bbox.center # 4. Execute Transaction transaction = design.transactions.add(“Scale Design by Factor ” + str(scale_factor)) try: # Apply the scale transformation to the collection of bodies transformManager.applyTransform(all_bodies, scale_matrix, scale_center) transaction.do() app.activeViewport.refresh() ui.messageBox(f”Design scaled successfully by {scale_factor} around center {scale_center.x:.2f}, {scale_center.y:.2f}, {scale_center.z:.2f}”) except: transaction.cancel() ui.messageBox(“Failed to scale design: ” + traceback.format_exc()) # Example Call (Run this within your main script entry point) # scale_entire_design(0.5)

Integrating Scaling into User Interfaces

When developing a Fusion 360 add-in scale functionality, you often need UI elements to accept the scale factor from the user.

Using Input Dialogs

You can use the adsk.core.UserInterface.inputBox method to quickly gather numerical input.

app = adsk.core.Application.get() ui = app.userInterface scale_input = ui.inputBox(“Enter Scale Factor (e.g., 2.0 for doubling):”, “Component Scaler”, “1.0”) # Default value if scale_input: try: factor = float(scale_input) # Call your scaling function here, e.g.: # scale_component(rootComp, “MyPart”, factor) print(f”User requested scale factor: {factor}”) except ValueError: ui.messageBox(“Invalid input. Please enter a valid number.”)

This ties the backend running Fusion API commands logic to a simple frontend interaction, crucial for any functional add-in.

Summary Table of Key API Methods for Scaling

Task API Method Used Object Accessed Notes
Define Scale adsk.core.Matrix4D.setToScale(sx, sy, sz) N/A Creates the scaling transformation.
Define Center adsk.core.Point3D.create(x, y, z) N/A Sets the pivot point for the scaling.
Apply Transform transformManager.applyTransform() adsk.fusion.TransformManager Executes the actual scaling on geometry.
Get Geometry .bodies, .sketches, .components adsk.fusion.ComponentDefinition How you list the targets for scaling.
Group Changes design.transactions.add() adsk.fusion.Design Essential for undo/redo integrity.

Final Thoughts on Programmatic Scaling

Controlling Fusion API tools like scaling provides immense power. Whether you are implementing simple resizing within a Fusion API automation script or building complex Fusion API custom commands, mastering the TransformManager and Matrix4D objects is the key. Remember to always wrap destructive operations in transactions and define your scale center precisely to achieve the desired result without unwanted movement.

Frequently Asked Questions (FAQ)

Q: Can I scale an existing feature (like a hole or fillet) using the API?

A: You generally cannot scale individual features directly. Features are historical operations. If you scale the parent body or component geometry using the transformation manager, the geometry associated with that feature will also scale or deform accordingly. For controlled feature size changes, you must edit the feature’s defining parameters (e.g., the diameter of a Hole feature) via the API’s Feature/Parameters collection, not through geometric transformation.

Q: How do I scale an assembly occurrence without affecting other instances?

A: This requires manipulating the occurrence’s transformation matrix relative to the assembly root. You would typically get the current occurrence, create a new scale matrix, and combine it with the occurrence’s existing transformation using matrix multiplication (using matrixA.multiply(matrixB)). This effectively moves and scales just that instance in the assembly structure.

Q: What is the difference between scaling geometry in the root component definition versus scaling an occurrence?

A: Scaling the root component definition changes the master CAD model. Every place that part is used (every occurrence) updates to the new size. Scaling an occurrence only changes how that specific instance appears in the assembly structure; the master definition remains unchanged.

Q: Does scaling affect the feature history tree?

A: No. When you use the TransformManager to scale geometry, you are applying a direct geometric offset, often called a direct modification or move/scale operation. This modification is not recorded as a parametric “Scale Feature” in the history timeline. This is why it is often used in specialized Fusion API macro execution rather than standard parametric modeling workflows.

Leave a Comment