occurrences.addByInsert() -> Wrong position and orientation with the inserted component

occurrences.addByInsert() -> Wrong position and orientation with the inserted component

maurizio_manzi
Advocate Advocate
123 Views
0 Replies
Message 1 of 1

occurrences.addByInsert() -> Wrong position and orientation with the inserted component

maurizio_manzi
Advocate
Advocate

Hello,
the position and the orientation of the via anyCad (occurrences.addByInsert) are wrong. The origin of the inserted component and the origin of the receiving component does not match, although my

baseTransform = occ.transform.
Best regards
Maurizio
28-05-_2025_14-27-33.png
import adsk.core, adsk.fusion, adsk.cam, traceback, os, math, subprocess, configparser, re
import adsk.core as core
from typing import Tuple
import platform, getpass, webbrowser
# import adsk.cam

# Initialize the global variables for the Application and UserInterface objects.
app = adsk.core.Application.get()
ui  = app.userInterface


def run(_context: str):


    # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    nameOfProject = "Manzi"             # Name of project, that contains the folder (-path)
    folderPath = "Elektrode/Halter"     # Folder path that contains the construction, that must be insert via anyCad
    constrToInsertName = "ER_007986"    # Name of construction, that must be insert via anyCad
    # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!



    try:
        # Your code goes here.
        trans = adsk.core.Matrix3D.create()
        trans.setToRotation(
            0.349066,
            adsk.core.Vector3D.create(0, 0, 1),
            adsk.core.Point3D.create(0, 0, 0)
        )
        trans.setCell(0, 3, 10)
        trans.setCell(1, 3, 5)
        trans.setCell(2, 3, 7)

        # Create new component occurrence
        design: adsk.fusion.Design = app.activeProduct
        root = design.rootComponent # Get the root component of the active design
        occ: fusion.Occurrence = root.occurrences.addNewComponent(trans)

        insertHolderFileToComp(nameOfProject, folderPath, constrToInsertName, occ)

    except:  #pylint:disable=bare-except
        # Write the error message to the TEXT COMMANDS window.
        app.log(f'Failed:\n{traceback.format_exc()}')






def insertHolderFileToComp(targetProjectName, folderPath, fileName, occ):
    try:
        targetFolderName = re.sub(r'(\\\\|//|\\)', '/', folderPath) # Replace // and \ and \\ with a /
        targetFolderName = targetFolderName.removesuffix("/") # Remove / (only if it's the latest char of the string)

        design: adsk.fusion.Design = app.activeProduct
        root = design.rootComponent # Get the root component of the active design
        isParametric = design.designType == adsk.fusion.DesignTypes.ParametricDesignType
        if isParametric == False:
            design.designType = adsk.fusion.DesignTypes.ParametricDesignType # .addByInsert is only available with parametric design type. Chnage to this mode

        # Split folderpath in separate folder-names
        pathParts = targetFolderName.split("/")

        # get reference to data-project
        theData: adsk.core.Data = app.data
        targetProj: adsk.core.DataProject = None
        projLst: list = theData.dataProjects.asArray()
        proj: adsk.core.DataProject
        for proj in projLst:
            if proj.name == targetProjectName:
                targetProj = proj
                break
        if not targetProj:
            ui.messageBox(f'{projectNotFoundStr} [{targetProjectName}]')
            return


        # get reference to data-folder
        targetFold: adsk.core.DataFolder = None
        currentFolder = targetProj.rootFolder # Start with the root folder of the project
        # Loop around all levels
        for part in pathParts:
            found = False
            # Search in the actual folder for a sub-folder with the name part
            for subFold in currentFolder.dataFolders.asArray():
                if subFold.name == part:
                    currentFolder = subFold
                    found = True
                    break
            if not found:
                ui.messageBox(f'{folderPathNotFoundStr} {" / ".join(pathParts[:pathParts.index(part)+1])}')
                return
        # currentFolder point now to the deepest sub-folder
        targetFold = currentFolder
        #ui.messageBox(targetFold.name)
       
        # Get the file and insert it to occ
        files: list = targetFold.dataFiles.asArray()
        file:adsk.core.DataFile
        if not files:
            ui.messageBox(noFilesFoundStr + "\n" + targetProjectName + "\n" + targetFolderName)
            return

        occurrences = occ.component.occurrences
        baseTransform = occ.transform
        for file in files:
            if file.name == fileName:
                newOcc = occurrences.addByInsert(
                    file,               # The DataFile
                    baseTransform,      # Position/Orientetion (the same as in occ)
                    False               # As an embedded component
                )



        if isParametric == False:
            design.designType = adsk.fusion.DesignTypes.DirectDesignType # parametric design type was not on. Turn off after .addByInsert
                    
        

    except Exception as e:
        error_message = (
            f"{"anyCad error"}\n\n"
            f"Error:\n{str(e)}\n\n"
            f"Traceback:\n{traceback.format_exc()}"
        )
        adsk.core.Application.get().userInterface.messageBox(error_message, 'Error')

 

0 Likes
124 Views
0 Replies
Replies (0)