yum-slop/TaSTT

Free self-hosted STT for VRChat.

git clone https://git.yummers.dev/yum-slop/TaSTT

yumUsers can now choose custom chatbox texture size in UI3db7723

v0.19.1
49.2 KiB1432 linesraw
1#!/usr/bin/env python3
2
3from functools import partial
4
5import argparse
6import copy
7import enum
8import math
9import os
10import pickle
11import random
12import sys
13import typing
14# python3 -m pip install pyyaml
15# License: MIT.
16import yaml
17
18import multiprocessing as mp
19
20WRITE_DEFAULTS_ANIM_TEMPLATE = """
21%YAML 1.1
22%TAG !u! tag:unity3d.com,2011:
23--- !u!74 &7400000
24AnimationClip:
25  m_ObjectHideFlags: 0
26  m_CorrespondingSourceObject: {fileID: 0}
27  m_PrefabInstance: {fileID: 0}
28  m_PrefabAsset: {fileID: 0}
29  m_Name: TaSTT_Reset_Animations
30  serializedVersion: 6
31  m_Legacy: 0
32  m_Compressed: 0
33  m_UseHighQualityCurve: 1
34  m_RotationCurves: []
35  m_CompressedRotationCurves: []
36  m_EulerCurves: []
37  m_PositionCurves: []
38  m_ScaleCurves: []
39  m_FloatCurves:
40  - curve:
41      serializedVersion: 2
42      m_Curve:
43      - serializedVersion: 3
44        time: 0
45        value: 0
46        inSlope: 0
47        outSlope: 0
48        tangentMode: 136
49        weightedMode: 0
50        inWeight: 0
51        outWeight: 0
52      m_PreInfinity: 2
53      m_PostInfinity: 2
54      m_RotationOrder: 4
55    attribute: REPLACEME_ATTRIBUTE
56    path: REPLACEME_PATH
57    classID: 137
58    script: {fileID: 0}
59  m_PPtrCurves: []
60  m_SampleRate: 60
61  m_WrapMode: 0
62  m_Bounds:
63    m_Center: {x: 0, y: 0, z: 0}
64    m_Extent: {x: 0, y: 0, z: 0}
65  m_ClipBindingConstant:
66    genericBindings:
67    - serializedVersion: 2
68      path: 2794480623
69      attribute: 2284639795
70      script: {fileID: 0}
71      typeID: 137
72      customType: 22
73      isPPtrCurve: 0
74    pptrCurveMapping: []
75  m_AnimationClipSettings:
76    serializedVersion: 2
77    m_AdditiveReferencePoseClip: {fileID: 0}
78    m_AdditiveReferencePoseTime: 0
79    m_StartTime: 0
80    m_StopTime: 0
81    m_OrientationOffsetY: 0
82    m_Level: 0
83    m_CycleOffset: 0
84    m_HasAdditiveReferencePose: 0
85    m_LoopTime: 1
86    m_LoopBlend: 0
87    m_LoopBlendOrientation: 0
88    m_LoopBlendPositionY: 0
89    m_LoopBlendPositionXZ: 0
90    m_KeepOriginalOrientation: 0
91    m_KeepOriginalPositionY: 1
92    m_KeepOriginalPositionXZ: 0
93    m_HeightFromFeet: 0
94    m_Mirror: 0
95  m_EditorCurves:
96  - curve:
97      serializedVersion: 2
98      m_Curve:
99      - serializedVersion: 3
100        time: 0
101        value: 0
102        inSlope: 0
103        outSlope: 0
104        tangentMode: 136
105        weightedMode: 0
106        inWeight: 0
107        outWeight: 0
108      m_PreInfinity: 2
109      m_PostInfinity: 2
110      m_RotationOrder: 4
111    attribute: REPLACEME_ATTRIBUTE
112    path: REPLACEME_PATH
113    classID: 137
114    script: {fileID: 0}
115  m_EulerEditorCurves: []
116  m_HasGenericRootTransform: 0
117  m_HasMotionFloatCurves: 0
118  m_Events: []
119"""[1:][:-1]
120
121METADATA_TEMPLATE = """
122fileFormatVersion: 2
123guid: REPLACEME_GUID
124NativeFormatImporter:
125  externalObjects: {}
126  mainObjectFileID: 7400000
127  userData:
128  assetBundleName:
129  assetBundleVariant: 
130"""[1:][:-1]
131
132ANIMATION_STATE_TEMPLATE = """
133--- !u!1102 &110200000
134AnimatorState:
135  serializedVersion: 6
136  m_ObjectHideFlags: 1
137  m_CorrespondingSourceObject: {fileID: 0}
138  m_PrefabInstance: {fileID: 0}
139  m_PrefabAsset: {fileID: 0}
140  m_Name: REPLACEME_ANIMATION_NAME
141  m_Speed: 1
142  m_CycleOffset: 0
143  m_Transitions: []
144  m_StateMachineBehaviours: []
145  m_Position: {x: 50, y: 50, z: 0}
146  m_IKOnFeet: 0
147  m_WriteDefaultValues: 0
148  m_Mirror: 0
149  m_SpeedParameterActive: 0
150  m_MirrorParameterActive: 0
151  m_CycleOffsetParameterActive: 0
152  m_TimeParameterActive: 0
153  m_Motion: {}
154  m_Tag: 
155  m_SpeedParameter: 
156  m_MirrorParameter: 
157  m_CycleOffsetParameter: 
158  m_TimeParameter: 
159"""[1:][:-1]
160
161TRANSITION_TEMPLATE = """
162--- !u!1101 &110100000
163AnimatorStateTransition:
164  m_ObjectHideFlags: 1
165  m_CorrespondingSourceObject: {fileID: 0}
166  m_PrefabInstance: {fileID: 0}
167  m_PrefabAsset: {fileID: 0}
168  m_Name: 
169  m_Conditions: []
170  m_DstStateMachine: {fileID: 0}
171  m_DstState: {fileID: 0}
172  m_Solo: 0
173  m_Mute: 0
174  m_IsExit: 0
175  serializedVersion: 3
176  m_TransitionDuration: 0
177  m_TransitionOffset: 0
178  m_ExitTime: 0.0
179  m_HasExitTime: 0
180  m_HasFixedDuration: 1
181  m_InterruptionSource: 2
182  m_OrderedInterruption: 1
183  m_CanTransitionToSelf: 1
184"""[1:][:-1]
185
186BLEND_TREE_TEMPLATE = """
187--- !u!206 &1071664566462684110
188BlendTree:
189  m_ObjectHideFlags: 1
190  m_CorrespondingSourceObject: {fileID: 0}
191  m_PrefabInstance: {fileID: 0}
192  m_PrefabAsset: {fileID: 0}
193  m_Name: REPLACEME_BLEND_TREE_NAME
194  m_Childs:
195  - serializedVersion: 2
196    m_Motion: {fileID: 7400000, guid: REPLACEME_GUID_LO, type: 2}
197    m_Threshold: -1
198    m_Position: {x: 0, y: 0}
199    m_TimeScale: 1
200    m_CycleOffset: 0
201    m_DirectBlendParameter: REPLACEME_BLEND_PARAMETER
202    m_Mirror: 0
203  - serializedVersion: 2
204    m_Motion: {fileID: 7400000, guid: REPLACEME_GUID_HI, type: 2}
205    m_Threshold: 1
206    m_Position: {x: 0, y: 0}
207    m_TimeScale: 1
208    m_CycleOffset: 0
209    m_DirectBlendParameter: REPLACEME_BLEND_PARAMETER
210    m_Mirror: 0
211  m_BlendParameter: REPLACEME_BLEND_PARAMETER
212  m_BlendParameterY: REPLACEME_BLEND_PARAMETER
213  m_MinThreshold: -1
214  m_MaxThreshold: 1
215  m_UseAutomaticThresholds: 0
216  m_NormalizedBlendValues: 0
217  m_BlendType: 0
218"""[1:][:-1]
219
220class Metadata:
221    def __init__(self):
222        self.guid = "%032x" % random.randrange(16 ** 32)
223
224    def load(self, path):
225        if not path.endswith(".meta"):
226            path = path + ".meta"
227
228        self.guid = None
229        with open(path, "r", encoding="utf-8") as f:
230            for line in f:
231                if line.startswith("guid"):
232                    self.guid = line.split()[1]
233
234    def loadOrCreate(self, path, guid_map):
235        if not path.endswith(".meta"):
236            path = path + ".meta"
237
238        if os.path.exists(path):
239            self.load(path)
240            return
241
242        self.persist(path, guid_map)
243
244    def persist(self, path, guid_map):
245        with open(path, "w", encoding="utf-8") as f:
246            f.write(str(self))
247
248        guid_map[self.guid] = path
249        guid_map[path] = self.guid
250
251    def __str__(self):
252        return METADATA_TEMPLATE.replace("REPLACEME_GUID", self.guid)
253
254class Node:
255    def __init__(self):
256        # Optional. In Unity, this is the fileID of an object. Not all YAML
257        # mappings have an anchor.
258        self.anchor = None
259
260        # Pointer to the Node containing this one.
261        self.parent = None
262
263class Sequence(Node):
264    def __init__(self):
265        super().__init__()
266        self.sequence = []
267
268    def copy(self):
269        new = Sequence()
270        new.anchor = self.anchor
271        new.parent = self.parent
272
273        for v in self.sequence:
274            if hasattr(v, "copy"):
275                new.sequence.append(v.copy())
276                new.sequence[-1].parent = new
277            else:
278                new.sequence.append(v)
279
280        return new
281
282    def prettyPrint(self, first_indent=None, leading_newline=None):
283        depth = 0
284        p = self.parent
285        while p != None:
286            depth += 1
287            p = p.parent
288        indent = "  " * depth
289
290        lines = []
291        first = True
292        for item in self.sequence:
293            cur_indent = indent
294            if first:
295                if first_indent != None:
296                    cur_indent = first_indent
297                first = False
298            if hasattr(item, "prettyPrint"):
299                lines.append("{}- {}".format(cur_indent, item.prettyPrint(first_indent="", leading_newline=False)))
300            else:
301                lines.append("{}- {}".format(cur_indent, item))
302
303        if len(lines) == 0:
304            return "[]"
305
306        return "\n" + '\n'.join(lines)
307
308    def __str__(self):
309        return self.prettyPrint()
310
311    def addChildMapping(self, anchor = None, add_to_head = False):
312        child = Mapping()
313        child.anchor = anchor
314        child.parent = self
315        child.sequence = []
316
317        if add_to_head:
318            self.sequence = [child] + self.sequence
319        else:
320            self.sequence.append(child)
321
322        return child
323
324    def addChildSequence(self, anchor = None):
325        child = Sequence()
326        child.anchor = anchor
327        child.parent = self
328        child.sequence = []
329
330        self.sequence.append(child)
331
332        return child
333
334    def forEach(self, cb):
335        for k in self.sequence:
336            cb(k)
337
338class Mapping(Node):
339    def __init__(self):
340        super().__init__()
341        self.mapping = {}
342
343    def copy(self):
344        new = Mapping()
345        new.anchor = self.anchor
346        new.parent = self.parent
347
348        for k, v in self.mapping.items():
349            if hasattr(v, "copy"):
350                new.mapping[k] = v.copy()
351                new.mapping[k].parent = new
352            else:
353                new.mapping[k] = v
354
355        return new
356
357    def prettyPrint(self, first_indent=None, leading_newline=True):
358        depth = 0
359        p = self.parent
360        while p != None:
361            depth += 1
362            p = p.parent
363        indent = "  " * depth
364
365        lines = []
366        first = True
367        for k, v in self.mapping.items():
368            cur_indent = indent
369            if first:
370                if first_indent != None:
371                    cur_indent = first_indent
372                first = False
373            lines.append("{}{}: {}".format(cur_indent, k, v))
374
375        result = '\n'.join(lines)
376
377        # Inline 1-item mappings, matching Unity behavior.
378        if len(self.mapping.keys()) == 1 and len(result.split("\n")) == 1:
379            if first_indent == None:
380                return self.prettyPrint(first_indent="")
381            return "{" + lines[0] + "}"
382
383        # Empty mappings are represented by '{}'. If we don't do this, Unity
384        # will assume that they are Sequences and get very sad.
385        if len(self.mapping.keys()) == 0:
386            return "{}"
387
388        if leading_newline:
389            result = "\n" + result
390
391        return result
392
393    def __str__(self):
394        return self.prettyPrint()
395
396    def addChildMapping(self, key, anchor = None):
397        child = Mapping()
398        child.anchor = anchor
399        child.parent = self
400        child.mapping = {}
401
402        self.mapping[key] = child
403
404        return child
405
406    def addChildSequence(self, key, anchor = None):
407        child = Sequence()
408        child.anchor = anchor
409        child.parent = self
410        child.mapping = {}
411
412        self.mapping[key] = child
413
414        return child
415
416    def forEach(self, cb):
417        for k, v in self.mapping.items():
418            cb(v)
419
420class UnityDocument(Mapping):
421    def __init__(self):
422        super().__init__()
423        self.class_id = None
424
425    def __str__(self):
426        return super().__str__()
427
428    def copy(self):
429        result = super().copy()
430        result.class_id = self.class_id
431        return result
432
433# Class representing a Unity AnimatorController. Implements manipulations, like
434# merging and reanchoring.
435class UnityAnimator():
436    def __init__(self):
437        self.nodes = []
438        self.id_to_node = {}
439        self.next_id = 1000 * 1000
440
441    def __str__(self):
442        return unityYamlToString(self.nodes)
443
444    def addNodes(self, nodes):
445        for node in nodes:
446            self.nodes.append(node)
447            anchor = node.anchor
448            if anchor == None:
449                anchor = self.allocateId()
450            if anchor in self.id_to_node:
451                raise Exception("Duplicate anchor: {}, node 1: {}, node 2: {}".format(anchor, str(node), str(self.id_to_node[anchor])))
452            self.id_to_node[anchor] = node
453
454            if int(anchor) > self.next_id:
455                self.next_id = int(anchor) + 1
456        # I don't know why but this fixes a bug in the `fixWriteDefaults`
457        # codepath: two documents wind up with the same anchor.
458        self.next_id += 1
459
460    def allocateId(self) -> int:
461        result = self.next_id
462        self.next_id += 1
463        return result
464
465    # Checks if `old_id` is in `self.id_mapping`, and if so, returns the
466    # already-generated ID. Otherwise this allocates a new ID and
467    # records it in `self.id_mapping`.
468    def mapId(self, old_id: str) -> int:
469        new_id = None
470        if old_id in self.id_mapping.keys():
471             new_id = self.id_mapping[old_id]
472        else:
473            new_id = self.allocateId()
474            self.id_mapping[old_id] = new_id
475        return new_id
476
477    # Recursively iterate every mapping under `node` and assign new IDs to
478    # every identifier. Mappings are recorded in `self.id_mapping`.
479    def mergeIterator(self, node):
480        if hasattr(node, "mapping"):
481            # Don't relabel anything that's defined in an external file.
482            # TODO(yum) do this.
483            if 'fileID' in node.mapping and not 'guid' in node.mapping:
484                if node.mapping['fileID'] != '0':
485                    old_id = node.mapping['fileID']
486                    new_id = self.mapId(old_id)
487                    node.mapping['fileID'] = str(new_id)
488        if hasattr(node, "forEach"):
489            node.forEach(self.mergeIterator)
490
491    # Delete any key-value pairs where the value == the value.
492    def scrubReferencesByValue(self, node, values: typing.Set[str]):
493        if hasattr(node, "mapping"):
494            node.mapping = {k: v for k, v in node.mapping.items() if v not in values}
495        if hasattr(node, "forEach"):
496            node.forEach(partial(self.scrubReferencesByValue, values=values))
497
498    def peekNodeOfClass(self, classId):
499        for node in self.nodes:
500            if node.class_id == classId:
501                return node
502        return None
503
504    def popNodeOfClass(self, classId):
505        result = None
506        for node in self.nodes:
507            if node.class_id == classId:
508                result = node
509                self.nodes.remove(result)
510                break
511        if result:
512            del self.id_to_node[result.anchor]
513        return result
514
515    def pushNode(self, node):
516        self.nodes.append(node)
517        self.id_to_node[node.anchor] = node
518
519    # Merges two animator controllers and returns the result. Any identifiers
520    # in the animators are reassigned in a new namespace. The mappings from old
521    # identifiers to new identifiers are recorded in `self.id_mapping0` and
522    # `self.id_mapping1`.
523    def mergeAnimatorControllers(self, ctrl0, ctrl1):
524        ctrl0 = copy.deepcopy(ctrl0)
525        ctrl1 = copy.deepcopy(ctrl1)
526
527        self.id_mapping0 = {}
528        self.id_mapping1 = {}
529
530        p0 = ctrl0.mapping['AnimatorController'].mapping['m_AnimatorParameters']
531        p1 = ctrl1.mapping['AnimatorController'].mapping['m_AnimatorParameters']
532
533        a0 = ctrl0.mapping['AnimatorController'].mapping['m_AnimatorLayers']
534        a1 = ctrl1.mapping['AnimatorController'].mapping['m_AnimatorLayers']
535
536        self.id_mapping = self.id_mapping0
537        p0.forEach(self.mergeIterator)
538        a0.forEach(self.mergeIterator)
539
540        # Hack to prevent ctrl1 from getting a new ID for the animator.
541        # TODO(yum) delete this?
542        #del self.class_to_next_id['91']
543
544        self.id_mapping = self.id_mapping1
545        p1.forEach(self.mergeIterator)
546        a1.forEach(self.mergeIterator)
547
548        p0.sequence += p1.sequence
549        a0.sequence += a1.sequence
550
551        for elm in p0.sequence:
552            elm.mapping['m_Controller'].mapping['fileID'] = ctrl0.anchor
553        for elm in a0.sequence:
554            elm.mapping['m_Controller'].mapping['fileID'] = ctrl0.anchor
555
556        return ctrl0
557
558    def merge(self, other):
559        ctrl0 = self.popNodeOfClass('91')
560        ctrl1 = other.popNodeOfClass('91')
561        # Merge animators and populate `self.id_mapping0` and
562        # `self.id_mapping1.
563        merged_anim = self.mergeAnimatorControllers(ctrl0, ctrl1)
564
565        # Mapping from class ID (string) to new class ID (int)
566        self.id_mapping = self.id_mapping0
567        for node in self.nodes:
568            new_id = self.mapId(node.anchor)
569            node.anchor = str(new_id)
570            node.forEach(self.mergeIterator)
571
572        self.id_mapping = self.id_mapping1
573        for node in other.nodes:
574            new_id = self.mapId(node.anchor)
575            node.anchor = str(new_id)
576            node.forEach(self.mergeIterator)
577
578        nodes = self.nodes
579        self.nodes = []
580        self.id_to_node = {}
581        self.pushNode(merged_anim)
582        self.addNodes(nodes)
583        self.addNodes(other.nodes)
584
585    # TODO(yum) support overwriting duplicates
586    def addParameter(self, param_name, param_type):
587        unity_type = None
588        if param_type == float:
589            unity_type = '1'
590        elif param_type == int:
591            unity_type = '3'
592        elif param_type == bool:
593            unity_type = '4'
594
595        anim = self.peekNodeOfClass('91')
596        params = anim.mapping['AnimatorController'].mapping['m_AnimatorParameters']
597
598        for p in params.sequence:
599            if p.mapping['m_Name'] == param_name:
600                return
601
602        param = params.addChildMapping()
603        param.mapping['m_Name'] = param_name
604        param.mapping['m_Type'] = unity_type
605        param.mapping['m_DefaultFloat'] = '0'
606        param.mapping['m_DefaultInt'] = '0'
607        param.mapping['m_DefaultBool'] = '0'
608        ctrl = param.addChildMapping('m_Controller')
609        ctrl.mapping['fileID'] = anim.anchor
610
611    def addLayer(self, layer_name, add_to_head = False, weight: float = 1.0) -> UnityDocument:
612        # Add layer to controller
613        anim = self.peekNodeOfClass('91')
614        layers = anim.mapping['AnimatorController'].mapping['m_AnimatorLayers']
615        layer = layers.addChildMapping(add_to_head = add_to_head)
616        layer.mapping['serializedVersion'] = '5'
617        layer.mapping['m_Name'] = layer_name
618        new_id = self.allocateId()
619        layer.addChildMapping('m_StateMachine').mapping['fileID'] = str(new_id)
620        layer.addChildMapping('m_Mask').mapping['fileID'] = '0'
621        layer.addChildSequence('m_Motions')
622        layer.addChildSequence('m_Behaviours')
623        layer.mapping['m_BlendingMode'] = '0'
624        layer.mapping['m_SyncedLayerIndex'] = '-1'
625        layer.mapping['m_DefaultWeight'] = str(weight)
626        layer.mapping['m_IKPass'] = '0'
627        layer.mapping['m_SyncedLayerAffectsTiming'] = '0'
628        layer.addChildMapping('m_Controller').mapping['fileID'] = anim.anchor
629
630        # Create layer object
631        layer = UnityDocument()
632        layer.class_id = "1107"
633        layer.anchor = str(new_id)
634        mach = layer.addChildMapping('AnimatorStateMachine')
635
636        mach.mapping['serializedVersion'] = '6'
637
638        mach.mapping['m_ObjectHideFlags'] = '1'
639        mach.addChildMapping('m_CorrespondingSourceObject').mapping['fileID'] = '0'
640        mach.addChildMapping('m_PrefabInstance').mapping['fileID'] = '0'
641        mach.addChildMapping('m_PrefabAsset').mapping['fileID'] = '0'
642        mach.mapping['m_Name'] = layer_name
643        mach.addChildSequence('m_ChildStates')
644        mach.addChildSequence('m_ChildStateMachines')
645        mach.addChildSequence('m_AnyStateTransitions')
646        mach.addChildSequence('m_EntryTransitions')
647        mach.addChildMapping('m_StateMachineTransitions')
648        mach.addChildSequence('m_StateMachineBehaviours')
649        pos = mach.addChildMapping('m_AnyStatePosition')
650        pos.mapping['x'] = '50'
651        pos.mapping['y'] = '20'
652        pos.mapping['z'] = '0'
653        pos = mach.addChildMapping('m_EntryPosition')
654        pos.mapping['x'] = '50'
655        pos.mapping['y'] = '120'
656        pos.mapping['z'] = '0'
657        pos = mach.addChildMapping('m_ExitPosition')
658        pos.mapping['x'] = '800'
659        pos.mapping['y'] = '120'
660        pos.mapping['z'] = '0'
661        pos = mach.addChildMapping('m_ParentStateMachinePosition')
662        pos.mapping['x'] = '800'
663        pos.mapping['y'] = '20'
664        pos.mapping['z'] = '0'
665        mach.addChildMapping('m_DefaultState')
666
667        self.nodes.append(layer)
668        return layer
669
670    def addAnimatorState(self, layer, state_name, is_default_state = False,
671            dx = 0, dy = 0) -> UnityDocument:
672        # Create animation state
673        parser = UnityParser()
674        parser.parse(ANIMATION_STATE_TEMPLATE)
675        new_anim = UnityAnimator()
676        new_anim.addNodes(parser.nodes)
677        node = new_anim.nodes[0]
678
679        new_id = self.allocateId()
680        node.class_id = "1102"
681        node.anchor = str(new_id)
682        state = node.mapping['AnimatorState']
683        state.mapping['m_Name'] = state_name
684        #state.mapping['m_Motion'].mapping['guid'] = anim_guid
685        self.nodes.append(node)
686
687        # Add state to layer
688        child_state = layer.mapping['AnimatorStateMachine'].mapping['m_ChildStates'].addChildMapping()
689        child_state.mapping['serializedVersion'] = '1'
690        child_state.addChildMapping('m_State').mapping['fileID'] = str(new_id)
691        state_pos = child_state.addChildMapping('m_Position')
692        state_pos.mapping['x'] = str(280 + dx)
693        state_pos.mapping['y'] = str(80 + dy)
694        state_pos.mapping['z'] = '0'
695
696        if is_default_state:
697            layer.mapping['AnimatorStateMachine'].mapping['m_DefaultState'].mapping['fileID'] = str(new_id)
698
699        return node
700
701    def setAnimatorStateAnimation(self, anim_state, anim_guid):
702        anim_state.mapping['AnimatorState'].mapping['m_Motion'].mapping['guid'] = anim_guid
703        anim_state.mapping['AnimatorState'].mapping['m_Motion'].mapping['fileID'] = '7400000'
704        anim_state.mapping['AnimatorState'].mapping['m_Motion'].mapping['type'] = '2'
705
706    # Adds a blend tree which uses the parameter named `param_name` to blend
707    # between anim_lo and anim_hi. Also creates the corresponding animation
708    # state.
709    def addAnimatorBlendTree(self, layer, state_name, param_name,
710            anim_guid_lo, anim_guid_hi, dx = 0, dy = 0,
711            lo_threshold = -1.0, hi_threshold = 1.0,
712            is_default_state = False) -> UnityDocument:
713        # Create the blend tree.
714        parser = UnityParser()
715        parser.parse(BLEND_TREE_TEMPLATE)
716        new_anim = UnityAnimator()
717        new_anim.addNodes(parser.nodes)
718        node = new_anim.nodes[0]
719
720        new_id = self.allocateId()
721        node.class_id = "206"
722        node.anchor = str(new_id)
723        tree = node.mapping['BlendTree']
724        tree.mapping['m_Name'] = state_name
725        # Low animation
726        tree.mapping['m_Childs'].sequence[0].mapping['m_Motion'].mapping['guid'] = anim_guid_lo
727        tree.mapping['m_Childs'].sequence[0].mapping['m_DirectBlendParameter'] = param_name
728        tree.mapping['m_Childs'].sequence[0].mapping['m_Threshold'] = str(lo_threshold)
729        # High animation
730        tree.mapping['m_Childs'].sequence[1].mapping['m_Motion'].mapping['guid'] = anim_guid_hi
731        tree.mapping['m_Childs'].sequence[1].mapping['m_DirectBlendParameter'] = param_name
732        tree.mapping['m_Childs'].sequence[1].mapping['m_Threshold'] = str(hi_threshold)
733
734        tree.mapping['m_BlendParameter'] = param_name
735        tree.mapping['m_BlendParameterY'] = param_name
736
737        self.nodes.append(node)
738
739        # Create the corresponding animation state.
740        anim_state = self.addAnimatorState(layer, state_name, is_default_state, dx = dx, dy =
741                dy)
742        anim_state.mapping['AnimatorState'].mapping['m_Motion'].mapping['fileID'] = node.anchor
743
744        return anim_state
745
746    def addTransition(self, dst_state, dur_s = 0.0):
747        # Create animation state
748        parser = UnityParser()
749        parser.parse(TRANSITION_TEMPLATE)
750        new_transition = UnityAnimator()
751        new_transition.addNodes(parser.nodes)
752        node = new_transition.nodes[0]
753
754        new_id = self.allocateId()
755        node.class_id = "1101"
756        node.anchor = str(new_id)
757        state = node.mapping['AnimatorStateTransition']
758        state.mapping['m_DstState'].mapping['fileID'] = copy.copy(dst_state.anchor)
759        state.mapping['m_TransitionDuration'] = dur_s
760        self.nodes.append(node)
761
762        return node
763
764    def fixWriteDefaults(self, guid_map, generated_anim_path):
765        # TODO(yum) we should have an Animation class which encapsulates all
766        # this stuff.
767        parser = UnityParser()
768        parser.parse(WRITE_DEFAULTS_ANIM_TEMPLATE)
769        new_anim = UnityAnimator()
770        new_anim.addNodes(parser.nodes)
771
772        new_clip = new_anim.peekNodeOfClass('74').mapping['AnimationClip']
773        curve_template = new_clip.mapping['m_FloatCurves'].sequence[0]
774        new_clip.mapping['m_FloatCurves'].sequence = []
775        new_clip.mapping['m_EditorCurves'].sequence = []
776
777        # Keep track of the (attribute, path) tuples we've already set to avoid
778        # animating the same thing twice.
779        attributes_set = set()
780
781        animator_state_id = '1102'
782        for node in self.nodes:
783            if node.class_id != animator_state_id:
784                continue
785
786            # Looking at an animator state.
787            if node.mapping['AnimatorState'].mapping['m_WriteDefaultValues'] != '1':
788                continue
789
790            # Disable write defaults.
791            node.mapping['AnimatorState'].mapping['m_WriteDefaultValues'] = '0'
792
793            # Looking at an animator state with write defaults.
794            motion = node.mapping['AnimatorState'].mapping['m_Motion']
795            # Some animations have write defaults but don't trigger an
796            # animation. No idea what that's about. For now, just ignore.
797            if not 'guid' in motion.mapping:
798                continue
799            guid = motion.mapping['guid']
800
801            # Again, not really sure what's going on here, just ignore and
802            # revisit if we hit problems.
803            if not guid in guid_map.keys():
804                continue
805
806            # OK, we found an animation with write defaults, and we know where
807            # the animation lives. Crack it open and see what it's writing.
808            animation_path = guid_map[guid]
809            print("Animation has write defaults: {}".format(animation_path), file=sys.stderr)
810            parser = UnityParser()
811            parser.parseFile(animation_path)
812            anim = UnityAnimator()
813            anim.addNodes(parser.nodes)
814
815            clip = anim.peekNodeOfClass('74')
816
817            for curve in clip.mapping['AnimationClip'].mapping['m_FloatCurves'].sequence:
818                attr = curve.mapping['attribute']
819                path = curve.mapping['path']
820                if (attr, path) in attributes_set:
821                    continue
822                #print("Fix attr/path {}/{}".format(attr, path), file=sys.stderr)
823                attributes_set.add((attr, path))
824
825                new_curve = curve_template.copy()
826                new_curve.mapping['attribute'] = attr
827                new_curve.mapping['path'] = path
828
829                new_clip.mapping['m_FloatCurves'].sequence.append(new_curve)
830                new_clip.mapping['m_EditorCurves'].sequence.append(new_curve)
831
832                #print("len float curves: {}".format(len(new_clip.mapping['m_FloatCurves'].sequence)), file=sys.stderr)
833
834    def generateOffAnimationForGuid(self, guid_map, generated_anim_dir, guid):
835        # Looking at an animation.
836        if not guid in guid_map.keys():
837            return
838
839        animation_path = guid_map[guid]
840        print("Checking animation at {}".format(animation_path), file=sys.stderr)
841        parser = UnityParser()
842        parser.parseFile(animation_path)
843        anim = UnityAnimator()
844        anim.addNodes(parser.nodes)
845
846        clip = anim.peekNodeOfClass('74')
847
848        has_nonzero = False
849        curve_members = ["m_FloatCurves", "m_EditorCurves"]
850        for memb in curve_members:
851            for curve in clip.mapping['AnimationClip'].mapping[memb].sequence:
852                attr = curve.mapping['attribute']
853                path = curve.mapping['path']
854
855                for m_curve in curve.mapping['curve'].mapping['m_Curve'].sequence:
856                    if m_curve.mapping['value'] != '0':
857                        has_nonzero = True
858                    m_curve.mapping['value'] = '0'
859
860        if not has_nonzero:
861            print("Animation does not set anything nonzero")
862            return
863
864        print("Animation sets things nonzero, fixing")
865
866        new_anim_path = "OFF_{}".format(os.path.basename(animation_path))
867        new_anim_path = "{}/{}".format(generated_anim_dir, new_anim_path)
868
869        with open(new_anim_path, "w", encoding="utf-8") as f:
870            f.write(str(anim))
871
872        meta = Metadata()
873        with open(new_anim_path + ".meta", "w", encoding="utf-8") as f:
874            f.write(str(meta))
875
876    def generateOffAnimationsAnimStates(self, guid_map, generated_anim_dir):
877        animator_state_id = '1102'
878        for node in self.nodes:
879            if node.class_id != animator_state_id:
880                continue
881
882            # Looking at an animation state.
883            motion = node.mapping['AnimatorState'].mapping['m_Motion']
884            if not 'guid' in motion.mapping:
885                continue
886            guid = motion.mapping['guid']
887            self.generateOffAnimationForGuid(guid_map, generated_anim_dir, guid)
888
889
890    def generateOffAnimationsBlendTrees(self, guid_map, generated_anim_dir):
891        animator_state_id = '206'
892        for node in self.nodes:
893            if node.class_id != animator_state_id:
894                continue
895
896            # Looking at an animation state.
897            for child in node.mapping['BlendTree'].mapping['m_Childs'].sequence:
898                motion = child.mapping['m_Motion']
899
900                if not 'guid' in motion.mapping:
901                    continue
902                guid = motion.mapping['guid']
903                self.generateOffAnimationForGuid(guid_map, generated_anim_dir, guid)
904
905    def generateOffAnimations(self, guid_map, generated_anim_dir):
906        self.generateOffAnimationsAnimStates(guid_map, generated_anim_dir)
907        self.generateOffAnimationsBlendTrees(guid_map, generated_anim_dir)
908
909    def addTransitionBooleanCondition(self, from_state, trans, param, branch):
910        # Populate the transition's condition logic.
911        cond = trans.mapping['AnimatorStateTransition'].mapping['m_Conditions'].addChildMapping()
912        if branch:
913            cond.mapping['m_ConditionMode'] = '1'
914        else:
915            cond.mapping['m_ConditionMode'] = '2'
916        cond.mapping['m_ConditionEvent'] = param
917        cond.mapping['m_EventThreshold'] = '0'
918        # Register the transition with the `from_state`.
919        if from_state:
920            from_state_trans = from_state.mapping['AnimatorState'].mapping['m_Transitions'].addChildMapping()
921            from_state_trans.mapping['fileID'] = copy.copy(trans.anchor)
922
923    def addTransitionIntegerEqualityCondition(self, from_state, trans, param, param_val):
924        # Populate the transition's condition logic.
925        cond = trans.mapping['AnimatorStateTransition'].mapping['m_Conditions'].addChildMapping()
926        cond.mapping['m_ConditionMode'] = '6'
927        cond.mapping['m_ConditionEvent'] = param
928        # Curiously, the typo ("treshold" only has 1 'h') is needed for this to
929        # work, but not for boolean conditions to work.
930        cond.mapping['m_EventTreshold'] = str(param_val)
931        # Register the transition with the `from_state`.
932        if from_state:
933            from_state_trans = from_state.mapping['AnimatorState'].mapping['m_Transitions'].addChildMapping()
934            from_state_trans.mapping['fileID'] = trans.anchor
935
936    def addTransitionIntegerGreaterCondition(self, from_state, trans, param, param_val):
937        # Populate the transition's condition logic.
938        cond = trans.mapping['AnimatorStateTransition'].mapping['m_Conditions'].addChildMapping()
939        cond.mapping['m_ConditionMode'] = '3'
940        cond.mapping['m_ConditionEvent'] = param
941        cond.mapping['m_EventThreshold'] = str(param_val)
942        # Register the transition with the `from_state`.
943        if from_state:
944            from_state_trans = from_state.mapping['AnimatorState'].mapping['m_Transitions'].addChildMapping()
945            from_state_trans.mapping['fileID'] = trans.anchor
946
947    # TODO(yum) this should be factored out into generate_fx.py
948    def addTasttToggle(self, off_anim_path, on_anim_path, toggle_param,
949            guid_map):
950        self.addParameter(toggle_param, bool)
951
952        off_anim_meta = Metadata()
953        off_anim_meta.loadOrCreate(off_anim_path, guid_map)
954
955        on_anim_meta = Metadata()
956        on_anim_meta.loadOrCreate(on_anim_path, guid_map)
957
958        layer = self.addLayer('TaSTT_Toggle')
959        off_anim = self.addAnimatorState(layer, 'TaSTT_Toggle_Off', is_default_state = True)
960        self.setAnimatorStateAnimation(off_anim, off_anim_meta.guid)
961        on_anim = self.addAnimatorState(layer, 'TaSTT_Toggle_On')
962        self.setAnimatorStateAnimation(on_anim, on_anim_meta.guid)
963
964        # TODO(yum) make a Transition class with methods for adding boolean
965        # conditions
966        off_to_on = self.addTransition(on_anim)
967        self.addTransitionBooleanCondition(off_anim, off_to_on, toggle_param, True)
968
969        on_to_off = self.addTransition(off_anim)
970        self.addTransitionBooleanCondition(on_anim, on_to_off, toggle_param, False)
971
972    def setNoopAnimations(self, guid_map, noop_anim_path):
973        noop_anim_meta = Metadata()
974        noop_anim_meta.loadOrCreate(noop_anim_path, guid_map)
975
976        for node in self.nodes:
977            if node.class_id != "1102":
978                continue
979            motion = node.mapping['AnimatorState'].mapping['m_Motion']
980            replace = False
981
982            name = node.mapping['AnimatorState'].mapping['m_Name']
983            anchor = node.anchor
984
985            # As of 8 May 2023, idle states look like this:
986            #   m_Motion: {fileID: 7400000, guid: e5881c5b0c09be854b0fd6fd8144333f, type: 2}
987            # Before that, they looked like this:
988            #   m_Motion: {fileID: 0}
989            # The first predicate looks for the new pattern.
990            # The second predicate looks for the second pattern.
991            if "fileID" in motion.mapping.keys() and \
992                    "guid" in motion.mapping.keys() and \
993                    not motion.mapping["guid"] in guid_map:
994                motion.mapping["fileID"] = "7400000"
995                print(f"Set noop animation to guid {noop_anim_meta.guid} in state {node.anchor}")
996                motion.mapping["guid"] = noop_anim_meta.guid
997                motion.mapping["type"] = "2"
998            elif not ("fileID" in motion.mapping.keys() and
999                    motion.mapping["fileID"] != "0") and not ("guid" in
1000                            motion.mapping.keys() and motion.mapping["guid"] in
1001                            guid_map):
1002                motion.mapping["fileID"] = "7400000"
1003                print(f"Set noop animation to guid {noop_anim_meta.guid} in state {node.anchor}")
1004                motion.mapping["guid"] = noop_anim_meta.guid
1005                motion.mapping["type"] = "2"
1006            else:
1007                #print(f"Skipping state {anchor} / {name}")
1008                pass
1009
1010def unityYamlToString(nodes):
1011    lines = []
1012    preamble = """
1013%YAML 1.1
1014%TAG !u! tag:unity3d.com,2011:
1015"""[1:][:-1]
1016    if len(nodes) > 1 or (len(nodes) == 1 and nodes[0].anchor):
1017        lines.append(preamble)
1018    for doc in nodes:
1019        if len(nodes) > 1 or (len(nodes) == 1 and nodes[0].anchor):
1020            lines.append("--- !u!" + doc.class_id + " &" + doc.anchor)
1021        lines.append(str(doc))
1022    result = '\n'.join(lines)
1023
1024    for i in range(0,10):
1025        result = result.replace("\n\n", "\n")
1026
1027    return result
1028
1029class UnityParser:
1030    STREAM_START = 100
1031    STREAM_END = 199
1032
1033    DOCUMENT_START = 200
1034    DOCUMENT_END = 299
1035
1036    MAPPING_START = 300
1037    MAPPING_KEY = 301
1038
1039    SEQUENCE_VALUE = 400
1040
1041    def __init__(self):
1042        self.state = self.STREAM_START
1043        self.cur_scalar = None
1044        self.cur_node = None
1045
1046        # Simple list of parsed documents. Populated by parse().
1047        self.nodes = []
1048        self.prev_states = []
1049
1050    def __str__(self):
1051        return unityYamlToString(self.nodes)
1052
1053    def pushState(self, state):
1054        self.prev_states.append(self.state)
1055        self.state = state
1056        #print("state {} ({})".format(self.state, len(self.prev_states)))
1057
1058    def popState(self):
1059        self.state = self.prev_states[-1]
1060        self.prev_states = self.prev_states[0:len(self.prev_states) - 1]
1061        #print("state {} ({})".format(self.state, len(self.prev_states)))
1062        return self.state
1063
1064    def cleanYaml(self, yaml_str):
1065        lines = []
1066        first_document = True
1067        got_document = False
1068        for line in yaml_str.split("\n"):
1069            # Add end-of-document indicators.
1070            if line.startswith("---"):
1071                got_document = True
1072                if not first_document:
1073                    lines.append("...\n")
1074                first_document = False
1075
1076            # Remove class ID tag from each block.
1077            if line.startswith("---"):
1078                parts = line.split()
1079                lines.append(parts[0] + " " + parts[2] + "\n")
1080                continue
1081            lines.append(line)
1082
1083        if got_document:
1084            lines.append("...\n")
1085        return '\n'.join(lines)
1086
1087    def getClassIds(self, yaml_str):
1088        anchor_to_class_id = {}
1089        for line in yaml_str.split("\n"):
1090            if not line.startswith("---"):
1091                continue
1092
1093            parts = line.split()
1094            class_id = parts[1][3:]
1095            anchor = parts[2][1:]
1096            anchor_to_class_id[anchor] = class_id
1097
1098        return anchor_to_class_id
1099
1100    def parseFile(self, yaml_file):
1101        yaml_str = ""
1102        with open(yaml_file, "r", encoding="utf-8") as f:
1103            yaml_str = f.read()
1104        return self.parse(yaml_str)
1105
1106    def parse(self, yaml_str):
1107        anchor_to_class_id = self.getClassIds(yaml_str)
1108        yaml_str = self.cleanYaml(yaml_str)
1109
1110        for event in yaml.parse(yaml_str):
1111            if isinstance(event, yaml.StreamStartEvent):
1112                if len(self.prev_states) > 0:
1113                    raise Exception("Multiple StreamStartEvents received")
1114                self.pushState(self.STREAM_START)
1115
1116            elif isinstance(event, yaml.StreamEndEvent):
1117                if self.state != self.STREAM_START:
1118                    raise Exception("Document end received after state {}".format(self.state))
1119                self.popState()
1120                if len(self.prev_states) > 0:
1121                    raise Exception("Extra states at stream end")
1122
1123            elif isinstance(event, yaml.DocumentStartEvent):
1124                if self.state != self.STREAM_START and self.state != self.DOCUMENT_END:
1125                    raise Exception("Document start received after state {}".format(self.state))
1126                self.pushState(self.DOCUMENT_START)
1127
1128            elif isinstance(event, yaml.DocumentEndEvent):
1129                if self.state != self.DOCUMENT_START:
1130                    raise Exception("Document end received after state {}".format(self.state))
1131                self.popState()
1132                self.nodes.append(self.cur_node)
1133                self.cur_node = None
1134
1135            elif isinstance(event, yaml.MappingStartEvent):
1136                if self.cur_node == None:
1137                    self.cur_node = UnityDocument()
1138                    self.cur_node.anchor = event.anchor
1139                    if event.anchor:
1140                        self.cur_node.class_id = anchor_to_class_id[event.anchor]
1141                else:
1142                    self.cur_node = self.cur_node.addChildMapping(self.cur_scalar)
1143                self.pushState(self.MAPPING_START)
1144
1145            elif isinstance(event, yaml.MappingEndEvent):
1146                if self.state != self.MAPPING_START:
1147                    raise Exception("Mapping end received after state {}".format(self.state))
1148                self.popState()
1149                if self.state == self.MAPPING_KEY:
1150                    self.popState()
1151                if self.cur_node.parent != None:
1152                    self.cur_node = self.cur_node.parent
1153
1154            elif isinstance(event, yaml.SequenceStartEvent):
1155                self.cur_node = self.cur_node.addChildSequence(self.cur_scalar)
1156                self.pushState(self.SEQUENCE_VALUE)
1157
1158            elif isinstance(event, yaml.SequenceEndEvent):
1159                if self.state != self.SEQUENCE_VALUE:
1160                    raise Exception("Sequence end received after state {}".format(self.state))
1161                self.popState()
1162                if self.state == self.MAPPING_KEY:
1163                    self.popState()
1164                self.cur_node = self.cur_node.parent
1165
1166            elif isinstance(event, yaml.ScalarEvent):
1167                if self.state == self.MAPPING_START:
1168                    self.cur_scalar = event.value
1169                    self.pushState(self.MAPPING_KEY)
1170                elif self.state == self.MAPPING_KEY:
1171                    self.cur_node.mapping[self.cur_scalar] = event.value
1172                    self.popState()
1173                elif self.state == self.SEQUENCE_VALUE:
1174                    self.cur_node.sequence.append(event.value)
1175                else:
1176                    raise Exception("Scalar event received after state {}".format(self.state))
1177            else:
1178                raise Exception("Unhandled event {}".format(event))
1179            continue
1180
1181class MulticoreUnityParser:
1182    def parseFile(self, yaml_file):
1183        yaml_str = ""
1184        with open(yaml_file, "r", encoding="utf-8") as f:
1185            yaml_str = f.read()
1186        return self.parse(yaml_str)
1187
1188    def parse(self, yaml_str):
1189        lines = []
1190        documents = []
1191        first = True
1192        n_lines = 0
1193        for line in yaml_str.split("\n"):
1194            n_lines += 1
1195            if line.startswith("---"):
1196                if not first:
1197                    documents.append("\n".join(lines))
1198                    lines = []
1199                first = False
1200            lines.append(line)
1201        if len(lines) > 0:
1202            documents.append("\n".join(lines))
1203            lines = []
1204        print("Got {} documents out of {} lines".format(len(documents), n_lines), file=sys.stderr)
1205
1206        # Divide the work evenly among the # of CPUs we have available.
1207        n_threads = os.cpu_count()
1208        window_size = int(math.ceil(len(documents) / n_threads))
1209        merge_window = []
1210        merged_documents = []
1211        for i in range(0, len(documents)):
1212            if i > 0 and i % window_size == 0:
1213                merged_documents.append("\n".join(merge_window))
1214                merge_window = []
1215            merge_window.append(documents[i])
1216        if len(merge_window) > 0:
1217            merged_documents.append("\n".join(merge_window))
1218            merge_window = []
1219        documents = merged_documents
1220
1221        mgr = mp.Manager()
1222
1223        print("Spawning {} threads".format(len(documents)), file=sys.stderr)
1224        threads = []
1225        for document in documents:
1226            res = mgr.dict()
1227            thread = mp.Process(target = self.parseOneSerial, args = (document, res,))
1228            threads.append((thread, res))
1229            thread.start()
1230
1231        print("Joining threads", file=sys.stderr)
1232        nodes = []
1233        for thread, res in threads:
1234            thread.join()
1235            nodes += res['nodes']
1236
1237        print("Creating animator", file=sys.stderr)
1238        result = UnityAnimator()
1239        result.addNodes(nodes)
1240
1241        return result
1242
1243    def parseOneSerial(self, document, res):
1244        parser = UnityParser()
1245        parser.parse(document)
1246        res['nodes'] = parser.nodes
1247
1248    def parseFile(self, yaml_file):
1249        yaml_str = ""
1250        with open(yaml_file, "r", encoding="utf-8") as f:
1251            yaml_str = f.read()
1252        return self.parse(yaml_str)
1253
1254def getGuidMap(d):
1255    result = {}
1256    for f in os.scandir(d):
1257        path = f.path
1258        if f.is_dir():
1259            result.update(getGuidMap(path))
1260        if not f.is_file():
1261            continue
1262        suffix = ".meta"
1263        if path.endswith(suffix):
1264            with open(path, "r", encoding="utf-8") as f:
1265                for line in f:
1266                    if line.startswith("guid"):
1267                        guid = line.split()[1]
1268                        result[guid] = path[:-len(suffix)]
1269    return result
1270
1271if __name__ == "__main__":
1272    os.chdir(os.path.dirname(os.path.abspath(__file__)))
1273
1274    parser = argparse.ArgumentParser()
1275    parser.add_argument("cmd", type=str, help="One of merge, guid_map, fix_write_defaults")
1276    parser.add_argument("--fx0", type=str, help="The first animator to merge")
1277    parser.add_argument("--fx1", type=str, help="The second animator to merge")
1278    parser.add_argument("--fx_dest", type=str, help="The path at which to " +
1279            "save the generated/merged animator")
1280    parser.add_argument("--project_root", type=str, help="The path to the " +
1281            "Unity project Assets folder")
1282    parser.add_argument("--save_to", type=str, help="The path to save the " +
1283            "result of the computation")
1284    parser.add_argument("--guid_map", type=str, help="Path to guid.map, " +
1285            "generated by a previous call to `guid_map`")
1286    parser.add_argument("--guid_map_append", type=bool, help="If set, " +
1287            "append to GUID map instead of overwriting.")
1288    parser.add_argument("--gen_anim_dir", type=str, help="The folder under which generated animations are stored")
1289    args = parser.parse_args()
1290
1291    if args.cmd == "merge":
1292        if not args.fx0 or not args.fx1 or not args.fx_dest:
1293            print("--fx0, --fx1, and --fx_dest required", file=sys.stderr)
1294            parser.print_help()
1295            parser.exit(1)
1296
1297        print("Parsing {}".format(args.fx0), file=sys.stderr)
1298        parser0 = MulticoreUnityParser()
1299        anim0 = parser0.parseFile(args.fx0)
1300
1301        arg1 = "TaSTT_fx.controller"
1302        print("Parsing {}".format(args.fx1), file=sys.stderr)
1303        parser1 = MulticoreUnityParser()
1304        anim1 = parser1.parseFile(args.fx1)
1305
1306        print("Merging animators", file=sys.stderr)
1307        anim0.merge(anim1)
1308
1309        print("Serializing to {}".format(args.fx_dest), file=sys.stderr)
1310        with open(args.fx_dest, "w", encoding="utf-8") as f:
1311            f.write(unityYamlToString(anim0.nodes))
1312
1313    elif args.cmd == "guid_map":
1314        if not args.project_root or not args.save_to:
1315            print("--project_root and --save_to required")
1316            parser.print_help()
1317            parser.exit(1)
1318
1319        print("Looking up GUIDs under {}".format(args.project_root),
1320                file=sys.stderr)
1321        guid_map = getGuidMap(args.project_root)
1322
1323        save_to_dir = os.path.dirname(args.save_to)
1324        os.makedirs(save_to_dir, exist_ok=True)
1325
1326        if args.guid_map_append:
1327            tmp_map = {}
1328            with open(args.save_to, "rb") as f:
1329                tmp_map = pickle.load(f)
1330            # combine guid_map and tmp_map
1331            guid_map = {**guid_map, **tmp_map}
1332        print("Saving to {}".format(args.save_to), file=sys.stderr)
1333        with open(args.save_to, 'wb') as f:
1334            pickle.dump(guid_map, f)
1335    elif args.cmd == "fix_write_defaults":
1336        if not args.fx0 or not args.guid_map:
1337            print("--fx0 and --guid_map required")
1338            parser.print_help()
1339            parser.exit(1)
1340
1341        guid_map = {}
1342        with open(args.guid_map, 'rb') as f:
1343            guid_map = pickle.load(f)
1344
1345        print("Parsing {}".format(args.fx0), file=sys.stderr)
1346        parser0 = MulticoreUnityParser()
1347        anim = parser0.parseFile(args.fx0)
1348
1349        print("Fixing write defaults", file=sys.stderr)
1350        anim_dir = "generated/animations/"
1351        os.makedirs(anim_dir, exist_ok=True)
1352        anim.fixWriteDefaults(guid_map, anim_dir + "TaSTT_Reset_Animation.anim")
1353        print(str(anim))
1354
1355    elif args.cmd == "gen_off_anims":
1356        if not args.fx0 or not args.guid_map:
1357            print("--fx0 and --guid_map required")
1358            parser.print_help()
1359            parser.exit(1)
1360
1361        guid_map = {}
1362        with open(args.guid_map, 'rb') as f:
1363            guid_map = pickle.load(f)
1364
1365        print("Parsing {}".format(args.fx0), file=sys.stderr)
1366        parser0 = MulticoreUnityParser()
1367        anim = parser0.parseFile(args.fx0)
1368
1369        print("Generating off animations", file=sys.stderr)
1370        anim_dir = "generated/animations/"
1371        os.makedirs(anim_dir, exist_ok=True)
1372        anim.generateOffAnimations(guid_map, "generated/animations")
1373
1374    elif args.cmd == "add_toggle":
1375        if not args.fx0 or not args.fx_dest or not args.gen_anim_dir or not args.guid_map:
1376            print("--fx0, --fx_dest, --gen_anim_dir and --guid_map required")
1377            parser.print_help()
1378            parser.exit(1)
1379
1380        guid_map = {}
1381        with open(args.guid_map, 'rb') as f:
1382            guid_map = pickle.load(f)
1383
1384        print("Parsing {}".format(args.fx0), file=sys.stderr)
1385        parser0 = MulticoreUnityParser()
1386        anim = parser0.parseFile(args.fx0)
1387
1388        print("Adding toggle", file=sys.stderr)
1389        anim.addTasttToggle(args.gen_anim_dir + "/TaSTT_Toggle_Off.anim",
1390                args.gen_anim_dir + "/TaSTT_Toggle_On.anim", "TaSTT_Toggle",
1391                guid_map)
1392
1393        print("Serializing to {}".format(args.fx_dest), file=sys.stderr)
1394        with open(args.fx_dest, "w", encoding="utf-8") as f:
1395            f.write(str(anim))
1396
1397        with open(args.guid_map, 'wb') as f:
1398            pickle.dump(guid_map, f)
1399
1400    elif args.cmd == "fast_parse_test":
1401        if not args.fx0:
1402            print("--fx0 required")
1403            parser.print_help()
1404            parser.exit(1)
1405
1406        print("Parsing {}".format(args.fx0), file=sys.stderr)
1407        parser0 = MulticoreUnityParser()
1408        anim = parser0.parseFile(args.fx0)
1409        print(str(anim))
1410
1411    elif args.cmd == "set_noop_anim":
1412        if not args.fx0 or not args.fx_dest or not args.gen_anim_dir or not args.guid_map:
1413            print("--fx0, --fx_dest, --gen_anim_dir and --guid_map required")
1414            parser.print_help()
1415            parser.exit(1)
1416
1417        guid_map = {}
1418        with open(args.guid_map, 'rb') as f:
1419            guid_map = pickle.load(f)
1420
1421        print("Parsing {}".format(args.fx0), file=sys.stderr)
1422        parser = MulticoreUnityParser()
1423        anim = parser.parseFile(args.fx0)
1424
1425        anim.setNoopAnimations(guid_map, args.gen_anim_dir + "/TaSTT_Do_Nothing.anim")
1426
1427        with open(args.fx_dest, "w", encoding="utf-8") as f:
1428            f.write(str(anim))
1429
1430    else:
1431        print("Unrecognized command: {}".format(args.cmd))
1432