예제 #1
0
    public static void HandleAssignments(Material material, List <FXTextureAssigner.RenderTextureAssignment> assignments)
    {
        var fxTextureSlots = new List <FXTextureSlot>();

        if (material)
        {
            var shader = material.shader;

            for (int i = 0; i < ShaderUtil.GetPropertyCount(shader); i++)
            {
                var isFxTexture = ShaderUtil.GetPropertyType(shader, i) == ShaderUtil.ShaderPropertyType.TexEnv &&
                                  FXMaterialHelper.GetFXTextureType(ShaderUtil.GetPropertyDescription(shader, i)) != null;

                if (isFxTexture)
                {
                    var match = Regex.Match(ShaderUtil.GetPropertyDescription(shader, i), @"(.*)\(\w*\).*", RegexOptions.IgnoreCase);

                    fxTextureSlots.Add(new FXTextureSlot()
                    {
                        Name        = ShaderUtil.GetPropertyName(shader, i),
                        Description = match.Groups[1].Value.Trim()
                    });
                }
            }
        }

        var currentSlots  = assignments.Select(a => a.TextureName);
        var slotsToRemove = currentSlots.Except(fxTextureSlots.Select(slot => slot.Name)).ToArray();
        var slotsToAdd    = fxTextureSlots.Where(slot => !currentSlots.Any(s => s == slot.Name)).ToArray();

        foreach (var toRemove in slotsToRemove)
        {
            assignments.Remove(assignments.First(a => a.TextureName == toRemove));
        }

        foreach (var toAdd in slotsToAdd)
        {
            assignments.Add(new FXTextureAssigner.RenderTextureAssignment()
            {
                TextureName        = toAdd.Name,
                TextureDescription = toAdd.Description
            });
        }

        foreach (var assignment in assignments)
        {
            assignment.RenderTexture = (FXRenderTexture)EditorGUILayout.ObjectField(assignment.TextureDescription, assignment.RenderTexture, typeof(FXRenderTexture), false);
        }
    }
예제 #2
0
    public override void OnInspectorGUI()
    {
        Debug.Log("==OnInspectorGUI== ");
        base.OnInspectorGUI();
        Material material = target as Material;
        Shader   shader   = material.shader;

        for (int i = 0; i < ShaderUtil.GetPropertyCount(shader); i++)
        {
            if (ShaderUtil.GetPropertyType(shader, i) != ShaderUtil.ShaderPropertyType.TexEnv)
            {
                continue;
            }
            //属性
            string name = ShaderUtil.GetPropertyName(shader, i);
            //文本值
            string           label         = ShaderUtil.GetPropertyDescription(shader, i);
            TextureDimension desiredTexdim = ShaderUtil.GetTexDim(shader, i);
            System.Type      t;
            switch (desiredTexdim)
            {
            case TextureDimension.Tex2D:
                t = typeof(Texture);
                //Debug.Log (" Tex2D ");
                Texture t1 = material.GetTexture(name);
                break;

            case TextureDimension.Cube:
                t = typeof(Cubemap);
                //Debug.Log (" Cube ");
                break;

            case TextureDimension.Tex3D:
                t = typeof(Texture3D);
                //Debug.Log (" Tex3D ");
                break;

            case TextureDimension.Tex2DArray:
                t = typeof(Texture);
                //Debug.Log (" Tex2DArray ");
                break;

            default:
                t = null;
                break;
            }
        }
    }
예제 #3
0
    public override void OnPreviewGUI(Rect r, GUIStyle background)
    {
        base.OnPreviewGUI(r, background);

        Material targetMat = target as Material;        //我们正在编辑的材质
        Shader   shader    = targetMat.shader;

        string  label        = ShaderUtil.GetPropertyDescription(shader, 0);
        string  propertyName = ShaderUtil.GetPropertyName(shader, 0);
        Texture tex          = targetMat.GetTexture(propertyName);

        if (tex != null)
        {
            EditorGUILayout.LabelField("" + tex.name + "  height:" + tex.height + "," + "width:" + tex.width);
        }
    }
예제 #4
0
        public static void      SerializeShaderProperty(Shader shader, int i, ByteBuffer buffer)
        {
            string description = ShaderUtil.GetPropertyDescription(shader, i);
            string name        = ShaderUtil.GetPropertyName(shader, i);

            ShaderUtil.ShaderPropertyType propertyType = ShaderUtil.GetPropertyType(shader, i);
            bool hidden = ShaderUtil.IsShaderPropertyHidden(shader, i);

            buffer.AppendUnicodeString(description);
            buffer.AppendUnicodeString(name);
            buffer.Append((int)propertyType);
            buffer.Append(hidden);

            buffer.Append(ShaderUtil.GetRangeLimits(shader, i, 1));
            buffer.Append(ShaderUtil.GetRangeLimits(shader, i, 2));
        }
예제 #5
0
파일: Rme_Main.cs 프로젝트: Vjutal/Game1747
    private void InitShader(ShaderLerpInfo shaderInfo, string shaderName)
    {
        shaderInfo.ShaderName  = shaderName;
        shaderInfo.PropsToLerp = new List <ShaderPropLerpInfo>();
        var shader = Shader.Find(shaderName);
        var props  = ShaderUtil.GetPropertyCount(shader);

        for (int i = 0; i < props; i++)
        {
            var propName = ShaderUtil.GetPropertyName(shader, i);
            var propDesc = ShaderUtil.GetPropertyDescription(shader, i);
            var type     = ShaderUtil.GetPropertyType(shader, i);

            if (!new[] { ShaderUtil.ShaderPropertyType.Color, ShaderUtil.ShaderPropertyType.Float, ShaderUtil.ShaderPropertyType.Range }.Any(s => type == s))
            {
                continue;
            }

            ShaderType shaderType;
            switch (type)
            {
            case ShaderUtil.ShaderPropertyType.Color:
                shaderType = ShaderType.Color;
                break;

            case ShaderUtil.ShaderPropertyType.Float:
                shaderType = ShaderType.Float;
                break;

            case ShaderUtil.ShaderPropertyType.Range:
                shaderType = ShaderType.Range;
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            shaderInfo.PropsToLerp.Add(new ShaderPropLerpInfo()
            {
                PropName      = propName,
                PropDesc      = propDesc,
                PropType      = shaderType,
                OnlyLerpAlpha = true,
                LerpTo        = 0
            });
        }
    }
예제 #6
0
    //When an object is selected
    void OnEnable()
    {
        //First, we gotta get the sprite or image component on the thing
        //Jesus Christ, Jesse, your keyboard is infuriating
        Sprite_CustomProperties comp   = serializedObject.targetObject as Sprite_CustomProperties;
        SpriteRenderer          sprite = comp.GetComponent <SpriteRenderer>();
        Image          image           = comp.GetComponent <Image>();
        CanvasRenderer canv            = comp.GetComponent <CanvasRenderer>();

        if (sprite != null)
        {
            m = sprite.material;
            sprite.GetPropertyBlock(block);
            isCanvas = false;

            comp.IsCanvasRenderer = true;
        }
        else if (image != null)
        {
            isCanvas = true;
            m        = image.material;

            comp.IsCanvasRenderer = true;
        }

        s = m.shader;

        numProperties      = ShaderUtil.GetPropertyCount(s);
        materialProperties = new List <MProperty>();

        for (int i = 0; i < numProperties; i++)
        {
            MProperty newProp = new MProperty();
            newProp.name        = ShaderUtil.GetPropertyName(s, i);
            newProp.description = ShaderUtil.GetPropertyDescription(s, i);
            //newProp.type = ShaderUtil.GetPropertyType(s, i);
            newProp.hidden = ShaderUtil.IsShaderPropertyHidden(s, i);

            //These are hardcoded values that Unity already takes care of for us
            if (!(newProp.name == "_MainTex" || newProp.name == "_Color"))
            {
                materialProperties.Add(newProp);
            }
        }
    }
예제 #7
0
		private void PopulatePropertiesFromShader()
		{
			if ( _Shader != null )
			{
				int propertyCount = ShaderUtil.GetPropertyCount( _Shader );

				if ( propertyCount > 0 )
				{
					for ( int i = 0; i < propertyCount; i++ )
					{
						string name = ShaderUtil.GetPropertyName( _Shader, i );

						if ( !_CastedTarget.Properties.Any( x => x.Name == name ) )
						{
							string desc = ShaderUtil.GetPropertyDescription( _Shader, i );

							MaterialProperty newProp;
							switch ( ShaderUtil.GetPropertyType( _Shader, i ) )
							{
								case SPT.Color:
									newProp = new MaterialProperty( name, desc, _Material.GetColor( name ) );
									break;

								case SPT.TexEnv:
									newProp = new MaterialProperty( name, desc, _Material.GetTexture( name ) );
									break;

								case SPT.Vector:
									newProp = new MaterialProperty( name, desc, _Material.GetVector( name ) );
									break;

								case SPT.Float:
								case SPT.Range:
								default:
									newProp = new MaterialProperty( name, desc, _Material.GetFloat( name ) );
									break;
							}

							_CastedTarget.Properties.Add( newProp );
						}
					}
				}
			}
		}
예제 #8
0
        private static RuntimeShaderInfo Create(Shader shader)
        {
            if (shader == null)
            {
                throw new System.ArgumentNullException("shader");
            }

            int propertyCount = ShaderUtil.GetPropertyCount(shader);

            RuntimeShaderInfo shaderInfo = new RuntimeShaderInfo();

            shaderInfo.Name                 = shader.name;
            shaderInfo.PropertyCount        = propertyCount;
            shaderInfo.PropertyDescriptions = new string[propertyCount];
            shaderInfo.PropertyNames        = new string[propertyCount];
            shaderInfo.PropertyRangeLimits  = new RuntimeShaderInfo.RangeLimits[propertyCount];
            shaderInfo.PropertyTexDims      = new TextureDimension[propertyCount];
            shaderInfo.PropertyTypes        = new RTShaderPropertyType[propertyCount];
            shaderInfo.IsHidden             = new bool[propertyCount];

            for (int i = 0; i < propertyCount; ++i)
            {
                shaderInfo.PropertyDescriptions[i] = ShaderUtil.GetPropertyDescription(shader, i);
                shaderInfo.PropertyNames[i]        = ShaderUtil.GetPropertyName(shader, i);
                shaderInfo.PropertyRangeLimits[i]  = new RuntimeShaderInfo.RangeLimits(
                    ShaderUtil.GetRangeLimits(shader, i, 0),
                    ShaderUtil.GetRangeLimits(shader, i, 1),
                    ShaderUtil.GetRangeLimits(shader, i, 2));
                shaderInfo.PropertyTexDims[i] = ShaderUtil.GetTexDim(shader, i);

                RTShaderPropertyType          rtType = RTShaderPropertyType.Unknown;
                ShaderUtil.ShaderPropertyType type   = ShaderUtil.GetPropertyType(shader, i);
                if (m_typeToType.ContainsKey(type))
                {
                    rtType = m_typeToType[type];
                }

                shaderInfo.PropertyTypes[i] = rtType;
                shaderInfo.IsHidden[i]      = ShaderUtil.IsShaderPropertyHidden(shader, i);
            }
            return(shaderInfo);
        }
예제 #9
0
        /// <summary>
        /// Shaderから指定のnameのプロパティの description を取得する。
        /// </summary>
        /// <param name="shader"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        private static string getPropertyDescription(Shader shader, string name)
        {
#if UNITY_2019_1_OR_NEWER
            var idx = shader.FindPropertyIndex(name);
            if (0 <= idx)
            {
                return(shader.GetPropertyDescription(idx));
            }
            return(null);
#else
            for (int idx = ShaderUtil.GetPropertyCount(shader) - 1; 0 <= idx; idx--)
            {
                if (name == ShaderUtil.GetPropertyName(shader, idx))
                {
                    return(ShaderUtil.GetPropertyDescription(shader, idx));
                }
            }
            return(null);
#endif
        }
예제 #10
0
		// 更新 Shader 数据
		void UpdateShader()
		{
			if (material)
			{
				if (_material.shader != _shader)
				{
					_shader = _material.shader;
					_propertyIndexInMenu = -2;

					if (_shader)
					{
						_propertyIndexes.Clear();
						_propertyCount = ShaderUtil.GetPropertyCount(_shader);

						for (int i = 0; i < _propertyCount; i++)
						{
							if (!ShaderUtil.IsShaderPropertyHidden(_shader, i) && ShaderUtil.GetPropertyType(_shader, i) == propertyType)
							{
								_propertyIndexes.Add(i);
							}
						}

						_propertyCount = _propertyIndexes.Count;
						if (_propertyCount > 0)
						{
							_propertyNames = new string[_propertyCount];
							_propertyDescriptions = new string[_propertyCount];

							for (int i = 0; i < _propertyCount; i++)
							{
								_propertyNames[i] = ShaderUtil.GetPropertyName(_shader, _propertyIndexes[i]);
								_propertyDescriptions[i] = string.Format("{0} ({1})",
									ShaderUtil.GetPropertyDescription(_shader, _propertyIndexes[i]),
									_propertyNames[i]);
							}
						}
					}
				}
			}
			else _shader = null;
		}
예제 #11
0
        bool DrawShaderPropertyOptions(SerializedProperty pLayer)
        {
            SerializedProperty shaderProperty = pLayer.FindPropertyRelative("mShaderProperty");
            SerializedProperty materialID     = pLayer.FindPropertyRelative("mMaterialID");

            List <string> texturePropertyNames = new List <string>();
            List <string> textureDescriptions  = new List <string>();
            Shader        shader = mMaterialMotion.GetComponent <Renderer>().sharedMaterials[materialID.intValue].shader;

            for (int i = 0; i < ShaderUtil.GetPropertyCount(shader); ++i)
            {
                switch (ShaderUtil.GetPropertyType(shader, i))
                {
                case ShaderUtil.ShaderPropertyType.TexEnv:
                case ShaderUtil.ShaderPropertyType.Float:
                case ShaderUtil.ShaderPropertyType.Color:
                case ShaderUtil.ShaderPropertyType.Range:
                    textureDescriptions.Add(ShaderUtil.GetPropertyDescription(shader, i));
                    texturePropertyNames.Add(ShaderUtil.GetPropertyName(shader, i));
                    break;
                }
            }
            if (texturePropertyNames.Count == 0)
            {
                EditorGUILayout.HelpBox("Shader does not have any valid Inputs (Texture, Float, Color)", MessageType.Info);
                return(true);
            }

            int index = texturePropertyNames.FindIndex(x => x.Equals(shaderProperty.stringValue));

            if (index == -1)
            {
                index = 0;
            }
            index = EditorGUILayout.Popup("Shader Property:", index, textureDescriptions.ToArray());
            shaderProperty.stringValue = texturePropertyNames[index];
            pLayer.FindPropertyRelative("mMotionProperty").enumValueIndex = (int)ShaderUtil.GetPropertyType(shader, index);

            return(false);
        }
예제 #12
0
    private void ShaderPropertyImpl(Shader shader, int propertyIndex, FeatureToggle currentToggle)
    {
        string propertyDescription = ShaderUtil.GetPropertyDescription(shader, propertyIndex);

        if (currentToggle == null)
        {
            for (int i = 0; i < Toggles.Count; i++)
            {
                if (Regex.IsMatch(propertyDescription, Toggles[i].InspectorPropertyHideTag, RegexOptions.IgnoreCase))
                {
                    return;
                }
            }
        }
        else if (!Regex.IsMatch(propertyDescription, currentToggle.InspectorPropertyHideTag, RegexOptions.IgnoreCase))
        {
            return;
        }

        MaterialProperty materialProperty = GetMaterialProperty(targets, propertyIndex);

        ShaderProperty(materialProperty, materialProperty.displayName);
    }
    public List <MaterialProperty> GetShaderProperties(Material material)
    {
        if (cache.ContainsKey(material.shader.name))
        {
            return(cache[material.shader.name]);
        }

        var    list  = new List <MaterialProperty>();
        Shader s     = material.shader;
        int    count = ShaderUtil.GetPropertyCount(s);

        for (int i = 0; i < count; i++)
        {
            list.Add(new MaterialProperty()
            {
                type        = ShaderUtil.GetPropertyType(s, i),
                description = ShaderUtil.GetPropertyDescription(s, i),
                name        = ShaderUtil.GetPropertyName(s, i)
            });
        }

        cache[material.shader.name] = list;
        return(list);
    }
예제 #14
0
    // This runs once for every property in our shader.
    private void ShaderPropertyImpl(Shader shader, int propertyIndex, FeatureToggle currentToggle)
    {
        string propertyDescription = ShaderUtil.GetPropertyDescription(shader, propertyIndex);

        // If current toggle is null, we only want to show properties that aren't already "owned" by a toggle,
        // so if it is owned by another toggle, then return.
        if (currentToggle == null)
        {
            for (int i = 0; i < Toggles.Count; i++)
            {
                if (Regex.IsMatch(propertyDescription, Toggles[i].InspectorPropertyHideTag, RegexOptions.IgnoreCase))
                {
                    return;
                }
            }
        }
        // Only draw if we the current property is owned by the current toggle.
        else if (!Regex.IsMatch(propertyDescription, currentToggle.InspectorPropertyHideTag, RegexOptions.IgnoreCase))
        {
            return;
        }
        // If we've gotten to this point, draw the shader property regulairly.
        ShaderProperty(shader, propertyIndex);
    }
예제 #15
0
        public static List <TexEnv> GetTexEnvs(Shader shader)
        {
            texEnvNames.Clear();

            if (shader != null)
            {
                var count = ShaderUtil.GetPropertyCount(shader);

                for (var i = 0; i < count; i++)
                {
                    if (ShaderUtil.GetPropertyType(shader, i) == ShaderUtil.ShaderPropertyType.TexEnv)
                    {
                        var texEnv = default(TexEnv);

                        texEnv.Name = ShaderUtil.GetPropertyName(shader, i);
                        texEnv.Desc = ShaderUtil.GetPropertyDescription(shader, i);

                        texEnvNames.Add(texEnv);
                    }
                }
            }

            return(texEnvNames);
        }
예제 #16
0
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            var drawingPosition = position;

            drawingPosition.height = EditorGUIUtility.singleLineHeight;

            var shaderProperty = property.FindPropertyRelative("shader");

            var currentShaderReference = shaderProperty.objectReferenceValue as Shader;
            var prefix    = "Hidden/EPO/Fill/";
            var fillLabel = currentShaderReference == null ? "none" : currentShaderReference.name.Substring(prefix.Length);

            if (shaderProperty.hasMultipleDifferentValues)
            {
                fillLabel = "-";
            }

            if (EditorGUI.DropdownButton(position, new GUIContent("Fill type: " + fillLabel), FocusType.Passive))
            {
                var menu = new GenericMenu();

                menu.AddItem(new GUIContent("none"), currentShaderReference == null && !shaderProperty.hasMultipleDifferentValues, () =>
                {
                    shaderProperty.objectReferenceValue = null;
                    shaderProperty.serializedObject.ApplyModifiedProperties();
                });

                var shaders = AssetDatabase.FindAssets("t:Shader");
                foreach (var shader in shaders)
                {
                    var loadedShader = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(shader), typeof(Shader)) as Shader;
                    if (!loadedShader.name.StartsWith(prefix))
                    {
                        continue;
                    }

                    menu.AddItem(new GUIContent(loadedShader.name.Substring(prefix.Length)), loadedShader == shaderProperty.objectReferenceValue && !shaderProperty.hasMultipleDifferentValues, () =>
                    {
                        shaderProperty.objectReferenceValue = loadedShader;
                        shaderProperty.serializedObject.ApplyModifiedProperties();
                    });
                }

                menu.ShowAsContext();
            }

            if (shaderProperty.hasMultipleDifferentValues)
            {
                return;
            }

            if (currentShaderReference != null)
            {
                position.x     += EditorGUIUtility.singleLineHeight;
                position.width -= EditorGUIUtility.singleLineHeight;
                var properties = new Dictionary <string, SerializedProperty>();

                var serializedProperties = property.FindPropertyRelative("serializedProperties");

                for (var index = 0; index < serializedProperties.arraySize; index++)
                {
                    var subProperty = serializedProperties.GetArrayElementAtIndex(index);

                    var propertyName  = subProperty.FindPropertyRelative("PropertyName");
                    var propertyValue = subProperty.FindPropertyRelative("Property");

                    if (propertyName == null || propertyValue == null)
                    {
                        break;
                    }

                    properties.Add(propertyName.stringValue, propertyValue);
                }

                var fillParametersPosition = position;
                for (var index = 0; index < ShaderUtil.GetPropertyCount(currentShaderReference); index++)
                {
                    var propertyName = ShaderUtil.GetPropertyName(currentShaderReference, index);
                    if (!propertyName.StartsWith("_Public"))
                    {
                        continue;
                    }

                    fillParametersPosition.y += EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing;

                    SerializedProperty currentProperty;
                    if (!properties.TryGetValue(propertyName, out currentProperty))
                    {
                        serializedProperties.InsertArrayElementAtIndex(serializedProperties.arraySize);
                        currentProperty = serializedProperties.GetArrayElementAtIndex(serializedProperties.arraySize - 1);
                        currentProperty.FindPropertyRelative("PropertyName").stringValue = propertyName;
                        currentProperty = currentProperty.FindPropertyRelative("Property");

                        var tempMaterial = new Material(currentShaderReference);

                        switch (ShaderUtil.GetPropertyType(currentShaderReference, index))
                        {
                        case ShaderUtil.ShaderPropertyType.Color:
                            currentProperty.FindPropertyRelative("ColorValue").colorValue = tempMaterial.GetColor(propertyName);
                            break;

                        case ShaderUtil.ShaderPropertyType.Vector:
                            currentProperty.FindPropertyRelative("VectorValue").vector4Value = tempMaterial.GetVector(propertyName);
                            break;

                        case ShaderUtil.ShaderPropertyType.Float:
                            currentProperty.FindPropertyRelative("FloatValue").floatValue = tempMaterial.GetFloat(propertyName);
                            break;

                        case ShaderUtil.ShaderPropertyType.Range:
                            currentProperty.FindPropertyRelative("FloatValue").floatValue = tempMaterial.GetFloat(propertyName);
                            break;

                        case ShaderUtil.ShaderPropertyType.TexEnv:
                            currentProperty.FindPropertyRelative("TextureValue").objectReferenceValue = tempMaterial.GetTexture(propertyName);
                            break;
                        }

                        GameObject.DestroyImmediate(tempMaterial);

                        properties.Add(propertyName, currentProperty);
                    }

                    if (currentProperty == null)
                    {
                        continue;
                    }

                    var content = new GUIContent(ShaderUtil.GetPropertyDescription(currentShaderReference, index));

                    switch (ShaderUtil.GetPropertyType(currentShaderReference, index))
                    {
                    case ShaderUtil.ShaderPropertyType.Color:
                        var colorProperty = currentProperty.FindPropertyRelative("ColorValue");
                        colorProperty.colorValue = EditorGUI.ColorField(fillParametersPosition, content, colorProperty.colorValue, true, true, true);
                        break;

                    case ShaderUtil.ShaderPropertyType.Vector:
                        var vectorProperty = currentProperty.FindPropertyRelative("VectorValue");
                        vectorProperty.vector4Value = EditorGUI.Vector4Field(fillParametersPosition, content, vectorProperty.vector4Value);
                        break;

                    case ShaderUtil.ShaderPropertyType.Float:
                        EditorGUI.PropertyField(fillParametersPosition, currentProperty.FindPropertyRelative("FloatValue"), content);
                        break;

                    case ShaderUtil.ShaderPropertyType.Range:
                        var floatProperty = currentProperty.FindPropertyRelative("FloatValue");
                        floatProperty.floatValue = EditorGUI.Slider(fillParametersPosition, content, floatProperty.floatValue,
                                                                    ShaderUtil.GetRangeLimits(currentShaderReference, index, 1),
                                                                    ShaderUtil.GetRangeLimits(currentShaderReference, index, 2));
                        break;

                    case ShaderUtil.ShaderPropertyType.TexEnv:
                        EditorGUI.PropertyField(fillParametersPosition, currentProperty.FindPropertyRelative("TextureValue"), content);
                        break;
                    }

                    currentProperty.FindPropertyRelative("PropertyType").intValue = (int)ShaderUtil.GetPropertyType(currentShaderReference, index);
                }
            }
        }
예제 #17
0
    private void ShaderPropertyImpl(Shader shader, int propertyIndex)
    {
        Material myMat = target as Material;

        Material[] mats = new Material[1] {
            myMat
        };
        MaterialProperty aProp            = MaterialEditor.GetMaterialProperty(mats, propertyIndex);
        GUIStyle         boldFoldoutStyle = new GUIStyle(EditorStyles.foldout);

        boldFoldoutStyle.fontStyle = FontStyle.Bold;
        Color c;

        int    i = propertyIndex;
        bool   separator_flag = false;
        string label          = ShaderUtil.GetPropertyDescription(shader, i);

        if (label.IndexOf("<") >= 0)
        {
            label          = label.Substring(1);
            separator_flag = true;
        }
        string propertyName    = ShaderUtil.GetPropertyName(shader, i);
        bool   adjustementFlag = false;

        if (ShaderUtil.GetPropertyType(shader, i) == ShaderUtil.ShaderPropertyType.Float)
        {
            if (propertyName == "BlockStart")
            {
                adjustementFlag = true;

                EditorGUILayout.BeginVertical("box");
                c         = GUI.color;
                GUI.color = new Color(0.8f, 1, 0.8f);
                GUILayout.BeginHorizontal();
                GUILayout.Space(12);

                propBlockAvailable = IsAvailable(ref label);
                if (propBlockAvailable)
                {
                    bool newVal = EditorGUILayout.Foldout(VolumeGrassMaterialInspector.blocks[i], label, boldFoldoutStyle);
                    if (VolumeGrassMaterialInspector.blocks[i] != newVal)
                    {
                        VolumeGrassMaterialInspector.blocks[i] = newVal;
                        EditorUtility.SetDirty(target);
                    }
                }
                else
                {
                    EditorGUILayout.LabelField(label + " (switched off)");
                }
                unfolded = VolumeGrassMaterialInspector.blocks[i];
                GUILayout.EndHorizontal();
                GUI.color = c;
                GUILayout.BeginHorizontal();
                GUILayout.Space(10);
                GUILayout.BeginVertical();
            }
            else if (propertyName == "BlockEnd")
            {
                adjustementFlag    = true;
                unfolded           = true;
                propBlockAvailable = true;

                GUILayout.EndVertical();
                GUILayout.EndHorizontal();
                EditorGUILayout.EndVertical();

                GUILayout.Space(3);
            }
        }
        if (!unfolded || !propBlockAvailable)
        {
            return;
        }

        if (separator_flag)
        {
            GUILayout.Space(8);
        }

        switch (ShaderUtil.GetPropertyType(shader, i))
        {
        case ShaderUtil.ShaderPropertyType.Range:         // float ranges
        {
            GUILayout.BeginHorizontal();
            RangeProperty(aProp, label);
            GUILayout.EndHorizontal();

            break;
        }

        case ShaderUtil.ShaderPropertyType.Float:         // floats
        {
            if (!adjustementFlag)
            {
                FloatProperty(aProp, label);
            }
            break;
        }

        case ShaderUtil.ShaderPropertyType.Color:         // colors
        {
            ColorProperty(aProp, label);
            break;
        }

        case ShaderUtil.ShaderPropertyType.TexEnv:         // textures
        {
            TextureProperty(aProp, label, false);
            GUILayout.Space(6);
            break;
        }

        case ShaderUtil.ShaderPropertyType.Vector:         // vectors
        {
            VectorProperty(aProp, label);
            break;
        }

        default:
        {
            GUILayout.Label("(unknown prop type for " + label + " ): " + ShaderUtil.GetPropertyType(shader, i));
            break;
        }
        }
    }
예제 #18
0
        private void ShowShaderPropertys(Shader s, Material m)
        {
            string propertyName = string.Empty;

            EditorGUI.BeginChangeCheck();

            for (int i = 0; i < ShaderUtil.GetPropertyCount(s); i++)
            {
                if (!ShaderUtil.IsShaderPropertyHidden(s, i))
                {
                    EditorGUILayout.BeginHorizontal();

                    propertyName = ShaderUtil.GetPropertyName(s, i);
                    MaterialProperty materialProperty = MaterialEditor.GetMaterialProperty(new UnityEngine.Object[] { m }, propertyName);

                    EditorGUILayout.LabelField(ShaderUtil.GetPropertyDescription(s, i), GUILayout.Width(150));


                    switch (ShaderUtil.GetPropertyType(s, i))
                    {
                    case ShaderUtil.ShaderPropertyType.Color:

                        Color c = EditorGUILayout.ColorField(m.GetColor(propertyName));
                        m.SetColor(propertyName, c);
                        break;

                    case ShaderUtil.ShaderPropertyType.Float:
                        float f = EditorGUILayout.FloatField(m.GetFloat(propertyName));
                        m.SetFloat(propertyName, f);
                        break;

                    case ShaderUtil.ShaderPropertyType.Range:
                        float min = ShaderUtil.GetRangeLimits(s, i, 1);
                        float max = ShaderUtil.GetRangeLimits(s, i, 2);
                        float r   = EditorGUILayout.Slider(m.GetFloat(propertyName), min, max);
                        m.SetFloat(propertyName, r);
                        break;

                    case ShaderUtil.ShaderPropertyType.TexEnv:
                        EditorGUILayout.BeginVertical();
                        Texture2D tex       = (Texture2D)EditorGUILayout.ObjectField(m.GetTexture(propertyName), typeof(Texture2D), false);
                        Vector2   texOffset = EditorGUILayout.Vector2Field("TextureOffset", m.GetTextureOffset(propertyName));
                        Vector2   texScale  = EditorGUILayout.Vector2Field("TextureOffset", m.GetTextureScale(propertyName));
                        EditorGUILayout.EndVertical();
                        m.SetTexture(propertyName, tex);
                        m.SetTextureOffset(propertyName, texOffset);
                        m.SetTextureScale(propertyName, texScale);
                        break;

                    case ShaderUtil.ShaderPropertyType.Vector:
                        Vector4 v = EditorGUILayout.Vector4Field("", m.GetVector(propertyName));
                        m.SetVector(propertyName, v);
                        break;
                    }
                    EditorGUILayout.EndHorizontal();
                }
            }
            if (EditorGUI.EndChangeCheck())
            {
                serializedObject.ApplyModifiedProperties();
            }
        }
            void DrawProperty(int materialCount)
            {
                var rect = EditorGUILayout.GetControlRect();
                rect = EditorGUI.PrefixLabel(rect, EditorGUIKit.TempContent("Property"));

                if (!string.IsNullOrEmpty(target.propertyName))
                {
                    _builder.Append(target.propertyName);
                    _builder.Append(" (");
                    _builder.Append(target._propertyType);
                    _builder.Append(')');
                }

                if (GUI.Button(rect, _builder.ToString(), EditorStyles.layerMaskField))
                {
                    var properties = new HashSet<Property>();
                    var menu = new GenericMenu();

                    for (int i = 0; i < materialCount; i++)
                    {
                        if (target.IsMaterialSelected(i) && _materials[i] && _materials[i].shader)
                        {
                            var shader = _materials[i].shader;
                            int count = ShaderUtil.GetPropertyCount(shader);

                            for (int idx = 0; idx < count; idx++)
                            {
                                if (!ShaderUtil.IsShaderPropertyHidden(shader, idx))
                                {
                                    var prop = new Property
                                    {
                                        name = ShaderUtil.GetPropertyName(shader, idx),
                                        type = ShaderUtil.GetPropertyType(shader, idx)
                                    };

                                    if (properties.Contains(prop)) continue;
                                    properties.Add(prop);

                                    string description = ShaderUtil.GetPropertyDescription(shader, idx);

                                    if (prop.type == ShaderUtil.ShaderPropertyType.TexEnv)
                                    {
                                        prop.name += "_ST";
                                        prop.type = ShaderUtil.ShaderPropertyType.Vector;
                                        description += " Scale and Offest";
                                    }

                                    _builder.Clear();
                                    _builder.Append(prop.name);
                                    _builder.Append(" (\"");
                                    _builder.Append(description);
                                    _builder.Append("\", ");
                                    _builder.Append(prop.type);
                                    _builder.Append(')');

                                    menu.AddItem(new GUIContent(_builder.ToString()),
                                        target._propertyName == prop.name && target._propertyType == (Type)(int)prop.type,
                                        () =>
                                        {
                                            Undo.RecordObject(target, "Select Property");
                                            Type oldType = target.propertyType;
                                            target.SetProperty(prop.name, (Type)(int)prop.type);

                                            if (oldType != target.propertyType)
                                            {
                                                if (target.propertyType == Type.Color)
                                                    target.from = target.to = Color.white;

                                                if (target.propertyType == Type.Float || target.propertyType == Type.Range)
                                                    target.from.x = target.to.x = 1f;

                                                if (target.propertyType == Type.Vector)
                                                {
                                                    if (prop.name.EndsWith("_ST"))
                                                        target.from = target.to = new Vector4(1, 1, 0, 0);
                                                    else
                                                        target.from = target.to = new Vector4(1, 1, 1, 1);
                                                }
                                            }
                                        });

                                    _builder.Clear();
                                }
                            }
                        }
                    }

                    if (properties.Count == 0) menu.AddItem(new GUIContent("(No Valid Property)"), false, () => { });

                    menu.DropDown(rect);
                }

                _builder.Clear();
            }
예제 #20
0
파일: UVPreview.cs 프로젝트: asmboom/forge
		void OnGUI() {
			// Initialize objects
			if (IconLoader == null) IconLoader = new IconLoader();
			if (BGTex == null) {
				BGTex = new Texture2D(1, 1);
				BGTex.hideFlags = HideFlags.HideAndDontSave;
				BGTex.SetPixel(0, 0, BGColor);
				BGTex.Apply();
			}
			if (VertexStyle == null) {
				VertexStyle = MakeStyle(Color.cyan, 0f);
				FaceStyle = MakeStyle(Color.red, 0f);
				ShadowStyle = MakeStyle(Color.black, 1f);
			}

			// Total canvas
			Canvas = new Rect(0f, 0f, position.width * 4 * Zoom, position.height * 4 * Zoom);

			// Scroll view
			Rect scrollViewRect = new Rect(0, 0, position.width, position.height);
			ScrollPoint = GUI.BeginScrollView(scrollViewRect, ScrollPoint, Canvas);
			bool needsRepaint = false;

			// Zoom with the mouse wheel
			if (Event.current.type == EventType.ScrollWheel) {
				Zoom += -Event.current.delta.y / 50;
				if (Zoom < 0.1f) Zoom = 0.1f;
				if (Zoom > 1f) Zoom = 1f;
				needsRepaint = true;
				Event.current.Use();
			}

			// Draw background
			GUI.DrawTexture(new Rect(ScrollPoint.x, ScrollPoint.y, scrollViewRect.width, scrollViewRect.height), BGTex);

			// Texture Inputs
			GameObject go = Selection.activeObject as GameObject;
			List<string> texInputsList = new List<string>();
			texInputsList.Add("-");
			Texture texPreview = null;
			if (go != null) {
				Renderer renderer = go.GetComponent<MeshRenderer>();
				if (renderer != null) {
					Material mat = renderer.sharedMaterial;
					if (mat != null) {
						for (int p = 0; p < ShaderUtil.GetPropertyCount(mat.shader); p++) {
							if (ShaderUtil.GetPropertyType(mat.shader, p) == ShaderUtil.ShaderPropertyType.TexEnv) {
								if (TexInput > 0 && TexInput == texInputsList.Count) {
									texPreview = mat.GetTexture(ShaderUtil.GetPropertyName(mat.shader, p));
								}
								texInputsList.Add(ShaderUtil.GetPropertyDescription(mat.shader, p));
							}
						}
					}
				}
			}

			// Draw UV Canvas
			Rect uvCanvas = new Rect(CanvasMargin, CanvasMarginTop, position.width * 4 * Zoom - CanvasMargin * 2, position.height * 4 * Zoom - (CanvasMarginTop + CanvasMargin));
			if (texPreview) {
				GUI.DrawTexture(uvCanvas, texPreview);
			} else {
				Handles.color = UVBorderColor;
				Handles.DrawPolyLine(new Vector3[] {
					new Vector3(uvCanvas.x, uvCanvas.y),
					new Vector3(uvCanvas.x + uvCanvas.width, uvCanvas.y),
					new Vector3(uvCanvas.x + uvCanvas.width, uvCanvas.y + uvCanvas.height),
					new Vector3(uvCanvas.x, uvCanvas.height + uvCanvas.y),
					new Vector3(uvCanvas.x, uvCanvas.y)
				});
			}

			// UI
			UVSet = EditorGUI.Popup(new Rect(10f, 12f, 100f, 30f), UVSet, new string[] { "uv0", "uv1" });
			DisplayVertices = GUI.Toggle(new Rect(120f, 10f, 30f, 20f), DisplayVertices, IconLoader.Icons["vertex"], "button");
			DisplayVertexIndices = GUI.Toggle(new Rect(155f, 10f, 30f, 20f), DisplayVertexIndices, IconLoader.Icons["vertexIndex"], "button");
			DisplayEdges = GUI.Toggle(new Rect(190f, 10f, 30f, 20f), DisplayEdges, IconLoader.Icons["face"], "button");
			DisplayFaces = GUI.Toggle(new Rect(225f, 10f, 30f, 20f), DisplayFaces, IconLoader.Icons["faceIndex"], "button");
			TexInput = EditorGUI.Popup(new Rect(260f, 12f, 100f, 30f), TexInput, texInputsList.ToArray());

			// Mesh data
			if (go != null) {
				var meshFilter = go.GetComponent<MeshFilter>();
				if (meshFilter != null) {

					Mesh mesh = meshFilter.sharedMesh;
					Vector2[] uvSet = UVSet == 0 ? mesh.uv : mesh.uv2;

					// Triangles
					for (int i = 0; i < mesh.triangles.Length; i += 3) {

						if (uvSet.Length == 0) {
							break;
						}

						Vector3[] verts = new Vector3[3];
						for (int n = 0; n < 3; n++) {
							verts[n] = new Vector3(
								uvCanvas.x + uvSet[mesh.triangles[i + n]].x * uvCanvas.width,
								uvCanvas.y + (1 - uvSet[mesh.triangles[i + n]].y) * uvCanvas.height,
								0f);
						}

						// Draw edges
						if (DisplayEdges) {
							Handles.color = Color.white;
							Handles.DrawPolyLine(new Vector3[] { verts[0], verts[1], verts[2], verts[0] });
						}

						// Draw face indices
						if (DisplayFaces) {
							Handles.color = Color.red;
							Vector3 mid = (verts[0] + verts[1] + verts[2]) / 3;
							mid.y -= 10f;
							DrawLabel(mid.x, mid.y, (i / 3).ToString(), FaceStyle);
						}
					}

					// Vertices
					for (int i = 0; i < uvSet.Length; i++) {
						Vector2 uv = uvSet[i];
						Vector3 point = new Vector3(uvCanvas.width * uv.x + uvCanvas.x, uvCanvas.height * (1 - uv.y) + uvCanvas.y, 0);

						// Draw vertex indices
						if (DisplayVertexIndices) {
							DrawLabel(point.x, point.y, i.ToString(), VertexStyle);
						}

						// Draw vertices
						if (DisplayVertices) {
							float thickness = 2f;
							Handles.color = Color.cyan;
							Handles.DrawSolidRectangleWithOutline(new Vector3[] {
								new Vector3(point.x - thickness, point.y - thickness, 0),
								new Vector3(point.x - thickness, point.y + thickness, 0),
								new Vector3(point.x + thickness, point.y + thickness, 0),
								new Vector3(point.x + thickness, point.y - thickness, 0)
							}, Color.white, Color.white);
						}
					}

				}
			}

			// Handle left mouse button events
			if (Event.current.button == 0) {

				// MouseDown
				if (Event.current.type == EventType.MouseDown && !_isDragging) {
					_isDragging = true;
				}

				// MouseDrag
				if (Event.current.type == EventType.MouseDrag && _isDragging) {
					if (Event.current.delta.magnitude > 0) {
						ScrollPoint.x += -Event.current.delta.x;
						ScrollPoint.y += -Event.current.delta.y;
						needsRepaint = true;
					}
				}

				// MouseUp
				if (Event.current.type == EventType.MouseUp) {
					_isDragging = false;
				}

			} // Left mouse down/drag/up

			// Right Click
			if (Event.current.button == 1 && Event.current.type == EventType.MouseUp) {
				var menu = new GenericMenu();
				menu.AddItem(new GUIContent("WIP"), false, MenuAction, null);
				menu.ShowAsContext();
			}


			if (needsRepaint) {
				Repaint();
			}

			GUI.EndScrollView();

		} // OnGUI
        public override sealed void OnInspectorGUI()
        {
            base.OnInspectorGUI();

            serializedObject.Update();

            EditorGUILayout.PropertyField(refMaterial, refMaterialLabel);

            if (refMaterial.objectReferenceValue == null)
            {
                EditorGUILayout.PropertyField(renderer);
                EditorGUILayout.PropertyField(useSharedMaterial);

                if (target.renderer)
                {
                    EditorGUI.BeginChangeCheck();
                    EditorGUILayout.PropertyField(materialIndex);
                    if (EditorGUI.EndChangeCheck())
                    {
                        materialIndex.intValue = Mathf.Clamp(materialIndex.intValue, 0, target.renderer.sharedMaterials.Length - 1);
                    }
                }
            }

            serializedObject.ApplyModifiedProperties();

            EditorGUILayout.Space();

            material = target.material;
            if (material)
            {
                // (重新)建立属性表
                if (shader != material.shader)
                {
                    shader = material.shader;
                    int count = ShaderUtil.GetPropertyCount(shader);

                    List <int> indexList = new List <int>(count);
                    for (int i = 0; i < count; i++)
                    {
                        if (ShaderUtil.GetPropertyType(shader, i) == target.propertyType)
                        {
                            indexList.Add(i);
                        }
                    }

                    propertyIndex       = indexList.ToArray();
                    propertyName        = new string[propertyIndex.Length];
                    propertyDescription = new string[propertyIndex.Length];
                    for (int i = 0; i < propertyIndex.Length; i++)
                    {
                        propertyName[i]        = ShaderUtil.GetPropertyName(shader, propertyIndex[i]);
                        propertyDescription[i] = ShaderUtil.GetPropertyDescription(shader, propertyIndex[i]);
                    }

                    if (propertyName.Length > 0)
                    {
                        menuIndex = System.Array.IndexOf(propertyName, target.propertyName);
                        if (menuIndex < 0)
                        {
                            Undo.RecordObject(target, undoString);
                            target.propertyName = propertyName[menuIndex = 0];
                            EditorUtility.SetDirty(target);
                        }
                    }
                }

                // 绘制属性和子类参数
                if (propertyName.Length > 0)
                {
                    DrawIntPopupLayout(menuIndex, propertyDescription, value => target.propertyName = propertyName[menuIndex = value], "Property");
                    OnDrawSubclass();
                    return;
                }
            }

            EditorGUILayout.LabelField("* No material or available property.");
        }
예제 #22
0
        public static void DRAW_PANEL()
        {
            bool GUI_TEMP  = GUI.enabled;
            int  CART_temp = KP.MAT_CART_INDEX;
            int  FAM_temp  = KP.MAT_FAM_INDEX;
            int  TYP_temp  = KP.MAT_TYPE_INDEX;

            if (ME_LIST == null)
            {
                ME_LIST = new List <MaterialEditor>(4);
                Material       m = new Material(Shader.Find("Diffuse"));
                MaterialEditor me;
                for (int i = 0, n = 5; i < n; i++)
                {
                    me = Editor.CreateEditor(m) as MaterialEditor;

                    me.SetTexture("_mainTexture", kLibary.LoadBitmap("create", 25, 25));
                    ME_LIST.Add(me);
                }
            }
            //GUI.enabled = (_selection != null);
            // GUILayoutOption glo = {  };
            EditorGUILayout.BeginVertical(); //----------------------------------------------------------> Begin Vertical
            EditorGUI.BeginChangeCheck();
            GUILayout.Space(2);
            // Material operation and selection slots
            KP.FOLD_mSele = EditorGUILayout.Foldout(KP.FOLD_mSele, "Material Operation ");
            if (KP.FOLD_mSele)
            {
                KP.MAT_SELE_INDEX = GUILayout.Toolbar(KP.MAT_SELE_INDEX, new string[] { "Get", "Set", "2file", "2data" });
                //KP.MAT_SELE_INDEX = GUILayout.Toolbar(KP.MAT_SELE_INDEX, new string[] { "MAT I", "MAT II", "MAT III" });
                EditorGUILayout.BeginHorizontal();

                for (int i = 0, n = 4; i < n; i++)
                {
                    GUILayout.BeginVertical();
                    GUILayout.Box(new GUIContent("Slot " + i), GUILayout.ExpandWidth(true), GUILayout.Height(22));
                    // Debug.Log(ME_LIST[i]);
                    MaterialEditor med = ME_LIST[i];

                    if (med && Event.current.type == EventType.layout)
                    {
                        med.OnPreviewGUI(GUILayoutUtility.GetRect(45, 45), EditorStyles.whiteLabel);
                    }
                    GUILayout.EndVertical();
                    GUILayout.Space(2);
                }

                EditorGUILayout.EndHorizontal();
            }
            KP.FOLD_object = EditorGUILayout.Foldout(KP.FOLD_object, "Shader Family ");
            if (KP.FOLD_object)
            {
                // Material category
                KP.MAT_CART_INDEX = EditorGUILayout.Popup(KP.MAT_CART_INDEX, kShaderLab.CATEGORY);
                GUILayout.Space(2);
                // Material family
                KP.MAT_FAM_INDEX = GUILayout.SelectionGrid(KP.MAT_FAM_INDEX, kShaderLab.FAMILY, 2, KP_Style.grid(), GUILayout.MinWidth(100));
            }
            // Material type
            KP.FOLD_type = EditorGUILayout.Foldout(KP.FOLD_type, "Shader Type ");
            if (KP.FOLD_type)
            {
                //sc1 = EditorGUILayout.BeginScrollView(sc1, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true), GUILayout.MaxHeight(250), GUILayout.MinHeight(20));
                KP.MAT_TYPE_INDEX = GUILayout.SelectionGrid(KP.MAT_TYPE_INDEX, kShaderLab.GetShaderList(KP.MAT_FAM_INDEX), 1, KP_Style.grid());
                //EditorGUILayout.EndScrollView();
            }
            // Material NAME
            KP.FOLD_name = EditorGUILayout.Foldout(KP.FOLD_name, "Material Name");
            if (KP.FOLD_name)
            {
                KP._meshName = EditorGUILayout.TextField(KP._meshName, KP_Style.tf_input_center());
            }
            // Material shader properties
            KP.FOLD_para = EditorGUILayout.Foldout(KP.FOLD_para, "Material Parameters");
            if (KP.FOLD_para)
            {
                Shader s = (KP._sMaterial != null) ? kShaderLab.GetShader(KP.MAT_CART_INDEX, KP.MAT_FAM_INDEX, KP.MAT_TYPE_INDEX) : null;
                if (s != null)
                {
                    //Debug.Log(s.name);
                    //EditorGUILayout.LabelField("sName : " + s.name);
                    int n = ShaderUtil.GetPropertyCount(s);
                    for (int i = 0; i < n; i++)
                    {
                        // foreach property in current selected

                        string label        = ShaderUtil.GetPropertyDescription(s, i);
                        string propertyName = ShaderUtil.GetPropertyName(s, i);

                        //Debug.Log(ShaderUtil.GetPropertyType(s, i));
                        switch (ShaderUtil.GetPropertyType(s, i))
                        {
                        case ShaderUtil.ShaderPropertyType.Range:     // float ranges
                        {
                            //GUILayout.BeginHorizontal();
                            float v2 = ShaderUtil.GetRangeLimits(s, i, 1);
                            float v3 = ShaderUtil.GetRangeLimits(s, i, 2);

                            RangeProperty(propertyName, label, v2, v3);

                            //GUILayout.EndHorizontal();
                            break;
                        }

                        case ShaderUtil.ShaderPropertyType.Float:     // floats
                            Debug.Log(label);
                            FloatProperty(propertyName, label);
                            break;

                        case ShaderUtil.ShaderPropertyType.Color:     // colors
                        {
                            ColorProperty(propertyName, label);
                            break;
                        }

                        case ShaderUtil.ShaderPropertyType.TexEnv:     // textures
                        {
                            ShaderUtil.ShaderPropertyTexDim desiredTexdim = ShaderUtil.GetTexDim(s, i);
                            TextureProperty(propertyName, label, desiredTexdim);
                            //GUILayout.Space(6);
                            break;
                        }

                        case ShaderUtil.ShaderPropertyType.Vector:     // vectors
                        {
                            Debug.Log(label);
                            //VectorProperty(propertyName, label);
                            break;
                        }

                        default:
                        {
                            GUILayout.Label("ARGH" + label + " : " + ShaderUtil.GetPropertyType(s, i));
                            break;
                        }
                        }
                    }
                }
            }
            if (EditorGUI.EndChangeCheck())
            {
                Debug.Log("REPAINT GUI");
                if (CART_temp != KP.MAT_CART_INDEX ||
                    FAM_temp != KP.MAT_FAM_INDEX ||
                    TYP_temp != KP.MAT_TYPE_INDEX)
                {
                    if (KP.MAT_SELE_INDEX != -1)
                    {
                        KP.Reset_material();
                    }
                }
                if (KP.MAT_SELE_INDEX != -1)
                {
                    switch (KP.MAT_SELE_INDEX)
                    {
                    case 0: KP._sMaterial = kSelect.MATERIAL; break;

                    case 1: kSelect.MATERIAL = KP._sMaterial; break;

                    case 2: break;

                    case 3: break;
                    }
                    KP.MAT_SELE_INDEX = -1;
                }
                kPoly2Tool.instance.Repaint();
            }
            EditorGUILayout.EndVertical(); //------------------------------------------------------------> End Vertical
            //GUILayout.Space(10);
            //GUILayout.EndHorizontal();
            GUI.enabled = GUI_TEMP;
        }
예제 #23
0
        public override void OnInspectorGUI()
        {
            //base.OnInspectorGUI ();

            ChangeMaterialProperty t = target as ChangeMaterialProperty;

            EditorGUI.BeginChangeCheck();
            Undo.RecordObject(t, "Change value");

            Shader        s            = t.GetComponent <Renderer>().sharedMaterial.shader;
            List <string> descriptions = new List <string>();
            List <int>    indices      = new List <int>();

            for (int i = 0; i < ShaderUtil.GetPropertyCount(s); i++)
            {
                ShaderUtil.ShaderPropertyType type = ShaderUtil.GetPropertyType(s, i);
                if (type == ShaderUtil.ShaderPropertyType.Color || type == ShaderUtil.ShaderPropertyType.Float || type == ShaderUtil.ShaderPropertyType.Range)
                {
                    descriptions.Add(ShaderUtil.GetPropertyDescription(s, i));
                    indices.Add(i);
                }
            }
            int descriptionsIndex = EditorGUILayout.Popup("Property", indices.IndexOf(t.propertyIndex), descriptions.ToArray());

            if (descriptionsIndex > 0)
            {
                t.propertyIndex       = indices[descriptionsIndex];
                t.stored_propertyName = ShaderUtil.GetPropertyName(s, t.propertyIndex);
                switch (ShaderUtil.GetPropertyType(s, t.propertyIndex))
                {
                case ShaderUtil.ShaderPropertyType.Float:
                case ShaderUtil.ShaderPropertyType.Range:
                    t.stored_propertyType = typeof(float).ToString();
                    break;

                case ShaderUtil.ShaderPropertyType.Color:
                    t.stored_propertyType = typeof(Color).ToString();
                    break;
                }
            }
            else
            {
                t.propertyIndex = 0;
            }

            if (t.propertyIndex >= 0)
            {
                ShaderUtil.ShaderPropertyType type = ShaderUtil.GetPropertyType(s, t.propertyIndex);
                if (type == ShaderUtil.ShaderPropertyType.Float)
                {
                    t.value_float = EditorGUILayout.FloatField("Value", t.value_float);
                }
                else if (type == ShaderUtil.ShaderPropertyType.Range)
                {
                    t.value_float = EditorGUILayout.Slider("Value", t.value_float, ShaderUtil.GetRangeLimits(s, t.propertyIndex, 1), ShaderUtil.GetRangeLimits(s, t.propertyIndex, 2));
                }
                else if (type == ShaderUtil.ShaderPropertyType.Color)
                {
                    t.value_color = EditorGUILayout.ColorField("Color", t.value_color);
                }
            }

            if (EditorGUI.EndChangeCheck())
            {
                EditorUtility.SetDirty(t);
            }
        }
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            lastWidth = position.width;

            var initialPosition = position;

            var labelWidth = EditorGUIUtility.labelWidth;

            position.y += EditorGUIUtility.singleLineHeight * 0.2f;

            position.height = EditorGUIUtility.singleLineHeight;
            var rendererPosition = position;

            rendererPosition.width = position.width / 2;
            Shift(ref rendererPosition, false);
            var renderer = property.FindPropertyRelative("Renderer");

            EditorGUI.PropertyField(rendererPosition, renderer, GUIContent.none);

            var menu = new GenericMenu();

            var useCutoutProperty = property.FindPropertyRelative("CutoutDescriptionType");

            var cutoutIsInUse = useCutoutProperty.intValue != (int)CutoutDescriptionType.None;

            menu.AddItem(new GUIContent("none"), !cutoutIsInUse, () =>
            {
                useCutoutProperty.intValue = (int)CutoutDescriptionType.None;
                useCutoutProperty.serializedObject.ApplyModifiedProperties();
            });

            var textureNameProperty = property.FindPropertyRelative("cutoutTextureName");

            var rendererReference = renderer.objectReferenceValue as Renderer;
            var referenceName     = "none";
            var usingCutout       = cutoutIsInUse && rendererReference != null;

            if (rendererReference != null)
            {
                var material = rendererReference.sharedMaterial;
                if (material != null)
                {
                    var propertiesCount = ShaderUtil.GetPropertyCount(material.shader);
                    for (var index = 0; index < propertiesCount; index++)
                    {
                        var propertyType = ShaderUtil.GetPropertyType(material.shader, index);
                        if (propertyType != ShaderUtil.ShaderPropertyType.TexEnv)
                        {
                            continue;
                        }

                        var propertyName = ShaderUtil.GetPropertyName(material.shader, index);
                        var equals       = propertyName == textureNameProperty.stringValue;
                        if (equals)
                        {
                            referenceName = ShaderUtil.GetPropertyDescription(material.shader, index);
                        }

                        menu.AddItem(new GUIContent(ShaderUtil.GetPropertyDescription(material.shader, index)), equals && usingCutout, () =>
                        {
                            textureNameProperty.stringValue = propertyName;
                            useCutoutProperty.intValue      = (int)CutoutDescriptionType.Hash;
                            textureNameProperty.serializedObject.ApplyModifiedProperties();
                        });
                    }
                }
            }

            var cutoutPosition = position;

            cutoutPosition.x      = rendererPosition.x + rendererPosition.width;
            cutoutPosition.width -= rendererPosition.width;
            Shift(ref cutoutPosition, true);

            var sourceLable = usingCutout ? referenceName : "none";

            if (EditorGUI.DropdownButton(cutoutPosition, new GUIContent("Cutout source: " + sourceLable), FocusType.Passive))
            {
                menu.ShowAsContext();
            }

            var drawingPosition = position;

            EditorGUIUtility.labelWidth = 160;
            drawingPosition.y          += EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing;
            var forceRecalculateBoundsDrawingPosition = initialPosition;

            forceRecalculateBoundsDrawingPosition.y     += EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing * 3.0f;
            forceRecalculateBoundsDrawingPosition.width  = initialPosition.width;
            forceRecalculateBoundsDrawingPosition.height = EditorGUIUtility.singleLineHeight;

            EditorGUI.PropertyField(forceRecalculateBoundsDrawingPosition, property.FindPropertyRelative("ForceRecalculateBounds"));

            forceRecalculateBoundsDrawingPosition.width /= 2;
            forceRecalculateBoundsDrawingPosition.x     += forceRecalculateBoundsDrawingPosition.width;

            EditorGUIUtility.labelWidth = 80;
            Shift(ref forceRecalculateBoundsDrawingPosition, true);
            EditorGUI.PropertyField(forceRecalculateBoundsDrawingPosition, property.FindPropertyRelative("cutoutTextureIndex"), new GUIContent("Texture index"));

            EditorGUIUtility.labelWidth = labelWidth;

            if (usingCutout || rendererReference is SpriteRenderer)
            {
                drawingPosition.y += EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing;

                EditorGUI.PropertyField(drawingPosition, property.FindPropertyRelative("CutoutThreshold"));
            }
            else
            {
                var isDilateRenderingMode      = property.FindPropertyRelative("DilateRenderingMode").intValue == (int)DilateRenderMode.EdgeShift;
                var appropriateToUseEdgeDilate = renderer.objectReferenceValue != null && !(renderer.objectReferenceValue as Renderer).gameObject.isStatic;
                if (appropriateToUseEdgeDilate)
                {
                    drawingPosition.y += EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing;
                }

                var modeDrawingPosition = drawingPosition;
                modeDrawingPosition.width /= 2;

                if (appropriateToUseEdgeDilate)
                {
                    Shift(ref modeDrawingPosition, false);
                    EditorGUI.LabelField(modeDrawingPosition, property.FindPropertyRelative("DilateRenderingMode").displayName);

                    modeDrawingPosition.x += modeDrawingPosition.width;
                    Shift(ref modeDrawingPosition, true);

                    var initialColor = GUI.color;
                    if (isDilateRenderingMode && PlayerSettings.stripUnusedMeshComponents)
                    {
                        GUI.color = Color.red;
                    }

                    EditorGUI.PropertyField(modeDrawingPosition, property.FindPropertyRelative("DilateRenderingMode"), GUIContent.none);

                    GUI.color = initialColor;
                }

                if (isDilateRenderingMode && appropriateToUseEdgeDilate)
                {
                    drawingPosition.y += EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing;

                    if (PlayerSettings.stripUnusedMeshComponents)
                    {
                        var helpBoxPosition = drawingPosition;

                        var buttonStart = EditorStyles.helpBox.CalcHeight(errorContent, lastWidth - 60) + EditorGUIUtility.standardVerticalSpacing;
                        helpBoxPosition.height = buttonStart + EditorGUIUtility.singleLineHeight * 2.0f;

                        EditorGUI.HelpBox(helpBoxPosition, errorContent.text, MessageType.Error);

                        var buttonPosition = drawingPosition;
                        buttonPosition.y      = helpBoxPosition.y + buttonStart + EditorGUIUtility.singleLineHeight * 0.5f;
                        buttonPosition.width -= EditorGUIUtility.singleLineHeight * 2.0f;
                        buttonPosition.x     += EditorGUIUtility.singleLineHeight;
                        if (GUI.Button(buttonPosition, "Disable 'Optimize mesh data' option"))
                        {
                            PlayerSettings.stripUnusedMeshComponents = false;
                        }

                        drawingPosition.y += helpBoxPosition.height + EditorGUIUtility.singleLineHeight;
                    }

                    var shiftDrawingPosition = drawingPosition;
                    shiftDrawingPosition.width /= 2;

                    var parentRenderStyle = property.serializedObject.FindProperty("renderStyle");

                    if (parentRenderStyle.intValue == (int)RenderStyle.Single)
                    {
                        EditorGUI.LabelField(shiftDrawingPosition, "Edge shift");

                        shiftDrawingPosition.x += shiftDrawingPosition.width;
                        Shift(ref shiftDrawingPosition, true);

                        EditorGUI.PropertyField(shiftDrawingPosition, property.FindPropertyRelative("edgeDilateAmount"), GUIContent.none);
                    }
                    else
                    {
                        EditorGUIUtility.labelWidth = 80;

                        Shift(ref shiftDrawingPosition, false);
                        EditorGUI.PropertyField(shiftDrawingPosition, property.FindPropertyRelative("frontEdgeDilateAmount"), new GUIContent("Front dilate"));

                        shiftDrawingPosition.x += shiftDrawingPosition.width;
                        Shift(ref shiftDrawingPosition, true);

                        EditorGUI.PropertyField(shiftDrawingPosition, property.FindPropertyRelative("backEdgeDilateAmount"), new GUIContent("Back dilate"));

                        EditorGUIUtility.labelWidth = labelWidth;
                    }
                }
            }

            drawingPosition.y += EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing;

            var linePosition = drawingPosition;

            linePosition.width /= 2;
            Shift(ref linePosition, false);

            var cullPosition = linePosition;

            cullPosition.width /= 2;
            EditorGUI.LabelField(cullPosition, new GUIContent("Cull mode"));
            cullPosition.x += cullPosition.width;

            EditorGUI.PropertyField(cullPosition, property.FindPropertyRelative("CullMode"), GUIContent.none);

            linePosition.x += linePosition.width;
            Shift(ref linePosition, true);

            var submeshIndex = property.FindPropertyRelative("SubmeshIndex");

            EditorGUIUtility.labelWidth = 90;

            EditorGUI.PropertyField(linePosition, submeshIndex);
            if (submeshIndex.intValue < 0)
            {
                submeshIndex.intValue = 0;
            }

            EditorGUIUtility.labelWidth = labelWidth;

            property.serializedObject.ApplyModifiedProperties();
        }
예제 #25
0
    private void ShaderPropertyImpl(Material owner, Shader shader, int propertyIndex)
    {
        int    i            = propertyIndex;
        string label        = ShaderUtil.GetPropertyDescription(shader, i);
        string propertyName = ShaderUtil.GetPropertyName(shader, i);

        switch (ShaderUtil.GetPropertyType(shader, i))
        {
        case ShaderUtil.ShaderPropertyType.Range:     // float ranges
        {
            GUILayout.BeginHorizontal();
            float v2 = ShaderUtil.GetRangeLimits(shader, i, 1);
            float v3 = ShaderUtil.GetRangeLimits(shader, i, 2);
            RangeProperty(propertyName, label, v2, v3);
            GUILayout.EndHorizontal();

            break;
        }

        case ShaderUtil.ShaderPropertyType.Float:     // floats
        {
            FloatProperty(propertyName, label);
            break;
        }

        case ShaderUtil.ShaderPropertyType.Color:     // colors
        {
            ColorProperty(propertyName, label);
            break;
        }

        case ShaderUtil.ShaderPropertyType.TexEnv:     // textures
        {
            var fxTextureType = FXMaterialHelper.GetFXTextureType(ShaderUtil.GetPropertyDescription(shader, i));
            if (fxTextureType != null)
            {
                if (!(Selection.activeObject is GameObject))
                {
                    if (DisplayHelpTexts)
                    {
                        GUILayout.Label(label);
                        EditorGUILayout.HelpBox(label + " is a FXTexture, you can use a FXTextureAssigner or a FXPostProcess component to set this Texture.", MessageType.Info);
                    }
                    else
                    {
                        break;
                    }
                }
                else
                {
                    var             match              = Regex.Match(label, @"(.*)\(\w*\).*", RegexOptions.IgnoreCase);
                    var             description        = match.Groups[1].Value.Trim();
                    var             name               = ShaderUtil.GetPropertyName(shader, i);
                    FXRenderTexture oldFxRenderTexture = GetRenderTextureForProperty(owner, shader, name);
                    var             newFxRenderTexture = (FXRenderTexture)EditorGUILayout.ObjectField(description + " (FXRenderTexture)", oldFxRenderTexture, typeof(FXRenderTexture), false);
                    SetRenderTextureForProperty(owner, shader, name, description, newFxRenderTexture);
                }
            }
            else
            {
                ShaderUtil.ShaderPropertyTexDim desiredTexdim = ShaderUtil.GetTexDim(shader, i);
                TextureProperty(propertyName, label, desiredTexdim);
            }

            GUILayout.Space(6);
            break;
        }

        case ShaderUtil.ShaderPropertyType.Vector:     // vectors
        {
            VectorProperty(propertyName, label);
            break;
        }

        default:
        {
            GUILayout.Label("Unknown " + label + " : " + ShaderUtil.GetPropertyType(shader, i));
            break;
        }
        }
    }
예제 #26
0
        private static void _Create(Shader shader, string bundleName, string variantName)
        {
            if (shader == null)
            {
                throw new System.ArgumentNullException("shader");
            }

            int propertyCount = ShaderUtil.GetPropertyCount(shader);

            RuntimeShaderInfo shaderInfo = new RuntimeShaderInfo();

            shaderInfo.Name = shader.name;
            if (!shader.HasMappedInstanceID())
            {
                //bool create = EditorUtility.DisplayDialog("RuntimeShaderInfo Generator", "Unable to create RuntimeShaderInfo. Please Create or Update ResourceMap", "Create", "Cancel");
                //if (create)
                //{
                //    ResourceMapGen.CreateResourceMap(true);
                //}

                return;
            }

            shaderInfo.InstanceId           = shader.GetMappedInstanceID();
            shaderInfo.PropertyCount        = propertyCount;
            shaderInfo.PropertyDescriptions = new string[propertyCount];
            shaderInfo.PropertyNames        = new string[propertyCount];
            shaderInfo.PropertyRangeLimits  = new RuntimeShaderInfo.RangeLimits[propertyCount];
            shaderInfo.PropertyTexDims      = new TextureDimension[propertyCount];
            shaderInfo.PropertyTypes        = new RTShaderPropertyType[propertyCount];
            shaderInfo.IsHidden             = new bool[propertyCount];

            for (int i = 0; i < propertyCount; ++i)
            {
                shaderInfo.PropertyDescriptions[i] = ShaderUtil.GetPropertyDescription(shader, i);
                shaderInfo.PropertyNames[i]        = ShaderUtil.GetPropertyName(shader, i);
                shaderInfo.PropertyRangeLimits[i]  = new RuntimeShaderInfo.RangeLimits(
                    ShaderUtil.GetRangeLimits(shader, i, 0),
                    ShaderUtil.GetRangeLimits(shader, i, 1),
                    ShaderUtil.GetRangeLimits(shader, i, 2));
                shaderInfo.PropertyTexDims[i] = ShaderUtil.GetTexDim(shader, i);

                RTShaderPropertyType          rtType = RTShaderPropertyType.Unknown;
                ShaderUtil.ShaderPropertyType type   = ShaderUtil.GetPropertyType(shader, i);
                if (m_typeToType.ContainsKey(type))
                {
                    rtType = m_typeToType[type];
                }

                shaderInfo.PropertyTypes[i] = rtType;
                shaderInfo.IsHidden[i]      = ShaderUtil.IsShaderPropertyHidden(shader, i);
            }

            string fullPath = Application.dataPath + RuntimeShaderUtil.GetPath(true);

            Directory.CreateDirectory(fullPath);

            string fileName = RuntimeShaderUtil.GetShaderInfoFileName(shader);

            string path = Path.Combine(fullPath, fileName);

            bool refresh = !File.Exists(path);

            File.WriteAllText(path, JsonUtility.ToJson(shaderInfo));

            if (refresh)
            {
                AssetDatabase.Refresh();
            }
        }