Skip to content

NukeFXSExporter

checkEqualTransform(shape1, shape2, fRange)

Compares 2 shapes transform data Used to identify identical transforms and group shapes inside the same tracked layer

Source code in client/ayon_nuke/vendor/NukeFXExporter/NukeFXSExporter.py
561
562
563
564
565
566
567
568
569
570
571
def checkEqualTransform(shape1,shape2,fRange):
    '''
    Compares 2 shapes transform data
    Used to identify identical transforms and group shapes inside the same tracked layer
    '''
    for f in fRange:
        m1 = shape1.getTransform().evaluate(f).getMatrix()
        m2 = shape2.getTransform().evaluate(f).getMatrix()
        if m1 != m2:
            return False
    return True

createLayers(layer, fRange, rotoNode, rptsw_shapeList, fxsExport, bakeshapes)

Creates the layer xml and assigns it to the fxsExport parent

===========================================================================

===========================================================================

Source code in client/ayon_nuke/vendor/NukeFXExporter/NukeFXSExporter.py
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
def createLayers(layer, fRange, rotoNode, rptsw_shapeList,fxsExport,bakeshapes):
    '''
    Creates the layer xml and assigns it to the fxsExport parent
    #===========================================================================
    # <Layer type="Layer" id="0" label="Layer 1" selected="True" expanded="True" uuid="6BFA7E72-AB79-48A7-BC5A-079A8F5651C8">
    #===========================================================================
    '''
    global cancel
    #=*=*=*=*=*=*===========================================================
    task = nuke.ProgressTask('Layer Exporter')
    task.setMessage('Creating Layer: %s' % layer[0].name)   
    #=*=*=*=*=*=*===========================================================
    if layer[0].name == layer[1].name: #(its the root)
        fxsLayer = ET.SubElement(fxsExport,'Layer',{'type':'Layer', 'label':layer[0].name, 'expanded':'True'})
    else:
        layermatch = False
        layerlist = fxsExport.findall('.//Object')
        for layeritem in layerlist:
            if layeritem.get('label') == layer[1].name:
                layermatch = True
                obj = layeritem.findall("Properties/Property")
                for item in obj:
                    if item.get('id') == "objects":
                        fxsLayer = ET.SubElement(item,'Object',{'type':'Layer', 'label':layer[0].name, 'expanded':'True'})
                break
        if not layermatch:
            layerlist = fxsExport.findall('.//Layer')
            for layeritem in layerlist:
                if layeritem.get('label') == layer[1].name:
                    layermatch = True
                    obj = layeritem.findall("Properties/Property")
                    for item in obj:
                        if item.get('id') == "objects":
                            fxsLayer = ET.SubElement(item,'Object',{'type':'Layer', 'label':layer[0].name, 'expanded':'True'})
                    break


    fxsProperties = ET.SubElement(fxsLayer,'Properties')
    #===========================================================================
    # Layer color - Silhouette default color
    #===========================================================================
    fxsColor = ET.SubElement(fxsProperties, 'Property', {'constant':'True','id':'color'})
    fxsColorValue = ET.SubElement(fxsColor, 'Value')
    fxsColorValue.text = "(1.000000,1.000000,1.000000)"
    #===========================================================================
    # shape overlay color end
    #===========================================================================
    fxsInvert = ET.SubElement(fxsProperties, 'Property', {'constant':'True','id':'invert'})
    fxsInvertValue = ET.SubElement(fxsInvert, 'Value')
    fxsInvertValue.text = "false"
    fxsMode = ET.SubElement(fxsProperties, 'Property', {'constant':'True','id':'mode'})
    fxsModeValue = ET.SubElement(fxsMode, 'Value')
    fxsModeValue.text = "Add"
    #===========================================================================
    # adds matrix data to the layer
    #===========================================================================
    if not bakeshapes:
        matrixtoLayer(layer, fRange, rotoNode,fxsProperties)
    #===========================================================================
    # ADD empty object tag for the child shapes
    #===========================================================================
    fxsObj = ET.SubElement(fxsProperties, 'Property', {'id':'objects','constant':'True','expanded':'True'})
    #=*=*=*=*=*=*==task=related=code======================================== 
    taskLenght=len(layer[0])
    taskCount =0
    #=*=*=*=*=*=*==task=related=code======================================== 
    for item in rptsw_shapeList[::-1]: #create all shapes in this layer 
        if isinstance(item[0], nuke.rotopaint.Shape) and item[1].name == layer[0].name: 
            #=*=*=*=*=*=*==task=related=code========================================  
            taskCount+=1 
            task.setProgress(int(taskCount/taskLenght * 100 ))
            if task.isCancelled():
                cancel = True
                break                
            if cancel:
                break
            #=*=*=*=*=*=*==task=related=code======================================== 
            createShapes(item, fRange, rotoNode, rptsw_shapeList, fxsExport,bakeshapes)

indent(elem, level=0)

function to make the generated xml more human read friendly

Source code in client/ayon_nuke/vendor/NukeFXExporter/NukeFXSExporter.py
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
def indent(elem, level=0):
    '''
    function to make the generated xml more human read friendly
    '''
    i = "\n" + level*"  "
    if len(elem):
        if not elem.text or not elem.text.strip():
            elem.text = i + "  "
        if not elem.tail or not elem.tail.strip():
            elem.tail = i
        for elem in elem:
            indent(elem, level+1)
        if not elem.tail or not elem.tail.strip():
            elem.tail = i
    else:
        if level and (not elem.tail or not elem.tail.strip()):
            elem.tail = i

manageTransforms(fRange, rotoNode, rptsw_shapeList)

Creates new parent Layers and transfer shapes transforms to them

Source code in client/ayon_nuke/vendor/NukeFXExporter/NukeFXSExporter.py
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
def manageTransforms(fRange, rotoNode, rptsw_shapeList):#,task):
    '''
    Creates new parent Layers and transfer shapes transforms to them
    '''
    global cancel
    rotoCurve = rotoNode['curves']
    createdShapes = []
    #=*=*=*=*=*=*==task=related=code========================================
    task = nuke.ProgressTask('Manage Transforms')
    taskCount = 0
    taskLenght = len(rptsw_shapeList)
    #=*=*=*=*=*=*==task=related=code========================================
    for item in rptsw_shapeList: 
        #=*=*=*=*=*=*==task=related=code========================================
        task.setMessage('Preparing Shapes and Layers')
        if cancel:
            return
        task.setProgress(int(taskCount/taskLenght * 100 ))
        taskCount +=1
        #=*=*=*=*=*=*==task=related=code========================================
        if isinstance(item[0], nuke.rotopaint.Shape):
            #===================================================================
            # optimization: verify if shapes share the very same transform data and put them on the same layer
            #===================================================================
            sametransform = False
            for shape in createdShapes:
                if shape[1].name == item[1].name and checkEqualTransform(item[0],shape[0],fRange):
                        sametransform = True
                        sameparent = shape[3]
                        break
            createdShapes.append(item)                
            #===================================================================
            shapeTransf = item[0].getTransform()           
            if len(item[1]) > 1: #apply to a new layer
                if not sametransform:
                    newLayer = rp.Layer(rotoCurve)
                    newLayer.name = item[0].name + "_trkdata" 
                    newLayer.setTransform(shapeTransf)
                    item[1].append(newLayer)
                    newLayer.append(item[0])
                    createdShapes[-1].append(newLayer)
                else:
                    sameparent.append(item[0])
            else: 
                #===============================================================
                # this shape is single child, transfer the transform data to the parent layer
                #===============================================================
                newLayer = rp.Layer(rotoCurve) #temp Layer to hold the data
                newLayerTransf = newLayer.getTransform() 
                matrixCurves = []
                for i in range(4):
                    matrixCurves.append([])
                    for j in range(4):
                        matrixCurves[i].append(newLayerTransf.getExtraMatrixAnimCurve(i, j))
                parentTranf = item[1].getTransform()
                for f in fRange:
                    m1 = shapeTransf.evaluate(f).getMatrix()
                    m2 = parentTranf.evaluate(f).getMatrix()
                    m3 = m2 * m1
                    m = 0
                    for i in range(4):
                        for j in range(4):
                            matrixCurves[i][j].addKey(f,m3.__getitem__(m))
                            m+=1
                newLayerTransf = newLayer.getTransform()
                item[1].setTransform(newLayerTransf)

matrixtoLayer(item, fRange, rotoNode, fxsLayer)

Adds a transform Matrix to the Layer

Source code in client/ayon_nuke/vendor/NukeFXExporter/NukeFXSExporter.py
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
def matrixtoLayer(item, fRange, rotoNode, fxsLayer):
    '''
    Adds a transform Matrix to the Layer
    '''
    projectionMatrixTo = nuke.math.Matrix4()
    projectionMatrixFrom = nuke.math.Matrix4()
    nodeFormat = rotoNode['format'].value()
    transf = item[0].getTransform()
    thematrix = ET.SubElement(fxsLayer,'Property',{'id':'transform.matrix'})
    for f in fRange:
        #===========================================================================
        # node format rectangle transformed through the matrix
        #===========================================================================
        to1 = [0.0,0.0]
        to2 = [float(nodeFormat.width()),0.0]
        to3 = [float(nodeFormat.width()),float(nodeFormat.height())]
        to4 = [0,float(nodeFormat.height())]
        to1 = rptsw_TransformToMatrix(to1, transf, f)
        to2 = rptsw_TransformToMatrix(to2, transf, f)
        to3 = rptsw_TransformToMatrix(to3, transf, f)
        to4 = rptsw_TransformToMatrix(to4, transf, f)
        #===========================================================================
        # convert it to Silhouette ImageTransform coordinates
        #===========================================================================
        to1x =  worldToImageTransform(to1[0],rotoNode,"x")
        to2x =  worldToImageTransform(to2[0],rotoNode,"x")
        to3x =  worldToImageTransform(to3[0],rotoNode,"x")
        to4x =  worldToImageTransform(to4[0],rotoNode,"x")
        to1y =  worldToImageTransform(to1[1],rotoNode,"y")
        to2y =  worldToImageTransform(to2[1],rotoNode,"y")
        to3y =  worldToImageTransform(to3[1],rotoNode,"y")
        to4y =  worldToImageTransform(to4[1],rotoNode,"y")
        #===========================================================================
        # from = Silhouette image coordinate system: -0.5 on top y, 0.5 on bottom y, x is dependent on the format size
        #===========================================================================
        from1x = worldToImageTransform(0.0,rotoNode,"x")
        from1y = 0.5
        from2x, from2y = [worldToImageTransform(float(nodeFormat.width()),rotoNode,"x"),0.5]
        from3x, from3y = [worldToImageTransform(float(nodeFormat.width()),rotoNode,"x"),-0.5]
        from4x, from4y = [worldToImageTransform(0.0,rotoNode,"x"),-0.5]


        projectionMatrixTo.mapUnitSquareToQuad(to1x,to1y,to2x,to2y,to3x,to3y,to4x,to4y)
        projectionMatrixFrom.mapUnitSquareToQuad(from1x,from1y,from2x,from2y,from3x,from3y,from4x,from4y)
        theCornerpinAsMatrix = projectionMatrixTo*projectionMatrixFrom.inverse()
        matrixkey = ET.SubElement(thematrix,'Key',{'frame':str(f-nuke.root().firstFrame()), 'interp':'linear'}) #it was fRange.first()
        #=======================================================================
        # format the matrix keyframe data string
        #=======================================================================
        matrixline = ""
        for n in range(len(theCornerpinAsMatrix)):
            matrixline+= "{:f}".format(theCornerpinAsMatrix[n])
            if n < 15:
                matrixline+= ","
        matrixkey.text = "(" + matrixline + ")"

        #===========================================================================
        # remove repeated keyframes optimization
        #===========================================================================
        #=*=*=*=*=*=*==task=related=code========================================
        if cancel:
            return
        #=*=*=*=*=*=*==task=related=code========================================  
        layerProps = fxsLayer.findall(".//Property")
        removelist = []
        for prop in layerProps:
            if prop.attrib.get('id') == "transform.matrix":
                keys = prop.findall(".//Key")
                if (
                    n > 0
                    and n < len(keys) - 1
                    and keys[n].text == keys[n - 1].text
                    and keys[n].text == keys[n + 1].text
                ):
                    removelist.append(n)
        mainpath = fxsLayer.findall(".//Property")
        for prop in mainpath:
            if prop.attrib.get('id') == "transform.matrix":
                keys = prop.findall(".//Key")
                keysn = len(keys)-1
                for k in keys[::-1]:
                    if keysn in removelist:
                        prop.remove(k)
                    keysn -=1

rptsw_TransformLayers(point, Layer, f, rotoRoot, rptsw_shapeList)

Returns the vector position of a 2d point passing through a series of Layers transform matrices until reaching the Root Layer

Source code in client/ayon_nuke/vendor/NukeFXExporter/NukeFXSExporter.py
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
def rptsw_TransformLayers(point, Layer, f, rotoRoot, rptsw_shapeList):
    '''
    Returns the vector position of a 2d point passing through a series
    of Layers transform matrices until reaching the Root Layer     
    '''

    if Layer == rotoRoot:
        transf = Layer.getTransform()
        newpoint = rptsw_TransformToMatrix(point, transf, f)

    else:
        transf = Layer.getTransform()
        newpoint = rptsw_TransformToMatrix(point, transf, f)
        for x in rptsw_shapeList: #look the layer parent
            if x[0] == Layer:
                newpoint = rptsw_TransformLayers(newpoint, x[1], f, rotoRoot, rptsw_shapeList)
    return newpoint

rptsw_TransformToMatrix(point, transf, f)

Returns the vector position of a 2d point passing through a transform matrix

Source code in client/ayon_nuke/vendor/NukeFXExporter/NukeFXSExporter.py
38
39
40
41
42
43
44
45
46
47
48
49
50
def rptsw_TransformToMatrix(point, transf, f):
    '''
    Returns the vector position of a 2d point passing through a transform matrix 
    '''
    extramatrix = transf.evaluate(f).getMatrix()
    vector = nuke.math.Vector4(point[0], point[1], 1, 1)
    x = (vector[0] * extramatrix[0]) + (vector[1] * extramatrix[1]) + extramatrix[2] + extramatrix[3]
    y = (vector[0] * extramatrix[4]) + (vector[1] * extramatrix[5]) + extramatrix[6] + extramatrix[7]
    z = (vector[0] * extramatrix[8]) + (vector[1] * extramatrix[9]) + extramatrix[10] + extramatrix[11]
    w = (vector[0] * extramatrix[12]) + (vector[1] * extramatrix[13]) + extramatrix[14] + extramatrix[15]
    vector = nuke.math.Vector4(x, y, z, w)
    vector = vector / w
    return vector

rptsw_walker(obj, list)

Returns the Rotopaint node tree [item, parentofitem, uuid]

Source code in client/ayon_nuke/vendor/NukeFXExporter/NukeFXSExporter.py
24
25
26
27
28
29
30
31
32
33
34
35
def rptsw_walker(obj, list):
    '''
    Returns the Rotopaint node tree [item, parentofitem, uuid]
    '''
    for i in obj:
        if isinstance(i, nuke.rotopaint.Shape):
            #uuid to take care of repeated names 
            list.append([i, obj,str(uuid.uuid4())]) 
        if isinstance(i, nuke.rotopaint.Layer):
            list.append([i, obj,str(uuid.uuid4())])
            rptsw_walker(i, list)
    return list

silhouetteFxsExporter(path, frame_start, frame_end, bakeshapes=False)

Main exporter code, UI

Source code in client/ayon_nuke/vendor/NukeFXExporter/NukeFXSExporter.py
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
def silhouetteFxsExporter(path, frame_start, frame_end, bakeshapes=False):
    '''
    Main exporter code, UI 
    '''
    rotoNode = nuke.selectedNode()
    #===========================================================================
    # Nuke UI panel setup
    #===========================================================================

    fRange = nuke.FrameRange("{}-{}".format(frame_start, frame_end))

    #===========================================================================
    # end of panel
    #===========================================================================
    start_time = time.time()
    rptsw_shapeList = []
    global cancel
    cancel = False

    if nuke.NUKE_VERSION_MAJOR > 6:
        #=======================================================================
        # creates a copy of the node to modify and keep original safe
        #=======================================================================
        nukescripts.node_copypaste()
        #=======================================================================       
        rotoNode = nuke.selectedNode()
        rotoCurve = rotoNode['curves']
        rotoRoot = rotoCurve.rootLayer
        #=*=*=*=*=*=*==task=related=code========================================
        task = nuke.ProgressTask('FXS Shape Exporter')
        task.setMessage('Starting FXS export')
        task.setProgress(10)
        #=*=*=*=*=*=*==task=related=code========================================
        rptsw_shapeList = rptsw_walker(rotoRoot, rptsw_shapeList)  
        #=======================================================================
        # creates additional layers to handle shape transforms
        #=======================================================================
        #=*=*=*=*=*=*==task=related=code========================================
        task.setMessage('Sorting out Transforms')
        task.setProgress(20)
        #=*=*=*=*=*=*==task=related=code========================================
        uniqueNames(rptsw_shapeList)
        if not bakeshapes:
            manageTransforms(fRange, rotoNode, rptsw_shapeList)#,task)
        #=*=*=*=*=*=*==task=related=code========================================
        if cancel:
            return
        #=*=*=*=*=*=*==task=related=code========================================
        rotoCurve.changed() #just for debugging purposes
        #=======================================================================
        rptsw_shapeList = []
        rptsw_shapeList = rptsw_walker(rotoRoot, rptsw_shapeList)  
        nodeFormat = rotoNode['format'].value()
        fxsExport = ET.Element('Silhouette',{'width':str(nodeFormat.width()),'height':str(nodeFormat.height()),'workRangeStart':str(fRange.first()),'workRangeEnd':str(fRange.last()),'sessionStartFrame':str(fRange.first())})
        #=======================================================================
        # create the root layer first
        #=======================================================================
        item = [rotoRoot,rotoRoot]
        createLayers(item,fRange, rotoNode, rptsw_shapeList, fxsExport,bakeshapes)
        #=*=*=*=*=*=*==task=related=code========================================
        task.setMessage('Creating Layers')
        task.setProgress(30)
        taskLength = len(rptsw_shapeList)
        taskCount = 0.0
        #=*=*=*=*=*=*==task=related=code========================================
        #=======================================================================
        # create all layers and shapes inside them
        #=======================================================================
        for item in rptsw_shapeList:
            taskCount +=1.0
            task.setProgress(30+int((taskCount/taskLength)*20))
            #=*=*=*=*=*=*==task=related=code========================================
            if cancel:
                break
            #=*=*=*=*=*=*==task=related=code========================================
            if isinstance(item[0], nuke.rotopaint.Layer):
                createLayers(item,fRange, rotoNode, rptsw_shapeList,fxsExport,bakeshapes)
        #===================================================================
        # reorder layers/shapes
        #===================================================================
        layerlist = []
        for item in rptsw_shapeList[::-1]:
            if item[1].name not in layerlist:#find all parent names
                layerlist.append(item[1].name)
        #=*=*=*=*=*=*==task=related=code========================================
        task.setMessage('Reordering Layer/Shapes')
        task.setProgress(50)
        taskLength = len(rptsw_shapeList)
        taskCount = 0.0
        #=*=*=*=*=*=*==task=related=code========================================
        for name in layerlist:
            #=*=*=*=*=*=*==task=related=code========================================
            task.setProgress(50+int((taskCount/taskLength)*50))
            taskCount +=1.0
            if cancel:
                break
            #=*=*=*=*=*=*==task=related=code========================================
            data = []
            parentElement = []
            for item in rptsw_shapeList[::-1]:
                if item[1].name == name: #all items from same parent
                    for itemx in fxsExport.findall('.//*'):
                        if (
                            itemx.get('label') != None and
                            item[0].name == itemx.get('label') and
                            itemx not in data
                        ):
                            data.append(itemx) #locate the elements of that parent
            for itemx in fxsExport.findall('.//*'):
                if itemx.get('label') == name:
                    obj = itemx.findall("Properties/Property")
                    for item in obj:
                        if item.get('id') == "objects":
                              parentElement.append(item)
                              break
            for n in range(len(data)):
                parentElement[0][n] = data[n]
        #===================================================================
        # end of reorder layers/shapes
        #===================================================================
    else:
        nuke.message( 'Shape Exporter is for Nuke v7 only' )

    #=*=*=*=*=*=*==task=related=code========================================
    if cancel:
        nuke.delete(rotoNode)
        return
    #=*=*=*=*=*=*==task=related=code========================================

    #===========================================================================
    # EXPORT the fxs file
    #===========================================================================
    indent(fxsExport)
    ET.ElementTree(fxsExport).write(path)
    nuke.delete(rotoNode)
    task.setProgress(100)  
    print("Time elapsed: %s seconds" % (time.time() - start_time))

uniqueNames(list)

Adds uuids to not unique Layer/Shapes names found Nuke doesn't allows repeated names, but other softwares like Silhouette may export repeated names to Nuke

Source code in client/ayon_nuke/vendor/NukeFXExporter/NukeFXSExporter.py
640
641
642
643
644
645
646
647
648
649
650
def uniqueNames(list):
    '''
    Adds uuids to not unique Layer/Shapes names found
    Nuke doesn't allows repeated names, but other softwares like Silhouette may export repeated names to Nuke
    '''          
    nameList = set()
    for item in list:
        if item[0].name not in nameList:
            nameList.add(item[0].name)
        else:
            item[0].name = f"{item[0].name}_{item[2]}"

worldToImageTransform(value, rotoNode, axis)

Converts values to Silhouette values (Image transform, project resolution independent)

Source code in client/ayon_nuke/vendor/NukeFXExporter/NukeFXSExporter.py
70
71
72
73
74
75
76
77
78
79
def worldToImageTransform(value,rotoNode,axis):
    """
    Converts values to Silhouette values (Image transform, project resolution independent)
    """
    nodeFormat = rotoNode['format'].value()
    if axis == "x":
        transform = ((value - (nodeFormat.width()/2))/nodeFormat.height())* nodeFormat.pixelAspect()
    else:
        transform = ((nodeFormat.height()-value) - (nodeFormat.height()/2))/nodeFormat.height()
    return transform