defining a selection input

defining a selection input

Anonymous
Not applicable
1,061 Views
4 Replies
Message 1 of 5

defining a selection input

Anonymous
Not applicable

Hello all,

  I'm very new to coding and the API and trying to make a program.  I'm using some of the sample programs to help guide me, but am having trouble finding an example of the addSelectionInput.  To clarify, It working in the sense that when I run the script, I can select a face, but I figure out how to define that selection to something I can use in the script.  I want have the script let the user select a face, then the sketch be made on that face and extruded a distance that the user defines.  Everything works if I have the sketch made off the xyplane, but when I try to incorporate the user selected face I get this error:

 

jacobreidmartinDGPF9_0-1589640608517.png

 

I'm sure this is something simple that I am overlooking and just can't find. Can someone please help me with a sample code of how to define my selection so that I can use it in my sketch.

 

Thank you so much.

Jacob

0 Likes
Accepted solutions (1)
1,062 Views
4 Replies
Replies (4)
Message 2 of 5

JeromeBriot
Mentor
Mentor

Hello,

 

Show us your code. Use the button "</>" to insert code in your message.

 

0 Likes
Message 3 of 5

Anonymous
Not applicable

My code is mostly taken from the "bolt" example.  I've changes it so that the user selects a face (lines 87-89) and then that face is used as the sketch plane (line 139).  The problem is that I need to define face1 and I don't know where or how to do this in the code. I'm sure it is something simple that I am just overlooking.  I really appreciate the help.

#Author-Autodesk Inc.
#Description-Create bolt

import adsk.core, adsk.fusion, traceback
import math

defaultBoltName = 'Bolt'
defaultBodyLength = .635

# global set of event handlers to keep them referenced for the duration of the command
handlers = []
app = adsk.core.Application.get()
if app:
    ui = app.userInterface

newComp = None

def createNewComponent():
    # Get the active design.
    product = app.activeProduct
    design = adsk.fusion.Design.cast(product)
    rootComp = design.rootComponent
    allOccs = rootComp.occurrences
    newOcc = allOccs.addNewComponent(adsk.core.Matrix3D.create())
    return newOcc.component

class BoltCommandExecuteHandler(adsk.core.CommandEventHandler):
    def __init__(self):
        super().__init__()
    def notify(self, args):
        try:
            unitsMgr = app.activeProduct.unitsManager
            command = args.firingEvent.sender
            inputs = command.commandInputs

            bolt = Bolt()
            for input in inputs:
                if input.id == 'boltName':
                    bolt.boltName = input.value
                elif input.id == 'bodyLength':
                    bolt.bodyLength = adsk.core.ValueInput.createByString(input.expression)


            bolt.buildBolt();
            args.isValidResult = True

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

class BoltCommandDestroyHandler(adsk.core.CommandEventHandler):
    def __init__(self):
        super().__init__()
    def notify(self, args):
        try:
            # when the command is done, terminate the script
            # this will release all globals which will remove all event handlers
            adsk.terminate()
        except:
            if ui:
                ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))

class BoltCommandCreatedHandler(adsk.core.CommandCreatedEventHandler):    
    def __init__(self):
        super().__init__()        
    def notify(self, args):
        try:
            cmd = args.command
            cmd.isRepeatable = False
            onExecute = BoltCommandExecuteHandler()
            cmd.execute.add(onExecute)
            onExecutePreview = BoltCommandExecuteHandler()
            cmd.executePreview.add(onExecutePreview)
            onDestroy = BoltCommandDestroyHandler()
            cmd.destroy.add(onDestroy)
            # keep the handler referenced beyond this function
            handlers.append(onExecute)
            handlers.append(onExecutePreview)
            handlers.append(onDestroy)

            #define the inputs
            inputs = cmd.commandInputs

            #inputs = cmd.commandInputs
            inputs.addStringValueInput('boltName', 'Bolt Name', defaultBoltName)

            selectionInput1 = inputs.addSelectionInput('face1', 'Select Face', 'Select a planar face')
            selectionInput1.setSelectionLimits(1,1)
            selectionInput1.addSelectionFilter('PlanarFaces')

            initBodyLength = adsk.core.ValueInput.createByReal(defaultBodyLength)
            inputs.addValueInput('bodyLength', 'Body Length', 'cm', initBodyLength)

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

class Bolt:
    def __init__(self):
        self._boltName = defaultBoltName
        self._bodyLength = adsk.core.ValueInput.createByReal(defaultBodyLength)
        



    #properties

    @Anonymous
    def boltName(self):
        return self._boltName
    @boltName.setter
    def boltName(self, value):
        self._boltName = value

    @Anonymous
    def bodyLength(self):
        return self._bodyLength
    @bodyLength.setter
    def bodyLength(self, value):
        self._bodyLength = value
    


    def buildBolt(self):
        global newComp
        newComp = createNewComponent()
        if newComp is None:
            ui.messageBox('New component failed to create', 'New Component Failed')
            return

        # Create a new sketch.



        sketches = newComp.sketches
        xyPlane = newComp.xYConstructionPlane
        xzPlane = newComp.xZConstructionPlane
        sketch = sketches.add(face1)
        center = adsk.core.Point3D.create(0, 0, 0)
        
        circles = sketch.sketchCurves.sketchCircles
        # Add a circle to the sketch circles collection by using addByCenterRadius. 
        # The needed parameters are the center points and radius.
        circle1 = circles.addByCenterRadius(adsk.core.Point3D.create(0, 0, 0), 7.62)

        extrudes = newComp.features.extrudeFeatures
        prof = sketch.profiles[0]
        extInput = extrudes.createInput(prof, adsk.fusion.FeatureOperations.NewBodyFeatureOperation)

        extInput.setDistanceExtent(False, self.bodyLength)
        headExt = extrudes.add(extInput)

        fc = headExt.faces[0]
        bd = fc.body
        bd.name = self.boltName


def run(context):
    try:
        product = app.activeProduct
        design = adsk.fusion.Design.cast(product)
        if not design:
            ui.messageBox('It is not supported in current workspace, please change to MODEL workspace and try again.')
            return
        commandDefinitions = ui.commandDefinitions
        #check the command exists or not
        cmdDef = commandDefinitions.itemById('Bolt')
        if not cmdDef:
            cmdDef = commandDefinitions.addButtonDefinition('Bolt',
                    'Create Bolt',
                    'Create a bolt.',
                    './resources') # relative resource file path is specified

        onCommandCreated = BoltCommandCreatedHandler()
        cmdDef.commandCreated.add(onCommandCreated)
        # keep the handler referenced beyond this function
        handlers.append(onCommandCreated)
        inputs = adsk.core.NamedValues.create()
        cmdDef.execute(inputs)

        # prevent this module from being terminate when the script returns, because we are waiting for event handlers to fire
        adsk.autoTerminate(False)
    except:
        if ui:
            ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
0 Likes
Message 4 of 5

JeromeBriot
Mentor
Mentor
Accepted solution

See modifications at lines 42-45 and at line 121:

 

#Author-Autodesk Inc.
#Description-Create bolt

import adsk.core, adsk.fusion, traceback
import math

defaultBoltName = 'Bolt'
defaultBodyLength = .635

# global set of event handlers to keep them referenced for the duration of the command
handlers = []
app = adsk.core.Application.get()
if app:
    ui = app.userInterface

newComp = None

def createNewComponent():
    # Get the active design.
    product = app.activeProduct
    design = adsk.fusion.Design.cast(product)
    rootComp = design.rootComponent
    allOccs = rootComp.occurrences
    newOcc = allOccs.addNewComponent(adsk.core.Matrix3D.create())
    return newOcc.component

class BoltCommandExecuteHandler(adsk.core.CommandEventHandler):
    def __init__(self):
        super().__init__()
    def notify(self, args):
        try:
            unitsMgr = app.activeProduct.unitsManager
            command = args.firingEvent.sender
            inputs = command.commandInputs

            bolt = Bolt()
            for input in inputs:
                if input.id == 'boltName':
                    bolt.boltName = input.value
                elif input.id == 'bodyLength':
                    bolt.bodyLength = adsk.core.ValueInput.createByString(input.expression)
                elif input.id == 'face1':
                    face = input.selection(0).entity

            bolt.buildBolt(face)
            args.isValidResult = True

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

class BoltCommandDestroyHandler(adsk.core.CommandEventHandler):
    def __init__(self):
        super().__init__()
    def notify(self, args):
        try:
            # when the command is done, terminate the script
            # this will release all globals which will remove all event handlers
            adsk.terminate()
        except:
            if ui:
                ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))

class BoltCommandCreatedHandler(adsk.core.CommandCreatedEventHandler):    
    def __init__(self):
        super().__init__()        
    def notify(self, args):
        try:
            cmd = args.command
            cmd.isRepeatable = False
            onExecute = BoltCommandExecuteHandler()
            cmd.execute.add(onExecute)
            onExecutePreview = BoltCommandExecuteHandler()
            cmd.executePreview.add(onExecutePreview)
            onDestroy = BoltCommandDestroyHandler()
            cmd.destroy.add(onDestroy)
            # keep the handler referenced beyond this function
            handlers.append(onExecute)
            handlers.append(onExecutePreview)
            handlers.append(onDestroy)

            #define the inputs
            inputs = cmd.commandInputs

            #inputs = cmd.commandInputs
            inputs.addStringValueInput('boltName', 'Bolt Name', defaultBoltName)

            selectionInput1 = inputs.addSelectionInput('face1', 'Select Face', 'Select a planar face')
            selectionInput1.setSelectionLimits(1,1)
            selectionInput1.addSelectionFilter('PlanarFaces')

            initBodyLength = adsk.core.ValueInput.createByReal(defaultBodyLength)
            inputs.addValueInput('bodyLength', 'Body Length', 'cm', initBodyLength)

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

class Bolt:
    def __init__(self):
        self._boltName = defaultBoltName
        self._bodyLength = adsk.core.ValueInput.createByReal(defaultBodyLength)

    #properties

    @Anonymous
    def boltName(self):
        return self._boltName
    @boltName.setter
    def boltName(self, value):
        self._boltName = value

    @Anonymous
    def bodyLength(self):
        return self._bodyLength
    @bodyLength.setter
    def bodyLength(self, value):
        self._bodyLength = value
    
    def buildBolt(self, face1):
        global newComp
        newComp = createNewComponent()
        if newComp is None:
            ui.messageBox('New component failed to create', 'New Component Failed')
            return

        # Create a new sketch.
        sketches = newComp.sketches
        xyPlane = newComp.xYConstructionPlane
        xzPlane = newComp.xZConstructionPlane
        sketch = sketches.add(face1)
        center = adsk.core.Point3D.create(0, 0, 0)
        
        circles = sketch.sketchCurves.sketchCircles
        # Add a circle to the sketch circles collection by using addByCenterRadius. 
        # The needed parameters are the center points and radius.
        circle1 = circles.addByCenterRadius(adsk.core.Point3D.create(0, 0, 0), 7.62)

        extrudes = newComp.features.extrudeFeatures
        prof = sketch.profiles[0]
        extInput = extrudes.createInput(prof, adsk.fusion.FeatureOperations.NewBodyFeatureOperation)

        extInput.setDistanceExtent(False, self.bodyLength)
        headExt = extrudes.add(extInput)

        fc = headExt.faces[0]
        bd = fc.body
        bd.name = self.boltName


def run(context):
    try:
        product = app.activeProduct
        design = adsk.fusion.Design.cast(product)
        if not design:
            ui.messageBox('It is not supported in current workspace, please change to MODEL workspace and try again.')
            return
        commandDefinitions = ui.commandDefinitions
        #check the command exists or not
        cmdDef = commandDefinitions.itemById('Bolt')
        if not cmdDef:
            cmdDef = commandDefinitions.addButtonDefinition('Bolt',
                    'Create Bolt',
                    'Create a bolt.',
                    '') # relative resource file path is specified

        onCommandCreated = BoltCommandCreatedHandler()
        cmdDef.commandCreated.add(onCommandCreated)
        # keep the handler referenced beyond this function
        handlers.append(onCommandCreated)
        inputs = adsk.core.NamedValues.create()
        cmdDef.execute(inputs)

        # prevent this module from being terminate when the script returns, because we are waiting for event handlers to fire
        adsk.autoTerminate(False)
    except:
        if ui:
            ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))

 

0 Likes
Message 5 of 5

Anonymous
Not applicable

Thank you so much, I don't think I would have stumbled on that on my own.  I'm trying to learn coding, but still so much I don't know.  This solution has worked and I've also been able to add more to my code which is also working.  One question I have.  If I want to add a second face selection so that a feature can extrude from my face1 to another selected face2, would I define it in the same way?  Or would I have to do something different than the code below?

Thanks again.

 elif input.id == 'face1':
                    face = input.selection(0).entity


            bolt.buildBolt(face);
            args.isValidResult = True

 

0 Likes