summaryrefslogtreecommitdiff
path: root/VRCSDK3AvatarsQuestLegacy/Assets/VRCSDK/SDK3A/Editor/Components3/VRCAvatarDescriptorEditor3EyeLook.cs
blob: b3a7479a476219ced32cd120f2a6ad4f1193e8d9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
#if VRC_SDK_VRCSDK3
using UnityEngine;
using UnityEditor;
using UnityEditorInternal;
using System.Collections.Generic;
using VRC.SDK3.Avatars.Components;
using System;
using System.Linq;


public partial class AvatarDescriptorEditor3 : Editor
{
    static string _eyeLookFoldoutPrefsKey = "VRCSDK3_AvatarDescriptorEditor3_EyeLookFoldout";
    static string _eyeMovementFoldoutPrefsKey = "VRCSDK3_AvatarDescriptorEditor3_EyeLookFoldout_Movement";
    static string _eyeTransformFoldoutPrefsKey = "VRCSDK3_AvatarDescriptorEditor3_EyeTransformFoldout";
    static string _eyeRotationFoldoutPrefsKey = "VRCSDK3_AvatarDescriptorEditor3_EyeRotationFoldout";
    static string _eyelidTransformFoldoutPrefsKey = "VRCSDK3_AvatarDescriptorEditor3_EyelidTransformFoldout";
    static string _eyelidRotationFoldoutPrefsKey = "VRCSDK3_AvatarDescriptorEditor3_EyelidRotationFoldout";
    static string _eyelidBlendshapesFoldoutPrefsKey = "VRCSDK3_AvatarDescriptorEditor3_EyeLookFoldout_EyelidBlendshapes";

    static string _linkEyelidsDialog = "Link Left + Right for '{0}'?\n(using values of: {1})";

    static string _activeProperty = null;
    static Color _activeButtonColor = new Color(0.5f, 1, 0.5f, 1);

    SkinnedMeshRenderer _currentEyelidsMesh;
    string[] _eyelidBlendshapeNames;

    static Texture _linkIcon;

    static List<System.Action> activePropertyRestore = new List<System.Action>();

    void InitEyeLook()
    {
        if (_linkIcon == null)
            _linkIcon = Resources.Load<Texture>("EditorUI_Icons/EditorUI_Link");

        EditorPrefs.SetBool(_eyeTransformFoldoutPrefsKey, true);
        EditorPrefs.SetBool(_eyelidTransformFoldoutPrefsKey, true);
    }

    void DrawEyeLook()
    {
        if (Foldout(_eyeLookFoldoutPrefsKey, "Eye Look"))
        {
            SerializedProperty p = serializedObject.FindProperty("enableEyeLook");

            bool toggle = GUILayout.Button(p.boolValue ? "Disable" : "Enable");

            if (toggle)
                p.boolValue = !p.boolValue;

            if (p.boolValue)
            {
                var eyeSettings = serializedObject.FindProperty("customEyeLookSettings");

                EditorGUILayout.BeginVertical();

                DrawEyesGeneralBox(eyeSettings);
                DrawEyesBox(eyeSettings);
                DrawEyelidsBox(eyeSettings);

                EditorGUILayout.EndVertical();
            }

            Separator();
        }
    }

    static void DrawEyesGeneralBox(SerializedProperty eyeSettings)
    {

        BeginBox("General", true);

        if (Foldout(_eyeMovementFoldoutPrefsKey, "Eye Movements"))
        {
            var eyeMovement = eyeSettings.FindPropertyRelative("eyeMovement");
            var confidence = eyeMovement.FindPropertyRelative("confidence");
            var excitement = eyeMovement.FindPropertyRelative("excitement");

            EyeLookMovementSlider(excitement, "Calm", "Excited");
            EyeLookMovementSlider(confidence, "Shy", "Confident");
        }

        EndBox();
    }

    void DrawEyesBox(SerializedProperty eyeSettings)
    {
        BeginBox("Eyes", true);

        var leftEye = eyeSettings.FindPropertyRelative("leftEye");
        var rightEye = eyeSettings.FindPropertyRelative("rightEye");

        if (Foldout(_eyeTransformFoldoutPrefsKey, "Transforms", true))
        {
            EditorGUI.BeginChangeCheck();
            EditorGUILayout.PropertyField(leftEye, new GUIContent("Left Eye Bone"));
            EditorGUILayout.PropertyField(rightEye, new GUIContent("Right Eye Bone"));
            if(EditorGUI.EndChangeCheck())
                SetActiveProperty(null); //Disable active property, maintains proper preview/undo state
        }
        Separator();

        EditorGUI.BeginDisabledGroup(leftEye.objectReferenceValue == null || rightEye.objectReferenceValue == null);
        if (Foldout(_eyeRotationFoldoutPrefsKey, "Rotation States"))
        {
            var eyesLookingStraight = eyeSettings.FindPropertyRelative("eyesLookingStraight");
            var eyesLookingUp = eyeSettings.FindPropertyRelative("eyesLookingUp");
            var eyesLookingDown = eyeSettings.FindPropertyRelative("eyesLookingDown");
            var eyesLookingLeft = eyeSettings.FindPropertyRelative("eyesLookingLeft");
            var eyesLookingRight = eyeSettings.FindPropertyRelative("eyesLookingRight");

            RotationFieldEyeLook(eyesLookingStraight, leftEye, rightEye, "Looking Straight");
            RotationFieldEyeLook(eyesLookingUp, leftEye, rightEye, "Looking Up", () => { BeginEyesUpDown(true); });
            RotationFieldEyeLook(eyesLookingDown, leftEye, rightEye, "Looking Down", () => { BeginEyesUpDown(false); });
            RotationFieldEyeLook(eyesLookingLeft, leftEye, rightEye, "Looking Left");
            RotationFieldEyeLook(eyesLookingRight, leftEye, rightEye, "Looking Right");
        }
        EditorGUI.EndDisabledGroup();

        EndBox();
    }
    void RotationFieldEyeLook(SerializedProperty property, SerializedProperty leftEyeBone, SerializedProperty rightEyeBone, string label, System.Action onSetActive=null)
    {
        RotationField(property, leftEyeBone, rightEyeBone, label, isActive: IsActiveProperty(property), SetActive: SetActive);
        void SetActive()
        {
            //Set
            SetActiveProperty(property);

            //Check for transforms
            if (((Transform)leftEyeBone.objectReferenceValue) == null || ((Transform)rightEyeBone.objectReferenceValue) == null)
                return;

            //Record
            RecordEyeRotations(property, leftEyeBone, rightEyeBone);

            //Other
            onSetActive?.Invoke();
        }
    }

    void DrawEyelidsBox(SerializedProperty eyeSettings)
    {
        BeginBox("Eyelids", true);

        DrawEyelidType(eyeSettings);

        if (avatarDescriptor.customEyeLookSettings.eyelidType == VRCAvatarDescriptor.EyelidType.Blendshapes)
        {
            DrawEyelidBlendshapeDropdowns(eyeSettings);
        }
        else if (avatarDescriptor.customEyeLookSettings.eyelidType == VRCAvatarDescriptor.EyelidType.Bones) 
        {
            DrawEyelidBoneRotations(eyeSettings);
            _currentEyelidsMesh = null;
        }
        else
        {
            _currentEyelidsMesh = null;
        }

        EndBox();
    }
    void DrawEyelidType(SerializedProperty eyeSettings)
    {
        EditorGUI.BeginChangeCheck();
        var eyelidType = eyeSettings.FindPropertyRelative("eyelidType");
        EditorGUILayout.PropertyField(eyelidType);
        if (EditorGUI.EndChangeCheck())
        {
            if (eyelidType.enumValueIndex == (int)VRCAvatarDescriptor.EyelidType.Blendshapes)
                EditorPrefs.SetBool(_eyelidBlendshapesFoldoutPrefsKey, true);
        }
    }
    void DrawEyelidBoneRotations(SerializedProperty eyeSettings)
    {
        Separator();

        var upperLeftEyelid = eyeSettings.FindPropertyRelative("upperLeftEyelid");
        var upperRightEyelid = eyeSettings.FindPropertyRelative("upperRightEyelid");
        var lowerLeftEyelid = eyeSettings.FindPropertyRelative("lowerLeftEyelid");
        var lowerRightEyelid = eyeSettings.FindPropertyRelative("lowerRightEyelid");

        if (Foldout(_eyelidTransformFoldoutPrefsKey, "Transforms", true))
        {
            EditorGUI.BeginChangeCheck();
            EditorGUILayout.PropertyField(upperLeftEyelid);
            EditorGUILayout.PropertyField(upperRightEyelid);
            EditorGUILayout.PropertyField(lowerLeftEyelid);
            EditorGUILayout.PropertyField(lowerRightEyelid);
            if (EditorGUI.EndChangeCheck())
                SetActiveProperty(null); //Disable active property, maintains proper preview/undo state
        }
        Separator();
        if (Foldout(_eyelidRotationFoldoutPrefsKey, "Rotation States"))
        {
            var eyelidsDefault = eyeSettings.FindPropertyRelative("eyelidsDefault");
            var eyelidsClosed = eyeSettings.FindPropertyRelative("eyelidsClosed");
            var eyelidsLookingUp = eyeSettings.FindPropertyRelative("eyelidsLookingUp");
            var eyelidsLookingDown = eyeSettings.FindPropertyRelative("eyelidsLookingDown");

            GUILayout.BeginHorizontal();
            GUILayout.Space(16);
            GUILayout.BeginVertical();
            RotationFieldEyelids(eyelidsDefault, upperLeftEyelid, upperRightEyelid, lowerLeftEyelid, lowerRightEyelid, "Default");
            RotationFieldEyelids(eyelidsClosed, upperLeftEyelid, upperRightEyelid, lowerLeftEyelid, lowerRightEyelid, "Closed");
            RotationFieldEyelids(eyelidsLookingUp, upperLeftEyelid, upperRightEyelid, lowerLeftEyelid, lowerRightEyelid, "Looking Up", () => { BeginEyesUpDown(true); } );
            RotationFieldEyelids(eyelidsLookingDown, upperLeftEyelid, upperRightEyelid, lowerLeftEyelid, lowerRightEyelid, "Looking Down", () => { BeginEyesUpDown(false); });

            GUILayout.EndVertical();
            GUILayout.EndHorizontal();
        }
    }
    void RotationFieldEyelids(SerializedProperty property,
        SerializedProperty upperLeftBone, SerializedProperty upperRightBone,
        SerializedProperty lowerLeftBone, SerializedProperty lowerRightBone,
        string label = null,
        System.Action onSetActive=null)
    {
        var upperProperty = property.FindPropertyRelative("upper");
        var lowerProperty = property.FindPropertyRelative("lower");
        GUILayout.BeginHorizontal();
        if (EditorGUILayout.PropertyField(property, new GUIContent(label), GUILayout.MinWidth(100)))
        {
            Button();
            GUILayout.EndHorizontal();
            GUILayout.BeginVertical();

            RotationField(upperProperty, upperLeftBone, upperRightBone, "Upper Eyelids", showButton:false, isActive:IsActiveProperty(property), SetActive:SetActive);
            RotationField(lowerProperty, lowerLeftBone, lowerRightBone, "Lower Eyelids", showButton:false, isActive:IsActiveProperty(property), SetActive:SetActive);
            GUILayout.EndVertical();
        }
        else
        {
            Button();
            GUILayout.EndHorizontal();
        }

        void SetActive()
        {
            SetActiveProperty(property);

            //Record
            RecordEyeRotations(upperProperty, upperLeftBone, upperRightBone);
            RecordEyeRotations(lowerProperty, lowerLeftBone, lowerRightBone);

            //Other
            onSetActive?.Invoke();
        }

        void Button()
        {
            bool isActiveProperty = IsActiveProperty(property);
            GUI.backgroundColor = isActiveProperty ? _activeButtonColor : Color.white;
            if (GUILayout.Button(isActiveProperty ? "Return" : "Preview", EditorStyles.miniButton, GUILayout.MaxWidth(PreviewButtonWidth), GUILayout.Height(PreviewButtonHeight)))
            {
                if(isActiveProperty)
                {
                    SetActiveProperty(null);
                }
                else
                {
                    SetActive();
                }
            }
            GUI.backgroundColor = Color.white;
        }
    }
    void DrawEyelidBlendshapeDropdowns(SerializedProperty eyeSettings)
    {
        Separator();

        var eyelidsMeshProp = eyeSettings.FindPropertyRelative("eyelidsSkinnedMesh");
        eyelidsMeshProp.objectReferenceValue = (SkinnedMeshRenderer)EditorGUILayout.ObjectField("Eyelids Mesh", eyelidsMeshProp.objectReferenceValue, typeof(SkinnedMeshRenderer), true);

        if (eyelidsMeshProp.objectReferenceValue == null)
        {
            _eyelidBlendshapeNames = null;
            return;
        }

        if (_currentEyelidsMesh == null)
        {
            _currentEyelidsMesh = (SkinnedMeshRenderer)eyelidsMeshProp.objectReferenceValue;
            _eyelidBlendshapeNames = GetBlendShapeNames(_currentEyelidsMesh);
        }

        var eyelidsBlendshapes = eyeSettings.FindPropertyRelative("eyelidsBlendshapes");

        if (Foldout(_eyelidBlendshapesFoldoutPrefsKey, "Blendshape States"))
        {

            if (eyelidsBlendshapes.arraySize != 3)
                eyelidsBlendshapes.arraySize = 3;
            int[] indices = new int[] { eyelidsBlendshapes.GetArrayElementAtIndex(0).intValue,
                                        eyelidsBlendshapes.GetArrayElementAtIndex(1).intValue,
                                        eyelidsBlendshapes.GetArrayElementAtIndex(2).intValue};

            PreviewBlendshapeField("Blink", 0, eyelidsBlendshapes.GetArrayElementAtIndex(0));
            PreviewBlendshapeField("Looking Up", 1, eyelidsBlendshapes.GetArrayElementAtIndex(1), () => { BeginEyesUpDown(true); });
            PreviewBlendshapeField("Looking Down", 2, eyelidsBlendshapes.GetArrayElementAtIndex(2), () => { BeginEyesUpDown(false); });
        }
    }

    /*static float NormalizedDegAngle ( float degrees )
    {
        int factor = (int) (degrees/360);
        degrees -= factor * 360;
        if ( degrees > 180 )
            return degrees - 360;

        if ( degrees < -180 )
            return degrees + 360;

        return degrees;
    }
    static Vector3 NormalizedEulers(Vector3 eulers)
    {
        Vector3 normEulers;
        normEulers.x = NormalizedDegAngle(eulers.x);
        normEulers.y = NormalizedDegAngle(eulers.y);
        normEulers.z = NormalizedDegAngle(eulers.z);

        return normEulers;
    }*/
    static int PreviewButtonWidth = 55;
    static int PreviewButtonHeight = 24;

    static void RecordEyeRotations(SerializedProperty property, SerializedProperty leftEyeBone, SerializedProperty rightEyeBone)
    {
        //Record restore point
        var transformL = (Transform)leftEyeBone.objectReferenceValue;
        var transformR = (Transform)rightEyeBone.objectReferenceValue;
        var prevRotationL = transformL != null ? transformL.localRotation : Quaternion.identity;
        var prevRotationR = transformR != null ? transformR.localRotation : Quaternion.identity;
        System.Action restore = () =>
        {
            if (transformL != null)
                transformL.localRotation = prevRotationL;
            if (transformR != null)
                transformR.localRotation = prevRotationR;
        };
        activePropertyRestore.Add(restore);

        //Set to value
        var leftRotation = property.FindPropertyRelative("left");
        var rightRotation = property.FindPropertyRelative("right");
        if(transformL != null)
            transformL.localRotation = leftRotation.quaternionValue;
        if (transformR != null)
            transformR.localRotation = rightRotation.quaternionValue;
    }
    void BeginEyesUpDown(bool isUp)
    {
        var eyeSettings = serializedObject.FindProperty("customEyeLookSettings");

        //Record - Eye Up
        {
            var eyesLooking = eyeSettings.FindPropertyRelative(isUp ? "eyesLookingUp" : "eyesLookingDown");
            var leftEye = eyeSettings.FindPropertyRelative("leftEye");
            var rightEye = eyeSettings.FindPropertyRelative("rightEye");
            RecordEyeRotations(eyesLooking, leftEye, rightEye);
        }

        //Record - Eyelid Up Bones
        if (avatarDescriptor.customEyeLookSettings.eyelidType == VRCAvatarDescriptor.EyelidType.Bones)
        {
            var upperLeftEyelid = eyeSettings.FindPropertyRelative("upperLeftEyelid");
            var upperRightEyelid = eyeSettings.FindPropertyRelative("upperRightEyelid");
            var lowerLeftEyelid = eyeSettings.FindPropertyRelative("lowerLeftEyelid");
            var lowerRightEyelid = eyeSettings.FindPropertyRelative("lowerRightEyelid");

            var eyelidsLooking = eyeSettings.FindPropertyRelative(isUp ? "eyelidsLookingUp" : "eyelidsLookingDown");
            var upperProperty = eyelidsLooking.FindPropertyRelative("upper");
            var lowerProperty = eyelidsLooking.FindPropertyRelative("lower");

            RecordEyeRotations(upperProperty, upperLeftEyelid, upperRightEyelid);
            RecordEyeRotations(lowerProperty, lowerLeftEyelid, lowerRightEyelid);
        }

        //Record - Eyelid Blendshapes
        if (avatarDescriptor.customEyeLookSettings.eyelidType == VRCAvatarDescriptor.EyelidType.Blendshapes)
        {
            var eyelidsBlendshapes = eyeSettings.FindPropertyRelative("eyelidsBlendshapes");
            var blendshapeIndex = eyelidsBlendshapes.GetArrayElementAtIndex(isUp ? 1 : 2);

            RecordBlendShape(blendshapeIndex.intValue);
        }
    }

    static Vector3 EditorQuaternionToVector3(Quaternion value)
    {
        var result = value.eulerAngles;

        //Fix the axis flipping
        if(Mathf.Approximately(value.eulerAngles.y, 180) && Mathf.Approximately(value.eulerAngles.z, 180))
        {
            if (result.x < 90.0f)
                result.x = 90f + (90f - result.x);
            else
                result.x = 270f + (270f - result.x);
            result.y = 0;
            result.z = 0;
        }

        //Represent angle as -180 to 180
        if (result.x > 180.0f)
            result.x = -(360f-result.x);
        if (result.y > 180.0f)
            result.y = -(360f - result.y);
        if (result.z > 180.0f)
            result.z = -(360f - result.z);

        //Prevent small number in editor, they arn't nessecary here
        if (result.x < 0.001f && result.x > -0.001f)
            result.x = 0f;
        if (result.y < 0.001f && result.y > -0.001f)
            result.y = 0f;
        if (result.z < 0.001f && result.z > -0.001f)
            result.z = 0f;

        //Return
        return result;
    }
    static bool RotationField(SerializedProperty property, SerializedProperty leftEyeBone, SerializedProperty rightEyeBone, string label = null, bool showButton = true, bool isActive=false, System.Action SetActive=null)
    {
        bool dirty = false;

        EditorGUI.BeginChangeCheck();
        GUILayout.BeginHorizontal();
        var leftRotation = property.FindPropertyRelative("left");
        var rightRotation = property.FindPropertyRelative("right");
        var linked = property.FindPropertyRelative("linked");
        GUILayout.BeginVertical();
        label = string.IsNullOrEmpty(label) ? property.displayName : label;
        if (GUILayout.Button(label, EditorStyles.label))
            dirty = true;
        if (linked.boolValue)
        {
            GUILayout.BeginHorizontal();
            {
                //Link button
                GUI.color = GUI.skin.label.normal.textColor;
                if (GUILayout.Button(new GUIContent(_linkIcon), GUI.skin.label, GUILayout.MaxWidth(16)))
                    linked.boolValue = false;
                GUI.color = Color.white;

                var testA1 = Quaternion.Euler(new Vector3(20, 0, 0)).eulerAngles;
                var testA2 = Quaternion.Euler(new Vector3(45, 0, 0)).eulerAngles;
                var testA3 = Quaternion.Euler(new Vector3(90, 0, 0)).eulerAngles;
                var testA4 = Quaternion.Euler(new Vector3(95, 0, 0)).eulerAngles;
                var testA5 = Quaternion.Euler(new Vector3(120, 0, 0)).eulerAngles;

                var testB1 = EditorQuaternionToVector3(Quaternion.Euler(new Vector3(20, 0, 0)));
                var testB2 = EditorQuaternionToVector3(Quaternion.Euler(new Vector3(45, 0, 0)));
                var testB3 = EditorQuaternionToVector3(Quaternion.Euler(new Vector3(90, 0, 0)));
                var testB4 = EditorQuaternionToVector3(Quaternion.Euler(new Vector3(95, 0, 0)));
                var testB5 = EditorQuaternionToVector3(Quaternion.Euler(new Vector3(120, 0, 0)));

                //Values
                //leftRotation.quaternionValue = EditorGUILayout.Vector3Field(GUIContent.none, QuaternionToVector3(leftRotation.quaternionValue), GUILayout.MinWidth(100)));
                leftRotation.quaternionValue =  Quaternion.Euler( EditorGUILayout.Vector3Field(GUIContent.none, EditorQuaternionToVector3(leftRotation.quaternionValue), GUILayout.MinWidth(100)) );
                rightRotation.quaternionValue = leftRotation.quaternionValue;
            }
            GUILayout.EndHorizontal();
        }
        else
        {
            GUIStyle style = new GUIStyle(EditorStyles.boldLabel);
            style.contentOffset = new Vector2(0, -4);

            GUILayout.BeginHorizontal();
            if (GUILayout.Button("L", style, GUILayout.MaxHeight(16)))
            {
                string message = string.Format(_linkEyelidsDialog, label, "L");
                if ((rightRotation.quaternionValue == leftRotation.quaternionValue)
                    || EditorUtility.DisplayDialog("Collapse?", message, "Yes", "No"))
                {
                    linked.boolValue = true;
                    rightRotation.quaternionValue = leftRotation.quaternionValue;
                }
            }
            leftRotation.quaternionValue = Quaternion.Euler(EditorGUILayout.Vector3Field(GUIContent.none, EditorQuaternionToVector3(leftRotation.quaternionValue), GUILayout.MinWidth(100)));
            GUILayout.EndHorizontal();
            GUILayout.BeginHorizontal();
            if (GUILayout.Button("R", style, GUILayout.MaxHeight(16)))
            {
                string message = string.Format(_linkEyelidsDialog, label, "R");
                if ((leftRotation.quaternionValue == rightRotation.quaternionValue)
                    || (EditorUtility.DisplayDialog("Collapse?", message, "Yes", "No")))
                {
                    linked.boolValue = true;
                    leftRotation.quaternionValue = rightRotation.quaternionValue;
                }
            }
            rightRotation.quaternionValue = Quaternion.Euler(EditorGUILayout.Vector3Field(GUIContent.none, EditorQuaternionToVector3(rightRotation.quaternionValue), GUILayout.MinWidth(100)));
            GUILayout.EndHorizontal();
        }
        GUILayout.EndVertical();
        GUILayout.FlexibleSpace();
        GUILayout.BeginVertical();
        bool changed = EditorGUI.EndChangeCheck();

        //Edit button
        if (showButton)
        {
            GUI.backgroundColor = (isActive ? _activeButtonColor : Color.white);
            GUILayout.BeginVertical();
            GUILayout.Space(linked.boolValue ? 4 : 20);
            if (GUILayout.Button(isActive ? "Return" : "Preview", EditorStyles.miniButton, GUILayout.Width(PreviewButtonWidth), GUILayout.Height(PreviewButtonHeight)))
            {
                if (isActive)
                {
                    SetActiveProperty(null);
                    isActive = false;
                }
                else
                {
                    SetActive();
                    isActive = true;
                }
                dirty = _repaint = true;
            }
            GUILayout.EndVertical();
            GUI.backgroundColor = Color.white;
        }

        GUILayout.EndVertical();
        GUILayout.EndHorizontal();

        //Mark active if changed
        if(changed)
        {
            //Set active if not already
            if (!isActive)
            {
                SetActive();
                isActive = true;
            }

            //Mark dirty
            dirty = _repaint = true;
        }

        //Update values, always update if active not only on change.
        //We do this because the user may change values with a control-z/undo operation
        if (isActive)
        {
            //Left
            var leftEyeTransform = (Transform)leftEyeBone.objectReferenceValue;
            if (leftEyeTransform != null)
                leftEyeTransform.localRotation = leftRotation.quaternionValue;

            //Right
            var rightEyeTransform = (Transform)rightEyeBone.objectReferenceValue;
            if (rightEyeTransform != null)
                rightEyeTransform.localRotation = rightRotation.quaternionValue;
        }

        //Return
        return dirty;
    }

    void PreviewBlendshapeField(string label, int buttonIndex, SerializedProperty blendShapeIndex, System.Action onSetActive=null)
    {
        if (_eyelidBlendshapeNames == null)
            return;

        bool setActive = false;
        GUILayout.BeginHorizontal();
        {
            //Dropdown
            EditorGUI.BeginChangeCheck();
            blendShapeIndex.intValue = EditorGUILayout.Popup(label, blendShapeIndex.intValue + 1, _eyelidBlendshapeNames) - 1;
            if (EditorGUI.EndChangeCheck())
            {
                SetActiveProperty(null);
                setActive = true;
            }   

            //Preview
            bool isActiveProperty = IsActiveProperty(blendShapeIndex);
            GUI.backgroundColor = isActiveProperty ? _activeButtonColor : Color.white;
            if (GUILayout.Button(isActiveProperty ? "Return" : "Preview", EditorStyles.miniButton, GUILayout.MaxWidth(PreviewButtonWidth)) || setActive)
            {
                if (isActiveProperty)
                {
                    SetActiveProperty(null);
                }
                else
                {
                    onSetActive?.Invoke();
                    SetActiveProperty(blendShapeIndex);

                    //Record
                    RecordBlendShape(blendShapeIndex.intValue);

                    //Other
                    onSetActive?.Invoke();
                }
            }
            GUI.backgroundColor = Color.white;
        }
        GUILayout.EndHorizontal();
    }
    void RecordBlendShape(int index, float newWeight = 100.0f)
    {
        //Validate
        if (avatarDescriptor.customEyeLookSettings.eyelidsSkinnedMesh == null || index < 0 || index >= avatarDescriptor.customEyeLookSettings.eyelidsSkinnedMesh.sharedMesh.blendShapeCount)
            return;

        //Record old position
        int oldIndex = index;
        float oldWeight = avatarDescriptor.customEyeLookSettings.eyelidsSkinnedMesh.GetBlendShapeWeight(index);
        System.Action restore = () =>
        {
            avatarDescriptor.customEyeLookSettings.eyelidsSkinnedMesh.SetBlendShapeWeight(oldIndex, oldWeight);
        };
        activePropertyRestore.Add(restore);

        //Set new weight
        avatarDescriptor.customEyeLookSettings.eyelidsSkinnedMesh.SetBlendShapeWeight(index, newWeight);
    }

    void ResetBlendshapes(int[] indices)
    {
        for (int v = 0; v < indices.Length; v++)
        {
            if (indices[v] < 0) continue;
            avatarDescriptor.customEyeLookSettings.eyelidsSkinnedMesh.SetBlendShapeWeight(indices[v], 0);
        }
    }

    static void EyeLookMovementSlider(SerializedProperty property, string minLabel, string maxLabel)
    {

        GUIStyle style = new GUIStyle(EditorStyles.miniLabel);
        style.alignment = TextAnchor.MiddleRight;
        style.padding.left = 10;
        style.padding.right = 10;

        GUILayout.BeginHorizontal();

        GUILayout.Label(GUIContent.none);
        Rect r = GUILayoutUtility.GetLastRect();

        // left word
        float leftLabelWidth = r.width * 0.2f;
        float rightLabelWidth = r.width * 0.3f;
        float sliderWidth = r.width * 0.5f;
        r.width = leftLabelWidth;
        GUI.Label(r, minLabel, style);
        r.x += r.width;

        // slider
        r.width = sliderWidth;
        property.floatValue = GUI.HorizontalSlider(r, property.floatValue, 0f, 1f);
        property.floatValue = Mathf.Round(property.floatValue * 10) * 0.1f;
        r.x += r.width;

        // right word
        r.width = rightLabelWidth;
        style.alignment = TextAnchor.MiddleLeft;
        GUI.Label(r, maxLabel, style);

        GUILayout.EndHorizontal();
    }

    static bool IsActiveProperty(SerializedProperty property)
    {
        return (_activeProperty != null) && _activeProperty.Equals(property.propertyPath, System.StringComparison.Ordinal);
    }
    static void SetActiveProperty(SerializedProperty property)
    {
        if (_activeProperty == property?.propertyPath)
            return;

        //Set
        _activeProperty = (property?.propertyPath);

        //Restore previous state
        activePropertyRestore.Reverse(); //Iterate from last to first
        foreach (var restore in activePropertyRestore)
            restore();
        activePropertyRestore.Clear();

        //Redraw
        _repaint = true;
    }

    public static string[] GetBlendShapeNames(SkinnedMeshRenderer skinnedMeshRenderer)
    {
        if (!skinnedMeshRenderer)
            return null;
        string[] names = new string[skinnedMeshRenderer.sharedMesh.blendShapeCount+1];
        names[0] = "-none-";
        for (int v = 0; v < skinnedMeshRenderer.sharedMesh.blendShapeCount; v++)
        {
            names[v+1] = skinnedMeshRenderer.sharedMesh.GetBlendShapeName(v);
        }
        return names;
    }

    void DrawSceneViewpoint()
    {
        var viewPosition = serializedObject.FindProperty("ViewPosition");
        if(IsActiveProperty(viewPosition))
        {
            viewPosition.vector3Value = Handles.PositionHandle(viewPosition.vector3Value, Quaternion.identity);
        }
    }

    void DrawSceneEyeLook()
    {
        var eyeSettings = serializedObject.FindProperty("customEyeLookSettings");
        var leftEye = eyeSettings.FindPropertyRelative("leftEye");
        var rightEye = eyeSettings.FindPropertyRelative("rightEye");

        //Eye Rotation State
        DrawSceneEyes(eyeSettings.FindPropertyRelative("eyesLookingStraight"), leftEye, rightEye);
        DrawSceneEyes(eyeSettings.FindPropertyRelative("eyesLookingUp"), leftEye, rightEye);
        DrawSceneEyes(eyeSettings.FindPropertyRelative("eyesLookingDown"), leftEye, rightEye);
        DrawSceneEyes(eyeSettings.FindPropertyRelative("eyesLookingLeft"), leftEye, rightEye);
        DrawSceneEyes(eyeSettings.FindPropertyRelative("eyesLookingRight"), leftEye, rightEye);

        //Eyelid Rotation States
        if(avatarDescriptor.customEyeLookSettings.eyelidType == VRCAvatarDescriptor.EyelidType.Bones)
        {
            var upperLeftEyelid = eyeSettings.FindPropertyRelative("upperLeftEyelid");
            var upperRightEyelid = eyeSettings.FindPropertyRelative("upperRightEyelid");
            var lowerLeftEyelid = eyeSettings.FindPropertyRelative("lowerLeftEyelid");
            var lowerRightEyelid = eyeSettings.FindPropertyRelative("lowerRightEyelid");

            DrawSceneEyelids(eyeSettings.FindPropertyRelative("eyelidsDefault"), upperLeftEyelid, upperRightEyelid, lowerLeftEyelid, lowerRightEyelid);
            DrawSceneEyelids(eyeSettings.FindPropertyRelative("eyelidsClosed"), upperLeftEyelid, upperRightEyelid, lowerLeftEyelid, lowerRightEyelid);
            DrawSceneEyelids(eyeSettings.FindPropertyRelative("eyelidsLookingUp"), upperLeftEyelid, upperRightEyelid, lowerLeftEyelid, lowerRightEyelid);
            DrawSceneEyelids(eyeSettings.FindPropertyRelative("eyelidsLookingDown"), upperLeftEyelid, upperRightEyelid, lowerLeftEyelid, lowerRightEyelid);
        }
    }
    void DrawSceneEyes(SerializedProperty property, SerializedProperty leftEye, SerializedProperty rightEye, bool checkActive=true)
    {
        if (checkActive && !IsActiveProperty(property))
            return;

        var leftRotation = property.FindPropertyRelative("left");
        var rightRotation = property.FindPropertyRelative("right");
        var linked = property.FindPropertyRelative("linked").boolValue;

        bool changeL = DrawRotationHandles(leftEye, leftRotation);
        bool changeR = DrawRotationHandles(rightEye, rightRotation);

        if(linked)
        {
            if(changeL)
            {
                var rotation = leftRotation.quaternionValue;
                (rightEye.objectReferenceValue as Transform).localRotation = rotation;
                rightRotation.quaternionValue = rotation;
            }
            else if (changeR)
            {
                var rotation = rightRotation.quaternionValue;
                (leftEye.objectReferenceValue as Transform).localRotation = rotation;
                leftRotation.quaternionValue = rotation;
            }
        }
    }
    void DrawSceneEyelids(SerializedProperty property, SerializedProperty upperLeftEyelid, SerializedProperty upperRightEyelid, SerializedProperty lowerLeftEyelid, SerializedProperty lowerRightEyelid)
    {
        if (!IsActiveProperty(property))
            return;

        var upperProperty = property.FindPropertyRelative("upper");
        var lowerProperty = property.FindPropertyRelative("lower");

        DrawSceneEyes(upperProperty, upperLeftEyelid, upperRightEyelid, false);
        DrawSceneEyes(lowerProperty, lowerLeftEyelid, lowerRightEyelid, false);
    }
    bool DrawRotationHandles(SerializedProperty transformProperty, SerializedProperty rotationProperty)
    {
        var transform = transformProperty.objectReferenceValue as Transform;
        if (transform == null)
            return false;
        Handles.matrix = Matrix4x4.TRS(transform.position, transform.parent.rotation, Vector3.one);

        transform.localRotation = rotationProperty.quaternionValue;
        var result = Handles.RotationHandle(transform.localRotation, Vector3.zero);
        if (result != transform.localRotation)
        {
            transform.localRotation = result;
            rotationProperty.quaternionValue = result;
            return true;
        }

        Handles.matrix = Matrix4x4.TRS(transform.position, transform.rotation, Vector3.one);
        Handles.color = new Color(1, 1, 1, 0.5f);
        Handles.DrawWireDisc(Vector3.zero, Vector3.forward, 0.01f);

        return false;
    }
}
#endif