public void UndoRedoOperatorSettings()
        {
            Func <VFXOperatorController> fnFirstOperatorController = delegate()
            {
                m_ViewController.ApplyChanges();
                return(m_ViewController.allChildren.OfType <VFXOperatorController>().FirstOrDefault());
            };

            var swizzleDesc = VFXLibrary.GetOperators().FirstOrDefault(o => o.name == "Swizzle");

            m_ViewController.AddVFXOperator(new Vector2(0, 0), swizzleDesc);

            var maskList = new string[] { "xy", "yww", "xw", "z" };

            for (int i = 0; i < maskList.Length; ++i)
            {
                var componentMaskController = fnFirstOperatorController();
                Undo.IncrementCurrentGroup();
                (componentMaskController.model as Operator.Swizzle).SetSettingValue("mask", maskList[i]);
                Assert.AreEqual(maskList[i], (componentMaskController.model as Operator.Swizzle).mask);
            }

            for (int i = maskList.Length - 1; i > 0; --i)
            {
                Undo.PerformUndo();
                var componentMaskController = fnFirstOperatorController();
                Assert.AreEqual(maskList[i - 1], (componentMaskController.model as Operator.Swizzle).mask);
            }

            for (int i = 0; i < maskList.Length - 1; ++i)
            {
                Undo.PerformRedo();
                var componentMaskController = fnFirstOperatorController();
                Assert.AreEqual(maskList[i + 1], (componentMaskController.model as Operator.Swizzle).mask);
            }
        }
Beispiel #2
0
        public override void Start()
        {
            base.Start();

            _OriginalMousePos = Event.current.mousePosition;

            // Just in case the order isn't guaranteed, I'm going to save the selecteds.
            _Selected          = Selection.GetTransforms(SelectionMode.TopLevel);
            _AvgPos            = Vector3.zero;
            _OriginalRotations = new Vector3[_Selected.Length];
            _OriginalPositions = new Vector3[_Selected.Length];
            _State.Init();

            for (int i = 0; i < _Selected.Length; i++)
            {
                _AvgPos += _Selected[i].position;
                _OriginalRotations[i] = _Selected[i].eulerAngles;
                _OriginalPositions[i] = _Selected[i].position;
            }

            _AvgPos /= _Selected.Length;

            Undo.IncrementCurrentGroup();
        }
        public void UndoRedoChangeSpace()
        {
            var inlineOperatorDesc = VFXLibrary.GetOperators().FirstOrDefault(o => o.modelType == typeof(VFXInlineOperator));
            var inlineOperator     = m_ViewController.AddVFXOperator(new Vector2(0, 0), inlineOperatorDesc);

            m_ViewController.ApplyChanges();
            var allController            = m_ViewController.allChildren.OfType <VFXNodeController>().ToArray();
            var inlineOperatorController = allController.OfType <VFXOperatorController>().FirstOrDefault();

            inlineOperator.SetSettingValue("m_Type", (SerializableType)typeof(Position));

            Assert.AreEqual(inlineOperator.inputSlots[0].space, VFXCoordinateSpace.Local);
            Assert.AreEqual((inlineOperatorController.model as VFXInlineOperator).inputSlots[0].space, VFXCoordinateSpace.Local);
            Assert.AreEqual((inlineOperatorController.model as VFXInlineOperator).inputSlots[0].GetSpaceTransformationType(), SpaceableType.Position);

            Undo.IncrementCurrentGroup();
            inlineOperator.inputSlots[0].space = VFXCoordinateSpace.World;
            Assert.AreEqual((inlineOperatorController.model as VFXInlineOperator).inputSlots[0].space, VFXCoordinateSpace.World);
            Assert.AreEqual((inlineOperatorController.model as VFXInlineOperator).inputSlots[0].GetSpaceTransformationType(), SpaceableType.Position);

            Undo.PerformUndo(); //Should go back to local
            Assert.AreEqual((inlineOperatorController.model as VFXInlineOperator).inputSlots[0].space, VFXCoordinateSpace.Local);
            Assert.AreEqual((inlineOperatorController.model as VFXInlineOperator).inputSlots[0].GetSpaceTransformationType(), SpaceableType.Position);
        }
        public void UndoRedoSetSlotValueAndGraphChange()
        {
            Func <VFXNodeController[]> fnAllOperatorController = delegate()
            {
                m_ViewController.ApplyChanges();
                var allController = m_ViewController.allChildren.OfType <VFXNodeController>();
                return(allController.OfType <VFXOperatorController>().ToArray());
            };

            var absDesc = VFXLibrary.GetOperators().FirstOrDefault(o => o.name == "Absolute");

            m_ViewController.AddVFXOperator(new Vector2(0, 0), absDesc);

            var absOperator = fnAllOperatorController()[0];

            Undo.IncrementCurrentGroup();
            absOperator.inputPorts[0].value = 0;

            absOperator.position = new Vector2(1, 2);


            Undo.IncrementCurrentGroup();

            absOperator.inputPorts[0].value = 123;
            absOperator.position            = new Vector2(123, 456);

            Undo.PerformUndo();

            Assert.AreEqual(123, absOperator.inputPorts[0].value);
            Assert.AreEqual(new Vector2(1, 2), absOperator.position);

            Undo.PerformRedo();

            Assert.AreEqual(123, absOperator.inputPorts[0].value);
            Assert.AreEqual(new Vector2(123, 456), absOperator.position);
        }
        public IEnumerator CreateModel_UndoCreateComponent_ModelDoesNotExist()
        {
            var scene           = TestUtility.defaultScene;
            var model           = TestUtility.CreateGameObjectWithUndoableModelComponent();
            var modelGameObject = model.gameObject;

            Assert.AreEqual(0, CSGManager.TreeCount, "Expected 0 Trees to Exist");
            Assert.AreEqual(0, CSGManager.TreeNodeCount, "Expected 0 TreeNodes to Exist");
            Undo.FlushUndoRecordObjects();
            Undo.IncrementCurrentGroup();
            yield return(null);

            Assert.AreEqual(1, CSGManager.TreeCount, "Expected 1 Tree to Exist");
            Assert.AreEqual(1, CSGManager.TreeNodeCount, "Expected 1 TreeNode to Exist");

            Undo.PerformUndo();
            yield return(null);

            Assert.True(modelGameObject);
            Assert.False(model);
            Assert.AreEqual(0, CSGManager.TreeCount, "Expected 0 Trees to Exist");
            Assert.AreEqual(0, CSGManager.TreeNodeCount, "Expected 0 TreeNodes to Exist");
            Assert.AreEqual(0, CSGNodeHierarchyManager.RootCount(scene));
        }
        public IEnumerator CreateAndDestroyModelComponent_Undo_ModelExist()
        {
            var scene           = TestUtility.defaultScene;
            var model           = TestUtility.CreateGameObjectWithUndoableModelComponent();
            var modelGameObject = model.gameObject;

            Assert.AreEqual(0, CSGManager.TreeCount, "Expected 0 Trees to Exist");
            Assert.AreEqual(0, CSGManager.TreeNodeCount, "Expected 0 TreeNodes to Exist");
            Undo.FlushUndoRecordObjects();
            Undo.IncrementCurrentGroup();
            yield return(null);

            Assert.AreEqual(1, CSGManager.TreeCount, "Expected 1 Tree to Exist");
            Assert.AreEqual(1, CSGManager.TreeNodeCount, "Expected 1 TreeNode to Exist");

            Undo.DestroyObjectImmediate(model);
            yield return(null);

            Assert.True(modelGameObject);
            Assert.False(model);
            Assert.AreEqual(0, CSGManager.TreeCount, "Expected 0 Trees to Exist");
            Assert.AreEqual(0, CSGManager.TreeNodeCount, "Expected 0 TreeNodes to Exist");

            Undo.PerformUndo();
            yield return(null);

            model           = Object.FindObjectsOfType <ChiselModel>()[0];
            modelGameObject = model.gameObject;
            yield return(null);

            Assert.True(modelGameObject);
            Assert.True(model);
            Assert.AreEqual(1, CSGManager.TreeCount, "Expected 1 Tree to Exist");
            Assert.AreEqual(1, CSGManager.TreeNodeCount, "Expected 1 TreeNode to Exist");
            Assert.AreEqual(1, CSGNodeHierarchyManager.RootCount(scene));
        }
        public IEnumerator CreateAndDestroyBrushComponent_Undo_BrushExists()
        {
            var scene           = TestUtility.defaultScene;
            var brush           = TestUtility.CreateGameObjectWithUndoableBrushComponent();
            var brushGameObject = brush.gameObject;

            Assert.AreEqual(0, CSGManager.TreeBrushCount, "Expected 0 TreeBrushes to Exist");
            Assert.AreEqual(0, CSGManager.TreeNodeCount, "Expected 0 TreeNodes to Exist");
            Undo.FlushUndoRecordObjects();
            Undo.IncrementCurrentGroup();
            yield return(null);

            Assert.AreEqual(1, CSGManager.TreeBrushCount, "Expected 1 TreeBrush to Exist");
            Assert.AreEqual(2, CSGManager.TreeNodeCount, "Expected 2 TreeNodes to Exist");

            Undo.DestroyObjectImmediate(brush);
            yield return(null);

            Assert.True(brushGameObject);
            Assert.False(brush);
            Assert.AreEqual(0, CSGManager.TreeBrushCount, "Expected 0 TreeBrushes to Exist");
            Assert.AreEqual(0, CSGManager.TreeNodeCount, "Expected 0 TreeNodes to Exist");
            Assert.AreEqual(0, CSGManager.TreeCount, "Expected 0 Trees to Exist");
            Assert.AreEqual(0, CSGNodeHierarchyManager.RootCount(scene));

            Undo.PerformUndo();
            brush = brushGameObject.GetComponent <ChiselBrush>();
            yield return(null);

            Assert.True(brushGameObject);
            Assert.True(brush);
            Assert.AreEqual(1, CSGManager.TreeBrushCount, "Expected 1 TreeBrush to Exist");
            Assert.AreEqual(2, CSGManager.TreeNodeCount, "Expected 2 TreeNodes to Exist");
            Assert.AreEqual(1, CSGManager.TreeCount, "Expected 1 Tree to Exist");
            Assert.AreEqual(1, CSGNodeHierarchyManager.RootCount(scene));
        }
        public IEnumerator CreateBrush_UndoCreateGameObject_BrushDoesNotExist()
        {
            var scene           = TestUtility.defaultScene;
            var brush           = TestUtility.CreateUndoableGameObjectWithBrush();
            var brushGameObject = brush.gameObject;

            Assert.AreEqual(0, CSGManager.TreeBrushCount, "Expected 0 TreeBrushes to Exist");
            Assert.AreEqual(0, CSGManager.TreeNodeCount, "Expected 0 TreeNodes to Exist");
            Undo.FlushUndoRecordObjects();
            Undo.IncrementCurrentGroup();
            yield return(null);

            Assert.AreEqual(1, CSGManager.TreeBrushCount, "Expected 1 TreeBrush to Exist");
            Assert.AreEqual(2, CSGManager.TreeNodeCount, "Expected 2 TreeNodes to Exist");

            Undo.PerformUndo();
            yield return(null);

            Assert.False(brushGameObject);
            Assert.False(brush);
            Assert.AreEqual(0, CSGManager.TreeBrushCount, "Expected 0 TreeBrushes to Exist");
            Assert.AreEqual(0, CSGManager.TreeNodeCount, "Expected 0 TreeNodes to Exist");
            Assert.AreEqual(0, CSGNodeHierarchyManager.RootCount(scene));
        }
        public void ExtractMacroIsUndoable()
        {
            FunctionCallNodeModel[] log;
            CreateStackAndLogs(out _, out log);
            var binOp = GraphModel.CreateBinaryOperatorNode(BinaryOperatorKind.Add, Vector2.zero);
            var varA  = GraphModel.CreateVariableNode(m_ADecl, Vector2.zero);

            GraphModel.CreateEdge(log[0].GetParameterPorts().First(), binOp.OutputPort);
            GraphModel.CreateEdge(binOp.InputPortA, varA.OutputPort);
            GraphModel.CreateEdge(binOp.InputPortB, varA.OutputPort);
            Undo.IncrementCurrentGroup();
            TestPrereqActionPostreq(TestingMode.UndoRedo, () =>
            {
                RefreshReference(ref binOp);
                RefreshReference(ref varA);
                RefreshReference(ref log[0]);
                Assert.That(GraphModel.NodeModels.Count, Is.EqualTo(3));
                Assert.That(GraphModel.NodeModels.OfType <MacroRefNodeModel>().Count(), Is.Zero);
                Assert.That(binOp.InputPortA, Is.ConnectedTo(varA.OutputPort));
                Assert.That(binOp.InputPortB, Is.ConnectedTo(varA.OutputPort));
                Assert.That(binOp.OutputPort, Is.ConnectedTo(log[0].GetParameterPorts().First()));
                return(new RefactorExtractMacroAction(new List <IGraphElementModel> {
                    binOp
                }, Vector2.zero, null));
            }, () =>
            {
                RefreshReference(ref binOp);
                RefreshReference(ref varA);
                RefreshReference(ref log[0]);
                Assert.That(GraphModel.NodeModels.Count, Is.EqualTo(3));
                var macroRef = GraphModel.NodeModels.OfType <MacroRefNodeModel>().Single();
                Assert.That(macroRef, Is.Not.Null);
                Assert.That(macroRef.InputVariablePorts.First(), Is.ConnectedTo(varA.OutputPort));
                Assert.That(macroRef.OutputVariablePorts.First(), Is.ConnectedTo(log[0].GetParameterPorts().First()));
            });
        }
Beispiel #10
0
        static void CornersToAnchors()
        {
            if (Selection.transforms == null || Selection.transforms.Length == 0)
            {
                return;
            }
            Undo.IncrementCurrentGroup();
            Undo.SetCurrentGroupName("CornersToAnchors");
            var undoGroup = Undo.GetCurrentGroup();

            foreach (Transform transform in Selection.transforms)
            {
                RectTransform t = transform as RectTransform;
                Undo.RecordObject(t, "CornersToAnchors");

                if (t == null)
                {
                    return;
                }

                t.offsetMin = t.offsetMax = new Vector2(0, 0);
            }
            Undo.CollapseUndoOperations(undoGroup);
        }
Beispiel #11
0
        private void RemoveSelectedPoints()
        {
            Undo.IncrementCurrentGroup();

            Object[] newSelection = new Object[selection.Length];
            for (int i = 0; i < selection.Length; i++)
            {
                BezierSpline  spline = selection[i].spline;
                BezierPoint[] points = selection[i].points;

                for (int j = 0; j < points.Length; j++)
                {
                    Undo.DestroyObjectImmediate(points[j].gameObject);
                }

                if (spline)
                {
                    newSelection[i] = spline.gameObject;
                }
            }

            Selection.objects = newSelection;
            SceneView.RepaintAll();
        }
Beispiel #12
0
        static private void Execute()
        {
            Undo.IncrementCurrentGroup();
            Undo.SetCurrentGroupName("Merge Models");

            // Merge target is first selected GameObject
            var mergeTarget = Selection.activeGameObject;

            // Merge sources are subsequently selected GameObjects
            var mergeSources = new List <GameObject>();

            foreach (var gameObject in Selection.gameObjects)
            {
                if (gameObject == mergeTarget)
                {
                    continue;
                }
                mergeSources.Add(gameObject);
            }
            ApplyTo(mergeTarget, mergeSources.ToArray());

            // View merged prefab
            var prefabType = PrefabUtility.GetPrefabAssetType(mergeTarget);

            if (
                prefabType == PrefabAssetType.Regular ||
                prefabType == PrefabAssetType.Variant
                )
            {
                // NOTE: PrefabUtility.LoadPrefabContents(prefabPath) changes EditorSceneManager.previewSceneCount but not editor scene
                // NOTE: PrefabUtility.LoadPrefabContentsIntoPreviewScene(prefabPath, EditorSceneManager.NewPreviewScene()) does not work
                var prefabPath  = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(mergeTarget);
                var prefabAsset = AssetDatabase.LoadAssetAtPath <GameObject>(prefabPath);
                AssetDatabase.OpenAsset(prefabAsset);
            }
        }
Beispiel #13
0
        void DeleteRecursive(Transform parent)
        {
#if UNITY_EDITOR
            Undo.IncrementCurrentGroup();
            Undo.SetCurrentGroupName("Destroy All Scripts @" + parent);
            var undoGroupIndex = Undo.GetCurrentGroup();

            foreach (var gg in GetComponentsInChildren <MonoBehaviour>(true))
            {
                if (gg != this)
                {
                    Undo.DestroyObjectImmediate(gg);
                }
                //DestroyImmediate(gg);
            }

            if (removeSelf)
            {
                Undo.DestroyObjectImmediate(this);
            }

            Undo.CollapseUndoOperations(undoGroupIndex);
#endif
        }
Beispiel #14
0
        void CategoryMenu()
        {
            var selectedId = 0;

            EditorGUILayout.BeginHorizontal(GUIHelper.Styles.NoSpaceBox, GUILayout.ExpandWidth(true));
            {
                GUILayout.Label("Category".ToBold());
                GUI.backgroundColor = Color.yellow;
                selectedId          = EditorGUILayout.Popup(selectCategoryId, WindowHelper.Data.CategoryList, EditorStyles.toolbarPopup);
                GUI.backgroundColor = Color.white;
            }
            EditorGUILayout.EndHorizontal();

            if (selectCategoryId != selectedId)
            {
                Undo.IncrementCurrentGroup();
                UndoHelper.WindowUndo(UndoHelper.UNDO_CHANGE_CATEGORY);
                GUIUtility.keyboardControl = 0;
                selectLabel  = 0;
                footerToggle = new bool[] { true, false, false, false, false, false };
                WindowHelper.CurCategory(selectCategoryId).OnCategoryChange();
            }
            selectCategoryId = selectedId;
        }
Beispiel #15
0
        public IEnumerator CreateOperation_UndoCreateGameObject_OperationDoesNotExist()
        {
            var scene               = TestUtility.defaultScene;
            var operation           = TestUtility.CreateUndoableGameObjectWithOperation();
            var operationGameObject = operation.gameObject;

            Assert.AreEqual(0, CSGManager.TreeBranchCount, "Expected 0 TreeBranches to Exist");
            Assert.AreEqual(0, CSGManager.TreeNodeCount, "Expected 0 TreeNodes to Exist");
            Undo.FlushUndoRecordObjects();
            Undo.IncrementCurrentGroup();
            yield return(null);

            Assert.AreEqual(1, CSGManager.TreeBranchCount, "Expected 1 TreeBranch to Exist");
            Assert.AreEqual(2, CSGManager.TreeNodeCount, "Expected 2 TreeNodes to Exist");

            Undo.PerformUndo();
            yield return(null);

            Assert.False(operationGameObject);
            Assert.False(operation);
            Assert.AreEqual(0, CSGManager.TreeBranchCount, "Expected 0 TreeBranches to Exist");
            Assert.AreEqual(0, CSGManager.TreeNodeCount, "Expected 0 TreeNodes to Exist");
            Assert.AreEqual(0, ChiselNodeHierarchyManager.RootCount(scene));
        }
Beispiel #16
0
        private static void CreateUI(System.Func <GameObject> callback)
        {
            var canvasObj  = SecurityCheck();
            var gameObject = callback();

            if (!Selection.activeTransform)      // 在根目录创建的, 自动移动到 Canvas下
            {
                gameObject.transform.SetParent(canvasObj.transform);
            }
            else // (Selection.activeTransform)
            {
                if (!Selection.activeTransform.GetComponentInParent <Canvas>())    // 没有在UI树下
                {
                    gameObject.transform.SetParent(canvasObj.transform);
                }
                else
                {
                    //callback();
                }
            }

            Undo.IncrementCurrentGroup();
            Undo.RegisterCreatedObjectUndo(gameObject, "");
        }
Beispiel #17
0
        public override void OnInspectorGUI()
        {
            Color c = GUI.color;

            if (spline != null && !spline.Equals(null))
            {
                BezierUtils.DrawSplineInspectorGUI(spline);

                if (point == null || point.Equals(null))
                {
                    return;
                }

                EditorGUILayout.Space();
                DrawSeparator();

                GUILayout.BeginHorizontal();

                if (GUILayout.Button("<-", GUILayout.Width(45)))
                {
                    int prevIndex = spline.IndexOf(point) - 1;
                    if (prevIndex < 0)
                    {
                        prevIndex = spline.Count - 1;
                    }

                    Selection.activeTransform = spline[prevIndex].transform;
                    return;
                }

                GUILayout.Box("Selected Point: " + (spline.IndexOf(point) + 1) + " / " + spline.Count, GUILayout.ExpandWidth(true));

                if (GUILayout.Button("->", GUILayout.Width(45)))
                {
                    int nextIndex = spline.IndexOf(point) + 1;
                    if (nextIndex >= spline.Count)
                    {
                        nextIndex = 0;
                    }

                    Selection.activeTransform = spline[nextIndex].transform;
                    return;
                }

                GUILayout.EndHorizontal();

                EditorGUILayout.Space();

                if (GUILayout.Button("Decrement Point's Index"))
                {
                    int index    = spline.IndexOf(point);
                    int newIndex = index - 1;
                    if (newIndex < 0)
                    {
                        newIndex = spline.Count - 1;
                    }

                    if (index != newIndex)
                    {
                        Undo.IncrementCurrentGroup();
                        Undo.RegisterCompleteObjectUndo(point.transform.parent, "Change point index");

                        spline.SwapPointsAt(index, newIndex);
                        SceneView.RepaintAll();
                    }
                }

                if (GUILayout.Button("Increment Point's Index"))
                {
                    int index    = spline.IndexOf(point);
                    int newIndex = index + 1;
                    if (newIndex >= spline.Count)
                    {
                        newIndex = 0;
                    }

                    if (index != newIndex)
                    {
                        Undo.IncrementCurrentGroup();
                        Undo.RegisterCompleteObjectUndo(point.transform.parent, "Change point index");

                        spline.SwapPointsAt(index, newIndex);
                        SceneView.RepaintAll();
                    }
                }

                EditorGUILayout.Space();

                if (GUILayout.Button("Insert Point Before"))
                {
                    InsertNewPointAt(spline.IndexOf(point));
                }

                if (GUILayout.Button("Insert Point After"))
                {
                    InsertNewPointAt(spline.IndexOf(point) + 1);
                }

                EditorGUILayout.Space();

                if (GUILayout.Button("Duplicate Point"))
                {
                    DuplicatePointAt(spline.IndexOf(point));
                }

                EditorGUILayout.Space();
            }

            EditorGUI.BeginChangeCheck();
            BezierPoint.HandleMode handleMode = (BezierPoint.HandleMode)EditorGUILayout.EnumPopup("Handle Mode", point.handleMode);
            if (EditorGUI.EndChangeCheck())
            {
                Undo.RecordObject(point, "Change Point Handle Mode");
                point.handleMode = handleMode;

                SceneView.RepaintAll();
            }

            EditorGUILayout.Space();

            EditorGUI.BeginChangeCheck();
            Vector3 position = EditorGUILayout.Vector3Field("Preceding Control Point Local Position", point.precedingControlPointLocalPosition);

            if (EditorGUI.EndChangeCheck())
            {
                Undo.RecordObject(point, "Change Point Position");
                point.precedingControlPointLocalPosition = position;

                SceneView.RepaintAll();
            }

            EditorGUI.BeginChangeCheck();
            position = EditorGUILayout.Vector3Field("Following Control Point Local Position", point.followingControlPointLocalPosition);
            if (EditorGUI.EndChangeCheck())
            {
                Undo.RecordObject(point, "Change Point Position");
                point.followingControlPointLocalPosition = position;

                SceneView.RepaintAll();
            }

            EditorGUILayout.Space();

            if (GUILayout.Button("Swap Control Points"))
            {
                Undo.RecordObject(point, "Swap Control Points");
                Vector3 precedingControlPointLocalPos = point.precedingControlPointLocalPosition;
                point.precedingControlPointLocalPosition = point.followingControlPointLocalPosition;
                point.followingControlPointLocalPosition = precedingControlPointLocalPos;

                SceneView.RepaintAll();
            }

            EditorGUILayout.Space();

            DrawSeparator();

            if (spline != null && !spline.Equals(null))
            {
                GUI.color = RESET_POINT_BUTTON_COLOR;

                if (GUILayout.Button("Reset Point"))
                {
                    ResetEndPointAt(spline.IndexOf(point));
                    SceneView.RepaintAll();
                }

                EditorGUILayout.Space();

                GUI.color = REMOVE_POINT_BUTTON_COLOR;

                if (spline.Count <= 2)
                {
                    GUI.enabled = false;
                }

                if (GUILayout.Button("Remove Point"))
                {
                    RemovePointAt(spline.IndexOf(point));
                }

                GUI.enabled = true;
            }

            GUI.color = c;
        }
        void DrawNoSequenceGUI(WindowState windowState)
        {
            bool showCreateButton    = false;
            var  currentlySelectedGo = UnityEditor.Selection.activeObject != null ? UnityEditor.Selection.activeObject as GameObject : null;
            var  textContent         = DirectorStyles.noTimelineAssetSelected;
            var  existingDirector    = currentlySelectedGo != null?currentlySelectedGo.GetComponent <PlayableDirector>() : null;

            var existingAsset = existingDirector != null ? existingDirector.playableAsset : null;

            if (currentlySelectedGo != null && !TimelineUtility.IsPrefabOrAsset(currentlySelectedGo) && existingAsset == null)
            {
                showCreateButton = true;
                textContent      = new GUIContent(String.Format(DirectorStyles.createTimelineOnSelection.text, currentlySelectedGo.name, "a Director component and a Timeline asset"));
            }
            GUILayout.FlexibleSpace();
            GUILayout.BeginVertical();
            GUILayout.FlexibleSpace();

            GUILayout.Label(textContent);

            if (showCreateButton)
            {
                GUILayout.BeginHorizontal();
                var textSize = GUI.skin.label.CalcSize(textContent);
                GUILayout.Space((textSize.x / 2.0f) - (WindowConstants.createButtonWidth / 2.0f));
                if (GUILayout.Button("Create", GUILayout.Width(WindowConstants.createButtonWidth)))
                {
                    var message     = DirectorStyles.createNewTimelineText.text + " '" + currentlySelectedGo.name + "'";
                    var defaultName = currentlySelectedGo.name.EndsWith(DirectorStyles.newTimelineDefaultNameSuffix, StringComparison.OrdinalIgnoreCase)
                        ? currentlySelectedGo.name
                        : currentlySelectedGo.name + DirectorStyles.newTimelineDefaultNameSuffix;

                    // Use the project window path by default only if it's under the asset folder.
                    // Otherwise the saveFilePanel will reject the save (case 1289923)
                    var defaultPath = ProjectWindowUtil.GetActiveFolderPath();
                    if (!defaultPath.StartsWith("Assets/", StringComparison.OrdinalIgnoreCase))
                    {
                        defaultPath = "Assets";
                    }

                    string newSequencePath = EditorUtility.SaveFilePanelInProject(DirectorStyles.createNewTimelineText.text, defaultName, "playable", message, defaultPath);
                    if (!string.IsNullOrEmpty(newSequencePath))
                    {
                        var newAsset = TimelineUtility.CreateAndSaveTimelineAsset(newSequencePath);

                        Undo.IncrementCurrentGroup();

                        if (existingDirector == null)
                        {
                            existingDirector = Undo.AddComponent <PlayableDirector>(currentlySelectedGo);
                        }

                        existingDirector.playableAsset = newAsset;
                        SetCurrentTimeline(existingDirector);
                        windowState.previewMode = false;
                    }

                    // If we reach this point, the state of the panel has changed; skip the rest of this GUI phase
                    // Fixes: case 955831 - [OSX] NullReferenceException when creating a timeline on a selected object
                    GUIUtility.ExitGUI();
                }
                GUILayout.EndHorizontal();
            }
            GUILayout.FlexibleSpace();
            GUILayout.EndVertical();
            GUILayout.FlexibleSpace();
        }
        void StoreOnStateChanged()
        {
            var editorDataModel = m_Store.GetState().EditorDataModel;

            UpdateFlags currentUpdateFlags = editorDataModel.UpdateFlags;

            if (currentUpdateFlags == 0)
            {
                return;
            }

            IGraphModel graphModel = m_Store.GetState()?.CurrentGraphModel;

            m_LastGraphFilePath = graphModel?.GetAssetPath();

            if (m_Store.GetState().requestNodeAlignment)
            {
                if (graphModel is VSGraphModel vsGraphModel)
                {
                    IEnumerable <INodeModel> entryPoints = vsGraphModel.Stencil.GetEntryPoints(vsGraphModel);
                    vsGraphModel.LastChanges.ModelsToAutoAlign.AddRange(entryPoints);
                }
            }

            if (currentUpdateFlags.HasFlag(UpdateFlags.RequestCompilation))
            {
                if (!currentUpdateFlags.HasFlag(UpdateFlags.CompilationResult))
                {
                    m_IdleTimer = Stopwatch.StartNew();
                    m_CompilationPendingLabel.EnableInClassList(k_CompilationPendingClassName, true);
                }
            }

            // The GraphGeometry part must happen BEFORE the GraphTopology part
            // When the onboarding page is displayed before loading a graph, we need first to insert the graphview in
            // the hierarchy (UpdateGraphContainer) then create the graph itself (UpdateTopology)
            // Fixes VSB-257: edge bubbles rely on a specific event order (AttachedToPanelEvent must occur early enough or the
            // bubble won't get attached)
            if (currentUpdateFlags.HasFlag(UpdateFlags.GraphGeometry))
            {
                UpdateGraphContainer();
                m_BlankPage.UpdateUI();
                m_Menu.UpdateUI();

                m_GraphView.schedule.Execute(() =>
                {
                    if (editorDataModel.NodeToFrameGuid != default)
                    {
                        m_GraphView.PanToNode(editorDataModel.NodeToFrameGuid);
                        editorDataModel.NodeToFrameGuid = default;
                    }
                }).ExecuteLater(1);
            }

            if (currentUpdateFlags.HasFlag(UpdateFlags.GraphTopology))
            {
                if (graphModel != null)
                {
                    AnalyticsHelper.Instance.FlushNodeCreationEvent(NodeCreationEvent.Keep); // if it was cancelled, already done
                    if (!currentUpdateFlags.HasFlag(UpdateFlags.CompilationResult))
                    {
                        m_IdleTimer = Stopwatch.StartNew();
                        m_CompilationPendingLabel.EnableInClassList(k_CompilationPendingClassName, true);
                    }

                    m_GraphView.NotifyTopologyChange(graphModel);
                }

                // A topology change should update everything.
                m_GraphView.UIController.UpdateTopology();
                currentUpdateFlags |= UpdateFlags.All;
            }

            if (currentUpdateFlags.HasFlag(UpdateFlags.CompilationResult))
            {
                UpdateCompilationErrorsDisplay(m_Store.GetState());
            }

            ((VSGraphModel)m_Store.GetState().CurrentGraphModel)?.CheckIntegrity(GraphModel.Verbosity.Errors);

            if (graphModel != null && currentUpdateFlags.HasFlag(UpdateFlags.RequestRebuild))
            {
//                var editors = Resources.FindObjectsOfTypeAll<VisualBehaviourInspector>();
//                foreach (var editor in editors)
//                {
//                    editor.Repaint();
//                }
            }

            if (graphModel != null && graphModel.LastChanges.ModelsToAutoAlign.Any())
            {
                var elementsToAlign = graphModel.LastChanges.ModelsToAutoAlign
                                      .Select(n => m_GraphView.UIController.ModelsToNodeMapping[n]);
                m_GraphView.schedule.Execute(() =>
                {
                    m_GraphView.AlignGraphElements(elementsToAlign);

                    // Black magic counter spell to the curse cast by WindowsDropTargetImpl::DragPerformed.
                    // Basically our scheduled alignment gets called right in the middle of a DragExit
                    //      (yes DragExit even though the Drag was performed properly, Look at WindowsDropTargetImpl::DragPerformed you'll understand...)
                    // DragExit calls Application::TickTimer() in the middle of its execution, letting our scheduled task run
                    // right after the TickTimer() resumes, since we're supposedly doing a DragExit (so a drag cancel) it Undoes the CurrentGroup
                    // since we don't want our scheduled task to be canceled, we do the following
                    Undo.IncrementCurrentGroup();
                });
            }
        }
Beispiel #20
0
 /// <summary>
 /// Begin merging multiple singular undo operations into one group that get's treated as one
 /// </summary>
 public static void BeginRecordStack()
 {
     inRecordStack      = true;
     firstInRecordStack = true;
     Undo.IncrementCurrentGroup();
 }
Beispiel #21
0
 /// <summary>
 /// End merging multiple singular undo operations into one group that get's treated as one
 /// </summary>
 public static void EndRecordStack()
 {
     Undo.FlushUndoRecordObjects();
     Undo.IncrementCurrentGroup();
     inRecordStack = false;
 }
        public static GameObject Convert(
            GameObject toConvert,
            string fbxDirectoryFullPath    = null,
            string fbxFullPath             = null,
            string prefabDirectoryFullPath = null,
            string prefabFullPath          = null,
            ConvertToPrefabSettingsSerialize exportOptions = null)
        {
            if (toConvert == null)
            {
                throw new System.ArgumentNullException("toConvert");
            }

            if (PrefabUtility.IsPartOfNonAssetPrefabInstance(toConvert) && !PrefabUtility.IsOutermostPrefabInstanceRoot(toConvert))
            {
                return(null); // cannot convert in this scenario
            }

            // can't currently handle converting root of prefab in prefab preview scene
            if (SceneManagement.EditorSceneManager.IsPreviewSceneObject(toConvert) && toConvert.transform.parent == null)
            {
                return(null);
            }

            // If we selected the something that's already backed by an
            // FBX, don't export.
            var mainAsset = GetOrCreateFbxAsset(toConvert, fbxDirectoryFullPath, fbxFullPath, exportOptions);

            // if toConvert is part of a prefab asset and not an instance, make it an instance in a preview scene
            // so that we can unpack it and avoid issues with nested prefab references.
            bool isPrefabAsset = false;

            UnityEngine.SceneManagement.Scene?previewScene = null;
            if (PrefabUtility.IsPartOfPrefabAsset(toConvert) && PrefabUtility.GetPrefabInstanceStatus(toConvert) == PrefabInstanceStatus.NotAPrefab)
            {
                previewScene  = SceneManagement.EditorSceneManager.NewPreviewScene();
                toConvert     = PrefabUtility.InstantiatePrefab(toConvert, previewScene.Value) as GameObject;
                isPrefabAsset = true;
            }

            // don't need to undo if we are converting a prefab asset
            if (!isPrefabAsset)
            {
                Undo.IncrementCurrentGroup();
                Undo.SetCurrentGroupName(string.Format(UndoConversionGroup, toConvert.name));
            }

            // if root is a prefab instance, unpack it. Unpack everything below as well
            if (PrefabUtility.GetPrefabInstanceStatus(toConvert) == PrefabInstanceStatus.Connected)
            {
                Undo.RegisterFullObjectHierarchyUndo(toConvert, "unpack prefab instance");
                PrefabUtility.UnpackPrefabInstance(toConvert, PrefabUnpackMode.Completely, InteractionMode.AutomatedAction);
            }

            // create prefab variant from the fbx
            var fbxInstance = PrefabUtility.InstantiatePrefab(mainAsset) as GameObject;

            // replace hierarchy in the scene
            if (!isPrefabAsset && toConvert != null)
            {
                // don't worry about keeping the world position in the prefab, as we will fix the transform on the instance root
                fbxInstance.transform.SetParent(toConvert.transform.parent, worldPositionStays: false);
                fbxInstance.transform.SetSiblingIndex(toConvert.transform.GetSiblingIndex());
            }

            // copy components over
            UpdateFromSourceRecursive(fbxInstance, toConvert);

            // make sure we have a path for the prefab
            if (string.IsNullOrEmpty(prefabFullPath))
            {
                // Generate a unique filename.
                if (string.IsNullOrEmpty(prefabDirectoryFullPath))
                {
                    prefabDirectoryFullPath = UnityEditor.Formats.Fbx.Exporter.ExportSettings.PrefabAbsoluteSavePath;
                }
                else
                {
                    prefabDirectoryFullPath = Path.GetFullPath(prefabDirectoryFullPath);
                }
                var prefabBasename = ModelExporter.ConvertToValidFilename(toConvert.name + ".prefab");

                prefabFullPath = Path.Combine(prefabDirectoryFullPath, prefabBasename);
                if (File.Exists(prefabFullPath))
                {
                    prefabFullPath = IncrementFileName(prefabDirectoryFullPath, prefabFullPath);
                }
            }
            // make sure the directory structure exists
            var dirName = Path.GetDirectoryName(prefabFullPath);

            if (!Directory.Exists(dirName))
            {
                Directory.CreateDirectory(dirName);
            }
            var prefab = PrefabUtility.SaveAsPrefabAssetAndConnect(fbxInstance, ExportSettings.GetProjectRelativePath(prefabFullPath), InteractionMode.AutomatedAction);

            // replace hierarchy in the scene
            if (!isPrefabAsset && toConvert != null)
            {
                Undo.DestroyObjectImmediate(toConvert);
                Undo.RegisterCreatedObjectUndo(fbxInstance, UndoConversionCreateObject);
                SceneManagement.EditorSceneManager.MarkSceneDirty(fbxInstance.scene);

                Undo.IncrementCurrentGroup();
                return(fbxInstance);
            }
            else
            {
                Undo.ClearUndo(toConvert);
                Undo.ClearUndo(fbxInstance);
                Object.DestroyImmediate(fbxInstance);
                Object.DestroyImmediate(toConvert);
            }
            if (previewScene.HasValue)
            {
                SceneManagement.EditorSceneManager.ClosePreviewScene(previewScene.Value);
            }

            return(prefab);
        }
Beispiel #23
0
        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;
                }

                var modelCache = InternalCSGModelManager.GetModelCache(model);
                if (modelCache == null ||
                    !modelCache.GeneratedMeshes)
                {
                    continue;
                }

                var meshContainerChildren = modelCache.GeneratedMeshes.GetComponentsInChildren <Transform>();
                //for (int s = 0; s < MeshInstanceManager.SceneStates.Count; s++)
                //{
                //var sceneState		= MeshInstanceManager.SceneStates[s];
                //if (!sceneState.ParentMeshContainer)
                //	continue;
                //var meshContainerChildren = sceneState.ParentMeshContainer.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);
        }
 internal static IEnumerator WaitForFramesAndIncrementUndo(int numFrames) {
     yield return YieldUtility.WaitForFrames(numFrames);
     Undo.IncrementCurrentGroup();
 }
        public static GameObject[] CreateInstantiatedModelPrefab(
            GameObject[] unityGameObjectsToConvert)
        {
            var toExport = ModelExporter.RemoveRedundantObjects(unityGameObjectsToConvert);

            if (ExportSettings.instance.DisplayOptionsWindow)
            {
                if (toExport.Count == 1)
                {
                    var go = toExport.First();
                    if (PrefabUtility.IsPartOfNonAssetPrefabInstance(go) && !PrefabUtility.IsOutermostPrefabInstanceRoot(go))
                    {
                        DisplayInvalidSelectionDialog(go,
                                                      "Children of a Prefab instance cannot be converted.\nYou can open the Prefab in Prefab Mode or unpack the Prefab instance to convert it's children");
                        return(null);
                    }

                    if (PrefabUtility.IsPartOfPrefabAsset(go) && go.transform.parent != null)
                    {
                        DisplayInvalidSelectionDialog(go,
                                                      "Children of a Prefab Asset cannot be converted.\nYou can open the Prefab in Prefab Mode or unpack the Prefab instance to convert it's children");
                        return(null);
                    }

                    // can't currently handle converting root of prefab in prefab preview scene
                    if (SceneManagement.EditorSceneManager.IsPreviewSceneObject(go) && go.transform.parent == null)
                    {
                        DisplayInvalidSelectionDialog(go,
                                                      "Cannot convert Prefab root in the Prefab Preview Scene.\nYou can convert a Prefab Instance or convert the Prefab Asset directly in the Project view");
                        return(null);
                    }
                }
                ConvertToPrefabEditorWindow.Init(toExport);
                return(toExport.ToArray());
            }

            bool onlyPrefabAssets = ConvertToNestedPrefab.SetContainsOnlyPrefabAssets(unityGameObjectsToConvert);
            int  groupIndex       = -1;

            // If only Prefab Assets on disk are selected (nothing in the scene), then do not
            // try to undo as modifications on disk cannot be undone.
            if (!onlyPrefabAssets)
            {
                Undo.IncrementCurrentGroup();
                groupIndex = Undo.GetCurrentGroup();
                Undo.SetCurrentGroupName(UndoConversionCreateObject);
            }
            var converted     = new List <GameObject>();
            var exportOptions = ExportSettings.instance.ConvertToPrefabSettings.info;

            foreach (var go in toExport)
            {
                var convertedGO = Convert(go, exportOptions: exportOptions);
                if (convertedGO != null)
                {
                    converted.Add(convertedGO);
                }
            }
            if (!onlyPrefabAssets && groupIndex >= 0)
            {
                Undo.CollapseUndoOperations(groupIndex);
                Undo.IncrementCurrentGroup();
            }
            return(converted.ToArray());
        }
Beispiel #26
0
        protected override bool Export()
        {
            if (string.IsNullOrEmpty(ExportFileName))
            {
                Debug.LogError("FbxExporter: Please specify an fbx filename");
                return(false);
            }

            if (string.IsNullOrEmpty(m_prefabFileName))
            {
                Debug.LogError("FbxExporter: Please specify a prefab filename");
                return(false);
            }

            var fbxDirPath = ExportSettings.FbxAbsoluteSavePath;
            var fbxPath    = System.IO.Path.Combine(fbxDirPath, ExportFileName + ".fbx");

            var prefabDirPath = ExportSettings.PrefabAbsoluteSavePath;
            var prefabPath    = System.IO.Path.Combine(prefabDirPath, m_prefabFileName + ".prefab");

            if (GetToExport() == null)
            {
                Debug.LogError("FbxExporter: missing object for conversion");
                return(false);
            }

            int rectTransformCount = GetUIElementsInExportSetCount();

            if (rectTransformCount > 0)
            {
                // Warn that UI elements will break if converted
                string warning = string.Format("Warning: UI Components (ie, RectTransform) are not saved when converting to FBX.\n{0} item(s) in the selection will lose their UI components.",
                                               rectTransformCount);
                bool result = UnityEditor.EditorUtility.DisplayDialog(
                    string.Format("{0} Warning", ModelExporter.PACKAGE_UI_NAME), warning, "Convert and Lose UI", "Cancel");

                if (!result)
                {
                    return(false);
                }
            }

            if (SettingsObject.UseMayaCompatibleNames && SettingsObject.AllowSceneModification)
            {
                string warning = "Names of objects in the hierarchy may change with the Compatible Naming option turned on";
                if (ExportSetContainsAnimation())
                {
                    warning = "Compatible Naming option turned on. Names of objects in hierarchy may change and break animations.";
                }

                // give a warning dialog that indicates that names in the scene may change
                int result = UnityEditor.EditorUtility.DisplayDialogComplex(
                    string.Format("{0} Warning", ModelExporter.PACKAGE_UI_NAME), warning, "OK", "Turn off and continue", "Cancel"
                    );
                if (result == 1)
                {
                    // turn compatible naming off
                    SettingsObject.SetUseMayaCompatibleNames(false);
                }
                else if (result == 2)
                {
                    return(false);
                }
            }

            if (GetToExport().Length == 1)
            {
                var go = ModelExporter.GetGameObject(GetToExport()[0]);

                // Check if we'll be clobbering files. If so, warn the user
                // first and let them cancel out.
                if (!OverwriteExistingFile(prefabPath))
                {
                    return(false);
                }

                if (ConvertToNestedPrefab.WillExportFbx(go))
                {
                    if (!OverwriteExistingFile(fbxPath))
                    {
                        return(false);
                    }
                }

                ConvertToNestedPrefab.Convert(
                    go, fbxFullPath: fbxPath, prefabFullPath: prefabPath, exportOptions: ExportSettings.instance.ConvertToPrefabSettings.info
                    );
                return(true);
            }

            bool onlyPrefabAssets = ConvertToNestedPrefab.SetContainsOnlyPrefabAssets(GetToExport());
            int  groupIndex       = -1;

            // no need to undo if we aren't converting anything that's in the scene
            if (!onlyPrefabAssets)
            {
                Undo.IncrementCurrentGroup();
                groupIndex = Undo.GetCurrentGroup();
                Undo.SetCurrentGroupName(ConvertToNestedPrefab.UndoConversionCreateObject);
            }
            foreach (var obj in GetToExport())
            {
                // Convert, automatically choosing a file path that won't clobber any existing files.
                var go = ModelExporter.GetGameObject(obj);
                ConvertToNestedPrefab.Convert(
                    go, fbxDirectoryFullPath: fbxDirPath, prefabDirectoryFullPath: prefabDirPath, exportOptions: ExportSettings.instance.ConvertToPrefabSettings.info
                    );
            }
            if (!onlyPrefabAssets && groupIndex >= 0)
            {
                Undo.CollapseUndoOperations(groupIndex);
                Undo.IncrementCurrentGroup();
            }
            return(true);
        }
 /// <inheritdoc />
 public void IncrementCurrentGroup()
 {
     Undo.IncrementCurrentGroup();
 }
Beispiel #28
0
        private void DrawCellRangeConfig()
        {
            GUILayout.Space(3);
            GUILayout.Box("", new GUILayoutOption[] { GUILayout.Height(2f), GUILayout.ExpandWidth(true) });
            GUILayout.Space(3);

            EditorGUILayout.BeginHorizontal();
            {
                GUILayout.Label("Cell Range".ToBold(), GUILayout.Width(100));
                GUILayout.Label((StartCell + " : " + EndCell).ToMiddleBold());
            }
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();
            {
                Undo.IncrementCurrentGroup();
                UndoHelper.ConverterUndo(data, UndoHelper.UNDO_CONVERTER_EDIT);
                GUILayout.Label(UseAutomaticEnd ? "Start Row" : "Row Range", GUILayout.Width(100));
                if (UseAutomaticEnd)
                {
                    data.RowRange.x = EditorGUILayout.IntSlider(( int )RowRange.x, 1, MaxRow);
                    data.RowRange.y = RowRange.x + 1;
                }
                else
                {
                    EditorGUILayout.MinMaxSlider(ref data.RowRange.x, ref data.RowRange.y, 1, MaxRow);
                }
                data.RowRange.x = ( int )RowRange.x;
                data.RowRange.y = ( int )RowRange.y;
                StartRow        = ( int )RowRange.x;
            }
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();
            {
                Undo.IncrementCurrentGroup();
                UndoHelper.ConverterUndo(data, UndoHelper.UNDO_CONVERTER_EDIT);
                GUILayout.Label(UseAutomaticEnd ? "Start Col" : "Col Range", GUILayout.Width(100));
                if (UseAutomaticEnd)
                {
                    data.ColRange.x = EditorGUILayout.IntSlider(( int )ColRange.x, 1, MaxCol);
                    data.ColRange.y = ColRange.x + 1;
                }
                else
                {
                    EditorGUILayout.MinMaxSlider(ref data.ColRange.x, ref data.ColRange.y, 1, MaxCol);
                }
                data.ColRange.x = ( int )ColRange.x;
                data.ColRange.y = ( int )ColRange.y;
                StartCol        = ( int )ColRange.x;
            }
            EditorGUILayout.EndHorizontal();

            GUILayout.Space(5);

            EditorGUI.BeginDisabledGroup(!IsEdit);
            {
                EditorGUILayout.BeginHorizontal();
                {
                    Undo.IncrementCurrentGroup();
                    UndoHelper.ConverterUndo(data, UndoHelper.UNDO_CONVERTER_EDIT);
                    GUILayout.Label("Use Automatic End", GUILayout.Width(150));
                    UseAutomaticEnd = EditorGUILayout.Toggle(UseAutomaticEnd);
                }
                EditorGUILayout.EndHorizontal();

                EditorGUILayout.BeginHorizontal();
                {
                    Undo.IncrementCurrentGroup();
                    UndoHelper.ConverterUndo(data, UndoHelper.UNDO_CONVERTER_EDIT);
                    GUILayout.Label("Max Row Range", GUILayout.Width(100));
                    MaxRow = EditorGUILayout.IntField(MaxRow, GUILayout.Width(50));
                }
                EditorGUILayout.EndHorizontal();

                EditorGUILayout.BeginHorizontal();
                {
                    Undo.IncrementCurrentGroup();
                    UndoHelper.ConverterUndo(data, UndoHelper.UNDO_CONVERTER_EDIT);
                    GUILayout.Label("Max Col Range", GUILayout.Width(100));
                    MaxCol = EditorGUILayout.IntField(MaxCol, GUILayout.Width(50));
                }
                EditorGUILayout.EndHorizontal();
            }
            EditorGUI.EndDisabledGroup();
        }
Beispiel #29
0
        private void DrawSheetNameConfig()
        {
            GUILayout.Space(5);

            EditorGUILayout.BeginHorizontal();
            {
                Undo.IncrementCurrentGroup();
                UndoHelper.ConverterUndo(data, UndoHelper.UNDO_CONVERTER_EDIT);
                GUILayout.Label("Sheet Name".ToBold(), GUILayout.Width(100));
                SheetName = EditorGUILayout.TextField(SheetName);
            }
            EditorGUILayout.EndHorizontal();

            EditorGUI.BeginDisabledGroup(!IsEdit);
            {
                EditorGUILayout.BeginHorizontal();
                {
                    Undo.IncrementCurrentGroup();
                    UndoHelper.ConverterUndo(data, UndoHelper.UNDO_CONVERTER_EDIT);
                    GUILayout.Label("Multi Sheet Convert".ToBold(), GUILayout.Width(150));
                    MultiSheetConvertMode = EditorGUILayout.Toggle(MultiSheetConvertMode);
                }
                EditorGUILayout.EndHorizontal();
                if (MultiSheetConvertMode)
                {
                    EditorGUILayout.BeginHorizontal();
                    {
                        Undo.IncrementCurrentGroup();
                        UndoHelper.ConverterUndo(data, UndoHelper.UNDO_CONVERTER_EDIT);
                        GUILayout.Label("Min Sheet Index", GUILayout.Width(150));
                        MinSheetIndex = EditorGUILayout.IntField(MinSheetIndex, GUILayout.Width(50));
                    }
                    EditorGUILayout.EndHorizontal();
                    EditorGUILayout.BeginHorizontal();
                    {
                        Undo.IncrementCurrentGroup();
                        UndoHelper.ConverterUndo(data, UndoHelper.UNDO_CONVERTER_EDIT);
                        GUILayout.Label("Max Sheet Index", GUILayout.Width(150));
                        MaxSheetIndex = EditorGUILayout.IntField(MaxSheetIndex, GUILayout.Width(50));
                    }
                    EditorGUILayout.EndHorizontal();
                }
            }
            EditorGUI.EndDisabledGroup();

            if (MultiSheetConvertMode)
            {
                Undo.IncrementCurrentGroup();
                UndoHelper.ConverterUndo(data, UndoHelper.UNDO_CONVERTER_EDIT);
                GUILayout.Label(("Sheet Range : " + data.SheetIndexRange.x + " - " + data.SheetIndexRange.y).ToMiddleBold());
                EditorGUILayout.BeginHorizontal();
                {
                    GUILayout.Space(100);
                    EditorGUILayout.MinMaxSlider(ref data.SheetIndexRange.x, ref data.SheetIndexRange.y, MinSheetIndex, MaxSheetIndex);
                }
                EditorGUILayout.EndHorizontal();
                data.SheetIndexRange.x = ( int )SheetIndexRange.x;
                data.SheetIndexRange.y = ( int )SheetIndexRange.y;
                EditorGUILayout.HelpBox("SheetName Example: mysheet_#NUM#", MessageType.Info);
            }
        }
        void OnGUI()
        {
#if FLUX_PROFILE
            Profiler.BeginSample("Flux OnGUI");
#endif
            if (_sequenceEditor == null)
            {
                return;
            }

            Rect currentWindowRect = position;
            currentWindowRect.x = 0;
            currentWindowRect.y = 0;

            if (currentWindowRect != _windowRect)
            {
                RebuildLayout();
            }

            if (Event.current.type == EventType.Ignore)
            {
                EditorGUIUtility.hotControl = 0;
            }

            GTimelineEditor sequence = _sequenceEditor.GetSequence();

            if (sequence == null)
            {
                ShowNotification(new GUIContent("Select Or Create Sequence"));
            }
            else if (Event.current.isKey)
            {
                if (Event.current.keyCode == KeyCode.Space)
                {
                    if (Event.current.type == EventType.KeyUp)
                    {
                        if (_sequenceEditor.IsPlaying)
                        {
                            if (Event.current.shift)
                            {
                                Stop();
                            }
                            else
                            {
                                Pause();
                            }
                        }
                        else
                        {
                            Play(Event.current.shift);
                        }


                        Repaint();
                    }
                    Event.current.Use();
                }

                if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Return)
                {
                    EditorGUIUtility.keyboardControl = 0;
                    Event.current.Use();
                    Repaint();
                }
            }


            // header
            _windowHeader.OnGUI();

            if (sequence == null)
            {
                return;
            }

            // toolbar
            _toolbar.OnGUI();

            switch (Event.current.type)
            {
            case EventType.KeyDown:
                if (Event.current.keyCode == KeyCode.Backspace || Event.current.keyCode == KeyCode.Delete)
                {
                    _sequenceEditor.DestroyEvents(_sequenceEditor._selectedEvents);
                    Event.current.Use();
                }
                else if (Event.current.keyCode == KeyCode.K && _sequenceEditor.GetSequence().GetCurrentFrame() >= 0)
                {
                    _sequenceEditor.AddEvent(_sequenceEditor.GetSequence().GetCurrentFrame());
                    Event.current.Use();
                }
                break;

            case EventType.MouseDown:
                break;

            case EventType.MouseUp:
                break;
            }

            if (Event.current.type == EventType.ValidateCommand)
            {
                Repaint();
            }

            _sequenceEditor.OnGUI();


            // because of a bug with windows editor, we have to not catch right button
            // otherwise ContextClick doesn't get called
            if (Event.current.type == EventType.MouseUp && Event.current.button != 1)
            {
                Event.current.Use();
            }

            // handle drag & drop
            if (Event.current.type == EventType.DragUpdated)
            {
                if (_windowRect.Contains(Event.current.mousePosition))
                {
                    DragAndDrop.visualMode = DragAndDropVisualMode.Link;
                    Event.current.Use();
                }
            }
            else if (Event.current.type == EventType.DragPerform)
            {
                if (_windowRect.Contains(Event.current.mousePosition))
                {
                    foreach (UnityEngine.Object obj in DragAndDrop.objectReferences)
                    {
                        if (!(obj is GameObject))
                        {
                            continue;
                        }

                        PrefabType prefabType = PrefabUtility.GetPrefabType(obj);
                        if (prefabType == PrefabType.ModelPrefab || prefabType == PrefabType.Prefab)
                        {
                            continue;
                        }

                        Undo.IncrementCurrentGroup();
                        UnityEngine.Object[] objsToSave = new UnityEngine.Object[] { sequence, this };

                        Undo.RegisterCompleteObjectUndo(objsToSave, string.Empty);

                        GameObject timelineGO = new GameObject(obj.name);

                        FTimeline timeline = timelineGO.AddComponent <Flux.FTimeline>();
                        timeline.SetOwner(((GameObject)obj).transform);
                        sequence.Add(timeline);

                        Undo.RegisterCompleteObjectUndo(objsToSave, string.Empty);
                        Undo.RegisterCreatedObjectUndo(timeline.gameObject, "create Timeline");
                        Undo.CollapseUndoOperations(Undo.GetCurrentGroup());
                    }
                    RemoveNotification();
                    Event.current.Use();
                    DragAndDrop.AcceptDrag();
                    Refresh();
                    EditorGUIUtility.ExitGUI();
                }
            }

            if (Event.current.type == EventType.Repaint)
            {
                Handles.DrawLine(new Vector3(_windowHeaderRect.xMin, _windowHeaderRect.yMax, 0), new Vector3(_windowHeaderRect.xMax - GTimelineEditor.RIGHT_BORDER, _windowHeaderRect.yMax, 0));
            }
#if FLUX_PROFILE
            Profiler.EndSample();
#endif
        }