yum-slop/YOTS
an optimized toggle system for vrchat
git clone https://git.yummers.dev/yum-slop/YOTS
2e9ac4c
v1.1.0
1#if UNITY_EDITOR 2 3using System ; 4using System . Collections . Generic ; 5using System . IO ; 6using System . Linq ; 7using UnityEngine ; 8using UnityEditor ; 9using UnityEditor . Animations ; 10using VRC . SDK3 . Avatars . Components ; 11using VRC . SDK3 . Avatars . ScriptableObjects ; 12 13namespace YOTS 14{ 15[ System . Serializable ] 16public class ToggleSpec { 17// The name of the toggle. This is plumbed into the menu, the VRChat 18// parameters, and the animator parameters. 19[ SerializeField ] 20public string name ; 21 22// The type of toggle. 23// Accepted values: 24// "toggle" - A boolean toggle. Creates a boolean sync param. 25// "radial" - A radial puppet. Creates a float sync param. 26[ SerializeField ] 27public string type = "toggle" ; 28 29// Dependencies are toggles that will be evaluated before this one. If 30// you have two toggles which animate the same thing, one must depend 31// on the other. 32[ SerializeField ] 33public List < string > dependencies = new List < string > () ; 34 35// The name of meshes to toggle. 36// For example, "Body" or "Shirt". 37[ SerializeField ] 38public List < string > meshToggles = new List < string > () ; 39 40// Blendshapes to animate. 41[ SerializeField ] 42public List < BlendShapeSpec > blendShapes = new List < BlendShapeSpec > () ; 43 44// Material properties to animate. 45[ SerializeField ] 46public List < ShaderToggleSpec > shaderToggles = new List < ShaderToggleSpec > () ; 47 48// Where to put the toggle in the menu. All toggles are placed under 49// /YOTS. So if you put "Clothes" here, it'll be placed under 50// /YOTS/Clothes. 51[ SerializeField ] 52public string menuPath = "/YOTS" ; 53 54// The default value of the toggle. Range from 0-1. 55// For example, if you want a gimmick to start toggled off, set this to 56// 0.0f. 57[ SerializeField ] 58public float defaultValue = 1.0f ; 59 60// Whether the corresponding VRChat parameter is synced. 61[ SerializeField ] 62public bool synced = true ; 63 64// Whether the corresponding VRChat parameter is saved. 65[ SerializeField ] 66public bool saved = true ; 67 68// If true, no menu entry will be created for this toggle. 69// The parameter will still be created and can be controlled by other means 70// - for example, via contacts. 71[ SerializeField ] 72public bool disableMenuEntry = false ; 73} 74 75[ System . Serializable ] 76public class BlendShapeSpec { 77// The name of the blend shape to apply. 78// For example, "Chest_Hide" or "Boobs+". 79[ SerializeField ] 80public string blendShape ; 81 82// The path to the mesh renderer to apply the blend shape to. 83// For example, "Body" or "Shirt". 84[ SerializeField ] 85public string path ; 86 87// The value of the blendshape when the toggle is off. Range from 0-100. 88[ SerializeField ] 89public float offValue = 0.0f ; 90 91// The value of the blendshape when the toggle is on. Range from 0-100. 92[ SerializeField ] 93public float onValue = 100.0f ; 94} 95 96[ System . Serializable ] 97public class ShaderToggleSpec { 98[ SerializeField ] 99public string materialProperty ; 100 101[ SerializeField ] 102public string path = "" ; 103 104[ SerializeField ] 105public List < string > paths = new List < string > () ; 106 107[ SerializeField ] 108public float offValue = 0.0f ; 109 110[ SerializeField ] 111public float onValue = 1.0f ; 112} 113 114[ System . Serializable ] 115public class AnimatorConfigFile { 116[ SerializeField ] 117public List < ToggleSpec > toggles = new List < ToggleSpec > () ; 118 119[ SerializeField ] 120public string api_version ; 121} 122 123[ System . Serializable ] 124public class GeneratedAnimationsConfig { 125public List < GeneratedAnimationClipConfig > animations = 126new List < GeneratedAnimationClipConfig > () ; 127} 128 129[ System . Serializable ] 130public class GeneratedAnimationClipConfig { 131public string name ; 132public List < GeneratedMeshToggle > meshToggles = 133new List < GeneratedMeshToggle > () ; 134public List < GeneratedBlendShape > blendShapes = 135new List < GeneratedBlendShape > () ; 136public List < GeneratedShaderToggle > shaderToggles = 137new List < GeneratedShaderToggle > () ; 138} 139 140[ System . Serializable ] 141public class GeneratedMeshToggle { 142public string path ; 143public float value ; 144} 145 146[ System . Serializable ] 147public class GeneratedBlendShape { 148public string path ; 149public string blendShape ; 150public float value ; 151} 152 153// Add new class for generated shader toggles 154[ System . Serializable ] 155public class GeneratedShaderToggle { 156public string path ; 157public string materialProperty ; 158public float value ; 159} 160 161// These classes describe the generated JSON output for the animator configuration. 162[ System . Serializable ] 163public class GeneratedAnimatorConfig { 164public List < AnimatorParameterSetting > parameters = new List < AnimatorParameterSetting > () ; 165public List < AnimatorLayer > layers = new List < AnimatorLayer > () ; 166public List < GeneratedAnimationClipConfig > animations = 167new List < GeneratedAnimationClipConfig > () ; 168} 169 170[ System . Serializable ] 171public class AnimatorLayer { 172public string name ; 173public AnimatorDirectBlendTree directBlendTree = 174new AnimatorDirectBlendTree () ; 175} 176 177[ System . Serializable ] 178public class AnimatorDirectBlendTree { 179public List < AnimatorDirectBlendTreeEntry > entries = 180new List < AnimatorDirectBlendTreeEntry > () ; 181} 182 183[ System . Serializable ] 184public class AnimatorDirectBlendTreeEntry { 185public string name ; // animation name 186public string parameter ; // parameter driving the animation 187} 188 189// Add these new classes at the namespace level 190[ System . Serializable ] 191public class VRCMenuConfig { 192public string menuName = "YOTS" ; 193public List < VRCMenuItemConfig > items = new List < VRCMenuItemConfig > () ; 194} 195 196[ System . Serializable ] 197public class VRCMenuItemConfig { 198public string name ; 199public string parameter ; 200public Texture2D icon ; 201} 202 203[ System . Serializable ] 204public class AnimatorParameterSetting { 205public string name ; 206public float defaultValue ; 207} 208 209public class YOTSCore { 210private static Dictionary < string , AnimationClip > animationClips = new Dictionary < string , AnimationClip > () ; 211 212private static string GetMeshToggleAttributeId ( string path ) { 213return "MeshToggle:" + path ; 214} 215 216private static string GetBlendShapeAttributeId ( string path , string blendShape ) { 217return "BlendShape:" + path + "/" + blendShape ; 218} 219 220private static string GetShaderToggleAttributeId ( string path , string materialProperty ) { 221return "ShaderToggle:" + path + "/" + materialProperty ; 222} 223 224public static AnimatorController GenerateAnimator ( string configJson , 225VRCExpressionParameters vrcParams , VRCExpressionsMenu vrcMenu ) { 226Debug . Log ( "=== Starting Animator Generation Process ===" ) ; 227 228if ( string . IsNullOrEmpty ( configJson )) { 229throw new ArgumentException ( "No config JSON provided." ) ; 230} 231 232AnimatorConfigFile config ; 233config = JsonUtility . FromJson < AnimatorConfigFile > ( configJson ) ; 234if ( config == null ) { 235throw new ArgumentException ( "JSON config is empty or invalid" ) ; 236} 237if ( config . toggles == null ) { 238throw new ArgumentException ( "No toggleSpecs found in configuration" ) ; 239} 240Debug . Log ( $"Configuration loaded. Found { config . toggles . Count } toggles." ) ; 241 242// Create abstract representation of the animator. 243GeneratedAnimatorConfig genAnimatorConfig = GenerateNaiveAnimatorConfig ( config . toggles ) ; 244genAnimatorConfig = ApplyIndependentFixToAnimatorConfig ( genAnimatorConfig ) ; 245genAnimatorConfig = RemoveOffAnimationsFromOverrideLayers ( genAnimatorConfig ) ; 246genAnimatorConfig = RemoveUnusedAnimations ( genAnimatorConfig ) ; 247// Create actual assets. 248GenerateVRChatAssets ( config . toggles , vrcParams , vrcMenu ) ; 249CreateAnimationClips ( new GeneratedAnimationsConfig { animations = genAnimatorConfig . animations }) ; 250AnimatorController controller = GenerateAnimatorController ( genAnimatorConfig ) ; 251 252Debug . Log ( "=== Animator Generation Process Complete ===" ) ; 253return controller ; 254} 255 256private static void CreateAnimationClips ( GeneratedAnimationsConfig animationsConfig ) { 257foreach ( var clipConfig in animationsConfig . animations ) { 258AnimationClip newClip = new AnimationClip () ; 259newClip . name = clipConfig . name ; 260 261// Apply mesh toggles 262foreach ( var meshToggle in clipConfig . meshToggles ) { 263AnimationCurve curve = new AnimationCurve ( new Keyframe ( 0 , meshToggle . value )) ; 264EditorCurveBinding binding = new EditorCurveBinding () ; 265binding . path = meshToggle . path ; 266binding . type = typeof ( GameObject ) ; 267binding . propertyName = "m_IsActive" ; 268AnimationUtility . SetEditorCurve ( newClip , binding , curve ) ; 269} 270 271// Apply blend shapes 272foreach ( var blendShape in clipConfig . blendShapes ) { 273AnimationCurve curve = AnimationCurve . Constant ( 0 , 0 , blendShape . value ) ; 274EditorCurveBinding binding = new EditorCurveBinding () ; 275binding . path = blendShape . path ; 276binding . type = typeof ( SkinnedMeshRenderer ) ; 277binding . propertyName = "blendShape." + blendShape . blendShape ; 278AnimationUtility . SetEditorCurve ( newClip , binding , curve ) ; 279} 280 281// Apply shader toggles 282foreach ( var shaderToggle in clipConfig . shaderToggles ) { 283AnimationCurve curve = AnimationCurve . Constant ( 0 , 0 , shaderToggle . value ) ; 284EditorCurveBinding binding = new EditorCurveBinding () ; 285binding . path = shaderToggle . path ; 286binding . type = typeof ( SkinnedMeshRenderer ) ; 287binding . propertyName = $"material. { shaderToggle . materialProperty } " ; 288AnimationUtility . SetEditorCurve ( newClip , binding , curve ) ; 289} 290 291// Store in memory 292animationClips [ clipConfig . name ] = newClip ; 293Debug . Log ( "Created animation clip " + clipConfig . name ) ; 294} 295} 296 297private static AnimatorController GenerateAnimatorController ( GeneratedAnimatorConfig animatorConfig ) { 298AnimatorController controller = new AnimatorController () ; 299 300// Add weight parameter used to ensure that the blendtrees always 301// run. All layers use this. Documented on vrc.school: 302// http://vrc.school/docs/Other/DBT-Combining#ed504c95853f4924adeffb6b125234ad 303List < AnimatorControllerParameter > parameters_list = new List < AnimatorControllerParameter > () ; 304var yots_weight = new AnimatorControllerParameter () ; 305yots_weight . name = "YOTS_Weight" ; 306yots_weight . type = AnimatorControllerParameterType . Float ; 307yots_weight . defaultFloat = 1.0f ; 308parameters_list . Add ( yots_weight ) ; 309// Add all other parameters 310foreach ( var param in animatorConfig . parameters ) { 311var p = new AnimatorControllerParameter () ; 312p . name = param . name ; 313p . type = AnimatorControllerParameterType . Float ; 314p . defaultFloat = param . defaultValue ; 315parameters_list . Add ( p ) ; 316} 317controller . parameters = parameters_list . ToArray () ; 318 319// Add base layer. This is structured as a wide direct blendtree 320// (DBT) comprised of blendtrees animating pairs of On/Off 321// animations. 322var baseLayerConfig = animatorConfig . layers [ 0 ] ; 323var baseStateMachine = new AnimatorStateMachine () ; 324baseStateMachine . name = "YOTS_BaseLayer_SM" ; 325 326var rootBlendTree = new BlendTree () ; 327rootBlendTree . name = "YOTS_BaseLayer_RootBlendTree" ; 328rootBlendTree . blendType = BlendTreeType . Direct ; 329 330var parameterGroups = baseLayerConfig . directBlendTree . entries 331. GroupBy ( e => e . parameter ) 332. ToDictionary ( g => g . Key , g => g . ToList ()) ; 333 334// Iterate over (parameter, animationSet) pairs in the base layer. 335foreach ( var group in parameterGroups ) { 336var param = group . Key ; 337var animations = group . Value ; 338 339// Create a blendtree controlled by this toggle's parameter. 340var paramBlendTree = new BlendTree () ; 341paramBlendTree . name = $"YOTS_BlendTree_ { param } " ; 342paramBlendTree . blendType = BlendTreeType . Simple1D ; 343paramBlendTree . blendParameter = param ; 344 345var children = new List < ChildMotion > () ; 346foreach ( var animation in animations . OrderBy ( e => e . name . EndsWith ( "_On" ))) { 347Debug . Log ( "Adding child motion for: " + animation . name ) ; 348if ( ! animationClips . TryGetValue ( animation . name , out AnimationClip clip )) { 349throw new InvalidOperationException ( $"Animation clip not found in memory: { animation . name } " ) ; 350} 351 352children . Add ( new ChildMotion { 353motion = clip , 354timeScale = 1f , 355threshold = animation . name . EndsWith ( "_On" ) ? 1f : 0f 356}) ; 357} 358paramBlendTree . children = children . ToArray () ; 359 360// Add that blendtree to the parent direct blendtree (DBT) 361// controlled by YOTS_Weight. That YOTS_Weight parameter is 362// always set to 1, so the child blendtree always runs. 363rootBlendTree . children = rootBlendTree . children . Append ( 364new ChildMotion { 365motion = paramBlendTree , 366timeScale = 1f , 367directBlendParameter = "YOTS_Weight" 368}) . ToArray () ; 369} 370 371var baseState = baseStateMachine . AddState ( "YOTS_BaseLayer_State" ) ; 372baseState . motion = rootBlendTree ; 373baseState . writeDefaultValues = true ; 374baseStateMachine . defaultState = baseState ; 375 376controller . AddLayer ( new AnimatorControllerLayer { 377name = "YOTS_BaseLayer" , 378defaultWeight = 1.0f , 379stateMachine = baseStateMachine 380}) ; 381 382// Add override layers. These are DBTs of On animations (no Off 383// animations). 384for ( int i = 1 ; i < animatorConfig . layers . Count ; i ++ ) { 385var layerConfig = animatorConfig . layers [ i ] ; 386string layerName = $"YOTS_OverrideLayer { ( i - 1 ) . ToString ( "00" ) } " ; 387 388var stateMachine = new AnimatorStateMachine () ; 389stateMachine . name = layerName + "_SM" ; 390 391var blendTree = new BlendTree () ; 392blendTree . name = layerName + "_BlendTree" ; 393blendTree . blendType = BlendTreeType . Direct ; 394 395foreach ( var entry in layerConfig . directBlendTree . entries ) { 396if ( ! animationClips . TryGetValue ( entry . name , out AnimationClip clip )) { 397throw new InvalidOperationException ( $"Animation clip not found in memory: { entry . name } " ) ; 398} 399 400blendTree . children = blendTree . children . Append ( new ChildMotion { 401motion = clip , 402timeScale = 1f , 403directBlendParameter = entry . parameter 404}) . ToArray () ; 405} 406 407var state = stateMachine . AddState ( layerName + "_State" ) ; 408state . motion = blendTree ; 409state . writeDefaultValues = true ; 410stateMachine . defaultState = state ; 411 412controller . AddLayer ( new AnimatorControllerLayer { 413name = layerName , 414defaultWeight = 1.0f , 415stateMachine = stateMachine 416}) ; 417 418Debug . Log ( $"Added override layer: { layerName } " ) ; 419} 420 421return controller ; 422} 423 424private static Dictionary < string , int > TopologicalSortToggles ( List < ToggleSpec > toggleSpecs ) { 425// Get mapping from toggle name to children 426Dictionary < string , HashSet < string >> graph = new Dictionary < string , HashSet < string >> () ; 427foreach ( var toggle in toggleSpecs ) { 428if ( ! graph . ContainsKey ( toggle . name )) 429graph [ toggle . name ] = new HashSet < string > () ; 430foreach ( var dep in toggle . dependencies ) { 431if ( ! graph . ContainsKey ( dep )) 432graph [ dep ] = new HashSet < string > () ; 433graph [ dep ] . Add ( toggle . name ) ; 434} 435} 436 437Dictionary < string , int > inDegree = new Dictionary < string , int > () ; 438foreach ( var toggle in toggleSpecs ) { 439inDegree [ toggle . name ] = toggle . dependencies . Count ; 440} 441 442Dictionary < string , int > depths = new Dictionary < string , int > () ; 443Queue < string > queue = new Queue < string > () ; 444 445// Identify start nodes 446foreach ( var pair in inDegree ) { 447if ( pair . Value == 0 ) { 448queue . Enqueue ( pair . Key ) ; 449depths [ pair . Key ] = 0 ; 450} 451} 452 453int processedNodes = 0 ; 454while ( queue . Count > 0 ) { 455// Pop start nodes one by one. 456string current = queue . Dequeue () ; 457processedNodes ++ ; 458int currentDepth = depths [ current ] ; 459// Enqueue children and set their depth to cur depth + 1. 460foreach ( var child in graph [ current ]) { 461inDegree [ child ] -- ; 462if ( inDegree [ child ] == 0 ) { 463queue . Enqueue ( child ) ; 464depths [ child ] = currentDepth + 1 ; 465} 466} 467} 468 469if ( processedNodes != toggleSpecs . Count ) { 470var cycleNodes = toggleSpecs 471. Where ( t => ! depths . ContainsKey ( t . name )) 472. Select ( t => t . name ) 473. ToList () ; 474throw new System . Exception ( $"Dependency cycle detected in toggle specifications. Nodes involved: { string . Join ( ", " , cycleNodes ) } " ) ; 475} 476 477return depths ; 478} 479 480private static GeneratedAnimatorConfig GenerateNaiveAnimatorConfig ( List < ToggleSpec > toggleSpecs ) { 481GeneratedAnimatorConfig genAnimatorConfig = new GeneratedAnimatorConfig () ; 482// Sort toggles into layers 483Dictionary < string , int > depths = TopologicalSortToggles ( toggleSpecs ) ; 484var togglesByDepth = toggleSpecs 485. GroupBy ( t => depths [ t . name ]) 486. OrderBy ( g => g . Key ) 487. ToList () ; 488// Add layers 489for ( int i = 0 ; i < togglesByDepth . Count ; i ++ ) { 490var depthGroup = togglesByDepth [ i ] ; 491AnimatorLayer layer = new AnimatorLayer () ; 492layer . name = i == 0 ? "YOTS_BaseLayer" : $"YOTS_OverrideLayer { ( i - 1 ) . ToString ( "00" ) } " ; 493foreach ( var toggle in depthGroup ) { 494string paramName = toggle . name ; 495if ( ! genAnimatorConfig . parameters . Any ( p => p . name == paramName )) 496genAnimatorConfig . parameters . Add ( new AnimatorParameterSetting { 497name = paramName , 498defaultValue = toggle . defaultValue 499}) ; 500 501layer . directBlendTree . entries . Add ( new AnimatorDirectBlendTreeEntry { 502name = toggle . name + "_On" , 503parameter = paramName 504}) ; 505 506layer . directBlendTree . entries . Add ( new AnimatorDirectBlendTreeEntry { 507name = toggle . name + "_Off" , 508parameter = paramName 509}) ; 510} 511genAnimatorConfig . layers . Add ( layer ) ; 512} 513// Add animations 514GeneratedAnimationsConfig animConfig = GenerateAnimationConfig ( toggleSpecs ) ; 515genAnimatorConfig . animations = animConfig . animations ; 516return genAnimatorConfig ; 517} 518 519private static GeneratedAnimationsConfig GenerateAnimationConfig ( List < ToggleSpec > toggleSpecs ) { 520GeneratedAnimationsConfig genAnimConfig = new GeneratedAnimationsConfig () ; 521foreach ( var toggle in toggleSpecs ) { 522GeneratedAnimationClipConfig onAnim = new GeneratedAnimationClipConfig () ; 523onAnim . name = toggle . name + "_On" ; 524if ( toggle . meshToggles != null ) { 525foreach ( var mesh in toggle . meshToggles ) { 526onAnim . meshToggles . Add ( new GeneratedMeshToggle { path = mesh , value = 1.0f }) ; 527} 528} 529if ( toggle . blendShapes != null ) { 530foreach ( var bs in toggle . blendShapes ) { 531onAnim . blendShapes . Add ( new GeneratedBlendShape { 532path = bs . path , 533blendShape = bs . blendShape , 534value = bs . onValue 535}) ; 536} 537} 538// Add shader toggles 539if ( toggle . shaderToggles != null ) { 540foreach ( var st in toggle . shaderToggles ) { 541// Validate that at least one path is provided 542if ( string . IsNullOrEmpty ( st . path ) && ( st . paths == null || st . paths . Count == 0 )) { 543throw new ArgumentException ( $"Shader toggle in ' { toggle . name } ' must specify either 'path' or 'paths'" ) ; 544} 545 546// Handle single path 547if ( ! string . IsNullOrEmpty ( st . path )) { 548onAnim . shaderToggles . Add ( new GeneratedShaderToggle { 549path = st . path , 550materialProperty = st . materialProperty , 551value = st . onValue 552}) ; 553} 554// Handle multiple paths 555if ( st . paths != null ) { 556foreach ( var path in st . paths ) { 557onAnim . shaderToggles . Add ( new GeneratedShaderToggle { 558path = path , 559materialProperty = st . materialProperty , 560value = st . onValue 561}) ; 562} 563} 564} 565} 566genAnimConfig . animations . Add ( onAnim ) ; 567 568GeneratedAnimationClipConfig offAnim = new GeneratedAnimationClipConfig () ; 569offAnim . name = toggle . name + "_Off" ; 570if ( toggle . meshToggles != null ) { 571foreach ( var mesh in toggle . meshToggles ) { 572offAnim . meshToggles . Add ( new GeneratedMeshToggle { path = mesh , value = 0.0f }) ; 573} 574} 575if ( toggle . blendShapes != null ) { 576foreach ( var bs in toggle . blendShapes ) { 577offAnim . blendShapes . Add ( new GeneratedBlendShape { 578path = bs . path , 579blendShape = bs . blendShape , 580value = bs . offValue 581}) ; 582} 583} 584// Add shader toggles 585if ( toggle . shaderToggles != null ) { 586foreach ( var st in toggle . shaderToggles ) { 587// Validate that at least one path is provided 588if ( string . IsNullOrEmpty ( st . path ) && ( st . paths == null || st . paths . Count == 0 )) { 589throw new ArgumentException ( $"Shader toggle in ' { toggle . name } ' must specify either 'path' or 'paths'" ) ; 590} 591 592// Handle single path 593if ( ! string . IsNullOrEmpty ( st . path )) { 594offAnim . shaderToggles . Add ( new GeneratedShaderToggle { 595path = st . path , 596materialProperty = st . materialProperty , 597value = st . offValue 598}) ; 599} 600// Handle multiple paths 601if ( st . paths != null ) { 602foreach ( var path in st . paths ) { 603offAnim . shaderToggles . Add ( new GeneratedShaderToggle { 604path = path , 605materialProperty = st . materialProperty , 606value = st . offValue 607}) ; 608} 609} 610} 611} 612genAnimConfig . animations . Add ( offAnim ) ; 613} 614return genAnimConfig ; 615} 616 617private static GeneratedAnimatorConfig ApplyIndependentFixToAnimatorConfig ( GeneratedAnimatorConfig genAnimatorConfig ) { 618// TODO meshToggles do not implement offValue/onValue at the JSON level, 619// so this is redundant. 620float GetOffValueForMesh ( string path , List < GeneratedMeshToggle > offList ) { 621var offToggle = offList ?. FirstOrDefault ( mt => mt . path == path ) ; 622return offToggle != null ? offToggle . value : 0.0f ; 623} 624 625float GetOffValueForBlend ( string path , string blendShapeName , List < GeneratedBlendShape > offList ) { 626var offBlend = offList ?. FirstOrDefault ( bs => bs . path == path && bs . blendShape == blendShapeName ) ; 627return offBlend != null ? offBlend . value : 0.0f ; 628} 629 630float GetOffValueForShader ( string path , string materialProperty , List < GeneratedShaderToggle > offList ) { 631var offShader = offList ?. FirstOrDefault ( st => st . path == path && st . materialProperty == materialProperty ) ; 632return offShader != null ? offShader . value : 0.0f ; 633} 634 635// Create mapping from toggle name -> (on animation, off animation) 636Dictionary < string , ( GeneratedAnimationClipConfig on , GeneratedAnimationClipConfig off ) > toggleAnimations = 637new Dictionary < string , ( GeneratedAnimationClipConfig , GeneratedAnimationClipConfig ) > () ; 638foreach ( var anim in genAnimatorConfig . animations ) { 639if ( anim . name . EndsWith ( "_On" )) { 640string toggleName = anim . name . Substring ( 0 , anim . name . LastIndexOf ( "_On" )) ; 641if ( ! toggleAnimations . ContainsKey ( toggleName )) 642toggleAnimations [ toggleName ] = ( null , null ) ; 643var pair = toggleAnimations [ toggleName ] ; 644pair . on = anim ; 645toggleAnimations [ toggleName ] = pair ; 646} 647else if ( anim . name . EndsWith ( "_Off" )) { 648string toggleName = anim . name . Substring ( 0 , anim . name . LastIndexOf ( "_Off" )) ; 649if ( ! toggleAnimations . ContainsKey ( toggleName )) 650toggleAnimations [ toggleName ] = ( null , null ) ; 651var pair = toggleAnimations [ toggleName ] ; 652pair . off = anim ; 653toggleAnimations [ toggleName ] = pair ; 654} 655} 656 657Dictionary < string , int > toggleToLayerIndex = new Dictionary < string , int > () ; 658for ( int i = 0 ; i < genAnimatorConfig . layers . Count ; i ++ ) { 659var layer = genAnimatorConfig . layers [ i ] ; 660foreach ( var entry in layer . directBlendTree . entries ) { 661string entryName = entry . name ; 662string toggleName = entryName ; 663if ( toggleName . EndsWith ( "_On" )) 664toggleName = toggleName . Substring ( 0 , toggleName . Length - "_On" . Length ) ; 665else if ( toggleName . EndsWith ( "_Off" )) 666toggleName = toggleName . Substring ( 0 , toggleName . Length - "_Off" . Length ) ; 667if ( ! toggleToLayerIndex . ContainsKey ( toggleName )) 668toggleToLayerIndex [ toggleName ] = i ; 669} 670} 671 672// Mapping from attribute touched by animation to the set of toggles 673// which affect it. 674Dictionary < string , HashSet < string >> attributeToToggles = new Dictionary < string , HashSet < string >> () ; 675foreach ( var kvp in toggleAnimations ) { 676string toggleName = kvp . Key ; 677var pair = kvp . Value ; 678if ( pair . on == null ) continue ; 679 680HashSet < string > attributes = new HashSet < string > () ; 681if ( pair . on . meshToggles != null ) { 682foreach ( var mt in pair . on . meshToggles ) { 683string attr = GetMeshToggleAttributeId ( mt . path ) ; 684attributes . Add ( attr ) ; 685} 686} 687if ( pair . on . blendShapes != null ) { 688foreach ( var bs in pair . on . blendShapes ) { 689string attr = GetBlendShapeAttributeId ( bs . path , bs . blendShape ) ; 690attributes . Add ( attr ) ; 691} 692} 693if ( pair . on . shaderToggles != null ) { 694foreach ( var st in pair . on . shaderToggles ) { 695string attr = GetShaderToggleAttributeId ( st . path , st . materialProperty ) ; 696attributes . Add ( attr ) ; 697} 698} 699foreach ( var attr in attributes ) { 700if ( ! attributeToToggles . TryGetValue ( attr , out var set )) { 701set = new HashSet < string > () ; 702attributeToToggles [ attr ] = set ; 703} 704set . Add ( toggleName ) ; 705} 706} 707 708// TODO assert that all toggles affecting the same attribute are on 709// different layers. 710 711List < GeneratedAnimationClipConfig > newAnimations = new List < GeneratedAnimationClipConfig > () ; 712 713AnimatorLayer baseLayer = genAnimatorConfig . layers . FirstOrDefault ( l => l . name == "BaseLayer" ) ; 714if ( baseLayer == null && genAnimatorConfig . layers . Count > 0 ) 715baseLayer = genAnimatorConfig . layers [ 0 ] ; 716 717foreach ( var kvp in toggleAnimations ) { 718string toggleName = kvp . Key ; 719var pair = kvp . Value ; 720int layerIndex = toggleToLayerIndex [ toggleName ] ; 721 722if ( layerIndex == 0 ) { 723newAnimations . Add ( pair . on ) ; 724newAnimations . Add ( pair . off ) ; 725continue ; 726} 727 728// Work out which of the animation's mesh toggles are overrides and 729// which are independent. 730List < GeneratedMeshToggle > independentMesh = new List < GeneratedMeshToggle > () ; 731List < GeneratedMeshToggle > dependentMesh = new List < GeneratedMeshToggle > () ; 732if ( pair . on . meshToggles != null ) { 733foreach ( var mt in pair . on . meshToggles ) { 734string attr = GetMeshToggleAttributeId ( mt . path ) ; 735if ( attributeToToggles [ attr ] . Count == 1 ) 736independentMesh . Add ( mt ) ; 737else 738dependentMesh . Add ( mt ) ; 739} 740} 741 742// Work out which of the animation's blendshapes are overrides and 743// which are independent. 744List < GeneratedBlendShape > independentBlend = new List < GeneratedBlendShape > () ; 745List < GeneratedBlendShape > dependentBlend = new List < GeneratedBlendShape > () ; 746if ( pair . on . blendShapes != null ) { 747foreach ( var bs in pair . on . blendShapes ) { 748string attr = GetBlendShapeAttributeId ( bs . path , bs . blendShape ) ; 749if ( attributeToToggles [ attr ] . Count == 1 ) 750independentBlend . Add ( bs ) ; 751else 752dependentBlend . Add ( bs ) ; 753} 754} 755 756// Work out which of the animation's shader toggles are overrides and which are independent 757List < GeneratedShaderToggle > independentShader = new List < GeneratedShaderToggle > () ; 758List < GeneratedShaderToggle > dependentShader = new List < GeneratedShaderToggle > () ; 759if ( pair . on . shaderToggles != null ) { 760foreach ( var st in pair . on . shaderToggles ) { 761string attr = GetShaderToggleAttributeId ( st . path , st . materialProperty ) ; 762if ( attributeToToggles [ attr ] . Count == 1 ) 763independentShader . Add ( st ) ; 764else 765dependentShader . Add ( st ) ; 766} 767} 768 769bool hasIndependent = ( independentMesh . Count > 0 || independentBlend . Count > 0 || independentShader . Count > 0 ) ; 770bool hasDependent = ( dependentMesh . Count > 0 || dependentBlend . Count > 0 || dependentShader . Count > 0 ) ; 771 772if ( hasIndependent && hasDependent ) { 773GeneratedAnimationClipConfig dependentOn = new GeneratedAnimationClipConfig () ; 774dependentOn . name = toggleName + "_Dependent_On" ; 775dependentOn . meshToggles = dependentMesh ; 776dependentOn . blendShapes = dependentBlend ; 777dependentOn . shaderToggles = dependentShader ; 778 779GeneratedAnimationClipConfig dependentOff = new GeneratedAnimationClipConfig () ; 780dependentOff . name = toggleName + "_Dependent_Off" ; 781dependentOff . meshToggles = dependentMesh 782. Select ( mt => new GeneratedMeshToggle { 783path = mt . path , 784value = GetOffValueForMesh ( mt . path , pair . off . meshToggles ) 785}) 786. ToList () ; 787dependentOff . blendShapes = dependentBlend 788. Select ( bs => new GeneratedBlendShape { 789path = bs . path , 790blendShape = bs . blendShape , 791value = GetOffValueForBlend ( bs . path , bs . blendShape , pair . off . blendShapes ) 792}) 793. ToList () ; 794dependentOff . shaderToggles = dependentShader 795. Select ( st => new GeneratedShaderToggle { 796path = st . path , 797materialProperty = st . materialProperty , 798value = GetOffValueForShader ( st . path , st . materialProperty , pair . off . shaderToggles ) 799}) 800. ToList () ; 801 802GeneratedAnimationClipConfig independentOn = new GeneratedAnimationClipConfig () ; 803independentOn . name = toggleName + "_Independent_On" ; 804independentOn . meshToggles = independentMesh ; 805independentOn . blendShapes = independentBlend ; 806independentOn . shaderToggles = independentShader ; 807 808GeneratedAnimationClipConfig independentOff = new GeneratedAnimationClipConfig () ; 809independentOff . name = toggleName + "_Independent_Off" ; 810independentOff . meshToggles = independentMesh 811. Select ( mt => new GeneratedMeshToggle { 812path = mt . path , 813value = GetOffValueForMesh ( mt . path , pair . off . meshToggles ) 814}) 815. ToList () ; 816independentOff . blendShapes = independentBlend 817. Select ( bs => new GeneratedBlendShape { 818path = bs . path , 819blendShape = bs . blendShape , 820value = GetOffValueForBlend ( bs . path , bs . blendShape , pair . off . blendShapes ) 821}) 822. ToList () ; 823independentOff . shaderToggles = independentShader 824. Select ( st => new GeneratedShaderToggle { 825path = st . path , 826materialProperty = st . materialProperty , 827value = GetOffValueForShader ( st . path , st . materialProperty , pair . off . shaderToggles ) 828}) 829. ToList () ; 830 831newAnimations . Add ( dependentOn ) ; 832newAnimations . Add ( dependentOff ) ; 833newAnimations . Add ( independentOn ) ; 834newAnimations . Add ( independentOff ) ; 835 836AnimatorLayer overrideLayer = genAnimatorConfig . layers [ layerIndex ] ; 837foreach ( var entry in overrideLayer . directBlendTree . entries ) { 838if ( entry . name . StartsWith ( toggleName ) && 839( entry . name . EndsWith ( "_On" ) || entry . name . EndsWith ( "_Off" ))) { 840entry . name = entry . name . EndsWith ( "_On" ) ? toggleName + "_Dependent_On" : toggleName + "_Dependent_Off" ; 841} 842} 843 844if ( baseLayer != null ) { 845baseLayer . directBlendTree . entries . Add ( new AnimatorDirectBlendTreeEntry { 846name = toggleName + "_Independent_On" , 847parameter = toggleName 848}) ; 849baseLayer . directBlendTree . entries . Add ( new AnimatorDirectBlendTreeEntry { 850name = toggleName + "_Independent_Off" , 851parameter = toggleName 852}) ; 853} 854} else if ( hasIndependent ) { 855GeneratedAnimationClipConfig independentOn = new GeneratedAnimationClipConfig () ; 856independentOn . name = toggleName + "_Independent_On" ; 857independentOn . meshToggles = pair . on . meshToggles ; 858independentOn . blendShapes = pair . on . blendShapes ; 859independentOn . shaderToggles = pair . on . shaderToggles ; 860GeneratedAnimationClipConfig independentOff = new GeneratedAnimationClipConfig () ; 861independentOff . name = toggleName + "_Independent_Off" ; 862independentOff . meshToggles = pair . off . meshToggles ; 863independentOff . blendShapes = pair . off . blendShapes ; 864independentOff . shaderToggles = pair . off . shaderToggles ; 865 866newAnimations . Add ( independentOn ) ; 867newAnimations . Add ( independentOff ) ; 868 869AnimatorLayer overrideLayer = genAnimatorConfig . layers [ layerIndex ] ; 870overrideLayer . directBlendTree . entries . RemoveAll ( e => e . name . StartsWith ( toggleName )) ; 871if ( baseLayer != null ) { 872baseLayer . directBlendTree . entries . Add ( new AnimatorDirectBlendTreeEntry { 873name = toggleName + "_Independent_On" , 874parameter = toggleName 875}) ; 876baseLayer . directBlendTree . entries . Add ( new AnimatorDirectBlendTreeEntry { 877name = toggleName + "_Independent_Off" , 878parameter = toggleName 879}) ; 880} 881} else if ( hasDependent ) { 882GeneratedAnimationClipConfig dependentOn = new GeneratedAnimationClipConfig () ; 883dependentOn . name = toggleName + "_Dependent_On" ; 884dependentOn . meshToggles = pair . on . meshToggles ; 885dependentOn . blendShapes = pair . on . blendShapes ; 886dependentOn . shaderToggles = pair . on . shaderToggles ; 887GeneratedAnimationClipConfig dependentOff = new GeneratedAnimationClipConfig () ; 888dependentOff . name = toggleName + "_Dependent_Off" ; 889dependentOff . meshToggles = pair . off . meshToggles ; 890dependentOff . blendShapes = pair . off . blendShapes ; 891dependentOff . shaderToggles = pair . off . shaderToggles ; 892 893newAnimations . Add ( dependentOn ) ; 894newAnimations . Add ( dependentOff ) ; 895 896AnimatorLayer overrideLayer = genAnimatorConfig . layers [ layerIndex ] ; 897foreach ( var entry in overrideLayer . directBlendTree . entries ) { 898if ( entry . name . StartsWith ( toggleName ) && 899( entry . name . EndsWith ( "_On" ) || entry . name . EndsWith ( "_Off" ))) { 900entry . name = entry . name . EndsWith ( "_On" ) ? toggleName + "_Dependent_On" : toggleName + "_Dependent_Off" ; 901} 902} 903} else { 904throw new ArgumentException ( $"Toggle { toggleName } seems to have no animations." ) ; 905} 906} 907 908genAnimatorConfig . animations = newAnimations ; 909return genAnimatorConfig ; 910} 911 912private static GeneratedAnimatorConfig 913RemoveOffAnimationsFromOverrideLayers ( GeneratedAnimatorConfig config ) { 914for ( int i = 1 ; i < config . layers . Count ; i ++ ) { 915var layer = config . layers [ i ] ; 916layer . directBlendTree . entries . RemoveAll ( entry => entry . name . EndsWith ( "_Off" )) ; 917} 918return config ; 919} 920 921private static GeneratedAnimatorConfig 922RemoveUnusedAnimations ( GeneratedAnimatorConfig config ) { 923HashSet < string > referencedAnimations = new HashSet < string > () ; 924foreach ( var layer in config . layers ) { 925foreach ( var entry in layer . directBlendTree . entries ) 926referencedAnimations . Add ( entry . name ) ; 927} 928 929config . animations = config . animations 930. Where ( anim => referencedAnimations . Contains ( anim . name )) 931. ToList () ; 932 933return config ; 934} 935 936private static VRCExpressionsMenu GetOrCreateSubmenu ( 937VRCExpressionsMenu parentMenu , 938string submenuName ) { 939// Check if submenu already exists 940foreach ( var control in parentMenu . controls ) { 941if ( control . type == VRCExpressionsMenu . Control . ControlType . SubMenu && 942control . name == submenuName && control . subMenu != null ) { 943return control . subMenu ; 944} 945} 946 947// Create new submenu 948var newSubmenu = ScriptableObject . CreateInstance < VRCExpressionsMenu > () ; 949newSubmenu . name = submenuName ; 950newSubmenu . controls = new List < VRCExpressionsMenu . Control > () ; 951 952var newControl = new VRCExpressionsMenu . Control { 953name = submenuName , 954type = VRCExpressionsMenu . Control . ControlType . SubMenu , 955subMenu = newSubmenu 956} ; 957parentMenu . controls . Add ( newControl ) ; 958 959return newSubmenu ; 960} 961 962private static void GenerateVRChatAssets ( 963List < ToggleSpec > toggleSpecs , 964VRCExpressionParameters vrcParams , 965VRCExpressionsMenu vrcMenu 966) { 967var uniqueToggles = toggleSpecs 968. Where ( t => t . name != "YOTS_Weight" ) 969. GroupBy ( t => t . name ) 970. Select ( g => g . First ()) 971. ToList () ; 972 973// Update parameters 974var paramList = new List < VRCExpressionParameters . Parameter > () ; 975paramList . AddRange ( vrcParams . parameters . Where ( p => ! uniqueToggles . Any ( t => t . name == p . name ))) ; 976foreach ( var toggle in uniqueToggles ) { 977paramList . Add ( new VRCExpressionParameters . Parameter { 978name = toggle . name , 979valueType = toggle . type == "radial" ? VRCExpressionParameters . ValueType . Float : VRCExpressionParameters . ValueType . Bool , 980defaultValue = toggle . defaultValue , 981saved = toggle . saved , 982networkSynced = toggle . synced 983}) ; 984} 985vrcParams . parameters = paramList . ToArray () ; 986 987// Add toggles to menu (skipping those with disableMenuEntry=true) 988foreach ( var toggle in toggleSpecs ) { 989// Skip creating menu entries for toggles with disableMenuEntry=true 990if ( toggle . disableMenuEntry ) 991continue ; 992 993VRCExpressionsMenu currentMenu = vrcMenu ; 994 995// Navigate or create menu path if specified 996if ( ! string . IsNullOrEmpty ( toggle . menuPath )) { 997string trimmedPath = toggle . menuPath . Trim ( '/' ) ; 998if ( ! string . IsNullOrEmpty ( trimmedPath )) { 999var sections = trimmedPath . Split ( '/' ) ; 1000foreach ( var section in sections ) { 1001currentMenu = GetOrCreateSubmenu ( currentMenu , section ) ; 1002} 1003} 1004} 1005 1006// Add toggle control 1007if ( toggle . type == "radial" ) { 1008currentMenu . controls . Add ( new VRCExpressionsMenu . Control { 1009name = toggle . name , 1010type = VRCExpressionsMenu . Control . ControlType . RadialPuppet , 1011subParameters = new VRCExpressionsMenu . Control . Parameter []{ 1012new VRCExpressionsMenu . Control . Parameter { name = toggle . name } 1013} 1014}) ; 1015} else { 1016currentMenu . controls . Add ( new VRCExpressionsMenu . Control { 1017name = toggle . name , 1018type = VRCExpressionsMenu . Control . ControlType . Toggle , 1019parameter = new VRCExpressionsMenu . Control . Parameter { name = toggle . name } , 1020value = 1f 1021}) ; 1022} 1023} 1024} 1025} 1026} 1027 1028#endif // UNITY_EDITOR