Python script for Autodesk Fusion 360

Python script for Autodesk Fusion 360

Anonymous
Not applicable
4,459 Views
10 Replies
Message 1 of 11

Python script for Autodesk Fusion 360

Anonymous
Not applicable

I want to draw 3D spheres using x,y,z coordinate. Then I am trying to use Python script for Autodesk Fusion 360(CAD).

I want to draw 3D spheres(all radius is same) using center points data of the spheres(x,y,z data from csv file) at once.
Could you please advice my code?

Q. How can I set to read the csv data(x,y,z) from a specific directory for drawing the spheres?

Q. I want to know how can I make the spheres from the data at once.

Q. How can I export the drawn spheres to STL, DWG format and set a specific directory and file name?

 

Furthermore, the error has occurred as the image below. "No module named 'adsk' problem".

I tried to install the adsk module, but I cant intall.

Then I found that the adsk is in definition folder. So I tried to run the file. But I cant get result.

 

 

I have attached error image and my code.

 

error.PNG

 

0 Likes
4,460 Views
10 Replies
Replies (10)
Message 2 of 11

zachesenbock
Contributor
Contributor

Assuming your preferred format for the CSV file is

 

x,y,z
x,y,z
x,y,z
x,y,z
x,y,z

 

Then we can iterate through it with something like this

 

    f = open(filename, 'r')
    line = f.readline()
    # CSV Data array
    data = []
    while line:
        pntStrArr = line.split(',')
        for pntStr in pntStrArr:
            data.append( str(pntStr))
            x = data[0]
            y = data[1]
            z = data[2]

            sphereCenter = adsk.core.Point3D.create(x, y, z)

 

And from there you can create your spheres with that reference point.

 

You can specify the directory of the CSV with the "filename" variable.

 

As for the reason you are seeing "adsk Not Found", you must run this script from inside Fusion 360. (Shift + S)

0 Likes
Message 3 of 11

BrianEkins
Mentor
Mentor

Here's a script that reads a CSV file and creates spheres.  I extended it so that instead of just the center of the sphere it also reads the radius from the CSV.  I use the temporary B-Rep capabilities of Fusion to create the spheres and a direct modeling document to speed up the process.  I was also curious about one other thing and made an option where it will either create one single body for all spheres or a body for each sphere.  For a single body, it takes 1.3 seconds to create 1000 spheres and for individual bodies it takes 5.08 seconds.  Interactively, Fusion wouldn't let you create them as a single body but through the API you can.  I haven't found that it causes any issues but I wouldn't want to do a lot of additional modeling with a model like that.  It's a valid solid model for the modeling kernel but Fusion simplifies it further. 

 

For fun, here's an example of the result where I set one of the center spheres to be a light source.

 

Spheres.png

 

There are samples in the documentation that demonstrate exporting models in different formats.  However, if you want to create a 2D drawing and export that, you'll need to do it interactively because there isn't any API support for the drawing functionality.

 

Here's my code and I've attached the CSV I tested with which I created with an Excel macro and a random number function.

import adsk.core, adsk.fusion, adsk.cam, traceback
import time

def run(context):
    ui = None
    try:
        app = adsk.core.Application.get()
        ui  = app.userInterface

        # Create a new document.
        doc = app.documents.add(adsk.core.DocumentTypes.FusionDesignDocumentType)
        des = app.activeProduct
        root = des.rootComponent
        bodies = root.bRepBodies

        # Make sure it is a direct modeling document.
        des.designType = adsk.fusion.DesignTypes.DirectDesignType

        # Open and read the CSV file into a list.
        with open("C:\\Temp\\Spheres.csv", "r") as coordFile:
            content = coordFile.readlines()
            content = [x.strip() for x in content]

        # Remove the first item, which is the header line.
        del content[0]

        tBrep = adsk.fusion.TemporaryBRepManager.get()
        mainBody = None

        # Flag used to indicate if a single body should be
        # created or a body for each sphere.
        singleBody = False

        startTime = time.time()

        cnt = 0
        for line in content:
            pieces = line.split(',')
            x = float(pieces[0])
            y = float(pieces[1])
            z = float(pieces[2])
            radius = float(pieces[3])

            # Create a sphere.
            center = adsk.core.Point3D.create(x,y,z)
            sphereBody = tBrep.createSphere(center, radius)

            cnt += 1
            if not singleBody:
                # Add this sphere as a body.
                body = bodies.add(sphereBody)
                body.name = 'Sphere ' + str(cnt)
            else:
                # Combine this sphere with any existing spheres.
                if mainBody:
                    tBrep.booleanOperation(mainBody, sphereBody, adsk.fusion.BooleanTypes.UnionBooleanType)
                else:
                    mainBody = sphereBody

        if singleBody:
            body = bodies.add(mainBody)
            body.name = 'Combined Sphere Bodies'

        ui.messageBox('Total time for {} spheres: {}'.format(cnt, time.time() - startTime) )
    except:
        if ui:
            ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))

 

---------------------------------------------------------------
Brian Ekins
Inventor and Fusion 360 API Expert
Website/Blog: https://EkinsSolutions.com
Message 4 of 11

Anonymous
Not applicable

Thank you @BrianEkins 

 

I can't run the script using Script ADD-INS when I click run after creating a new script.

After clicking it, nothing happens.

The other sample scripts are also the same.

(C++ type file looks run.)

I have attached my operation movie and CSV file (My CSV file doesn't include radius information.).

 

Furthermore, I'm sorry I don't understand the exact meaning of interactively as below your words.

 

"However, if you want to create a 2D drawing and export that, you'll need to do it interactively because there isn't any API support for the drawing functionality."

 

Is it impossible to export 3D spheres as STL format using a script?

And, I have many CSV files(100~3000). It's hard to transfer to STL files(Spheres) one by one.

Is it possible to transfer to STL files(100-3000) automatically? or more convenient method?

 

0 Likes
Message 5 of 11

Anonymous
Not applicable

Thank you @zachesenbock 

 

I can't run the script using Script ADD-INS when I click run after creating a new script.

After clicking it, nothing happens.

The other sample scripts are also the same.

(C++ type file looks run.)

I have attached my operation movie.

 

Furthermore, I want to export 3D spheres as STL format using a script.

I have many CSV files(100~3000). It's hard to transfer to STL files(Spheres) one by one.

Is it possible to transfer to STL files(100-3000) automatically? or more convenient method?

0 Likes
Message 6 of 11

zachesenbock
Contributor
Contributor

My first thought is that maybe Fusion 360 didn't properly update your Python. Try manually installing Python 3.7.3. I would also recommend trying to place your script directly in the scripts folder.

0 Likes
Message 7 of 11

JeromeBriot
Mentor
Mentor

@Anonymous wrote:

Furthermore, I want to export 3D spheres as STL format using a script.

I have many CSV files(100~3000). It's hard to transfer to STL files(Spheres) one by one.

Is it possible to transfer to STL files(100-3000) automatically? or more convenient method?


Hello,

 

Create a unit sphere centered on (0,0,0) with Fusion 360 then export it in STL.

 

Now you need a code outside of Fusion that reads the data from this STL file and for each line of the CSV file:

  • Multiplies the coordinates by the radius r
  • Adds the coordinates of the center (x,y,z)
  • Saves modified coordinates in a new STL file

 

0 Likes
Message 8 of 11

rbtHTJJU
Contributor
Contributor

phyllotaxMe_1.pngHi Brian,

 

I have been reading some of your responses to Python/Fusion questions and although I've been able to make some headway with my scripting, I haven't been able to do any further research on your statement:

I use the temporary B-Rep capabilities of Fusion to create the spheres and a direct modeling document to speed up the process.


It also mentions the CSV file as being "attached" but I could not locate it anywhere on that forum thread.

The goal is to do in Fusion the same thing that I do with almost identical Python code in Blender, where I can instantiate literally hundreds of objects such as cones and icospheres, etc. and it takes like ½ a second.

Fusion, on the other hand, seems to be a real memory hog as it times out with the whirling rainbow when I try to merely establish like 50 circles in a sketch as opposed to the 360 that I'm doing in blender and that's only half of the exercise that I'm trying.

 

I would like to extrude the circles, and, eventually any body(s) that I target, and use them as a texture applied to another surface. But again, I can only get up to about 50 and then Fusion just times out and that's just circles in a sketch. (see attached)

 

Perhaps you can elaborate on the items in your statement there so I can test those out - B-Rep capabilities and "direct modeling".

 

Thanks, Rob T

0 Likes
Message 9 of 11

rbtHTJJU
Contributor
Contributor

As Borat would say - "Great Success!" 

 

phylloDo2.png

0 Likes
Message 10 of 11

BrianEkins
Mentor
Mentor

My original response was from a long time ago, so the test CSV is gone. However, it was a simple format like that shown below. Each row defines a sphere where the first three columns are the X, Y, and Z values, and the fourth column is the radius in centimeters.

0.0, 0.0 ,0.0 ,5.0
1.0 ,5.5, 2.25, 4.0
3.5, 2.1, 3.6, 1.5

 

Here's a link to the content of a class I presented at Autodesk University a few years ago that talks about B-Rep and covers the idea of Temporary B-Rep data.

https://www.autodesk.com/autodesk-university/class/Understanding-Geometry-and-B-Rep-Inventor-and-Fus... 

---------------------------------------------------------------
Brian Ekins
Inventor and Fusion 360 API Expert
Website/Blog: https://EkinsSolutions.com
0 Likes
Message 11 of 11

rbtHTJJU
Contributor
Contributor

Thanks Brian! I was out of pocket yesterday so just seeing this Sat AM. Great! I will take a look at the link there. I am also working on some random generated matrices from Basic code that I originally developed back in '88 for computer generated carpet designs and have now adapted that to Python and trying to map pipes or sweeps along the lines. Doing it by hand now but should be able to do that programmatically as well.

 

maze_1maze_1

 

Thanks again, for the response and I will continue following your work and posts.

Cheers,

Rob Thomas,

Industrial Designer

0 Likes