public override void OnGUI(Rect position, SerializedProperty prop, GUIContent content)
        {
            var att = (ShaderPropertyPopupAttribute)attribute;

            var directable = prop.serializedObject.targetObject as IDirectable;

            if (directable != null)
            {
                var actor = directable.actor;
                if (actor != null)
                {
                    var renderer = actor.GetComponent <Renderer>();
                    if (renderer != null)
                    {
                        var material = renderer.sharedMaterial;
                        if (material != null)
                        {
                            var shader  = material.shader;
                            var options = new List <string>();
                            for (var i = 0; i < ShaderUtil.GetPropertyCount(shader); i++)
                            {
                                if (ShaderUtil.IsShaderPropertyHidden(shader, i))
                                {
                                    continue;
                                }

                                if (att.propertyType != null)
                                {
                                    var type = ShaderUtil.GetPropertyType(shader, i);
                                    if (att.propertyType == typeof(Color) && type != ShaderUtil.ShaderPropertyType.Color)
                                    {
                                        continue;
                                    }
                                    if (att.propertyType == typeof(Texture) && type != ShaderUtil.ShaderPropertyType.TexEnv)
                                    {
                                        continue;
                                    }
                                    if (att.propertyType == typeof(float) && type != ShaderUtil.ShaderPropertyType.Float && type != ShaderUtil.ShaderPropertyType.Range)
                                    {
                                        continue;
                                    }
                                    if ((att.propertyType == typeof(Vector2) || att.propertyType == typeof(Vector4)) && type != ShaderUtil.ShaderPropertyType.Vector)
                                    {
                                        continue;
                                    }
                                }

                                options.Add(ShaderUtil.GetPropertyName(shader, i));
                            }

                            prop.stringValue = EditorTools.CleanPopup <string>(content.text, prop.stringValue, options);
                            return;
                        }
                    }
                }
            }

            prop.stringValue = EditorGUILayout.TextField(content.text, prop.stringValue);
        }
Example #2
0
        private static MaterialPropertyHandler GetShaderPropertyHandler(Shader shader, string name)
        {
            string[] attribs = ShaderUtil.GetShaderPropertyAttributes(shader, name);
            if (attribs == null || attribs.Length == 0)
            {
                return(null);
            }

            var handler = new MaterialPropertyHandler();

            foreach (var attr in attribs)
            {
                bool isDecorator;
                MaterialPropertyDrawer drawer = GetShaderPropertyDrawer(attr, out isDecorator);
                if (drawer != null)
                {
                    if (isDecorator)
                    {
                        if (handler.m_DecoratorDrawers == null)
                        {
                            handler.m_DecoratorDrawers = new List <MaterialPropertyDrawer>();
                        }
                        handler.m_DecoratorDrawers.Add(drawer);
                    }
                    else
                    {
                        if (handler.m_PropertyDrawer != null)
                        {
                            Debug.LogWarning(string.Format("Shader property {0} already has a property drawer", name), shader);
                        }
                        handler.m_PropertyDrawer = drawer;
                    }
                }
            }

            return(handler);
        }
Example #3
0
        private static int GetMaterialPropertyPopupHash(UnityEngine.Object[] objects)
        {
            int num = 0;

            for (int i = 0; i < objects.Length; i++)
            {
                VideoPlayer videoPlayer = (VideoPlayer)objects[i];
                if (videoPlayer)
                {
                    Renderer targetRenderer = VideoPlayerEditor.GetTargetRenderer(videoPlayer);
                    if (targetRenderer)
                    {
                        num ^= videoPlayer.targetMaterialProperty.GetHashCode();
                        Material[] sharedMaterials = targetRenderer.sharedMaterials;
                        for (int j = 0; j < sharedMaterials.Length; j++)
                        {
                            Material material = sharedMaterials[j];
                            if (material)
                            {
                                num ^= material.name.GetHashCode();
                                int k             = 0;
                                int propertyCount = ShaderUtil.GetPropertyCount(material.shader);
                                while (k < propertyCount)
                                {
                                    if (ShaderUtil.GetPropertyType(material.shader, k) == ShaderUtil.ShaderPropertyType.TexEnv)
                                    {
                                        num ^= ShaderUtil.GetPropertyName(material.shader, k).GetHashCode();
                                    }
                                    k++;
                                }
                            }
                        }
                    }
                }
            }
            return(num);
        }
        private static MaterialPropertyHandler GetShaderPropertyHandler(Shader shader, string name)
        {
            string[] shaderPropertyAttributes = ShaderUtil.GetShaderPropertyAttributes(shader, name);
            if (shaderPropertyAttributes == null || shaderPropertyAttributes.Length == 0)
            {
                return(null);
            }
            MaterialPropertyHandler materialPropertyHandler = new MaterialPropertyHandler();

            string[] array = shaderPropertyAttributes;
            for (int i = 0; i < array.Length; i++)
            {
                string attrib = array[i];
                bool   flag;
                MaterialPropertyDrawer shaderPropertyDrawer = MaterialPropertyHandler.GetShaderPropertyDrawer(attrib, out flag);
                if (shaderPropertyDrawer != null)
                {
                    if (flag)
                    {
                        if (materialPropertyHandler.m_DecoratorDrawers == null)
                        {
                            materialPropertyHandler.m_DecoratorDrawers = new List <MaterialPropertyDrawer>();
                        }
                        materialPropertyHandler.m_DecoratorDrawers.Add(shaderPropertyDrawer);
                    }
                    else
                    {
                        if (materialPropertyHandler.m_PropertyDrawer != null)
                        {
                            Debug.LogWarning(string.Format("Shader property {0} already has a property drawer", name), shader);
                        }
                        materialPropertyHandler.m_PropertyDrawer = shaderPropertyDrawer;
                    }
                }
            }
            return(materialPropertyHandler);
        }
Example #5
0
 private void ShaderPreloadGUI()
 {
     EditorGUILayout.Space();
     GUILayout.Label(GraphicsSettingsInspector.Styles.shaderPreloadSettings, EditorStyles.boldLabel, new GUILayoutOption[0]);
     EditorGUILayout.PropertyField(this.m_PreloadedShaders, true, new GUILayoutOption[0]);
     EditorGUILayout.Space();
     GUILayout.Label(string.Format("Currently tracked: {0} shaders {1} total variants", (object)ShaderUtil.GetCurrentShaderVariantCollectionShaderCount(), (object)ShaderUtil.GetCurrentShaderVariantCollectionVariantCount()));
     EditorGUILayout.BeginHorizontal();
     GUILayout.FlexibleSpace();
     if (GUILayout.Button(GraphicsSettingsInspector.Styles.shaderPreloadSave, EditorStyles.miniButton, new GUILayoutOption[0]))
     {
         string path = EditorUtility.SaveFilePanelInProject("Save Shader Variant Collection", "NewShaderVariants", "shadervariants", "Save shader variant collection", ProjectWindowUtil.GetActiveFolderPath());
         if (!string.IsNullOrEmpty(path))
         {
             ShaderUtil.SaveCurrentShaderVariantCollection(path);
         }
         GUIUtility.ExitGUI();
     }
     if (GUILayout.Button(GraphicsSettingsInspector.Styles.shaderPreloadClear, EditorStyles.miniButton, new GUILayoutOption[0]))
     {
         ShaderUtil.ClearCurrentShaderVariantCollection();
     }
     EditorGUILayout.EndHorizontal();
 }
        public override void OnInspectorGUI()
        {
            base.serializedObject.Update();
            bool flag  = false;
            bool flag2 = false;

            GUILayout.Label(GraphicsSettingsInspector.Styles.builtinSettings, EditorStyles.boldLabel, new GUILayoutOption[0]);
            this.m_Deferred.DoGUI();
            EditorGUI.BeginChangeCheck();
            this.m_DeferredReflections.DoGUI();
            if (EditorGUI.EndChangeCheck())
            {
                ShaderUtil.ReloadAllShaders();
            }
            this.m_ScreenSpaceShadows.DoGUI();
            this.m_LegacyDeferred.DoGUI();
            this.m_DepthNormals.DoGUI();
            this.m_MotionVectors.DoGUI();
            this.m_LightHalo.DoGUI();
            this.m_LensFlare.DoGUI();
            EditorGUILayout.PropertyField(this.m_AlwaysIncludedShaders, true, new GUILayoutOption[0]);
            EditorGUILayout.Space();
            GUILayout.Label(GraphicsSettingsInspector.Styles.shaderStrippingSettings, EditorStyles.boldLabel, new GUILayoutOption[0]);
            this.LightmapStrippingGUI(out flag);
            this.FogStrippingGUI(out flag2);
            this.ShaderPreloadGUI();
            base.serializedObject.ApplyModifiedProperties();
            if (flag)
            {
                ShaderUtil.CalculateLightmapStrippingFromCurrentScene();
            }
            if (flag2)
            {
                ShaderUtil.CalculateFogStrippingFromCurrentScene();
            }
        }
        public override void OnInspectorGUI()
        {
            serializedObject.Update();

            // Evaluate displayMaterialWarning before drawing properties to avoid mismatched layout group
            bool displayMaterialWarning = false;

            if (!m_Materials.hasMultipleDifferentValues)
            {
                MeshFilter mf = ((MeshRenderer)serializedObject.targetObject).GetComponent <MeshFilter>();
                displayMaterialWarning = mf != null && mf.sharedMesh != null && m_Materials.arraySize > mf.sharedMesh.subMeshCount;
            }

            DrawMaterials();

            if (!m_Materials.hasMultipleDifferentValues && displayMaterialWarning)
            {
                EditorGUILayout.HelpBox(Styles.materialWarning.text, MessageType.Warning, true);
            }

            if (ShaderUtil.MaterialsUseInstancingShader(m_Materials))
            {
                m_GameObjectsSerializedObject.Update();

                if (!m_GameObjectStaticFlags.hasMultipleDifferentValues && ((StaticEditorFlags)m_GameObjectStaticFlags.intValue & StaticEditorFlags.BatchingStatic) != 0)
                {
                    EditorGUILayout.HelpBox(Styles.staticBatchingWarning.text, MessageType.Warning, true);
                }
            }

            LightingSettingsGUI(true);
            RayTracingSettingsGUI();
            OtherSettingsGUI(true, false, false);

            serializedObject.ApplyModifiedProperties();
        }
 private void DisplayAddVariantsWindow(Shader shader, ShaderVariantCollection collection)
 {
     string[] strArray;
     AddShaderVariantWindow.PopupData data = new AddShaderVariantWindow.PopupData {
         shader     = shader,
         collection = collection
     };
     ShaderUtil.GetShaderVariantEntries(shader, collection, out data.types, out strArray);
     if (strArray.Length == 0)
     {
         EditorApplication.Beep();
     }
     else
     {
         data.keywords = new string[strArray.Length][];
         for (int i = 0; i < strArray.Length; i++)
         {
             char[] separator = new char[] { ' ' };
             data.keywords[i] = strArray[i].Split(separator);
         }
         AddShaderVariantWindow.ShowAddVariantWindow(data);
         GUIUtility.ExitGUI();
     }
 }
        private static List <ComputeShaderInspector.KernelInfo> GetKernelDisplayInfo(ComputeShader cs)
        {
            List <ComputeShaderInspector.KernelInfo> list = new List <ComputeShaderInspector.KernelInfo>();
            int computeShaderPlatformCount = ShaderUtil.GetComputeShaderPlatformCount(cs);

            for (int i = 0; i < computeShaderPlatformCount; i++)
            {
                GraphicsDeviceType computeShaderPlatformType = ShaderUtil.GetComputeShaderPlatformType(cs, i);
                int computeShaderPlatformKernelCount         = ShaderUtil.GetComputeShaderPlatformKernelCount(cs, i);
                for (int j = 0; j < computeShaderPlatformKernelCount; j++)
                {
                    string computeShaderPlatformKernelName = ShaderUtil.GetComputeShaderPlatformKernelName(cs, i, j);
                    bool   flag = false;
                    foreach (ComputeShaderInspector.KernelInfo current in list)
                    {
                        if (current.name == computeShaderPlatformKernelName)
                        {
                            ComputeShaderInspector.KernelInfo expr_6C = current;
                            expr_6C.platforms += ' ';
                            ComputeShaderInspector.KernelInfo expr_85 = current;
                            expr_85.platforms += computeShaderPlatformType.ToString();
                            flag = true;
                        }
                    }
                    if (!flag)
                    {
                        list.Add(new ComputeShaderInspector.KernelInfo
                        {
                            name      = computeShaderPlatformKernelName,
                            platforms = computeShaderPlatformType.ToString()
                        });
                    }
                }
            }
            return(list);
        }
Example #10
0
            public override void OnInspectorGUI()
            {
                serializedObject.Update();

                m_Deferred.DoGUI();

                // deferred reflections being off affects forward vs deferred style probe rendering;
                // need to reload shaders for new platform macro to live update
                EditorGUI.BeginChangeCheck();
                m_DeferredReflections.DoGUI();
                if (EditorGUI.EndChangeCheck())
                {
                    ShaderUtil.ReloadAllShaders();
                }

                m_LegacyDeferred.DoGUI();
                m_ScreenSpaceShadows.DoGUI();
                m_DepthNormals.DoGUI();
                m_MotionVectors.DoGUI();
                m_LightHalo.DoGUI();
                m_LensFlare.DoGUI();

                serializedObject.ApplyModifiedProperties();
            }
Example #11
0
        internal static bool MaterialsUseInstancingShader(SerializedProperty materialsArray)
        {
            bool result;

            if (materialsArray.hasMultipleDifferentValues)
            {
                result = false;
            }
            else
            {
                for (int i = 0; i < materialsArray.arraySize; i++)
                {
                    Material material = materialsArray.GetArrayElementAtIndex(i).objectReferenceValue as Material;
                    if (material != null && material.enableInstancing && material.shader != null && ShaderUtil.HasInstancing(material.shader))
                    {
                        result = true;
                        return(result);
                    }
                }
                result = false;
            }
            return(result);
        }
 public void ReadFromMaterialPropertyBlock(MaterialPropertyBlock block)
 {
     ShaderUtil.ApplyMaterialPropertyBlockToMaterialProperty(block, this);
 }
 public void WriteToMaterialPropertyBlock(MaterialPropertyBlock materialblock, int changedPropertyMask)
 {
     ShaderUtil.ApplyMaterialPropertyToMaterialPropertyBlock(this, changedPropertyMask, materialblock);
 }
Example #14
0
        public static Texture2D Render(GameObject prefab)
        {
            if (prefab == null)
            {
                return(null);
            }
            if (prefab.GetComponent <Renderer>() == null)
            {
                return(null);
            }
            Texture2D textured2 = new Texture2D(0x40, 0x40)
            {
                hideFlags = HideFlags.HideAndDontSave,
                name      = "Preview Texture"
            };
            RenderTexture temporary = RenderTexture.GetTemporary(textured2.width, textured2.height);
            GameObject    obj2      = new GameObject("Preview")
            {
                hideFlags = HideFlags.HideAndDontSave
            };
            Camera camera = obj2.AddComponent(typeof(Camera)) as Camera;

            camera.cameraType      = CameraType.Preview;
            camera.clearFlags      = CameraClearFlags.Color;
            camera.backgroundColor = new Color(0.5f, 0.5f, 0.5f, 0f);
            camera.cullingMask     = 0;
            camera.enabled         = false;
            camera.targetTexture   = temporary;
            Light light = obj2.AddComponent(typeof(Light)) as Light;

            light.type = LightType.Directional;
            Bounds  bounds = CalculateVisibleBounds(prefab);
            Vector3 vector = new Vector3(0.7f, 0.3f, 0.7f);
            float   num    = bounds.extents.magnitude * 1.6f;

            obj2.transform.position = bounds.center + ((Vector3)(vector.normalized * num));
            obj2.transform.LookAt(bounds.center);
            camera.nearClipPlane = num * 0.1f;
            camera.farClipPlane  = num * 2.2f;
            Camera current = Camera.current;

            camera.RenderDontRestore();
            Light[] lights = new Light[] { light };
            Graphics.SetupVertexLights(lights);
            Component[] componentsInChildren = prefab.GetComponentsInChildren(typeof(Renderer));
            foreach (Renderer renderer in componentsInChildren)
            {
                if (renderer.enabled)
                {
                    Material[] sharedMaterials = renderer.sharedMaterials;
                    for (int i = 0; i < sharedMaterials.Length; i++)
                    {
                        if (sharedMaterials[i] != null)
                        {
                            Material original   = sharedMaterials[i];
                            string   dependency = ShaderUtil.GetDependency(original.shader, "BillboardShader");
                            if ((dependency != null) && (dependency != ""))
                            {
                                original           = UnityEngine.Object.Instantiate <Material>(original);
                                original.shader    = Shader.Find(dependency);
                                original.hideFlags = HideFlags.HideAndDontSave;
                            }
                            for (int j = 0; j < original.passCount; j++)
                            {
                                if (original.SetPass(j))
                                {
                                    renderer.RenderNow(i);
                                }
                            }
                            if (original != sharedMaterials[i])
                            {
                                UnityEngine.Object.DestroyImmediate(original);
                            }
                        }
                    }
                }
            }
            textured2.ReadPixels(new Rect(0f, 0f, (float)textured2.width, (float)textured2.height), 0, 0);
            RenderTexture.ReleaseTemporary(temporary);
            UnityEngine.Object.DestroyImmediate(obj2);
            Camera.SetupCurrent(current);
            return(textured2);
        }
Example #15
0
            public override void OnInspectorGUI()
            {
                serializedObject.Update();

                serializedObject.ApplyModifiedProperties();

                EditorGUILayout.PropertyField(m_PreloadedShaders, true);

                EditorGUILayout.Space();
                GUILayout.Label(
                    string.Format("Currently tracked: {0} shaders {1} total variants",
                                  ShaderUtil.GetCurrentShaderVariantCollectionShaderCount(), ShaderUtil.GetCurrentShaderVariantCollectionVariantCount()
                                  )
                    );

                EditorGUILayout.BeginHorizontal();
                GUILayout.FlexibleSpace();
                if (GUILayout.Button(Styles.shaderPreloadSave, EditorStyles.miniButton))
                {
                    string message   = "Save shader variant collection";
                    string assetPath = EditorUtility.SaveFilePanelInProject("Save Shader Variant Collection", "NewShaderVariants", "shadervariants", message, ProjectWindowUtil.GetActiveFolderPath());
                    if (!string.IsNullOrEmpty(assetPath))
                    {
                        ShaderUtil.SaveCurrentShaderVariantCollection(assetPath);
                    }
                    GUIUtility.ExitGUI();
                }
                if (GUILayout.Button(Styles.shaderPreloadClear, EditorStyles.miniButton))
                {
                    ShaderUtil.ClearCurrentShaderVariantCollection();
                }
                EditorGUILayout.EndHorizontal();

                serializedObject.ApplyModifiedProperties();
            }
Example #16
0
        public virtual void OnEnable()
        {
            Shader target = this.target as Shader;

            ShaderUtil.FetchCachedErrors(target);
        }
Example #17
0
        // Compiled shader code button+dropdown
        private void ShowCompiledCodeButton(Shader s)
        {
            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.PrefixLabel("Compiled code", EditorStyles.miniButton);

            var hasCode = ShaderUtil.HasShaderSnippets(s) || ShaderUtil.HasSurfaceShaders(s) || ShaderUtil.HasFixedFunctionShaders(s);

            if (hasCode)
            {
                // button with a drop-down part on the right
                var modeContent  = Styles.showCurrent;
                var modeRect     = GUILayoutUtility.GetRect(modeContent, EditorStyles.miniButton, GUILayout.ExpandWidth(false));
                var modeDropRect = new Rect(modeRect.xMax - 16, modeRect.y, 16, modeRect.height);
                if (EditorGUI.DropdownButton(modeDropRect, GUIContent.none, FocusType.Passive, GUIStyle.none))
                {
                    Rect rect = GUILayoutUtility.topLevel.GetLast();
                    PopupWindow.Show(rect, new ShaderInspectorPlatformsPopup(s));
                    GUIUtility.ExitGUI();
                }
                if (GUI.Button(modeRect, modeContent, EditorStyles.miniButton))
                {
                    ShaderUtil.OpenCompiledShader(s, ShaderInspectorPlatformsPopup.currentMode, ShaderInspectorPlatformsPopup.currentPlatformMask, ShaderInspectorPlatformsPopup.currentVariantStripping == 0);
                    GUIUtility.ExitGUI();
                }
            }
            else
            {
                // Note: PrefixLabel is sometimes buggy if followed by a non-control (like Label).
                // We just want to show a label here, but have to pretend it's a button so it is treated like
                // a control.
                GUILayout.Button("none (precompiled shader)", GUI.skin.label);
            }

            EditorGUILayout.EndHorizontal();
        }
Example #18
0
        public override void OnInspectorGUI()
        {
            var s = target as Shader;

            if (s == null)
            {
                return;
            }

            GUI.enabled = true;

            EditorGUI.indentLevel = 0;

            ShowShaderCodeArea(s);

            if (s.isSupported)
            {
                EditorGUILayout.LabelField("Cast shadows", (ShaderUtil.HasShadowCasterPass(s)) ? "yes" : "no");
                EditorGUILayout.LabelField("Render queue", ShaderUtil.GetRenderQueue(s).ToString(CultureInfo.InvariantCulture));
                EditorGUILayout.LabelField("LOD", ShaderUtil.GetLOD(s).ToString(CultureInfo.InvariantCulture));
                EditorGUILayout.LabelField("Ignore projector", ShaderUtil.DoesIgnoreProjector(s) ? "yes" : "no");
                string disableBatchingString;
                switch (s.disableBatching)
                {
                case DisableBatchingType.False:
                    disableBatchingString = "no";
                    break;

                case DisableBatchingType.True:
                    disableBatchingString = "yes";
                    break;

                case DisableBatchingType.WhenLODFading:
                    disableBatchingString = "when LOD fading is on";
                    break;

                default:
                    disableBatchingString = "unknown";
                    break;
                }
                EditorGUILayout.LabelField("Disable batching", disableBatchingString);
                ShowKeywords(s);

                // If any SRP is active, then display the SRP Batcher compatibility status
                if (RenderPipelineManager.currentPipeline != null)
                {
                    // NOTE: Force the shader compilation to ensure GetSRPBatcherCompatibilityCode will be up to date
                    srpCompatibilityCheckMaterial.SetPass(0);
                    int    subShader  = ShaderUtil.GetShaderActiveSubshaderIndex(s);
                    int    SRPErrCode = ShaderUtil.GetSRPBatcherCompatibilityCode(s, subShader);
                    string result     = (0 == SRPErrCode) ? "compatible" : "not compatible";
                    EditorGUILayout.LabelField("SRP Batcher", result);
                    if (SRPErrCode != 0)
                    {
                        EditorGUILayout.HelpBox(ShaderUtil.GetSRPBatcherCompatibilityIssueReason(s, subShader, SRPErrCode), MessageType.Info);
                    }
                }

                ShowShaderProperties(s);
            }
        }
Example #19
0
 private static void TextureProperty(string propertyName, string label, ShaderUtil.ShaderPropertyTexDim desiredTexdim)
 {
     GUILayout.BeginHorizontal();
     GUILayout.Label(label + " |TP " + propertyName, GUILayout.Width(_LABEL_WIDTH));
     GUILayout.Space(3);
     switch (propertyName)
     {
         case "_MainTex":
             KP.Mtexture_a = ((Texture2D)EditorGUILayout.ObjectField(KP.Mtexture_a, typeof(Texture2D), true));
             KP._sMaterial.SetTexture(propertyName, KP.Mtexture_a);
             break;
         case "_BumpMap":
         case "_DecalTex":
         case "_Detail":
         case "_Illum":
             KP.Mtexture_b = ((Texture2D)EditorGUILayout.ObjectField(KP.Mtexture_b, typeof(Texture2D), true));
             KP._sMaterial.SetTexture(propertyName, KP.Mtexture_b);
             break;
         case "_ParallaxMap":
             KP.Mtexture_c = ((Texture2D)EditorGUILayout.ObjectField(KP.Mtexture_c, typeof(Texture2D), true));
             KP._sMaterial.SetTexture(propertyName, KP.Mtexture_c);
             break;
     }
     GUILayout.EndHorizontal();
 }
        public static Texture2D Render(GameObject prefab)
        {
            if (prefab == null)
            {
                return(null);
            }
            if (prefab.GetComponent <Renderer>() == null)
            {
                return(null);
            }
            EditorUtility.SetTemporarilyAllowIndieRenderTexture(true);
            Texture2D texture2D = new Texture2D(64, 64);

            texture2D.hideFlags = HideFlags.HideAndDontSave;
            texture2D.name      = "Preview Texture";
            RenderTexture temporary  = RenderTexture.GetTemporary(texture2D.width, texture2D.height);
            GameObject    gameObject = new GameObject("Preview");

            gameObject.hideFlags = HideFlags.HideAndDontSave;
            Camera camera = gameObject.AddComponent(typeof(Camera)) as Camera;

            camera.clearFlags      = CameraClearFlags.Color;
            camera.backgroundColor = new Color(0.5f, 0.5f, 0.5f, 0f);
            camera.cullingMask     = 0;
            camera.enabled         = false;
            camera.targetTexture   = temporary;
            Light light = gameObject.AddComponent(typeof(Light)) as Light;

            light.type = LightType.Directional;
            Bounds  bounds = RenderThumbnailUtility.CalculateVisibleBounds(prefab);
            Vector3 vector = new Vector3(0.7f, 0.3f, 0.7f);
            float   num    = bounds.extents.magnitude * 1.6f;

            gameObject.transform.position = bounds.center + vector.normalized * num;
            gameObject.transform.LookAt(bounds.center);
            camera.nearClipPlane = num * 0.1f;
            camera.farClipPlane  = num * 2.2f;
            Camera current = Camera.current;

            camera.RenderDontRestore();
            Light[] lights = new Light[]
            {
                light
            };
            Graphics.SetupVertexLights(lights);
            Component[] componentsInChildren = prefab.GetComponentsInChildren(typeof(Renderer));
            Component[] array = componentsInChildren;
            for (int i = 0; i < array.Length; i++)
            {
                Renderer renderer = (Renderer)array[i];
                if (renderer.enabled)
                {
                    Material[] sharedMaterials = renderer.sharedMaterials;
                    for (int j = 0; j < sharedMaterials.Length; j++)
                    {
                        if (!(sharedMaterials[j] == null))
                        {
                            Material material   = sharedMaterials[j];
                            string   dependency = ShaderUtil.GetDependency(material.shader, "BillboardShader");
                            if (dependency != null && dependency != string.Empty)
                            {
                                material           = UnityEngine.Object.Instantiate <Material>(material);
                                material.shader    = Shader.Find(dependency);
                                material.hideFlags = HideFlags.HideAndDontSave;
                            }
                            for (int k = 0; k < material.passCount; k++)
                            {
                                if (material.SetPass(k))
                                {
                                    renderer.RenderNow(j);
                                }
                            }
                            if (material != sharedMaterials[j])
                            {
                                UnityEngine.Object.DestroyImmediate(material);
                            }
                        }
                    }
                }
            }
            texture2D.ReadPixels(new Rect(0f, 0f, (float)texture2D.width, (float)texture2D.height), 0, 0);
            RenderTexture.ReleaseTemporary(temporary);
            UnityEngine.Object.DestroyImmediate(gameObject);
            Camera.SetupCurrent(current);
            EditorUtility.SetTemporarilyAllowIndieRenderTexture(false);
            return(texture2D);
        }
		public Texture TextureProperty(string propertyName, string label, ShaderUtil.ShaderPropertyTexDim texDim)
		{
			MaterialProperty materialProperty = MaterialEditor.GetMaterialProperty(base.targets, propertyName);
			return this.TextureProperty(materialProperty, label);
		}
 public Texture TextureProperty(string propertyName, string label, ShaderUtil.ShaderPropertyTexDim texDim, bool scaleOffset)
 {
   return this.TextureProperty(MaterialEditor.GetMaterialProperty(this.targets, propertyName), label, scaleOffset);
 }
        private bool IsMaterialUsingFixedFunction()
        {
            Material sharedMaterial = (this.target as SpriteRenderer).sharedMaterial;

            return(!(sharedMaterial == null) && ShaderUtil.DoesShaderContainFixedFunctionPasses(sharedMaterial.shader));
        }
Example #24
0
        public virtual void OnEnable()
        {
            Shader s = base.target as Shader;

            ShaderUtil.FetchCachedErrors(s);
        }
Example #25
0
 internal static MaterialProperty GetMaterialProperty(UnityEngine.Object[] mats, int propertyIndex)
 {
     return(ShaderUtil.GetMaterialProperty_Index(mats, propertyIndex));
 }
Example #26
0
            public override void OnInspectorGUI()
            {
                base.serializedObject.Update();
                bool flag  = false;
                bool flag2 = false;

                EditorGUILayout.PropertyField(this.m_LightmapStripping, GraphicsSettingsWindow.ShaderStrippingEditor.Styles.lightmapModes, new GUILayoutOption[0]);
                if (this.m_LightmapStripping.intValue != 0)
                {
                    EditorGUI.indentLevel++;
                    EditorGUILayout.PropertyField(this.m_LightmapKeepPlain, GraphicsSettingsWindow.ShaderStrippingEditor.Styles.lightmapPlain, new GUILayoutOption[0]);
                    EditorGUILayout.PropertyField(this.m_LightmapKeepDirCombined, GraphicsSettingsWindow.ShaderStrippingEditor.Styles.lightmapDirCombined, new GUILayoutOption[0]);
                    EditorGUILayout.PropertyField(this.m_LightmapKeepDynamicPlain, GraphicsSettingsWindow.ShaderStrippingEditor.Styles.lightmapDynamicPlain, new GUILayoutOption[0]);
                    EditorGUILayout.PropertyField(this.m_LightmapKeepDynamicDirCombined, GraphicsSettingsWindow.ShaderStrippingEditor.Styles.lightmapDynamicDirCombined, new GUILayoutOption[0]);
                    EditorGUILayout.PropertyField(this.m_LightmapKeepShadowMask, GraphicsSettingsWindow.ShaderStrippingEditor.Styles.lightmapKeepShadowMask, new GUILayoutOption[0]);
                    EditorGUILayout.PropertyField(this.m_LightmapKeepSubtractive, GraphicsSettingsWindow.ShaderStrippingEditor.Styles.lightmapKeepSubtractive, new GUILayoutOption[0]);
                    EditorGUILayout.Space();
                    EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]);
                    EditorGUILayout.PrefixLabel(GUIContent.Temp(" "), EditorStyles.miniButton);
                    if (GUILayout.Button(GraphicsSettingsWindow.ShaderStrippingEditor.Styles.lightmapFromScene, EditorStyles.miniButton, new GUILayoutOption[]
                    {
                        GUILayout.ExpandWidth(false)
                    }))
                    {
                        flag = true;
                    }
                    EditorGUILayout.EndHorizontal();
                    EditorGUI.indentLevel--;
                    EditorGUILayout.Space();
                }
                EditorGUILayout.PropertyField(this.m_FogStripping, GraphicsSettingsWindow.ShaderStrippingEditor.Styles.fogModes, new GUILayoutOption[0]);
                if (this.m_FogStripping.intValue != 0)
                {
                    EditorGUI.indentLevel++;
                    EditorGUILayout.PropertyField(this.m_FogKeepLinear, GraphicsSettingsWindow.ShaderStrippingEditor.Styles.fogLinear, new GUILayoutOption[0]);
                    EditorGUILayout.PropertyField(this.m_FogKeepExp, GraphicsSettingsWindow.ShaderStrippingEditor.Styles.fogExp, new GUILayoutOption[0]);
                    EditorGUILayout.PropertyField(this.m_FogKeepExp2, GraphicsSettingsWindow.ShaderStrippingEditor.Styles.fogExp2, new GUILayoutOption[0]);
                    EditorGUILayout.Space();
                    EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]);
                    EditorGUILayout.PrefixLabel(GUIContent.Temp(" "), EditorStyles.miniButton);
                    if (GUILayout.Button(GraphicsSettingsWindow.ShaderStrippingEditor.Styles.fogFromScene, EditorStyles.miniButton, new GUILayoutOption[]
                    {
                        GUILayout.ExpandWidth(false)
                    }))
                    {
                        flag2 = true;
                    }
                    EditorGUILayout.EndHorizontal();
                    EditorGUI.indentLevel--;
                    EditorGUILayout.Space();
                }
                EditorGUILayout.PropertyField(this.m_InstancingStripping, GraphicsSettingsWindow.ShaderStrippingEditor.Styles.instancingVariants, new GUILayoutOption[0]);
                base.serializedObject.ApplyModifiedProperties();
                if (flag)
                {
                    ShaderUtil.CalculateLightmapStrippingFromCurrentScene();
                }
                if (flag2)
                {
                    ShaderUtil.CalculateFogStrippingFromCurrentScene();
                }
            }
Example #27
0
        // shared by compute shader inspector too
        internal static void ShaderErrorListUI(Object shader, ShaderMessage[] messages, ref Vector2 scrollPosition)
        {
            int n = messages.Length;

            GUILayout.Space(kSpace);
            GUILayout.Label(string.Format("Errors ({0}):", n), EditorStyles.boldLabel);
            int   errorListID = GUIUtility.GetControlID(kErrorViewHash, FocusType.Passive);
            float height      = Mathf.Min(n * 20f + 40f, 150f);

            scrollPosition = GUILayout.BeginScrollView(scrollPosition, GUISkin.current.box, GUILayout.MinHeight(height));

            EditorGUIUtility.SetIconSize(new Vector2(16.0f, 16.0f));
            float lineHeight = Styles.messageStyle.CalcHeight(EditorGUIUtility.TempContent(Styles.errorIcon), 100);

            Event e = Event.current;

            for (int i = 0; i < n; ++i)
            {
                Rect r = EditorGUILayout.GetControlRect(false, lineHeight);

                string err      = messages[i].message;
                string plat     = messages[i].platform.ToString();
                bool   warn     = messages[i].severity != ShaderCompilerMessageSeverity.Error;
                string fileName = FileUtil.GetLastPathNameComponent(messages[i].file);
                int    line     = messages[i].line;

                // Double click opens shader file at error line
                if (e.type == EventType.MouseDown && e.button == 0 && r.Contains(e.mousePosition))
                {
                    GUIUtility.keyboardControl = errorListID;
                    if (e.clickCount == 2)
                    {
                        string filePath = messages[i].file;
                        Object asset    = string.IsNullOrEmpty(filePath) ? null : AssetDatabase.LoadMainAssetAtPath(filePath);

                        // if we don't have an asset and the filePath is an absolute path, it's an error in a system
                        // cginc - open that instead
                        if (asset == null && System.IO.Path.IsPathRooted(filePath))
                        {
                            ShaderUtil.OpenSystemShaderIncludeError(filePath, line);
                        }
                        else
                        {
                            AssetDatabase.OpenAsset(asset ?? shader, line);
                        }
                        GUIUtility.ExitGUI();
                    }
                    e.Use();
                }

                // Context menu, "Copy"
                if (e.type == EventType.ContextClick && r.Contains(e.mousePosition))
                {
                    e.Use();
                    var menu = new GenericMenu();
                    // need to copy current value to be used in delegate
                    // (C# closures close over variables, not their values)
                    var errorIndex = i;
                    menu.AddItem(EditorGUIUtility.TrTextContent("Copy error text"), false, delegate {
                        string errMsg = messages[errorIndex].message;
                        if (!string.IsNullOrEmpty(messages[errorIndex].messageDetails))
                        {
                            errMsg += '\n';
                            errMsg += messages[errorIndex].messageDetails;
                        }
                        EditorGUIUtility.systemCopyBuffer = errMsg;
                    });
                    menu.ShowAsContext();
                }

                // background
                if (e.type == EventType.Repaint)
                {
                    if ((i & 1) == 0)
                    {
                        GUIStyle st = Styles.evenBackground;
                        st.Draw(r, false, false, false, false);
                    }
                }

                // error location on the right side
                Rect locRect = r;
                locRect.xMin = locRect.xMax;
                if (line > 0)
                {
                    GUIContent gc;
                    if (string.IsNullOrEmpty(fileName))
                    {
                        gc = EditorGUIUtility.TempContent(line.ToString(CultureInfo.InvariantCulture));
                    }
                    else
                    {
                        gc = EditorGUIUtility.TempContent(fileName + ":" + line.ToString(CultureInfo.InvariantCulture));
                    }

                    // calculate size so we can right-align it
                    Vector2 size = EditorStyles.miniLabel.CalcSize(gc);
                    locRect.xMin -= size.x;
                    GUI.Label(locRect, gc, EditorStyles.miniLabel);
                    locRect.xMin -= 2;
                    // ensure some minimum width so that platform field next will line up
                    if (locRect.width < 30)
                    {
                        locRect.xMin = locRect.xMax - 30;
                    }
                }

                // platform to the left of it
                Rect platRect = locRect;
                platRect.width = 0;
                if (plat.Length > 0)
                {
                    GUIContent gc = EditorGUIUtility.TempContent(plat);
                    // calculate size so we can right-align it
                    Vector2 size = EditorStyles.miniLabel.CalcSize(gc);
                    platRect.xMin -= size.x;

                    // draw platform in dimmer color; it's often not very important information
                    Color oldColor = GUI.contentColor;
                    GUI.contentColor = new Color(1, 1, 1, 0.5f);
                    GUI.Label(platRect, gc, EditorStyles.miniLabel);
                    GUI.contentColor = oldColor;
                    platRect.xMin   -= 2;
                }

                // error message
                Rect msgRect = r;
                msgRect.xMax = platRect.xMin;
                GUI.Label(msgRect, EditorGUIUtility.TempContent(err, warn ? Styles.warningIcon : Styles.errorIcon), Styles.messageStyle);
            }
            EditorGUIUtility.SetIconSize(Vector2.zero);
            GUILayout.EndScrollView();
        }
Example #28
0
 public VariantCompileInfo CompileVariant(ShaderType shaderType, string[] keywords,
                                          ShaderCompilerPlatform shaderCompilerPlatform, BuildTarget buildTarget, BuiltinShaderDefine[] platformKeywords, GraphicsTier tier, bool forExternalTool)
 {
     return(ShaderUtil.CompileShaderVariant(SourceShader, SubshaderIndex, m_PassIndex, shaderType, platformKeywords, keywords, shaderCompilerPlatform, buildTarget, tier, forExternalTool));
 }
Example #29
0
        public virtual void OnEnable()
        {
            var s = target as Shader;

            ShaderUtil.FetchCachedMessages(s);
        }
Example #30
0
 public PreprocessedVariant PreprocessVariant(ShaderType shaderType, string[] keywords,
                                              ShaderCompilerPlatform shaderCompilerPlatform, BuildTarget buildTarget, BuiltinShaderDefine[] platformKeywords, GraphicsTier tier, bool stripLineDirectives)
 {
     return(ShaderUtil.PreprocessShaderVariant(SourceShader, SubshaderIndex, m_PassIndex, shaderType, platformKeywords, keywords, shaderCompilerPlatform, buildTarget, tier, stripLineDirectives));
 }
Example #31
0
            public override void OnInspectorGUI()
            {
                serializedObject.Update();

                bool calcLightmapStripping = false, calcFogStripping = false;

                EditorGUILayout.PropertyField(m_LightmapStripping, Styles.lightmapModes);

                if (m_LightmapStripping.intValue != 0)
                {
                    EditorGUI.indentLevel++;
                    EditorGUILayout.PropertyField(m_LightmapKeepPlain, Styles.lightmapPlain);
                    EditorGUILayout.PropertyField(m_LightmapKeepDirCombined, Styles.lightmapDirCombined);
                    EditorGUILayout.PropertyField(m_LightmapKeepDynamicPlain, Styles.lightmapDynamicPlain);
                    EditorGUILayout.PropertyField(m_LightmapKeepDynamicDirCombined, Styles.lightmapDynamicDirCombined);
                    EditorGUILayout.PropertyField(m_LightmapKeepShadowMask, Styles.lightmapKeepShadowMask);
                    EditorGUILayout.PropertyField(m_LightmapKeepSubtractive, Styles.lightmapKeepSubtractive);
                    EditorGUILayout.Space();

                    EditorGUILayout.BeginHorizontal();
                    EditorGUILayout.PrefixLabel(GUIContent.Temp(" "), EditorStyles.miniButton);

                    if (GUILayout.Button(Styles.lightmapFromScene, EditorStyles.miniButton, GUILayout.ExpandWidth(false)))
                    {
                        calcLightmapStripping = true;
                    }

                    EditorGUILayout.EndHorizontal();
                    EditorGUI.indentLevel--;
                    EditorGUILayout.Space();
                }

                EditorGUILayout.PropertyField(m_FogStripping, Styles.fogModes);
                if (m_FogStripping.intValue != 0)
                {
                    EditorGUI.indentLevel++;
                    EditorGUILayout.PropertyField(m_FogKeepLinear, Styles.fogLinear);
                    EditorGUILayout.PropertyField(m_FogKeepExp, Styles.fogExp);
                    EditorGUILayout.PropertyField(m_FogKeepExp2, Styles.fogExp2);
                    EditorGUILayout.Space();

                    EditorGUILayout.BeginHorizontal();
                    EditorGUILayout.PrefixLabel(GUIContent.Temp(" "), EditorStyles.miniButton);

                    if (GUILayout.Button(Styles.fogFromScene, EditorStyles.miniButton, GUILayout.ExpandWidth(false)))
                    {
                        calcFogStripping = true;
                    }

                    EditorGUILayout.EndHorizontal();
                    EditorGUI.indentLevel--;
                    EditorGUILayout.Space();
                }

                EditorGUILayout.PropertyField(m_InstancingStripping, Styles.instancingVariants);

                serializedObject.ApplyModifiedProperties();

                // need to do these after ApplyModifiedProperties, since it changes their values from native code
                if (calcLightmapStripping)
                {
                    ShaderUtil.CalculateLightmapStrippingFromCurrentScene();
                }
                if (calcFogStripping)
                {
                    ShaderUtil.CalculateFogStrippingFromCurrentScene();
                }
            }
Example #32
0
 public bool HasShaderStage(ShaderType shaderType)
 {
     return(ShaderUtil.PassHasShaderStage(SourceShader, SubshaderIndex, m_PassIndex, shaderType));
 }
        void DoVertexStreamsArea(Material material)
        {
            // Display list of streams required to make this shader work
            bool useLighting         = (material.GetFloat("_LightingEnabled") > 0.0f);
            bool useFlipbookBlending = (material.GetFloat("_FlipbookMode") > 0.0f);
            bool useTangents         = useLighting && material.GetTexture("_BumpMap");

            bool useGPUInstancing = ShaderUtil.HasProceduralInstancing(material.shader);

            if (useGPUInstancing && m_RenderersUsingThisMaterial.Count > 0)
            {
                if (!m_RenderersUsingThisMaterial[0].enableGPUInstancing)
                {
                    useGPUInstancing = false;
                }
            }

            GUILayout.Label(Styles.streamPositionText, EditorStyles.label);

            if (useLighting)
            {
                GUILayout.Label(Styles.streamNormalText, EditorStyles.label);
            }

            GUILayout.Label(useGPUInstancing ? Styles.streamColorInstancedText : Styles.streamColorText, EditorStyles.label);
            GUILayout.Label(Styles.streamUVText, EditorStyles.label);

            if (useTangents)
            {
                GUILayout.Label(Styles.streamTangentText, EditorStyles.label);
            }

            if (useGPUInstancing)
            {
                GUILayout.Label(Styles.streamAnimFrameText, EditorStyles.label);
            }
            else if (useFlipbookBlending && !useGPUInstancing)
            {
                GUILayout.Label(Styles.streamUV2Text, EditorStyles.label);
                GUILayout.Label(Styles.streamAnimBlendText, EditorStyles.label);
            }

            // Build the list of expected vertex streams
            List <ParticleSystemVertexStream> streams = new List <ParticleSystemVertexStream>();

            streams.Add(ParticleSystemVertexStream.Position);

            if (useLighting)
            {
                streams.Add(ParticleSystemVertexStream.Normal);
            }

            streams.Add(ParticleSystemVertexStream.Color);
            streams.Add(ParticleSystemVertexStream.UV);

            if (useTangents)
            {
                streams.Add(ParticleSystemVertexStream.Tangent);
            }

            List <ParticleSystemVertexStream> instancedStreams = new List <ParticleSystemVertexStream>(streams);

            if (useGPUInstancing)
            {
                instancedStreams.Add(ParticleSystemVertexStream.AnimFrame);
            }
            if (useFlipbookBlending)
            {
                streams.Add(ParticleSystemVertexStream.UV2);
                streams.Add(ParticleSystemVertexStream.AnimBlend);
            }

            // Set the streams on all systems using this material
            if (GUILayout.Button(Styles.streamApplyToAllSystemsText, EditorStyles.miniButton, GUILayout.ExpandWidth(false)))
            {
                Undo.RecordObjects(m_RenderersUsingThisMaterial.Where(r => r != null).ToArray(), Styles.undoApplyCustomVertexStreams);

                foreach (ParticleSystemRenderer renderer in m_RenderersUsingThisMaterial)
                {
                    if (renderer != null)
                    {
                        if (useGPUInstancing && renderer.renderMode == ParticleSystemRenderMode.Mesh && renderer.supportsMeshInstancing)
                        {
                            renderer.SetActiveVertexStreams(instancedStreams);
                        }
                        else
                        {
                            renderer.SetActiveVertexStreams(streams);
                        }
                    }
                }
            }

            // Display a warning if any renderers have incorrect vertex streams
            string Warnings = "";
            List <ParticleSystemVertexStream> rendererStreams = new List <ParticleSystemVertexStream>();

            foreach (ParticleSystemRenderer renderer in m_RenderersUsingThisMaterial)
            {
                if (renderer != null)
                {
                    renderer.GetActiveVertexStreams(rendererStreams);

                    bool streamsValid;
                    if (useGPUInstancing && renderer.renderMode == ParticleSystemRenderMode.Mesh && renderer.supportsMeshInstancing)
                    {
                        streamsValid = rendererStreams.SequenceEqual(instancedStreams);
                    }
                    else
                    {
                        streamsValid = rendererStreams.SequenceEqual(streams);
                    }

                    if (!streamsValid)
                    {
                        Warnings += "  " + renderer.name + "\n";
                    }
                }
            }
            if (Warnings != "")
            {
                EditorGUILayout.HelpBox("The following Particle System Renderers are using this material with incorrect Vertex Streams:\n" + Warnings + "Use the Apply to Systems button to fix this", MessageType.Warning, true);
            }

            EditorGUILayout.Space();
        }
Example #34
0
 public Texture TextureProperty(string propertyName, string label, ShaderUtil.ShaderPropertyTexDim texDim, bool scaleOffset)
 {
     MaterialProperty materialProperty = GetMaterialProperty(base.targets, propertyName);
     return this.TextureProperty(materialProperty, label, scaleOffset);
 }