How to create selectionSet using the API?

How to create selectionSet using the API?

sharas_s
Contributor Contributor
1,145 Views
7 Replies
Message 1 of 8

How to create selectionSet using the API?

sharas_s
Contributor
Contributor

Hello everyone,

 

I am trying to create a Selection Set of a subcomponent sketch using API with `selectionSets.add()` but had no luck with it. Does anyone know how to make this method work? From the error message it seems this method requires 2 or 3 arguments instead of 1 or 2 mentioned in the documentation. Error message:

sharass_1-1660058580357.png

Example document structure for testing:

sharass_0-1660058198803.png

 

Code to reproduce the error:

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

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

        doc = app.activeDocument
        design = doc.products.item( 0 )

        for occ in design.rootComponent.occurrences:
            for sketch in occ.component.sketches:
                if 'XXXX' in sketch.name:
                    design.selectionSets.add(sketch, f'my_selection_set')

    except:
        if ui:
            ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))

 

I was able to solve this problem using commands but would like to know if there is a way using API:

cmdDefs: adsk.core.CommandDefinitions = ui.commandDefinitions
cmdDef: adsk.core.CommandDefinition = cmdDefs.itemById('CreateSelectionGroupCmd')
if cmdDef:
    cmdDef.execute()

 

0 Likes
Accepted solutions (1)
1,146 Views
7 Replies
Replies (7)
Message 2 of 8

Jorge_Jaramillo
Collaborator
Collaborator

Hi @sharas_s ,

 

From the SelectionSets specification it stands that the first parameter (entities) is an array.

So just enclose sketch in "[ ]" like so and you're done:

design.selectionSets.add([sketch], f'my_selection_set')

And if you need to include many more objects, just populate an array with all elements you want on the selection set and pass the array to the add method.

 

Hope this help.

 

Regards,

Jorge

0 Likes
Message 3 of 8

sharas_s
Contributor
Contributor

Hey @Jorge_Jaramillo ,

 

Thank you for a response. Tried putting the sketch into a list but got another error:

sharass_0-1660115113625.png

 

0 Likes
Message 4 of 8

kandennti
Mentor
Mentor

@sharas_s .

 

I think I get errors in sketches other than the root component.
I thought it might be a Proxy issue, but I still get the error.

0 Likes
Message 5 of 8

kandennti
Mentor
Mentor

I have done such a test.

 

# Fusion360API Python script
import traceback
import adsk.fusion
import adsk.core


def run(context):
    ui = adsk.core.UserInterface.cast(None)
    try:
        app: adsk.core.Application = adsk.core.Application.get()
        ui = app.userInterface
        app.documents.add(adsk.core.DocumentTypes.FusionDesignDocumentType)
        des: adsk.fusion.Design = app.activeProduct
        des.designType = adsk.fusion.DesignTypes.ParametricDesignType
        root: adsk.fusion.Component = des.rootComponent


        # create body & sketch
        initDammy(root, 0)

        occ: adsk.fusion.Occurrence = root.occurrences.addNewComponent(
            adsk.core.Matrix3D.create()
        )
        initDammy(occ.component, 2)

        # create SelectionSet
        # root
        initSelectionSet(root.bRepBodies[0])
        initSelectionSet(root.sketches[0])

        # occ
        initSelectionSet(occ.component.bRepBodies[0])
        initSelectionSet(occ.component.sketches[0])

        # proxy
        occ: adsk.fusion.Occurrence = root.occurrences[0]
        initSelectionSet(
            occ.component.bRepBodies[0].createForAssemblyContext(
                occ
            )
        )
        initSelectionSet(
            occ.component.sketches[0].createForAssemblyContext(
                occ
            )
        )

    except:
        if ui:
            ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))


def initSelectionSet(
    entity: adsk.core.Base):

    if not hasattr(entity, 'parentComponent'):
        return

    comp: adsk.fusion.Component = entity.parentComponent
    des: adsk.fusion.Design = comp.parentDesign

    try:
        des.selectionSets.add(
            [entity],
            entity.name
        )
    except:
        name = entity.name
        if entity.nativeObject:
            name = entity.nativeObject.name

        adsk.core.Application.get().log(
            f'Failed: {name}'
        )


def initDammy(
    comp: adsk.fusion.Component,
    value: float) -> None:

    # body
    tmgMgr: adsk.fusion.TemporaryBRepManager = adsk.fusion.TemporaryBRepManager.get()
    tmpBody: adsk.fusion.BRepBody = tmgMgr.createSphere(
        adsk.core.Point3D.create(value, 0, 0),
        1
    )

    baseFeat: adsk.fusion.BaseFeature = None
    baseFeat = comp.features.baseFeatures.add()

    bodies: adsk.fusion.BRepBodies = comp.bRepBodies
    baseFeat.startEdit()
    bodies.add(tmpBody, baseFeat)
    baseFeat.finishEdit()

    baseFeat.bodies[0].name = f'{comp.name}_{baseFeat.bodies[0].name}'

    # sketch
    skt: adsk.fusion.Sketch = comp.sketches.add(comp.xYConstructionPlane)
    skt.name = f'{comp.name}_{skt.name}'
    skt.sketchCurves.sketchCircles.addByCenterRadius(
        adsk.core.Point3D.create(value, 2, 0),
        1
    )
0 Likes
Message 6 of 8

Jorge_Jaramillo
Collaborator
Collaborator

Hi @sharas_s ,

 

You missed the name of the selection set which is the second argument:

wtallerdemadera_0-1660140495258.png

 

 

In this example I created 4 selections sets:

 

def createSelectionSets():
    try:
        des = adsk.fusion.Design.cast(app.activeProduct)
        sk = des.rootComponent.sketches.itemByName('xy1')
        lines = [skc for skc in sk.sketchCurves if skc.length<1]
        des.selectionSets.add(lines, 'instagram_curves_short')
        lines = [skc for skc in sk.sketchCurves if skc.length>=1]
        des.selectionSets.add(lines, 'instagram_curves_long')
        points = [skp for skp in sk.sketchPoints]
        des.selectionSets.add(points, 'instagram_points')
        disc = []
        ps = []
        for skcps in sk.sketchCurves.sketchControlPointSplines:
            if skcps.startSketchPoint.geometry.asArray() not in ps and \
               skcps.endSketchPoint.geometry.asArray not in ps:
                disc.append(skcps)
                ps.append(skcps.startSketchPoint.geometry.asArray())
                ps.append(skcps.endSketchPoint.geometry.asArray())
        des.selectionSets.add(disc, 'instagram_discontinuous')
    except:
        pass

 

 

This is the result:

 

wtallerdemadera_2-1660140736904.png

 

Hope this help.

 

Regards,

Jorge

 

0 Likes
Message 7 of 8

kandennti
Mentor
Mentor
Accepted solution

It could be created by using the TextCommands.

 

# Fusion360API Python script
import traceback
import adsk.fusion
import adsk.core


def run(context):
    ui = adsk.core.UserInterface.cast(None)
    try:
        app: adsk.core.Application = adsk.core.Application.get()
        ui = app.userInterface
        app.documents.add(adsk.core.DocumentTypes.FusionDesignDocumentType)
        des: adsk.fusion.Design = app.activeProduct
        des.designType = adsk.fusion.DesignTypes.ParametricDesignType
        root: adsk.fusion.Component = des.rootComponent


        # create body & sketch
        initDammy(root, 0)

        occ: adsk.fusion.Occurrence = root.occurrences.addNewComponent(
            adsk.core.Matrix3D.create()
        )
        initDammy(occ.component, 2)

        # create SelectionSet - using textcommand
        # root
        initSelectionSet_TxtCmds(root.bRepBodies[0])
        initSelectionSet_TxtCmds(root.sketches[0])

        # occ
        initSelectionSet_TxtCmds(
            occ.component.bRepBodies[0].createForAssemblyContext(
                occ
            )
        )
        initSelectionSet_TxtCmds(
            occ.component.sketches[0].createForAssemblyContext(
                occ
            )
        )

    except:
        if ui:
            ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))


def initSelectionSet_TxtCmds(
    entity: adsk.core.Base):

    if not hasattr(entity, 'parentComponent'):
        return

    comp: adsk.fusion.Component = entity.parentComponent
    des: adsk.fusion.Design = comp.parentDesign

    app: adsk.core.Application = adsk.core.Application.get()
    ui: adsk.core.UserInterface = app.userInterface
    sels: adsk.core.Selections = ui.activeSelections
    sels.clear()
    sels.add(entity)

    beforeLst = [s for s in des.selectionSets]
    app.executeTextCommand('NuComponents.CreateSelectionGroupCmd')
    afterLst = [s for s in des.selectionSets]

    res = list(filter(lambda x: x not in beforeLst, afterLst))
    if len(res) < 1:
        return None

    selSet: adsk.core.SelectionSet = res[0]
    selSet.name = f'{entity.name}_TxtCmds'

    return selSet


def initDammy(
    comp: adsk.fusion.Component,
    value: float) -> None:

    # body
    tmgMgr: adsk.fusion.TemporaryBRepManager = adsk.fusion.TemporaryBRepManager.get()
    tmpBody: adsk.fusion.BRepBody = tmgMgr.createSphere(
        adsk.core.Point3D.create(value, 0, 0),
        1
    )

    baseFeat: adsk.fusion.BaseFeature = None
    baseFeat = comp.features.baseFeatures.add()

    bodies: adsk.fusion.BRepBodies = comp.bRepBodies
    baseFeat.startEdit()
    bodies.add(tmpBody, baseFeat)
    baseFeat.finishEdit()

    baseFeat.bodies[0].name = f'{comp.name}_{baseFeat.bodies[0].name}'

    # sketch
    skt: adsk.fusion.Sketch = comp.sketches.add(comp.xYConstructionPlane)
    skt.name = f'{comp.name}_{skt.name}'
    skt.sketchCurves.sketchCircles.addByCenterRadius(
        adsk.core.Point3D.create(value, 2, 0),
        1
    )
Message 8 of 8

sharas_s
Contributor
Contributor

Hey, thank you for your inputs. 

@Jorge_Jaramillo your solutions works but only if sketches are in rootComponent. If they are within a subcomponent (as showed in original post), function doesn't work anymore, even if you use proxy as @kandennti mentioned. 

@kandennti  solution using TextCommands seems the best option currently. Seems to work in all cases. At least until API function is fixed or explained better how to use it in such situations. 

0 Likes