Beispiel #1
0
    def _initKL(self, unguarded, noopt):
        """Initializes the Fabric client.

        The core client is what drives the application and what the user
        interface interacts with to create data types and process the data. The
        client is required in all Fabric based applications.

        Arguments:
            unguarded (bool): Sets the client to run in guarded mode or not.
            noopt (bool): Set the client to skip KL code optimization

        """

        self.rtvalEncoderDecoder = RTValEncoderDecoder(None)
        clientOpts = {
          'guarded': not unguarded,
          'noOptimization': noopt,
          'interactive': True,
          'reportCallback': self._reportCallback,
          'rtValToJSONEncoder': self.rtvalEncoderDecoder.encode,
          'rtValFromJSONDecoder': self.rtvalEncoderDecoder.decode,
          }

        client = Core.createClient(clientOpts)
        client.loadExtension('Math')
        client.loadExtension('Parameters')
        client.loadExtension('Util')
        client.setStatusCallback(self._statusCallback)
        self.client = client
        self.qUndoStack = QtGui.QUndoStack()
        self.rtvalEncoderDecoder.client = self.client
Beispiel #2
0
	def __init__(self, extensionName, includeRequires):
		self.extensionName = extensionName
		self.includeRequires = includeRequires
		self.extensions = {}
		self.c = core.createClient()
		self.ast = self.c.getKLJSONAST('AST.kl', "require %s; operator entry() {}" % extensionName, True)
		self.data = json.loads(self.ast.getStringCString())['ast']
		self.parseData()
Beispiel #3
0
 def __init__(self, extensionName, includeRequires):
     self.extensionName = extensionName
     self.includeRequires = includeRequires
     self.extensions = {}
     self.c = core.createClient()
     self.ast = self.c.getKLJSONAST(
         'AST.kl', "require %s; operator entry() {}" % extensionName, True)
     self.data = json.loads(self.ast.getStringCString())['ast']
     self.parseData()
Beispiel #4
0
def generateKLFilesToTest(klFiles):
	klTestFiles = []
	c = FECore.createClient()
	for klFile in klFiles:
		file = open(klFile, 'r')
		sourceCode = file.read()
		file.close()
		ast = c.getKLJSONAST('AST.kl', sourceCode, False)
		data = json.loads(ast.getStringCString())['ast']

		klObjects = {}
		for elementList in data:
		    type = elementList['type']
		    if type == 'ASTObjectDecl':
		        objectName = elementList['name']
		        parentObjectName = [] if 'parentsAndInterfaces' not in elementList else elementList['parentsAndInterfaces']
		        klObjects[objectName] = KLObject(objectName, parentObjectName)
		    elif type == 'MethodOpImpl':
		        klObjects[elementList['thisType']].addMethod(elementList['name'])	

		ordererdKlObjects = collections.OrderedDict(sorted(klObjects.items(), key=lambda t: t[0]))
		ignoreThisTest = True
		for klObjectName in ordererdKlObjects:
			klObject = ordererdKlObjects[klObjectName]
			if klObject.canBeTested(ordererdKlObjects):
				ignoreThisTest = False
		if ignoreThisTest: continue

		klTmpFilePrefix = testRootDir + '/kltest_'
		newFileName = klTmpFilePrefix + klFile.replace('/', '_').replace('.', '_')
		newFile = open(newFileName, 'w')
		newFile.write(sourceCode)

		newFile.write('operator entry() { \n')
		newFile.write('\tSize testCount = 0; Size invalidTestCount = 0; report("Processing %s.."); \n' % os.path.splitext(os.path.basename(klFile))[0])
		for klObjectName in ordererdKlObjects:
			klObject = ordererdKlObjects[klObjectName]
			if klObject.canBeTested(ordererdKlObjects):
				newFile.write('\n\treport(" - %s: %s");\n' % (klObjectName, ', '.join(klObject.getTestMethods())))
				newFile.write('\tinvalidTestCount += %s().setOutFile("%s")\n' % (klObjectName, klFile.replace('.kl', '.out')))
				for method in klObject.getTestMethods():
					newFile.write('\t.setUp().%s().tearDown()\n' % method)
				newFile.write('\t.isValid() ? 0 : 1; testCount ++;\n')
		newFile.write('\n\tif (invalidTestCount == 0) report("Ran " + testCount + " test case(s).. OK!" + "\n");\n')
		newFile.write('\telse report("Failed test case(s) " + invalidTestCount + "/" + testCount + "\n");\n')
		newFile.write('}')
		newFile.close()
		klTestFiles.append(newFileName)
	return klTestFiles
Beispiel #5
0
def getPortValue(canvasNode, port):
    # Get Client
    contextID = cmds.fabricSplice('getClientContextID')
    if contextID == '':
        cmds.fabricSplice('constructClient')
        contextID = cmds.fabricSplice('getClientContextID')
    client = fabric.createClient({"contextID": contextID})
    host = client.DFG.host

    # Get Binding for Operator
    opBindingID = cmds.FabricCanvasGetBindingID(n=canvasNode)
    opBinding = host.getBindingForID(opBindingID)

    # force graph evaluation
    opBinding.execute()

    # return port value
    rtVal = opBinding.getArgValue(port)
    return rtVal
Beispiel #6
0
def main():

    options, args = argOpts()
    suffix = ""

    client = FabricCore.createClient()
    if not hasattr(client, 'exportKLExtensions'):
        raise Exception(
            'This build of Fabric does not have the exportKLExtensions feature enabled.'
        )

    if not options.suffix:
        raise Exception('You need to specify the --suffix option.')
    suffix = options.suffix
    flags = client.RegisterKLExtension_Flag_AutoNamespace

    extensions = args[:-1]
    outputfile = args[-1]

    for ext in extensions:
        print 'Loading extension ' + str(ext)
        try:
            client.loadExtension(ext)
        except Exception as e:
            print "Caught exception: " + str(e)
            return

    json = None
    try:
        json = client.exportKLExtensions(extensions, suffix, flags=flags)
    except Exception as e:
        print "Caught exception: " + str(e)
        return

    client = None

    open(outputfile, 'wb').write(json)
    print 'Created json package %s' % outputfile
Beispiel #7
0
    def __test_URI(self):
        c = core.createClient()  # todo use singleton
        # c.loadExtension('Math') # todo use extension manager to load extensions only once
        c.loadExtension(
            'BasicExtension'
        )  # todo use extension manager to load extensions only once
        # ast = c.getKLJSONAST('AST.kl', "require Math; operator entry() {}", True)
        # data = json.loads(ast.getStringCString())['ast']
        # # print data
        # for elementList in data:
        # 	print elementList
        # 	type = elementList['type']
        # 	print type

        sourceCode = "require BasicExtension; operator entry() {}"
        ast = c.getKLJSONAST('AST.kl', sourceCode, True)
        data = json.loads(ast.getStringCString())['ast']

        klObjects = {}
        # elementList = data[0]
        # print elementList
        for elementList in data:
            if type(elementList) == list:
                for el in elementList:
                    print 'type = list 1'
                    print el
                    print '---'
                    # print elementList[el]
            elif type(elementList) == dict:
                for el in elementList:
                    print 'type = dict 2'
                    print el
                    print '...'
                    print elementList[el]
            else:
                print '******************** found ' + str(type(elementList))
            print '  '
Beispiel #8
0
def core_client():
    import FabricEngine.Core as Core
    return Core.createClient({'noOptimization': True})
Beispiel #9
0
	def __init__(self, *args): #['', u'String name', u'String name, Boolean valid']
		c = core.createClient()
		c.loadExtension("BasicExtension")
		self.klObj = c.RT.types.Stuff(*args)
Beispiel #10
0
    def buildSpliceOperators(self, kOperator):
        """Builds Splice Operators on the components.

        Arguments:
        kOperator -- Object, kraken operator that represents a Splice operator.

        Return:
        True if successful.

        """

        try:
            # Get or construct a Fabric Engine client
            contextID = si.fabricSplice('getClientContextID')
            if contextID == '':
                si.fabricSplice('constructClient')
                contextID = si.fabricSplice('getClientContextID')

            # Connect the Python client to the Softimage client.
            client = core.createClient({"contextID": contextID})

            # Get the extension to load and create an instance of the object.
            extension = kOperator.getExtension()
            client.loadExtension(extension)

            client.loadExtension('KrakenSolver')
            client.loadExtension('KrakenSolverArg')

            solverTypeName = kOperator.getSolverTypeName()
            klType = getattr(client.RT.types, solverTypeName)

            try:
                # Test if object
                solver = klType.create()
            except:
                # Else is struct
                solver = klType()

            # Find operatorOwner to attach Splice Operator to.
            operatorOwner = None
            operatorOwnerArg = None

            args = solver.getArguments('KrakenSolverArg[]')
            for i in range(len(args)):
                arg = args[i]

                if arg.connectionType == 'io' and arg.dataType == 'Mat44':

                    operatorOwner = self._getDCCSceneItem(kOperator.getOutput(arg.name))
                    operatorOwnerArg = arg.name
                    break

            if operatorOwner is None:
                raise Exception("Solver '" + kOperator.getName() + "' has no outputs!")

            # Create Splice Operator
            si.fabricSplice('newSplice', "{\"targets\":\"" + operatorOwner.FullName + ".kine.global" + "\", \"portName\":\"" + arg.name + "\", \"portMode\":\"out\"}", "", "")

            # Add the private/non-mayaAttr port that stores the Solver object
            si.fabricSplice("addInternalPort", operatorOwner.FullName + ".kine.global.SpliceOp", "{\"portName\":\"solver\", \"dataType\":\"" + solverTypeName + "\", \"extension\":\"" + kOperator.getExtension() + "\", \"portMode\":\"io\"}", "")

            # Start constructing the source code.
            opSourceCode = ""
            opSourceCode += "require KrakenSolver;\n"
            opSourceCode += "require KrakenSolverArg;\n"
            opSourceCode += "require " + kOperator.getExtension() + ";\n\n"
            opSourceCode += "operator " + kOperator.getName() + "(\n"

            opSourceCode += "  io " + solverTypeName + " solver,\n"

            # Get the args from the solver KL object.
            args = solver.getArguments('KrakenSolverArg[]')

            functionCall = "  solver.solve("
            for i in range(len(args)):
                arg = args[i]

                # Get the argument's input from the DCC
                try:
                    targetObject = self._getDCCSceneItem(kOperator.getInput(arg.name))
                except:
                    targetObject = self._getDCCSceneItem(kOperator.getOutput(arg.name))

                # Append the suffix based on the argument type, Softimage Only
                if arg.dataType == 'Mat44':
                    connectionSuffix = ".kine.global"
                elif arg.dataType in ['Scalar', 'Boolean']:
                    connectionSuffix = ""
                else:
                    connectionSuffix = ""

                # Skip arg if it's the target arg
                if arg.name != operatorOwnerArg:

                    # Add the splice Port for each arg.
                    if arg.connectionType == 'in':
                        si.fabricSplice("addInputPort", operatorOwner.FullName + ".kine.global.SpliceOp", "{\"portName\":\"" + arg.name + "\", \"dataType\":\"" + arg.dataType + "\", \"extension\":\"\", \"targets\":\"" + targetObject.FullName + connectionSuffix + "\"}", "")

                    elif arg.connectionType in ['io', 'out']:
                        si.fabricSplice("addOutputPort", operatorOwner.FullName + ".kine.global.SpliceOp", "{\"portName\":\"" + arg.name + "\", \"dataType\":\"" + arg.dataType + "\", \"extension\":\"\", \"targets\":\"" + targetObject.FullName + connectionSuffix + "\"}", "")

                # Connect the ports to the inputs/outputs in the rig.
                opSourceCode += "  " + arg.connectionType + " " + arg.dataType + " " + arg.name
                if i == len(args) - 1:
                    opSourceCode += "\n"
                else:
                    opSourceCode += ",\n"

                if i == len(args) - 1:
                    functionCall += arg.name
                else:
                    functionCall += arg.name + ", "

            opSourceCode += "    )\n"
            opSourceCode += "{\n"
            opSourceCode += functionCall + ");\n"
            opSourceCode += "}\n"

            si.fabricSplice('addKLOperator', operatorOwner.FullName + ".kine.global.SpliceOp", '{"opName": "' + kOperator.getName() + '"}', opSourceCode)

        finally:
            si.fabricSplice('destroyClient')

        return True
Beispiel #11
0
 def __init__(self,
              *args):  #['', u'String name', u'String name, Boolean valid']
     c = core.createClient()
     c.loadExtension("BasicExtension")
     self.klObj = c.RT.types.Stuff(*args)
Beispiel #12
0
	def __init__(self, *args): #[]
		c = core.createClient()
		c.loadExtension("BasicExtension")
		self.klObj = c.RT.types.MyStruct(*args)
Beispiel #13
0
#
# Fabric Core 1.11.4
# HelloWorld EDK Sample
#
# Copyright 2010-2014 Fabric Software Inc. All rights reserved.
#

import os
if 'FABRIC_EXTS_PATH' in os.environ:
  os.environ['FABRIC_EXTS_PATH'] = os.pathsep.join(['.', os.environ['FABRIC_EXTS_PATH']])
else:
  os.environ['FABRIC_EXTS_PATH'] = '.'

import FabricEngine.Core as fabric
fabricClient = fabric.createClient();

opSource = """
require ViconDataStream;

operator testViconDataStream(io String string);
"""

op = fabricClient.DG.createOperator("op")
op.setSourceCode(opSource)
op.setEntryPoint("testViconDataStream")

b = fabricClient.DG.createBinding()
b.setOperator(op)
b.setParameterLayout(['self.string'])

node = fabricClient.DG.createNode("node")
Beispiel #14
0
def generateKLFilesToTest(klFiles):
    klTestFiles = []
    c = FECore.createClient()
    for klFile in klFiles:
        file = open(klFile, 'r')
        sourceCode = file.read()
        file.close()
        ast = c.getKLJSONAST('AST.kl', sourceCode, False)
        data = json.loads(ast.getStringCString())['ast']

        klObjects = {}
        for elementList in data:
            type = elementList['type']
            if type == 'ASTObjectDecl':
                objectName = elementList['name']
                parentObjectName = [] if 'parentsAndInterfaces' not in elementList else elementList[
                    'parentsAndInterfaces']
                klObjects[objectName] = KLObject(objectName, parentObjectName)
            elif type == 'MethodOpImpl':
                klObjects[elementList['thisType']].addMethod(
                    elementList['name'])

        ordererdKlObjects = collections.OrderedDict(
            sorted(klObjects.items(), key=lambda t: t[0]))
        ignoreThisTest = True
        for klObjectName in ordererdKlObjects:
            klObject = ordererdKlObjects[klObjectName]
            if klObject.canBeTested(ordererdKlObjects):
                ignoreThisTest = False
        if ignoreThisTest: continue

        klTmpFilePrefix = testRootDir + '/kltest_'
        newFileName = klTmpFilePrefix + klFile.replace('/', '_').replace(
            '.', '_')
        newFile = open(newFileName, 'w')
        newFile.write(sourceCode)

        newFile.write('operator entry() { \n')
        newFile.write(
            '\tSize testCount = 0; Size invalidTestCount = 0; report("Processing %s.."); \n'
            % os.path.splitext(os.path.basename(klFile))[0])
        for klObjectName in ordererdKlObjects:
            klObject = ordererdKlObjects[klObjectName]
            if klObject.canBeTested(ordererdKlObjects):
                newFile.write(
                    '\n\treport(" - %s: %s");\n' %
                    (klObjectName, ', '.join(klObject.getTestMethods())))
                newFile.write('\tinvalidTestCount += %s().setOutFile("%s")\n' %
                              (klObjectName, klFile.replace('.kl', '.out')))
                for method in klObject.getTestMethods():
                    newFile.write('\t.setUp().%s().tearDown()\n' % method)
                newFile.write('\t.isValid() ? 0 : 1; testCount ++;\n')
        newFile.write(
            '\n\tif (invalidTestCount == 0) report("Ran " + testCount + " test case(s).. OK!" + "\n");\n'
        )
        newFile.write(
            '\telse report("Failed test case(s) " + invalidTestCount + "/" + testCount + "\n");\n'
        )
        newFile.write('}')
        newFile.close()
        klTestFiles.append(newFileName)
    return klTestFiles
Beispiel #15
0
 def __init__(self, *args):  #[]
     c = core.createClient()
     c.loadExtension("BasicExtension")
     self.klObj = c.RT.types.MyStruct(*args)
Beispiel #16
0
import FabricEngine.Core as Core

# construct the client
client = Core.createClient()

# get access to the dependency graph
# and construct a DG node
node = client.DG.createNode('myNode')

# create some members
node.addMember("a", "Scalar", 3)
node.addMember("b", "Scalar", 4)
node.addMember("c", "Scalar")

# construct a KL operator
operator = client.DG.createOperator('myOp')
operator.setSourceCode("""
  operator myOp(Scalar a, Scalar b, io Scalar c) {
    c = a + b;
  }
""")
operator.setEntryPoint('myOp')

# create a binding, to connect the operator
# parameters to the node data members
binding = client.DG.createBinding()
binding.setOperator(operator)
binding.setParameterLayout(['self.a', 'self.b', 'self.c'])

# put the binding (with its operator)
# onto the binding stack of the node
Beispiel #17
0
#

import os
if 'FABRIC_EXTS_PATH' in os.environ:
    os.environ['FABRIC_EXTS_PATH'] = os.pathsep.join(
        ['.', os.environ['FABRIC_EXTS_PATH']])
else:
    os.environ['FABRIC_EXTS_PATH'] = '.'

#os.environ['FABRIC_EXTS_PATH'] = '.'
print "ECHO FABRIC_EXTS_PATH = " + os.environ['FABRIC_EXTS_PATH']

from time import sleep

import FabricEngine.Core as fabric
fabricClient = fabric.createClient()

fabricClient.loadExtension("LarmorSound")

lsObj = fabricClient.RT.types.LarmorSound.create(
    "/home/larmor/DEVELOP/FabricSound_proj/samples/liz.mp3")
interfaceObj = fabricClient.RT.types.LarmorSound_Interface(lsObj)

numSamples = interfaceObj.getNumSamples("UInt32")
print numSamples.getSimpleType()
#print "Test LarmorSound numSamples = " + str(numSamples)
channelSample = interfaceObj.getChannelSample("Float32<>", 1)
print channelSample.getSimpleType()
print channelSample
#print "Test LarmorSound channelSample = " + str(channelSample)
#interfaceObj.initPlay("Boolean")
Beispiel #18
0
    def __init__(self, settings, unguarded):
        super(MainWindow, self).__init__()

        self.settings = settings
        DFG.DFGWidget.setSettings(settings)

        self.viewport = None
        self.dfgWidget = None
        self.currentGraph = None

        self.config = DFG.DFGConfig()

        self.autosaveFilename = os.path.join(fabricDir, 'autosave')
        if not os.path.exists(self.autosaveFilename):
            os.makedirs(self.autosaveFilename)
        autosaveBasename = 'autosave.' + str(os.getpid()) + '.canvas'
        self.autosaveFilename = os.path.join(self.autosaveFilename,
                                             autosaveBasename)
        print 'Will autosave to ' + self.autosaveFilename + ' every ' + str(
            MainWindow.autosaveIntervalSecs) + ' seconds'

        self.autosaveTimer = QtCore.QTimer()
        self.autosaveTimer.timeout.connect(self.autosave)
        self.autosaveTimer.start(MainWindow.autosaveIntervalSecs * 1000)

        self.windowTitle = 'Fabric Engine'
        self.lastFileName = ''
        self.onFileNameChanged('')

        statusBar = QtGui.QStatusBar(self)
        self.fpsLabel = QtGui.QLabel(statusBar)
        statusBar.addPermanentWidget(self.fpsLabel)
        self.setStatusBar(statusBar)
        statusBar.show()

        self.fpsTimer = QtCore.QTimer()
        self.fpsTimer.setInterval(1000)
        self.fpsTimer.timeout.connect(self.updateFPS)
        self.fpsTimer.start()

        client = Core.createClient({
            'unguarded': unguarded,
            'reportCallback': self.reportCallback
        })
        #options.licenseType = FabricCore::ClientLicenseType_Interactive
        client.loadExtension('Math')
        client.loadExtension('Parameters')
        client.loadExtension('Util')
        client.setStatusCallback(self.statusCallback)
        self.client = client

        self.qUndoStack = QtGui.QUndoStack()
        self.dfguiCommandHandler = DFG.DFGUICmdHandler_QUndo(self.qUndoStack)

        astManager = KLASTManager(client)

        self.evalContext = client.RT.types.EvalContext.create()
        self.evalContext = self.evalContext.getInstance('EvalContext')
        self.evalContext.host = 'Canvas'
        self.evalContext.graph = ''

        self.host = client.getDFGHost()
        binding = self.host.createBindingToNewGraph()
        self.lastSavedBindingVersion = binding.getVersion()
        self.lastAutosaveBindingVersion = self.lastSavedBindingVersion

        graph = binding.getExec()

        glFormat = QtOpenGL.QGLFormat()
        glFormat.setDoubleBuffer(True)
        glFormat.setDepth(True)
        glFormat.setAlpha(True)
        glFormat.setSampleBuffers(True)
        glFormat.setSamples(4)

        self.viewport = Viewports.GLViewportWidget(
            client, self.config.defaultWindowColor, glFormat, None, None)
        self.setCentralWidget(self.viewport)

        self.dfgWidget = DFG.DFGWidget(None, client, self.host, binding, '',
                                       graph, astManager,
                                       self.dfguiCommandHandler, self.config)

        self.contentChanged.connect(self.viewport.redraw)
        self.viewport.portManipulationRequested.connect(
            self.onPortManipulationRequested)

        dockFeatures = QtGui.QDockWidget.DockWidgetMovable | QtGui.QDockWidget.DockWidgetFloatable | QtGui.QDockWidget.DockWidgetClosable

        dfgDock = QtGui.QDockWidget('Canvas Graph', self)
        dfgDock.setObjectName('Canvas Graph')
        dfgDock.setFeatures(dockFeatures)
        dfgDock.setWidget(self.dfgWidget)
        self.addDockWidget(QtCore.Qt.BottomDockWidgetArea, dfgDock,
                           QtCore.Qt.Vertical)

        self.timeLinePortIndex = -1
        self.timeLinePortPath = None
        self.timeLine = Viewports.TimeLineWidget()
        self.timeLine.setTimeRange(MainWindow.defaultFrameIn,
                                   MainWindow.defaultFrameOut)
        self.timeLine.updateTime(1)
        timeLineDock = QtGui.QDockWidget("TimeLine", self)
        timeLineDock.setObjectName("TimeLine")
        timeLineDock.setFeatures(dockFeatures)
        timeLineDock.setWidget(self.timeLine)
        self.addDockWidget(QtCore.Qt.BottomDockWidgetArea, timeLineDock,
                           QtCore.Qt.Vertical)

        treeWidget = DFG.PresetTreeWidget(self.dfgWidget.getDFGController(),
                                          self.config, True, False, True)
        treeDock = QtGui.QDockWidget("Explorer", self)
        treeDock.setObjectName("Explorer")
        treeDock.setFeatures(dockFeatures)
        treeDock.setWidget(treeWidget)
        self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, treeDock)

        self.dfgWidget.newPresetSaved.connect(treeWidget.refresh)

        self.dfgValueEditor = DFG.DFGValueEditor(
            self.dfgWidget.getDFGController(), self.config)
        dfgValueEditorDockWidget = QtGui.QDockWidget("Value Editor", self)
        dfgValueEditorDockWidget.setObjectName("Values")
        dfgValueEditorDockWidget.setFeatures(dockFeatures)
        dfgValueEditorDockWidget.setWidget(self.dfgValueEditor)
        self.addDockWidget(QtCore.Qt.RightDockWidgetArea,
                           dfgValueEditorDockWidget)

        self.logWidget = DFG.DFGLogWidget(self.config)
        logDockWidget = QtGui.QDockWidget("Log Messages", self)
        logDockWidget.setObjectName("Log")
        logDockWidget.setFeatures(dockFeatures)
        logDockWidget.setWidget(self.logWidget)
        logDockWidget.hide()
        self.addDockWidget(QtCore.Qt.TopDockWidgetArea, logDockWidget,
                           QtCore.Qt.Vertical)

        self.qUndoView = QtGui.QUndoView(self.qUndoStack)
        self.qUndoView.setEmptyLabel("New Graph")
        undoDockWidget = QtGui.QDockWidget("History", self)
        undoDockWidget.setObjectName("History")
        undoDockWidget.setFeatures(dockFeatures)
        undoDockWidget.setWidget(self.qUndoView)
        undoDockWidget.hide()
        self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, undoDockWidget)

        self.newGraphAction = None
        self.loadGraphAction = None
        self.saveGraphAction = None
        self.saveGraphAsAction = None
        self.quitAction = None
        self.manipAction = None
        self.setGridVisibleAction = None
        self.resetCameraAction = None
        self.clearLogAction = None
        self.blockCompilationsAction = None

        controller = self.dfgWidget.getDFGController()
        controller.varsChanged.connect(treeWidget.refresh)
        controller.argsChanged.connect(self.onStructureChanged)
        controller.argValuesChanged.connect(self.onValueChanged)
        controller.defaultValuesChanged.connect(self.onValueChanged)
        self.dfgWidget.nodeInspectRequested.connect(
            self.onNodeInspectRequested)
        controller.dirty.connect(self.onDirty)
        controller.bindingChanged.connect(self.dfgValueEditor.setBinding)
        controller.nodeRemoved.connect(self.dfgValueEditor.onNodeRemoved)
        tabSearchWidget = self.dfgWidget.getTabSearchWidget()
        tabSearchWidget.enabled.connect(self.enableShortCuts)
        self.timeLine.frameChanged.connect(self.onFrameChanged)
        self.dfgWidget.onGraphSet.connect(self.onGraphSet)

        self.restoreGeometry(settings.value("mainWindow/geometry"))
        self.restoreState(settings.value("mainWindow/state"))

        self.dfgWidget.additionalMenuActionsRequested.connect(
            self.onAdditionalMenuActionsRequested)

        self.dfgWidget.populateMenuBar(self.menuBar())
        windowMenu = self.menuBar().addMenu("&Window")

        toggleAction = dfgDock.toggleViewAction()
        toggleAction.setShortcut(QtCore.Qt.CTRL + QtCore.Qt.Key_4)
        windowMenu.addAction(toggleAction)
        toggleAction = treeDock.toggleViewAction()
        toggleAction.setShortcut(QtCore.Qt.CTRL + QtCore.Qt.Key_5)
        windowMenu.addAction(toggleAction)
        toggleAction = dfgValueEditorDockWidget.toggleViewAction()
        toggleAction.setShortcut(QtCore.Qt.CTRL + QtCore.Qt.Key_6)
        windowMenu.addAction(toggleAction)
        toggleAction = timeLineDock.toggleViewAction()
        toggleAction.setShortcut(QtCore.Qt.CTRL + QtCore.Qt.Key_9)
        windowMenu.addAction(toggleAction)
        windowMenu.addSeparator()
        toggleAction = undoDockWidget.toggleViewAction()
        toggleAction.setShortcut(QtCore.Qt.CTRL + QtCore.Qt.Key_7)
        windowMenu.addAction(toggleAction)
        toggleAction = logDockWidget.toggleViewAction()
        toggleAction.setShortcut(QtCore.Qt.CTRL + QtCore.Qt.Key_8)
        windowMenu.addAction(toggleAction)

        self.onFrameChanged(self.timeLine.getTime())
        self.onGraphSet(self.dfgWidget.getUIGraph())
        self.onSidePanelInspectRequested()

        self.installEventFilter(MainWindowEventFilter(self))
Beispiel #19
0
	def __init__(self, *args): #['', u'Integer id']
		c = core.createClient()
		c.loadExtension("AnotherBasicExtension")
		self.klObj = c.RT.types.Foo(*args)
Beispiel #20
0
fabricPath = os.environ.get("FABRIC_DIR")
kl2dfgPath = os.path.join(fabricPath, 'bin', 'kl2dfg.exe')
guidGenPath = os.path.join(fabricPath, 'bin', 'canvasGUIDGen.exe')
krakenPath = os.environ.get('KRAKEN_PATH')
krakenExtsPath = os.path.join(krakenPath, 'Exts')
krakenStageDFGPath = os.path.join(krakenPath, 'Exts', 'Kraken', 'DFGStage')
krakenDFGPath = os.path.join(krakenPath, 'Exts', 'Kraken', 'DFG')
krakenDFGSolverPath = os.path.join(krakenDFGPath, 'Solvers')

# =====================
# Create Fabric Client
# =====================
options = {'guarded': True}

client = fabric.createClient(options)
dfgHost = client.getDFGHost()


# ===================
# Store Preset GUIDs
# ===================
def storePresetGUIDs():
    guidMap = {}
    for root, dirs, files in os.walk(krakenExtsPath):
        for file in files:
            if file.endswith('.canvas'):
                presetFilePath = os.path.join(root, file)
                presetPathItems = presetFilePath.replace(
                    krakenExtsPath, '').split(os.path.sep)[1:]
                presetCanvasPath = '.'.join(presetPathItems).replace(
Beispiel #21
0
    def buildSpliceOperators(self, kOperator):
        """Builds Splice Operators on the components.

        Arguments:
        kOperator -- Object, kraken operator that represents a Splice operator.

        Return:
        True if successful.

        """

        try:
            # Get or construct a Fabric Engine client
            contextID = cmds.fabricSplice('getClientContextID')
            if contextID == '':
                cmds.fabricSplice('constructClient')
                contextID = cmds.fabricSplice('getClientContextID')

            # Connect the Python client to the Softimage client.
            client = core.createClient({"contextID": contextID})

            # Get the extension to load and create an instance of the object.
            extension = kOperator.getExtension()
            client.loadExtension(extension)

            client.loadExtension('KrakenSolver')
            client.loadExtension('KrakenSolverArg')

            solverTypeName = kOperator.getSolverTypeName()
            klType = getattr(client.RT.types, solverTypeName)

            try:
                # Test if object
                solver = klType.create()
            except:
                # Else is struct
                solver = klType()

            # Create Splice Operator
            spliceNode = pm.createNode('spliceMayaNode', name=kOperator.getName() + "_SpliceOp")

            # Add the private/non-mayaAttr port that stores the Solver object
            cmds.fabricSplice("addIOPort", spliceNode, "{\"portName\":\"solver\", \"dataType\":\"" + solverTypeName + "\", \"extension\":\"" + kOperator.getExtension() + "\", \"addMayaAttr\": false}")

            # Start constructing the source code.
            opSourceCode = ""
            opSourceCode += "require KrakenSolver;\n"
            opSourceCode += "require KrakenSolverArg;\n"
            opSourceCode += "require " + kOperator.getExtension() + ";\n\n"
            opSourceCode += "operator " + kOperator.getName() + "(\n"

            opSourceCode += "    io " + solverTypeName + " solver,\n"

            # Get the args from the solver KL object.
            args = solver.getArguments('KrakenSolverArg[]')

            functionCall = "    solver.solve("
            for i in range(len(args)):
                arg = args[i]

                # Get the argument's input from the DCC
                try:
                    opObject = kOperator.getInput(arg.name)
                    targetObject = self._getDCCSceneItem(kOperator.getInput(arg.name))
                except:
                    opObject = kOperator.getOutput(arg.name)
                    targetObject = self._getDCCSceneItem(kOperator.getOutput(arg.name))

                # Add the splice Port for each arg.
                if arg.connectionType == 'in':
                    cmds.fabricSplice("addInputPort", spliceNode, "{\"portName\":\"" + arg.name + "\", \"dataType\":\"" + arg.dataType + "\", \"extension\":\"\", \"addMayaAttr\": true}", "")

                    if isinstance(opObject, BaseAttribute):
                        targetObject.connect(spliceNode.attr(arg.name))
                    elif isinstance(opObject, SceneItem):
                        targetObject.attr('worldMatrix').connect(spliceNode.attr(arg.name))
                    else:
                        raise Exception(opObject.getFullName() + " with type '" + opObject.getKType() + " is not implemented!")


                elif arg.connectionType in ['io', 'out']:
                    cmds.fabricSplice("addOutputPort", spliceNode, "{\"portName\":\"" + arg.name + "\", \"dataType\":\"" + arg.dataType + "\", \"extension\":\"\", \"addMayaAttr\": true}", "")

                    if isinstance(opObject, BaseAttribute):
                        spliceNode.attr(arg.name).connect(targetObject)

                    elif isinstance(opObject, SceneItem):
                        decomposeNode = pm.createNode('decomposeMatrix')
                        spliceNode.attr(arg.name).connect(decomposeNode.attr("inputMatrix"))

                        decomposeNode.attr("outputRotate").connect(targetObject.attr("rotate"))
                        decomposeNode.attr("outputScale").connect(targetObject.attr("scale"))
                        decomposeNode.attr("outputTranslate").connect(targetObject.attr("translate"))


                # Connect the ports to the inputs/outputs in the rig.
                opSourceCode += "    " + arg.connectionType + " " + arg.dataType + " " + arg.name
                if i == len(args) - 1:
                    opSourceCode += "\n"
                else:
                    opSourceCode += ",\n"

                if i == len(args) - 1:
                    functionCall += arg.name
                else:
                    functionCall += arg.name + ", "

            opSourceCode += "    )\n"
            opSourceCode += "{\n"
            opSourceCode += functionCall + ");\n"
            opSourceCode += "}\n"

            cmds.fabricSplice('addKLOperator', spliceNode, '{"opName": "' + kOperator.getName() + '"}', opSourceCode)

        finally:
            cmds.fabricSplice('destroyClient')

        return True
Beispiel #22
0
#!/usr/bin/env python
# 
# Copyright (c) 2014, Steven Caron <*****@*****.**> All rights reserved.
# 
# FabricArnold Extension
# test_0001

import sys
import os

testNumber = "test_0001"
print("[FabricArnold::TestSuite] Running extension {0}...".format(testNumber))

import FabricEngine.Core as Core
client = Core.createClient()

node = client.DG.createNode("test_node")
node.addMember("filename", "String")
operator = client.DG.createOperator("test_operator")

klFilename = os.path.join(os.getcwd(), testNumber, "test.kl")
operatorSource = open(klFilename).read()

operator.setSourceCode(operatorSource)
operator.setEntryPoint("entry")

if operator.getDiagnostics():
    print("Error(s) compiling operator:")
    for d in operator.getDiagnostics():
        print("  {0}".format(str(d)))
    sys.exit(1)