Beispiel #1
0
 public UUndoScope(string text)
 {
     Undo.IncrementCurrentGroup();
     Undo.SetCurrentGroupName(text);
     m_currentGroup = Undo.GetCurrentGroup();
 }
Beispiel #2
0
        public static void ModifyAction(ActionListAsset _target, AC.Action _action, string callback)
        {
            ActionsManager actionsManager = AdvGame.GetReferences().actionsManager;

            if (actionsManager == null)
            {
                return;
            }

            int i = -1;

            if (_action != null && _target.actions.IndexOf(_action) > -1)
            {
                i = _target.actions.IndexOf(_action);
            }

            bool doUndo = (callback != "Copy");

            if (doUndo)
            {
                Undo.SetCurrentGroupName(callback);
                Undo.RecordObjects(new UnityEngine.Object [] { _target }, callback);
                Undo.RecordObjects(_target.actions.ToArray(), callback);
            }

            switch (callback)
            {
            case "Enable":
                _target.actions [i].isEnabled = true;
                break;

            case "Disable":
                _target.actions [i].isEnabled = false;
                break;

            case "Cut":
                List <AC.Action> cutList   = new List <AC.Action>();
                AC.Action        cutAction = Object.Instantiate(_action) as AC.Action;
                cutAction.name = cutAction.name.Replace("(Clone)", "");
                cutList.Add(cutAction);
                AdvGame.copiedActions = cutList;
                DeleteAction(_action, _target);
                break;

            case "Copy":
                List <AC.Action> copyList   = new List <AC.Action>();
                AC.Action        copyAction = Object.Instantiate(_action) as AC.Action;
                copyAction.ClearIDs();
                copyAction.name = copyAction.name.Replace("(Clone)", string.Empty);
                copyList.Add(copyAction);
                AdvGame.copiedActions = copyList;
                break;

            case "Paste after":
                List <AC.Action> pasteList = AdvGame.copiedActions;
                int j = i + 1;
                foreach (AC.Action action in pasteList)
                {
                    if (action == null)
                    {
                        ACDebug.LogWarning("Error when pasting Action - cannot find original. Did you change scene before pasting? If you need to transfer Actions between scenes, copy them to an ActionList asset first.");
                        continue;
                    }

                    AC.Action pastedAction = Object.Instantiate(action) as AC.Action;
                    pastedAction.name = pastedAction.name.Replace("(Clone)", string.Empty);
                    AddAction(pastedAction, j, _target);
                    j++;
                }
                break;

            case "Insert after":
                Action newAction = AddAction(ActionsManager.GetDefaultAction(), i + 1, _target);
                newAction.endAction        = _action.endAction;
                newAction.skipAction       = -1;
                newAction.skipActionActual = _action.skipActionActual;
                break;

            case "Delete":
                DeleteAction(_action, _target);
                break;

            case "Move to top":
                _target.actions.Remove(_action);
                _target.actions.Insert(0, _action);
                break;

            case "Move up":
                _target.actions.Remove(_action);
                _target.actions.Insert(i - 1, _action);
                break;

            case "Move to bottom":
                _target.actions.Remove(_action);
                _target.actions.Insert(_target.actions.Count, _action);
                break;

            case "Move down":
                _target.actions.Remove(_action);
                _target.actions.Insert(i + 1, _action);
                break;
            }

            if (doUndo)
            {
                Undo.RecordObjects(new UnityEngine.Object [] { _target }, callback);
                Undo.RecordObjects(_target.actions.ToArray(), callback);
                Undo.CollapseUndoOperations(Undo.GetCurrentGroup());
                EditorUtility.SetDirty(_target);
            }
        }
        public static void Migrate()
        {
            int oldUndoIndex = Undo.GetCurrentGroup();

            Undo.IncrementCurrentGroup();
            #if !UNITY_4_6 || UNITY_4_7
            Undo.SetCurrentGroupName("FMOD Studio Integration Migration");
            #endif

            Settings settings = Settings.Instance;

            var prefKey   = "FMODStudioProjectPath_" + Application.dataPath;
            var prefValue = EditorPrefs.GetString(prefKey);
            if (prefValue != null)
            {
                settings.SourceBankPath   = prefValue as string;
                settings.SourceBankPath  += "/Build";
                settings.HasSourceProject = false;
            }

            // for each level
            EditorApplication.SaveCurrentSceneIfUserWantsTo();

            var scenes = AssetDatabase.FindAssets("*.scene");
            foreach (string scene in scenes)
            {
                if (!EditorUtility.DisplayDialog("FMOD Studio Integration Migration", String.Format("Migrate scene {0}", AssetDatabase.GUIDToAssetPath(scene)), "OK", "Cancel"))
                {
                    continue;
                }

                EditorApplication.OpenScene(AssetDatabase.GUIDToAssetPath(scene));

                var emitters = FindObjectsOfType <FMOD_StudioEventEmitter>();
                foreach (var emitter in emitters)
                {
                    GameObject parent       = emitter.gameObject;
                    bool       startOnAwake = emitter.startEventOnAwake;
                    string     path         = null;
                    if (emitter.asset != null)
                    {
                        path = emitter.asset.path;
                    }
                    else if (!String.IsNullOrEmpty(emitter.path))
                    {
                        path = emitter.path;
                    }
                    else
                    {
                        continue;
                    }

                    Undo.DestroyObjectImmediate(emitter);

                    var newEmitter = Undo.AddComponent <StudioEventEmitter>(parent);
                    newEmitter.Event     = path;
                    newEmitter.PlayEvent = startOnAwake ? EmitterGameEvent.LevelStart : EmitterGameEvent.None;
                    newEmitter.PlayEvent = startOnAwake ? EmitterGameEvent.LevelEnd : EmitterGameEvent.None;
                }


                var listeners = FindObjectsOfType <FMOD_Listener>();

                foreach (var listener in listeners)
                {
                    GameObject parent = listener.gameObject;

                    foreach (var plugin in listener.pluginPaths)
                    {
                        if (!settings.Plugins.Contains(plugin))
                        {
                            settings.Plugins.Add(plugin);
                        }
                    }

                    Undo.DestroyObjectImmediate(listener);
                    Undo.AddComponent <StudioListener>(parent);
                }

                foreach (var custom in CustomMigrationEntries)
                {
                    var objects = FindObjectsOfType(custom.ScriptClass);
                    foreach (var obj in objects)
                    {
                        var serializedObj = new SerializedObject(obj);
                        var oldProp       = serializedObj.FindProperty(custom.OldProperty);
                        if (oldProp == null || oldProp.propertyType != SerializedPropertyType.ObjectReference || (oldProp.objectReferenceValue != null && oldProp.objectReferenceValue.GetType() != typeof(FMODAsset)))
                        {
                            UnityEngine.Debug.LogWarning(String.Format("FMOD Studio Migration: Cannot find property {0} of type FMODAsset on script {1}", custom.OldProperty, custom.ScriptClass.ToString()));
                            continue;
                        }
                        var newProp = serializedObj.FindProperty(custom.NewProperty);
                        if (newProp == null || newProp.propertyType != SerializedPropertyType.String)
                        {
                            UnityEngine.Debug.LogWarning(String.Format("FMOD Studio Migration: Cannot find property {0} of type string on script {1}", custom.NewProperty, custom.ScriptClass.ToString()));
                            continue;
                        }
                        var oldAsset = oldProp.objectReferenceValue as FMODAsset;
                        if (oldAsset != null)
                        {
                            newProp.stringValue = oldAsset.path;
                        }
                        oldProp.objectReferenceValue = null;
                        serializedObj.ApplyModifiedProperties();
                    }
                }

                EditorApplication.SaveCurrentSceneIfUserWantsTo();
            }

            EditorUtility.SetDirty(settings);

            AssetDatabase.DeleteAsset("Assets/FMODAssets");
            AssetDatabase.Refresh();
            Undo.CollapseUndoOperations(oldUndoIndex);
        }
        public static void CreateDeformerFromAttribute(DeformerAttribute attribute, bool autoAdd)
        {
            var selectedGameObjects = Selection.gameObjects;

            if (selectedGameObjects == null || selectedGameObjects.Length == 0)
            {
                var newGameObject = new GameObject(attribute.Name);

                Undo.RegisterCreatedObjectUndo(newGameObject, "Created Deformer");

                newGameObject.AddComponent(attribute.Type);

                newGameObject.transform.localRotation = Quaternion.Euler(attribute.XRotation, attribute.YRotation, attribute.ZRotation);

                Selection.activeGameObject = newGameObject;
            }
            else
            {
                Undo.SetCurrentGroupName("Created Deformer");

                var newGameObject = new GameObject(attribute.Name);
                Undo.RegisterCreatedObjectUndo(newGameObject, "Created Deformer");

                EditorGUIUtility.PingObject(newGameObject);

                var newDeformer = newGameObject.AddComponent(attribute.Type) as Deformer;

                if (autoAdd)
                {
                    if (selectedGameObjects.Length == 1)
                    {
                        if (!PrefabUtility.IsPartOfPrefabAsset(Selection.gameObjects[0]))
                        {
                            var parent = selectedGameObjects[0].transform;
                            newGameObject.transform.SetParent(parent, true);
                            newGameObject.transform.position = parent.position;
                            newGameObject.transform.rotation = parent.rotation * Quaternion.Euler(attribute.XRotation, attribute.YRotation, attribute.ZRotation);
                        }
                    }
                    else
                    {
                        var center   = GetAverageGameObjectPosition(selectedGameObjects);
                        var rotation = Quaternion.Euler(attribute.XRotation, attribute.YRotation, attribute.ZRotation);
                        newGameObject.transform.SetPositionAndRotation(center, rotation);
                    }

                    var deformables = GetComponents <Deformable> (selectedGameObjects);
                    var groups      = GetComponents <GroupDeformer> (selectedGameObjects);
                    var repeaters   = GetComponents <RepeaterDeformer> (selectedGameObjects);

                    foreach (var deformable in deformables)
                    {
                        if (deformable != null && !PrefabUtility.IsPartOfPrefabAsset(deformable))
                        {
                            Undo.RecordObject(deformable, "Added Deformer");
                            deformable.DeformerElements.Add(new DeformerElement(newDeformer));
                        }
                    }

                    foreach (var group in groups)
                    {
                        if (group != null && !PrefabUtility.IsPartOfPrefabAsset(group))
                        {
                            Undo.RecordObject(group, "Added Deformer");
                            group.DeformerElements.Add(new DeformerElement(newDeformer));
                        }
                    }

                    foreach (var repeater in repeaters)
                    {
                        if (repeater != null && !PrefabUtility.IsPartOfPrefabAsset(repeater))
                        {
                            Undo.RecordObject(repeater, "Set Deformer");
                            repeater.DeformerElement.Component = newDeformer;
                        }
                    }
                }
                else
                {
                    Selection.activeGameObject = newGameObject;
                }

                Undo.CollapseUndoOperations(Undo.GetCurrentGroup());
            }
        }
        FloatField AddField(VisualElement panel, string label, int index, Vector3 initValiue)
        {
            var field = new FloatField {
                userData = index, value = initValiue[index]
            };

            if (label != "")
            {
                var l = new Label(label);
                panel.Add(l);
                var dragger = new FieldMouseDragger <double>(field);
                dragger.SetDragZone(l);
            }

            field.RegisterCallback <MouseDownEvent>(Repaint);
            field.RegisterCallback <MouseMoveEvent>(Repaint);
            field.RegisterValueChangedCallback(evt =>
            {
                var value    = (Vector3)m_PropertyInfo.GetValue(m_Node, null);
                value[index] = (float)evt.newValue;
                m_PropertyInfo.SetValue(m_Node, value, null);
                m_UndoGroup = -1;
                this.MarkDirtyRepaint();
            });
            field.Q("unity-text-input").RegisterCallback <InputEvent>(evt =>
            {
                if (m_UndoGroup == -1)
                {
                    m_UndoGroup = Undo.GetCurrentGroup();
                    m_Node.owner.owner.RegisterCompleteObjectUndo("Change " + m_Node.name);
                }
                float newValue;
                if (!float.TryParse(evt.newData, NumberStyles.Float, CultureInfo.InvariantCulture.NumberFormat, out newValue))
                {
                    newValue = 0f;
                }
                var value    = (Vector3)m_PropertyInfo.GetValue(m_Node, null);
                value[index] = newValue;
                m_PropertyInfo.SetValue(m_Node, value, null);
                if (evt.newData.Length != 0 &&
                    evt.newData[evt.newData.Length - 1] != '.' &&
                    evt.newData[evt.newData.Length - 1] != ',')
                {
                    UpdateSlider(m_SliderPanel, index, value);
                }
                this.MarkDirtyRepaint();
            });
            field.Q("unity-text-input").RegisterCallback <KeyDownEvent>(evt =>
            {
                if (evt.keyCode == KeyCode.Escape && m_UndoGroup > -1)
                {
                    Undo.RevertAllDownToGroup(m_UndoGroup);
                    m_UndoGroup = -1;
                    m_Value     = (Vector3)m_PropertyInfo.GetValue(m_Node, null);
                    UpdateSlider(m_SliderPanel, index, m_Value);
                    evt.StopPropagation();
                }
                this.MarkDirtyRepaint();
            });
            panel.Add(field);
            return(field);
        }
        public BlackboardFieldPropertyView(BlackboardField blackboardField, GraphData graph, AbstractShaderProperty property)
        {
            styleSheets.Add(Resources.Load <StyleSheet>("Styles/ShaderGraphBlackboard"));
            m_BlackboardField = blackboardField;
            m_Graph           = graph;
            m_Property        = property;

            if (!m_Graph.isSubGraph)
            {
                if (property.isExposable)
                {
                    m_ExposedToogle = new Toggle();
                    m_ExposedToogle.OnToggleChanged(evt =>
                    {
                        m_Graph.owner.RegisterCompleteObjectUndo("Change Exposed Toggle");
                        if (m_OnExposedToggle != null)
                        {
                            m_OnExposedToggle();
                        }
                        property.generatePropertyBlock = evt.newValue;
                        if (property.generatePropertyBlock)
                        {
                            m_BlackboardField.icon = BlackboardProvider.exposedIcon;
                        }
                        else
                        {
                            m_BlackboardField.icon = null;
                        }
                        DirtyNodes(ModificationScope.Graph);
                    });
                    m_ExposedToogle.value = property.generatePropertyBlock;
                    AddRow("Exposed", m_ExposedToogle);
                }

                if (property.isExposable)
                {
                    m_ReferenceNameField = new TextField(512, false, false, ' ');
                    m_ReferenceNameField.styleSheets.Add(Resources.Load <StyleSheet>("Styles/PropertyNameReferenceField"));
                    AddRow("Reference", m_ReferenceNameField);
                    m_ReferenceNameField.value     = property.referenceName;
                    m_ReferenceNameField.isDelayed = true;
                    m_ReferenceNameField.RegisterValueChangedCallback(newName =>
                    {
                        m_Graph.owner.RegisterCompleteObjectUndo("Change Reference Name");
                        if (m_ReferenceNameField.value != m_Property.referenceName)
                        {
                            string newReferenceName        = m_Graph.SanitizePropertyReferenceName(newName.newValue, property.guid);
                            property.overrideReferenceName = newReferenceName;
                        }
                        m_ReferenceNameField.value = property.referenceName;

                        if (string.IsNullOrEmpty(property.overrideReferenceName))
                        {
                            m_ReferenceNameField.RemoveFromClassList("modified");
                        }
                        else
                        {
                            m_ReferenceNameField.AddToClassList("modified");
                        }

                        DirtyNodes(ModificationScope.Graph);
                        UpdateReferenceNameResetMenu();
                    });

                    if (!string.IsNullOrEmpty(property.overrideReferenceName))
                    {
                        m_ReferenceNameField.AddToClassList("modified");
                    }
                }
            }

            // Key Undo callbacks for input fields
            EventCallback <KeyDownEvent> keyDownCallback = new EventCallback <KeyDownEvent>(evt =>
            {
                // Record Undo for input field edit
                if (m_UndoGroup == -1)
                {
                    m_UndoGroup = Undo.GetCurrentGroup();
                    m_Graph.owner.RegisterCompleteObjectUndo("Change property value");
                }
                // Handle scaping input field edit
                if (evt.keyCode == KeyCode.Escape && m_UndoGroup > -1)
                {
                    Undo.RevertAllDownToGroup(m_UndoGroup);
                    m_UndoGroup = -1;
                    evt.StopPropagation();
                }
                // Dont record Undo again until input field is unfocused
                m_UndoGroup++;
                this.MarkDirtyRepaint();
            });
            EventCallback <FocusOutEvent> focusOutCallback = new EventCallback <FocusOutEvent>(evt =>
            {
                // Reset UndoGroup when done editing input field
                m_UndoGroup = -1;
            });

            if (property is Vector1ShaderProperty)
            {
                var floatProperty = (Vector1ShaderProperty)property;
                BuildVector1PropertyView(floatProperty);
            }
            else if (property is Vector2ShaderProperty)
            {
                var vectorProperty = (Vector2ShaderProperty)property;
                var field          = new Vector2Field {
                    value = vectorProperty.value
                };

                field.Q("unity-x-input").Q("unity-text-input").RegisterCallback <KeyDownEvent>(keyDownCallback);
                field.Q("unity-x-input").Q("unity-text-input").RegisterCallback <FocusOutEvent>(focusOutCallback);
                field.Q("unity-y-input").Q("unity-text-input").RegisterCallback <KeyDownEvent>(keyDownCallback);
                field.Q("unity-y-input").Q("unity-text-input").RegisterCallback <FocusOutEvent>(focusOutCallback);

                // Called after KeyDownEvent
                field.RegisterValueChangedCallback(evt =>
                {
                    // Only true when setting value via FieldMouseDragger
                    // Undo recorded once per dragger release
                    if (m_UndoGroup == -1)
                    {
                        m_Graph.owner.RegisterCompleteObjectUndo("Change property value");
                    }
                    vectorProperty.value = evt.newValue;
                    DirtyNodes();
                });
                AddRow("Default", field);
            }
            else if (property is Vector3ShaderProperty)
            {
                var vectorProperty = (Vector3ShaderProperty)property;
                var field          = new Vector3Field {
                    value = vectorProperty.value
                };

                field.Q("unity-x-input").Q("unity-text-input").RegisterCallback <KeyDownEvent>(keyDownCallback);
                field.Q("unity-x-input").Q("unity-text-input").RegisterCallback <FocusOutEvent>(focusOutCallback);
                field.Q("unity-y-input").Q("unity-text-input").RegisterCallback <KeyDownEvent>(keyDownCallback);
                field.Q("unity-y-input").Q("unity-text-input").RegisterCallback <FocusOutEvent>(focusOutCallback);
                field.Q("unity-z-input").Q("unity-text-input").RegisterCallback <KeyDownEvent>(keyDownCallback);
                field.Q("unity-z-input").Q("unity-text-input").RegisterCallback <FocusOutEvent>(focusOutCallback);

                // Called after KeyDownEvent
                field.RegisterValueChangedCallback(evt =>
                {
                    // Only true when setting value via FieldMouseDragger
                    // Undo recorded once per dragger release
                    if (m_UndoGroup == -1)
                    {
                        m_Graph.owner.RegisterCompleteObjectUndo("Change property value");
                    }
                    vectorProperty.value = evt.newValue;
                    DirtyNodes();
                });
                AddRow("Default", field);
            }
            else if (property is Vector4ShaderProperty)
            {
                var vectorProperty = (Vector4ShaderProperty)property;
                var field          = new Vector4Field {
                    value = vectorProperty.value
                };

                field.Q("unity-x-input").Q("unity-text-input").RegisterCallback <KeyDownEvent>(keyDownCallback);
                field.Q("unity-x-input").Q("unity-text-input").RegisterCallback <FocusOutEvent>(focusOutCallback);
                field.Q("unity-y-input").Q("unity-text-input").RegisterCallback <KeyDownEvent>(keyDownCallback);
                field.Q("unity-y-input").Q("unity-text-input").RegisterCallback <FocusOutEvent>(focusOutCallback);
                field.Q("unity-z-input").Q("unity-text-input").RegisterCallback <KeyDownEvent>(keyDownCallback);
                field.Q("unity-z-input").Q("unity-text-input").RegisterCallback <FocusOutEvent>(focusOutCallback);
                field.Q("unity-w-input").Q("unity-text-input").RegisterCallback <KeyDownEvent>(keyDownCallback);
                field.Q("unity-w-input").Q("unity-text-input").RegisterCallback <FocusOutEvent>(focusOutCallback);

                // Called after KeyDownEvent
                field.RegisterValueChangedCallback(evt =>
                {
                    // Only true when setting value via FieldMouseDragger
                    // Undo recorded once per dragger release
                    if (m_UndoGroup == -1)
                    {
                        m_Graph.owner.RegisterCompleteObjectUndo("Change property value");
                    }
                    vectorProperty.value = evt.newValue;
                    DirtyNodes();
                });
                AddRow("Default", field);
            }
            else if (property is ColorShaderProperty)
            {
                var colorProperty = (ColorShaderProperty)property;
                var colorField    = new ColorField {
                    value = property.defaultValue, showEyeDropper = false, hdr = colorProperty.colorMode == ColorMode.HDR
                };
                colorField.RegisterValueChangedCallback(evt =>
                {
                    m_Graph.owner.RegisterCompleteObjectUndo("Change property value");
                    colorProperty.value = evt.newValue;
                    DirtyNodes();
                });
                AddRow("Default", colorField);
                if (!m_Graph.isSubGraph)
                {
                    var colorModeField = new EnumField((Enum)colorProperty.colorMode);
                    colorModeField.RegisterValueChangedCallback(evt =>
                    {
                        m_Graph.owner.RegisterCompleteObjectUndo("Change Color Mode");
                        if (colorProperty.colorMode == (ColorMode)evt.newValue)
                        {
                            return;
                        }
                        colorProperty.colorMode = (ColorMode)evt.newValue;
                        colorField.hdr          = colorProperty.colorMode == ColorMode.HDR;
                        colorField.MarkDirtyRepaint();
                        DirtyNodes();
                    });
                    AddRow("Mode", colorModeField);
                }
            }
            else if (property is TextureShaderProperty)
            {
                var textureProperty = (TextureShaderProperty)property;
                var field           = new ObjectField {
                    value = textureProperty.value.texture, objectType = typeof(Texture)
                };
                field.RegisterValueChangedCallback(evt =>
                {
                    m_Graph.owner.RegisterCompleteObjectUndo("Change property value");
                    textureProperty.value.texture = (Texture)evt.newValue;
                    DirtyNodes();
                });
                AddRow("Default", field);
                if (!m_Graph.isSubGraph)
                {
                    var defaultModeField = new EnumField((Enum)textureProperty.defaultType);
                    defaultModeField.RegisterValueChangedCallback(evt =>
                    {
                        m_Graph.owner.RegisterCompleteObjectUndo("Change Texture Mode");
                        if (textureProperty.defaultType == (TextureShaderProperty.DefaultType)evt.newValue)
                        {
                            return;
                        }
                        textureProperty.defaultType = (TextureShaderProperty.DefaultType)evt.newValue;
                        DirtyNodes(ModificationScope.Graph);
                    });
                    void ToggleDefaultModeFieldEnabled()
                    {
                        defaultModeField.SetEnabled(!defaultModeField.enabledSelf);
                    }

                    m_OnExposedToggle += ToggleDefaultModeFieldEnabled;
                    AddRow("Mode", defaultModeField);
                }
            }
            else if (property is Texture2DArrayShaderProperty)
            {
                var textureProperty = (Texture2DArrayShaderProperty)property;
                var field           = new ObjectField {
                    value = textureProperty.value.textureArray, objectType = typeof(Texture2DArray)
                };
                field.RegisterValueChangedCallback(evt =>
                {
                    m_Graph.owner.RegisterCompleteObjectUndo("Change property value");
                    textureProperty.value.textureArray = (Texture2DArray)evt.newValue;
                    DirtyNodes();
                });
                AddRow("Default", field);
            }
            else if (property is Texture3DShaderProperty)
            {
                var textureProperty = (Texture3DShaderProperty)property;
                var field           = new ObjectField {
                    value = textureProperty.value.texture, objectType = typeof(Texture3D)
                };
                field.RegisterValueChangedCallback(evt =>
                {
                    m_Graph.owner.RegisterCompleteObjectUndo("Change property value");
                    textureProperty.value.texture = (Texture3D)evt.newValue;
                    DirtyNodes();
                });
                AddRow("Default", field);
            }
            else if (property is CubemapShaderProperty)
            {
                var cubemapProperty = (CubemapShaderProperty)property;
                var field           = new ObjectField {
                    value = cubemapProperty.value.cubemap, objectType = typeof(Cubemap)
                };
                field.RegisterValueChangedCallback(evt =>
                {
                    m_Graph.owner.RegisterCompleteObjectUndo("Change property value");
                    cubemapProperty.value.cubemap = (Cubemap)evt.newValue;
                    DirtyNodes();
                });
                AddRow("Default", field);
            }
            else if (property is BooleanShaderProperty)
            {
                var booleanProperty = (BooleanShaderProperty)property;
                EventCallback <ChangeEvent <bool> > onBooleanChanged = evt =>
                {
                    m_Graph.owner.RegisterCompleteObjectUndo("Change property value");
                    booleanProperty.value = evt.newValue;
                    DirtyNodes();
                };
                var field = new Toggle();
                field.OnToggleChanged(onBooleanChanged);
                field.value = booleanProperty.value;
                AddRow("Default", field);
            }
            else if (property is Matrix2ShaderProperty)
            {
                var matrix2Property = (Matrix2ShaderProperty)property;
                var row0Field       = new Vector2Field {
                    value = matrix2Property.value.GetRow(0)
                };
                row0Field.RegisterValueChangedCallback(evt =>
                {
                    m_Graph.owner.RegisterCompleteObjectUndo("Change Property Value");
                    Vector2 row1          = matrix2Property.value.GetRow(1);
                    matrix2Property.value = new Matrix4x4()
                    {
                        m00 = evt.newValue.x,
                        m01 = evt.newValue.y,
                        m02 = 0,
                        m03 = 0,
                        m10 = row1.x,
                        m11 = row1.y,
                        m12 = 0,
                        m13 = 0,
                        m20 = 0,
                        m21 = 0,
                        m22 = 0,
                        m23 = 0,
                        m30 = 0,
                        m31 = 0,
                        m32 = 0,
                        m33 = 0,
                    };
                    DirtyNodes();
                });
                AddRow("Default", row0Field);
                var row1Field = new Vector2Field {
                    value = matrix2Property.value.GetRow(1)
                };
                row1Field.RegisterValueChangedCallback(evt =>
                {
                    m_Graph.owner.RegisterCompleteObjectUndo("Change Property Value");
                    Vector2 row0          = matrix2Property.value.GetRow(0);
                    matrix2Property.value = new Matrix4x4()
                    {
                        m00 = row0.x,
                        m01 = row0.y,
                        m02 = 0,
                        m03 = 0,
                        m10 = evt.newValue.x,
                        m11 = evt.newValue.y,
                        m12 = 0,
                        m13 = 0,
                        m20 = 0,
                        m21 = 0,
                        m22 = 0,
                        m23 = 0,
                        m30 = 0,
                        m31 = 0,
                        m32 = 0,
                        m33 = 0,
                    };
                    DirtyNodes();
                });
                AddRow("", row1Field);
            }
            else if (property is Matrix3ShaderProperty)
            {
                var matrix3Property = (Matrix3ShaderProperty)property;
                var row0Field       = new Vector3Field {
                    value = matrix3Property.value.GetRow(0)
                };
                row0Field.RegisterValueChangedCallback(evt =>
                {
                    m_Graph.owner.RegisterCompleteObjectUndo("Change Property Value");
                    Vector3 row1          = matrix3Property.value.GetRow(1);
                    Vector3 row2          = matrix3Property.value.GetRow(2);
                    matrix3Property.value = new Matrix4x4()
                    {
                        m00 = evt.newValue.x,
                        m01 = evt.newValue.y,
                        m02 = evt.newValue.z,
                        m03 = 0,
                        m10 = row1.x,
                        m11 = row1.y,
                        m12 = row1.z,
                        m13 = 0,
                        m20 = row2.x,
                        m21 = row2.y,
                        m22 = row2.z,
                        m23 = 0,
                        m30 = 0,
                        m31 = 0,
                        m32 = 0,
                        m33 = 0,
                    };
                    DirtyNodes();
                });
                AddRow("Default", row0Field);
                var row1Field = new Vector3Field {
                    value = matrix3Property.value.GetRow(1)
                };
                row1Field.RegisterValueChangedCallback(evt =>
                {
                    m_Graph.owner.RegisterCompleteObjectUndo("Change Property Value");
                    Vector3 row0          = matrix3Property.value.GetRow(0);
                    Vector3 row2          = matrix3Property.value.GetRow(2);
                    matrix3Property.value = new Matrix4x4()
                    {
                        m00 = row0.x,
                        m01 = row0.y,
                        m02 = row0.z,
                        m03 = 0,
                        m10 = evt.newValue.x,
                        m11 = evt.newValue.y,
                        m12 = evt.newValue.z,
                        m13 = 0,
                        m20 = row2.x,
                        m21 = row2.y,
                        m22 = row2.z,
                        m23 = 0,
                        m30 = 0,
                        m31 = 0,
                        m32 = 0,
                        m33 = 0,
                    };
                    DirtyNodes();
                });
                AddRow("", row1Field);
                var row2Field = new Vector3Field {
                    value = matrix3Property.value.GetRow(2)
                };
                row2Field.RegisterValueChangedCallback(evt =>
                {
                    m_Graph.owner.RegisterCompleteObjectUndo("Change Property Value");
                    Vector3 row0          = matrix3Property.value.GetRow(0);
                    Vector3 row1          = matrix3Property.value.GetRow(1);
                    matrix3Property.value = new Matrix4x4()
                    {
                        m00 = row0.x,
                        m01 = row0.y,
                        m02 = row0.z,
                        m03 = 0,
                        m10 = row1.x,
                        m11 = row1.y,
                        m12 = row1.z,
                        m13 = 0,
                        m20 = evt.newValue.x,
                        m21 = evt.newValue.y,
                        m22 = evt.newValue.z,
                        m23 = 0,
                        m30 = 0,
                        m31 = 0,
                        m32 = 0,
                        m33 = 0,
                    };
                    DirtyNodes();
                });
                AddRow("", row2Field);
            }
            else if (property is Matrix4ShaderProperty)
            {
                var matrix4Property = (Matrix4ShaderProperty)property;
                var row0Field       = new Vector4Field {
                    value = matrix4Property.value.GetRow(0)
                };
                row0Field.RegisterValueChangedCallback(evt =>
                {
                    m_Graph.owner.RegisterCompleteObjectUndo("Change Property Value");
                    Vector4 row1          = matrix4Property.value.GetRow(1);
                    Vector4 row2          = matrix4Property.value.GetRow(2);
                    Vector4 row3          = matrix4Property.value.GetRow(3);
                    matrix4Property.value = new Matrix4x4()
                    {
                        m00 = evt.newValue.x,
                        m01 = evt.newValue.y,
                        m02 = evt.newValue.z,
                        m03 = evt.newValue.w,
                        m10 = row1.x,
                        m11 = row1.y,
                        m12 = row1.z,
                        m13 = row1.w,
                        m20 = row2.x,
                        m21 = row2.y,
                        m22 = row2.z,
                        m23 = row2.w,
                        m30 = row3.x,
                        m31 = row3.y,
                        m32 = row3.z,
                        m33 = row3.w,
                    };
                    DirtyNodes();
                });
                AddRow("Default", row0Field);
                var row1Field = new Vector4Field {
                    value = matrix4Property.value.GetRow(1)
                };
                row1Field.RegisterValueChangedCallback(evt =>
                {
                    m_Graph.owner.RegisterCompleteObjectUndo("Change Property Value");
                    Vector4 row0          = matrix4Property.value.GetRow(0);
                    Vector4 row2          = matrix4Property.value.GetRow(2);
                    Vector4 row3          = matrix4Property.value.GetRow(3);
                    matrix4Property.value = new Matrix4x4()
                    {
                        m00 = row0.x,
                        m01 = row0.y,
                        m02 = row0.z,
                        m03 = row0.w,
                        m10 = evt.newValue.x,
                        m11 = evt.newValue.y,
                        m12 = evt.newValue.z,
                        m13 = evt.newValue.w,
                        m20 = row2.x,
                        m21 = row2.y,
                        m22 = row2.z,
                        m23 = row2.w,
                        m30 = row3.x,
                        m31 = row3.y,
                        m32 = row3.z,
                        m33 = row3.w,
                    };
                    DirtyNodes();
                });
                AddRow("", row1Field);
                var row2Field = new Vector4Field {
                    value = matrix4Property.value.GetRow(2)
                };
                row2Field.RegisterValueChangedCallback(evt =>
                {
                    m_Graph.owner.RegisterCompleteObjectUndo("Change Property Value");
                    Vector4 row0          = matrix4Property.value.GetRow(0);
                    Vector4 row1          = matrix4Property.value.GetRow(1);
                    Vector4 row3          = matrix4Property.value.GetRow(3);
                    matrix4Property.value = new Matrix4x4()
                    {
                        m00 = row0.x,
                        m01 = row0.y,
                        m02 = row0.z,
                        m03 = row0.w,
                        m10 = row1.x,
                        m11 = row1.y,
                        m12 = row1.z,
                        m13 = row1.w,
                        m20 = evt.newValue.x,
                        m21 = evt.newValue.y,
                        m22 = evt.newValue.z,
                        m23 = evt.newValue.w,
                        m30 = row3.x,
                        m31 = row3.y,
                        m32 = row3.z,
                        m33 = row3.w,
                    };
                    DirtyNodes();
                });
                AddRow("", row2Field);
                var row3Field = new Vector4Field {
                    value = matrix4Property.value.GetRow(3)
                };
                row3Field.RegisterValueChangedCallback(evt =>
                {
                    m_Graph.owner.RegisterCompleteObjectUndo("Change Property Value");
                    Vector4 row0          = matrix4Property.value.GetRow(0);
                    Vector4 row1          = matrix4Property.value.GetRow(1);
                    Vector4 row2          = matrix4Property.value.GetRow(2);
                    matrix4Property.value = new Matrix4x4()
                    {
                        m00 = row0.x,
                        m01 = row0.y,
                        m02 = row0.z,
                        m03 = row0.w,
                        m10 = row1.x,
                        m11 = row1.y,
                        m12 = row1.z,
                        m13 = row1.w,
                        m20 = row2.x,
                        m21 = row2.y,
                        m22 = row2.z,
                        m23 = row2.w,
                        m30 = evt.newValue.x,
                        m31 = evt.newValue.y,
                        m32 = evt.newValue.z,
                        m33 = evt.newValue.w,
                    };
                    DirtyNodes();
                });
                AddRow("", row3Field);
            }
            else if (property is SamplerStateShaderProperty)
            {
                var samplerStateProperty = (SamplerStateShaderProperty)property;
                var filterField          = new EnumField(samplerStateProperty.value.filter);
                filterField.RegisterValueChangedCallback(evt =>
                {
                    m_Graph.owner.RegisterCompleteObjectUndo("Change Property Value");
                    TextureSamplerState state = samplerStateProperty.value;
                    state.filter = (TextureSamplerState.FilterMode)evt.newValue;
                    samplerStateProperty.value = state;
                    DirtyNodes(ModificationScope.Graph);
                });
                AddRow("Filter", filterField);
                var wrapField = new EnumField(samplerStateProperty.value.wrap);
                wrapField.RegisterValueChangedCallback(evt =>
                {
                    m_Graph.owner.RegisterCompleteObjectUndo("Change Property Value");
                    TextureSamplerState state = samplerStateProperty.value;
                    state.wrap = (TextureSamplerState.WrapMode)evt.newValue;
                    samplerStateProperty.value = state;
                    DirtyNodes(ModificationScope.Graph);
                });
                AddRow("Wrap", wrapField);
            }
            else if (property is GradientShaderProperty)
            {
                var gradientProperty = (GradientShaderProperty)property;
                var field            = new GradientField {
                    value = gradientProperty.value
                };
                field.RegisterValueChangedCallback(evt =>
                {
                    m_Graph.owner.RegisterCompleteObjectUndo("Change Property Value");
                    gradientProperty.value = evt.newValue;
                    DirtyNodes();
                });
                AddRow("Default", field);
            }

            var precisionField = new EnumField((Enum)property.precision);

            precisionField.RegisterValueChangedCallback(evt =>
            {
                m_Graph.owner.RegisterCompleteObjectUndo("Change Precision");
                if (property.precision == (Precision)evt.newValue)
                {
                    return;
                }
                property.precision = (Precision)evt.newValue;
                m_Graph.ValidateGraph();
                precisionField.MarkDirtyRepaint();
                DirtyNodes();
            });
            AddRow("Precision", precisionField);

            AddToClassList("sgblackboardFieldPropertyView");

            UpdateReferenceNameResetMenu();
        }
		protected bool GenerateBrushObjects(int brushObjectCount, bool inGridSpace = true)
		{
			Undo.IncrementCurrentGroup();
			undoGroupIndex = Undo.GetCurrentGroup();

            var lastUsedModel			= SelectionUtility.LastUsedModel;
            if (!ModelTraits.IsModelEditable(lastUsedModel))
                lastUsedModel = null;
            var lastUsedModelTransform	= !lastUsedModel ? null : lastUsedModel.transform;

			if (!lastUsedModelTransform ||
				!lastUsedModel.isActiveAndEnabled)
			{
				if (prevSelection != null && prevSelection.Length > 0)
				{
					for (int i = 0; i < prevSelection.Length; i++)
					{
						UnityEngine.Object	obj		= prevSelection[i];
						CSGBrush			brush	= obj as CSGBrush;
						MonoBehaviour		mono	= obj as MonoBehaviour;
						GameObject			go		= obj as GameObject;
						if (!brush)
						{
							if (mono)
							{
								brush = mono.GetComponentInChildren<CSGBrush>();
							}
							if (go)
							{
								brush = go.GetComponentInChildren<CSGBrush>();
							}
						}

						if (!brush)
							continue;
						
						if ((brush.gameObject.hideFlags & (HideFlags.HideInHierarchy | HideFlags.NotEditable | HideFlags.DontSaveInBuild)) != 0)
							continue;

						if (brush.ChildData == null ||
							brush.ChildData.ModelTransform == null)
							continue;

						var model = brush.ChildData.Model;
						if (!model ||
							!model.isActiveAndEnabled)
							continue;

						lastUsedModelTransform = brush.ChildData.ModelTransform;
						break;
					}
				}
			}     

			if (generatedBrushes != null && generatedBrushes.Length > 0)
            {
                for (int i = generatedBrushes.Length - 1; i >= 0; i--)
                {
                    if (generatedBrushes[i])
                        continue;
                    ArrayUtility.RemoveAt(ref generatedBrushes, i);
                }
                for (int i = generatedGameObjects.Length - 1; i >= 0; i--)
                {
					if (generatedGameObjects[i])
					{				
						var brush = generatedGameObjects[i].GetComponentInChildren<CSGBrush>();
						if (brush && ArrayUtility.Contains(generatedBrushes, brush))
							continue;
					}
                    ArrayUtility.RemoveAt(ref generatedGameObjects, i);
                }
            }

			if (generatedGameObjects == null ||
				generatedGameObjects.Length != brushObjectCount)
			{
				if (generatedBrushes != null && generatedBrushes.Length > 0)
				{
					for (int i = 0; i < generatedBrushes.Length; i++)
					{
						InternalCSGModelManager.OnDestroyed(generatedBrushes[i]);
						GameObject.DestroyImmediate(generatedBrushes[i]);
					}
				}
				if (generatedGameObjects != null && generatedGameObjects.Length > 0)
				{
					for (int i = 0; i < generatedGameObjects.Length; i++)
						GameObject.DestroyImmediate(generatedGameObjects[i]);
				}

				if (parentGameObject != null)
					GameObject.DestroyImmediate(parentGameObject);

				//DebugEditorWindow.PrintDebugInfo();

				if (lastUsedModelTransform == null)
				{
					parentGameObject = OperationsUtility.CreateGameObject(lastUsedModelTransform, "Model", true);
					InternalCSGModelManager.CreateCSGModel(parentGameObject);
					parentModel = parentGameObject.GetComponent<CSGModel>();
					Undo.RegisterCreatedObjectUndo(parentGameObject, "Created model");

					if (brushObjectCount > 1)
					{
						operationGameObject = OperationsUtility.CreateGameObject(parentGameObject.transform, "Operation", true);
						var transform = operationGameObject.transform;
						SetBrushTransformation(transform);

						var operation = operationGameObject.AddComponent<CSGOperation>();
						if (CurrentCSGOperationType != invalidCSGOperationType)							
							operation.OperationType = CurrentCSGOperationType;
						operation.HandleAsOne = true;
						Undo.RegisterCreatedObjectUndo(operationGameObject, "Created operation");
						parentTransform = operationGameObject.transform;
					} else
					{
						parentTransform = parentGameObject.transform;
					}
				} else
				if (brushObjectCount > 1)
				{
					parentModel = lastUsedModelTransform.GetComponent<CSGModel>();
					parentGameObject = OperationsUtility.CreateGameObject(lastUsedModelTransform, "Brushes", true);
					var transform = parentGameObject.transform;
					SetBrushTransformation(transform);

					operationGameObject = parentGameObject;
					var operation = operationGameObject.AddComponent<CSGOperation>();
					if (CurrentCSGOperationType != invalidCSGOperationType)
						operation.OperationType = CurrentCSGOperationType;
					operation.HandleAsOne = true;
					parentTransform = operationGameObject.transform;
					Undo.RegisterCreatedObjectUndo(parentGameObject, "Created brush");
				} else
				{
					parentGameObject = null;
					operationGameObject = null;
					parentTransform = lastUsedModelTransform;
					parentModel = lastUsedModelTransform.GetComponent<CSGModel>();
				}

				
				generatedGameObjects = new GameObject[brushObjectCount];
				generatedBrushes = new CSGBrush[brushObjectCount];
				for (int p = 0; p < brushObjectCount; p++)
				{
					string name;
					if (brushObjectCount == 1)
						name = "Brush";
					else
						name = "Brush (" + p + ")";
					var gameObject = OperationsUtility.CreateGameObject(parentTransform, name, false);
					gameObject.SetActive(false);

					var brushComponent = gameObject.AddComponent<CSGBrush>();

					if (operationGameObject == null)
					{
						if (CurrentCSGOperationType != invalidCSGOperationType)
							brushComponent.OperationType = CurrentCSGOperationType;
						operationGameObject = gameObject;
						var transform = gameObject.transform;
						SetBrushTransformation(transform);
					}

					generatedBrushes[p] = brushComponent;
					generatedBrushes[p].ControlMesh = new ControlMesh();
					generatedBrushes[p].Shape = new Shape();
					Undo.RegisterCreatedObjectUndo(gameObject, "Created brush");
					generatedGameObjects[p] = gameObject;
				}
				//InternalCSGModelManager.Refresh(forceHierarchyUpdate: true);
				// brushes not registered at this point!??


				//DebugEditorWindow.PrintDebugInfo();
				//Selection.objects = generatedGameObjects;
			} else
				UpdateBrushPosition();

			return generatedBrushes != null && generatedBrushes.Length > 0 && generatedBrushes.Length == brushObjectCount;
		}
Beispiel #8
0
    void EditorRegenerate()
    {
        if (transform.childCount == 0)
        {
            Debug.LogError("Leave at least one child element which will be used as a template to generate all other items");
            return;
        }

        var grid = GetComponent <GridLayoutGroup>();

        if (grid == null)
        {
            Debug.LogError("A Grid Layout is required");
            return;
        }

        if (_sourceSprite == null)
        {
            Debug.LogError("Assign a source sprite to generate Palette");
            return;
        }

        int numItemsX = _sourceSprite.texture.width;
        int numItemsY = _sourceSprite.texture.height;

        if ((numItemsX < 1) || (numItemsY < 1))
        {
            Debug.LogError("Assign a source sprite with at least one pixel");
            return;
        }
        if ((numItemsX * numItemsY) > 128)
        {
            Debug.LogError("Too many pixels in source sprite (> 128)");
            return;
        }

        var pixels = _sourceSprite.texture.GetPixels();

        if (pixels == null)
        {
            Debug.LogError("Can't read pixels from source sprite");
            return;
        }

        // Use first item as template
        var itemTransf = transform.GetChild(0);
        var itemSel    = itemTransf.GetComponentInChildren <Selectable>();

        if (itemSel == null)
        {
            Debug.LogError("First child must be a Selectable, it will be used as a template to generate all other items");
            return;
        }

        Debug.LogFormat("Generating {0}x{1} palette", numItemsX, numItemsY);

        Undo.SetCurrentGroupName("Regenerate palette");
        int group = Undo.GetCurrentGroup();

        Undo.RecordObject(gameObject, "Regenerate palette");

        for (int i = transform.childCount - 1; i > 0; --i)
        {
            Undo.DestroyObjectImmediate(transform.GetChild(i).gameObject);
        }

        var rectTransf = (RectTransform)transform;

        grid.constraint      = GridLayoutGroup.Constraint.FixedColumnCount;
        grid.constraintCount = numItemsX;
        grid.cellSize        = new Vector2(
            (rectTransf.rect.width - (numItemsX - 1) * grid.spacing.x - grid.padding.horizontal) / numItemsX,
            (rectTransf.rect.height - (numItemsY - 1) * grid.spacing.y - grid.padding.vertical) / numItemsY);

        // Apply color on original item
        var colors = itemSel.colors;

        colors.normalColor      = pixels[numItemsX * (numItemsY - 1)];
        colors.highlightedColor = colors.normalColor;
        colors.pressedColor     = colors.normalColor;
        itemSel.colors          = colors;

        bool first = true;

        for (int y = (numItemsY - 1); y >= 0; --y)
        {
            int xStart = first ? 1 : 0;
            for (int x = xStart; x < numItemsX; ++x)
            {
                first = false;

                var go  = GameObject.Instantiate(itemTransf.gameObject, transform);
                var sel = go.GetComponentInChildren <Selectable>();
                colors.normalColor      = pixels[x + y * numItemsX];
                colors.highlightedColor = colors.normalColor;
                colors.pressedColor     = colors.normalColor;
                sel.colors = colors;

                Undo.RegisterCreatedObjectUndo(go, "Duplicated palette item");
            }
        }

        Undo.CollapseUndoOperations(group);
    }
        public void Grab(IEnumerable <ITimelineItem> items, TrackAsset referenceTrack, Vector2 mousePosition)
        {
            if (items == null)
            {
                return;
            }

            items = items.ToArray(); // Cache enumeration result

            if (!items.Any())
            {
                return;
            }

            m_GrabbedModalUndoGroup = Undo.GetCurrentGroup();

            var trackItems      = items.GroupBy(c => c.parentTrack).ToArray();
            var trackItemsCount = trackItems.Length;

            movingItems = new MovingItems[trackItemsCount];

            allowTrackSwitch = trackItemsCount == 1 && !trackItems.SelectMany(x => x).Any(x => x is MarkerItem); // For now, track switch is only supported when all items are on the same track and there are no items
            foreach (var item in referenceTrack.GetItems())                                                      // Ripple changes other items
            {
                item.PushUndo("Move Items");
            }

            for (var i = 0; i < trackItemsCount; ++i)
            {
                var track        = trackItems[i].Key;
                var grabbedItems = new MovingItems(m_State, track, trackItems[i].ToArray(), referenceTrack, mousePosition, allowTrackSwitch);
                movingItems[i] = grabbedItems;
            }

            m_LeftMostMovingItems  = null;
            m_RightMostMovingItems = null;

            foreach (var grabbedTrackItems in movingItems)
            {
                if (m_LeftMostMovingItems == null || m_LeftMostMovingItems.start > grabbedTrackItems.start)
                {
                    m_LeftMostMovingItems = grabbedTrackItems;
                }

                if (m_RightMostMovingItems == null || m_RightMostMovingItems.end < grabbedTrackItems.end)
                {
                    m_RightMostMovingItems = grabbedTrackItems;
                }
            }

            m_ItemGUIs   = new HashSet <TimelineItemGUI>();
            m_ItemsGroup = new ItemsGroup(items);

            foreach (var item in items)
            {
                m_ItemGUIs.Add(item.gui);
            }

            targetTrack = referenceTrack;

            EditMode.BeginMove(this);
            m_Grabbing = true;
        }
Beispiel #10
0
        protected override void OnInspectorGUIOverride()
        {
            if (m_deformer == null)
            {
                m_deformer = GetTarget() as MeshDeformer;
            }

            if (m_deformer == null)
            {
                return;
            }

            DoOriginalMeshes();

            EditorGUI.BeginChangeCheck();
            Axis axis = (Axis)EditorGUILayout.EnumPopup("Deformation Axis", m_deformer.Axis);

            if (EditorGUI.EndChangeCheck())
            {
                ChangeAxis(m_deformer, axis);
            }

            EditorGUI.BeginChangeCheck();
            int sliceCount = EditorGUILayout.IntField("Approximation", m_deformer.Approximation);

            if (EditorGUI.EndChangeCheck())
            {
                if (sliceCount > 100)
                {
                    if (!EditorUtility.DisplayDialog("Are you sure", "Are you sure you want to set Approximation = " + sliceCount, "Yes", "No"))
                    {
                        sliceCount = m_deformer.Approximation;
                    }
                }
                Undo.RecordObject(m_deformer, "Battlehub.MeshDeformer.Approximation Changed");
                RecordScaffolds(m_deformer, "Battlehub.MeshDeformer.Approximation Changed");
                EditorUtility.SetDirty(m_deformer);

                Debug.Log("Undo Operations will be Collapsed");
                Undo.CollapseUndoOperations(Undo.GetCurrentGroup());

                m_deformer.Approximation = sliceCount;
            }

            EditorGUI.BeginChangeCheck();
            float spacing = EditorGUILayout.FloatField("Spacing", m_deformer.Spacing);

            if (EditorGUI.EndChangeCheck())
            {
                Undo.RecordObject(m_deformer, "Battlehub.MeshDeformer.Spacing Changed");
                RecordScaffolds(m_deformer, "Battlehub.MeshDeformer.Spacing Changed");
                EditorUtility.SetDirty(m_deformer);
                m_deformer.Spacing = spacing;
            }

            EditorGUI.BeginChangeCheck();
            int curvesPerMesh = EditorGUILayout.IntField("Curves Per Mesh", m_deformer.CurvesPerMesh);

            if (EditorGUI.EndChangeCheck())
            {
                Selection.activeGameObject = m_deformer.gameObject;
                Undo.RecordObject(m_deformer, "Battlehub.MeshDeformer.CurvesPerMesh Changed");
                RecordScaffolds(m_deformer, "Battlehub.MeshDeformer.CurvesPerMesh Changed");
                EditorUtility.SetDirty(m_deformer);
                m_deformer.CurvesPerMesh = curvesPerMesh;
            }

            EditorGUI.BeginChangeCheck();
            bool loop = EditorGUILayout.Toggle("Loop", m_deformer.Loop);

            if (EditorGUI.EndChangeCheck())
            {
                Undo.RecordObject(m_deformer, UNDO_TOGGLELOOP);
                EditorUtility.SetDirty(m_deformer);
                m_deformer.Loop = loop;
            }


            GUILayout.BeginHorizontal();
            {
                if (GUILayout.Button("Append"))
                {
                    Undo.RecordObject(m_deformer, "Battlehub.MeshDeformer.Append");
                    Undo.RegisterCreatedObjectUndo(m_deformer.Append(), "Battlehub.MeshDeformer.Append");
                    EditorUtility.SetDirty(m_deformer);
                }

                if (GUILayout.Button("Prepend"))
                {
                    Undo.RecordObject(m_deformer, "Battlehub.MeshDeformer.Prepend");
                    RecordScaffolds(m_deformer, "Battlehub.MeshDeformer.Prepend");
                    Undo.RegisterCreatedObjectUndo(m_deformer.Prepend(), "Battlehub.MeshDeformer.Prepend");
                    EditorUtility.SetDirty(m_deformer);
                }
            }
            GUILayout.EndHorizontal();
            if (GUILayout.Button("Smooth Spline"))
            {
                Undo.RecordObject(m_deformer, "Battlehub.MeshDeformer.Fit");
                RecordScaffolds(m_deformer, "Battlehub.MeshDeformer.Fit");
                EditorUtility.SetDirty(m_deformer);
                m_deformer.Smooth();
            }

            GUILayout.BeginHorizontal();
            {
                GUILayout.BeginVertical(GUILayout.ExpandWidth(true));
                {
                    if (GUILayout.Button("Set Rigid Mode"))
                    {
                        Undo.RecordObject(m_deformer, "Battlehub.MeshDeformer.SetMode");
                        RecordScaffolds(m_deformer, "Battlehub.MeshDeformer.SetMode");
                        EditorUtility.SetDirty(m_deformer);
                        SetMode(m_deformer, ControlPointMode.Free, true);
                    }

                    if (GUILayout.Button("Set Free Mode"))
                    {
                        Undo.RecordObject(m_deformer, "Battlehub.MeshDeformer.SetMode");
                        RecordScaffolds(m_deformer, "Battlehub.MeshDeformer.SetMode");
                        EditorUtility.SetDirty(m_deformer);
                        SetMode(m_deformer, ControlPointMode.Free, false);
                    }
                }
                GUILayout.EndVertical();
                GUILayout.BeginVertical(GUILayout.ExpandWidth(true));
                {
                    if (GUILayout.Button("Set Aligned Mode"))
                    {
                        Undo.RecordObject(m_deformer, "Battlehub.MeshDeformer.SetMode");
                        RecordScaffolds(m_deformer, "Battlehub.MeshDeformer.SetMode");
                        EditorUtility.SetDirty(m_deformer);
                        SetMode(m_deformer, ControlPointMode.Free, false);
                        SetMode(m_deformer, ControlPointMode.Aligned, false);
                    }

                    if (GUILayout.Button("Set Mirrored Mode"))
                    {
                        Undo.RecordObject(m_deformer, "Battlehub.MeshDeformer.SetMode");
                        RecordScaffolds(m_deformer, "Battlehub.MeshDeformer.SetMode");
                        EditorUtility.SetDirty(m_deformer);
                        SetMode(m_deformer, ControlPointMode.Free, false);
                        SetMode(m_deformer, ControlPointMode.Mirrored, false);
                    }
                }
                GUILayout.EndVertical();
            }
            GUILayout.EndHorizontal();



#if MD_GIZMOS
            EditorGUI.BeginChangeCheck();
            bool drawGizoms = EditorGUILayout.Toggle("Draw Gizmos", m_deformer.DrawGizmos);
            if (EditorGUI.EndChangeCheck())
            {
                Undo.RecordObject(m_deformer, "Battlehub.MeshDeformer.Approximation Changed");
                EditorUtility.SetDirty(m_deformer);
                m_deformer.DrawGizmos = drawGizoms;
            }
#endif
        }
Beispiel #11
0
        /// <summary>
        /// Update the current brush object and weights with the current mouse position.
        /// </summary>
        /// <param name="mousePosition">current mouse position (from Event)</param>
        /// <param name="isDrag">optional, is dragging the mouse cursor</param>
        /// <param name="overridenGO">optional, provides an already selected gameobject (used in unit tests only)</param>
        /// <param name="overridenRay"> optional, provides a ray already created (used in unit tests only)</param>
        internal void UpdateBrush(Vector2 mousePosition, bool isUserHoldingControl = false, bool isUserHoldingShift = false, bool isDrag = false, GameObject overridenGO = null, Ray?overridenRay = null)
        {
            MirrorSettings mirrorSettings = m_BrushMirrorEditor.settings;

            // NOTE: Quick fix for the lockBrushToFirst feature, probably need to refactor
            // some code in order to be able to do it properly
            if (firstGameObject != null && s_LockBrushToFirst)
            {
                Ray mouseRay2 = overridenRay != null ? (Ray)overridenRay : HandleUtility.GUIPointToWorldRay(mousePosition);
                DoMeshRaycast(mouseRay2, brushTarget, mirrorSettings);
                OnBrushMove();
                SceneView.RepaintAll();
                this.Repaint();
                return;
            }

            // Must check HandleUtility.PickGameObject only during MouseMoveEvents or errors will rain.
            GameObject go = null;

            brushTarget = null;

            if (isDrag && s_LockBrushToFirst && m_LastHoveredGameObject != null)
            {
                go          = m_LastHoveredGameObject;
                brushTarget = GetBrushTarget(go);
            }
            else if (s_IgnoreUnselected || isDrag)
            {
                GameObject cur = null;
                int        max = 0;             // safeguard against unforeseen while loop errors crashing unity

                do
                {
                    int tmp;
                    // overloaded PickGameObject ignores array of GameObjects, this is used
                    // when there are non-selected gameObjects between the mouse and selected
                    // gameObjects.
                    cur = overridenGO;
                    if (cur == null)
                    {
                        m_IgnoreDrag.RemoveAll(x => x == null);
                        cur = HandleUtility.PickGameObject(mousePosition, m_IgnoreDrag.ToArray(), out tmp);
                    }

                    if (cur != null)
                    {
                        if (!PolyEditorUtility.InSelection(cur))
                        {
                            if (!m_IgnoreDrag.Contains(cur))
                            {
                                m_IgnoreDrag.Add(cur);
                            }
                        }
                        else
                        {
                            brushTarget = GetBrushTarget(cur);

                            if (brushTarget != null)
                            {
                                go = cur;
                            }
                            else
                            {
                                m_IgnoreDrag.Add(cur);
                            }
                        }
                    }
                } while(go == null && cur != null && max++ < 128);
            }
            else
            {
                go = overridenGO;
                if (go == null)
                {
                    go = HandleUtility.PickGameObject(mousePosition, false);
                }

                if (go != null && PolyEditorUtility.InSelection(go))
                {
                    brushTarget = GetBrushTarget(go);
                }
                else
                {
                    go = null;
                }
            }

            bool mouseHoverTargetChanged = false;
            Ray  mouseRay = overridenRay != null ? (Ray)overridenRay :  HandleUtility.GUIPointToWorldRay(mousePosition);

            // if the mouse hover picked up a valid editable, raycast against that.  otherwise
            // raycast all meshes in selection
            if (go == null)
            {
                foreach (var kvp in m_Hovering)
                {
                    BrushTarget t = kvp.Value;

                    if (Util.IsValid(t) && DoMeshRaycast(mouseRay, t, mirrorSettings))
                    {
                        brushTarget = t;
                        go          = t.gameObject;
                        break;
                    }
                }
            }
            else
            {
                if (!DoMeshRaycast(mouseRay, brushTarget, mirrorSettings))
                {
                    if (!isDrag || !s_LockBrushToFirst)
                    {
                        go          = null;
                        brushTarget = null;
                    }

                    return;
                }
            }

            // if m_Hovering off another gameobject, call OnBrushExit on that last one and mark the
            // target as having been changed
            if (go != m_LastHoveredGameObject)
            {
                OnBrushExit(m_LastHoveredGameObject);
                mouseHoverTargetChanged = true;
                m_LastHoveredGameObject = go;
            }

            SceneView.RepaintAll();
            this.Repaint();

            if (brushTarget == null)
            {
                return;
            }

            if (mouseHoverTargetChanged)
            {
                brushSettings.isUserHoldingControl = isUserHoldingControl;
                brushSettings.isUserHoldingShift   = isUserHoldingShift;

                OnBrushEnter(brushTarget, brushSettings);

                // brush is in use, adding a new object to the undo
                if (m_ApplyingBrush && !m_UndoQueue.Contains(go))
                {
                    int curGroup = Undo.GetCurrentGroup();
                    brushTarget.editableObject.isDirty = true;
                    OnBrushBeginApply(brushTarget, brushSettings);
                    Undo.CollapseUndoOperations(curGroup);
                }
            }

            OnBrushMove();

            SceneView.RepaintAll();
            this.Repaint();
        }
        public static void CreateVisual()
        {
            // Multi-selection and we're receiving one call per selected object
            // but it's not possible to process one object each call when
            // Selection.active* aren't changed - so we're blocking calls for
            // x seconds.
            if (EditorApplication.timeSinceStartup - m_lastCreateVisualCall < 0.5)
            {
                return;
            }

            var objects = Selection.GetFiltered <GameObject>(SelectionMode.Editable | SelectionMode.TopLevel);

            if (objects.Length == 0)
            {
                Debug.Log("Unable to create visual: Selected objects not supported (not editable - such as prefabs).");
                return;
            }

            var validShapes = from go in objects
                              from shape in go.GetComponentsInChildren <Shape>()
                              where !ShapeVisual.HasShapeVisual(shape) &&
                              ShapeVisual.SupportsShapeVisual(shape)
                              select shape;
            var numSensors             = validShapes.Count(shape => shape.IsSensor);
            var createVisualForSensors = validShapes.Count() > 0 &&
                                         numSensors > 0 &&
                                         // Negated when "No" is first (left button)
                                         !EditorUtility.DisplayDialog("Sensors",
                                                                      "There are " +
                                                                      numSensors +
                                                                      " sensors in this object. Would you like to" +
                                                                      " create visuals for sensors as well?",
                                                                      "No",
                                                                      "Yes");

            if (validShapes.Count() > 0 && (createVisualForSensors || numSensors < validShapes.Count()))
            {
                Undo.SetCurrentGroupName("Create GameObject(s) shape visual.");
                var grouId = Undo.GetCurrentGroup();

                foreach (var shape in validShapes)
                {
                    if (shape.IsSensor && !createVisualForSensors)
                    {
                        continue;
                    }

                    var visual = ShapeVisual.Create(shape);
                    if (visual != null)
                    {
                        Undo.RegisterCreatedObjectUndo(visual, "Create visual: " + shape.name);
                    }
                }

                Undo.CollapseUndoOperations(grouId);
            }
            else
            {
                Debug.Log("Create visual ignored: All shapes already have visual data or doesn't support to be visualized.",
                          Selection.activeGameObject);
            }

            m_lastCreateVisualCall = EditorApplication.timeSinceStartup;
        }
    public override void OnInspectorGUI()
    {
        bool doConvert = false;

        base.OnInspectorGUI();

        tk2dGuiUtility.InfoBox("The tk2dAnimatedSprite has been deprecated in favor of the new tk2dSpriteAnimator behaviour. " +
                               "Using this new system will allow you to animate other kinds of sprites, etc. " +
                               "The tk2dAnimatedSprite is now a wrapper to this system, but you can upgrade entirely to the new system " +
                               "if you choose to", tk2dGuiUtility.WarningLevel.Warning);

        GUILayout.Space(8);
        GUI.backgroundColor = Color.red;
        GUILayout.BeginHorizontal();
        GUILayout.FlexibleSpace();
        if (GUILayout.Button("Convert to SpriteAnimator", GUILayout.Width(200)) &&
            EditorUtility.DisplayDialog("Convert to SpriteAnimator",
                                        "Converting to the SpriteAnimator system will require you to manually fix " +
                                        "all references of this tk2dSpriteAnimation.\n\n" +
                                        "Are you sure you wish to proceed?", "Yes", "No"))
        {
            doConvert = true;
        }
        GUILayout.FlexibleSpace();
        GUILayout.EndHorizontal();
        GUI.backgroundColor = Color.white;
        GUILayout.Space(8);

        if (doConvert)
        {
#if UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2
            Undo.RegisterSceneUndo("Convert animated sprite -> sprite animator");
#else
            int undoGroup = Undo.GetCurrentGroup();
#endif

            foreach (Object target in targets)
            {
                tk2dAnimatedSprite animSprite           = target as tk2dAnimatedSprite;
                GameObject         animSpriteGameObject = animSprite.gameObject;
                if (animSprite != null)
                {
                    tk2dSprite sprite = animSprite.gameObject.AddComponent <tk2dSprite>();
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
                    Undo.RegisterCreatedObjectUndo(sprite, "Create Sprite Animator");
#endif
                    sprite.SetSprite(animSprite.Collection, animSprite.spriteId);
                    sprite.color = animSprite.color;
                    sprite.scale = animSprite.scale;
                    // If this is not null, we assume it is already set up properly
                    if (animSprite.GetComponent <tk2dSpriteAnimator>() == null)
                    {
                        tk2dSpriteAnimator spriteAnimator = animSprite.gameObject.AddComponent <tk2dSpriteAnimator>();
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
                        Undo.RegisterCreatedObjectUndo(spriteAnimator, "Create Sprite Animator");
#endif
                        spriteAnimator.Library           = animSprite.Library;
                        spriteAnimator.DefaultClipId     = animSprite.DefaultClipId;
                        spriteAnimator.playAutomatically = animSprite.playAutomatically;
                    }

#if (UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
                    GameObject.DestroyImmediate(animSprite, true);
#else
                    Undo.DestroyObjectImmediate(animSprite);
#endif

                    tk2dUtil.SetDirty(animSpriteGameObject);
                }
            }

#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
            Undo.CollapseUndoOperations(undoGroup);
#endif
        }
    }
Beispiel #14
0
    void OnGUI()
    {
        if (_assetStore.Count == 0)
        {
            BuildLocalAssetStore();
        }
        var bold     = new GUIStyle("label");
        var boldFold = new GUIStyle("foldout");

        bold.fontStyle     = FontStyle.Bold;
        bold.fontSize      = 14;
        boldFold.fontStyle = FontStyle.Bold;
        var someMatched = false;

        using (new Horizontal()) {
            if (GUILayout.Toggle(showMain, "Save Game", "toolbarbutton", GUILayout.ExpandWidth(false)))
            {
                showMain       = true;
                showReferences = false;
                showRoom       = false;
                showMaterials  = false;
            }

            if (GUILayout.Toggle(showMaterials, "Materials", "toolbarbutton", GUILayout.ExpandWidth(false)))
            {
                showMain       = false;
                showReferences = false;
                showRoom       = false;
                showMaterials  = true;
            }

            if (GUILayout.Toggle(showRoom, "Rooms", "toolbarbutton", GUILayout.ExpandWidth(false)))
            {
                showMain       = false;
                showRoom       = true;
                showReferences = false;
                showMaterials  = false;
            }
            if (_assetStore.SelectMany(s => s.Value).All(s => s.Value.Count <= 1))
            {
                GUI.color = Color.white;
            }
            else
            {
                someMatched = true;
                GUI.color   = Color.yellow;
            }

            if (GUILayout.Toggle(showReferences, "References", "toolbarbutton", GUILayout.ExpandWidth(false)))
            {
                showMain       = false;
                showRoom       = false;
                showReferences = true;
                showMaterials  = false;
            }
            GUILayout.Label("", "toolbarbutton");
            GUI.color = Color.white;
        }
        if (showReferences)
        {
            using (new ScrollView(ref scroll)) {
                using (new Vertical()) {
                    foreach (var tp in _assetStore)
                    {
                        if (!open.ContainsKey(tp.Key))
                        {
                            open[tp.Key] = false;
                        }

                        if (tp.Value.Any(v => v.Value.Count > 1))
                        {
                            GUI.color    = Color.yellow;
                            open[tp.Key] = EditorGUILayout.Foldout(open[tp.Key], tp.Key.ToString(), boldFold);
                            GUI.color    = Color.white;
                        }
                        else
                        {
                            open[tp.Key] = EditorGUILayout.Foldout(open[tp.Key], tp.Key.ToString(), "foldout");
                        }
                        if (open[tp.Key])
                        {
                            foreach (var n in tp.Value.OrderByDescending(q => q.Value.Count).ThenBy(q => q.Key))
                            {
                                using (new Horizontal()) {
                                    GUILayout.Space(10);
                                    if (!open.ContainsKey(tp.Key + n.Key))
                                    {
                                        open[tp.Key + n.Key] = false;
                                    }
                                    if (n.Value.Count <= 1)
                                    {
                                        open[tp.Key + n.Key] = false;
                                        if (GUILayout.Button(n.Key, "label"))
                                        {
                                            Selection.activeObject = n.Value[0] as UnityEngine.Object;
                                            EditorGUIUtility.PingObject(n.Value[0] as UnityEngine.Object);
                                        }
                                    }
                                    else
                                    {
                                        open[tp.Key + n.Key] = EditorGUILayout.Foldout(open[tp.Key + n.Key], n.Key + " (" + n.Value.Count + ")", boldFold);
                                    }
                                }
                                if (open[tp.Key + n.Key])
                                {
                                    using (new Vertical()) {
                                        foreach (var i in n.Value.Cast <UnityEngine.Object>())
                                        {
                                            using (new Horizontal()) {
                                                GUILayout.Space(20);
                                                var addOn = "";
                                                if (!AssetDatabase.IsMainAsset(i) && !AssetDatabase.IsSubAsset(i))
                                                {
                                                    GUI.color = Color.red;
                                                    addOn     = " (internal to Unity)";
                                                }
                                                else
                                                {
                                                    GUI.color = Color.white;
                                                }
                                                if (GUILayout.Button(i.name.ToString() + addOn, "label"))
                                                {
                                                    Selection.activeObject = i as UnityEngine.Object;
                                                    EditorGUIUtility.PingObject(i);
                                                }
                                                GUI.color = Color.white;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if (someMatched)
            {
                var style = new GUIStyle("label");
                style.wordWrap = true;

                GUILayout.Space(5);
                GUI.color = Color.yellow;
                GUILayout.Label("Warning", bold);
                GUI.color = Color.white;
                GUILayout.Label("Some referencable items have the same name. This is only a problem if you actually refer to one of the items in a saved variable and then more get added with the same name (existing saved games may load the wrong instance), or if for some other reason Unity reorders the similarly named items.  If you use a highlighted item as a reference it may be worth renaming it to be a unique name if you can.", style);
                GUILayout.Space(5);
            }
        }

        if (showMain)
        {
            GUILayout.BeginVertical();
            if (Selection.gameObjects.Length == 1)
            {
                if (Selection.activeGameObject != null)
                {
                    GUILayout.Space(8);
                    using (new HorizontalCentered()) {
                        GUILayout.Label(Selection.activeGameObject.name, bold);
                    }
                    using (new HorizontalCentered()) {
                        GUI.color = new Color(0.8f, 1f, 0.8f, 1);

                        if (Has(Selection.activeGameObject, typeof(UniqueIdentifier)))
                        {
                            GUILayout.Label("Uniquely Identified");
                        }
                        else if (Has(Selection.activeGameObject, typeof(StoreInformation)))
                        {
                            GUILayout.Label("Storing Information");
                        }
                        else if (Has(Selection.activeGameObject, typeof(PrefabIdentifier)))
                        {
                            GUILayout.Label("Prefab Identifier");
                        }
                        else
                        {
                            GUI.color = Color.gray;
                            GUILayout.Label("Nothing stored");
                        }
                        if (Has(Selection.activeGameObject, typeof(StoreMaterials)))
                        {
                            GUILayout.Label(" + materials");
                        }
                        if (Has(Selection.activeGameObject, typeof(StoreMesh)))
                        {
                            GUILayout.Label(" + mesh");
                        }
                        if (Has(Selection.activeGameObject, typeof(StoreAnimator)))
                        {
                            GUILayout.Label(" + animator");
                        }
                    }
                    GUILayout.Space(4);
                    GUI.color = Color.white;
                    using (new HorizontalCentered()) {
                        using (new Vertical()) {
                            using (new Horizontal()) {
                                if (!Has(Selection.activeGameObject, typeof(UniqueIdentifier)) && GUILayout.Button("Unique Identifier"))
                                {
                                    Undo.RecordObject(Selection.activeGameObject, "usng: Add unique identifier");
                                    AddUndo(typeof(UniqueIdentifier), Selection.activeGameObject);
                                }
                                if (!Has(Selection.activeGameObject, typeof(StoreInformation)) && GUILayout.Button("Store Information"))
                                {
                                    Undo.RecordObject(Selection.activeGameObject, "usng: Store information");
                                    AddUndo(typeof(StoreInformation), Selection.activeGameObject);
                                }
                                if (Selection.activeGameObject.GetComponent <StoreMaterials>() == null && Selection.activeGameObject.GetComponent <StoreInformation>() != null)
                                {
                                    if (GUILayout.Button("Store Materials"))
                                    {
                                        Undo.RecordObject(Selection.activeGameObject, "usng: Store materials");
                                        Undo.AddComponent <StoreMaterials>(Selection.activeGameObject);
                                    }
                                }
                            }
                            using (new Horizontal()) {
                                if (Selection.activeGameObject.GetComponent <StoreMesh>() == null && Selection.activeGameObject.GetComponent <StoreInformation>() != null && (Selection.activeGameObject.GetComponent <MeshFilter>() != null || Selection.activeGameObject.GetComponent <SkinnedMeshRenderer>() != null))
                                {
                                    if (GUILayout.Button("Store Mesh"))
                                    {
                                        Undo.RecordObject(Selection.activeGameObject, "usng: Store mesh");
                                        Undo.AddComponent <StoreMesh>(Selection.activeGameObject);
                                    }
                                }
                                if (Selection.activeGameObject.GetComponent <StoreAnimator>() == null && Selection.activeGameObject.GetComponent <StoreInformation>() != null && Selection.activeGameObject.GetComponent <Animator>() != null)
                                {
                                    if (GUILayout.Button("Store Animator"))
                                    {
                                        Undo.RecordObject(Selection.activeGameObject, "usng: Store animator");
                                        Undo.AddComponent <StoreAnimator>(Selection.activeGameObject);
                                    }
                                }
                            }
                            using (new Horizontal()) {
                                if (!Has(Selection.activeGameObject, typeof(PrefabIdentifier)) && PrefabUtility.GetPrefabType(Selection.activeGameObject) != PrefabType.None && GUILayout.Button("Prefab Identifier"))
                                {
                                    Undo.RecordObject(Selection.activeGameObject, "usng: Add prefab identifier");
                                    AddUndo(typeof(PrefabIdentifier), Selection.activeGameObject);
                                    PrefabUtility.ReplacePrefab(Selection.activeGameObject, PrefabUtility.GetPrefabParent(Selection.activeGameObject), ReplacePrefabOptions.ConnectToPrefab);
                                }
                                GUI.color = new Color(0.9f, 0.5f, 0.5f);
                                if (GUILayout.Button("Remove"))
                                {
                                    int group = Undo.GetCurrentGroup();
                                    Undo.IncrementCurrentGroup();

                                    Undo.RecordObject(Selection.activeGameObject, "usng: Remove components");
                                    foreach (var c in Selection.activeGameObject.GetComponents <UniqueIdentifier>())
                                    {
                                        Undo.DestroyObjectImmediate(c);
                                    }
                                    foreach (var c in Selection.activeGameObject.GetComponents <StoreMaterials>())
                                    {
                                        Undo.DestroyObjectImmediate(c);
                                    }
                                    foreach (var c in Selection.activeGameObject.GetComponents <StoreMesh>())
                                    {
                                        Undo.DestroyObjectImmediate(c);
                                    }
                                    foreach (var c in Selection.activeGameObject.GetComponents <StoreAnimator>())
                                    {
                                        Undo.DestroyObjectImmediate(c);
                                    }

                                    Undo.CollapseUndoOperations(group);
                                }
                                GUI.color = Color.white;
                            }
                        }
                    }
                    GUILayout.Space(12);
                    if (Selection.activeGameObject.transform.Cast <Transform>().Count() > 0)
                    {
                        using (new HorizontalCentered()) {
                            GUILayout.Label(Selection.activeGameObject.name, bold);
                            bold.fontStyle = FontStyle.Italic;
                            GUILayout.Label("+ Children", bold);
                        }
                        GUILayout.Space(6);
                        using (new HorizontalCentered()) {
                            using (new Vertical()) {
                                using (new Horizontal()) {
                                    if (GUILayout.Button("Unique Identifier"))
                                    {
                                        GameObject[] objects = Selection.activeGameObject.GetAllComponentsInChildren <Transform>().Select(t => t.gameObject).Where(g => !Has(g, typeof(UniqueIdentifier))).ToArray();
                                        int          group   = Undo.GetCurrentGroup();
                                        Undo.IncrementCurrentGroup();

                                        Undo.RecordObjects(objects, "usng: Add unique identifiers");
                                        foreach (var c in objects)
                                        {
                                            AddUndo(typeof(UniqueIdentifier), c);
                                        }
                                        Undo.CollapseUndoOperations(group);
                                    }
                                    if (GUILayout.Button("Store Information"))
                                    {
                                        GameObject[] objects = Selection.activeGameObject.GetAllComponentsInChildren <Transform>().Select(t => t.gameObject).Where(g => !Has(g, typeof(StoreInformation))).ToArray();
                                        int          group   = Undo.GetCurrentGroup();
                                        Undo.IncrementCurrentGroup();

                                        Undo.RecordObjects(objects, "usng: Store information of objects");
                                        foreach (var c in objects)
                                        {
                                            AddUndo(typeof(StoreInformation), c);
                                        }
                                        Undo.CollapseUndoOperations(group);
                                    }
                                }
                                GUI.color = new Color(0.9f, 0.5f, 0.5f);
                                if (GUILayout.Button("Remove All"))
                                {
                                    int group = Undo.GetCurrentGroup();
                                    Undo.IncrementCurrentGroup();

                                    while (Selection.activeGameObject.GetAllComponentsInChildren <UniqueIdentifier>().Length > 0)
                                    {
                                        Undo.RecordObject(Selection.activeGameObject.GetAllComponentsInChildren <UniqueIdentifier>()[0], "usng: Remove all");
                                        Undo.DestroyObjectImmediate(Selection.activeGameObject.GetAllComponentsInChildren <UniqueIdentifier>()[0]);
                                    }
                                    while (Selection.activeGameObject.GetAllComponentsInChildren <StoreMaterials>().Length > 0)
                                    {
                                        Undo.RecordObject(Selection.activeGameObject.GetAllComponentsInChildren <StoreMaterials>()[0], "usng: Remove all");
                                        Undo.DestroyObjectImmediate(Selection.activeGameObject.GetAllComponentsInChildren <StoreMaterials>()[0]);
                                    }
                                    while (Selection.activeGameObject.GetAllComponentsInChildren <StoreMesh>().Length > 0)
                                    {
                                        Undo.RecordObject(Selection.activeGameObject.GetAllComponentsInChildren <StoreMesh>()[0], "usng: Remove all");
                                        Undo.DestroyObjectImmediate(Selection.activeGameObject.GetAllComponentsInChildren <StoreMesh>()[0]);
                                    }
                                    while (Selection.activeGameObject.GetAllComponentsInChildren <StoreAnimator>().Length > 0)
                                    {
                                        Undo.RecordObject(Selection.activeGameObject.GetAllComponentsInChildren <StoreAnimator>()[0], "usng: Remove all");
                                        Undo.DestroyObjectImmediate(Selection.activeGameObject.GetAllComponentsInChildren <StoreAnimator>()[0]);
                                    }

                                    Undo.CollapseUndoOperations(group);
                                }
                                GUI.color = Color.white;
                            }
                        }
                    }
                }
            }
            else if (Selection.gameObjects.Length > 0)
            {
                using (new HorizontalCentered()) {
                    GUILayout.Label("Selected Objects", bold);
                }
                GUILayout.Space(6);
                using (new HorizontalCentered()) {
                    using (new Vertical()) {
                        using (new Horizontal()) {
                            if (GUILayout.Button("Unique Identifier"))
                            {
                                int group = Undo.GetCurrentGroup();
                                Undo.IncrementCurrentGroup();

                                Undo.RecordObjects(Selection.gameObjects, "usng: Add unique identifiers");
                                foreach (var c in Selection.gameObjects)
                                {
                                    AddUndo(typeof(UniqueIdentifier), c);
                                }
                                Undo.CollapseUndoOperations(group);
                            }
                            if (GUILayout.Button("Store Information"))
                            {
                                int group = Undo.GetCurrentGroup();
                                Undo.IncrementCurrentGroup();

                                Undo.RecordObjects(Selection.gameObjects, "usng: Store information of objects");
                                foreach (var c in Selection.gameObjects)
                                {
                                    AddUndo(typeof(StoreInformation), c);
                                }
                                Undo.CollapseUndoOperations(group);
                            }
                        }
                        using (new Horizontal()) {
                            if (GUILayout.Button("Store Materials"))
                            {
                                GameObject[] objects = Selection.gameObjects.Where(g => g.GetComponent <StoreMaterials>() == null && g.GetComponent <Renderer>() != null).ToArray();
                                int          group   = Undo.GetCurrentGroup();
                                Undo.IncrementCurrentGroup();

                                Undo.RecordObjects(objects, "usng: Store materials of objects");
                                foreach (var c in objects)
                                {
                                    Undo.AddComponent <StoreMaterials>(c);
                                }
                                Undo.CollapseUndoOperations(group);
                            }
                            GUI.color = new Color(0.9f, 0.5f, 0.5f);
                            if (GUILayout.Button("Remove All"))
                            {
                                int group = Undo.GetCurrentGroup();
                                Undo.IncrementCurrentGroup();

                                while (Selection.gameObjects.Cast <GameObject>().SelectMany(s => s.GetAllComponentsInChildren <UniqueIdentifier>()).Count() > 0)
                                {
                                    var obj = Selection.gameObjects.Cast <GameObject>().SelectMany(s => s.GetAllComponentsInChildren <UniqueIdentifier>()).First();
                                    Undo.RecordObject(obj, "usng: Remove all");
                                    Undo.DestroyObjectImmediate(obj);
                                }

                                Undo.CollapseUndoOperations(group);
                            }
                            GUI.color = Color.white;
                        }
                    }
                }
            }
            GUILayout.FlexibleSpace();
            if (GameObject.FindObjectsOfType <SaveGameManager>().Length == 0)
            {
                GUI.color = new Color(1, 0.6f, 0.6f, 1f);
                var style = new GUIStyle("label");
                style.wordWrap = true;
                GUILayout.Label("You need to assign a Save Game Manager script to an object in this scene.  This object should be something that ISN'T loaded and saved with one of the scripts, and NOT set to DontDestroyOnLoad.", style);
                GUILayout.Space(6);
                GUI.color = Color.white;
                using (new Horizontal()) {
                    if (Selection.activeGameObject != null && GUILayout.Button("Assign Save Game Manager"))
                    {
                        Undo.RecordObject(Selection.activeGameObject, "usng: Assign save game manager");
                        Undo.AddComponent <SaveGameManager>(Selection.activeGameObject);
                    }
                    if (GUILayout.Button("Create a new Save Game Manager"))
                    {
                        var go = new GameObject();
                        Undo.RegisterCreatedObjectUndo(go, "usng: Create save game manager");
                        go.name = "Save Game Manager";
                        go.AddComponent <SaveGameManager>();
                    }
                }
                GUILayout.Space(15);
            }



            GUILayout.Label("Maintenance");
            using (new Horizontal()) {
                if (GUILayout.Button("Delete all saved games"))
                {
                    if (EditorUtility.DisplayDialog("Delete Saved Games",
                                                    "Are you sure you want to delete all of the saved games?", "Yes", "No"))
                    {
                        LevelSerializer.SavedGames.Clear();
                        LevelSerializer.ClearCheckpoint(true);
                        LevelSerializer.SaveDataToFilePrefs();
                    }
                }
                if (GameObject.FindObjectsOfType(typeof(SaveGameManager)).Length != 0 && GUILayout.Button("Capture All Objects"))
                {
                    EditorApplication.isPlaying = true;
                    stopWhenReady = 50;
                }
            }
            GUILayout.Space(8);
            using (new Horizontal()) {
                GUILayout.Label(string.Format("Tracked Scene Items: {0:#,0}", UniqueIdentifier.AllIdentifiers.Count));
                var old = drawInfo;
                drawInfo = GUILayout.Toggle(drawInfo, "Hierarchy markers");
                if (old != drawInfo)
                {
                    EditorApplication.RepaintHierarchyWindow();
                    EditorPrefs.SetBool("UnitySerializer.drawHierarchy", drawInfo);
                }
            }
            GUILayout.Space(4);
            GUILayout.EndVertical();
        }

        if (showRoom)
        {
            GUILayout.BeginVertical();
            if (GameObject.FindObjectOfType <Room>())
            {
                if (Selection.gameObjects.Length == 1)
                {
                    if (Selection.activeGameObject != null)
                    {
                        GUILayout.Space(8);
                        using (new HorizontalCentered()) {
                            GUILayout.Label(Selection.activeGameObject.name, bold);
                        }
                        using (new HorizontalCentered()) {
                            GUI.color = new Color(0.8f, 1f, 0.8f, 1);

                            if (Selection.activeGameObject.GetComponent <DontStoreObjectInRoom>())
                            {
                                GUILayout.Label(Has(Selection.activeGameObject, typeof(StoreInformation)) ? "Stored in the save game but not stored in the room state" : "Not saved but flagged for exclusion anyway.");
                            }
                            else if (Has(Selection.activeGameObject, typeof(StoreInformation)))
                            {
                                GUILayout.Label("Stored in the saved game and the room");
                            }
                        }
                        GUILayout.Space(4);
                        GUI.color = Color.white;
                        using (new HorizontalCentered()) {
                            using (new Vertical()) {
                                using (new Horizontal()) {
                                    if (!Selection.activeGameObject.GetComponent <DontStoreObjectInRoom>() && GUILayout.Button("Exclude from room"))
                                    {
                                        Undo.RecordObject(Selection.activeGameObject, "usng: Exclude from room");
                                        AddUndo(typeof(DontStoreObjectInRoom), Selection.activeGameObject);
                                    }
                                }
                                GUI.color = new Color(0.9f, 0.5f, 0.5f);
                                if (GUILayout.Button("Remove"))
                                {
                                    Undo.RecordObject(Selection.activeGameObject, "usng: Remove (room)");
                                    foreach (var c in Selection.activeGameObject.GetComponents <DontStoreObjectInRoom>())
                                    {
                                        Undo.DestroyObjectImmediate(c);
                                    }
                                }
                                GUI.color = Color.white;
                            }
                        }
                        GUILayout.Space(12);
                        if (Selection.activeGameObject.transform.Cast <Transform>().Count() > 0)
                        {
                            using (new HorizontalCentered()) {
                                GUILayout.Label(Selection.activeGameObject.name, bold);
                                bold.fontStyle = FontStyle.Italic;
                                GUILayout.Label("+ Children", bold);
                            }
                            GUILayout.Space(6);
                            using (new HorizontalCentered()) {
                                using (new Vertical()) {
                                    using (new Horizontal()) {
                                        if (GUILayout.Button("Exclude from room"))
                                        {
                                            int group = Undo.GetCurrentGroup();
                                            Undo.IncrementCurrentGroup();

                                            var objects = Selection.activeGameObject.GetAllComponentsInChildren <Transform>().Select(t => t.gameObject).Where(g => !g.GetComponent <DontStoreObjectInRoom>()).ToArray();
                                            Undo.RecordObjects(objects, "usng: Exclude from room");
                                            foreach (var c in Selection.activeGameObject.GetAllComponentsInChildren <Transform>().Select(t => t.gameObject).Where(g => !g.GetComponent <DontStoreObjectInRoom>()))
                                            {
                                                AddUndo(typeof(DontStoreObjectInRoom), c);
                                            }

                                            Undo.CollapseUndoOperations(group);
                                        }

                                        GUI.color = new Color(0.9f, 0.5f, 0.5f);
                                        if (GUILayout.Button("Remove"))
                                        {
                                            int group = Undo.GetCurrentGroup();
                                            Undo.IncrementCurrentGroup();

                                            for (int i = 0; i < Selection.activeGameObject.GetAllComponentsInChildren <DontStoreObjectInRoom>().Length; i++)
                                            {
                                                Undo.RecordObject(Selection.activeGameObject.GetAllComponentsInChildren <DontStoreObjectInRoom>()[i], "unsg: Remove room scripts");
                                                Undo.DestroyObjectImmediate(Selection.activeGameObject.GetAllComponentsInChildren <DontStoreObjectInRoom>()[i]);
                                            }

                                            Undo.CollapseUndoOperations(group);
                                        }
                                        GUI.color = Color.white;
                                    }
                                }
                            }
                        }
                    }
                }
                else if (Selection.gameObjects.Length > 0)
                {
                    using (new HorizontalCentered()) {
                        GUILayout.Label("Selected Objects", bold);
                    }
                    GUILayout.Space(6);
                    using (new HorizontalCentered()) {
                        using (new Vertical()) {
                            using (new Horizontal()) {
                                if (GUILayout.Button("Exlude from room"))
                                {
                                    int group = Undo.GetCurrentGroup();
                                    Undo.IncrementCurrentGroup();
                                    var objects = Selection.gameObjects.Where(g => !g.GetComponent <DontStoreObjectInRoom>()).ToArray();

                                    Undo.RecordObjects(objects, "undo: Exclude from room");
                                    foreach (var c in objects)
                                    {
                                        AddUndo(typeof(DontStoreObjectInRoom), c);
                                    }

                                    Undo.CollapseUndoOperations(group);
                                }
                            }
                            using (new Horizontal()) {
                                GUI.color = new Color(0.9f, 0.5f, 0.5f);
                                if (GUILayout.Button("Remove"))
                                {
                                    int group = Undo.GetCurrentGroup();
                                    Undo.IncrementCurrentGroup();

                                    while (Selection.gameObjects.Cast <GameObject>().SelectMany(s => s.GetAllComponentsInChildren <DontStoreObjectInRoom>()).Count() > 0)
                                    {
                                        Undo.RecordObject(Selection.gameObjects.Cast <GameObject>().SelectMany(s => s.GetAllComponentsInChildren <DontStoreObjectInRoom>()).First(), "usng: Remove room");
                                        Undo.DestroyObjectImmediate(Selection.gameObjects.Cast <GameObject>().SelectMany(s => s.GetAllComponentsInChildren <DontStoreObjectInRoom>()).First());
                                    }

                                    Undo.CollapseUndoOperations(group);
                                }
                                GUI.color = Color.white;
                            }
                        }
                    }
                }
            }
            else
            {
                GUI.color = new Color(1, 0.6f, 0.6f, 1f);
                var style = new GUIStyle("label");
                style.wordWrap = true;
                GUILayout.Label("You need to assign a Room Manager script to an object in this scene.  This object should be something that IS loaded and saved with one of the scripts, and NOT set to DontDestroyOnLoad.", style);
                GUILayout.Space(6);
                GUI.color = Color.white;
                using (new Horizontal()) {
                    if (GUILayout.Button("Create a new Room Manager"))
                    {
                        var go    = new GameObject("Room Manager");
                        int group = Undo.GetCurrentGroup();
                        Undo.RegisterCreatedObjectUndo(go, "usng: Create room manager");

                        if (!FindObjectOfType <SaveGameManager>())
                        {
                            var manager = new GameObject("Save Game Manager");
                            Undo.RegisterCreatedObjectUndo(manager, "usng: Create room manager");
                            manager.AddComponent <SaveGameManager>();
                        }
                        Undo.CollapseUndoOperations(group);

                        go.AddComponent <StoreInformation>();
                        go.AddComponent <RoomDataSaveGameStorage>();
                        go.AddComponent <Room>();
                    }
                }
                GUILayout.Space(15);
            }



            GUILayout.Label("Maintenance");
            using (new Horizontal()) {
                if (GUILayout.Button("Delete all saved games"))
                {
                    if (EditorUtility.DisplayDialog("Delete Saved Games",
                                                    "Are you sure you want to delete all of the saved games?", "Yes", "No"))
                    {
                        LevelSerializer.SavedGames.Clear();
                        LevelSerializer.ClearCheckpoint(true);
                        LevelSerializer.SaveDataToFilePrefs();
                    }
                }
                if (GameObject.FindObjectsOfType(typeof(SaveGameManager)).Length != 0 && GUILayout.Button("Capture All Objects"))
                {
                    EditorApplication.isPlaying = true;
                    stopWhenReady = 50;
                }
            }
            GUILayout.Space(8);
            using (new Horizontal()) {
                GUILayout.Label(string.Format("Tracked Scene Items: {0:#,0}", UniqueIdentifier.AllIdentifiers.Count));
                var old = drawInfo;
                drawInfo = GUILayout.Toggle(drawInfo, "Hierarchy markers");
                if (old != drawInfo)
                {
                    EditorApplication.RepaintHierarchyWindow();
                    EditorPrefs.SetBool("UnitySerializer.drawHierarchy", drawInfo);
                }
            }
            GUILayout.Space(4);
            GUILayout.EndVertical();
        }

        if (showMaterials)
        {
            EditorGUILayout.BeginHorizontal();
            {
                EditorGUILayout.LabelField("Current status:");
                Color c = GUI.color;
                GUI.color = StoreMaterials.Dirty ? Color.red : Color.green;
                EditorGUILayout.LabelField(StoreMaterials.Dirty ? "Dirty" : "Clean", EditorStyles.boldLabel);
                GUI.color = c;
            }
            EditorGUILayout.EndHorizontal();
            EditorGUILayout.BeginHorizontal();
            {
                EditorGUILayout.LabelField("Shader count:");
                EditorGUILayout.LabelField(StoreMaterials.ShaderCount.ToString());
            }
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();
            {
                EditorGUILayout.LabelField("Property count:");
                EditorGUILayout.LabelField(StoreMaterials.PropertyCount.ToString());
            }
            EditorGUILayout.EndHorizontal();


            EditorGUILayout.HelpBox("Make sure that there are no inactive root-objects that are supposed to have their materials stored when using minimal generation. This wizard will not be able to discover them!"
                                    , MessageType.Warning);

            if (GUILayout.Button("Generate minimal"))
            {
                EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene());
                if (EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo())
                {
                    ShaderDBGenerator.GenerateShaderDB();

                    AssetDatabase.Refresh();
                }

                StoreMaterials.Dirty = false;
            }

            EditorGUILayout.Space();
            EditorGUILayout.HelpBox("Make sure that you have added the builtin shaders for your Unity version when using full generation. They can be found on the Unity website."
                                    , MessageType.Warning);

            if (GUILayout.Button("Generate full (slow!)"))
            {
                ShaderDBGenerator.GenerateFullShaderDB();
                AssetDatabase.Refresh();

                StoreMaterials.Dirty = false;
            }
        }
        Repaint();
    }
    /// <summary>
    /// Draws the Director GUI
    /// </summary>
    protected void OnGUI()
    {
        scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition);
        {
            txtCutsceneName = EditorGUILayout.TextField(NameContentCutscene, txtCutsceneName);
            EditorGUILayout.BeginHorizontal();
            txtDuration = EditorGUILayout.FloatField(DurationContentCutscene, txtDuration);
            timeEnum    = (DirectorHelper.TimeEnum)EditorGUILayout.EnumPopup(timeEnum);
            EditorGUILayout.EndHorizontal();

            isLooping   = EditorGUILayout.Toggle(LoopingContentCutscene, isLooping);
            isSkippable = EditorGUILayout.Toggle(SkippableContentCutscene, isSkippable);
            StartMethod = (StartMethod)EditorGUILayout.EnumPopup(new GUIContent("开始方法"), StartMethod);

            EditorGUILayout.Space();
            EditorGUILayout.LabelField("轨道组", EditorStyles.boldLabel);

            // Director Group
            directorTrackGroupsSelection = EditorGUILayout.Popup(AddDirectorGroupContent, directorTrackGroupsSelection, intValues1.ToArray());

            if (directorTrackGroupsSelection > 0)
            {
                EditorGUI.indentLevel++;

                // Shot Tracks
                shotTrackSelection = EditorGUILayout.Popup(AddShotTracksContent, shotTrackSelection, intValues1.ToArray());

                // Audio Tracks
                audioTrackSelection = EditorGUILayout.Popup(AddAudioTracksContent, audioTrackSelection, intValues4.ToArray());

                // Global Item Tracks
                globalItemTrackSelection = EditorGUILayout.Popup(AddGlobalTracksContent, globalItemTrackSelection, intValues10.ToArray());

                EditorGUI.indentLevel--;
            }

            EditorGUILayout.Space();

            // Actor Track Groups
            int actorCount = EditorGUILayout.Popup(new GUIContent("主角轨道群组"), actorTrackGroupsSelection, intValues10.ToArray());

            if (actorCount != actorTrackGroupsSelection)
            {
                actorTrackGroupsSelection = actorCount;

                Transform[] tempActors = new Transform[actors.Length];
                Array.Copy(actors, tempActors, actors.Length);

                actors = new Transform[actorCount];
                int amount = Math.Min(actorCount, tempActors.Length);
                Array.Copy(tempActors, actors, amount);
            }

            EditorGUI.indentLevel++;
            for (int i = 1; i <= actorTrackGroupsSelection; i++)
            {
                actors[i - 1] = EditorGUILayout.ObjectField(new GUIContent(string.Format("主角 {0}", i)), actors[i - 1], typeof(Transform), true) as Transform;
            }
            EditorGUI.indentLevel--;

            EditorGUILayout.Space();
            // Multi Actor Track Groups
            multiActorTrackGroupsSelection = EditorGUILayout.Popup(new GUIContent("多主角轨道群组"), multiActorTrackGroupsSelection, intValues10.ToArray());
            EditorGUI.indentLevel++;
            EditorGUI.indentLevel--;
            Add(ref characters, ref characterTrackGroupsSelection, "ActorTrackGroups");
            for (int i = 1; i <= characterTrackGroupsSelection; i++)
            {
                characters[i - 1] = EditorGUILayout.ObjectField(new GUIContent(string.Format("角色 {0}", i)), characters[i - 1], typeof(Transform), true) as Transform;
            }
            EditorGUI.indentLevel--;
        }

        EditorGUILayout.EndScrollView();

        EditorGUILayout.BeginHorizontal();
        {
            if (GUILayout.Button("I'm Feeling Lucky"))
            {
                List <Transform> interestingActors = UnitySceneEvaluator.GetHighestRankedGameObjects(10);

                actorTrackGroupsSelection = interestingActors.Count;
                actors = interestingActors.ToArray();
            }

            if (GUILayout.Button("创建剧情"))
            {
                string cutsceneName = DirectorHelper.getCutsceneItemName(txtCutsceneName, typeof(Cutscene));

                GameObject cutsceneGO = new GameObject(cutsceneName);
                Cutscene   cutscene   = cutsceneGO.AddComponent <Cutscene>();
                for (int i = 0; i < directorTrackGroupsSelection; i++)
                {
                    DirectorGroup dg = CutsceneItemFactory.CreateDirectorGroup(cutscene);
                    dg.Ordinal = 0;
                    for (int j = 0; j < shotTrackSelection; j++)
                    {
                        CutsceneItemFactory.CreateShotTrack(dg);
                    }
                    for (int j = 0; j < audioTrackSelection; j++)
                    {
                        CutsceneItemFactory.CreateAudioTrack(dg);
                    }
                    for (int j = 0; j < globalItemTrackSelection; j++)
                    {
                        CutsceneItemFactory.CreateGlobalItemTrack(dg);
                    }
                }

                for (int i = 0; i < actorTrackGroupsSelection; i++)
                {
                    CutsceneItemFactory.CreateActorTrackGroup(cutscene, actors[i]);
                }

                for (int i = 0; i < multiActorTrackGroupsSelection; i++)
                {
                    CutsceneItemFactory.CreateMultiActorTrackGroup(cutscene);
                }

                for (int i = 0; i < characterTrackGroupsSelection; i++)
                {
                    CutsceneItemFactory.CreateCharacterTrackGroup(cutscene, characters[i]);
                }
                float duration = txtDuration;
                if (timeEnum == DirectorHelper.TimeEnum.Minutes)
                {
                    duration *= 60;
                }
                cutscene.Duration = duration;

                int undoIndex = Undo.GetCurrentGroup();

                if (StartMethod != StartMethod.None)
                {
                    GameObject      cutsceneTriggerGO = new GameObject("Cutscene Trigger");
                    CutsceneTrigger cutsceneTrigger   = cutsceneTriggerGO.AddComponent <CutsceneTrigger>();
                    if (StartMethod == StartMethod.OnTrigger)
                    {
                        cutsceneTriggerGO.AddComponent <BoxCollider>();
                    }
                    cutsceneTrigger.StartMethod = StartMethod;
                    cutsceneTrigger.Cutscene    = cutscene;
                    Undo.RegisterCreatedObjectUndo(cutsceneTriggerGO, string.Format("Created {0}", txtCutsceneName));
                }

                Undo.RegisterCreatedObjectUndo(cutsceneGO, string.Format("Created {0}", txtCutsceneName));
                Undo.CollapseUndoOperations(undoIndex);
                Selection.activeTransform = cutsceneGO.transform;
            }
        }
        EditorGUILayout.EndHorizontal();
    }
Beispiel #16
0
 public RecordDisposer(UnityEngine.Object[] objects, string msg)
 {
     Undo.IncrementCurrentGroup();
     _group = Undo.GetCurrentGroup();
     Undo.RecordObjects(objects, msg);
 }
        public override void OnInspectorGUI()
        {
            GUILayout.BeginVertical(GUI.skin.box);
            {
                GUILayout.Label("A hidden CSG model, and all it's brushes and operations, is contained by this object. This will automatically be removed at build time.", GUIStyleUtility.wrapLabel);
                GUILayout.Space(10);
                if (GUILayout.Button("Revert back to CSG model"))
                {
                    Undo.IncrementCurrentGroup();
                    var groupIndex = Undo.GetCurrentGroup();
                    Undo.SetCurrentGroupName("Reverted to former CSG model");
                    try
                    {
                        var selection    = new List <UnityEngine.Object>();
                        var updateScenes = new HashSet <Scene>();
                        foreach (var target in targets)
                        {
                            var exportedModel = target as CSGModelExported;
                            if (!exportedModel)
                            {
                                continue;
                            }

                            exportedModel.disarm    = true;
                            exportedModel.hideFlags = HideFlags.DontSaveInBuild;
                            updateScenes.Add(exportedModel.gameObject.scene);
                            if (exportedModel.containedModel)
                            {
                                Undo.RecordObject(exportedModel.containedModel, "Revert model");
                                selection.Add(exportedModel.containedModel.gameObject);
                                exportedModel.containedModel.transform.SetParent(exportedModel.transform.parent, true);
                                exportedModel.containedModel.transform.SetSiblingIndex(exportedModel.transform.GetSiblingIndex());
                                exportedModel.containedModel.gameObject.SetActive(true);
                                exportedModel.containedModel.gameObject.hideFlags = HideFlags.None;
                                EditorUtility.SetDirty(exportedModel.containedModel);
                                Undo.DestroyObjectImmediate(exportedModel);
                            }
                            else
                            {
                                MeshInstanceManager.ReverseExport(exportedModel);
                                selection.Add(exportedModel.gameObject);
                                EditorUtility.SetDirty(exportedModel);
                                Undo.DestroyObjectImmediate(exportedModel);
                            }
                        }
                        Selection.objects = selection.ToArray();

                        InternalCSGModelManager.skipRefresh = true;

                        BrushOutlineManager.ClearOutlines();
                        //CSGModelManager.Refresh(forceHierarchyUpdate: true);
                        InternalCSGModelManager.Rebuild();
                        foreach (var scene in updateScenes)
                        {
                            UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty(scene);
                        }
                    }
                    finally
                    {
                        InternalCSGModelManager.skipRefresh = false;
                        Undo.CollapseUndoOperations(groupIndex);
                    }
                }
            }
            GUILayout.Space(30);
            if (GUILayout.Button("Remove hidden CSG model"))
            {
                Undo.IncrementCurrentGroup();
                var groupIndex = Undo.GetCurrentGroup();
                Undo.SetCurrentGroupName("Removed hidden CSG model");
                Undo.RecordObject(this, "Removed hidden CSG model");
                foreach (var target in targets)
                {
                    var exportedModel = target as CSGModelExported;
                    if (!exportedModel)
                    {
                        continue;
                    }
                    exportedModel.DestroyModel(undoable: true);
                    Undo.DestroyObjectImmediate(exportedModel);
                }
                Undo.CollapseUndoOperations(groupIndex);
            }
            GUILayout.Space(10);
            GUILayout.EndVertical();
        }
        public static Transform[] CloneTargets(SetTransformation setTransform = null)
        {
            if (instance.filteredSelection.NodeTargets.Length == 0)
            {
                return(new Transform[0]);
            }

            var groupId = Undo.GetCurrentGroup();

            Undo.IncrementCurrentGroup();

            var newTargets    = new GameObject[instance.filteredSelection.NodeTargets.Length];
            var newTransforms = new Transform[instance.filteredSelection.NodeTargets.Length];

            for (int i = 0; i < instance.filteredSelection.NodeTargets.Length; i++)
            {
                var originalGameObject = instance.filteredSelection.NodeTargets[i].gameObject;
                var originalTransform  = originalGameObject.GetComponent <Transform>();
                newTargets[i] = UnityEngine.Object.Instantiate(originalGameObject) as GameObject;
                var newTransform = newTargets[i].GetComponent <Transform>();
                if (originalTransform.parent != null)
                {
                    newTransform.SetParent(originalTransform.parent, false);
                    newTransform.SetSiblingIndex(originalTransform.GetSiblingIndex() + 1);
                    newTransform.name = GameObjectUtility.GetUniqueNameForSibling(originalTransform.parent, originalTransform.name);
                }
                if (setTransform == null)
                {
                    newTransform.localScale    = originalTransform.localScale;
                    newTransform.localPosition = originalTransform.localPosition;
                    newTransform.localRotation = originalTransform.localRotation;
                }
                else
                {
                    setTransform(newTransform, originalTransform);
                }

                var childBrushes = newTargets[i].GetComponentsInChildren <CSGBrush>();

                Dictionary <uint, uint> uniqueSmoothingGroups = new Dictionary <uint, uint>();
                foreach (var childBrush in childBrushes)
                {
                    for (int g = 0; g < childBrush.Shape.TexGens.Length; g++)
                    {
                        var smoothingGroup = childBrush.Shape.TexGens[g].SmoothingGroup;
                        if (smoothingGroup == 0)
                        {
                            continue;
                        }

                        uint newSmoothingGroup;
                        if (!uniqueSmoothingGroups.TryGetValue(smoothingGroup, out newSmoothingGroup))
                        {
                            newSmoothingGroup = SurfaceUtility.FindUnusedSmoothingGroupIndex();
                            uniqueSmoothingGroups[smoothingGroup] = newSmoothingGroup;
                        }

                        childBrush.Shape.TexGens[g].SmoothingGroup = newSmoothingGroup;
                    }
                }

                newTransforms[i] = newTransform;
                Undo.RegisterCreatedObjectUndo(newTargets[i], "Created clone of " + originalGameObject.name);
            }

            Selection.objects = newTargets;
            Undo.CollapseUndoOperations(groupId);

            return(newTransforms);
        }
Beispiel #19
0
        FloatField AddField(VisualElement panel, Slider slider, int index, DielectricSpecularNode.DielectricMaterial initMaterial)
        {
            float initValue;

            if (index == 1)
            {
                initValue = initMaterial.indexOfRefraction;
            }
            else
            {
                initValue = initMaterial.range;
            }

            var field = new FloatField {
                userData = index, value = initValue
            };

            field.RegisterCallback <MouseDownEvent>(Repaint);
            field.RegisterCallback <MouseMoveEvent>(Repaint);
            field.OnValueChanged(evt =>
            {
                var value      = (DielectricSpecularNode.DielectricMaterial)m_PropertyInfo.GetValue(m_Node, null);
                var fieldValue = (float)evt.newValue;
                if (index == 1)
                {
                    value.indexOfRefraction = fieldValue;
                    RedrawIORControls(fieldValue);
                }
                else
                {
                    value.range = fieldValue;
                    RedrawRangeControls(fieldValue);
                }
                m_PropertyInfo.SetValue(m_Node, value, null);
                m_UndoGroup = -1;
                this.MarkDirtyRepaint();
            });
            field.RegisterCallback <InputEvent>(evt =>
            {
                if (m_UndoGroup == -1)
                {
                    m_UndoGroup = Undo.GetCurrentGroup();
                    m_Node.owner.owner.RegisterCompleteObjectUndo("Change " + m_Node.name);
                }
                float newValue;
                if (!float.TryParse(evt.newData, out newValue))
                {
                    newValue = 0f;
                }
                var value = (DielectricSpecularNode.DielectricMaterial)m_PropertyInfo.GetValue(m_Node, null);
                if (index == 1)
                {
                    value.indexOfRefraction = newValue;
                }
                else
                {
                    value.range = newValue;
                }
                m_PropertyInfo.SetValue(m_Node, value, null);
                this.MarkDirtyRepaint();
            });
            field.RegisterCallback <KeyDownEvent>(evt =>
            {
                if (evt.keyCode == KeyCode.Escape && m_UndoGroup > -1)
                {
                    Undo.RevertAllDownToGroup(m_UndoGroup);
                    m_UndoGroup = -1;
                    var value   = (DielectricSpecularNode.DielectricMaterial)m_PropertyInfo.GetValue(m_Node, null);
                    if (index == 1)
                    {
                        RedrawIORControls(value.indexOfRefraction);
                    }
                    else
                    {
                        RedrawRangeControls(value.range);
                    }
                    evt.StopPropagation();
                }
                this.MarkDirtyRepaint();
            });
            panel.Add(field);
            return(field);
        }
        void UpdateRenderers()
        {
            m_UndoGroup = Undo.GetCurrentGroup();

            EditorApplication.delayCall += DoUpdateRenderer;
        }
Beispiel #21
0
        private void HandleDragDrop(Event current, SceneView sceneView)
        {
            var mouseOverSceneView = EditorWindow.mouseOverWindow == sceneView;
            var mouseOverHierarchy = !mouseOverSceneView &&
                                     EditorWindow.mouseOverWindow != null &&
                                     EditorWindow.mouseOverWindow.GetType().FullName == "UnityEditor.SceneHierarchyWindow";
            var dragDropSceneViewActive = (mouseOverSceneView || mouseOverHierarchy) &&
                                          (current.type == EventType.DragPerform || current.type == EventType.DragUpdated);

            if (!dragDropSceneViewActive)
            {
                return;
            }

            Manager.UpdateMouseOverPrimitives(current, true);

            var mouseOverShapes         = HasShapeMaterialProperty(Manager.MouseOverObject);
            var isDraggingShapeMaterial = DragAndDrop.objectReferences.Length == 1 &&
                                          DragAndDrop.objectReferences[0] is AGXUnity.ShapeMaterial;

            DragAndDrop.visualMode = isDraggingShapeMaterial && mouseOverShapes ?
                                     DragAndDropVisualMode.Copy :
                                     DragAndDropVisualMode.Rejected;
            if (mouseOverShapes &&
                isDraggingShapeMaterial &&
                Event.current.type == EventType.DragPerform)
            {
                DragAndDrop.AcceptDrag();

                DroppedShapeMaterial = DragAndDrop.objectReferences[0] as AGXUnity.ShapeMaterial;

                var menuTool = new SelectGameObjectDropdownMenuTool()
                {
                    Target = Manager.MouseOverObject
                };
                menuTool.OnSelect = go =>
                {
                    AGXUnity.Collide.Shape[] shapes = go.GetComponentsInChildren <AGXUnity.Collide.Shape>();
                    AGXUnity.Wire[]          wires  = go.GetComponentsInChildren <AGXUnity.Wire>();
                    AGXUnity.Cable[]         cables = go.GetComponentsInChildren <AGXUnity.Cable>();
                    Action assignAll = () =>
                    {
                        Undo.SetCurrentGroupName("Assigning shape materials.");
                        var undoGroup = Undo.GetCurrentGroup();
                        foreach (var shape in shapes)
                        {
                            Undo.RecordObject(shape, "New shape material");
                            shape.Material = DroppedShapeMaterial;
                        }
                        foreach (var wire in wires)
                        {
                            Undo.RecordObject(wire, "New shape material");
                            wire.Material = DroppedShapeMaterial;
                        }
                        foreach (var cable in cables)
                        {
                            Undo.RecordObject(cable, "New shape material");
                            cable.Material = DroppedShapeMaterial;
                        }
                        Undo.CollapseUndoOperations(undoGroup);
                    };

                    var sumSupported = shapes.Length + wires.Length + cables.Length;
                    if (sumSupported == 0)
                    {
                        Debug.LogWarning("Object selected doesn't have shapes, wires or cables.", go);
                    }
                    else if (sumSupported == 1 || EditorUtility.DisplayDialog("Assign shape materials",
                                                                              string.Format("Assign materials to:\n  - #shapes: {0}\n  - #wires: {1}\n  - #cables: {2}",
                                                                                            shapes.Length, wires.Length, cables.Length), "Assign", "Ignore all"))
                    {
                        assignAll();
                    }

                    DroppedShapeMaterial = null;
                };
                menuTool.Show();
                AddChild(menuTool);
            }
        }
Beispiel #22
0
        //Adds a tab at the specified index, optionally using GAMEOBJECTS as prefabs for panel and button
        public void InsertTabWithObjects(int tabNum, string btnTxt = "TabButton", GameObject prefab_Button = null, GameObject prefab_Panel = null, bool switchToNewTab = SWITCH_TO_NEW_TAB)
        {
#if UNITY_EDITOR
            //start the undo records
            List <UnityEngine.Object> undoGOs = new List <UnityEngine.Object>();
            undoGOs.Add(this);                  //record currentTab
            foreach (GameObject go in panels)   //record which panels are active
            {
                undoGOs.Add(go);
            }
            //Undo.IncrementCurrentGroup();
            Undo.SetCurrentGroupName("Add Tab");
            int undoGroup = Undo.GetCurrentGroup();
            Undo.RecordObjects(undoGOs.ToArray(), "Remove Tab");
#endif

            //put the tab num within the correct bounds
            if (tabNum < 0)
            {
                tabNum = 0;
            }
            if (tabNum > panels.Count)
            {
                tabNum = panels.Count;
            }

            //create button and panel from prefabs
            GameObject tabBtn;
            GameObject tabPan;

            //if the path to the button prefab is not empty, use it to make a new button
            if (prefab_Button != null)
            {
                tabBtn = Instantiate <GameObject>(prefab_Button);
            }
            //else, if the prefab is not empty, use it
            else if (prefabButton != null)
            {
                tabBtn = Instantiate <GameObject>(prefabButton);
            }
            //else use the default
            else
            {
                tabBtn = Instantiate <GameObject>(Resources.Load <GameObject>(TabConfig.prefabPath_Button));
            }

            //if the path to the panel prefab is not empty, use it to make a new button
            if (prefab_Panel != null)
            {
                tabPan = Instantiate <GameObject>(prefab_Panel);
            }
            //else, if the prefab is not empty, use it
            else if (prefabButton != null)
            {
                tabPan = Instantiate <GameObject>(prefabPanel);
            }
            //else use the default
            else
            {
                tabPan = Instantiate <GameObject>(Resources.Load <GameObject>(TabConfig.prefabPath_Panel));
            }

            //Set Parents
            tabBtn.transform.SetParent(this.transform.Find("TabButtons"));
            tabPan.transform.SetParent(this.transform.Find("TabPanels"));

            //Correct for Screen Space Canvas
            tabBtn.GetComponent <RectTransform>().localRotation = new Quaternion();
            tabBtn.GetComponent <RectTransform>().localPosition = new Vector3(tabBtn.GetComponent <RectTransform>().localPosition.x, tabBtn.GetComponent <RectTransform>().localPosition.y, 0);
            tabPan.GetComponent <RectTransform>().localRotation = new Quaternion();
            tabPan.GetComponent <RectTransform>().localPosition = new Vector3(tabPan.GetComponent <RectTransform>().localPosition.x, tabPan.GetComponent <RectTransform>().localPosition.y, 0);

            //change button text, or delete if no text
            if (btnTxt != "" && btnTxt != null)
            {
                tabBtn.transform.GetChild(0).GetComponent <Text>().text = btnTxt;
            }
            else
            {
                Destroy(tabBtn.transform.GetChild(0));
            }

            //set scale
            tabBtn.GetComponent <RectTransform>().localScale = new Vector3(1, 1, 1);
            tabPan.GetComponent <RectTransform>().localScale = new Vector3(1, 1, 1);
            if (tabBtn.transform.GetChild(0) != null)
            {
                tabBtn.transform.GetChild(0).GetComponent <RectTransform>().localScale = new Vector3(1, 1, 1);
            }

            //put tab compenents at the right index
            tabBtn.transform.SetSiblingIndex(tabNum);
            tabPan.transform.SetSiblingIndex(tabNum);

            //renumber the tabs to register the new one.
            ReNumberTabs();

#if UNITY_EDITOR
            //finish up adding undo
            Undo.RegisterCreatedObjectUndo(tabBtn, "Add Tab");
            Undo.RegisterCreatedObjectUndo(tabPan, "Add Tab");
            Undo.CollapseUndoOperations(undoGroup);
#endif
            if (switchToNewTab)
            {
                SwitchToTab(tabNum);
#if UNITY_EDITOR
                Selection.activeObject = tabPan;
#endif
            }
            else
            {
                SwitchToTab(currentTab);
            }
        }
        public void Grab(IEnumerable <ITimelineItem> items, TrackAsset referenceTrack, Vector2 mousePosition)
        {
            if (items == null)
            {
                return;
            }

            items = items.ToArray(); // Cache enumeration result

            if (!items.Any())
            {
                return;
            }

            m_GrabbedModalUndoGroup = Undo.GetCurrentGroup();

            var trackItems      = items.GroupBy(c => c.parentTrack).ToArray();
            var trackItemsCount = trackItems.Length;
            var tracks          = items.Select(c => c.parentTrack).Where(x => x != null).Distinct();

            movingItems = new MovingItems[trackItemsCount];

            allowTrackSwitch = trackItemsCount == 1 && !trackItems.SelectMany(x => x).Any(x => x is MarkerItem); // For now, track switch is only supported when all items are on the same track and there are no items
            foreach (var sourceTrack in tracks)
            {
                // one push per track handles all the clips on the track
                TimelineUndo.PushUndo(sourceTrack, "Move Items");

                // push all markers on the track because of ripple
                foreach (var marker in sourceTrack.GetMarkers().OfType <ScriptableObject>())
                {
                    TimelineUndo.PushUndo(marker, "Move Items");
                }
            }

            for (var i = 0; i < trackItemsCount; ++i)
            {
                var track        = trackItems[i].Key;
                var grabbedItems = new MovingItems(m_State, track, trackItems[i].ToArray(), referenceTrack, mousePosition, allowTrackSwitch);
                movingItems[i] = grabbedItems;
            }

            m_LeftMostMovingItems  = null;
            m_RightMostMovingItems = null;

            foreach (var grabbedTrackItems in movingItems)
            {
                if (m_LeftMostMovingItems == null || m_LeftMostMovingItems.start > grabbedTrackItems.start)
                {
                    m_LeftMostMovingItems = grabbedTrackItems;
                }

                if (m_RightMostMovingItems == null || m_RightMostMovingItems.end < grabbedTrackItems.end)
                {
                    m_RightMostMovingItems = grabbedTrackItems;
                }
            }

            m_ItemGUIs   = new HashSet <TimelineItemGUI>();
            m_ItemsGroup = new ItemsGroup(items);

            foreach (var item in items)
            {
                m_ItemGUIs.Add(item.gui);
            }

            targetTrack = referenceTrack;

            EditMode.BeginMove(this);
            m_Grabbing = true;
        }
Beispiel #24
0
 private static int RegisterUndo()
 {
     return(Undo.GetCurrentGroup());
 }
        public static void UndoCollapseCurrentGroup()
        {
#if UNITY_EDITOR
            Undo.CollapseUndoOperations(Undo.GetCurrentGroup());
#endif
        }
Beispiel #26
0
        public static void Export(CSGModel model, RealtimeCSG.Components.ExportType exportType, bool exportColliders)
        {
            string typeName;
            string extension;

            switch (exportType)
            {
            case RealtimeCSG.Components.ExportType.FBX: typeName = "FBX"; extension = @"fbx"; break;

            default:
                //case RealtimeCSG.Components.ExportType.UnityMesh:
                typeName = "Mesh"; extension = @"prefab"; exportType = RealtimeCSG.Components.ExportType.UnityMesh; break;
            }
            var newPath = model.exportPath;

            if (exportType != RealtimeCSG.Components.ExportType.UnityMesh)
            {
                newPath = UnityFBXExporter.ExporterMenu.GetNewPath(model.gameObject, typeName, extension, model.exportPath);
                if (string.IsNullOrEmpty(newPath))
                {
                    return;
                }
            }

            model.ShowGeneratedMeshes = false;
            var foundModels = model.GetComponentsInChildren <CSGModel>(true);

            for (var index = 0; index < foundModels.Length; index++)
            {
                if (!foundModels[index].ShowGeneratedMeshes)
                {
                    continue;
                }
                foundModels[index].ShowGeneratedMeshes = false;
                UpdateGeneratedMeshesVisibility(foundModels[index]);
            }

            GameObject tempExportObject;

            if (!string.IsNullOrEmpty(model.exportPath))
            {
                tempExportObject = new GameObject(System.IO.Path.GetFileNameWithoutExtension(model.exportPath));
                if (string.IsNullOrEmpty(tempExportObject.name))
                {
                    tempExportObject.name = model.name;
                }
            }
            else
            {
                tempExportObject = new GameObject(model.name);
            }

            tempExportObject.transform.position   = MathConstants.zeroVector3;
            tempExportObject.transform.rotation   = MathConstants.identityQuaternion;
            tempExportObject.transform.localScale = MathConstants.oneVector3;

            int colliderCounter      = 1;
            int shadowOnlyCounter    = 1;
            var materialMeshCounters = new Dictionary <Material, int>();

            var currentScene        = model.gameObject.scene;
            var foundMeshContainers = SceneQueryUtility.GetAllComponentsInScene <GeneratedMeshes>(currentScene);
            var bounds = new AABB();

            bounds.Reset();
            var foundMeshFilters   = new List <MeshFilter>();
            var foundMeshColliders = new List <MeshCollider>();

            foreach (var meshContainer in foundMeshContainers)
            {
                var owner = meshContainer.owner;
                if (!owner || !ArrayUtility.Contains(foundModels, owner))
                {
                    continue;
                }

                if (!meshContainer || !meshContainer.HasMeshInstances)
                {
                    continue;
                }

                foreach (var instance in meshContainer.MeshInstances)
                {
                    if (!instance)
                    {
                        continue;
                    }

                    Refresh(instance, model, postProcessScene: true, skipAssetDatabaseUpdate: true);

                    var surfaceType = GetSurfaceType(instance.MeshDescription, owner.Settings);
                    if (surfaceType != RenderSurfaceType.Normal &&
                        surfaceType != RenderSurfaceType.ShadowOnly &&
                        surfaceType != RenderSurfaceType.Collider)
                    {
                        continue;
                    }

                    int counter = 0;
                    if (instance.RenderMaterial)
                    {
                        if (!materialMeshCounters.TryGetValue(instance.RenderMaterial, out counter))
                        {
                            counter = 1;
                        }
                        else
                        {
                            counter++;
                        }
                    }

                    var mesh = instance.SharedMesh;
                    if (!mesh.isReadable)
                    {
                        //bounds.Extend(mesh.bounds.min);
                        //bounds.Extend(mesh.bounds.max);
                    }
                    else
                    {
                        var vertices = mesh.vertices;
                        for (int v = 0; v < vertices.Length; v++)
                        {
                            bounds.Extend(vertices[v]);
                        }
                    }


                    var subObj = UnityEngine.Object.Instantiate(instance.gameObject, MathConstants.zeroVector3, MathConstants.identityQuaternion) as GameObject;
                    subObj.hideFlags            = HideFlags.None;
                    subObj.transform.position   = owner.transform.position;
                    subObj.transform.rotation   = owner.transform.rotation;
                    subObj.transform.localScale = owner.transform.localScale;
                    subObj.transform.SetParent(tempExportObject.transform, false);

                    var genMeshInstance = subObj.GetComponent <GeneratedMeshInstance>();

                    UnityEngine.Object.DestroyImmediate(genMeshInstance);

                    if (surfaceType == RenderSurfaceType.Collider)
                    {
                        subObj.name = "no-material Mesh (" + colliderCounter + ") COLLIDER"; colliderCounter++;
                    }
                    else
                    {
                        if (surfaceType == RenderSurfaceType.ShadowOnly)
                        {
                            subObj.name = "shadow-only Mesh (" + shadowOnlyCounter + ")"; shadowOnlyCounter++;
                            var meshRenderer = subObj.GetComponent <MeshRenderer>();
                            if (meshRenderer)
                            {
                                meshRenderer.sharedMaterial = MaterialUtility.DefaultMaterial;
                            }
                        }
                        else
                        {
                            Material renderMaterial = instance.RenderMaterial;
                            if (!renderMaterial)
                            {
                                renderMaterial = MaterialUtility.DefaultMaterial;
                                subObj.name    = "missing-material Mesh (" + counter + ")"; counter++;
                            }
                            else
                            {
                                subObj.name = renderMaterial.name + " Mesh (" + counter + ")";
                            } counter++;
                            materialMeshCounters[instance.RenderMaterial] = counter;
                        }

                        var meshFilter = subObj.GetComponent <MeshFilter>();
                        if (meshFilter)
                        {
                            foundMeshFilters.Add(meshFilter);
                        }
                    }

                    var meshCollider = subObj.GetComponent <MeshCollider>();
                    if (meshCollider)
                    {
                        foundMeshColliders.Add(meshCollider);
                    }
                }
            }

            Undo.IncrementCurrentGroup();
            var groupIndex = Undo.GetCurrentGroup();

            Undo.SetCurrentGroupName("Exported model");
            try
            {
                Vector3 position = model.transform.position;
                if (float.IsInfinity(position.x) || float.IsNaN(position.x))
                {
                    position.x = 0;
                }
                if (float.IsInfinity(position.y) || float.IsNaN(position.y))
                {
                    position.y = 0;
                }
                if (float.IsInfinity(position.z) || float.IsNaN(position.z))
                {
                    position.z = 0;
                }

                Vector3 center = bounds.Center;
                switch (model.originType)
                {
                default:
                case OriginType.ModelCenter:    center = bounds.Center + position; break;

                case OriginType.ModelPivot:             center = position; break;

                case OriginType.WorldSpace:             center = Vector3.zero; break;
                }
                if (float.IsInfinity(center.x) || float.IsNaN(center.x))
                {
                    center.x = 0;
                }
                if (float.IsInfinity(center.y) || float.IsNaN(center.y))
                {
                    center.y = 0;
                }
                if (float.IsInfinity(center.z) || float.IsNaN(center.z))
                {
                    center.z = 0;
                }

                var modifiedMeshes = new Dictionary <Mesh, Mesh>();
                foreach (var meshFilter in foundMeshFilters)
                {
                    var mesh = meshFilter.sharedMesh;
                    if (!mesh.isReadable)
                    {
                        continue;
                    }

                    Mesh newMesh;
                    if (!modifiedMeshes.TryGetValue(mesh, out newMesh))
                    {
                        newMesh = (Mesh)UnityEngine.Object.Instantiate(mesh);
                        var vertices = mesh.vertices;
                        for (int v = 0; v < vertices.Length; v++)
                        {
                            vertices[v] += position;
                            vertices[v] -= center;
                        }
                        newMesh.vertices = vertices;
                        newMesh.RecalculateBounds();
                        modifiedMeshes[mesh] = newMesh;
                    }
                    meshFilter.sharedMesh         = newMesh;
                    meshFilter.transform.position = Vector3.zero;
                }

                foreach (var meshCollider in foundMeshColliders)
                {
                    var mesh = meshCollider.sharedMesh;
                    if (!mesh.isReadable)
                    {
                        continue;
                    }

                    Mesh newMesh;
                    if (!modifiedMeshes.TryGetValue(mesh, out newMesh))
                    {
                        newMesh = (Mesh)UnityEngine.Object.Instantiate(mesh);
                        var vertices = mesh.vertices;
                        for (int v = 0; v < vertices.Length; v++)
                        {
                            vertices[v] += position;
                            vertices[v] -= center;
                        }
                        newMesh.vertices = vertices;
                        newMesh.RecalculateBounds();
                        modifiedMeshes[mesh] = newMesh;
                    }
                    meshCollider.sharedMesh         = newMesh;
                    meshCollider.transform.position = Vector3.zero;
                }

                UnityEngine.GameObject prefabObj;
                GameObject             modelGameObject;
                switch (exportType)
                {
                case RealtimeCSG.Components.ExportType.FBX:
                {
                    if (!UnityFBXExporter.FBXExporter.ExportGameObjToFBX(tempExportObject, newPath, exportColliders: exportColliders))
                    {
                        //InternalCSGModelManager.ClearMeshInstances();
                        EditorUtility.DisplayDialog("Warning", "Failed to export the FBX file.", "Ok");
                        return;
                    }
                    prefabObj = AssetDatabase.LoadAssetAtPath <UnityEngine.GameObject>(newPath);

                    modelGameObject = CSGPrefabUtility.Instantiate(prefabObj);

                    foreach (var renderer in modelGameObject.GetComponentsInChildren <MeshRenderer>())
                    {
                        var gameObject = renderer.gameObject;
                        if (gameObject.name.EndsWith("COLLIDER"))
                        {
                            var filter       = gameObject.GetComponent <MeshFilter>();
                            var meshCollider = gameObject.AddComponent <MeshCollider>();
                            meshCollider.sharedMesh = filter.sharedMesh;
                            UnityEngine.Object.DestroyImmediate(renderer);
                            UnityEngine.Object.DestroyImmediate(filter);
                        }
                    }
                    model.exportPath = newPath;
                    break;
                }

                default:
                    //case RealtimeCSG.Components.ExportType.UnityMesh:
                {
                    prefabObj       = tempExportObject;                      // AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(newPath);
                    modelGameObject = tempExportObject;

                    foreach (var meshFilter in tempExportObject.GetComponentsInChildren <MeshFilter>())
                    {
                        var mesh = meshFilter.sharedMesh;
                        mesh.name       = tempExportObject.name;
                        meshFilter.mesh = mesh;
                    }
                    break;
                }
                }


                model.exportPath = newPath;

                if (exportType == RealtimeCSG.Components.ExportType.FBX && prefabObj)
                {
                    foreach (var meshRenderer in prefabObj.GetComponentsInChildren <MeshRenderer>())
                    {
                        if (meshRenderer.sharedMaterials.Length != 1)
                        {
                            continue;
                        }

                        var gameObject = meshRenderer.gameObject;
                        var nameSplit  = gameObject.name.Split('|');
                        if (nameSplit.Length == 1)
                        {
                            continue;
                        }

                        int instanceId;
                        if (!int.TryParse(nameSplit[1], out instanceId))
                        {
                            continue;
                        }

                        var realMaterial = EditorUtility.InstanceIDToObject(instanceId) as Material;
                        if (!realMaterial)
                        {
                            continue;
                        }

                        meshRenderer.sharedMaterial = realMaterial;
                        gameObject.name             = nameSplit[0];
                    }
                }


                var staticFlags = GameObjectUtility.GetStaticEditorFlags(model.gameObject);
                var modelLayer  = model.gameObject.layer;
                foreach (var transform in modelGameObject.GetComponentsInChildren <Transform>())
                {
                    var gameObject = transform.gameObject;
                    GameObjectUtility.SetStaticEditorFlags(gameObject, staticFlags);
                    gameObject.layer = modelLayer;
                }

                modelGameObject.transform.SetParent(model.transform, true);
                modelGameObject.transform.SetSiblingIndex(0);
                modelGameObject.tag = model.gameObject.tag;

                modelGameObject.transform.localPosition = center - position;


                Undo.RegisterCreatedObjectUndo(modelGameObject, "Instantiated model");


                var exported = model.gameObject.AddComponent <CSGModelExported>();
                exported.containedModel         = null;
                exported.containedExportedModel = modelGameObject;
                exported.disarm = true;
                Undo.RegisterCreatedObjectUndo(exported, "Created CSGModelExported");
                Undo.RegisterCompleteObjectUndo(exported, "Created CSGModelExported");


                var foundBrushes    = model.GetComponentsInChildren <CSGBrush>(true);
                var foundOperations = model.GetComponentsInChildren <CSGOperation>(true);
                var foundContainers = model.GetComponentsInChildren <GeneratedMeshes>(true);

                var foundBehaviours = new HashSet <MonoBehaviour>();

                foreach (var foundBrush         in foundBrushes)
                {
                    foundBehaviours.Add(foundBrush);
                }
                foreach (var foundOperation in foundOperations)
                {
                    foundBehaviours.Add(foundOperation);
                }
                foreach (var foundModel         in foundModels)
                {
                    foundBehaviours.Add(foundModel);
                }
                foreach (var foundContainer in foundContainers)
                {
                    foundBehaviours.Add(foundContainer);
                }


                exported.hiddenComponents = new HiddenComponentData[foundBehaviours.Count];
                var index = 0;
                foreach (var foundBehaviour in foundBehaviours)
                {
                    Undo.RegisterCompleteObjectUndo(foundBehaviour, "Hide component");
                    exported.hiddenComponents[index] = new HiddenComponentData {
                        behaviour = foundBehaviour
                    };
                    index++;
                }

                for (var i = 0; i < exported.hiddenComponents.Length; i++)
                {
                    exported.hiddenComponents[i].hideFlags = exported.hiddenComponents[i].behaviour.hideFlags;
                    exported.hiddenComponents[i].enabled   = exported.hiddenComponents[i].behaviour.enabled;
                }

                for (var i = 0; i < exported.hiddenComponents.Length; i++)
                {
                    exported.hiddenComponents[i].behaviour.hideFlags = exported.hiddenComponents[i].behaviour.hideFlags | ComponentHideFlags;
                    exported.hiddenComponents[i].behaviour.enabled   = false;
                }

                EditorSceneManager.MarkSceneDirty(currentScene);
                Undo.CollapseUndoOperations(groupIndex);
                groupIndex      = 0;
                exported.disarm = false;
            }
            finally
            {
                switch (exportType)
                {
                case RealtimeCSG.Components.ExportType.FBX:
                {
                    UnityEngine.Object.DestroyImmediate(tempExportObject);
                    break;
                }
                }
                if (groupIndex != 0)
                {
                    Undo.CollapseUndoOperations(groupIndex);
                }
            }
        }
		/**
		 * Update the current brush object and weights with the current mouse position.
		 */
		void UpdateBrush(Vector2 mousePosition, bool isDrag = false)
		{
			// Must check HandleUtility.PickGameObject only during MouseMoveEvents or errors will rain.
			GameObject go = null;
			brushTarget = null;

			if( isDrag && lockBrushToFirst && lastHoveredGameObject != null )
			{
				go = lastHoveredGameObject;
				brushTarget = GetBrushTarget(go);
			}
			else if(ignoreUnselected || isDrag)
			{
				GameObject cur = null;
				int max = 0;	// safeguard against unforeseen while loop errors crashing unity

				do
				{
					int tmp;
					// overloaded PickGameObject ignores array of GameObjects, this is used
					// when there are non-selected gameObjects between the mouse and selected
					// gameObjects.
					cur = HandleUtility.PickGameObject(mousePosition, m_IgnoreDrag.ToArray(), out tmp);

					if(cur != null)
					{
						if( !z_EditorUtility.InSelection(cur.transform) )
						{
							if(!m_IgnoreDrag.Contains(cur))
							{
								m_IgnoreDrag.Add(cur);
							}
						}
						else
						{
							brushTarget = GetBrushTarget(cur);

							if(brushTarget != null)
							{
								go = cur;
							}
							else
							{
								m_IgnoreDrag.Add(cur);
							}
						}
					}
				} while( go == null && cur != null && max++ < 128);
			}
			else
			{
				go = HandleUtility.PickGameObject(mousePosition, false);

				if( go != null && z_EditorUtility.InSelection(go) )
					brushTarget = GetBrushTarget(go);
				else
					go = null;
			}

			bool mouseHoverTargetChanged = false;

			Ray mouseRay = HandleUtility.GUIPointToWorldRay(mousePosition);

			// if the mouse hover picked up a valid editable, raycast against that.  otherwise
			// raycast all meshes in selection
			if(go == null)
			{
				foreach(var kvp in hovering)
				{
					z_BrushTarget t = kvp.Value;

					if( z_Util.IsValid(t) && DoMeshRaycast(mouseRay, t) )
					{
						brushTarget = t;
						go = t.gameObject;
						break;
					}
				}

			}
			else
			{
				if(!DoMeshRaycast(mouseRay, brushTarget))
				{
					if(!isDrag || !lockBrushToFirst)
					{
						go = null;
						brushTarget = null;
					}

					return;
				}
			}

			// if hovering off another gameobject, call OnBrushExit on that last one and mark the
			// target as having been changed
			if( go != lastHoveredGameObject )
			{
				OnBrushExit(lastHoveredGameObject);
				mouseHoverTargetChanged = true;
				lastHoveredGameObject = go;
			}

			if(brushTarget == null)
				return;

			if(mouseHoverTargetChanged)
			{
				OnBrushEnter(brushTarget, brushSettings);

				// brush is in use, adding a new object to the undo
				if(applyingBrush && !undoQueue.Contains(go))
				{
					int curGroup = Undo.GetCurrentGroup();
					brushTarget.editableObject.isDirty = true;
					OnBrushBeginApply(brushTarget, brushSettings);
					Undo.CollapseUndoOperations(curGroup);
				}
			}

			OnBrushMove();

			SceneView.RepaintAll();
			this.Repaint();
		}
        public static void HideUnselectedObjects()
        {
            Undo.IncrementCurrentGroup();
            var undoGroupIndex = Undo.GetCurrentGroup();

            var selected    = Selection.gameObjects.ToList();
            var selectedIDs = new HashSet <int>();

            var models = InternalCSGModelManager.Models;

            for (var i = 0; i < models.Length; i++)
            {
                var model = models[i];
                if (!model)
                {
                    continue;
                }

                if (!model.generatedMeshes)
                {
                    continue;
                }

                var meshContainerChildren = model.generatedMeshes.GetComponentsInChildren <Transform>();
                foreach (var child in meshContainerChildren)
                {
                    selected.Add(child.gameObject);
                }
            }

            for (int i = 0; i < selected.Count; i++)             // we keep adding parents, and their parents until we hit the root-objects
            {
                selectedIDs.Add(selected[i].GetInstanceID());
                var transform = selected[i].transform;
                var parent    = transform.parent;
                if (parent == null)
                {
                    continue;
                }
                selected.Add(parent.gameObject);
            }

            for (var sceneIndex = 0; sceneIndex < SceneManager.sceneCount; sceneIndex++)
            {
                var activeScene     = SceneManager.GetSceneAt(sceneIndex);
                var rootGameObjects = activeScene.GetRootGameObjects();
                for (var i = 0; i < rootGameObjects.Length; i++)
                {
                    var children = rootGameObjects[i].GetComponentsInChildren <Transform>();
                    for (var c = 0; c < children.Length; c++)
                    {
                        var transform  = children[c];
                        var gameObject = transform.gameObject;
                        if (!gameObject.activeInHierarchy || (gameObject.hideFlags != HideFlags.None))
                        {
                            continue;
                        }

                        if (selectedIDs.Contains(gameObject.GetInstanceID()))
                        {
                            continue;
                        }

                        Undo.RecordObject(gameObject, "Hiding Object");
                        gameObject.SetActive(false);
                    }
                }
            }

            Undo.CollapseUndoOperations(undoGroupIndex);
        }
Beispiel #29
0
        public static void MakeGroup()
        {
            if (!CorePreferences.allowGroupObjectsHotkey)
            {
                return;
            }

            GameObject[] objs = Selection.GetFiltered <GameObject>(SelectionMode.ExcludePrefab | SelectionMode.OnlyUserModifiable | SelectionMode.Editable);
            if (objs.Length == 0)
            {
                return;
            }

            Transform first = objs[0].transform;

            List <Transform> hierarchy = new List <Transform>();

            Transform parent = first.parent;

            while (parent != null)
            {
                hierarchy.Add(parent);
                parent = parent.parent;
            }

            int index = 0;

            parent = hierarchy.FirstOrDefault();

            if (parent != null)
            {
                foreach (var obj in objs)
                {
                    Transform t = obj.transform;
                    while (!t.IsChildOf(parent) || t == parent)
                    {
                        index++;
                        if (index >= hierarchy.Count)
                        {
                            parent = null;
                            break;
                        }
                        else
                        {
                            parent = hierarchy[index];
                        }
                    }
                    if (parent == null)
                    {
                        break;
                    }
                }
            }

            GameObject root = new GameObject("Group");

            root.transform.SetParent(parent);
            root.transform.localPosition = Vector3.zero;
            root.transform.localRotation = Quaternion.identity;
            root.transform.localScale    = Vector3.one;
            Undo.RegisterCreatedObjectUndo(root, "Created group object.");

            List <Transform> allTransforms = new List <Transform>();

            if (parent == null)
            {
                var sceneRoots = root.scene.GetRootGameObjects();
                foreach (var sceneRoot in sceneRoots)
                {
                    allTransforms.AddRange(sceneRoot.GetComponentsInChildren <Transform>());
                }
            }
            else
            {
                allTransforms.AddRange(parent.GetComponentsInChildren <Transform>());
            }

            foreach (var obj in allTransforms)
            {
                if (objs.Contains(obj.gameObject))
                {
                    Transform originalParent = obj.transform.parent;
                    obj.transform.SetParent(root.transform, worldPositionStays: true);

                    Vector3    newPos   = obj.transform.localPosition;
                    Quaternion newRot   = obj.transform.localRotation;
                    Vector3    newScale = obj.transform.localScale;

                    obj.transform.SetParent(originalParent, worldPositionStays: true);
                    Undo.SetTransformParent(obj.transform, root.transform, "Moved " + obj.name + " into group.");
                    Undo.RecordObject(obj.transform, "Set new transform for " + obj.name + ".");

                    obj.transform.localPosition = newPos;
                    obj.transform.localRotation = newRot;
                    obj.transform.localScale    = newScale;
                }
            }

            Selection.activeGameObject = root;
            Undo.CollapseUndoOperations(Undo.GetCurrentGroup());
        }
    public Cutscene CreateCutscene()
    {
        string cutsceneName = DirectorHelper.getCutsceneItemName(txtCutsceneName, typeof(Cutscene));

        GameObject cutsceneGO = new GameObject(cutsceneName);
        Cutscene   cutscene   = cutsceneGO.AddComponent <Cutscene>();

        for (int i = 0; i < directorTrackGroupsSelection; i++)
        {
            DirectorGroup dg = CutsceneItemFactory.CreateDirectorGroup(cutscene);
            dg.Ordinal = 0;
            for (int j = 0; j < shotTrackSelection; j++)
            {
                CutsceneItemFactory.CreateShotTrack(dg);
            }
            for (int j = 0; j < audioTrackSelection; j++)
            {
                CutsceneItemFactory.CreateAudioTrack(dg);
            }
            for (int j = 0; j < globalItemTrackSelection; j++)
            {
                CutsceneItemFactory.CreateGlobalItemTrack(dg);
            }
        }

        for (int i = 0; i < actorTrackGroupsSelection; i++)
        {
            CutsceneItemFactory.CreateActorTrackGroup(cutscene, actors[i]);
        }

        for (int i = 0; i < multiActorTrackGroupsSelection; i++)
        {
            CutsceneItemFactory.CreateMultiActorTrackGroup(cutscene);
        }

        for (int i = 0; i < characterTrackGroupsSelection; i++)
        {
            CutsceneItemFactory.CreateCharacterTrackGroup(cutscene, characters[i]);
        }

        float duration = txtDuration;

        if (timeEnum == DirectorHelper.TimeEnum.Minutes)
        {
            duration *= 60;
        }
        cutscene.Duration = duration;

        cutscene.IsLooping = isLooping;

        cutscene.IsSkippable = isSkippable;

        int undoIndex = Undo.GetCurrentGroup();

        if (StartMethod != StartMethod.None)
        {
            CreateCutsceneTrigger(cutscene);
        }

        Undo.RegisterCreatedObjectUndo(cutsceneGO, string.Format("Created {0}", txtCutsceneName));
        Undo.CollapseUndoOperations(undoIndex);

        Selection.activeTransform = cutsceneGO.transform;

        return(cutscene);
    }