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);
        }
예제 #2
0
        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);
            }
        }
예제 #3
0
        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);
        }
예제 #4
0
        VFXContextController CreateAllBlocks(VFXContextType type)
        {
            var initContextDesc = VFXLibrary.GetContexts().Where(t => t.model.contextType == type).First();

            var newContext = m_ViewController.AddVFXContext(new Vector2(300, 2000), initContextDesc);

            m_ViewController.ApplyChanges();

            var contextController = m_ViewController.nodes.Where(t => t is VFXContextController && (t as VFXContextController).model == newContext).First() as VFXContextController;

            Assert.AreEqual(contextController.model, newContext);

            // Adding every block compatible with an init context

            var newBlocks = new List <VFXBlock>();

            foreach (var block in VFXLibrary.GetBlocks().Where(t => t.AcceptParent(newContext)))
            {
                var newBlock = block.CreateInstance();
                contextController.AddBlock(0, newBlock);
                newBlocks.Add(newBlock);
            }

            m_ViewController.ApplyChanges();

            foreach (var newBlock in newBlocks)
            {
                Assert.AreEqual(contextController.blockControllers.Where(t => t.model == newBlock).Count(), 1, "Failing Block" + newBlock.name + "in context" + newContext.name);

                var blockController = contextController.blockControllers.Where(t => t.model == newBlock).First() as VFXBlockController;

                Assert.NotNull(blockController);
            }

            return(contextController);
        }
예제 #5
0
        public IEnumerator Create_Prefab_Modify_And_Expect_No_Override()
        {
            var graph = VFXTestCommon.MakeTemporaryGraph();
            var parametersVector3Desc = VFXLibrary.GetParameters().Where(o => o.model.type == typeof(Vector3)).First();

            var exposedName = "ghjkl";
            var parameter   = parametersVector3Desc.CreateInstance();

            parameter.SetSettingValue("m_ExposedName", exposedName);
            parameter.SetSettingValue("m_Exposed", true);
            parameter.value = new Vector3(0, 0, 0);
            graph.AddChild(parameter);

            AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(graph));

            var mainObject = MakeTemporaryGameObject();

            var vfx = mainObject.AddComponent <VisualEffect>();

            vfx.visualEffectAsset = graph.visualEffectResource.asset;
            Assert.IsTrue(vfx.HasVector3(exposedName));
            vfx.SetVector3(exposedName, new Vector3(1, 2, 3));

            GameObject newGameObject, prefabInstanceObject;

            MakeTemporaryPrebab(mainObject, out newGameObject, out prefabInstanceObject);
            GameObject.DestroyImmediate(mainObject);

            var currentPrefabInstanceObject = PrefabUtility.InstantiatePrefab(prefabInstanceObject) as GameObject;

            yield return(null);

            var vfxInPrefab      = prefabInstanceObject.GetComponent <VisualEffect>();
            var expectedNewValue = new Vector3(4, 5, 6);

            if (k_HasFixed_DisabledState)
            {
                Assert.IsTrue(vfxInPrefab.HasVector3(exposedName));
                vfxInPrefab.SetVector3(exposedName, expectedNewValue);
            }
            else
            {
                /* modifying prefab using serialized property */
                var editor = Editor.CreateEditor(vfxInPrefab);
                editor.serializedObject.Update();

                var propertySheet = editor.serializedObject.FindProperty("m_PropertySheet");
                var fieldName     = VisualEffectSerializationUtility.GetTypeField(VFXExpression.TypeToType(VFXValueType.Float3)) + ".m_Array";
                var vfxField      = propertySheet.FindPropertyRelative(fieldName);

                Assert.AreEqual(1, vfxField.arraySize);

                var property = vfxField.GetArrayElementAtIndex(0);
                property = property.FindPropertyRelative("m_Value");

                property.vector3Value = expectedNewValue;

                editor.serializedObject.ApplyModifiedPropertiesWithoutUndo();
                GameObject.DestroyImmediate(editor);
                EditorUtility.SetDirty(prefabInstanceObject);
            }
            //AssetDatabase.SaveAssets(); //Helps debug but not necessary

            PrefabUtility.SavePrefabAsset(prefabInstanceObject);
            yield return(null);

            var currentVFXInstanciedFromPrefab = currentPrefabInstanceObject.GetComponent <VisualEffect>();

            Assert.IsTrue(currentVFXInstanciedFromPrefab.HasVector3(exposedName));
            var refExposedValue = currentVFXInstanciedFromPrefab.GetVector3(exposedName);

            var newInstanciedFromPrefab    = PrefabUtility.InstantiatePrefab(prefabInstanceObject) as GameObject;
            var newVFXInstanciedFromPrefab = newInstanciedFromPrefab.GetComponent <VisualEffect>();

            Assert.IsTrue(newVFXInstanciedFromPrefab.HasVector3(exposedName));
            var newExposedValue = newVFXInstanciedFromPrefab.GetVector3(exposedName);

            var overrides = PrefabUtility.GetObjectOverrides(currentPrefabInstanceObject);

            Assert.AreEqual(newExposedValue.x, expectedNewValue.x); Assert.AreEqual(newExposedValue.y, expectedNewValue.y); Assert.AreEqual(newExposedValue.z, expectedNewValue.z); //< Expected to work
            if (k_HasFixed_PrefabOverride)
            {
                //Known issue : Failing due to fogbugz 1117103
                Assert.AreEqual(refExposedValue.x, expectedNewValue.x); Assert.AreEqual(refExposedValue.y, expectedNewValue.y); Assert.AreEqual(refExposedValue.z, expectedNewValue.z);
                Assert.IsEmpty(overrides);
            }
        }
예제 #6
0
        static VFXModelDescriptor <VFXOperator> GetTotalTimeOperator()
        {
            string opName = ObjectNames.NicifyVariableName(VFXExpressionOperation.TotalTime.ToString());

            return(VFXLibrary.GetOperators().First(o => o.name == opName));
        }
예제 #7
0
        protected override IEnumerable <Descriptor> GetDescriptors()
        {
            IEnumerable <Descriptor> descs = Enumerable.Empty <Descriptor>();

            if (m_AcceptedTypes == null || m_AcceptedTypes.Contains(typeof(VFXContext)))
            {
                var descriptorsContext = VFXLibrary.GetContexts().Select(o =>
                {
                    return(new Descriptor()
                    {
                        modelDescriptor = o,
                        category = ComputeCategory("Context", o),
                        name = o.name
                    });
                }).OrderBy(o => o.category + o.name);

                descs = descs.Concat(descriptorsContext);
            }
            if (m_AcceptedTypes == null || m_AcceptedTypes.Contains(typeof(VFXOperator)))
            {
                var descriptorsOperator = VFXLibrary.GetOperators().Select(o =>
                {
                    return(new Descriptor()
                    {
                        modelDescriptor = o,
                        category = ComputeCategory("Operator", o),
                        name = o.name
                    });
                });

                descriptorsOperator = descriptorsOperator.Concat(SubGraphCache.GetItems(typeof(VisualEffectSubgraphOperator)).Select(
                                                                     t => new Descriptor()
                {
                    modelDescriptor = t.path,
                    category        = "Operator/" + t.category,
                    name            = t.name
                }
                                                                     ));

                descs = descs.Concat(descriptorsOperator.OrderBy(o => o.category + o.name));
            }
            if (m_AcceptedTypes == null || m_AcceptedTypes.Contains(typeof(VFXParameter)))
            {
                var parameterDescriptors = m_Controller.parameterControllers.Select(t =>
                                                                                    new Descriptor
                {
                    modelDescriptor = t,
                    category        = string.IsNullOrEmpty(t.model.category) ? "Property" : string.Format("Property/{0}", t.model.category),
                    name            = t.exposedName
                }
                                                                                    ).OrderBy(t => t.category);
                descs = descs.Concat(parameterDescriptors);
            }
            if (m_AcceptedTypes == null)
            {
                var systemFiles = System.IO.Directory.GetFiles(VisualEffectAssetEditorUtility.templatePath).Where(t => Path.GetExtension(t) == VisualEffectResource.Extension).Select(t => t.Replace("\\", "/"));

                var systemDesc = systemFiles.Select(t => new Descriptor()
                {
                    modelDescriptor = t.Replace(VisualEffectGraphPackageInfo.fileSystemPackagePath, VisualEffectGraphPackageInfo.assetPackagePath), category = "System", name = System.IO.Path.GetFileNameWithoutExtension(t)
                });

                descs = descs.Concat(systemDesc);
            }
            var groupNodeDesc = new Descriptor()
            {
                modelDescriptor = new GroupNodeAdder(),
                category        = "Misc",
                name            = "Group Node"
            };

            descs = descs.Concat(Enumerable.Repeat(groupNodeDesc, 1));

            if (m_Filter == null)
            {
                return(descs);
            }
            else
            {
                return(descs.Where(t => m_Filter(t)));
            }
        }
        public void CopyPasteContextWithBlock()
        {
            var initContextDesc = VFXLibrary.GetContexts().Where(t => t.name == "Initialize").First();

            var newContext = m_ViewController.AddVFXContext(new Vector2(100, 100), initContextDesc);

            m_ViewController.ApplyChanges();

            Assert.AreEqual(m_ViewController.allChildren.Where(t => t is VFXContextController).Count(), 1);

            var contextController = m_ViewController.allChildren.OfType <VFXContextController>().First();

            Assert.AreEqual(contextController.model, newContext);

            var flipBookBlockDesc = VFXLibrary.GetBlocks().First(t => t.name == "Set Tex Index ");

            contextController.AddBlock(0, flipBookBlockDesc.CreateInstance());

            m_ViewController.ApplyChanges();

            VFXViewWindow window = EditorWindow.GetWindow <VFXViewWindow>();

            VFXView view = window.graphView;

            view.controller = m_ViewController;

            view.ClearSelection();
            foreach (var element in view.Query().OfType <GraphElement>().ToList().OfType <ISelectable>())
            {
                view.AddToSelection(element);
            }

            VFXSlot boundsSlot = newContext.GetInputSlot(0);

            AABox originalBounds = new AABox()
            {
                center = Vector3.one, size = Vector3.one * 10
            };

            boundsSlot.value = originalBounds;

            VFXBlock flipBookBlock = m_ViewController.contexts.First().blockControllers.First().model;
            VFXSlot  minValueSlot  = flipBookBlock.GetInputSlot(0);


            float originalMinValue = 123.456f;

            minValueSlot.value = originalMinValue;

            view.CopySelectionCallback();

            boundsSlot.value = new AABox()
            {
                center = Vector3.zero, size = Vector3.zero
            };
            minValueSlot.value = 789f;

            view.PasteCallback();
            var elements = view.Query().OfType <GraphElement>().ToList();

            var contexts    = elements.OfType <VFXContextUI>().ToArray();
            var copyContext = elements.OfType <VFXContextUI>().Select(t => t.controller).First(t => t.model != newContext).model;

            var copyBoundsSlot = copyContext.GetInputSlot(0);
            var copyMinSlot    = copyContext[0].GetInputSlot(0);

            Assert.AreEqual((AABox)copyBoundsSlot.value, originalBounds);
            Assert.AreEqual((float)copyMinSlot.value, originalMinValue);
            Assert.AreNotEqual(copyContext.position, newContext.position);


            view.PasteCallback();

            elements = view.Query().OfType <GraphElement>().ToList();
            contexts = elements.OfType <VFXContextUI>().ToArray();

            var copy2Context = contexts.First(t => t.controller.model != newContext && t.controller.model != copyContext).controller.model;

            Assert.AreNotEqual(copy2Context.position, newContext.position);
            Assert.AreNotEqual(copy2Context.position, copyContext.position);
        }
        public void UndoRedoContextLinkMultiSlot()
        {
            Func <VFXContextController[]> fnContextController = delegate()
            {
                m_ViewController.ApplyChanges();
                return(m_ViewController.allChildren.OfType <VFXContextController>().Cast <VFXContextController>().ToArray());
            };

            Func <VFXContextController> fnSpawner = delegate()
            {
                var controller = fnContextController();
                return(controller.FirstOrDefault(o => o.model.name.Contains("Spawn")));
            };

            Func <string, VFXContextController> fnEvent = delegate(string name)
            {
                var controller = fnContextController();
                var allEvent   = controller.Where(o => o.model.name.Contains("Event"));
                return(allEvent.FirstOrDefault(o => (o.model as VFXBasicEvent).eventName == name) as VFXContextController);
            };

            Func <VFXContextController> fnStart = delegate()
            {
                return(fnEvent("Start"));
            };

            Func <VFXContextController> fnStop = delegate()
            {
                return(fnEvent("Stop"));
            };

            Func <int> fnFlowEdgeCount = delegate()
            {
                m_ViewController.ApplyChanges();
                return(m_ViewController.allChildren.OfType <VFXFlowEdgeController>().Count());
            };

            var contextSpawner = VFXLibrary.GetContexts().FirstOrDefault(o => o.name.Contains("Spawn"));
            var contextEvent   = VFXLibrary.GetContexts().FirstOrDefault(o => o.name.Contains("Event"));

            m_ViewController.AddVFXContext(new Vector2(1, 1), contextSpawner);
            var eventStartController = m_ViewController.AddVFXContext(new Vector2(2, 2), contextEvent) as VFXBasicEvent;
            var eventStopController  = m_ViewController.AddVFXContext(new Vector2(3, 3), contextEvent) as VFXBasicEvent;

            eventStartController.SetSettingValue("eventName", "Start");
            eventStopController.SetSettingValue("eventName", "Stop");

            //Creation
            var flowEdge = new VFXFlowEdgeController(fnSpawner().flowInputAnchors.ElementAt(0), fnStart().flowOutputAnchors.FirstOrDefault());

            Undo.IncrementCurrentGroup();
            m_ViewController.AddElement(flowEdge);
            Assert.AreEqual(1, fnFlowEdgeCount());

            flowEdge = new VFXFlowEdgeController(fnSpawner().flowInputAnchors.ElementAt(1), fnStop().flowOutputAnchors.FirstOrDefault());

            Undo.IncrementCurrentGroup();
            m_ViewController.AddElement(flowEdge);
            Assert.AreEqual(2, fnFlowEdgeCount());

            //Test a single deletion
            var allFlowEdge = m_ViewController.allChildren.OfType <VFXFlowEdgeController>().ToArray();

            // Integrity test...
            var inputSlotIndex  = allFlowEdge.Select(o => (o.input as VFXFlowAnchorController).slotIndex).OrderBy(o => o).ToArray();
            var outputSlotIndex = allFlowEdge.Select(o => (o.output as VFXFlowAnchorController).slotIndex).OrderBy(o => o).ToArray();

            Assert.AreEqual(inputSlotIndex[0], 0);
            Assert.AreEqual(inputSlotIndex[1], 1);
            Assert.AreEqual(outputSlotIndex[0], 0);
            Assert.AreEqual(outputSlotIndex[1], 0);

            var edge = allFlowEdge.First(o => o.input == fnSpawner().flowInputAnchors.ElementAt(1) && o.output == fnStop().flowOutputAnchors.FirstOrDefault());

            Undo.IncrementCurrentGroup();
            m_ViewController.RemoveElement(edge);
            Assert.AreEqual(1, fnFlowEdgeCount());

            Undo.PerformUndo();
            Assert.AreEqual(2, fnFlowEdgeCount());

            Undo.PerformRedo();
            Assert.AreEqual(1, fnFlowEdgeCount());

            Undo.PerformUndo();
            Assert.AreEqual(2, fnFlowEdgeCount());

            //Global Deletion
            Undo.PerformUndo();
            Assert.AreEqual(1, fnFlowEdgeCount());

            Undo.PerformUndo();
            Assert.AreEqual(0, fnFlowEdgeCount());
        }
        public void UndoRedoOperatorLinkToBlock()
        {
            Func <VFXContextController> fnFirstContextController = delegate()
            {
                m_ViewController.ApplyChanges();
                return(m_ViewController.allChildren.OfType <VFXContextController>().FirstOrDefault());
            };

            Func <Type, VFXNodeController> fnFindController = delegate(Type type)
            {
                m_ViewController.ApplyChanges();
                var allController = m_ViewController.allChildren.OfType <VFXNodeController>();
                return(allController.FirstOrDefault(o => type.IsInstanceOfType(o.slotContainer)));
            };

            Func <VFXBlockController> fnFirstBlockController = delegate()
            {
                m_ViewController.ApplyChanges();
                return(m_ViewController.allChildren.OfType <VFXContextController>().SelectMany(t => t.blockControllers).FirstOrDefault());
            };

            Func <VFXDataEdgeController> fnFirstEdgeController = delegate()
            {
                m_ViewController.ApplyChanges();
                return(m_ViewController.allChildren.OfType <VFXDataEdgeController>().FirstOrDefault());
            };

            Undo.IncrementCurrentGroup();
            var cosDesc            = VFXLibrary.GetOperators().FirstOrDefault(o => o.name == "Cosine");
            var contextUpdateDesc  = VFXLibrary.GetContexts().FirstOrDefault(o => o.name.Contains("Update"));
            var blockAttributeDesc = VFXLibrary.GetBlocks().FirstOrDefault(o => o.modelType == typeof(Block.SetAttribute));

            m_ViewController.AddVFXOperator(new Vector2(0, 0), cosDesc);
            m_ViewController.AddVFXContext(new Vector2(2, 2), contextUpdateDesc);
            var blockAttribute = blockAttributeDesc.CreateInstance();

            blockAttribute.SetSettingValue("attribute", "color");
            blockAttribute.SetSettingValue("Source", Block.SetAttribute.ValueSource.Slot);
            fnFirstContextController().AddBlock(0, blockAttribute);

            var firstBlockController = fnFirstBlockController();
            var cosController        = fnFindController(typeof(Operator.Cosine));

            var blockInputPorts = firstBlockController.inputPorts.ToArray();
            var cosOutputPorts  = cosController.outputPorts.ToArray();

            var edgeController = new VFXDataEdgeController(blockInputPorts[0], cosOutputPorts[0]);

            m_ViewController.AddElement(edgeController);
            Undo.IncrementCurrentGroup();

            m_ViewController.RemoveElement(fnFirstEdgeController());
            Assert.IsNull(fnFirstEdgeController());
            Undo.IncrementCurrentGroup();

            Undo.PerformUndo();
            Assert.IsNotNull(fnFirstEdgeController());

            Undo.PerformRedo();
            Assert.IsNull(fnFirstEdgeController());
        }
예제 #11
0
            void TransfertOperatorOutputEdges()
            {
                var traversingOutEdges = new Dictionary <VFXDataAnchorController, List <VFXDataAnchorController> >();

                foreach (var edge in m_SourceController.dataEdges.Where(
                             t =>
                {
                    if (t.output.sourceNode is VFXParameterNodeController)
                    {
                        return(false);
                    }
                    var inputInControllers = m_SourceControllersWithBlocks.Contains(t.input.sourceNode);
                    var outputInControllers = m_SourceControllersWithBlocks.Contains(t.output.sourceNode);

                    return(!inputInControllers && outputInControllers);
                }
                             ))
                {
                    List <VFXDataAnchorController> inputs = null;
                    if (!traversingOutEdges.TryGetValue(edge.output, out inputs))
                    {
                        inputs = new List <VFXDataAnchorController>();
                        traversingOutEdges[edge.output] = inputs;
                    }

                    inputs.Add(edge.input);
                }

                var newSourceOutputs = traversingOutEdges.Keys.ToArray();

                for (int i = 0; i < newSourceOutputs.Length; ++i)
                {
                    VFXParameter newTargetParameter = m_TargetController.AddVFXParameter(Vector2.zero, VFXLibrary.GetParameters().First(t => t.model.type == newSourceOutputs[i].portType));

                    m_TargetController.LightApplyChanges();

                    VFXParameterController newTargetParamController = m_TargetController.GetParameterController(newTargetParameter);
                    newTargetParamController.isOutput = true;

                    var inputs = traversingOutEdges[newSourceOutputs[i]];

                    var linkedParameter = inputs.FirstOrDefault(t => t.sourceNode is VFXParameterNodeController);
                    if (linkedParameter != null)
                    {
                        newTargetParamController.exposedName = (linkedParameter.sourceNode as VFXParameterNodeController).parentController.exposedName;
                    }
                    else
                    {
                        newTargetParamController.exposedName = newSourceOutputs[i].name;
                    }

                    //first the equivalent of sourceInput in the target

                    VFXNodeController targetNode = null;

                    if (newSourceOutputs[i].sourceNode is VFXBlockController)
                    {
                        var blockController = newSourceOutputs[i].sourceNode as VFXBlockController;
                        if (m_TargetBlocks != null)
                        {
                            targetNode = m_TargetBlocks[m_SourceBlockControllers.IndexOf(blockController)];
                        }
                        else
                        {
                            var targetContext = m_TargetControllers[m_SourceControllers.IndexOf(blockController.contextController)] as VFXContextController;

                            targetNode = targetContext.blockControllers[blockController.index];
                        }
                    }
                    else
                    {
                        targetNode = m_TargetControllers[m_SourceControllers.IndexOf(newSourceOutputs[i].sourceNode)];
                    }

                    VFXDataAnchorController targetAnchor = targetNode.outputPorts.FirstOrDefault(t => t.path == newSourceOutputs[i].path);

                    if (targetAnchor != null)
                    {
                        VFXNodeController parameterNode = m_TargetController.AddVFXParameter(targetNode.position + new Vector2(400, 0), newTargetParamController, null);

                        // Link the parameternode and the input in the target
                        m_TargetController.CreateLink(parameterNode.inputPorts[0], targetAnchor);

                        if (m_SourceSlotContainer is VFXOperator)
                        {
                            (m_SourceSlotContainer as VFXOperator).ResyncSlots(true);
                        }
                        m_SourceNodeController.ApplyChanges();
                    }
                    //Link all the outputs to the matching input of the subgraph
                    foreach (var input in inputs)
                    {
                        var port = m_SourceNodeController.outputPorts.FirstOrDefault(t => t.model == m_SourceSlotContainer.outputSlots.Last());
                        if (port != null)
                        {
                            m_SourceController.CreateLink(input, port);
                        }
                    }
                }
            }
예제 #12
0
        //[UnityTest] Not really a test but helper to profile the controller invalidation.
        public IEnumerator ExperimentCreateAllBlocksTiming([ValueSource(nameof(kApplyChange))] bool applyChanges, [ValueSource(nameof(kApplyChange))] bool blocks)
        {
            var referenceBlock    = VFXLibrary.GetBlocks().Where(t => t.model is Block.KillSphere).First();
            var referenceOperator = VFXLibrary.GetOperators().Where(t => t.model is Operator.DistanceToSphere).First();
            var referenceContext  = VFXLibrary.GetContexts().Where(t => t.model is VFXBasicUpdate).First();

            var param = new CreateAllBlockParam()
            {
                name        = "Test",
                destContext = referenceContext
            };

            var results = new List <(int, double)>();

            int modelCount = 1;

            while (modelCount < 512)
            {
                var watch = new System.Diagnostics.Stopwatch();
                watch.Start();

                if (modelCount >= 256)
                {
                    modelCount += 128;
                }
                else
                {
                    modelCount *= 2;
                }

                var controller = StartEditTestAsset();

                if (blocks)
                {
                    param.blocks = Enumerable.Repeat(referenceBlock, modelCount);
                    CreateAllBlocksExperiment(controller, param.destContext, param.blocks, applyChanges);
                }
                else
                {
                    var operators = Enumerable.Repeat(referenceOperator, modelCount);
                    CreateAllOperatorsExperiment(controller, operators, applyChanges);
                }

                watch.Stop();
                var stopwatchElapsed = watch.Elapsed;
                results.Add((modelCount, stopwatchElapsed.TotalMilliseconds));

                //Clean up for next experiment
                System.GC.Collect();
                var window = EditorWindow.GetWindow <VFXViewWindow>();
                window.Close();
                VFXTestCommon.DeleteAllTemporaryGraph();

                for (int i = 0; i < 8; ++i)
                {
                    yield return(null);
                }
            }

            var report = new System.Text.StringBuilder();

            report.AppendFormat("ApplyChange : {0} - {1}", applyChanges, blocks ? "Blocks" : "Operators");
            report.AppendLine();
            foreach (var result in results)
            {
                report.AppendFormat("{0};{1}", result.Item1, result.Item2);
                report.AppendLine();
            }
            Debug.Log(report);
        }
예제 #13
0
 private static IEnumerable <VFXModelDescriptor> GetSortedParameters()
 {
     return(VFXLibrary.GetParameters().OrderBy(o => o.name));
 }
예제 #14
0
        public IEnumerator Create_Prefab_Several_Override()
        {
            var graph             = VFXTestCommon.MakeTemporaryGraph();
            var parametersIntDesc = VFXLibrary.GetParameters().Where(o => o.model.type == typeof(int)).First();

            Func <VisualEffect, string> dumpPropertySheetInteger = delegate(VisualEffect target)
            {
                var r = "{";

                var editor = Editor.CreateEditor(target);
                editor.serializedObject.Update();

                var propertySheet = editor.serializedObject.FindProperty("m_PropertySheet");
                var fieldName     = VisualEffectSerializationUtility.GetTypeField(VFXExpression.TypeToType(VFXValueType.Int32)) + ".m_Array";
                var vfxField      = propertySheet.FindPropertyRelative(fieldName);

                for (int i = 0; i < vfxField.arraySize; ++i)
                {
                    var itField    = vfxField.GetArrayElementAtIndex(i);
                    var name       = itField.FindPropertyRelative("m_Name").stringValue;
                    var value      = itField.FindPropertyRelative("m_Value").intValue;
                    var overridden = itField.FindPropertyRelative("m_Overridden").boolValue;

                    r += string.Format("({0}, {1}, {2})", name, value, overridden);
                    if (i != vfxField.arraySize - 1)
                    {
                        r += ", ";
                    }
                }

                GameObject.DestroyImmediate(editor);
                r += "}";
                return(r);
            };

            var log = string.Empty;
            var exposedProperties = new[] { "a", "b", "c" };

            for (var i = 0; i < exposedProperties.Length; ++i)
            {
                var parameter = parametersIntDesc.CreateInstance();
                parameter.SetSettingValue("m_ExposedName", exposedProperties[i]);
                parameter.SetSettingValue("m_Exposed", true);
                parameter.value = i + 1;
                graph.AddChild(parameter);
            }

            AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(graph));

            var mainObject = MakeTemporaryGameObject();
            var vfx        = mainObject.AddComponent <VisualEffect>();

            vfx.visualEffectAsset = graph.visualEffectResource.asset;

            GameObject newGameObject, prefabInstanceObject;

            MakeTemporaryPrebab(mainObject, out newGameObject, out prefabInstanceObject);
            GameObject.DestroyImmediate(mainObject);
            yield return(null);

            var currentPrefabInstanceObject = PrefabUtility.InstantiatePrefab(prefabInstanceObject) as GameObject;

            var overridenParametersInScene  = new[] { new { name = "b", value = 666 }, new { name = "a", value = 444 } };
            var overridenParametersInPrefab = new[] { new { name = "c", value = -123 } };

            log += "Initial Sheet\n";
            log += "Prefab : " + dumpPropertySheetInteger(prefabInstanceObject.GetComponent <VisualEffect>()) + "\n";
            log += "Instance  : " + dumpPropertySheetInteger(currentPrefabInstanceObject.GetComponent <VisualEffect>()) + "\n";
            yield return(null);

            foreach (var overridenParameter in overridenParametersInScene)
            {
                currentPrefabInstanceObject.GetComponent <VisualEffect>().SetInt(overridenParameter.name, overridenParameter.value);
            }

            log += "\nIntermediate Sheet\n";
            log += "Prefab : " + dumpPropertySheetInteger(prefabInstanceObject.GetComponent <VisualEffect>()) + "\n";
            log += "Instance  : " + dumpPropertySheetInteger(currentPrefabInstanceObject.GetComponent <VisualEffect>()) + "\n";
            yield return(null);

            foreach (var overridenParameter in overridenParametersInPrefab)
            {
                prefabInstanceObject.GetComponent <VisualEffect>().SetInt(overridenParameter.name, overridenParameter.value);
            }

            yield return(null);

            log += "\nEnd Sheet\n";
            log += "Prefab : " + dumpPropertySheetInteger(prefabInstanceObject.GetComponent <VisualEffect>()) + "\n";
            log += "Instance  : " + dumpPropertySheetInteger(currentPrefabInstanceObject.GetComponent <VisualEffect>()) + "\n";

            var stringFormat   = @"({0} : {1}) ";
            var expectedValues = string.Empty;

            for (var i = 0; i < exposedProperties.Length; ++i)
            {
                var expectedValue    = i;
                var expectedName     = exposedProperties[i];
                var overrideInPrefab = overridenParametersInPrefab.FirstOrDefault(o => o.name == exposedProperties[i]);
                var overrideInScene  = overridenParametersInScene.FirstOrDefault(o => o.name == exposedProperties[i]);

                if (overrideInPrefab != null)
                {
                    expectedValue = overrideInPrefab.value;
                }

                if (overrideInScene != null)
                {
                    expectedValue = overrideInScene.value;
                }

                expectedValues += string.Format(stringFormat, expectedName, expectedValue);
            }

            var actualValues = string.Empty;

            for (var i = 0; i < exposedProperties.Length; ++i)
            {
                var expectedName = exposedProperties[i];
                var actualValue  = currentPrefabInstanceObject.GetComponent <VisualEffect>().GetInt(expectedName);
                actualValues += string.Format(stringFormat, expectedName, actualValue);
            }

            if (k_HasFixed_Several_PrefabOverride)
            {
                Assert.AreEqual(expectedValues, actualValues, log);
            }
            else
            {
                Assert.AreNotEqual(expectedValues, actualValues, log); //Did you fixed it ? Should enable this test : k_HasFixed_Several_PrefabOverride
            }
            yield return(null);
        }
예제 #15
0
        public static void ShowWindow()
        {
            VFXLibrary.LogUnsupportedSRP();

            GetWindow <VFXViewWindow>();
        }
예제 #16
0
            void TransfertDataEdges()
            {
                m_SourceControllersWithBlocks = m_SourceControllers.Concat(m_SourceControllers.OfType <VFXContextController>().SelectMany(t => t.blockControllers));

                // Search for links between with inputs in the selected part and the output in other parts of the graph.
                Dictionary <VFXDataAnchorController, List <VFXDataAnchorController> > traversingInEdges = new Dictionary <VFXDataAnchorController, List <VFXDataAnchorController> >();

                foreach (var edge in m_SourceController.dataEdges.Where(
                             t =>
                {
                    if (parameterNodeControllers.Contains(t.output.sourceNode))
                    {
                        return(false);
                    }
                    var inputInControllers = m_SourceControllersWithBlocks.Contains(t.input.sourceNode);
                    var outputInControllers = m_SourceControllersWithBlocks.Contains(t.output.sourceNode);

                    return(inputInControllers && !outputInControllers);
                }
                             ))
                {
                    List <VFXDataAnchorController> outputs = null;
                    if (!traversingInEdges.TryGetValue(edge.input, out outputs))
                    {
                        outputs = new List <VFXDataAnchorController>();
                        traversingInEdges[edge.input] = outputs;
                    }

                    outputs.Add(edge.output);
                }

                var newSourceInputs = traversingInEdges.Keys.ToArray();

                for (int i = 0; i < newSourceInputs.Length; ++i)
                {
                    VFXParameter newTargetParameter = m_TargetController.AddVFXParameter(Vector2.zero, VFXLibrary.GetParameters().First(t => t.model.type == newSourceInputs[i].portType));

                    m_TargetController.LightApplyChanges();

                    VFXParameterController newTargetParamController = m_TargetController.GetParameterController(newTargetParameter);
                    newTargetParamController.exposed = true;

                    var outputs = traversingInEdges[newSourceInputs[i]];

                    var linkedParameter = outputs.FirstOrDefault(t => t.sourceNode is VFXParameterNodeController);
                    if (linkedParameter != null)
                    {
                        newTargetParamController.exposedName = (linkedParameter.sourceNode as VFXParameterNodeController).parentController.exposedName;
                    }
                    else
                    {
                        newTargetParamController.exposedName = newSourceInputs[i].name;
                    }

                    //first the equivalent of sourceInput in the target

                    VFXNodeController targetNode = null;
                    Vector2           position;

                    if (newSourceInputs[i].sourceNode is VFXBlockController)
                    {
                        var blockController = newSourceInputs[i].sourceNode as VFXBlockController;
                        if (m_TargetBlocks != null)
                        {
                            targetNode = m_TargetBlocks[m_SourceBlockControllers.IndexOf(blockController)];
                            position   = blockController.contextController.position;
                        }
                        else
                        {
                            var targetContext = m_TargetControllers[m_SourceControllers.IndexOf(blockController.contextController)] as VFXContextController;

                            targetNode = targetContext.blockControllers[blockController.index];
                            position   = blockController.contextController.position;
                        }
                    }
                    else
                    {
                        targetNode = m_TargetControllers[m_SourceControllers.IndexOf(newSourceInputs[i].sourceNode)];
                        position   = targetNode.position;
                    }

                    VFXDataAnchorController targetAnchor = targetNode.inputPorts.First(t => t.path == newSourceInputs[i].path);


                    position.y += targetAnchor.model.owner.inputSlots.IndexOf(targetAnchor.model) * 32;

                    VFXNodeController parameterNode = m_TargetController.AddVFXParameter(position - new Vector2(200, 0), newTargetParamController, null);

                    // Link the parameternode and the input in the target
                    m_TargetController.CreateLink(targetAnchor, parameterNode.outputPorts[0]);

                    if (m_SourceSlotContainer is VFXOperator)
                    {
                        (m_SourceSlotContainer as VFXOperator).ResyncSlots(true);
                    }
                    else if (m_SourceSlotContainer is VFXSubgraphBlock)
                    {
                        VFXSubgraphBlock blk = (m_SourceSlotContainer as VFXSubgraphBlock);
                        blk.RecreateCopy();
                        blk.ResyncSlots(true);
                    }
                    else if (m_SourceSlotContainer is VFXSubgraphContext)
                    {
                        VFXSubgraphContext ctx = (m_SourceSlotContainer as VFXSubgraphContext);
                        ctx.RecreateCopy();
                        ctx.ResyncSlots(true);
                    }

                    m_SourceNodeController.ApplyChanges();
                    //Link all the outputs to the matching input of the subgraph
                    foreach (var output in outputs)
                    {
                        m_SourceController.CreateLink(m_SourceNodeController.inputPorts.First(t => t.model == m_SourceSlotContainer.inputSlots.Last()), output);
                    }
                }
            }
        public IEnumerator CreateComponentAndCheckDimensionConstraint()
        {
            EditorApplication.ExecuteMenuItem("Window/General/Game");
            var graph = MakeTemporaryGraph();

            var contextInitialize = ScriptableObject.CreateInstance <VFXBasicInitialize>();
            var allType           = ScriptableObject.CreateInstance <AllType>();

            contextInitialize.AddChild(allType);
            graph.AddChild(contextInitialize);

            // Needs a spawner and output for the system to be valid (TODOPAUL : Should not be needed here)
            {
                var spawner = ScriptableObject.CreateInstance <VFXBasicSpawner>();
                spawner.LinkTo(contextInitialize);
                graph.AddChild(spawner);

                var output = ScriptableObject.CreateInstance <VFXPointOutput>();
                output.LinkFrom(contextInitialize);
                graph.AddChild(output);
            }

            var parameter = VFXLibrary.GetParameters().First(o => o.model.type == typeof(Texture2D)).CreateInstance();
            var type      = VFXValueType.Texture2D;

            var targetTextureName = "exposed_test_tex2D";

            if (type != VFXValueType.None)
            {
                parameter.SetSettingValue("m_exposedName", targetTextureName);
                parameter.SetSettingValue("m_exposed", true);
                graph.AddChild(parameter);
            }

            for (int i = 0; i < allType.GetNbInputSlots(); ++i)
            {
                var currentSlot = allType.GetInputSlot(i);
                var expression  = currentSlot.GetExpression();
                if (expression != null && expression.valueType == type)
                {
                    currentSlot.Link(parameter.GetOutputSlot(0));
                    break;
                }
            }

            graph.RecompileIfNeeded();

            while (m_mainObject.GetComponent <VisualEffect>() != null)
            {
                UnityEngine.Object.DestroyImmediate(m_mainObject.GetComponent <VisualEffect>());
            }
            var vfxComponent = m_mainObject.AddComponent <VisualEffect>();

            vfxComponent.visualEffectAsset = graph.visualEffectResource.asset;

            yield return(null);

            Assert.IsTrue(vfxComponent.HasTexture(targetTextureName));
            Assert.AreEqual(TextureDimension.Tex2D, vfxComponent.GetTextureDimension(targetTextureName));

            var renderTartget3D = new RenderTexture(4, 4, 4, RenderTextureFormat.ARGB32);

            renderTartget3D.dimension = TextureDimension.Tex3D;

            vfxComponent.SetTexture(targetTextureName, renderTartget3D);
            LogAssert.Expect(LogType.Error, new System.Text.RegularExpressions.Regex("3D"));
            Assert.AreNotEqual(renderTartget3D, vfxComponent.GetTexture(targetTextureName));

            var renderTartget2D = new RenderTexture(4, 4, 4, RenderTextureFormat.ARGB32);

            renderTartget2D.dimension = TextureDimension.Tex2D;
            vfxComponent.SetTexture(targetTextureName, renderTartget2D);
            Assert.AreEqual(renderTartget2D, vfxComponent.GetTexture(targetTextureName));
            yield return(null);

            /*
             * Actually, this error is only caught in debug mode, ignored in release for performance reason
             * renderTartget2D.dimension = TextureDimension.Tex3D; //try to hack dimension
             * Assert.AreEqual(renderTartget2D, vfxComponent.GetTexture(targetTextureName));
             * yield return null;
             * LogAssert.Expect(LogType.Error, new System.Text.RegularExpressions.Regex("3D"));
             */
        }
예제 #18
0
        void IEdgeConnectorListener.OnDropOutsidePort(Edge edge, Vector2 position)
        {
            VFXSlot startSlot = controller.model;

            VFXView           view           = this.GetFirstAncestorOfType <VFXView>();
            VFXViewController viewController = view.controller;


            VFXNodeUI endNode = null;

            foreach (var node in view.GetAllNodes())
            {
                if (node.worldBound.Contains(position))
                {
                    endNode = node;
                }
            }

            VFXDataEdge dataEdge = edge as VFXDataEdge;
            bool        exists   = false;

            if (dataEdge.controller != null)
            {
                exists = true;
                view.controller.RemoveElement(dataEdge.controller);
            }

            if (endNode != null)
            {
                VFXNodeController nodeController = endNode.controller;

                if (nodeController != null)
                {
                    IVFXSlotContainer slotContainer = nodeController.slotContainer;
                    if (controller.direction == Direction.Input)
                    {
                        foreach (var output in nodeController.outputPorts.Where(t => t.model == null || t.model.IsMasterSlot()))
                        {
                            if (viewController.CreateLink(controller, output))
                            {
                                break;
                            }
                        }
                    }
                    else
                    {
                        foreach (var input in nodeController.inputPorts.Where(t => t.model == null || t.model.IsMasterSlot()))
                        {
                            if (viewController.CreateLink(input, controller))
                            {
                                break;
                            }
                        }
                    }
                }
            }
            else if (controller.direction == Direction.Input && Event.current.modifiers == EventModifiers.Alt)
            {
                VFXModelDescriptorParameters parameterDesc = VFXLibrary.GetParameters().FirstOrDefault(t => t.name == controller.portType.UserFriendlyName());
                if (parameterDesc != null)
                {
                    VFXParameter parameter = viewController.AddVFXParameter(view.contentViewContainer.GlobalToBound(position) - new Vector2(140, 20), parameterDesc);
                    parameter.SetSettingValue("m_Exposed", true);
                    startSlot.Link(parameter.outputSlots[0]);

                    CopyValueToParameter(parameter);
                }
            }
            else if (!exists)
            {
                VFXFilterWindow.Show(VFXViewWindow.currentWindow, Event.current.mousePosition, view.ViewToScreenPosition(Event.current.mousePosition), new VFXNodeProvider(viewController, AddLinkedNode, ProviderFilter, new Type[] { typeof(VFXOperator), typeof(VFXParameter), typeof(VFXContext) }));
            }
        }
        public IEnumerator CreateComponentWithAllBasicTypeExposed([ValueSource("linkModes")] bool linkMode, [ValueSource("bindingModes")] bool bindingModes)
        {
            var commonBaseName = "abcd_";

            Func <Type, object> GetValue_A_Type = delegate(Type type)
            {
                if (typeof(float) == type)
                {
                    return(2.0f);
                }
                else if (typeof(Vector2) == type)
                {
                    return(new Vector2(3.0f, 4.0f));
                }
                else if (typeof(Vector3) == type)
                {
                    return(new Vector3(8.0f, 9.0f, 10.0f));
                }
                else if (typeof(Vector4) == type)
                {
                    return(new Vector4(11.0f, 12.0f, 13.0f, 14.0f));
                }
                else if (typeof(Color) == type)
                {
                    return(new Color(0.1f, 0.2f, 0.3f, 0.4f));
                }
                else if (typeof(int) == type)
                {
                    return(15);
                }
                else if (typeof(uint) == type)
                {
                    return(16u);
                }
                else if (typeof(AnimationCurve) == type)
                {
                    return(new AnimationCurve(new Keyframe(0, 13), new Keyframe(1, 14)));
                }
                else if (typeof(Gradient) == type)
                {
                    return new Gradient()
                           {
                               colorKeys = new GradientColorKey[] { new GradientColorKey(Color.white, 0.2f) }
                           }
                }
                ;
                else if (typeof(Mesh) == type)
                {
                    return(m_cubeEmpty.GetComponent <MeshFilter>().sharedMesh);
                }
                else if (typeof(Texture2D) == type)
                {
                    return(m_texture2D_A);
                }
                else if (typeof(Texture2DArray) == type)
                {
                    return(m_texture2DArray_A);
                }
                else if (typeof(Texture3D) == type)
                {
                    return(m_texture3D_A);
                }
                else if (typeof(Cubemap) == type)
                {
                    return(m_textureCube_A);
                }
                else if (typeof(CubemapArray) == type)
                {
                    return(m_textureCubeArray_A);
                }
                else if (typeof(bool) == type)
                {
                    return(true);
                }
                else if (typeof(Matrix4x4) == type)
                {
                    return(Matrix4x4.identity);
                }
                Assert.Fail();
                return(null);
            };

            Func <Type, object> GetValue_B_Type = delegate(Type type)
            {
                if (typeof(float) == type)
                {
                    return(50.0f);
                }
                else if (typeof(Vector2) == type)
                {
                    return(new Vector2(53.0f, 54.0f));
                }
                else if (typeof(Vector3) == type)
                {
                    return(new Vector3(58.0f, 59.0f, 510.0f));
                }
                else if (typeof(Vector4) == type || typeof(Color) == type)// ValueB_Type is used to set a component value, so return a Vector4 with color values
                {
                    return(new Vector4(511.0f, 512.0f, 513.0f, 514.0f));
                }
                else if (typeof(int) == type)
                {
                    return(515);
                }
                else if (typeof(uint) == type)
                {
                    return(516u);
                }
                else if (typeof(AnimationCurve) == type)
                {
                    return(new AnimationCurve(new Keyframe(0, 47), new Keyframe(0.5f, 23), new Keyframe(1.0f, 17)));
                }
                else if (typeof(Gradient) == type)
                {
                    return new Gradient()
                           {
                               colorKeys = new GradientColorKey[] { new GradientColorKey(Color.white, 0.2f), new GradientColorKey(Color.black, 0.6f) }
                           }
                }
                ;
                else if (typeof(Mesh) == type)
                {
                    return(m_sphereEmpty.GetComponent <MeshFilter>().sharedMesh);
                }
                else if (typeof(Texture2D) == type)
                {
                    return(m_texture2D_B);
                }
                else if (typeof(Texture2DArray) == type)
                {
                    return(m_texture2DArray_B);
                }
                else if (typeof(Texture3D) == type)
                {
                    return(m_texture3D_B);
                }
                else if (typeof(Cubemap) == type)
                {
                    return(m_textureCube_B);
                }
                else if (typeof(CubemapArray) == type)
                {
                    return(m_textureCubeArray_B);
                }
                else if (typeof(bool) == type)
                {
                    return(true);
                }
                else if (typeof(Matrix4x4) == type)
                {
                    return(Matrix4x4.identity);
                }
                Assert.Fail();
                return(null);
            };

            Func <VFXValueType, VisualEffect, string, bool> fnHas_UsingBindings = delegate(VFXValueType type, VisualEffect vfx, string name)
            {
                switch (type)
                {
                case VFXValueType.Float: return(vfx.HasFloat(name));

                case VFXValueType.Float2: return(vfx.HasVector2(name));

                case VFXValueType.Float3: return(vfx.HasVector3(name));

                case VFXValueType.Float4: return(vfx.HasVector4(name));

                case VFXValueType.Int32: return(vfx.HasInt(name));

                case VFXValueType.Uint32: return(vfx.HasUInt(name));

                case VFXValueType.Curve: return(vfx.HasAnimationCurve(name));

                case VFXValueType.ColorGradient: return(vfx.HasGradient(name));

                case VFXValueType.Mesh: return(vfx.HasMesh(name));

                case VFXValueType.Texture2D: return(vfx.HasTexture(name) && vfx.GetTextureDimension(name) == TextureDimension.Tex2D);

                case VFXValueType.Texture2DArray: return(vfx.HasTexture(name) && vfx.GetTextureDimension(name) == TextureDimension.Tex2DArray);

                case VFXValueType.Texture3D: return(vfx.HasTexture(name) && vfx.GetTextureDimension(name) == TextureDimension.Tex3D);

                case VFXValueType.TextureCube: return(vfx.HasTexture(name) && vfx.GetTextureDimension(name) == TextureDimension.Cube);

                case VFXValueType.TextureCubeArray: return(vfx.HasTexture(name) && vfx.GetTextureDimension(name) == TextureDimension.CubeArray);

                case VFXValueType.Boolean: return(vfx.HasBool(name));

                case VFXValueType.Matrix4x4: return(vfx.HasMatrix4x4(name));
                }
                Assert.Fail();
                return(false);
            };

            Func <VFXValueType, VisualEffect, string, object> fnGet_UsingBindings = delegate(VFXValueType type, VisualEffect vfx, string name)
            {
                switch (type)
                {
                case VFXValueType.Float: return(vfx.GetFloat(name));

                case VFXValueType.Float2: return(vfx.GetVector2(name));

                case VFXValueType.Float3: return(vfx.GetVector3(name));

                case VFXValueType.Float4: return(vfx.GetVector4(name));

                case VFXValueType.Int32: return(vfx.GetInt(name));

                case VFXValueType.Uint32: return(vfx.GetUInt(name));

                case VFXValueType.Curve: return(vfx.GetAnimationCurve(name));

                case VFXValueType.ColorGradient: return(vfx.GetGradient(name));

                case VFXValueType.Mesh: return(vfx.GetMesh(name));

                case VFXValueType.Texture2D:
                case VFXValueType.Texture2DArray:
                case VFXValueType.Texture3D:
                case VFXValueType.TextureCube:
                case VFXValueType.TextureCubeArray: return(vfx.GetTexture(name));

                case VFXValueType.Boolean: return(vfx.GetBool(name));

                case VFXValueType.Matrix4x4: return(vfx.GetMatrix4x4(name));
                }
                Assert.Fail();
                return(null);
            };

            Action <VFXValueType, VisualEffect, string, object> fnSet_UsingBindings = delegate(VFXValueType type, VisualEffect vfx, string name, object value)
            {
                switch (type)
                {
                case VFXValueType.Float: vfx.SetFloat(name, (float)value); break;

                case VFXValueType.Float2: vfx.SetVector2(name, (Vector2)value); break;

                case VFXValueType.Float3: vfx.SetVector3(name, (Vector3)value); break;

                case VFXValueType.Float4: vfx.SetVector4(name, (Vector4)value); break;

                case VFXValueType.Int32: vfx.SetInt(name, (int)value); break;

                case VFXValueType.Uint32: vfx.SetUInt(name, (uint)value); break;

                case VFXValueType.Curve: vfx.SetAnimationCurve(name, (AnimationCurve)value); break;

                case VFXValueType.ColorGradient: vfx.SetGradient(name, (Gradient)value); break;

                case VFXValueType.Mesh: vfx.SetMesh(name, (Mesh)value); break;

                case VFXValueType.Texture2D:
                case VFXValueType.Texture2DArray:
                case VFXValueType.Texture3D:
                case VFXValueType.TextureCube:
                case VFXValueType.TextureCubeArray: vfx.SetTexture(name, (Texture)value); break;

                case VFXValueType.Boolean: vfx.SetBool(name, (bool)value); break;

                case VFXValueType.Matrix4x4: vfx.SetMatrix4x4(name, (Matrix4x4)value); break;
                }
            };


            Func <VFXValueType, VisualEffect, string, bool> fnHas_UsingSerializedProperty = delegate(VFXValueType type, VisualEffect vfx, string name)
            {
                var editor = Editor.CreateEditor(vfx);
                try
                {
                    var propertySheet = editor.serializedObject.FindProperty("m_PropertySheet");
                    var fieldName     = VisualEffectSerializationUtility.GetTypeField(VFXExpression.TypeToType(type)) + ".m_Array";
                    var vfxField      = propertySheet.FindPropertyRelative(fieldName);
                    if (vfxField != null)
                    {
                        for (int i = 0; i < vfxField.arraySize; ++i)
                        {
                            var property     = vfxField.GetArrayElementAtIndex(i);
                            var nameProperty = property.FindPropertyRelative("m_Name").stringValue;
                            if (nameProperty == name)
                            {
                                return(true);
                            }
                        }
                    }
                }
                finally
                {
                    GameObject.DestroyImmediate(editor);
                }
                return(false);
            };

            Func <SerializedProperty, Matrix4x4> fnMatrixFromSerializedProperty = delegate(SerializedProperty property)
            {
                var mat = new Matrix4x4();

                mat.m00 = property.FindPropertyRelative("e00").floatValue;
                mat.m01 = property.FindPropertyRelative("e01").floatValue;
                mat.m02 = property.FindPropertyRelative("e02").floatValue;
                mat.m03 = property.FindPropertyRelative("e03").floatValue;

                mat.m10 = property.FindPropertyRelative("e10").floatValue;
                mat.m11 = property.FindPropertyRelative("e11").floatValue;
                mat.m12 = property.FindPropertyRelative("e12").floatValue;
                mat.m13 = property.FindPropertyRelative("e13").floatValue;

                mat.m20 = property.FindPropertyRelative("e20").floatValue;
                mat.m21 = property.FindPropertyRelative("e21").floatValue;
                mat.m22 = property.FindPropertyRelative("e22").floatValue;
                mat.m23 = property.FindPropertyRelative("e23").floatValue;

                mat.m30 = property.FindPropertyRelative("e30").floatValue;
                mat.m31 = property.FindPropertyRelative("e31").floatValue;
                mat.m32 = property.FindPropertyRelative("e32").floatValue;
                mat.m33 = property.FindPropertyRelative("e33").floatValue;

                return(mat);
            };

            Action <SerializedProperty, Matrix4x4> fnMatrixToSerializedProperty = delegate(SerializedProperty property, Matrix4x4 mat)
            {
                property.FindPropertyRelative("e00").floatValue = mat.m00;
                property.FindPropertyRelative("e01").floatValue = mat.m01;
                property.FindPropertyRelative("e02").floatValue = mat.m02;
                property.FindPropertyRelative("e03").floatValue = mat.m03;

                property.FindPropertyRelative("e10").floatValue = mat.m10;
                property.FindPropertyRelative("e11").floatValue = mat.m11;
                property.FindPropertyRelative("e12").floatValue = mat.m12;
                property.FindPropertyRelative("e13").floatValue = mat.m13;

                property.FindPropertyRelative("e20").floatValue = mat.m20;
                property.FindPropertyRelative("e21").floatValue = mat.m21;
                property.FindPropertyRelative("e22").floatValue = mat.m22;
                property.FindPropertyRelative("e23").floatValue = mat.m23;

                property.FindPropertyRelative("e30").floatValue = mat.m30;
                property.FindPropertyRelative("e31").floatValue = mat.m31;
                property.FindPropertyRelative("e32").floatValue = mat.m32;
                property.FindPropertyRelative("e33").floatValue = mat.m33;
            };

            Func <VFXValueType, VisualEffect, string, object> fnGet_UsingSerializedProperty = delegate(VFXValueType type, VisualEffect vfx, string name)
            {
                var editor = Editor.CreateEditor(vfx);
                try
                {
                    var propertySheet = editor.serializedObject.FindProperty("m_PropertySheet");
                    editor.serializedObject.Update();

                    var fieldName = VisualEffectSerializationUtility.GetTypeField(VFXExpression.TypeToType(type)) + ".m_Array";
                    var vfxField  = propertySheet.FindPropertyRelative(fieldName);
                    if (vfxField != null)
                    {
                        for (int i = 0; i < vfxField.arraySize; ++i)
                        {
                            var property     = vfxField.GetArrayElementAtIndex(i);
                            var nameProperty = property.FindPropertyRelative("m_Name").stringValue;
                            if (nameProperty == name)
                            {
                                property = property.FindPropertyRelative("m_Value");

                                switch (type)
                                {
                                case VFXValueType.Float: return(property.floatValue);

                                case VFXValueType.Float2: return(property.vector2Value);

                                case VFXValueType.Float3: return(property.vector3Value);

                                case VFXValueType.Float4: return(property.vector4Value);

                                case VFXValueType.Int32: return(property.intValue);

                                case VFXValueType.Uint32: return(property.intValue);        // there isn't uintValue

                                case VFXValueType.Curve: return(property.animationCurveValue);

                                case VFXValueType.ColorGradient: return(property.gradientValue);

                                case VFXValueType.Mesh: return(property.objectReferenceValue);

                                case VFXValueType.Texture2D:
                                case VFXValueType.Texture2DArray:
                                case VFXValueType.Texture3D:
                                case VFXValueType.TextureCube:
                                case VFXValueType.TextureCubeArray: return(property.objectReferenceValue);

                                case VFXValueType.Boolean: return(property.boolValue);

                                case VFXValueType.Matrix4x4: return(fnMatrixFromSerializedProperty(property));
                                }
                                Assert.Fail();
                            }
                        }
                    }
                }
                finally
                {
                    GameObject.DestroyImmediate(editor);
                }

                return(null);
            };

            Action <VFXValueType, VisualEffect, string, object> fnSet_UsingSerializedProperty = delegate(VFXValueType type, VisualEffect vfx, string name, object value)
            {
                var editor = Editor.CreateEditor(vfx);
                try
                {
                    editor.serializedObject.Update();

                    var propertySheet = editor.serializedObject.FindProperty("m_PropertySheet");
                    var fieldName     = VisualEffectSerializationUtility.GetTypeField(VFXExpression.TypeToType(type)) + ".m_Array";
                    var vfxField      = propertySheet.FindPropertyRelative(fieldName);
                    if (vfxField != null)
                    {
                        for (int i = 0; i < vfxField.arraySize; ++i)
                        {
                            var property     = vfxField.GetArrayElementAtIndex(i);
                            var propertyName = property.FindPropertyRelative("m_Name").stringValue;
                            if (propertyName == name)
                            {
                                var propertyValue     = property.FindPropertyRelative("m_Value");
                                var propertyOverriden = property.FindPropertyRelative("m_Overridden");

                                switch (type)
                                {
                                case VFXValueType.Float: propertyValue.floatValue = (float)value; break;

                                case VFXValueType.Float2: propertyValue.vector2Value = (Vector2)value; break;

                                case VFXValueType.Float3: propertyValue.vector3Value = (Vector3)value; break;

                                case VFXValueType.Float4: propertyValue.vector4Value = (Vector4)value; break;

                                case VFXValueType.Int32: propertyValue.intValue = (int)value; break;

                                case VFXValueType.Uint32: propertyValue.intValue = (int)((uint)value); break;         // there isn't uintValue

                                case VFXValueType.Curve: propertyValue.animationCurveValue = (AnimationCurve)value; break;

                                case VFXValueType.ColorGradient: propertyValue.gradientValue = (Gradient)value; break;

                                case VFXValueType.Mesh: propertyValue.objectReferenceValue = (UnityEngine.Object)value; break;

                                case VFXValueType.Texture2D:
                                case VFXValueType.Texture2DArray:
                                case VFXValueType.Texture3D:
                                case VFXValueType.TextureCube:
                                case VFXValueType.TextureCubeArray: propertyValue.objectReferenceValue = (UnityEngine.Object)value;   break;

                                case VFXValueType.Boolean: propertyValue.boolValue = (bool)value; break;

                                case VFXValueType.Matrix4x4: fnMatrixToSerializedProperty(propertyValue, (Matrix4x4)value); break;
                                }
                                propertyOverriden.boolValue = true;
                            }
                        }
                    }
                    editor.serializedObject.ApplyModifiedProperties();
                }
                finally
                {
                    GameObject.DestroyImmediate(editor);
                }
            };

            Func <VFXValueType, VisualEffect, string, bool>     fnHas = bindingModes ? fnHas_UsingBindings : fnHas_UsingSerializedProperty;
            Func <VFXValueType, VisualEffect, string, object>   fnGet = bindingModes ? fnGet_UsingBindings : fnGet_UsingSerializedProperty;
            Action <VFXValueType, VisualEffect, string, object> fnSet = bindingModes ? fnSet_UsingBindings : fnSet_UsingSerializedProperty;

            EditorApplication.ExecuteMenuItem("Window/General/Game");
            var graph = MakeTemporaryGraph();

            var contextInitialize = ScriptableObject.CreateInstance <VFXBasicInitialize>();
            var allType           = ScriptableObject.CreateInstance <AllType>();

            contextInitialize.AddChild(allType);
            graph.AddChild(contextInitialize);

            // Needs a spawner and output for the system to be valid
            {
                var spawner = ScriptableObject.CreateInstance <VFXBasicSpawner>();
                spawner.LinkTo(contextInitialize);
                graph.AddChild(spawner);

                var output = ScriptableObject.CreateInstance <VFXPointOutput>();
                output.LinkFrom(contextInitialize);
                graph.AddChild(output);
            }

            var types = Enum.GetValues(typeof(VFXValueType)).Cast <VFXValueType>()
                        .Where(e => e != VFXValueType.Spline &&
                               e != VFXValueType.None).ToArray();

            foreach (var parameter in VFXLibrary.GetParameters())
            {
                var newInstance = parameter.CreateInstance();

                VFXValueType type = types.FirstOrDefault(e => VFXExpression.GetVFXValueTypeFromType(newInstance.type) == e);
                if (type != VFXValueType.None)
                {
                    newInstance.SetSettingValue("m_exposedName", commonBaseName + newInstance.type.UserFriendlyName());
                    newInstance.SetSettingValue("m_exposed", true);
                    var value = GetValue_A_Type(newInstance.type);
                    Assert.IsNotNull(value);
                    newInstance.value = value;
                    graph.AddChild(newInstance);
                }
            }

            if (linkMode)
            {
                foreach (var type in types)
                {
                    VFXSlot slot = null;
                    for (int i = 0; i < allType.GetNbInputSlots(); ++i)
                    {
                        var currentSlot = allType.GetInputSlot(i);
                        var expression  = currentSlot.GetExpression();
                        if (expression != null && expression.valueType == type)
                        {
                            slot = currentSlot;
                            break;
                        }
                    }
                    Assert.IsNotNull(slot, type.ToString());

                    var parameter = graph.children.OfType <VFXParameter>().FirstOrDefault(o =>
                    {
                        if (o.GetNbOutputSlots() > 0)
                        {
                            var expression = o.outputSlots[0].GetExpression();
                            if (expression != null && expression.valueType == type)
                            {
                                return(true);
                            }
                        }
                        return(false);
                    });
                    Assert.IsNotNull(parameter, "parameter with type : " + type.ToString());
                    slot.Link(parameter.GetOutputSlot(0));
                }
            }

            graph.RecompileIfNeeded();

            while (m_mainObject.GetComponent <VisualEffect>() != null)
            {
                UnityEngine.Object.DestroyImmediate(m_mainObject.GetComponent <VisualEffect>());
            }
            var vfxComponent = m_mainObject.AddComponent <VisualEffect>();

            vfxComponent.visualEffectAsset = graph.visualEffectResource.asset;

            yield return(null);

            Func <AnimationCurve, AnimationCurve, bool> fnCompareCurve = delegate(AnimationCurve left, AnimationCurve right)
            {
                return(left.keys.Length == right.keys.Length);
            };

            Func <Gradient, Gradient, bool> fnCompareGradient = delegate(Gradient left, Gradient right)
            {
                return(left.colorKeys.Length == right.colorKeys.Length);
            };

            //Check default Value_A & change to Value_B (At this stage, it's useless to access with SerializedProperty)
            foreach (var parameter in VFXLibrary.GetParameters())
            {
                VFXValueType type = types.FirstOrDefault(e => VFXExpression.GetVFXValueTypeFromType(parameter.model.type) == e);
                if (type == VFXValueType.None)
                {
                    continue;
                }
                var currentName = commonBaseName + parameter.model.type.UserFriendlyName();
                var baseValue   = GetValue_A_Type(parameter.model.type);
                var newValue    = GetValue_B_Type(parameter.model.type);

                Assert.IsTrue(fnHas_UsingBindings(type, vfxComponent, currentName));
                var currentValue = fnGet_UsingBindings(type, vfxComponent, currentName);
                if (type == VFXValueType.ColorGradient)
                {
                    Assert.IsTrue(fnCompareGradient((Gradient)baseValue, (Gradient)currentValue));
                }
                else if (type == VFXValueType.Curve)
                {
                    Assert.IsTrue(fnCompareCurve((AnimationCurve)baseValue, (AnimationCurve)currentValue));
                }
                else if (parameter.model.type == typeof(Color))
                {
                    Color col = (Color)baseValue;
                    Assert.AreEqual(new Vector4(col.r, col.g, col.b, col.a), currentValue);
                }
                else
                {
                    Assert.AreEqual(baseValue, currentValue);
                }
                fnSet_UsingBindings(type, vfxComponent, currentName, newValue);

                yield return(null);
            }

            //Compare new setted values
            foreach (var parameter in VFXLibrary.GetParameters())
            {
                VFXValueType type = types.FirstOrDefault(e => VFXExpression.GetVFXValueTypeFromType(parameter.model.type) == e);
                if (type == VFXValueType.None)
                {
                    continue;
                }
                var currentName = commonBaseName + parameter.model.type.UserFriendlyName();
                var baseValue   = GetValue_B_Type(parameter.model.type);
                Assert.IsTrue(fnHas(type, vfxComponent, currentName));

                var currentValue = fnGet(type, vfxComponent, currentName);
                if (type == VFXValueType.ColorGradient)
                {
                    Assert.IsTrue(fnCompareGradient((Gradient)baseValue, (Gradient)currentValue));
                }
                else if (type == VFXValueType.Curve)
                {
                    Assert.IsTrue(fnCompareCurve((AnimationCurve)baseValue, (AnimationCurve)currentValue));
                }
                else
                {
                    Assert.AreEqual(baseValue, currentValue);
                }
                yield return(null);
            }

            //Test ResetOverride function
            foreach (var parameter in VFXLibrary.GetParameters())
            {
                VFXValueType type = types.FirstOrDefault(e => VFXExpression.GetVFXValueTypeFromType(parameter.model.type) == e);
                if (type == VFXValueType.None)
                {
                    continue;
                }
                var currentName = commonBaseName + parameter.model.type.UserFriendlyName();
                vfxComponent.ResetOverride(currentName);

                {
                    //If we use bindings, internal value is restored but it doesn't change serialized property (strange at first but intended behavior)
                    var baseValue = bindingModes ? GetValue_A_Type(parameter.model.type) : GetValue_B_Type(parameter.model.type);

                    var currentValue = fnGet(type, vfxComponent, currentName);
                    if (type == VFXValueType.ColorGradient)
                    {
                        Assert.IsTrue(fnCompareGradient((Gradient)baseValue, (Gradient)currentValue));
                    }
                    else if (type == VFXValueType.Curve)
                    {
                        Assert.IsTrue(fnCompareCurve((AnimationCurve)baseValue, (AnimationCurve)currentValue));
                    }
                    else if (bindingModes && parameter.model.type == typeof(Color))
                    {
                        Color col = (Color)baseValue;
                        Assert.AreEqual(new Vector4(col.r, col.g, col.b, col.a), currentValue);
                    }
                    else
                    {
                        Assert.AreEqual(baseValue, currentValue);
                    }
                }

                if (!bindingModes)
                {
                    var internalValue      = fnGet_UsingBindings(type, vfxComponent, currentName);
                    var originalAssetValue = GetValue_A_Type(parameter.model.type);

                    if (type == VFXValueType.ColorGradient)
                    {
                        Assert.IsTrue(fnCompareGradient((Gradient)originalAssetValue, (Gradient)internalValue));
                    }
                    else if (type == VFXValueType.Curve)
                    {
                        Assert.IsTrue(fnCompareCurve((AnimationCurve)originalAssetValue, (AnimationCurve)internalValue));
                    }
                    else if (parameter.model.type == typeof(Color))
                    {
                        Color col = (Color)originalAssetValue;
                        Assert.AreEqual(new Vector4(col.r, col.g, col.b, col.a), internalValue);
                    }
                    else
                    {
                        Assert.AreEqual(originalAssetValue, internalValue);
                    }
                }
                yield return(null);
            }
        }
        public void LinkPositionOrVectorAndDirection([ValueSource("usePosition")] bool usePosition)
        {
            var crossDesc     = VFXLibrary.GetOperators().FirstOrDefault(o => o.name.Contains("Cross"));
            var positionDesc  = VFXLibrary.GetParameters().FirstOrDefault(o => o.name.Contains("Position"));
            var vectorDesc    = VFXLibrary.GetParameters().FirstOrDefault(o => o.name == "Vector");
            var directionDesc = VFXLibrary.GetParameters().FirstOrDefault(o => o.name.Contains("Direction"));

            var cross     = m_ViewController.AddVFXOperator(new Vector2(1, 1), crossDesc);
            var position  = m_ViewController.AddVFXParameter(new Vector2(2, 2), positionDesc);
            var vector    = m_ViewController.AddVFXParameter(new Vector2(3, 3), vectorDesc);
            var direction = m_ViewController.AddVFXParameter(new Vector2(4, 4), directionDesc);

            (cross as IVFXOperatorUniform).SetOperandType(typeof(Vector3));

            m_ViewController.ApplyChanges();

            Func <IVFXSlotContainer, VFXNodeController> fnFindController = delegate(IVFXSlotContainer slotContainer)
            {
                var allController = m_ViewController.allChildren.OfType <VFXNodeController>();
                return(allController.FirstOrDefault(o => o.slotContainer == slotContainer));
            };

            var controllerCross = fnFindController(cross);

            var vA = new Vector3(2, 3, 4);

            position.outputSlots[0].value = new Position()
            {
                position = vA
            };
            vector.outputSlots[0].value = new Vector()
            {
                vector = vA
            };

            var vB = new Vector3(5, 6, 7);

            direction.outputSlots[0].value = new DirectionType()
            {
                direction = vB
            };

            var edgeControllerAppend_A = new VFXDataEdgeController(controllerCross.inputPorts.Where(o => o.portType == typeof(Vector3)).First(), fnFindController(usePosition ? position : vector).outputPorts.First());

            m_ViewController.AddElement(edgeControllerAppend_A);
            (cross as IVFXOperatorUniform).SetOperandType(typeof(Vector3));
            m_ViewController.ApplyChanges();

            var edgeControllerAppend_B = new VFXDataEdgeController(controllerCross.inputPorts.Where(o => o.portType == typeof(Vector3)).Last(), fnFindController(direction).outputPorts.First());

            m_ViewController.AddElement(edgeControllerAppend_B);
            (cross as IVFXOperatorUniform).SetOperandType(typeof(Vector3));
            m_ViewController.ApplyChanges();

            m_ViewController.ForceReload();

            Assert.AreEqual(1, cross.inputSlots[0].LinkedSlots.Count());
            Assert.AreEqual(1, cross.inputSlots[1].LinkedSlots.Count());

            var context = new VFXExpression.Context(VFXExpressionContextOption.CPUEvaluation | VFXExpressionContextOption.ConstantFolding);

            var currentA = context.Compile(cross.inputSlots[0].GetExpression()).Get <Vector3>();
            var currentB = context.Compile(cross.inputSlots[1].GetExpression()).Get <Vector3>();
            var result   = context.Compile(cross.outputSlots[0].GetExpression()).Get <Vector3>();

            Assert.AreEqual((double)vA.x, (double)currentA.x, 0.001f);
            Assert.AreEqual((double)vA.y, (double)currentA.y, 0.001f);
            Assert.AreEqual((double)vA.z, (double)currentA.z, 0.001f);

            Assert.AreEqual((double)vB.normalized.x, (double)currentB.x, 0.001f);
            Assert.AreEqual((double)vB.normalized.y, (double)currentB.y, 0.001f);
            Assert.AreEqual((double)vB.normalized.z, (double)currentB.z, 0.001f);

            var expectedResult = Vector3.Cross(vA, vB.normalized);

            Assert.AreEqual((double)expectedResult.x, (double)result.x, 0.001f);
            Assert.AreEqual((double)expectedResult.y, (double)result.y, 0.001f);
            Assert.AreEqual((double)expectedResult.z, (double)result.z, 0.001f);
        }
예제 #21
0
        private void PasteParameters(VFXViewController viewController, ref SerializableGraph serializableGraph)
        {
            newParameters.Clear();

            if (serializableGraph.parameters != null)
            {
                foreach (var parameter in serializableGraph.parameters)
                {
                    // if we have a parameter with the same name use it else create it with the copied data
                    VFXParameter p = viewController.graph.children.OfType <VFXParameter>().FirstOrDefault(t => t.GetInstanceID() == parameter.originalInstanceID);
                    if (p == null)
                    {
                        Type type = parameter.value.type;
                        VFXModelDescriptorParameters desc = VFXLibrary.GetParameters().FirstOrDefault(t => t.model.type == type);
                        if (desc != null)
                        {
                            p             = viewController.AddVFXParameter(Vector2.zero, desc);
                            p.value       = parameter.value.Get();
                            p.valueFilter = parameter.valueFilter;
                            if (parameter.valueFilter == VFXValueFilter.Range)
                            {
                                p.min = parameter.min.Get();
                                p.max = parameter.max.Get();
                            }
                            else if (parameter.valueFilter == VFXValueFilter.Enum)
                            {
                                p.enumValues = parameter.enumValue.ToList();
                            }
                            p.SetSettingValue("m_Exposed", parameter.exposed);
                            if (viewController.model.visualEffectObject is VisualEffectSubgraphOperator)
                            {
                                p.isOutput = parameter.isOutput;
                            }
                            p.SetSettingValue("m_ExposedName", parameter.name); // the controller will take care or name unicity later
                            p.tooltip = parameter.tooltip;
                        }
                    }

                    if (p == null)
                    {
                        newParameters.Add(new KeyValuePair <VFXParameter, List <int> >(null, null));
                        continue;
                    }

                    var newParameterNodes = new List <int>();
                    foreach (var node in parameter.nodes)
                    {
                        int nodeIndex = p.AddNode(node.position + pasteOffset);

                        var nodeModel = p.nodes.LastOrDefault(t => t.id == nodeIndex);
                        nodeModel.expanded      = !node.collapsed;
                        nodeModel.expandedSlots = AllSlots(p.outputSlots).Where(t => node.expandedOutput.Contains(t.path)).ToList();


                        m_NodesInTheSameOrder[node.indexInClipboard] = new VFXNodeID(p, nodeModel.id);
                        newParameterNodes.Add(nodeIndex);
                    }

                    newParameters.Add(new KeyValuePair <VFXParameter, List <int> >(p, newParameterNodes));
                }
            }
        }
        public void ConvertParameterToInline()
        {
            VFXParameter newParameter = m_ViewController.AddVFXParameter(Vector2.zero, VFXLibrary.GetParameters().First(t => t.model.type == typeof(AABox)));

            m_ViewController.LightApplyChanges();

            VFXParameterController parameterController = m_ViewController.GetParameterController(newParameter);

            parameterController.model.AddNode(new Vector2(123, 456));

            AABox value = new AABox {
                center = new Vector3(1, 2, 3), size = new Vector3(4, 5, 6)
            };

            parameterController.value = value;

            m_ViewController.LightApplyChanges();

            VFXParameterNodeController parameterNode = parameterController.nodes.First();

            parameterNode.ConvertToInline();

            VFXInlineOperator op = m_ViewController.graph.children.OfType <VFXInlineOperator>().First();

            Assert.AreEqual(new Vector2(123, 456), op.position);
            Assert.AreEqual(typeof(AABox), op.type);
            Assert.AreEqual(value, op.inputSlots[0].value);
        }
예제 #23
0
        public void ExpandRetractAndSetPropertyValue()
        {
            EditTestAsset(7);

            var initContextDesc = VFXLibrary.GetContexts().Where(t => typeof(VFXBasicInitialize).IsAssignableFrom(t.modelType)).First();

            var newContext = m_ViewController.AddVFXContext(new Vector2(300, 100), initContextDesc);

            m_ViewController.ApplyChanges();

            Assert.AreEqual(m_ViewController.allChildren.Where(t => t is VFXContextController).Count(), 1);

            var contextController = m_ViewController.allChildren.Where(t => t is VFXContextController).First() as VFXContextController;

            Assert.AreEqual(contextController.model, newContext);

            // Adding every block compatible with an init context

            var blockDesc = new VFXModelDescriptor <VFXBlock>(ScriptableObject.CreateInstance <AllType>());

            var newBlock = blockDesc.CreateInstance();

            contextController.AddBlock(0, newBlock);

            Assert.IsTrue(newBlock is AllType);
            m_ViewController.ApplyChanges();

            Assert.AreEqual(contextController.blockControllers.Where(t => t.model == newBlock).Count(), 1);

            var blockController = contextController.blockControllers.Where(t => t.model == newBlock).First();

            Assert.NotNull(blockController);

            Assert.NotZero(blockController.inputPorts.Where(t => t is VFXContextDataInputAnchorController && (t as VFXContextDataInputAnchorController).name == "aVector3").Count());

            VFXSlot slot = blockController.model.inputSlots.First(t => t.name == "aVector3");


            var aVector3Controller = blockController.inputPorts.Where(t => t is VFXContextDataInputAnchorController && (t as VFXContextDataInputAnchorController).name == "aVector3").First() as VFXContextDataInputAnchorController;

            Assert.AreEqual(blockController.inputPorts.Where(t => t is VFXContextDataInputAnchorController && (t as VFXContextDataInputAnchorController).path == "aVector3.x").Count(), 1);
            Assert.AreEqual(blockController.inputPorts.Where(t => t is VFXContextDataInputAnchorController && (t as VFXContextDataInputAnchorController).path == "aVector3.y").Count(), 1);
            Assert.AreEqual(blockController.inputPorts.Where(t => t is VFXContextDataInputAnchorController && (t as VFXContextDataInputAnchorController).path == "aVector3.z").Count(), 1);

            aVector3Controller.ExpandPath();
            m_ViewController.ApplyChanges();

            Assert.AreEqual(blockController.inputPorts.Where(t => t is VFXContextDataInputAnchorController && (t as VFXContextDataInputAnchorController).path == "aVector3.x").Count(), 1);
            Assert.AreEqual(blockController.inputPorts.Where(t => t is VFXContextDataInputAnchorController && (t as VFXContextDataInputAnchorController).path == "aVector3.y").Count(), 1);
            Assert.AreEqual(blockController.inputPorts.Where(t => t is VFXContextDataInputAnchorController && (t as VFXContextDataInputAnchorController).path == "aVector3.z").Count(), 1);


            aVector3Controller.RetractPath();
            m_ViewController.ApplyChanges();

            Assert.AreEqual(blockController.inputPorts.Where(t => t is VFXContextDataInputAnchorController && (t as VFXContextDataInputAnchorController).path == "aVector3.x").Count(), 1);
            Assert.AreEqual(blockController.inputPorts.Where(t => t is VFXContextDataInputAnchorController && (t as VFXContextDataInputAnchorController).path == "aVector3.y").Count(), 1);
            Assert.AreEqual(blockController.inputPorts.Where(t => t is VFXContextDataInputAnchorController && (t as VFXContextDataInputAnchorController).path == "aVector3.z").Count(), 1);


            aVector3Controller.SetPropertyValue(new Vector3(1.2f, 3.4f, 5.6f));

            Assert.AreEqual(slot.value, new Vector3(1.2f, 3.4f, 5.6f));

            aVector3Controller.ExpandPath();
            m_ViewController.ApplyChanges();

            var vector3yController = blockController.inputPorts.Where(t => t is VFXContextDataInputAnchorController && (t as VFXContextDataInputAnchorController).path == "aVector3.y").First() as VFXContextDataInputAnchorController;

            vector3yController.SetPropertyValue(7.8f);

            Assert.AreEqual(slot.value, new Vector3(1.2f, 7.8f, 5.6f));
        }
예제 #24
0
        void IEdgeConnectorListener.OnDropOutsidePort(Edge edge, Vector2 position)
        {
            VFXSlot startSlot = controller.model;

            VFXView           view           = this.GetFirstAncestorOfType <VFXView>();
            VFXViewController viewController = view.controller;


            List <VisualElement> picked = new List <VisualElement>();

            panel.PickAll(position, picked);
            VFXNodeUI endNode = null;

            foreach (var element in picked)
            {
                if (element is VFXNodeUI node)
                {
                    endNode = node;
                    break;
                }
            }


            VFXDataEdge dataEdge = edge as VFXDataEdge;
            bool        exists   = false;

            if (dataEdge.controller != null)
            {
                exists = true;
                view.controller.RemoveElement(dataEdge.controller);
            }

            if (endNode != null)
            {
                VFXNodeController nodeController = endNode.controller;

                if (nodeController != null)
                {
                    IVFXSlotContainer slotContainer = nodeController.slotContainer;
                    if (controller.direction == Direction.Input)
                    {
                        foreach (var output in nodeController.outputPorts.Where(t => t.model == null || t.model.IsMasterSlot()))
                        {
                            if (viewController.CreateLink(controller, output))
                            {
                                break;
                            }
                        }
                    }
                    else
                    {
                        foreach (var input in nodeController.inputPorts.Where(t => t.model == null || t.model.IsMasterSlot() && !t.model.HasLink(true)))
                        {
                            if (viewController.CreateLink(input, controller))
                            {
                                break;
                            }
                        }
                    }
                }
            }
            else if (controller.direction == Direction.Input && Event.current.modifiers == EventModifiers.Alt)
            {
                var targetType = controller.portType;

                var attribute = VFXLibrary.GetAttributeFromSlotType(controller.portType);
                VFXModelDescriptorParameters parameterDesc;
                if (attribute != null && attribute.usages.HasFlag(VFXTypeAttribute.Usage.ExcludeFromProperty))
                {
                    parameterDesc = VFXLibrary.GetParameters().FirstOrDefault(t =>
                    {
                        if (!t.model.outputSlots[0].CanLink(controller.model))
                        {
                            return(false);
                        }
                        var attributeCandidate = VFXLibrary.GetAttributeFromSlotType(t.model.type);
                        return(attributeCandidate == null || !attributeCandidate.usages.HasFlag(VFXTypeAttribute.Usage.ExcludeFromProperty));
                    });
                }
                else
                {
                    parameterDesc = VFXLibrary.GetParameters().FirstOrDefault(t =>
                    {
                        return(t.model.type == targetType);
                    });
                }

                if (parameterDesc != null)
                {
                    Vector2 pos = view.contentViewContainer.GlobalToBound(position) - new Vector2(140, 20);
                    view.UpdateSelectionWithNewNode();
                    VFXParameter parameter = viewController.AddVFXParameter(pos, parameterDesc, false);
                    parameter.SetSettingValue("m_Exposed", true);
                    startSlot.Link(parameter.outputSlots[0]);

                    CopyValueToParameter(parameter);

                    viewController.AddVFXModel(pos, parameter);
                }
            }
            else if (!exists)
            {
                var window = VFXViewWindow.GetWindow(view);

                if (direction == Direction.Input || viewController.model.visualEffectObject is VisualEffectSubgraphOperator || viewController.model.visualEffectObject is VisualEffectSubgraphBlock) // no context for subgraph operators.
                {
                    VFXFilterWindow.Show(window, Event.current.mousePosition, view.ViewToScreenPosition(Event.current.mousePosition), new VFXNodeProvider(viewController, AddLinkedNode, ProviderFilter, new Type[] { typeof(VFXOperator), typeof(VFXParameter) }));
                }
                else
                {
                    VFXFilterWindow.Show(window, Event.current.mousePosition, view.ViewToScreenPosition(Event.current.mousePosition), new VFXNodeProvider(viewController, AddLinkedNode, ProviderFilter, new Type[] { typeof(VFXOperator), typeof(VFXParameter), typeof(VFXContext) }));
                }
            }
        }
예제 #25
0
        protected override IEnumerable <Descriptor> GetDescriptors()
        {
            IEnumerable <Descriptor> descs = Enumerable.Empty <Descriptor>();

            if (m_AcceptedTypes == null || m_AcceptedTypes.Contains(typeof(VFXContext)))
            {
                var descriptorsContext = VFXLibrary.GetContexts().Select(o =>
                {
                    return(new Descriptor()
                    {
                        modelDescriptor = o,
                        category = ComputeCategory("Context", o),
                        name = o.name
                    });
                }).OrderBy(o => o.category + o.name);

                descs = descs.Concat(descriptorsContext);
            }
            if (m_AcceptedTypes == null || m_AcceptedTypes.Contains(typeof(VFXOperator)))
            {
                var descriptorsOperator = VFXLibrary.GetOperators().Select(o =>
                {
                    return(new Descriptor()
                    {
                        modelDescriptor = o,
                        category = ComputeCategory("Operator", o),
                        name = o.name
                    });
                });

                descriptorsOperator = descriptorsOperator.Concat(SubGraphCache.GetItems(typeof(VisualEffectSubgraphOperator)).Select(
                                                                     t => new Descriptor()
                {
                    modelDescriptor = t.path,
                    category        = "Operator/" + t.category,
                    name            = t.name
                }
                                                                     ));

                descs = descs.Concat(descriptorsOperator.OrderBy(o => o.category + o.name));
            }
            if (m_AcceptedTypes == null || m_AcceptedTypes.Contains(typeof(VFXParameter)))
            {
                var parameterDescriptors = m_Controller.parameterControllers.Select(t =>
                                                                                    new Descriptor
                {
                    modelDescriptor = t,
                    category        = string.IsNullOrEmpty(t.model.category) ? "Property" : string.Format("Property/{0}", t.model.category),
                    name            = t.exposedName
                }
                                                                                    ).OrderBy(t => t.category);
                descs = descs.Concat(parameterDescriptors);
            }
            if (m_AcceptedTypes == null)
            {
                AddTemplatesFromDirectory(VisualEffectAssetEditorUtility.templatePath, "System", ref descs);

                if ((VFXResources.defaultResources.userTemplateDirectory.Length > 0) && System.IO.Directory.Exists(VFXResources.defaultResources.userTemplateDirectory))
                {
                    AddTemplatesFromDirectory(VFXResources.defaultResources.userTemplateDirectory, "User Systems", ref descs);
                }
            }
            var groupNodeDesc = new Descriptor()
            {
                modelDescriptor = new GroupNodeAdder(),
                category        = "Misc",
                name            = "Group Node"
            };

            descs = descs.Concat(Enumerable.Repeat(groupNodeDesc, 1));

            if (m_Filter == null)
            {
                return(descs);
            }
            else
            {
                return(descs.Where(t => m_Filter(t)));
            }
        }
예제 #26
0
        protected override void OnNewController()
        {
            var blocks = new List <VFXModelDescriptor <VFXBlock> >(VFXLibrary.GetBlocks());

            m_CanHaveBlocks = blocks.Any(t => controller.model.AcceptChild(t.model));
        }
예제 #27
0
        public IEnumerator CreateComponent_Modify_Asset_Keep_Override()
        {
            var graph = MakeTemporaryGraph();

            var parametersVector3Desc = VFXLibrary.GetParameters().Where(o => o.model.type == typeof(Vector3)).First();

            var exposedName = "poiuyt";
            var parameter   = parametersVector3Desc.CreateInstance();

            parameter.SetSettingValue("m_exposedName", exposedName);
            parameter.SetSettingValue("m_exposed", true);
            parameter.value = new Vector3(0, 0, 0);
            graph.AddChild(parameter);
            graph.RecompileIfNeeded();

            while (m_mainObject.GetComponent <VisualEffect>() != null)
            {
                UnityEngine.Object.DestroyImmediate(m_mainObject.GetComponent <VisualEffect>());
            }
            var vfx = m_mainObject.AddComponent <VisualEffect>();

            vfx.visualEffectAsset = graph.visualEffectResource.asset;
            Assert.IsTrue(vfx.HasVector3(exposedName));
            var expectedOverriden = new Vector3(1, 2, 3);

            vfx.SetVector3(exposedName, expectedOverriden);

            yield return(null);

            var actualOverriden = vfx.GetVector3(exposedName);

            Assert.AreEqual(actualOverriden.x, expectedOverriden.x); Assert.AreEqual(actualOverriden.y, expectedOverriden.y); Assert.AreEqual(actualOverriden.z, expectedOverriden.z);

            /* Add system & another exposed */
            var contextInitialize = ScriptableObject.CreateInstance <VFXBasicInitialize>();
            var allType           = ScriptableObject.CreateInstance <AllType>();

            contextInitialize.AddChild(allType);
            graph.AddChild(contextInitialize);

            var spawner = ScriptableObject.CreateInstance <VFXBasicSpawner>();

            spawner.LinkTo(contextInitialize);
            graph.AddChild(spawner);

            var output = ScriptableObject.CreateInstance <VFXPointOutput>();

            output.LinkFrom(contextInitialize);
            graph.AddChild(output);

            var parameter_Other   = parametersVector3Desc.CreateInstance();
            var exposedName_Other = "tyuiop";

            parameter_Other.SetSettingValue("m_exposedName", exposedName_Other);
            parameter_Other.SetSettingValue("m_exposed", true);
            parameter_Other.value = new Vector3(6, 6, 6);
            graph.AddChild(parameter_Other);
            parameter.value = new Vector3(5, 5, 5);
            graph.RecompileIfNeeded();

            yield return(null);

            Assert.IsTrue(vfx.HasVector3(exposedName));
            Assert.IsTrue(vfx.HasVector3(exposedName_Other));
            actualOverriden = vfx.GetVector3(exposedName);

            Assert.AreEqual(actualOverriden.x, expectedOverriden.x); Assert.AreEqual(actualOverriden.y, expectedOverriden.y); Assert.AreEqual(actualOverriden.z, expectedOverriden.z);
        }