示例#1
0
        public static void Draw(Rect area, Target target, GUIContent label)
        {
            if (target.parent.IsNull())
            {
                return;
            }
            if (TargetDrawer.skin.IsNull())
            {
                string skin = EditorGUIUtility.isProSkin || EditorPref.Get <bool>("Zios.Theme.Dark", false) ? "Dark" : "Light";
                TargetDrawer.skin = File.GetAsset <GUISkin>("Gentleface-" + skin + ".guiskin");
            }
            Rect  toggleRect   = new Rect(area);
            Rect  propertyRect = new Rect(area);
            float labelWidth   = label.text.IsEmpty() ? 0 : EditorGUIUtility.labelWidth;

            propertyRect.x     += labelWidth + 18;
            propertyRect.width -= labelWidth + 18;
            toggleRect.x       += labelWidth;
            toggleRect.width    = 18;
            bool previousMode = target.mode == TargetMode.Direct;
            bool currentMode  = previousMode.Draw(toggleRect, "", TargetDrawer.skin.GetStyle("TargetToggle"));

            if (previousMode != currentMode)
            {
                target.mode = target.mode == TargetMode.Direct ? TargetMode.Search : TargetMode.Direct;
            }
            label.ToLabel().DrawLabel(area, null, true);
            ProxyEditor.RecordObject(target.parent, "Target Changes");
            if (target.mode == TargetMode.Direct)
            {
                target.directObject = target.directObject.Draw <GameObject>(propertyRect, "", true);
            }
            else
            {
                target.Verify();
                var     faded       = GUI.skin.textField.Background("").TextColor(GUI.skin.textField.normal.textColor.SetAlpha(0.75f)).ContentOffset(-3, 0).UseState("normal");
                Rect    textRect    = propertyRect;
                string  result      = !target.searchObject.IsNull() ? target.searchObject.GetPath().Trim("/") : "Not Found.";
                Vector2 textSize    = TargetDrawer.skin.textField.CalcSize(new GUIContent(target.search));
                Vector2 subtleSize  = faded.CalcSize(new GUIContent(result));
                float   subtleX     = propertyRect.x + propertyRect.width - subtleSize.x;
                float   subtleWidth = subtleSize.x;
                float   minimumX    = propertyRect.x + textSize.x + 3;
                if (subtleX < minimumX)
                {
                    subtleWidth -= (minimumX - subtleX);
                    subtleX      = minimumX;
                }
                propertyRect = propertyRect.SetX(subtleX).SetWidth(subtleWidth);
                EditorGUIUtility.AddCursorRect(propertyRect, MouseCursor.Zoom);
                if (!target.searchObject.IsNull() && propertyRect.Clicked(0))
                {
                    Selection.activeGameObject = target.searchObject;
                    Event.current.Use();
                }
                target.search = target.search.Draw(textRect);
                result.ToLabel().DrawLabel(propertyRect, faded);
            }
            if (GUI.changed && !target.IsNull())
            {
                target.Search();
                if (target.parent is DataBehaviour)
                {
                    var parent = target.parent.As <DataBehaviour>();
                    parent.DelayEvent(parent.path, "On Validate");
                    ProxyEditor.SetDirty(parent);
                }
            }
        }
示例#2
0
        public void RefreshSceneView(bool rebuild)
        {
            this.Setup();
            this.RefreshShader();
            var meshLists = new List <GameObject>[2] {
                this.vertexMeshes, this.distanceMeshes
            };

            if (this.vertexMeshes.Count != this.cached.Values.SelectMany(x => x).ToArray().Length)
            {
                rebuild = true;
            }
            if (!this.lockSelection && rebuild)
            {
                this.cached.Clear();
                foreach (var selected in Selection.gameObjects)
                {
                    if (!selected.IsNull() && !selected.name.Contains("@TempMesh"))
                    {
                        this.cached[selected] = selected.GetMeshSources().Where(x => x.target.activeInHierarchy).ToArray();
                    }
                }
                this.RemoveMeshes();
                if (this.visible || this.alwaysDisplay)
                {
                    foreach (var displayMeshes in meshLists)
                    {
                        displayMeshes.Clear();
                        var material = displayMeshes == this.vertexMeshes ? this.vertexMaterial : this.distanceMaterial;
                        foreach (var target in this.cached.SelectMany(x => x.Value))
                        {
                            var instance = displayMeshes.AddNew();
                            var mesh     = target.GetMesh(true).Copy();
                            instance.name      = "@TempMesh";
                            instance.hideFlags = HideFlags.HideInHierarchy | HideFlags.DontSave;
                            instance.AddComponent <MeshFilter>().mesh = mesh;
                            var renderer  = instance.AddComponent <MeshRenderer>();
                            var materials = new Material[mesh.subMeshCount];
                            for (var index = 0; index < mesh.subMeshCount; ++index)
                            {
                                materials[index] = material;
                            }
                            renderer.materials = materials;
                        }
                    }
                }
            }
            if (this.visible || this.alwaysDisplay)
            {
                var cachedTargets = this.cached.SelectMany(x => x.Value).ToArray();
                foreach (var displayMeshes in meshLists)
                {
                    for (var index = 0; index < displayMeshes.Count; ++index)
                    {
                        if (cachedTargets[index].IsNull())
                        {
                            continue;
                        }
                        var target   = cachedTargets[index].target;
                        var instance = displayMeshes[index];
                        if (target.IsNull() || instance.IsNull())
                        {
                            continue;
                        }
                        instance.transform.position   = target.transform.position;
                        instance.transform.rotation   = target.transform.rotation;
                        instance.transform.localScale = target.transform.localScale;
                        if (!cachedTargets[index].skinnedRenderer)
                        {
                        }
                    }
                }
                this.ClearVertexes();
                this.FindOverlapping();
            }
            ProxyEditor.RepaintSceneView();
        }
示例#3
0
        public override void OnInspectorGUI()
        {
            EditorUI.Reset();
            Events.Add("On Editor Update", this.EditorUpdate);
            if (this.renderer.sharedMesh != this.blendState.mesh)
            {
                this.OnEnable();
            }
            var blendValues = this.blendState.values;
            var id          = this.renderer.GetInstanceID();

            EditorUI.SetFieldSize(-1, 150, false);
            var hasSkeletal    = !this.target.As <AnimationSettings>().Get <Animation>().IsNull();
            var hasBlendshapes = blendValues.Count > 0;

            if (hasBlendshapes && (!hasSkeletal || EditorUI.DrawFoldout("Blend Shapes", id + "Blend")))
            {
                EditorGUI.indentLevel += 1;
                var wrap   = this.renderer.gameObject.GetMeshWrap();
                var names  = blendValues.Keys.ToList();
                var values = this.blendStates.Values.ToList();
                var active = values.IndexOf(this.blendState);
                this.blendState = values[this.blendStates.Keys.ToList().Draw(active, "State")];
                if (EditorUI.lastChanged)
                {
                    this.SetBlendState(this.blendState.name);
                    this.Repaint();
                }
                for (var index = 0; index < blendValues.Count; ++index)
                {
                    if (index > names.Count - 1)
                    {
                        break;
                    }
                    var shapeName  = names[index];
                    var shapeValue = this.renderer.GetBlendShapeWeight(index);
                    var separated  = blendValues.ContainsKey(shapeName + "-Left") && blendValues.ContainsKey(shapeName + "-Right");
                    if (shapeName.EndsWith("-"))
                    {
                        continue;
                    }
                    if (shapeName.EndsWith("+"))
                    {
                        shapeName = shapeName.TrimRight("+");
                        if (!wrap.blendShapes.ContainsKey(shapeName + "-"))
                        {
                            Log.Warning("[AnimationSettings] Matching blendshape (" + shapeName + "-) does not exist. Skipping.");
                            continue;
                        }
                        var negativeIndex = wrap.blendShapes[shapeName + "-"].index;
                        var positiveIndex = wrap.blendShapes[shapeName + "+"].index;
                        var negativeValue = this.renderer.GetBlendShapeWeight(negativeIndex);
                        var displayValue  = shapeValue > 0 ? (shapeValue / 100f).Lerp(50, 100) : 50f;
                        displayValue = negativeValue > 0 ? (negativeValue / 100f).Lerp(50, 0) : displayValue;
                        displayValue = displayValue.DrawSlider(0, 100, shapeName);
                        if (EditorUI.lastChanged)
                        {
                            blendValues[shapeName + "+"] = 100 * displayValue.InverseLerp(50, 100);
                            blendValues[shapeName + "-"] = 100 * displayValue.InverseLerp(50, 0);
                            this.renderer.SetBlendShapeWeight(positiveIndex, blendValues[shapeName + "+"]);
                            this.renderer.SetBlendShapeWeight(negativeIndex, blendValues[shapeName + "-"]);
                        }
                        index += 1;
                        continue;
                    }
                    var expanded = false;
                    if (separated)
                    {
                        EditorGUILayout.BeginHorizontal();
                        expanded = EditorUI.DrawFoldout(shapeName, id + shapeName + "Individual", EditorStyles.toggle);
                        EditorUI.SetFieldSize(-1, 96);
                        this.DrawBlendState(index, shapeName, shapeValue, null);
                        EditorGUILayout.EndHorizontal();
                        if (expanded)
                        {
                            EditorGUI.indentLevel += 1;
                            EditorUI.SetFieldSize(-1, 150, false);
                            this.DrawBlendState(index + 1, shapeName + "-Left", this.renderer.GetBlendShapeWeight(index + 1), "Left");
                            this.DrawBlendState(index + 2, shapeName + "-Right", this.renderer.GetBlendShapeWeight(index + 2), "Right");
                            EditorGUI.indentLevel -= 1;
                        }
                        index += 2;
                        continue;
                    }
                    this.DrawBlendState(index, shapeName, shapeValue);
                }
                EditorGUILayout.BeginHorizontal();
                this.newState = this.newState.Layout(150, 18).Draw();
                if ("Add State".ToLabel().Layout(100, 19).DrawButton() && !this.newState.IsEmpty() && !this.blendStates.ContainsKey(this.newState))
                {
                    var mesh = Mesh.Instantiate(this.renderer.sharedMesh);
                    this.renderer.BakeMesh(mesh);
                    this.blendStates.AddNew(this.newState).Set(this.newState, mesh);
                    this.SetBlendState(this.newState);
                    this.newState = "";
                }
                if ("Randomize".ToLabel().Layout(100, 19).DrawButton())
                {
                    foreach (var item in wrap.blendShapes)
                    {
                        var shape = item.Value;
                        this.renderer.SetBlendShapeWeight(shape.index, Random.Range(0, 100));
                    }
                }
                if ("Reset".ToLabel().Layout(100, 19).DrawButton())
                {
                    foreach (var item in wrap.blendShapes)
                    {
                        var shape = item.Value;
                        this.renderer.SetBlendShapeWeight(shape.index, 0);
                    }
                }
                EditorGUILayout.EndHorizontal();
                EditorGUI.indentLevel -= 1;
            }
            EditorUI.allowIndention = false;
            if (hasSkeletal && (!hasBlendshapes || EditorUI.DrawFoldout("Skeletal", id + "Skeleton")))
            {
                EditorGUILayout.BeginHorizontal();
                "Name".Layout(150).DrawLabel();
                "Rate •".Layout(50).DrawLabel();
                if (GUILayoutUtility.GetLastRect().Clicked())
                {
                    AnimationConfiguration.rateMode.Get().GetNames().DrawMenu(this.SetRateMode, AnimationConfiguration.rateMode.Get().ToName().AsList());
                }
                "Speed •".Layout(50).DrawLabel();
                if (GUILayoutUtility.GetLastRect().Clicked())
                {
                    AnimationConfiguration.speedMode.Get().GetNames().DrawMenu(this.SetSpeedMode, AnimationConfiguration.speedMode.Get().ToName().AsList());
                }
                "Blend".Layout(80).DrawLabel();
                "Wrap".Layout(115).DrawLabel();
                EditorGUILayout.EndHorizontal();
                foreach (var config in this.target.As <AnimationSettings>().animations)
                {
                    EditorGUILayout.BeginHorizontal();
                    bool isPlaying = this.active.Contains(config);
                    config.name.Layout(150).DrawLabel();
                    config.rate      = config.rate.Layout(50).Draw();
                    config.speed     = config.speed.Layout(50).Draw();
                    config.blendMode = config.blendMode.Layout(80).Draw().As <AnimationBlendMode>();
                    config.wrapMode  = config.wrapMode.Layout(115).Draw().As <WrapMode>();
                    if (isPlaying && "Stop".ToLabel().Layout(0, 17).DrawButton())
                    {
                        this.Stop(config);
                    }
                    if (!isPlaying && "Play".ToLabel().Layout(0, 17).DrawButton())
                    {
                        this.StopAll();
                        this.active.AddNew(config);
                        Events.Pause("On Hierarchy Changed");
                    }
                    if (GUI.changed)
                    {
                        ProxyEditor.RecordObject(this.target, "Animation Settings Changed");
                        config.Apply();
                        ProxyEditor.SetDirty(this.target);
                    }
                    EditorGUILayout.EndHorizontal();
                }
            }
        }
        public override void OnInspectorGUI()
        {
            EditorUI.Reset();
            ProxyEditor.GetInspector(this).SetTitle(this.title);
            ProxyEditor.GetInspectors().ForEach(x => x.wantsMouseMove = true);
            if (!Event.current.IsUseful())
            {
                return;
            }
            if (this.target is MonoBehaviour && this.target.As <MonoBehaviour>().InPrefabFile())
            {
                return;
            }
            this.BeginArea();
            bool fastInspector = EditorPref.Get <bool>("MonoBehaviourEditor-FastInspector");

            /*if(fastInspector && MonoBehaviourEditor.offScreen.ContainsKey(this)){
             *      GUILayout.Space(this.area.height);
             *      this.CheckChanges();
             *      return;
             * }*/
            if (Event.current.type == EventType.MouseMove)
            {
                Call.Delay(ProxyEditor.RepaintInspectors, 0.1f);
            }
            bool hideAllDefault = EditorPref.Get <bool>("MonoBehaviourEditor-HideAllDefault", false);

            this.hideDefault = EditorPref.Get <bool>("MonoBehaviourEditor-" + this.target.GetInstanceID() + "HideDefault", false);
            bool hideDefault = hideAllDefault || this.hideDefault;

            if (hideDefault)
            {
                this.SortDefaults();
            }
            this.serializedObject.Update();
            this.SortProperties();
            this.Setup();
            Type type = this.target.GetType();

            this.changed = false;
            bool showAdvanced   = EditorPref.Get <bool>("MonoBehaviourEditor-Advanced");
            bool showInternal   = EditorPref.Get <bool>("MonoBehaviourEditor-Internal");
            bool showDictionary = EditorPref.Get <bool>("MonoBehaviourEditor-Dictionary");

            EditorGUILayout.BeginVertical();
            foreach (var property in this.properties)
            {
                string[] attributes = this.serializedObject.targetObject.ListAttributes(property.name).Select(x => x.GetType().Name).ToArray();
                bool     isInternal = attributes.Contains("InternalAttribute");
                bool     isAdvanced = attributes.Contains("AdvancedAttribute");
                bool     isReadOnly = isInternal || attributes.Contains("ReadOnlyAttribute");
                bool     isHidden   = !this.showAll && this.hidden.Contains(property);
                if (isAdvanced && !showAdvanced)
                {
                    isHidden = true;
                }
                if (isInternal && !showInternal)
                {
                    isHidden = true;
                }
                object currentValue = property.GetObject <object>();
                bool   hasDefault   = MonoBehaviourEditor.defaults.ContainsKey(type) && MonoBehaviourEditor.defaults[type].ContainsKey(property.name);
                if (!this.showAll && hideDefault && hasDefault)
                {
                    object defaultValue = MonoBehaviourEditor.defaults[type][property.name];
                    if (defaultValue.IsNull())
                    {
                        continue;
                    }
                    bool isDefault = defaultValue.Equals(currentValue);
                    if (isDefault)
                    {
                        isHidden = true;
                    }
                }
                if (!isHidden)
                {
                    bool hasArea = this.propertyArea.ContainsKey(property);
                    if (hasArea)
                    {
                        if (Event.current.shift)
                        {
                            bool canHide = (this.properties.Count - this.hidden.Count) > 1;
                            if (this.propertyArea[property].Clicked(0) && canHide)
                            {
                                string path = "MonoBehaviourEditor-PropertyHide-" + this.target.GetInstanceID() + "-" + property.propertyPath;
                                EditorPref.Set <bool>(path, true);
                                this.hidden.Add(property);
                            }
                            if (this.propertyArea[property].Clicked(1))
                            {
                                this.DrawMenu();
                            }
                        }
                        if (fastInspector && this.propertyVisible.ContainsKey(property) && !this.propertyVisible[property])
                        {
                            GUILayout.Space(this.propertyArea[property].height);
                            continue;
                        }
                    }
                    string propertyName = null;
                    if (isReadOnly)
                    {
                        GUI.enabled = false;
                    }
                    GUI.changed = false;
                    EditorGUILayout.BeginVertical();
                    if (hasArea)
                    {
                        EditorGUI.BeginProperty(this.propertyArea[property], new GUIContent(property.displayName), property);
                    }
                    property.Draw(propertyName);
                    if (hasArea)
                    {
                        EditorGUI.EndProperty();
                    }
                    EditorGUILayout.EndVertical();
                    this.changed = this.changed || GUI.changed;
                    if (isReadOnly)
                    {
                        GUI.enabled = true;
                    }
                    if (Proxy.IsRepainting())
                    {
                        Rect area = GUILayoutUtility.GetLastRect();
                        if (!area.IsEmpty())
                        {
                            this.propertyArea[property] = area.AddHeight(2);
                        }
                    }
                }
            }
            if (showDictionary)
            {
                GUI.enabled = false;
                foreach (var item in this.dictionaries)
                {
                    item.Value.DrawAuto(item.Key, null, true);
                }
                GUI.enabled = true;
            }
            EditorGUILayout.EndVertical();
            this.EndArea();
            if (this.changed)
            {
                this.serializedObject.ApplyModifiedProperties();
                //this.serializedObject.targetObject.CallMethod("OnValidate");
                ProxyEditor.SetDirty(this.serializedObject.targetObject, false, true);
            }
            this.CheckChanges();
            if (Proxy.IsRepainting())
            {
                ProxyEditor.GetInspector(this).SetTitle("Inspector");
            }
        }
示例#5
0
 public void MonitorStart()
 {
     this.ThreadStart();
     ProxyEditor.AddUpdate(Worker.MonitorCheck);
 }
示例#6
0
        public ProxyManagerViewModel()
        {
            RunTests = new DelegateCommand(parameter =>
            {
                foreach (ProxyTestableViewModel proxy in Proxies)
                {
                    if (proxy.TestProxy.CanExecute(parameter))
                    {
                        proxy.TestProxy.ExecuteAsync(SelectedSite.BaseUrl);
                    }
                }
            },
                                           parameter => Proxies.Count > 0);

            Delete = new DelegateCommand(parameter =>
            {
                foreach (ProxyTestableViewModel proxy in SelectedProxies.ToList())
                {
                    m_model.Remove(proxy.Model);
                }
            },
                                         parameter => SelectedProxies.Count > 0);

            Export = new DelegateCommand(parameter =>
            {
                SaveFileDialog saveFileDialog = new SaveFileDialog
                {
                    DefaultExt = ".csv",
                    Filter     = "CSV files (.csv)|*.csv"
                };

                if (saveFileDialog.ShowDialog() ?? false)
                {
                    using (StreamWriter writer = new StreamWriter(saveFileDialog.FileName))
                    {
                        foreach (ProxyTestableViewModel proxy in Proxies)
                        {
                            writer.WriteLine($"{proxy.IP}:{proxy.Port}:{proxy.Username ?? ""}:{proxy.Password ?? ""}");
                        }

                        writer.Close();
                    }
                }
            },
                                         parameter => Proxies.Count > 0);

            Import = new DelegateCommand(parameter =>
            {
                OpenFileDialog openFIleDialog = new OpenFileDialog()
                {
                    DefaultExt = ".csv",
                    Filter     = "CSV files (.csv)|*.csv"
                };

                if (openFIleDialog.ShowDialog() ?? false)
                {
                    using (StreamReader reader = new StreamReader(openFIleDialog.FileName))
                    {
                        int lineCount = 0;
                        bool isOk     = true;
                        while (!reader.EndOfStream)
                        {
                            Proxy proxy = null;

                            try
                            {
                                proxy = new Proxy(reader.ReadLine());
                            }
                            catch (Exception e)
                            {
                                isOk = false;
                                break;
                            }

                            //if (m_model.Where(p => p.IP.Equals(proxy.IP)).ToList().Count == 0)
                            {
                                m_model.Add(proxy);
                            }

                            lineCount++;
                        }

                        if (!isOk)
                        {
                            MessageBox.Show($"Wrong format at line {lineCount + 1}");
                        }

                        reader.Close();
                    }
                }
            });

            AddNew = new DelegateCommand(parameter =>
            {
                ProxyEditor proxyEditor = null;
                Proxy proxy             = new Proxy();

                while (true)
                {
                    proxyEditor = new ProxyEditor()
                    {
                        DataContext = new ProxyEditViewModel()
                        {
                            Model = proxy
                        }
                    };

                    if (proxyEditor.ShowDialog() ?? false)
                    {
                        //if (m_model.Where(p => p.IP.Equals(proxy.IP)).ToList().Count == 0)
                        {
                            m_model.Add(proxy);

                            break;
                        }

                        //MessageBox.Show($"Proxy with IP {proxy.IP} already exists", "Duplication", MessageBoxButton.OK, MessageBoxImage.Warning);
                    }
                    else
                    {
                        break;
                    }
                }
            });

            Edit = new DelegateCommand(parameter =>
            {
                ProxyEditor proxyEditor = null;
                Proxy originalProxy     = SelectedProxies[0].Model;
                Proxy proxy             = new Proxy(originalProxy);

                while (true)
                {
                    proxyEditor = new ProxyEditor()
                    {
                        DataContext = new ProxyEditViewModel()
                        {
                            Model = proxy
                        }
                    };

                    if (proxyEditor.ShowDialog() ?? false)
                    {
                        //List<Proxy> dupList = m_model.Where(p => p.IP.Equals(proxy.IP)).ToList();

                        //if (dupList.Count == 0 || dupList[0] == originalProxy)
                        {
                            m_model[m_model.IndexOf(originalProxy)] = proxy;
                            break;
                        }

                        //MessageBox.Show($"Proxy with IP {proxy.IP} already exists", "Duplication", MessageBoxButton.OK, MessageBoxImage.Warning);
                    }
                    else
                    {
                        break;
                    }
                }
            },
                                       parameter => SelectedProxies.Count == 1);

            PasteProxies = new DelegateCommand(parameter =>
            {
                string[] strs = Clipboard.GetText().Split(new string[] { Environment.NewLine }, StringSplitOptions.None);

                foreach (string s in strs)
                {
                    Proxy proxy = null;

                    try
                    {
                        proxy = new Proxy(s);
                    }
                    catch (Exception e)
                    {
                    }

                    if (proxy != null)
                    {
                        m_model.Add(proxy);
                    }
                }
            });
        }
示例#7
0
 public string GetGUID()
 {
     return(ProxyEditor.GetGUID(this.GetAssetPath()));
 }
示例#8
0
        public static void Flatten(params UnityObject[] targets)
        {
            string originalName = "";

            foreach (var target in targets)
            {
                Material material   = (Material)target;
                FileData shaderFile = VariableMaterial.GetParentShader(target);
                if (shaderFile.IsNull())
                {
                    continue;
                }
                string timestamp   = shaderFile.GetModifiedDate("MdyyHmmff");
                string projectPath = Application.dataPath + "/" + "Shaders";
                string hash        = timestamp + "-" + material.shaderKeywords.Join(" ").ToMD5();
                string folderPath  = projectPath + "/" + shaderFile.name + "/";
                string outputPath  = folderPath + shaderFile.name + "#" + hash + ".shader";
                Action update      = () => {
                    ProxyEditor.RecordObject(material, "Variable Material - Shader Set");
                    material.EnableKeyword("VARIABLE_MATERIAL_" + shaderFile.name.ToUpper());
                    material.shader = File.GetAsset <Shader>(outputPath);
                    ProxyEditor.SetAssetDirty(material);
                    if (VariableMaterial.debug)
                    {
                        Log.Show("[VariableMaterial] Shader set " + outputPath);
                    }
                };
                if (!VariableMaterial.force && File.Exists(outputPath))
                {
                    VariableMaterial.updates += update;
                    continue;
                }
                originalName = shaderFile.fullName;
                string text       = shaderFile.ReadText();
                string shaderName = text.Parse("Shader ", "{").Trim(' ', '"');
                if (shaderName.Contains("#"))
                {
                    continue;
                }
                string output  = "Shader " + '"' + "Hidden/" + shaderName + "#" + hash + '"' + "{\r\n";
                var    allowed = new Stack <bool?>();
                int    tabs    = -1;
                text = text.Replace("\\\r\n", "");
                int lineNumber = 0;
                foreach (string current in text.Split("\r\n").Skip(1))
                {
                    lineNumber += 1;
                    if (current.IsEmpty())
                    {
                        continue;
                    }
                    string line          = current;
                    bool   hideBlock     = allowed.Count > 0 && allowed.Peek() != true;
                    bool   allowedBranch = line.ContainsAny("#else", "#elif") && allowed.Peek() != null;
                    bool   ignoredBranch = line.Contains("@#");
                    //if(line.ContainsAny("[KeywordEnum","[Toggle")){continue;}
                    if (!ignoredBranch && line.Contains("#endif"))
                    {
                        allowed.Pop();
                        if (allowed.Count == 0)
                        {
                            tabs = -1;
                        }
                        continue;
                    }
                    if (hideBlock && !allowedBranch)
                    {
                        if (!ignoredBranch && line.ContainsAny("#if"))
                        {
                            allowed.Push(null);
                        }
                        continue;
                    }
                    if (ignoredBranch)
                    {
                        bool end     = line.Contains("#end");
                        bool include = line.Contains("#include");
                        if (tabs < 0)
                        {
                            tabs = line.Length - line.TrimStart().Length;
                        }
                        if (end)
                        {
                            tabs -= 1;
                        }
                        line    = new String('\t', tabs) + line.TrimStart();
                        output += line.Replace("@#", "#") + "\r\n";
                        if (!end && !include)
                        {
                            tabs += 1;
                        }
                        continue;
                    }
                    if (line.Contains("#include"))
                    {
                        line = line.Replace("#include \"", "#include \"../");
                    }
                    if (line.Contains("#pragma shader_feature"))
                    {
                        continue;
                    }
                    if (line.Contains("#pragma multi_compile "))
                    {
                        continue;
                    }
                    if (line.ContainsAny("#if", "#elif", "#else"))
                    {
                        bool useBlock = false;
                        if (line.ContainsAny("#else", "#elif"))
                        {
                            bool lastAllowed = allowed.Pop() == true;
                            if (lastAllowed)
                            {
                                allowed.Push(null);
                                continue;
                            }
                            useBlock = line.Contains("#else");
                        }
                        if (line.ContainsAny("#ifdef", "#ifndef"))
                        {
                            bool hasTerm = material.shaderKeywords.Contains(line.Trim().Split(" ").Last());
                            useBlock = line.Contains("#ifndef") ? !hasTerm : hasTerm;
                        }
                        else if (line.Contains("defined"))
                        {
                            string[] orBlocks = line.Trim().Trim("#if ").Trim("#elif ").Split("||");
                            foreach (string orBlock in orBlocks)
                            {
                                string[] andBlocks = orBlock.Split("&&");
                                foreach (string andBlock in andBlocks)
                                {
                                    string term    = andBlock.Parse("defined(", ")");
                                    bool   hasTerm = material.shaderKeywords.Contains(term);
                                    useBlock = andBlock.Contains("!") ? !hasTerm : hasTerm;
                                    if (!useBlock)
                                    {
                                        break;
                                    }
                                }
                                if (useBlock)
                                {
                                    break;
                                }
                            }
                        }
                        allowed.Push(useBlock);
                        if (useBlock && allowed.Count == 1 && tabs <= 0)
                        {
                            tabs = line.Length - line.TrimStart().Length;
                        }
                        continue;
                    }
                    if (tabs >= 1)
                    {
                        if (line.Contains("}") && !line.Contains("{"))
                        {
                            tabs -= 1;
                        }
                        line = new String('\t', tabs) + line.TrimStart();
                        if (line.Contains("{") && !line.Contains("}"))
                        {
                            tabs += 1;
                        }
                    }
                    output += line + "\r\n";
                }
                output = output.Replace("{\r\n\t\t\t}", "{}");
                string pattern = output.Cut("{\r\n\t\t\t\treturn ", ";\r\n\t\t\t");
                while (!pattern.IsEmpty())
                {
                    string replace = pattern.Replace("\r\n", "").Replace("\t", "");
                    output  = output.ReplaceFirst(pattern, replace);
                    pattern = output.Cut("{\r\n\t\t\t\treturn ", ";\r\n\t\t\t");
                }
                if (output != text)
                {
                    Action write = () => {
                        File.Create(outputPath).Write(output);
                    };
                    VariableMaterial.writes  += write;
                    VariableMaterial.updates += update;
                }
            }
            if (VariableMaterial.debug)
            {
                Log.Show("[VariableMaterial] " + originalName + " -- " + targets.Length + " flattened.");
            }
            if (VariableMaterial.delay)
            {
                Call.Delay(VariableMaterial.RefreshEditor, 0.5f);
                return;
            }
            VariableMaterial.RefreshEditor();
            VariableMaterial.force = false;
        }
示例#9
0
 public override void OnInspectorGUI()
 {
     if (!Event.current.IsUseful())
     {
         return;
     }
     EditorUI.Reset();
     this.Setup(true);
     if (this.isVisible && MaterialBuffer.active != null)
     {
         Material material = MaterialBuffer.material;
         this.stateChanged = "";
         this.titleChanged = "";
         string unsaved = MaterialBuffer.unsaved ? "*" : "";
         MaterialBuffer.options["ShaderUnity"] = this.DrawTitle("Unity Shader" + unsaved, MaterialBuffer.options["ShaderUnity"]);
         if (MaterialBuffer.options["ShaderUnity"])
         {
             this.drawn = -2;
             bool isPreview = MaterialBuffer.active.menuPath.Contains("Hidden/Preview/");
             bool isBranch  = MaterialBuffer.active.fileName.Contains("#");
             bool exists    = Shader.Find(MaterialBuffer.active.menuPath) != null;
             EditorGUIUtility.labelWidth = Screen.width - 207;
             EditorGUILayout.BeginHorizontal();
             if (!isBranch && GUILayout.Button("Save"))
             {
                 string warning = "Saving will overwrite the original shader and effect all materials that use it.";
                 warning += "  It is advised to instead use the Save As or Branch option.";
                 bool confirm = EditorUI.DrawDialog("Are you sure?", warning, "Save", "Cancel");
                 if (confirm)
                 {
                     this.EndPreview();
                     MaterialBuffer.unsaved         = false;
                     MaterialBuffer.material.shader = MaterialBuffer.active.Save();
                     Log.Show("[ExtendedMaterial] Shader saved -- " + MaterialBuffer.active.path);
                     return;
                 }
             }
             if (GUILayout.Button("Save As"))
             {
                 if (exists && !isPreview)
                 {
                     GUI.FocusControl("Menu");
                     this.warning = "Menu path must be unique for shader.";
                 }
                 else
                 {
                     this.EndPreview();
                     MaterialBuffer.unsaved = false;
                     string path = EditorUtility.SaveFilePanel("Save Shader", MaterialBuffer.active.path, MaterialBuffer.active.fileName, "shader");
                     MaterialBuffer.material.shader = MaterialBuffer.active.Save(path);
                     Log.Show("[ExtendedMaterial] Shader saved -- " + path);
                     return;
                 }
             }
             if ((MaterialBuffer.unsaved || isPreview) && GUILayout.Button("Revert"))
             {
                 string warning = "Changes will be lost.";
                 bool   confirm = EditorUI.DrawDialog("Revert shader to defaults?", warning, "Revert", "Cancel");
                 if (confirm)
                 {
                     ProxyEditor.RegisterUndo(MaterialBuffer.material, "Shader Edit - Revert");
                     this.EndPreview();
                     this.FixPreviewShader(true);
                     return;
                 }
             }
             if (GUILayout.Button("Branch"))
             {
                 this.EndPreview();
                 MaterialBuffer.unsaved = false;
                 MaterialBuffer.active.Branch();
                 Log.Show("[ExtendedMaterial] Shader branched -- " + MaterialBuffer.active.path);
                 return;
             }
             EditorGUILayout.EndHorizontal();
             EditorGUILayout.BeginHorizontal();
             MaterialBuffer.options["ShowDefault"] = this.DrawToggleButton("Show Default", MaterialBuffer.options["ShowDefault"]);
             MaterialBuffer.options["ShowPreview"] = this.DrawToggleButton("Show Preview", MaterialBuffer.options["ShowPreview"]);
             EditorGUILayout.EndHorizontal();
             if (this.warning != "")
             {
                 EditorGUILayout.HelpBox(this.warning, MessageType.Warning);
             }
             EditorGUI.BeginDisabledGroup(true);
             MaterialBuffer.active.fileName = (string)this.Draw("File", MaterialBuffer.active.fileName.Remove("-Preview"));
             EditorGUI.EndDisabledGroup();
             string pathPrefix = isPreview ? "Hidden/Preview/" : "";
             MaterialBuffer.active.menuPath       = pathPrefix + (string)this.Draw("Menu", MaterialBuffer.active.menuPath.Remove("\\", "Hidden/Preview/"));
             MaterialBuffer.active.fallback       = (string)this.Draw("Fallback", MaterialBuffer.active.fallback, "");
             MaterialBuffer.active.editor         = (string)this.Draw("Editor", MaterialBuffer.active.editor, "");
             MaterialBuffer.options["Properties"] = this.DrawFold("Properties", MaterialBuffer.options["Properties"]);
             if (MaterialBuffer.options["Properties"])
             {
                 EditorGUI.BeginChangeCheck();
                 EditorGUILayout.BeginHorizontal();
                 EditorGUILayout.LabelField("\t", GUILayout.Width(10));
                 EditorGUILayout.LabelField("Variable", GUILayout.Width(100));
                 EditorGUILayout.LabelField("Type", GUILayout.Width(60));
                 EditorGUILayout.LabelField("Name", GUILayout.Width(100));
                 EditorGUILayout.LabelField("Default", GUILayout.Width(100));
                 EditorGUILayout.EndHorizontal();
                 foreach (var item in MaterialBuffer.active.properties)
                 {
                     EditorGUILayout.BeginHorizontal();
                     Property property = item.Value;
                     string   type     = property.type.ToString();
                     EditorGUILayout.LabelField("", GUILayout.Width(10));
                     property.variable = EditorGUILayout.TextField(property.variable, GUILayout.Width(100));
                     property.type     = (PropertyType)EditorGUILayout.EnumPopup(property.type, GUILayout.Width(60));
                     property.name     = EditorGUILayout.TextField(property.name, GUILayout.Width(100));
                     if (type != property.type.ToString())
                     {
                         property.SetDefault();
                         continue;
                     }
                     if (type == "Range")
                     {
                         property.minimum      = EditorGUILayout.FloatField(property.minimum, GUILayout.Width(30));
                         property.maximum      = EditorGUILayout.FloatField(property.maximum, GUILayout.Width(30));
                         property.defaultValue = EditorGUILayout.FloatField((float)property.defaultValue, GUILayout.Width(64));
                     }
                     else if (type == "Color")
                     {
                         property.defaultValue = EditorGUILayout.ColorField((Color)property.defaultValue, GUILayout.Width(128));
                     }
                     else if (type == "Texture" || type == "Rect" || type == "Cube")
                     {
                         property.texgenMode   = (TexGen)EditorGUILayout.EnumPopup(property.texgenMode, GUILayout.Width(64));
                         property.defaultValue = (TextureDefault)EditorGUILayout.EnumPopup((Enum)property.defaultValue, GUILayout.Width(64));
                     }
                     else
                     {
                         property.defaultValue = EditorGUILayout.TextField(property.defaultValue.ToString(), GUILayout.Width(132));
                     }
                     EditorGUILayout.EndHorizontal();
                     this.hoverObject = this.CheckHover() ? property : this.hoverObject;
                 }
                 bool changes = EditorGUI.EndChangeCheck();
                 if (GUILayout.Button("Add Property", this.UI.button, GUILayout.Width(115)))
                 {
                     //ProxyEditor.RegisterUndo(Buffer.active,"Shader - Add Property");
                     MaterialBuffer.active.AddProperty();
                     this.stateChanged = "Event-AddProperty";
                 }
                 this.stateChanged         = changes ? "Property" : this.stateChanged;
                 MaterialBuffer.branchable = !changes;
             }
             int shaderIndex = 0;
             int passIndex   = 0;
             foreach (SubShader subShader in MaterialBuffer.active.subShaders)
             {
                 shaderIndex += 1;
                 string hash           = "Sub" + shaderIndex;
                 bool   showSubShaders = MaterialBuffer.active.subShaders.Count > 0;
                 if (!MaterialBuffer.options.ContainsKey(hash))
                 {
                     continue;
                 }
                 int    passAmount = subShader.passes.Count;
                 string passInfo   = passAmount > 1 ? " [" + passAmount + " passes]" : " [1 pass]";
                 if (showSubShaders)
                 {
                     MaterialBuffer.options[hash] = this.DrawFold("SubShader" + passInfo, MaterialBuffer.options[hash]);
                 }
                 this.hoverObject = this.CheckHover() ? subShader : this.hoverObject;
                 if (showSubShaders && !MaterialBuffer.options[hash])
                 {
                     continue;
                 }
                 if (showSubShaders)
                 {
                     ++EditorGUI.indentLevel;
                 }
                 this.DrawCommon(subShader);
                 bool hideTags = !MaterialBuffer.options["ShowDefault"] && subShader.tags.IsDefault();
                 if (!hideTags)
                 {
                     MaterialBuffer.options[hash + "Tags"] = this.DrawFold("Tags", MaterialBuffer.options[hash + "Tags"]);
                     if (MaterialBuffer.options[hash + "Tags"])
                     {
                         ++EditorGUI.indentLevel;
                         subShader.tags.lightMode   = (LightMode)this.Draw("Light Mode", subShader.tags.lightMode);
                         subShader.tags.require     = (Require)this.Draw("Require", subShader.tags.require);
                         subShader.tags.renderQueue = (RenderQueue)this.Draw("Render Queue", subShader.tags.renderQueue);
                         if (subShader.tags.renderQueue != RenderQueue.Default)
                         {
                             ++EditorGUI.indentLevel;
                             subShader.tags.renderQueueOffset = (int)this.Draw("Offset", subShader.tags.renderQueueOffset);
                             --EditorGUI.indentLevel;
                         }
                         subShader.tags.renderType           = (RenderType)this.Draw("Render Type", subShader.tags.renderType);
                         subShader.tags.ignoreProjector      = (bool)this.Draw("Ignore Projector", subShader.tags.ignoreProjector, false);
                         subShader.tags.forceNoShadowCasting = (bool)this.Draw("No Shadow Casting", subShader.tags.forceNoShadowCasting, false);
                         --EditorGUI.indentLevel;
                     }
                 }
                 this.DrawFog(subShader.fog, hash);
                 string   resetPass = "";
                 PassType resetType = PassType.Normal;
                 foreach (var item in subShader.passes)
                 {
                     passIndex += 1;
                     Pass   pass     = item.Value;
                     string passHash = "Pass" + passIndex;
                     string passName = pass.name != "" && !pass.name.Contains("!") ? "Pass [" + pass.name + "]" : "Pass";
                     if (pass.type == PassType.Use)
                     {
                         passName = "UsePass";
                     }
                     if (pass.type == PassType.Grab)
                     {
                         passName = "GrabPass";
                     }
                     MaterialBuffer.options[passHash] = this.DrawFold(passName, MaterialBuffer.options[passHash]);
                     this.hoverObject = this.CheckHover() ? new object[] { subShader, pass } : this.hoverObject;
                     if (!MaterialBuffer.options[passHash])
                     {
                         continue;
                     }
                     ++EditorGUI.indentLevel;
                     PassType passType = pass.type;
                     pass.type = (PassType)this.Draw("Type", pass.type);
                     if (pass.type != passType)
                     {
                         resetPass = item.Key;
                         resetType = pass.type;
                         continue;
                     }
                     if (pass.type == PassType.Normal)
                     {
                         pass.name = (string)this.Draw("Name", pass.name, "");
                         this.DrawCommon(pass);
                         bool hidePassTags = !MaterialBuffer.options["ShowDefault"] && pass.tags.IsDefault();
                         if (!hidePassTags)
                         {
                             MaterialBuffer.options[passHash + "Tags"] = this.DrawFold("Tags", MaterialBuffer.options[passHash + "Tags"]);
                             if (MaterialBuffer.options[passHash + "Tags"])
                             {
                                 ++EditorGUI.indentLevel;
                                 pass.tags.lightMode = (LightMode)this.Draw("Light Mode", pass.tags.lightMode);
                                 pass.tags.require   = (Require)this.Draw("Require", pass.tags.require);
                                 --EditorGUI.indentLevel;
                             }
                         }
                         this.DrawFog(pass.fog, passHash);
                         bool hideGPUShader = !MaterialBuffer.options["ShowDefault"] && pass.gpuShader == "";
                         if (!hideGPUShader)
                         {
                             EditorGUI.BeginChangeCheck();
                             pass.gpuShader    = EditorGUILayout.TextArea(pass.gpuShader, GUILayout.Width(Screen.width - 45));
                             this.stateChanged = EditorGUI.EndChangeCheck() ? "TextArea" : this.stateChanged;
                         }
                     }
                     else if (pass.type == PassType.Use)
                     {
                         pass.usePass = (string)this.Draw("Shader", pass.usePass);
                     }
                     else if (pass.type == PassType.Grab)
                     {
                         pass.grabPass = (string)this.Draw("Texture", pass.grabPass, "");
                     }
                     --EditorGUI.indentLevel;
                 }
                 if (resetPass != "")
                 {
                     subShader.passes[resetPass]      = new Pass();
                     subShader.passes[resetPass].type = resetType;
                 }
                 if (GUILayout.Button("Add Pass", this.UI.button, GUILayout.Width(115)))
                 {
                     //ProxyEditor.RegisterUndo(Buffer.active,"Shader - Add Pass");
                     subShader.AddPass();
                     this.LoadSettings();
                     this.stateChanged = "Event-AddPass";
                 }
                 if (showSubShaders)
                 {
                     --EditorGUI.indentLevel;
                 }
             }
             if (GUILayout.Button("Add SubShader", GUILayout.Width(115)))
             {
                 //ProxyEditor.RegisterUndo(Buffer.active,"Shader - Add SubShader");
                 MaterialBuffer.active.AddSubShader();
                 this.LoadSettings();
                 this.stateChanged = "Event-AddSubShader";
             }
         }
         //Buffer.options["ShaderGPU"] = this.DrawTitle("GPU Shader",Buffer.options["ShaderGPU"]);
         MaterialBuffer.options["Material"] = this.DrawTitle("Material", MaterialBuffer.options["Material"]);
         if (MaterialBuffer.options["Material"])
         {
             EditorGUIUtility.labelWidth = Screen.width - 84;
             base.OnInspectorGUI();
         }
         if (this.stateChanged != "" || this.titleChanged != "")
         {
             foreach (var item in MaterialBuffer.options)
             {
                 string key           = item.Key;
                 int    value         = item.Value.ToInt();
                 string settingPrefix = key.ContainsAny("ShowDefault", "ShowPreview") ? "ExtendedMaterial-" : MaterialBuffer.material.name + "-";
                 EditorPref.Set <int>(settingPrefix + key, value);
             }
             this.warning = "";
             ProxyEditor.SetDirty(material);
         }
         if (this.titleChanged != "" || this.stateChanged.Contains("ToggleButton"))
         {
             GUI.FocusControl("Menu");
         }
         if (this.stateChanged != "")
         {
             MaterialBuffer.unsaved = true;
             if (MaterialBuffer.options["ShowPreview"])
             {
                 MaterialBuffer.buildDelay   = Time.Get();
                 MaterialBuffer.buildPreview = true;
             }
             if (this.stateChanged.Contains("TextArea"))
             {
                 MaterialBuffer.buildDelay += 2.0f;
             }
             if (this.stateChanged.Contains("Field"))
             {
                 MaterialBuffer.buildDelay += 1.5f;
             }
             if (this.stateChanged.Contains("Color"))
             {
                 MaterialBuffer.buildDelay += 0.5f;
             }
             //Log.Show("[ExtendedMaterial] Value changed -- " + this.stateChanged);
         }
     }
     this.CheckContext();
 }
示例#10
0
 public static string GetGUID(UnityObject target)
 {
     return(ProxyEditor.GetGUID(File.GetAssetPath(target)));
 }
示例#11
0
        public object Draw(string label, object field, object ignore = default(object))
        {
            EditorGUI.BeginChangeCheck();
            GUILayoutOption[] size = new GUILayoutOption[] { GUILayout.Width(165), GUILayout.Height(18) };
            GUILayoutOption[] half = new GUILayoutOption[] { GUILayout.Width(80), GUILayout.Height(18) };
            bool hideDefault       = (field is Enum && (int)field == 0);

            hideDefault = hideDefault || (ignore != default(object) && ignore.Equals(field));
            if (hideDefault && !MaterialBuffer.options["ShowDefault"])
            {
                return(field);
            }
            int indent = EditorGUI.indentLevel;

            EditorGUILayout.BeginHorizontal();
            Type type = field.GetType();

            if (label != "")
            {
                EditorGUILayout.PrefixLabel(label);
            }
            EditorGUI.indentLevel = 0;
            GUI.SetNextControlName(label);
            if (field is Enum)
            {
                field = EditorGUILayout.EnumPopup((Enum)field, size);
            }
            if (field is int)
            {
                field = EditorGUILayout.IntField((int)field, size);
            }
            if (field is float)
            {
                field = EditorGUILayout.FloatField((float)field, size);
            }
            if (field is string)
            {
                field = EditorGUILayout.TextField((string)field, size);
            }
            if (field is Color)
            {
                field = EditorGUILayout.ColorField((Color)field, size);
            }
            if (field is Vector2)
            {
                Vector2 value  = (Vector2)field;
                float   fieldA = EditorGUILayout.FloatField((float)value.x, half);
                float   fieldB = EditorGUILayout.FloatField((float)value.y, half);
                field = new Vector2(fieldA, fieldB);
            }
            if (type.IsArray && typeof(Enum).IsAssignableFrom(type.GetElementType()))
            {
                IEnumerable items  = (IEnumerable)field;
                List <Enum> result = new List <Enum>();
                foreach (object value in items)
                {
                    result.Add(EditorGUILayout.EnumPopup((Enum)value, half));
                }
                field = result.ToArray();
            }
            if (field is bool)
            {
                field = EditorGUILayout.Toggle((bool)field);
            }
            string typeName = field is Enum ? "Enum" : "Field";

            if (field is Color)
            {
                typeName = "Color";
            }
            if (field is bool)
            {
                typeName = "Toggle";
            }
            this.drawn += 1;
            EditorGUILayout.EndHorizontal();
            EditorGUI.indentLevel = indent;
            bool currentChanged = EditorGUI.EndChangeCheck();

            this.stateChanged = currentChanged ? typeName + "-" + label : this.stateChanged;
            if (currentChanged)
            {
                ProxyEditor.RegisterUndo(MaterialBuffer.active, "Shader Edit - " + label);
            }
            return(field);
        }
示例#12
0
        public void ApplyTexture(string path, Texture2D texture)
        {
            var empty = false;

            Worker.MainThread(() => empty = texture.IsNull());
            if (empty)
            {
                return;
            }
            var name        = path.GetPathTerm().TrimLeft("#");
            var ignoreAlpha = name.StartsWith("A-");
            var isSplat     = name.StartsWith("!");
            var parts       = name.TrimLeft("!", "A-").Split("-");

            if (isSplat && parts.Length < 2)
            {
                Log.Warning("[ThemePalette] : Improperly formed splat texture -- " + path.GetPathTerm());
                return;
            }
            var colorA = isSplat ? this.ParseColor(parts[0]) : Color.clear;
            var colorB = isSplat ? this.ParseColor(parts[1]) : Color.clear;
            var colorC = isSplat ? this.ParseColor(parts[2]) : Color.clear;

            if (isSplat)
            {
                parts = parts.Skip(3).ToArray();
            }
            name = parts.Join("-");
            bool      changes       = false;
            Texture2D originalImage = null;
            var       originalPath  = path.GetDirectory().GetDirectory() + "/" + name;
            var       pixels        = new Color[0];
            Action    method        = () => {
                originalImage = File.GetAsset <Texture2D>(originalPath, false);
                if (originalImage.IsNull() && !originalPath.ContainsAny("Themes", "@Themes"))
                {
                    originalImage = File.GetAsset <Texture2D>(name, false);
                }
                pixels = texture.GetPixels();
                if (originalImage.IsNull() || pixels.Length != originalImage.GetPixels().Length)
                {
                    Log.Show("[TexturePalette] : Generating source for index/splat -- " + originalPath.GetPathTerm());
                    texture.SaveAs(originalPath);
                    var assetPath = originalPath.GetAssetPath();
                    ProxyEditor.ImportAsset(assetPath);
                    var importer = TextureImporter.GetAtPath(assetPath).As <TextureImporter>();
                    ColorImportSettings.Apply(importer);
                    importer.SaveAndReimport();
                    originalImage = File.GetAsset <Texture2D>(originalPath, false);
                }
                originalPath = originalImage.GetAssetPath();
                if (Theme.debug && originalImage.format != TextureFormat.RGBA32)
                {
                    Log.Show("[ThemePalette] Original image is not an RGBA32 texture -- " + originalPath);
                }
            };

            Worker.MainThread(method);
            if (Theme.debug && pixels.Length > 65536)
            {
                Log.Warning("[ThemePalette] Dynamic image has over 65K pixels. Performance can be affected -- " + name);
            }
            var swapKeys       = this.swap.Keys.ToArray();
            var originalPixels = pixels.Copy();

            for (int index = 0; index < pixels.Length; ++index)
            {
                var pixel = pixels[index];
                if (isSplat)
                {
                    var emptyRed    = pixel.r == 0 || colorA.a == 0;
                    var emptyGreen  = pixel.g == 0 || colorB.a == 0;
                    var emptyBlue   = pixel.b == 0 || colorC.a == 0;
                    var colorAStart = emptyGreen && emptyBlue?colorA.SetAlpha(0) : Color.clear;

                    var colorBStart = emptyRed && emptyBlue?colorB.SetAlpha(0) : Color.clear;

                    var colorCStart = emptyRed && emptyGreen?colorC.SetAlpha(0) : Color.clear;

                    var splatA     = colorAStart.Lerp(colorA, pixel.r);
                    var splatB     = colorBStart.Lerp(colorB, pixel.g);
                    var splatC     = colorCStart.Lerp(colorC, pixel.b);
                    var pixelColor = splatA + splatB + splatC;
                    pixelColor.a *= pixel.a;
                    if (originalPixels[index] != pixelColor)
                    {
                        originalPixels[index] = pixelColor;
                        changes = true;
                    }
                    continue;
                }
                for (int swapIndex = 0; swapIndex < swapKeys.Length; ++swapIndex)
                {
                    var swapColor = swapKeys[swapIndex];
                    if (pixel.Matches(swapColor, false))
                    {
                        var color = this.swap[swapColor].value;
                        color.a = ignoreAlpha ? pixel.a : color.a * pixel.a;
                        if (originalPixels[index] != color)
                        {
                            originalPixels[index] = color;
                            changes = true;
                        }
                    }
                }
            }
            if (changes)
            {
                method = () => {
                    originalImage.SetPixels(originalPixels);
                    originalImage.Apply();
                };
                Worker.MainThread(method);
            }
        }
示例#13
0
        private static void Step()
        {
            if (BakeVertexData.complete)
            {
                return;
            }
            Renderer   renderer      = BakeVertexData.renderers[BakeVertexData.index];
            int        size          = BakeVertexData.renderers.Length;
            GameObject current       = renderer.gameObject;
            MeshFilter filter        = current.GetComponent <MeshFilter>();
            string     updateMessage = "Mesh " + BakeVertexData.index + "/" + size;
            bool       canceled      = EditorUI.DrawProgressBar("Baking Vertex Colors", updateMessage, ((float)BakeVertexData.index) / size);

            if (canceled)
            {
                size = 0;
            }
            else if (filter && filter.sharedMesh && renderer.sharedMaterial)
            {
                bool   generateMesh = true;
                string meshPath     = File.GetAssetPath(filter.sharedMesh);
                if (meshPath.Contains(".fbx", true))
                {
                    FileData   file         = File.Find(meshPath);
                    int        subMeshIndex = 0;
                    string     newPath      = file.path.GetAssetPath() + "Baked/" + file.name + "%%.asset";
                    int        vertexCount  = filter.sharedMesh.vertices.Length;
                    Color32[]  colorValues  = new Color32[vertexCount];
                    Material[] materials    = renderer.sharedMaterials;
                    bool       complex      = renderer.sharedMaterials.Length > 1;
                    foreach (Material material in materials)
                    {
                        bool    hasColor = material.HasProperty("_Color");
                        Color32 color    = hasColor ? material.GetColor("_Color") : Colors.Get("Violet");
                        //color.a = shaderName.Contains("Outline",true) ? 255 : 0;
                        string colorValue = color.ToString().Remove("RGBA(", " ", ",", ")");
                        string pathID     = complex ? "" : "-" + colorValue;
                        newPath = newPath.Replace("%%", pathID);
                        Mesh     existing       = File.GetAsset <Mesh>(newPath, false);
                        Material targetMaterial = BakeVertexData.baked;
                        string   shaderName     = material.shader.name;
                        if (shaderName.Contains("Lighted", true))
                        {
                            targetMaterial = BakeVertexData.bakedShaded;
                        }
                        if (shaderName.Contains("Outline", true))
                        {
                            targetMaterial = BakeVertexData.bakedOutline;
                        }
                        if (existing != null && !complex)
                        {
                            //Log.Show("[Bake Vertex Colors] Already exists -- " + newPath);
                            filter.sharedMesh       = existing;
                            materials[subMeshIndex] = targetMaterial;
                            generateMesh            = false;
                            subMeshIndex           += 1;
                            continue;
                        }
                        int[] indices = filter.sharedMesh.GetIndices(subMeshIndex);
                        foreach (int index in indices)
                        {
                            colorValues[index] = color;
                        }
                        materials[subMeshIndex] = targetMaterial;
                        subMeshIndex           += 1;
                    }
                    if (generateMesh)
                    {
                        var newMesh = (Mesh)UnityEngine.Object.Instantiate(filter.sharedMesh);
                        newMesh.colors32 = colorValues;
                        //Log.Show("[Bake Vertex Colors] Generating -- " + newPath);
                        File.Create(file.path.GetDirectory() + "/Baked");
                        ProxyEditor.CreateAsset(newMesh, newPath);
                        filter.sharedMesh = newMesh;
                    }
                    renderer.sharedMaterials = materials;
                }
            }
            BakeVertexData.index += 1;
            if (BakeVertexData.index >= size)
            {
                var    span      = TimeSpan.FromSeconds(Time.Get() - BakeVertexData.time);
                string totalTime = span.Minutes + " minutes and " + span.Seconds + " seconds";
                Log.Show("[Bake Vertex Colors] Baked data for " + size + " renderers.");
                Log.Show("[Bake Vertex Colors] Completed in " + totalTime + ".");
                ProxyEditor.SaveAssets();
                EditorUI.ClearProgressBar();
                EditorApplication.update -= BakeVertexData.Step;
                BakeVertexData.complete   = true;
            }
        }
示例#14
0
        //public void OnDestroy(){this.OnDisable();}
        //==================
        // Interface
        //==================
        public void OnGUI()
        {
            EditorUI.Reset();
            EditorUI.SetFieldSize(-1, 175, false);
            var width        = (Screen.width * 0.25f).Clamp(100, 250).ToInt();
            var mergeStyle   = EditorStyles.miniButtonLeft.FixedHeight(0);
            var flattenStyle = EditorStyles.miniButtonRight.FixedHeight(0);

            if (this.operationMode == OperationMode.Merge)
            {
                mergeStyle = mergeStyle.UseState("onNormal", "*");
            }
            if (this.operationMode == OperationMode.Flatten)
            {
                flattenStyle = flattenStyle.UseState("onNormal", "*");
            }
            EditorGUILayout.BeginVertical(new GUIStyle().Margin(8, 8, 15, 8));
            EditorGUILayout.BeginHorizontal(new GUIStyle().Margin(0, 0, 0, 10).Center(width * 2));
            if ("Merge".ToLabel().Layout(width, 20).DrawButton(mergeStyle))
            {
                this.operationMode = OperationMode.Merge;
            }
            if ("Flatten".ToLabel().Layout(width, 20).DrawButton(flattenStyle))
            {
                this.operationMode = OperationMode.Flatten;
            }
            EditorGUILayout.EndHorizontal();
            if (this.operationMode.Has("Merge"))
            {
                EditorWindowExtensions.SetTitle(this, "Mesh");
                //"Vertex".DrawLabel(EditorStyles.boldLabel);
                this.vertexMode          = this.vertexMode.Draw("Vertex Mode").As <VertexMode>();
                this.vertexDisplay       = this.vertexDisplay.DrawMask("Vertex Display").As <VertexDisplay>();
                this.vertexColor         = this.vertexColor.Draw("Vertex Color");
                this.vertexDistanceColor = this.vertexDistanceColor.Draw("Vertex Distance Color");
                this.vertexOverlapColor  = this.vertexOverlapColor.Draw("Vertex Overlap Color");
                this.distance            = this.distance.DrawSlider(0, 1f, "Vertex Overlap Distance");
                this.size          = this.size.DrawSlider(0, 1, "Vertex Size");
                this.scaleFactor   = this.scaleFactor.DrawSlider(1, 10, "Vertex Display Scale");
                this.scale         = (0.0625f * Mathf.Pow(2, this.scaleFactor - 1));
                this.alwaysDisplay = this.alwaysDisplay.Draw("Always Display");
                var lockText = this.lockSelection ? "Unlock Selection" : "Lock Selection";
                GUI.enabled = this.lockSelection || this.cached.Count > 0;
                if (lockText.ToLabel().Layout(150, 25).DrawButton() && (this.lockSelection || this.cached.Count > 0))
                {
                    this.lockSelection = !this.lockSelection;
                }
                GUI.enabled = true;
            }
            else if (this.operationMode.Has("Flatten"))
            {
            }
            if (EditorUI.anyChanged)
            {
                ProxyEditor.RegisterUndo(this, "Mesh Operation Changes");
                this.Repaint();
                this.RefreshSceneView();
            }
            EditorGUILayout.EndVertical();
            this.visible = true;
        }
示例#15
0
        private static void Step()
        {
            if (Class.complete)
            {
                return;
            }
            int        index         = Class.index;
            MeshFilter filter        = Class.filters[index];
            string     updateMessage = "Mesh " + index + "/" + Class.meshCount;
            bool       canceled      = EditorUI.DrawProgressBar("Combining Meshes", updateMessage, ((float)index) / Class.meshCount);

            if (canceled)
            {
                Class.meshCount = 0;
            }
            else if (filter != null && filter.sharedMesh != null)
            {
                if ((Class.vertexCount + filter.sharedMesh.vertexCount) >= 65534)
                {
                    Log.Show("[Combine Meshes] Added extra submesh due to vertices at " + Class.vertexCount);
                    Class.StepLast();
                    Class.meshes.Add(new Mesh());
                    Class.subIndex    = index;
                    Class.vertexCount = 0;
                }
                Mesh currentMesh = filter.sharedMesh;
                if (filter.sharedMesh.subMeshCount > 1)
                {
                    currentMesh           = (Mesh)UnityEngine.Object.Instantiate(filter.sharedMesh);
                    currentMesh.triangles = currentMesh.triangles;
                }
                Class.combines[index].mesh      = currentMesh;
                Class.combines[index].transform = filter.transform.localToWorldMatrix;
                Class.vertexCount += currentMesh.vertexCount;
                if (Class.inline)
                {
                    Component.DestroyImmediate(filter.gameObject.GetComponent <MeshRenderer>());
                    Component.DestroyImmediate(filter.gameObject.GetComponent <MeshFilter>());
                }
            }
            Class.index += 1;
            if (Class.index >= Class.meshCount)
            {
                if (!canceled)
                {
                    Class.StepLast();
                    //Material material = File.GetAsset<Material>("Baked.mat");
                    if (!Class.inline)
                    {
                        foreach (GameObject current in Class.selection)
                        {
                            GameObject target = (GameObject)GameObject.Instantiate(current);
                            target.name             = target.name.Replace("(Clone)", "");
                            target.transform.parent = Locate.GetScenePath("Scene-Combined").transform;
                            MeshFilter[] filters = target.GetComponentsInChildren <MeshFilter>();
                            foreach (MeshFilter nullFilter in filters)
                            {
                                Component.DestroyImmediate(nullFilter.gameObject.GetComponent <MeshRenderer>());
                                Component.DestroyImmediate(nullFilter.gameObject.GetComponent <MeshFilter>());
                            }
                            current.SetActive(false);
                        }
                    }
                    bool   singleRoot = Class.selection.Length == 1;
                    string start      = singleRoot ? Class.selection[0].name + "/" : "";
                    foreach (Mesh mesh in Class.meshes)
                    {
                        GameObject container = new GameObject("@Mesh" + Class.meshNumber);
                        if (Class.inline && singleRoot)
                        {
                            container.transform.parent = Class.selection[0].transform;
                        }
                        else
                        {
                            container.transform.parent = Locate.GetScenePath("Scene-Combined/" + start).transform;
                        }
                        //MeshRenderer containerRenderer = container.AddComponent<MeshRenderer>();
                        MeshFilter containerFilter = container.AddComponent <MeshFilter>();
                        if (Class.path.IsEmpty())
                        {
                            Class.path = EditorUtility.SaveFolderPanel("Combine Meshes", Application.dataPath, "").GetAssetPath();
                        }
                        File.Create(path);
                        ProxyEditor.CreateAsset(mesh, path + "/Combined" + meshNumber + ".asset");
                        containerFilter.mesh = mesh;
                        //containerRenderer.material = new Material(material);
                        Class.meshNumber += 1;
                    }
                }
                TimeSpan span      = TimeSpan.FromSeconds(Time.Get() - Class.time);
                string   totalTime = span.Minutes + " minutes and " + span.Seconds + " seconds";
                Log.Show("[Combine Meshes] Reduced " + Class.meshCount + " meshes to " + Class.meshes.Count + ".");
                Log.Show("[Combine Meshes] Completed in " + totalTime + ".");
                ProxyEditor.SaveAssets();
                EditorUI.ClearProgressBar();
                Class.complete = true;
                while (EditorApplication.update == Class.Step)
                {
                    EditorApplication.update -= Class.Step;
                }
            }
        }
示例#16
0
        public static void Step(object collection, int itemIndex)
        {
            var  materials = (FileData[])collection;
            var  file      = materials[itemIndex];
            bool last      = itemIndex == materials.Length - 1;

            Stepper.title   = "Updating " + materials.Length + " Materials";
            Stepper.message = "Updating material : " + file.name;
            string text           = file.ReadText();
            string copy           = text;
            int    index          = 0;
            bool   changed        = false;
            bool   removePrevious = false;
            string guid           = text.Parse("guid: ", ",");
            string shaderPath     = ProxyEditor.GetAssetPath(guid);

            if (!shaderPath.IsEmpty())
            {
                Material material = file.GetAsset <Material>();
                Shader   shader   = File.GetAsset <Shader>(shaderPath, false);
                if (shader != null)
                {
                    int propertyCount = ProxyEditor.GetPropertyCount(shader);
                    Dictionary <string, string> properties = new Dictionary <string, string>();
                    for (int propertyIndex = 0; propertyIndex < propertyCount; ++propertyIndex)
                    {
                        string name = ProxyEditor.GetPropertyName(shader, propertyIndex);
                        properties[name] = ProxyEditor.GetPropertyType(shader, propertyIndex).ToName();
                    }
                    string keywords = text.Parse("m_ShaderKeywords:", "m_").Trim("[]");
                    if (!keywords.IsEmpty())
                    {
                        string keywordsCleaned = keywords;
                        foreach (string keyword in keywords.Replace("\n   ", "").Split(" "))
                        {
                            if (!properties.ContainsKey(keyword.Split("_")[0], true))
                            {
                                keywordsCleaned = keywordsCleaned.Replace(" " + keyword, "");
                                changed         = true;
                            }
                        }
                        copy = copy.Replace(keywords, keywordsCleaned);
                    }
                    while (true)
                    {
                        int nextIndex = text.IndexOf("data:", index + 5);
                        if (removePrevious)
                        {
                            int    nextGroup = text.IndexOf("\n    m", index);
                            int    count     = nextGroup != -1 && nextGroup < nextIndex ? nextGroup - index : nextIndex - index;
                            string section   = nextIndex < 0 ? text.Substring(index) : text.Substring(index, count);
                            copy           = copy.Replace(section, "");
                            removePrevious = false;
                            changed        = true;
                        }
                        if (nextIndex == -1)
                        {
                            break;
                        }
                        index = nextIndex;
                        int    keywordStart = text.IndexOf("name: ", index) + 6;
                        int    keywordEnd   = text.IndexOf("\n", keywordStart);
                        string name         = text.Substring(keywordStart, keywordEnd - keywordStart);
                        if (name.IsEmpty())
                        {
                            continue;
                        }
                        bool emptyTexture = properties.ContainsKey(name) && properties[name] == "Texture" && material.GetTexture(name) == null;
                        removePrevious = !properties.ContainsKey(name) || emptyTexture;
                        //if(removePrevious){Log.Show("[MaterialCleaner] : Removing " + name + " from " + file.fullName);}
                    }
                    if (changed)
                    {
                        MaterialCleaner.changes = true;
                        Log.Show("[MaterialCleaner] : Cleaned unused serialized data " + file.fullName);
                        file.Write(copy);
                    }
                }
            }
            if (last)
            {
                if (!MaterialCleaner.changes)
                {
                    Log.Show("[MaterialCleaner] : All files already clean.");
                }
                else
                {
                    Log.Show("[MaterialCleaner] : Cleaned all materials.");
                }
                Call.Delay(() => ProxyEditor.RefreshAssets(), 1);
            }
        }
示例#17
0
        public void Call(bool debugDeep, bool debugTime, object[] values)
        {
            if (ProxyEditor.IsPaused() || this.paused || !this.IsValid())
            {
                return;
            }
            if (this.IsResting())
            {
                if (!this.delayed)
                {
                    float remaining = this.resting - Time.Get();
                    UnityCall.Delay(this.method, () => this.Call(debugDeep, debugTime, values), remaining);
                    this.delayed = true;
                }
                return;
            }
            this.delayed = false;
            Events.stack.Add(this);
            Events.AddHistory(this.name);
            float duration = Time.Get();

            if (this.cooldown > 0)
            {
                this.Rest(this.cooldown);
            }
            if (this.occurrences > 0)
            {
                this.occurrences -= 1;
            }
            if (this.occurrences == 0)
            {
                this.Remove();
            }
            if (values.Length < 1 || this.method is Method)
            {
                ((Method)this.method)();
            }
            else
            {
                object value = values[0];
                if (this.method is MethodObjects)
                {
                    ((MethodObjects)this.method)(values);
                }
                else if (value is object && this.method is MethodObject)
                {
                    ((MethodObject)this.method)((object)value);
                }
                else if (value is int && this.method is MethodInt)
                {
                    ((MethodInt)this.method)((int)value);
                }
                else if (value is float && this.method is MethodFloat)
                {
                    ((MethodFloat)this.method)((float)value);
                }
                else if (value is string && this.method is MethodString)
                {
                    ((MethodString)this.method)((string)value);
                }
                else if (value is bool && this.method is MethodBool)
                {
                    ((MethodBool)this.method)((bool)value);
                }
                else if (value is Vector2 && this.method is MethodVector2)
                {
                    ((MethodVector2)this.method)((Vector2)value);
                }
                else if (value is Vector3 && this.method is MethodVector3)
                {
                    ((MethodVector3)this.method)((Vector3)value);
                }
            }
            if (debugDeep)
            {
                string message = "[Events] : " + name + " -- " + Events.GetMethodName(this.method);
                if (debugTime)
                {
                    duration = Time.Get() - duration;
                    if (duration > 0.001f || Events.debug.Has("CallTimerZero"))
                    {
                        string time = duration.ToString("F10").TrimRight("0", ".").Trim() + " seconds.";
                        message = message + " -- " + time;
                    }
                }
                Log.Show(message);
            }
            Events.stack.Remove(this);
        }