GetVector() public method

Get a named vector value.

public GetVector ( int nameID ) : Vector4
nameID int The name ID of the property retrieved by Shader.PropertyToID.
return Vector4
        protected override void Init()
        {
            if (null == m_target)
            {
                return;
            }
            // end if
            var renderer = m_target.GetComponent <Renderer>();

            if (null != renderer)
            {
                m_Material = renderer.material;
            }
            // end if
            if (null == m_Material)
            {
                return;
            }
            // end if
            if (!string.IsNullOrEmpty(m_property))
            {
                m_beginVector = m_Material.GetVector(m_property);
            }
            else if (-1 != m_propertyID)
            {
                m_beginVector = m_Material.GetVector(m_propertyID);
            } // end if
        }
        protected override void SetMaterialKeywords(UnityEngine.Material material)
        {
            bool applyTintOnTopOfTexture = material.GetFloat("_Waterfall2D_IsApplyTintColorOnTopOfTextureEnabled") == 1f;

            SetKeywordState(material, "Waterfall2D_ApplyTintColorBeforeTexture", !applyTintOnTopOfTexture);

            // Body Keywords
            bool    hasBodyTexture = material.GetTexture("_BodyTexture") != null;
            bool    isBodyTextureAlphaCutoffEnabled          = material.GetInt("_Waterfall2D_IsBodyTextureAlphaCutoffEnabled") == 1;
            bool    isBodyTextureSheetEnabled                = material.GetInt("_Waterfall2D_IsBodyTextureSheetEnabled") == 1;
            bool    isBodyTextureSheetWithLerpEnabled        = material.GetInt("_Waterfall2D_IsBodyTextureSheetWithLerpEnabled") == 1;
            Vector4 bodyTextureTilingModeParameters          = material.GetVector("_BodyTextureTilingParameters");
            bool    isBodyTextureTilingModeSetToStretch      = bodyTextureTilingModeParameters.x == 1f;
            bool    isBodyTextureStretchTilingModeKeepAspect = bodyTextureTilingModeParameters.y == 1f;
            bool    isBodyTextureStretchTilingModeAutoX      = bodyTextureTilingModeParameters.z == 1f;
            bool    hasBodySecondTexture                           = material.GetTexture("_BodySecondTexture") != null;
            bool    isBodySecondTextureSheetEnabled                = material.GetInt("_Waterfall2D_IsBodySecondTextureSheetEnabled") == 1;
            bool    isBodySecondTextureSheetWithLerpEnabled        = material.GetInt("_Waterfall2D_IsBodySecondTextureSheetWithLerpEnabled") == 1;
            Vector4 bodySecondTextureTilingModeParameters          = material.GetVector("_BodySecondTextureTilingParameters");
            bool    isBodySecondTextureTilingModeSetToStretch      = bodySecondTextureTilingModeParameters.x == 1f;
            bool    isBodySecondTextureStretchTilingModeKeepAspect = bodySecondTextureTilingModeParameters.y == 1f;
            bool    isBodySecondTextureStretchTilingModeAutoX      = bodySecondTextureTilingModeParameters.z == 1f;

            SetKeywordState(material, "Waterfall2D_BodyTexture", hasBodyTexture && !isBodyTextureSheetEnabled && !(isBodyTextureSheetEnabled && isBodyTextureSheetWithLerpEnabled));
            SetKeywordState(material, "Waterfall2D_BodyTextureSheet", hasBodyTexture && isBodyTextureSheetEnabled & !isBodyTextureSheetWithLerpEnabled);
            SetKeywordState(material, "Waterfall2D_BodyTextureSheetWithLerp", hasBodyTexture && isBodyTextureSheetEnabled & isBodyTextureSheetWithLerpEnabled);
            SetKeywordState(material, "Waterfall2D_BodyTextureStretch", hasBodyTexture && isBodyTextureTilingModeSetToStretch && !isBodyTextureStretchTilingModeKeepAspect);
            SetKeywordState(material, "Waterfall2D_BodyTextureStretchAutoX", hasBodyTexture && isBodyTextureTilingModeSetToStretch && isBodyTextureStretchTilingModeKeepAspect && isBodyTextureStretchTilingModeAutoX);
            SetKeywordState(material, "Waterfall2D_BodyTextureStretchAutoY", hasBodyTexture && isBodyTextureTilingModeSetToStretch && isBodyTextureStretchTilingModeKeepAspect && !isBodyTextureStretchTilingModeAutoX);
            SetKeywordState(material, "Waterfall2D_BodySecondTexture", hasBodySecondTexture && !isBodySecondTextureSheetEnabled && !(isBodySecondTextureSheetEnabled && isBodySecondTextureSheetWithLerpEnabled));
            SetKeywordState(material, "Waterfall2D_BodySecondTextureSheet", hasBodySecondTexture && isBodySecondTextureSheetEnabled & !isBodySecondTextureSheetWithLerpEnabled);
            SetKeywordState(material, "Waterfall2D_BodySecondTextureSheetWithLerp", hasBodySecondTexture && isBodySecondTextureSheetEnabled & isBodySecondTextureSheetWithLerpEnabled);
            SetKeywordState(material, "Waterfall2D_BodySecondTextureStretch", hasBodySecondTexture && isBodySecondTextureTilingModeSetToStretch && !isBodySecondTextureStretchTilingModeKeepAspect);
            SetKeywordState(material, "Waterfall2D_BodySecondTextureStretchAutoX", hasBodySecondTexture && isBodySecondTextureTilingModeSetToStretch && isBodySecondTextureStretchTilingModeKeepAspect && isBodySecondTextureStretchTilingModeAutoX);
            SetKeywordState(material, "Waterfall2D_BodySecondTextureStretchAutoY", hasBodySecondTexture && isBodySecondTextureTilingModeSetToStretch && isBodySecondTextureStretchTilingModeKeepAspect && !isBodySecondTextureStretchTilingModeAutoX);
            SetKeywordState(material, "Waterfall2D_BodyColorGradient", material.GetInt("_Waterfall2D_IsColorGradientEnabled") == 1);
            SetKeywordState(material, "Waterfall2D_BodyTextureNoise", hasBodyTexture && (material.GetInt("_Waterfall2D_IsBodyNoiseEnabled") == 1));
            SetKeywordState(material, "Waterfall2D_BodyTextureAlphaCutoff", (hasBodyTexture || hasBodySecondTexture) && isBodyTextureAlphaCutoffEnabled);

            // Top-Bottom / Left-Right Edges
            SetEdgesKeywords(material, "Top", "Bottom");
            SetEdgesKeywords(material, "Left", "Right");

            // Refraction
            bool isRefractionEnabled = material.GetInt("_Waterfall2D_IsRefractionEnabled") == 1;

            SetKeywordState(material, "Waterfall2D_Refraction", isRefractionEnabled);

            // Emission
            bool isEmissionEnabled = material.GetInt("_Waterfall2D_IsEmissionColorEnabled") == 1;

            SetKeywordState(material, "Waterfall2D_ApplyEmissionColor", isEmissionEnabled);
        }
示例#3
0
 static public int GetVector(IntPtr l)
 {
     try{
         if (matchType(l, 2, typeof(System.String)))
         {
             UnityEngine.Material self = (UnityEngine.Material)checkSelf(l);
             System.String        a1;
             checkType(l, 2, out a1);
             UnityEngine.Vector4 ret = self.GetVector(a1);
             pushValue(l, ret);
             return(1);
         }
         else if (matchType(l, 2, typeof(System.Int32)))
         {
             UnityEngine.Material self = (UnityEngine.Material)checkSelf(l);
             System.Int32         a1;
             checkType(l, 2, out a1);
             UnityEngine.Vector4 ret = self.GetVector(a1);
             pushValue(l, ret);
             return(1);
         }
         LuaDLL.luaL_error(l, "No matched override function to call");
         return(0);
     }
     catch (Exception e) {
         LuaDLL.luaL_error(l, e.ToString());
         return(0);
     }
 }
示例#4
0
 static public int GetVector(IntPtr l)
 {
     try {
         int argc = LuaDLL.lua_gettop(l);
         if (matchType(l, argc, 2, typeof(int)))
         {
             UnityEngine.Material self = (UnityEngine.Material)checkSelf(l);
             System.Int32         a1;
             checkType(l, 2, out a1);
             var ret = self.GetVector(a1);
             pushValue(l, true);
             pushValue(l, ret);
             return(2);
         }
         else if (matchType(l, argc, 2, typeof(string)))
         {
             UnityEngine.Material self = (UnityEngine.Material)checkSelf(l);
             System.String        a1;
             checkType(l, 2, out a1);
             var ret = self.GetVector(a1);
             pushValue(l, true);
             pushValue(l, ret);
             return(2);
         }
         pushValue(l, false);
         LuaDLL.lua_pushstring(l, "No matched override function to call");
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
        public static SMaterial FromMaterial(Material mat)
        {
            if (mat == null)
                return null;

            Shader shader = mat.shader;
            if (shader == null)
                return null;

            SMaterial result = new SMaterial();
            result.instanceID = mat.GetInstanceID();
            result.materialName = mat.name;
            result.shaderName = shader.name;

            ShaderProperties.Info info = ShaderPropertyHelper.GetShaderInfo(shader.name);

            if (info != null){
                ComposedByteStream rawData = new ComposedByteStream();

                int iMax = info.propertyNames.Length;
                for (int i = 0; i < iMax; i++)
                {
                    string propName = info.propertyNames[i];
                    switch (info.propertyTypes[i])
                    {
                        case ShaderProperties.PropType.Color:
                            Color color = mat.GetColor(propName);
                            rawData.AddStream(new float[] { color.r, color.g, color.b, color.a });
                            break;

                        case ShaderProperties.PropType.Range:
                        case ShaderProperties.PropType.Float:
                            rawData.AddStream(new float[] { mat.GetFloat(propName) });
                            break;

                        case ShaderProperties.PropType.TexEnv:
                            Texture texture = mat.GetTexture(propName);
                            Vector2 offset = mat.GetTextureOffset(propName);
                            Vector2 scale = mat.GetTextureScale(propName);

                            rawData.AddStream(new int[] { texture != null ? texture.GetInstanceID() : -1 });
                            rawData.AddStream(texture != null ? texture.name : "" );
                            rawData.AddStream(new float[] { offset.x, offset.y });
                            rawData.AddStream(new float[] { scale.x, scale.y });
                            break;

                        case ShaderProperties.PropType.Vector:
                            Vector4 vector = mat.GetVector(propName);
                            rawData.AddStream(new float[] { vector.x, vector.y, vector.z, vector.w });
                            break;
                    }
                }
                result.rawData = rawData.Compose();
                return result;
            } else {
                if (vBug.settings.general.debugMode)
                    Debug.LogError("No shader-info found @" + shader.name);
                return null;
            }
        }
	public List<StoredValue> GetValues(Material m)
	{
		var list = GetShaderProperties(m);
		var output = new List<StoredValue>();
		foreach(var p in list)
		{
			var o = new StoredValue { Property = p };
			output.Add(o);
			switch(p.type)
			{
			case MaterialProperty.PropertyType.color:
				o.Value = m.GetColor(p.name);
				break;
			case MaterialProperty.PropertyType.real:
				o.Value = m.GetFloat(p.name);
				break;
			case MaterialProperty.PropertyType.texture:
				o.Value = m.GetTexture(p.name);
				break;
			case MaterialProperty.PropertyType.vector:
				o.Value = m.GetVector(p.name);
				break;
			case MaterialProperty.PropertyType.textureOffset:
				o.Value = m.GetTextureOffset(p.name);
				break;
			case MaterialProperty.PropertyType.textureScale:
				o.Value = m.GetTextureScale(p.name);
				break;
			case MaterialProperty.PropertyType.matrix:
				o.Value = m.GetMatrix(p.name);
				break;
			}
		}
		return output;
	}
示例#7
0
 public void SetFromToCurrent()
 {
     if (_material = material)
     {
         from = _material.GetVector(propertyID);
     }
 }
示例#8
0
 public override void OnRecord()
 {
     if (_material = material)
     {
         _original = _material.GetVector(propertyID);
     }
 }
        /// <summary>
        /// Copy Shader properties from source to destination material.
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static void CopyMaterialProperties(Material source, Material destination)
        {
            MaterialProperty[] source_prop = MaterialEditor.GetMaterialProperties(new Material[] { source });

            for (int i = 0; i < source_prop.Length; i++)
            {
                int property_ID = Shader.PropertyToID(source_prop[i].name);
                if (destination.HasProperty(property_ID))
                {
                    //Debug.Log(source_prop[i].name + "  Type:" + ShaderUtil.GetPropertyType(source.shader, i));
                    switch (ShaderUtil.GetPropertyType(source.shader, i))
                    {
                        case ShaderUtil.ShaderPropertyType.Color:
                            destination.SetColor(property_ID, source.GetColor(property_ID));                          
                            break;
                        case ShaderUtil.ShaderPropertyType.Float:
                            destination.SetFloat(property_ID, source.GetFloat(property_ID));
                            break;
                        case ShaderUtil.ShaderPropertyType.Range:
                            destination.SetFloat(property_ID, source.GetFloat(property_ID));
                            break;
                        case ShaderUtil.ShaderPropertyType.TexEnv:
                            destination.SetTexture(property_ID, source.GetTexture(property_ID));
                            break;
                        case ShaderUtil.ShaderPropertyType.Vector:
                            destination.SetVector(property_ID, source.GetVector(property_ID));
                            break;
                    }
                }
            }

        }
    static int GetVector(IntPtr L)
    {
        try
        {
            int count = LuaDLL.lua_gettop(L);

            if (count == 2 && TypeChecker.CheckTypes(L, 1, typeof(UnityEngine.Material), typeof(int)))
            {
                UnityEngine.Material obj = (UnityEngine.Material)ToLua.ToObject(L, 1);
                int arg0 = (int)LuaDLL.lua_tonumber(L, 2);
                UnityEngine.Vector4 o = obj.GetVector(arg0);
                ToLua.Push(L, o);
                return(1);
            }
            else if (count == 2 && TypeChecker.CheckTypes(L, 1, typeof(UnityEngine.Material), typeof(string)))
            {
                UnityEngine.Material obj = (UnityEngine.Material)ToLua.ToObject(L, 1);
                string arg0           = ToLua.ToString(L, 2);
                UnityEngine.Vector4 o = obj.GetVector(arg0);
                ToLua.Push(L, o);
                return(1);
            }
            else
            {
                return(LuaDLL.luaL_throw(L, "invalid arguments to method: UnityEngine.Material.GetVector"));
            }
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e));
        }
    }
 static void SetMatrix(Material material)
 {
     var r = material.GetVector("_Euler");
     var q = Quaternion.Euler(r.x, r.y, r.z);
     var m = Matrix4x4.TRS(Vector3.zero, q, Vector3.one);
     material.SetVector("_Rotation1", m.GetRow(0));
     material.SetVector("_Rotation2", m.GetRow(1));
     material.SetVector("_Rotation3", m.GetRow(2));
 }
示例#12
0
        public override void OnTween(float factor)
        {
            if (_material = material)
            {
                _temp = _material.GetVector(propertyID);

                if (mask.GetBit(0)) _temp.x = from.x + (to.x - from.x) * factor;
                if (mask.GetBit(1)) _temp.y = from.y + (to.y - from.y) * factor;
                if (mask.GetBit(2)) _temp.z = from.z + (to.z - from.z) * factor;
                if (mask.GetBit(3)) _temp.w = from.w + (to.w - from.w) * factor;

                _material.SetVector(propertyID, _temp);
            }
        }
示例#13
0
        public void WriteToJson(IResMgr resmgr, Material mat, MyJson.JsonNode_Object json)
        {
            json["shaderName"] = new MyJson.JsonNode_ValueString(this.shaderName);
            if (jsonConfig.ContainsKey("params"))
            {
                foreach (var item in jsonConfig["params"].asDict())
                {
                    //Debug.Log(item.Value);
                    string type = item.Value.asDict()["type"].AsString();
                    string flag = item.Value.asDict()["flags"].AsString();
                    string name = item.Value.asDict()["name"].AsString();
                    if (type == "Float" || type == "Range")
                    {
                        json[name] = new MyJson.JsonNode_ValueNumber(mat.GetFloat(name));
                    }
                    else if (type == "Vector")
                    {
                        json[name] = new MyJson.JsonNode_ValueString(StringHelper.ToString(mat.GetVector(name)));
                    }
                    else if (type == "Color")
                    {
                        json[name] = new MyJson.JsonNode_ValueString(StringHelper.ToString((Color32)mat.GetColor(name)));
                    }
                    else if (type == "Texture")
                    {
                        string texdim = item.Value.asDict()["texdim"].AsString();
                        var tex = mat.GetTexture(name);
                        if (tex != null)
                        {
                            if (texdim == "Tex2D")
                            {
                                string texname = resmgr.SaveTexture(tex as Texture2D);
                                json[name] = new MyJson.JsonNode_ValueString(texname);
                            }
                            else
                            {
                                throw new Exception("not support texdim:" + texdim);
                            }
                        }
                    }
                    else
                    {
                        throw new Exception("not support type:" + type);
                    }

                }
            }

        }
 /// <summary>
 /// Gets the values given a material
 /// </summary>
 /// <param name="m">The material</param>
 /// <returns>A StoredValue containing value and type information</returns>
 public List<StoredValue> GetValues(Material m)
 {
     var list = GetShaderProperties(m);
     var output = new List<StoredValue>();
     foreach (var p in list) {
         var o = new StoredValue {
             property = p
         };
         output.Add(o);
         switch (p.type) {
             case MaterialProperty.PropertyType.Color:
                 o.value = new object[1];
                 o.value[0] = m.GetColor(p.name);
                 break;
             case MaterialProperty.PropertyType.Float:
                 o.value = new object[1];
                 o.value[0] = m.GetFloat(p.name);
                 break;
             case MaterialProperty.PropertyType.Range:
                 o.value = new object[1];
                 o.value[0] = m.GetFloat(p.name);
                 break;
             case MaterialProperty.PropertyType.TexEnv:
                 o.value = new object[3];
                 o.value[0] = m.GetTexture(p.name);
                 o.value[1] = m.GetTextureOffset(p.name);
                 o.value[2] = m.GetTextureScale(p.name);
                 break;
             case MaterialProperty.PropertyType.Vector:
                 o.value = new object[1];
                 o.value[0] = m.GetVector(p.name);
                 break;
             default:
                 Debug.LogError("Unsupported type: " + p.type.ToString());
                 break;
         }
     }
     return output;
 }
        private BabylonMaterial DumpShaderMaterial(Material material)
        {
            if (materialsDictionary.ContainsKey(material.name))
            {
                return materialsDictionary[material.name];
            }

            var babylonShaderMaterial = new BabylonShaderMaterial
            {
                name = material.name,
                id = Guid.NewGuid().ToString(),
            };

            ExporterWindow.ReportProgress(1, "Exporting glsl material: " + material.name);

            List<string> tnames = material.GetTextureNames();
            foreach (string tname in tnames)
            {
                BabylonTexture tdata = DumpTextureFromMaterial(material, tname);
                if (tdata != null)
                {
                    babylonShaderMaterial.textures.Add(tname, tdata);
                }
            }

            List<string> fnames = material.GetFloatNames();
            foreach (string fname in fnames)
            {
                float fdata = material.GetFloat(fname);
                babylonShaderMaterial.floats.Add(fname, fdata);
            }

            List<string> rnames = material.GetRangeNames();
            foreach (string rname in rnames)
            {
                float rdata = material.GetFloat(rname);
                babylonShaderMaterial.floats.Add(rname, rdata);
            }

            List<string> cnames = material.GetColorNames();
            foreach (string cname in cnames)
            {
                Color cdata = material.GetColor(cname);
                babylonShaderMaterial.vectors4.Add(cname, cdata.ToFloat());
            }

            List<string> vnames = material.GetVectorNames();
            foreach (string vname in vnames)
            {
                Vector4 vdata = material.GetVector(vname);
                babylonShaderMaterial.vectors4.Add(vname, vdata.ToFloat());
            }

            Shader shader = material.shader;
            string filename = AssetDatabase.GetAssetPath(shader);
            string program = Tools.LoadTextAsset(filename);
            string basename = shader.name.Replace("BabylonJS/", "").Replace("/", "_").Replace(" ", "");
            string outpath = (!String.IsNullOrEmpty(exportationOptions.DefaultShaderFolder)) ? exportationOptions.DefaultShaderFolder : OutputPath;

            var shaderpath = new Dictionary<string, string>();
            List<string> attributeList = new List<string>();
            List<string> uniformList = new List<string>();
            List<string> samplerList = new List<string>();
            List<string> defineList = new List<string>();
            string babylonOptions = GetShaderProgramSection(basename, program, BabylonProgramSection.Babylon);
            string[] babylonLines = babylonOptions.Split('\n');
            foreach (string babylonLine in babylonLines)
            {
                if (babylonLine.IndexOf("attributes", StringComparison.OrdinalIgnoreCase) >= 0)
                {
                    string[] attributes = babylonLine.Split(':');
                    if (attributes != null && attributes.Length > 1)
                    {
                        string abuffer = attributes[1].Replace("[", "").Replace("]", "");
                        if (!String.IsNullOrEmpty(abuffer))
                        {
                            abuffer = abuffer.Trim();
                            string[] adata = abuffer.Split(',');
                            if (adata != null && adata.Length > 0)
                            {
                                foreach (string aoption in adata)
                                {
                                    string aoption_buffer = aoption.Trim().Replace("\"", "").Trim();
                                    if (!String.IsNullOrEmpty(aoption_buffer))
                                    {
                                        attributeList.Add(aoption_buffer);
                                    }
                                }
                            }
                        }
                    }
                }
                else if (babylonLine.IndexOf("uniforms", StringComparison.OrdinalIgnoreCase) >= 0)
                {
                    string[] uniforms = babylonLine.Split(':');
                    if (uniforms != null && uniforms.Length > 1)
                    {
                        string ubuffer = uniforms[1].Replace("[", "").Replace("]", "");
                        if (!String.IsNullOrEmpty(ubuffer))
                        {
                            ubuffer = ubuffer.Trim();
                            string[] udata = ubuffer.Split(',');
                            if (udata != null && udata.Length > 0)
                            {
                                foreach (string uoption in udata)
                                {
                                    string uoption_buffer = uoption.Trim().Replace("\"", "").Trim();
                                    if (!String.IsNullOrEmpty(uoption_buffer))
                                    {
                                        uniformList.Add(uoption_buffer);
                                    }
                                }
                            }
                        }
                    }
                }
                else if (babylonLine.IndexOf("samplers", StringComparison.OrdinalIgnoreCase) >= 0)
                {
                    string[] samplers = babylonLine.Split(':');
                    if (samplers != null && samplers.Length > 1)
                    {
                        string sbuffer = samplers[1].Replace("[", "").Replace("]", "");
                        if (!String.IsNullOrEmpty(sbuffer))
                        {
                            sbuffer = sbuffer.Trim();
                            string[] sdata = sbuffer.Split(',');
                            if (sdata != null && sdata.Length > 0)
                            {
                                foreach (string soption in sdata)
                                {
                                    string soption_buffer = soption.Trim().Replace("\"", "").Trim();
                                    if (!String.IsNullOrEmpty(soption_buffer))
                                    {
                                        samplerList.Add(soption_buffer);
                                    }
                                }
                            }
                        }
                    }
                }
                else if (babylonLine.IndexOf("defines", StringComparison.OrdinalIgnoreCase) >= 0)
                {
                    string[] defines = babylonLine.Split(':');
                    if (defines != null && defines.Length > 1)
                    {
                        string dbuffer = defines[1].Replace("[", "").Replace("]", "");
                        if (!String.IsNullOrEmpty(dbuffer))
                        {
                            dbuffer = dbuffer.Trim();
                            string[] ddata = dbuffer.Split(',');
                            if (ddata != null && ddata.Length > 0)
                            {
                                foreach (string doption in ddata)
                                {
                                    string doption_buffer = doption.Trim().Replace("\"", "").Trim();
                                    if (!String.IsNullOrEmpty(doption_buffer))
                                    {
                                        defineList.Add(doption_buffer);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            babylonShaderMaterial.options = new BabylonShaderOptions();
            babylonShaderMaterial.options.attributes = attributeList.ToArray();
            babylonShaderMaterial.options.uniforms = uniformList.ToArray();
            babylonShaderMaterial.options.samplers = samplerList.ToArray();
            babylonShaderMaterial.options.defines = defineList.ToArray();

            string vertexProgram = GetShaderProgramSection(basename, program, BabylonProgramSection.Vertex);
            var vertextFile = Path.Combine(outpath, basename + ".vertex.fx");
            if (exportationOptions.EmbeddedShaders)
            {
                shaderpath.Add("vertexElement", ("base64:" + Tools.FormatBase64(vertexProgram)));
            }
            else
            {
                File.WriteAllText(vertextFile, vertexProgram);
            }

            string fragmentProgram = GetShaderProgramSection(basename, program, BabylonProgramSection.Fragment);
            var fragmentFile = Path.Combine(outpath, basename + ".fragment.fx");
            if (exportationOptions.EmbeddedShaders)
            {
                shaderpath.Add("fragmentElement", ("base64:" + Tools.FormatBase64(fragmentProgram)));
            }
            else
            {
                File.WriteAllText(fragmentFile, fragmentProgram);
            }

            babylonShaderMaterial.shaderPath = (exportationOptions.EmbeddedShaders) ? (object)shaderpath : (object)basename;
            materialsDictionary.Add(babylonShaderMaterial.name, babylonShaderMaterial);
            return babylonShaderMaterial;
        }
示例#16
0
        static void SetMaterialKeywords(Material material)
        {
            // Note: keywords must be based on Material value not on MaterialProperty due to multi-edit & material animation
            // (MaterialProperty value might come from renderer material property block)
            SetKeyword (material, "_NORMALMAP", material.GetTexture ("_BumpMap") || material.GetTexture ("_DetailNormalMap"));

            SpecularMode specularMode = ( SpecularMode )material.GetInt( "_SpecularMode" );
            if ( specularMode == SpecularMode.BlinnPhong )
            {
            SetKeyword( material, "_SPECGLOSSMAP", material.GetTexture( "_SpecGlossMap" ) );
            }
            else if ( specularMode == SpecularMode.Metallic )
            {
            SetKeyword( material, "_METALLICGLOSSMAP", material.GetTexture( "_MetallicGlossMap" ) );
            }
            SetKeyword( material, "S_SPECULAR_NONE", specularMode == SpecularMode.None );
            SetKeyword( material, "S_SPECULAR_BLINNPHONG", specularMode == SpecularMode.BlinnPhong );
            SetKeyword( material, "S_SPECULAR_METALLIC", specularMode == SpecularMode.Metallic );
            SetKeyword( material, "S_OCCLUSION", material.GetTexture("_OcclusionMap") );

            SetKeyword( material, "_PARALLAXMAP", material.GetTexture("_ParallaxMap"));
            SetKeyword( material, "_DETAIL_MULX2", material.GetTexture("_DetailAlbedoMap") || material.GetTexture("_DetailNormalMap"));
            SetKeyword( material, "S_OVERRIDE_LIGHTMAP", material.GetTexture( "g_tOverrideLightmap" ) );

            SetKeyword( material, "S_UNLIT", material.GetInt( "g_bUnlit" ) == 1 );
            SetKeyword( material, "S_RECEIVE_SHADOWS", material.GetInt( "g_bReceiveShadows" ) == 1 );
            SetKeyword( material, "S_WORLD_ALIGNED_TEXTURE", material.GetInt( "g_bWorldAlignedTexture" ) == 1 );

            bool shouldEmissionBeEnabled = ShouldEmissionBeEnabled (material.GetColor("_EmissionColor"));
            SetKeyword (material, "_EMISSION", shouldEmissionBeEnabled);

            if ( material.IsKeywordEnabled( "S_RENDER_BACKFACES" ) )
            {
            material.SetInt( "_Cull", ( int )UnityEngine.Rendering.CullMode.Off );
            }
            else
            {
            material.SetInt( "_Cull", ( int )UnityEngine.Rendering.CullMode.Back );
            }

            // Setup lightmap emissive flags
            MaterialGlobalIlluminationFlags flags = material.globalIlluminationFlags;
            if ((flags & (MaterialGlobalIlluminationFlags.BakedEmissive | MaterialGlobalIlluminationFlags.RealtimeEmissive)) != 0)
            {
            flags &= ~MaterialGlobalIlluminationFlags.EmissiveIsBlack;
            if (!shouldEmissionBeEnabled)
                flags |= MaterialGlobalIlluminationFlags.EmissiveIsBlack;

            material.globalIlluminationFlags = flags;
            }

            // Reflectance constants
            float flReflectanceMin = material.GetFloat( "g_flReflectanceMin" );
            float flReflectanceMax = material.GetFloat( "g_flReflectanceMax" );
            material.SetFloat( "g_flReflectanceScale", Mathf.Max( flReflectanceMin, flReflectanceMax ) - flReflectanceMin );
            material.SetFloat( "g_flReflectanceBias", flReflectanceMin );

            // World aligned texture constants
            Vector4 worldAlignedTextureNormal = material.GetVector( "g_vWorldAlignedTextureNormal" );
            Vector3 normal = new Vector3( worldAlignedTextureNormal.x, worldAlignedTextureNormal.y, worldAlignedTextureNormal.z );
            normal = ( normal.sqrMagnitude > 0.0f ) ? normal : Vector3.up;
            Vector3 tangentU = Vector3.zero, tangentV = Vector3.zero;
            Vector3.OrthoNormalize( ref normal, ref tangentU, ref tangentV );
            material.SetVector( "g_vWorldAlignedNormalTangentU", new Vector4( tangentU.x, tangentU.y, tangentU.z, 0.0f ) );
            material.SetVector( "g_vWorldAlignedNormalTangentV", new Vector4( tangentV.x, tangentV.y, tangentV.z, 0.0f ) );

            // Static combo skips
            if ( material.GetInt( "g_bUnlit" ) == 1 )
            {
            material.DisableKeyword( "_NORMALMAP" );
            material.EnableKeyword( "S_SPECULAR_NONE" );
            material.DisableKeyword( "S_SPECULAR_BLINNPHONG" );
            material.DisableKeyword( "S_SPECULAR_METALLIC" );
            material.DisableKeyword( "_METALLICGLOSSMAP" );
            material.DisableKeyword( "_SPECGLOSSMAP" );
            material.DisableKeyword( "S_OVERRIDE_LIGHTMAP" );
            material.DisableKeyword( "S_RECEIVE_SHADOWS" );
            }
        }
        private void SetEdgesKeywords(UnityEngine.Material material, string firstEdgeName, string secondEdgeName)
        {
            bool isSettingTopBottomEdgesKeywords = firstEdgeName == "Top";

            bool areFirstSecondEdgesEnabled          = material.GetInt("_Waterfall2D_Is" + firstEdgeName + secondEdgeName + "EdgesEnabled") == 1;
            bool isFirstEdgeEnabled                  = material.GetInt("_Waterfall2D_Is" + firstEdgeName + "EdgeEnabled") == 1;
            bool isSecondEdgeEnabled                 = material.GetInt("_Waterfall2D_Is" + secondEdgeName + "EdgeEnabled") == 1;
            bool areFirstSecondEdgesUsingSameTexture = material.GetInt("_Waterfall2D_Is" + firstEdgeName + secondEdgeName + "EdgesUseSameTextureEnabled") == 1;

            if (!areFirstSecondEdgesUsingSameTexture)
            {
                isFirstEdgeEnabled  &= material.GetTexture("_" + firstEdgeName + "EdgeTexture") != null;
                isSecondEdgeEnabled &= material.GetTexture("_" + secondEdgeName + "EdgeTexture") != null;
            }
            else
            {
                areFirstSecondEdgesEnabled &= material.GetTexture("_" + firstEdgeName + secondEdgeName + "EdgesTexture") != null;
            }
            bool    isFirstSecondEdgesDistortionEffectEnabled            = material.GetInt("_Waterfall2D_Is" + firstEdgeName + secondEdgeName + "EdgesNoiseEnabled") == 1;
            bool    isFirstEdgeTextureSheetEnabled                       = material.GetInt("_Waterfall2D_Is" + firstEdgeName + "EdgeTextureSheetEnabled") == 1;
            bool    isSecondEdgeTextureSheetEnabled                      = material.GetInt("_Waterfall2D_Is" + secondEdgeName + "EdgeTextureSheetEnabled") == 1;
            bool    isFirstSecondEdgesTextureSheetEnabled                = material.GetInt("_Waterfall2D_Is" + firstEdgeName + secondEdgeName + "EdgesTextureSheetEnabled") == 1;
            bool    isFirstEdgeTextureSheetLerpEnabled                   = material.GetInt("_Waterfall2D_Is" + firstEdgeName + "EdgeTextureSheetWithLerpEnabled") == 1;
            bool    isSecondEdgeTextureSheetLerpEnabled                  = material.GetInt("_Waterfall2D_Is" + secondEdgeName + "EdgeTextureSheetWithLerpEnabled") == 1;
            bool    isFirstSecondEdgesTextureSheetLerpEnabled            = material.GetInt("_Waterfall2D_Is" + firstEdgeName + secondEdgeName + "EdgesTextureSheetWithLerpEnabled") == 1;
            Vector4 firstEdgeTextureTilingModeParameters                 = material.GetVector("_" + firstEdgeName + "EdgeTextureTilingParameters");
            Vector4 secondEdgeTextureTilingModeParameters                = material.GetVector("_" + secondEdgeName + "EdgeTextureTilingParameters");
            Vector4 firstSecondEdgesTextureTilingModeParameters          = material.GetVector("_" + firstEdgeName + secondEdgeName + "EdgesTextureTilingParameters");
            bool    isFirstEdgeTextureTilingModeSetToStretch             = firstEdgeTextureTilingModeParameters.x == 1f;
            bool    isFirstEdgeTextureStretchTilingModeKeepAspect        = firstEdgeTextureTilingModeParameters.y == 1f;
            bool    isFirstEdgeTextureStretchTilingModeAutoX             = firstEdgeTextureTilingModeParameters.z == 1f;
            bool    isSecondEdgeTextureTilingModeSetToStretch            = secondEdgeTextureTilingModeParameters.x == 1f;
            bool    isSecondEdgeTextureStretchTilingModeKeepAspect       = secondEdgeTextureTilingModeParameters.y == 1f;
            bool    isSecondEdgeTextureStretchTilingModeAutoX            = secondEdgeTextureTilingModeParameters.z == 1f;
            bool    isFirstSecondEdgesTextureTilingModeSetToStretch      = firstSecondEdgesTextureTilingModeParameters.x == 1f;
            bool    isFirstSecondEdgesTextureStretchTilingModeKeepAspect = firstSecondEdgesTextureTilingModeParameters.y == 1f;
            bool    isFirstSecondEdgesTextureStretchTilingModeAutoX      = firstSecondEdgesTextureTilingModeParameters.z == 1f;
            Vector4 textureFlippingParametes   = material.GetVector("_" + firstEdgeName + secondEdgeName + "EdgesTextureFlipParameters");
            bool    isTextureFlippingEnabled   = textureFlippingParametes.x == 1f;
            bool    isTextureFlippingFirstEdge = textureFlippingParametes.y == 1f;
            bool    isFirstSecondEdgesAbsoluteThicknessAndOffsetAbsolute = material.GetInt("_Waterfall2D_Is" + firstEdgeName + secondEdgeName + "EdgesAbsoluteThicknessAndOffsetEnabled") == 1;

            SetKeywordState(material, "Waterfall2D_" + firstEdgeName + secondEdgeName + "EdgesSameTexture", areFirstSecondEdgesEnabled && isFirstEdgeEnabled && isSecondEdgeEnabled && areFirstSecondEdgesUsingSameTexture && !isFirstSecondEdgesTextureSheetEnabled && !(isFirstSecondEdgesTextureSheetEnabled && isFirstSecondEdgesTextureSheetLerpEnabled));
            SetKeywordState(material, "Waterfall2D_" + firstEdgeName + secondEdgeName + "EdgesSameTextureSheet", areFirstSecondEdgesEnabled && isFirstEdgeEnabled && isSecondEdgeEnabled && areFirstSecondEdgesUsingSameTexture && isFirstSecondEdgesTextureSheetEnabled && !isFirstSecondEdgesTextureSheetLerpEnabled);
            SetKeywordState(material, "Waterfall2D_" + firstEdgeName + secondEdgeName + "EdgesSameTextureSheetWithLerp", areFirstSecondEdgesEnabled && isFirstEdgeEnabled && isSecondEdgeEnabled && areFirstSecondEdgesUsingSameTexture && isFirstSecondEdgesTextureSheetEnabled && isFirstSecondEdgesTextureSheetLerpEnabled);
            SetKeywordState(material, "Waterfall2D_" + firstEdgeName + "Edge", areFirstSecondEdgesEnabled && isFirstEdgeEnabled && !(isSecondEdgeEnabled && areFirstSecondEdgesUsingSameTexture) && !isFirstEdgeTextureSheetEnabled && !(isFirstEdgeTextureSheetEnabled && isFirstEdgeTextureSheetLerpEnabled));
            SetKeywordState(material, "Waterfall2D_" + firstEdgeName + "EdgeTextureSheet", areFirstSecondEdgesEnabled && isFirstEdgeEnabled && !(isSecondEdgeEnabled && areFirstSecondEdgesUsingSameTexture) && isFirstEdgeTextureSheetEnabled && !isFirstEdgeTextureSheetLerpEnabled);
            SetKeywordState(material, "Waterfall2D_" + firstEdgeName + "EdgeTextureSheetWithLerp", areFirstSecondEdgesEnabled && isFirstEdgeEnabled && !(isSecondEdgeEnabled && areFirstSecondEdgesUsingSameTexture) && isFirstEdgeTextureSheetEnabled && isFirstEdgeTextureSheetLerpEnabled);
            SetKeywordState(material, "Waterfall2D_" + secondEdgeName + "Edge", areFirstSecondEdgesEnabled && isSecondEdgeEnabled && !(isFirstEdgeEnabled && areFirstSecondEdgesUsingSameTexture) && !isSecondEdgeTextureSheetEnabled && !(isSecondEdgeTextureSheetEnabled && isSecondEdgeTextureSheetLerpEnabled));
            SetKeywordState(material, "Waterfall2D_" + secondEdgeName + "EdgeTextureSheet", areFirstSecondEdgesEnabled && isSecondEdgeEnabled && !(isFirstEdgeEnabled && areFirstSecondEdgesUsingSameTexture) && isSecondEdgeTextureSheetEnabled && !isSecondEdgeTextureSheetLerpEnabled);
            SetKeywordState(material, "Waterfall2D_" + secondEdgeName + "EdgeTextureSheetWithLerp", areFirstSecondEdgesEnabled && isSecondEdgeEnabled && !(isFirstEdgeEnabled && areFirstSecondEdgesUsingSameTexture) && isSecondEdgeTextureSheetEnabled && isSecondEdgeTextureSheetLerpEnabled);
            SetKeywordState(material, "Waterfall2D_" + firstEdgeName + secondEdgeName + "EdgesNoise", areFirstSecondEdgesEnabled && (isFirstEdgeEnabled || isSecondEdgeEnabled) && isFirstSecondEdgesDistortionEffectEnabled);
            SetKeywordState(material, "Waterfall2D_" + firstEdgeName + "EdgeTextureStretch", areFirstSecondEdgesEnabled && isFirstEdgeEnabled && !(isSecondEdgeEnabled && areFirstSecondEdgesUsingSameTexture) && isFirstEdgeTextureTilingModeSetToStretch && !isFirstEdgeTextureStretchTilingModeKeepAspect);
            SetKeywordState(material, "Waterfall2D_" + firstEdgeName + "EdgeTextureStretchAutoX", areFirstSecondEdgesEnabled && isFirstEdgeEnabled && !(isSecondEdgeEnabled && areFirstSecondEdgesUsingSameTexture) && isFirstEdgeTextureTilingModeSetToStretch && isFirstEdgeTextureStretchTilingModeKeepAspect && isFirstEdgeTextureStretchTilingModeAutoX);
            SetKeywordState(material, "Waterfall2D_" + firstEdgeName + "EdgeTextureStretchAutoY", areFirstSecondEdgesEnabled && isFirstEdgeEnabled && !(isSecondEdgeEnabled && areFirstSecondEdgesUsingSameTexture) && isFirstEdgeTextureTilingModeSetToStretch && isFirstEdgeTextureStretchTilingModeKeepAspect && !isFirstEdgeTextureStretchTilingModeAutoX);
            SetKeywordState(material, "Waterfall2D_" + secondEdgeName + "EdgeTextureStretch", areFirstSecondEdgesEnabled && isSecondEdgeEnabled && !(isFirstEdgeEnabled && areFirstSecondEdgesUsingSameTexture) && isSecondEdgeTextureTilingModeSetToStretch && !isSecondEdgeTextureStretchTilingModeKeepAspect);
            SetKeywordState(material, "Waterfall2D_" + secondEdgeName + "EdgeTextureStretchAutoX", areFirstSecondEdgesEnabled && isSecondEdgeEnabled && !(isFirstEdgeEnabled && areFirstSecondEdgesUsingSameTexture) && isSecondEdgeTextureTilingModeSetToStretch && isSecondEdgeTextureStretchTilingModeKeepAspect && isSecondEdgeTextureStretchTilingModeAutoX);
            SetKeywordState(material, "Waterfall2D_" + secondEdgeName + "EdgeTextureStretchAutoY", areFirstSecondEdgesEnabled && isSecondEdgeEnabled && !(isFirstEdgeEnabled && areFirstSecondEdgesUsingSameTexture) && isSecondEdgeTextureTilingModeSetToStretch && isSecondEdgeTextureStretchTilingModeKeepAspect && !isSecondEdgeTextureStretchTilingModeAutoX);
            SetKeywordState(material, "Waterfall2D_" + firstEdgeName + secondEdgeName + "EdgesTextureStretch", areFirstSecondEdgesEnabled && isFirstEdgeEnabled && isSecondEdgeEnabled && areFirstSecondEdgesUsingSameTexture && isFirstSecondEdgesTextureTilingModeSetToStretch && !isFirstSecondEdgesTextureStretchTilingModeKeepAspect);
            SetKeywordState(material, "Waterfall2D_" + firstEdgeName + secondEdgeName + "EdgesTextureStretchAutoX", areFirstSecondEdgesEnabled && isFirstEdgeEnabled && isSecondEdgeEnabled && areFirstSecondEdgesUsingSameTexture && isFirstSecondEdgesTextureTilingModeSetToStretch && isFirstSecondEdgesTextureStretchTilingModeKeepAspect && isFirstSecondEdgesTextureStretchTilingModeAutoX);
            SetKeywordState(material, "Waterfall2D_" + firstEdgeName + secondEdgeName + "EdgesTextureStretchAutoY", areFirstSecondEdgesEnabled && isFirstEdgeEnabled && isSecondEdgeEnabled && areFirstSecondEdgesUsingSameTexture && isFirstSecondEdgesTextureTilingModeSetToStretch && isFirstSecondEdgesTextureStretchTilingModeKeepAspect && !isFirstSecondEdgesTextureStretchTilingModeAutoX);
            SetKeywordState(material, "Waterfall2D_" + firstEdgeName + secondEdgeName + "EdgesFlip" + firstEdgeName + "Edge" + (isSettingTopBottomEdgesKeywords ? "Y" : "X"), areFirstSecondEdgesEnabled && isFirstEdgeEnabled && isSecondEdgeEnabled && areFirstSecondEdgesUsingSameTexture && isTextureFlippingEnabled && isTextureFlippingFirstEdge);
            SetKeywordState(material, "Waterfall2D_" + firstEdgeName + secondEdgeName + "EdgesFlip" + secondEdgeName + "Edge" + (isSettingTopBottomEdgesKeywords ? "Y" : "X"), areFirstSecondEdgesEnabled && isFirstEdgeEnabled && isSecondEdgeEnabled && areFirstSecondEdgesUsingSameTexture && isTextureFlippingEnabled && !isTextureFlippingFirstEdge);
            SetKeywordState(material, "Waterfall2D_" + firstEdgeName + secondEdgeName + "EdgesAbsoluteThicknessAndOffset", areFirstSecondEdgesEnabled && (isFirstEdgeEnabled || isSecondEdgeEnabled) && isFirstSecondEdgesAbsoluteThicknessAndOffsetAbsolute);

            if (!isSettingTopBottomEdgesKeywords)
            {
                bool isTextureAlphaCutoffEnabled = FindProperty("_Waterfall2D_Is" + firstEdgeName + secondEdgeName + "EdgesTextureAlphaCutoffEnabled", _materialProperties).floatValue == 1f;
                SetKeywordState(material, "Waterfall2D_" + firstEdgeName + secondEdgeName + "EdgesTextureAlphaCutoff", (areFirstSecondEdgesEnabled || isFirstEdgeEnabled || isSecondEdgeEnabled) && isTextureAlphaCutoffEnabled);
            }
        }
示例#18
0
        public static ByteBuffer Save(UnityEngine.Material material)
        {
            FlatBufferBuilder builder = new FlatBufferBuilder(InitBufferSize);

            int count = ShaderUtil.GetPropertyCount(material.shader);
            List <Offset <ShaderProperty> > listOffShaderProperties = new List <Offset <ShaderProperty> >();

            for (int i = 0; i < count; i++)
            {
                string name = ShaderUtil.GetPropertyName(material.shader, i);
                ShaderUtil.ShaderPropertyType type      = ShaderUtil.GetPropertyType(material.shader, i);
                Schema.ShaderPropertyValue    valueType = ShaderPropertyValue.NONE;
                int valueOffset = -1;
                switch (type)
                {
                case ShaderUtil.ShaderPropertyType.Color:
                {
                    UnityEngine.Color c = material.GetColor(name);
                    ShaderPropertyColor.StartShaderPropertyColor(builder);
                    ShaderPropertyColor.AddColor(builder, Schema.Color.CreateColor(builder, c.a, c.b, c.g, c.r));
                    Offset <ShaderPropertyColor> offset = ShaderPropertyColor.EndShaderPropertyColor(builder);
                    valueType   = ShaderPropertyValue.ShaderPropertyColor;
                    valueOffset = offset.Value;
                }
                break;

                case ShaderUtil.ShaderPropertyType.Vector:
                {
                    Vector4 v = material.GetVector(name);
                    ShaderPropertyVector.StartShaderPropertyVector(builder);
                    ShaderPropertyVector.AddVector(builder, Schema.Vec4.CreateVec4(builder, v.x, v.y, v.z, v.w));
                    Offset <ShaderPropertyVector> offset = ShaderPropertyVector.EndShaderPropertyVector(builder);
                    valueType   = ShaderPropertyValue.ShaderPropertyVector;
                    valueOffset = offset.Value;
                }
                break;

                case ShaderUtil.ShaderPropertyType.Range:
                case ShaderUtil.ShaderPropertyType.Float:
                {
                    float f = material.GetFloat(name);
                    ShaderPropertyFloat.StartShaderPropertyFloat(builder);
                    ShaderPropertyFloat.AddValue(builder, f);
                    Offset <ShaderPropertyFloat> offset = ShaderPropertyFloat.EndShaderPropertyFloat(builder);
                    valueType   = ShaderPropertyValue.ShaderPropertyFloat;
                    valueOffset = offset.Value;
                }
                break;

                case ShaderUtil.ShaderPropertyType.TexEnv:
                {
                    UnityEngine.Texture t = material.GetTexture(name);
                    string textureName    = "$NULL_TEXTURE";
                    if (t != null)
                    {
                        textureName = AssetDatabase.GetAssetPath(t.GetInstanceID());
                        if (string.IsNullOrEmpty(textureName))
                        {
                            textureName = t.name;
                        }
                        else
                        {
                            textureName = textureName.Substring(ArtWork.path.Length);
                            textureName = System.IO.Path.GetDirectoryName(textureName) + "/" + System.IO.Path.GetFileNameWithoutExtension(textureName);
                        }
                    }
                    Vector2 toffset = material.GetTextureOffset(name);
                    Vector2 tscale  = material.GetTextureScale(name);

                    StringOffset pathOffset = builder.CreateString(textureName);
                    ShaderPropertyTexture.StartShaderPropertyTexture(builder);
                    ShaderPropertyTexture.AddName(builder, pathOffset);
                    ShaderPropertyTexture.AddOffset(builder, Vec2.CreateVec2(builder, toffset.x, toffset.y));
                    ShaderPropertyTexture.AddScale(builder, Vec2.CreateVec2(builder, tscale.x, tscale.y));
                    Offset <ShaderPropertyTexture> offset = ShaderPropertyTexture.EndShaderPropertyTexture(builder);
                    valueType   = ShaderPropertyValue.ShaderPropertyTexture;
                    valueOffset = offset.Value;
                }
                break;
                }

                if (valueOffset >= 0)
                {
                    listOffShaderProperties.Add(
                        ShaderProperty.CreateShaderProperty(
                            builder, builder.CreateString(name), (Schema.ShaderPropertyType)type, valueType, valueOffset
                            ));
                }
            }
            StringOffset             offMaterialName = builder.CreateString(material.name);
            StringOffset             offShader       = builder.CreateString(material.shader.name);
            Offset <Schema.Material> offMaterial     = Schema.Material.CreateMaterial(
                builder, offMaterialName, offShader, Schema.Material.CreatePropertiesVector(builder, listOffShaderProperties.ToArray()));

            builder.Finish(offMaterial.Value);
            return(builder.DataBuffer);
        }
    private void Awake()
    {
        m_material = GetComponent<Renderer>().sharedMaterial;

        // Actual water rendering mode depends on both the current setting AND
        // the hardware support. There's no point in rendering refraction textures
        // if they won't be visible in the end.
        m_HardwareWaterSupport = FindHardwareWaterSupport ();
        //m_waterMode = GetWaterMode ();

        m_waveSpeed = m_material.GetVector ("WaveSpeed");
        m_waveScale = m_material.GetFloat ("_WaveScale");
        m_waveScale4 = new Vector4 (m_waveScale, m_waveScale, m_waveScale * 0.4f, m_waveScale * 0.45f);

        m_material.SetVector ("_WaveScale4", m_waveScale4);
        m_xWaveSpeedScaled = m_waveSpeed.x * m_waveScale4.x;
        m_yWaveSpeedScaled = m_waveSpeed.y * m_waveScale4.y;
        m_zWaveSpeedScaled = m_waveSpeed.z * m_waveScale4.z;
        m_wWaveSpeedScaled = m_waveSpeed.w * m_waveScale4.w;

        m_camera = Camera.current;
        //		CreateWaterObjects (m_camera, out m_reflectionCamera, out m_refractionCamera);
        //		UpdateCameraModes (m_camera, m_reflectionCamera);
        //		UpdateCameraModes (m_camera, m_refractionCamera);
    }
        public static GLTF.Schema.Material ConvertSeinCustomMaterial(UnityEngine.Material mat, ExporterEntry entry)
        {
            if (_tempGO == null)
            {
                _tempGO = new GameObject();
            }

            var customMaterial = _tempGO.AddComponent <SeinCustomMaterial>();
            var className      = mat.shader.name.Replace("Sein/", "");

            if (!className.Contains("Material"))
            {
                className += "Material";
            }

            var shaderPath = AssetDatabase.GetAssetPath(mat.shader);

            if (shaderPath != null)
            {
                var matScriptPath = Path.Combine(
                    shaderPath.Replace(Path.GetFileName(shaderPath), ""),
                    className + ".js"
                    );

                if (File.Exists(matScriptPath))
                {
                    if (entry.root.Extensions == null)
                    {
                        entry.root.Extensions = new Dictionary <string, Extension>();
                    }

                    customMaterial.matScriptPath = matScriptPath;
                }
            }

            customMaterial.className         = className;
            customMaterial.renderOrder       = mat.renderQueue;
            customMaterial.unityMaterialName = mat.name;

            var floatArray   = new List <SeinMaterialUniformFloat>();
            var vector4Array = new List <SeinMaterialUniformFloatVec4>();
            var colorArray   = new List <SeinMaterialUniformColor>();
            var textureArray = new List <SeinMaterialUniformTexture>();

            for (int i = 0; i < ShaderUtil.GetPropertyCount(mat.shader); i += 1)
            {
                var propType = ShaderUtil.GetPropertyType(mat.shader, i);
                var propName = ShaderUtil.GetPropertyName(mat.shader, i);

                if (propName == "cloneForInst")
                {
                    customMaterial.cloneForInst = mat.GetInt("cloneForInst") != 0;
                    continue;
                }

                if (ShaderUtil.IsShaderPropertyHidden(mat.shader, i))
                {
                    continue;
                }

                var n = propName;

                switch (propType)
                {
                case ShaderUtil.ShaderPropertyType.Float:
                case ShaderUtil.ShaderPropertyType.Range:
                    floatArray.Add(new SeinMaterialUniformFloat {
                        name = propName, value = mat.GetFloat(n)
                    });
                    break;

                case ShaderUtil.ShaderPropertyType.Color:
                    colorArray.Add(new SeinMaterialUniformColor {
                        name = propName, value = mat.GetColor(n)
                    });
                    break;

                case ShaderUtil.ShaderPropertyType.Vector:
                    vector4Array.Add(new SeinMaterialUniformFloatVec4 {
                        name = propName, value = mat.GetVector(n)
                    });
                    break;

                case ShaderUtil.ShaderPropertyType.TexEnv:
                    if (mat.GetTexture(n) != null)
                    {
                        textureArray.Add(new SeinMaterialUniformTexture {
                            name = propName, value = (Texture2D)mat.GetTexture(n)
                        });
                    }
                    break;
                }

                customMaterial.uniformsFloat     = floatArray.ToArray();
                customMaterial.uniformsFloatVec4 = vector4Array.ToArray();
                customMaterial.uniformsColor     = colorArray.ToArray();
                customMaterial.uniformsTexture   = textureArray.ToArray();
            }

            var tempM = new GLTF.Schema.Material();

            customMaterial.transparent = ProcessTransparency(mat, tempM);

            var m = ConvertMaterial(customMaterial, entry);

            return(m);
        }
示例#21
0
    static JsonData getUnityMatData(UnityEngine.Material mat, Paladin paladin = null)
    {
        var ret = new JsonData();

        ret["type"] = mat.name;

        var param  = new JsonData();
        var albedo = new JsonData();
        var color  = Util.fromColor(mat.GetColor("_Color"));

        albedo.Add(color);
        var uvOffset = mat.GetVector("_MainTex_ST");

        var mainTex = mat.GetTexture("_MainTex");
        var texData = new JsonData();

        if (mainTex != null)
        {
            texData["type"] = "image";
            var srcFn = AssetDatabase.GetAssetPath(mainTex);
            var idx   = srcFn.LastIndexOf("/");
            var dstFn = paladin.outputDir + "/" + paladin.outputName + srcFn.Substring(idx);
            var fn    = srcFn.Substring(idx + 1);
            if (!File.Exists(dstFn))
            {
                FileUtil.CopyFileOrDirectory(srcFn, dstFn);
            }
            texData["param"]   = new JsonData();
            texData["subtype"] = "spectrum";
            if (uvOffset != null)
            {
                texData["param"]["uvOffset"] = Util.fromVec4(uvOffset);
            }
            texData["param"]["fileName"]     = fn;
            texData["param"]["fromBasePath"] = true;
        }
        else
        {
            texData.Add(1);
            texData.Add(1);
            texData.Add(1);
        }
        albedo.Add(texData);
        param["albedo"]    = albedo;
        param["bumpScale"] = mat.GetFloat("_BumpScale");

        var emission = mat.GetColor("_EmissionColor");

        if (emission != null)
        {
            var emissionData = new JsonData();
            param["emission"]  = emissionData;
            emissionData["Le"] = new JsonData();
            emissionData["Le"]["colorType"] = 1;
            emissionData["Le"]["color"]     = Util.fromColor(emission);
        }

        var normalMap = mat.GetTexture("_BumpMap");

        if (normalMap != null)
        {
            var normalMapData = new JsonData();
            var srcFn         = AssetDatabase.GetAssetPath(normalMap);
            var idx           = srcFn.LastIndexOf("/");
            var dstFn         = paladin.outputDir + "/" + paladin.outputName + srcFn.Substring(idx);
            var fn            = srcFn.Substring(idx + 1);
            if (!File.Exists(dstFn))
            {
                FileUtil.CopyFileOrDirectory(srcFn, dstFn);
            }

            normalMapData["param"]                 = new JsonData();
            normalMapData["subtype"]               = "spectrum";
            normalMapData["type"]                  = "image";
            normalMapData["param"]["fileName"]     = fn;
            normalMapData["param"]["fromBasePath"] = true;
            if (uvOffset != null)
            {
                normalMapData["param"]["uvOffset"] = Util.fromVec4(uvOffset);
            }
            param["normalMap"] = normalMapData;
        }

        var bumpMap = mat.GetTexture("_ParallaxMap");

        if (bumpMap != null)
        {
            var bumpMapData = new JsonData();
            var srcFn       = AssetDatabase.GetAssetPath(bumpMap);
            var idx         = srcFn.LastIndexOf("/");
            var dstFn       = paladin.outputDir + "/" + paladin.outputName + srcFn.Substring(idx);
            var fn          = srcFn.Substring(idx + 1);
            if (!File.Exists(dstFn))
            {
                FileUtil.CopyFileOrDirectory(srcFn, dstFn);
            }

            bumpMapData["param"]                 = new JsonData();
            bumpMapData["subtype"]               = "spectrum";
            bumpMapData["type"]                  = "image";
            bumpMapData["param"]["fileName"]     = fn;
            bumpMapData["param"]["fromBasePath"] = true;
            if (uvOffset != null)
            {
                bumpMapData["param"]["uvOffset"] = Util.fromVec4(uvOffset);
            }
            param["bumpMap"] = bumpMapData;
        }

        param["roughness"] = 1 - mat.GetFloat("_Glossiness");
        param["metallic"]  = mat.GetFloat("_Metallic");
        ret["param"]       = param;

        return(ret);
    }
        private void CloneToBuffer(Material mat, CommandBuffer buf)
        {
            foreach (KeyValuePair<object, object> field in cache)
            {
                object obj = field.Value;
                //float
                int id = (int)field.Key;
                if (obj.GetType() == typeof(float))
                {
                    float value = mat.GetFloat(id);
                    buf.SetGlobalFloat(id, value);
                }
                //Color
                else if (obj.GetType() == typeof(Color))
                {
                    Color value = mat.GetColor(id);
                    buf.SetGlobalColor(id, value);
                }
                //Color32
                else if (obj.GetType() == typeof(Color32))
                {
                    Color value = mat.GetColor(id);
                    buf.SetGlobalColor(id, value);
                }//Vector2
                else if (obj.GetType() == typeof(Vector2))
                {
                    Vector4 value = mat.GetVector(id);
                    buf.SetGlobalVector(id, value);
                }
                //Vector3
                else if (obj.GetType() == typeof(Vector3))
                {
                    Vector4 value = mat.GetVector(id);
                    buf.SetGlobalVector(id, value);
                }
                //Vector4
                else if (obj.GetType() == typeof(Vector4))
                {
                    Vector4 value = mat.GetVector(id);
                    buf.SetGlobalVector(id, value);
                }
                //Matrix
                else if (obj.GetType() == typeof(Matrix4x4))
                {
                    Matrix4x4 value = mat.GetMatrix(id);
                    buf.SetGlobalMatrix(id, value);
                }

            }
        }
示例#23
0
 public void SetToToCurrent()
 {
     if (_material = material)
     {
         to = _material.GetVector(propertyID);
     }
 }
 public static Texture2D BuildPreviewTexture(int width, int height, Sprite sprite, Material spriteRendererMaterial, bool isPolygon)
 {
     if (!ShaderUtil.hardwareSupportsRectRenderTexture)
     {
         return null;
     }
     float num = sprite.rect.width;
     float num2 = sprite.rect.height;
     Texture2D spriteTexture = SpriteUtility.GetSpriteTexture(sprite, false);
     if (!isPolygon)
     {
         PreviewHelpers.AdjustWidthAndHeightForStaticPreview((int) num, (int) num2, ref width, ref height);
     }
     SavedRenderTargetState state = new SavedRenderTargetState();
     RenderTexture temp = RenderTexture.GetTemporary(width, height, 0, RenderTextureFormat.Default, RenderTextureReadWrite.Default);
     RenderTexture.active = temp;
     GL.sRGBWrite = QualitySettings.activeColorSpace == ColorSpace.Linear;
     GL.Clear(true, true, new Color(0f, 0f, 0f, 0f));
     Texture texture = null;
     Vector4 vector = new Vector4(0f, 0f, 0f, 0f);
     bool flag = false;
     bool flag2 = false;
     if (spriteRendererMaterial != null)
     {
         flag = spriteRendererMaterial.HasProperty("_MainTex");
         flag2 = spriteRendererMaterial.HasProperty("_MainTex_TexelSize");
     }
     Material material = null;
     if (spriteRendererMaterial != null)
     {
         if (flag)
         {
             texture = spriteRendererMaterial.GetTexture("_MainTex");
             spriteRendererMaterial.SetTexture("_MainTex", spriteTexture);
         }
         if (flag2)
         {
             vector = spriteRendererMaterial.GetVector("_MainTex_TexelSize");
             spriteRendererMaterial.SetVector("_MainTex_TexelSize", TextureUtil.GetTexelSizeVector(spriteTexture));
         }
         spriteRendererMaterial.SetPass(0);
     }
     else
     {
         material = new Material(Shader.Find("Hidden/BlitCopy")) {
             mainTexture = spriteTexture,
             mainTextureScale = Vector2.one,
             mainTextureOffset = Vector2.zero
         };
         material.SetPass(0);
     }
     float num3 = sprite.rect.width / sprite.bounds.size.x;
     Vector2[] vertices = sprite.vertices;
     Vector2[] uv = sprite.uv;
     ushort[] triangles = sprite.triangles;
     Vector2 pivot = sprite.pivot;
     GL.PushMatrix();
     GL.LoadOrtho();
     GL.Color(new Color(1f, 1f, 1f, 1f));
     GL.Begin(4);
     for (int i = 0; i < triangles.Length; i++)
     {
         ushort index = triangles[i];
         Vector2 vector4 = vertices[index];
         Vector2 vector5 = uv[index];
         GL.TexCoord(new Vector3(vector5.x, vector5.y, 0f));
         GL.Vertex3(((vector4.x * num3) + pivot.x) / num, ((vector4.y * num3) + pivot.y) / num2, 0f);
     }
     GL.End();
     GL.PopMatrix();
     GL.sRGBWrite = false;
     if (spriteRendererMaterial != null)
     {
         if (flag)
         {
             spriteRendererMaterial.SetTexture("_MainTex", texture);
         }
         if (flag2)
         {
             spriteRendererMaterial.SetVector("_MainTex_TexelSize", vector);
         }
     }
     Texture2D textured3 = new Texture2D(width, height, TextureFormat.RGBA32, false) {
         hideFlags = HideFlags.HideAndDontSave,
         filterMode = spriteTexture.filterMode,
         anisoLevel = spriteTexture.anisoLevel,
         wrapMode = spriteTexture.wrapMode
     };
     textured3.ReadPixels(new Rect(0f, 0f, (float) width, (float) height), 0, 0);
     textured3.Apply();
     RenderTexture.ReleaseTemporary(temp);
     state.Restore();
     if (material != null)
     {
         Object.DestroyImmediate(material);
     }
     return textured3;
 }
示例#25
0
 // Use this for initialization
 void Start()
 {
     waveScale = new Vector3 ();
     _mat = GetComponent<Renderer>().sharedMaterial;
     steepness = _mat.GetVector ("_GSteepness");
     amplitude = _mat.GetVector ("_GAmplitude");
     frequency = _mat.GetVector ("_GFrequency");
     speed = _mat.GetVector ("_GSpeed");
     dirAB = _mat.GetVector ("_GDirectionAB");
     dirCD = _mat.GetVector ("_GDirectionCD");
     //waveScale = _mat.GetVector("_WaveScale");
 }
示例#26
0
 void UpdateMaterial(Material m)
 {
     Vector3 d1 = m.GetVector("_Direction1");
     Vector3 d2 = m.GetVector("_Direction2");
     Vector3 d3 = m.GetVector("_Direction3");
     Vector3 d4 = m.GetVector("_Direction4");
     m.SetVector("_NormalizedVector1", d1.normalized);
     m.SetVector("_NormalizedVector2", d2.normalized);
     m.SetVector("_NormalizedVector3", d3.normalized);
     m.SetVector("_NormalizedVector4", d4.normalized);
 }
示例#27
0
    private void UpdateCurrentWater()
    {
        if (Boat != null)
        {
            Boat.SetActive(false);
            Boat.SetActive(true);
        }
        startSunIntencity = Sun.intensity;
        currentWater = GameObject.Find("Water");
        currentWaterMaterial = currentWater.GetComponent<Renderer>().material;

        refl = currentWaterMaterial.GetColor("_ReflectionColor").r;
        if (!IsMobileScene) transparent = currentWaterMaterial.GetFloat("_DepthTransperent");
        if (!IsMobileScene) fadeBlend = currentWaterMaterial.GetFloat("_FadeDepth");
        refraction = currentWaterMaterial.GetFloat("_Distortion");
        oldTextureScale = currentWaterMaterial.GetFloat("_TexturesScale");
        oldWaveScale = currentWaterMaterial.GetFloat("_WaveScale");
        var infiniteMesh = GameObject.Find("InfiniteWaterMesh");
        if (infiniteMesh != null) infiniteMesh.GetComponent<Renderer>().material = currentWaterMaterial;
        var projectorCausticScale = GameObject.Find("ProjectorCausticScale");
        if (projectorCausticScale != null) oldCausticScale = projectorCausticScale.transform.localScale;

        caustic = GameObject.Find("Caustic");
        if (IsMobileScene) caustic.SetActive(false);

        if (!IsMobileScene) causticMaterial = caustic.GetComponent<Projector>().material;
        waterDirection = currentWaterMaterial.GetVector("_Direction");
        if (!IsMobileScene) foamDirection = currentWaterMaterial.GetVector("_FoamDirection");
        if (!IsMobileScene) causticDirection = causticMaterial.GetVector("_CausticDirection");
        ABDirection = currentWaterMaterial.GetVector("_GDirectionAB");
        CDDirection = currentWaterMaterial.GetVector("_GDirectionCD");
    }
示例#28
0
        protected override void SetMaterialKeywords(UnityEngine.Material material)
        {
            bool applyTintOnTopOfTexture = material.GetFloat("_Water2D_IsApplyTintColorOnTopOfTextureEnabled") == 1f;

            SetKeywordState(material, "Water2D_ApplyTintColorBeforeTexture", !applyTintOnTopOfTexture);

            //Water Body Keywords
            bool    hasWaterBodyTexture                           = material.GetTexture("_WaterTexture") != null;
            bool    isWaterBodyTextureSheetEnabled                = material.GetFloat("_Water2D_IsWaterTextureSheetEnabled") == 1.0f;
            bool    isWaterBodyTextureSheetWithLerpEnabled        = material.GetFloat("_Water2D_IsWaterTextureSheetWithLerpEnabled") == 1.0;
            Vector4 waterBodyTextureTilingParameters              = material.GetVector("_WaterTextureTilingParameters");
            bool    isWaterBodyTextureTilingModeSetToStretch      = waterBodyTextureTilingParameters.x == 1f;
            bool    isWaterBodyTextureStretchTilingModeKeepAspect = waterBodyTextureTilingParameters.y == 1f;
            bool    isWaterBodyTextureStretchTilingModeAutoX      = waterBodyTextureTilingParameters.z == 1f;
            bool    isWaterBodyTextureScrollingEnabled            = material.GetFloat("_WaterTextureScrollingSpeedX") != 0f || material.GetFloat("_WaterTextureScrollingSpeedY") != 0f;

            SetKeywordState(material, "Water2D_WaterTexture", hasWaterBodyTexture && !isWaterBodyTextureSheetEnabled);
            SetKeywordState(material, "Water2D_WaterTextureSheet", hasWaterBodyTexture && isWaterBodyTextureSheetEnabled && !isWaterBodyTextureSheetWithLerpEnabled);
            SetKeywordState(material, "Water2D_WaterTextureSheetWithLerp", hasWaterBodyTexture && isWaterBodyTextureSheetEnabled && isWaterBodyTextureSheetWithLerpEnabled);
            SetKeywordState(material, "Water2D_WaterNoise", hasWaterBodyTexture && material.GetFloat("_Water2D_IsWaterNoiseEnabled") == 1.0f);
            SetKeywordState(material, "Water2D_WaterTextureStretch", hasWaterBodyTexture && isWaterBodyTextureTilingModeSetToStretch && !isWaterBodyTextureStretchTilingModeKeepAspect);
            SetKeywordState(material, "Water2D_WaterTextureStretchAutoX", hasWaterBodyTexture && isWaterBodyTextureTilingModeSetToStretch && isWaterBodyTextureStretchTilingModeKeepAspect && isWaterBodyTextureStretchTilingModeAutoX);
            SetKeywordState(material, "Water2D_WaterTextureStretchAutoY", hasWaterBodyTexture && isWaterBodyTextureTilingModeSetToStretch && isWaterBodyTextureStretchTilingModeKeepAspect && !isWaterBodyTextureStretchTilingModeAutoX);
            SetKeywordState(material, "Water2D_ColorGradient", material.GetFloat("_Water2D_IsColorGradientEnabled") == 1.0f);
            SetKeywordState(material, "Water2D_WaterTextureScroll", hasWaterBodyTexture && isWaterBodyTextureScrollingEnabled);

            //Refraction & Reflection Keywords
            bool    isReflectionEnabled        = material.GetFloat("_Water2D_IsReflectionEnabled") == 1.0f;
            bool    isRefractionEnabled        = material.GetFloat("_Water2D_IsRefractionEnabled") == 1.0f;
            Vector4 reflectionFadingParameters = material.GetVector("_ReflectionFadingParameters");
            bool    isReflectionFadingEnabled  = reflectionFadingParameters.x == 1f;

            SetKeywordState(material, "Water2D_Refraction", isRefractionEnabled);
            SetKeywordState(material, "Water2D_Reflection", isReflectionEnabled);
            SetKeywordState(material, "Water2D_ReflectionFadeLinear", isReflectionEnabled && isReflectionFadingEnabled && reflectionFadingParameters.y == 0f);
            SetKeywordState(material, "Water2D_ReflectionFadeExponentialTwo", isReflectionEnabled && isReflectionFadingEnabled && reflectionFadingParameters.y == 1f);
            SetKeywordState(material, "Water2D_ReflectionFadeExponentialThree", isReflectionEnabled && isReflectionFadingEnabled && reflectionFadingParameters.y == 2f);
            SetKeywordState(material, "Water2D_ReflectionFadeExponentialFour", isReflectionEnabled && isReflectionFadingEnabled && reflectionFadingParameters.y == 3f);

            //Water Surface Keywords
            bool    isSurfaceEnabled                            = material.GetFloat("_Water2D_IsSurfaceEnabled") == 1.0f;
            bool    hasSurfaceTexture                           = material.GetTexture("_SurfaceTexture") != null;
            bool    isSurfaceTextureSheetEnabled                = material.GetFloat("_Water2D_IsWaterSurfaceTextureSheetEnabled") == 1.0f;
            bool    isSurfaceTextureSheetWithLerpEnbaled        = material.GetFloat("_Water2D_IsWaterSurfaceTextureSheetWithLerpEnabled") == 1.0f;
            Vector4 waterSurfaceTextureTilingParameters         = material.GetVector("_SurfaceTextureTilingParameters");
            bool    isSurfaceTextureTilingModeSetToStretch      = waterSurfaceTextureTilingParameters.x == 1f;
            bool    isSurfaceTextureStretchTilingModeKeepAspect = waterSurfaceTextureTilingParameters.y == 1f;
            bool    isSurfaceTextureStretchTilingModeAutoX      = waterSurfaceTextureTilingParameters.z == 1f;
            bool    isSurfaceTextureScrollingEnabled            = material.GetFloat("_SurfaceTextureScrollingSpeedX") != 0f || material.GetFloat("_SurfaceTextureScrollingSpeedY") != 0f;

            SetKeywordState(material, "Water2D_Surface", isSurfaceEnabled);
            SetKeywordState(material, "Water2D_SurfaceTexture", isSurfaceEnabled && hasSurfaceTexture && !isSurfaceTextureSheetEnabled);
            SetKeywordState(material, "Water2D_SurfaceTextureSheet", isSurfaceEnabled && hasSurfaceTexture && isSurfaceTextureSheetEnabled && !isSurfaceTextureSheetWithLerpEnbaled);
            SetKeywordState(material, "Water2D_SurfaceTextureSheetWithLerp", isSurfaceEnabled && hasSurfaceTexture && isSurfaceTextureSheetEnabled && isSurfaceTextureSheetWithLerpEnbaled);
            SetKeywordState(material, "Water2D_SurfaceNoise", isSurfaceEnabled && hasSurfaceTexture && material.GetFloat("_Water2D_IsSurfaceNoiseEnabled") == 1.0f);
            SetKeywordState(material, "Water2D_SurfaceTextureStretch", isSurfaceEnabled && hasSurfaceTexture && isSurfaceTextureTilingModeSetToStretch && !isSurfaceTextureStretchTilingModeKeepAspect);
            SetKeywordState(material, "Water2D_SurfaceTextureStretchAutoX", isSurfaceEnabled && hasSurfaceTexture && isSurfaceTextureTilingModeSetToStretch && isSurfaceTextureStretchTilingModeKeepAspect && isSurfaceTextureStretchTilingModeAutoX);
            SetKeywordState(material, "Water2D_SurfaceTextureStretchAutoY", isSurfaceEnabled && hasSurfaceTexture && isSurfaceTextureTilingModeSetToStretch && isSurfaceTextureStretchTilingModeKeepAspect && !isSurfaceTextureStretchTilingModeAutoX);
            SetKeywordState(material, "Water2D_SurfaceColorGradient", isSurfaceEnabled && material.GetFloat("_Water2D_IsSurfaceColorGradientEnabled") == 1.0f);
            SetKeywordState(material, "Water2D_SurfaceTextureScroll", isSurfaceEnabled && hasSurfaceTexture && isSurfaceTextureScrollingEnabled);

            //Water Fake Perspective
            bool isFakePerspectiveEnabled = isSurfaceEnabled && (isRefractionEnabled || isReflectionEnabled) && (material.GetFloat("_Water2D_IsFakePerspectiveEnabled") == 1.0f);

            SetKeywordState(material, "Water2D_FakePerspective", isFakePerspectiveEnabled);

            //Lighting keywords
            SetKeywordState(material, "Water2D_ApplyEmissionColor", material.GetFloat("_Water2D_IsEmissionColorEnabled") == 1.0f);
        }
        public void EqualSource()
        {
            UnityEngine.Material realMaterial = resultMaterial.Unity3dObject as UnityEngine.Material;

            Assert.AreEqual(material.Name, realMaterial.name);
            Assert.AreEqual(material.Shader, realMaterial.shader.name);
            for (int i = 0; i < material.PropertiesLength; i++)
            {
                Schema.ShaderProperty p = material.GetProperties(i);

                Assert.IsTrue(realMaterial.HasProperty(p.Names));

                switch (p.Type)
                {
                case ShaderPropertyType.Float:
                case ShaderPropertyType.Range:
                {
                    Assert.AreEqual(p.ValueType, ShaderPropertyValue.ShaderPropertyFloat);

                    float originValue     = realMaterial.GetFloat(p.Names);
                    ShaderPropertyFloat f = p.GetValue <ShaderPropertyFloat>(new ShaderPropertyFloat());
                    Assert.AreEqual(f.Value, originValue);
                }
                break;

                case ShaderPropertyType.Color:
                {
                    Assert.AreEqual(p.ValueType, ShaderPropertyValue.ShaderPropertyColor);

                    UnityEngine.Color   originValue = realMaterial.GetColor(p.Names);
                    ShaderPropertyColor c           = p.GetValue <ShaderPropertyColor>(new ShaderPropertyColor());
                    Assert.AreEqual(originValue.a, c.Color.A);
                    Assert.AreEqual(originValue.g, c.Color.G);
                    Assert.AreEqual(originValue.b, c.Color.B);
                    Assert.AreEqual(originValue.r, c.Color.R);
                }
                break;

                case ShaderPropertyType.Vector:
                {
                    Assert.AreEqual(p.ValueType, ShaderPropertyValue.ShaderPropertyVector);

                    UnityEngine.Vector4  originValue = realMaterial.GetVector(p.Names);
                    ShaderPropertyVector v           = p.GetValue <ShaderPropertyVector>(new ShaderPropertyVector());
                    Assert.AreEqual(originValue.x, v.Vector.X);
                    Assert.AreEqual(originValue.y, v.Vector.Y);
                    Assert.AreEqual(originValue.z, v.Vector.Z);
                    Assert.AreEqual(originValue.w, v.Vector.W);
                }
                break;

                case ShaderPropertyType.TexEnv:
                {
                    Assert.AreEqual(p.ValueType, ShaderPropertyValue.ShaderPropertyTexture);
                    //UnityEngine.Texture texture = realMaterial.GetTexture(p.Names);
                    Vector2 offset = realMaterial.GetTextureOffset(p.Names);
                    Vector2 scale  = realMaterial.GetTextureScale(p.Names);

                    //这个测试用例不真正装载 texture.
                    //Assert.IsFalse(texture == null);
                    ShaderPropertyTexture t = p.GetValue <ShaderPropertyTexture>(new ShaderPropertyTexture());
                    string texturePath      = resultMaterial.GetTexturePath(t.Name);

                    Assert.IsTrue(realMaterial.HasProperty(p.Names));
                    Assert.IsTrue(dictTextures.ContainsKey(texturePath));
                    Assert.IsNotNull(realMaterial.GetTexture(p.Names));
                    Assert.AreEqual(dictTextures[texturePath].resourceObject.Unity3dObject.GetInstanceID(), realMaterial.GetTexture(p.Names).GetInstanceID());

                    Assert.AreEqual(offset.x, t.Offset.X);
                    Assert.AreEqual(offset.y, t.Offset.Y);
                    Assert.AreEqual(scale.x, t.Scale.X);
                    Assert.AreEqual(scale.y, t.Scale.Y);
                }
                break;
                }
            }
        }
		private static Texture2D BuildPreviewTexture(int width, int height, Sprite sprite, Material spriteRendererMaterial)
		{
			if (!ShaderUtil.hardwareSupportsRectRenderTexture)
			{
				return null;
			}
			float width2 = sprite.rect.width;
			float height2 = sprite.rect.height;
			Texture2D spriteTexture = UnityEditor.Sprites.SpriteUtility.GetSpriteTexture(sprite, false);
			PreviewHelpers.AdjustWidthAndHeightForStaticPreview((int)width2, (int)height2, ref width, ref height);
			EditorUtility.SetTemporarilyAllowIndieRenderTexture(true);
			SavedRenderTargetState savedRenderTargetState = new SavedRenderTargetState();
			RenderTexture temporary = RenderTexture.GetTemporary(width, height, 0, RenderTextureFormat.Default, RenderTextureReadWrite.Default);
			RenderTexture.active = temporary;
			GL.sRGBWrite = (QualitySettings.activeColorSpace == ColorSpace.Linear);
			GL.Clear(true, true, new Color(0f, 0f, 0f, 0f));
			Texture texture = null;
			Vector4 vector = new Vector4(0f, 0f, 0f, 0f);
			bool flag = false;
			bool flag2 = false;
			if (spriteRendererMaterial != null)
			{
				flag = spriteRendererMaterial.HasProperty("_MainTex");
				flag2 = spriteRendererMaterial.HasProperty("_MainTex_TexelSize");
			}
			Material material = null;
			if (spriteRendererMaterial != null)
			{
				if (flag)
				{
					texture = spriteRendererMaterial.GetTexture("_MainTex");
					spriteRendererMaterial.SetTexture("_MainTex", spriteTexture);
				}
				if (flag2)
				{
					vector = spriteRendererMaterial.GetVector("_MainTex_TexelSize");
					spriteRendererMaterial.SetVector("_MainTex_TexelSize", TextureUtil.GetTexelSizeVector(spriteTexture));
				}
				spriteRendererMaterial.SetPass(0);
			}
			else
			{
				material = new Material(Shader.Find("Hidden/BlitCopy"));
				material.mainTexture = spriteTexture;
				material.SetPass(0);
			}
			float num = sprite.rect.width / sprite.bounds.size.x;
			Vector2[] vertices = sprite.vertices;
			Vector2[] uv = sprite.uv;
			ushort[] triangles = sprite.triangles;
			Vector2 pivot = sprite.pivot;
			GL.PushMatrix();
			GL.LoadOrtho();
			GL.Color(new Color(1f, 1f, 1f, 1f));
			GL.Begin(4);
			for (int i = 0; i < sprite.triangles.Length; i++)
			{
				ushort num2 = triangles[i];
				Vector2 vector2 = vertices[(int)num2];
				Vector2 vector3 = uv[(int)num2];
				GL.TexCoord(new Vector3(vector3.x, vector3.y, 0f));
				GL.Vertex3((vector2.x * num + pivot.x) / width2, (vector2.y * num + pivot.y) / height2, 0f);
			}
			GL.End();
			GL.PopMatrix();
			GL.sRGBWrite = false;
			if (spriteRendererMaterial != null)
			{
				if (flag)
				{
					spriteRendererMaterial.SetTexture("_MainTex", texture);
				}
				if (flag2)
				{
					spriteRendererMaterial.SetVector("_MainTex_TexelSize", vector);
				}
			}
			Texture2D texture2D = new Texture2D(width, height, TextureFormat.ARGB32, false);
			texture2D.hideFlags = HideFlags.HideAndDontSave;
			texture2D.ReadPixels(new Rect(0f, 0f, (float)width, (float)height), 0, 0);
			texture2D.Apply();
			RenderTexture.ReleaseTemporary(temporary);
			savedRenderTargetState.Restore();
			EditorUtility.SetTemporarilyAllowIndieRenderTexture(false);
			if (material != null)
			{
				UnityEngine.Object.DestroyImmediate(material);
			}
			return texture2D;
		}
示例#31
0
        public void EqualSource()
        {
            Assert.AreEqual(material.Name, originMaterial.name);
            Assert.AreEqual(material.Shader, originMaterial.shader.name);
            for (int i = 0; i < material.PropertiesLength; i++)
            {
                Schema.ShaderProperty p = material.GetProperties(i);

                Assert.IsTrue(originMaterial.HasProperty(p.Names));

                switch (p.Type)
                {
                case ShaderPropertyType.Float:
                case ShaderPropertyType.Range:
                {
                    Assert.AreEqual(p.ValueType, ShaderPropertyValue.ShaderPropertyFloat);

                    float originValue     = originMaterial.GetFloat(p.Names);
                    ShaderPropertyFloat f = p.GetValue <ShaderPropertyFloat>(new ShaderPropertyFloat());
                    Assert.AreEqual(f.Value, originValue);
                }
                break;

                case ShaderPropertyType.Color:
                {
                    Assert.AreEqual(p.ValueType, ShaderPropertyValue.ShaderPropertyColor);

                    UnityEngine.Color   originValue = originMaterial.GetColor(p.Names);
                    ShaderPropertyColor c           = p.GetValue <ShaderPropertyColor>(new ShaderPropertyColor());
                    Assert.AreEqual(originValue.a, c.Color.A);
                    Assert.AreEqual(originValue.g, c.Color.G);
                    Assert.AreEqual(originValue.b, c.Color.B);
                    Assert.AreEqual(originValue.r, c.Color.R);
                }
                break;

                case ShaderPropertyType.Vector:
                {
                    Assert.AreEqual(p.ValueType, ShaderPropertyValue.ShaderPropertyVector);

                    UnityEngine.Vector4  originValue = originMaterial.GetVector(p.Names);
                    ShaderPropertyVector v           = p.GetValue <ShaderPropertyVector>(new ShaderPropertyVector());
                    Assert.AreEqual(originValue.x, v.Vector.X);
                    Assert.AreEqual(originValue.y, v.Vector.Y);
                    Assert.AreEqual(originValue.z, v.Vector.Z);
                    Assert.AreEqual(originValue.w, v.Vector.W);
                }
                break;

                case ShaderPropertyType.TexEnv:
                {
                    Assert.AreEqual(p.ValueType, ShaderPropertyValue.ShaderPropertyTexture);
                    UnityEngine.Texture texture = originMaterial.GetTexture(p.Names);
                    Vector2             offset  = originMaterial.GetTextureOffset(p.Names);
                    Vector2             scale   = originMaterial.GetTextureScale(p.Names);

                    Assert.IsFalse(texture == null);
                    ShaderPropertyTexture t = p.GetValue <ShaderPropertyTexture>(new ShaderPropertyTexture());

                    Assert.AreEqual(texture.name, t.Name);
                    Assert.AreEqual(offset.x, t.Offset.X);
                    Assert.AreEqual(offset.y, t.Offset.Y);
                    Assert.AreEqual(scale.x, t.Scale.X);
                    Assert.AreEqual(scale.y, t.Scale.Y);
                }
                break;
                }
            }
        }
示例#32
0
        private static GLTF.Schema.Material ConvertSeinCustomMaterial(UnityEngine.Material mat, ExporterEntry entry)
        {
            if (_tempGO == null)
            {
                _tempGO = new GameObject();
            }

            var customMaterial = _tempGO.AddComponent <SeinCustomMaterial>();
            var className      = mat.shader.name.Replace("Sein/", "");

            if (!className.Contains("Material"))
            {
                className += "Material";
            }
            customMaterial.className   = className;
            customMaterial.renderOrder = mat.renderQueue;
            var floatArray   = new List <SeinMaterialUniformFloat>();
            var vector4Array = new List <SeinMaterialUniformFloatVec4>();
            var textureArray = new List <SeinMaterialUniformTexture>();

            for (int i = 0; i < ShaderUtil.GetPropertyCount(mat.shader); i += 1)
            {
                var propType = ShaderUtil.GetPropertyType(mat.shader, i);
                var propName = ShaderUtil.GetPropertyName(mat.shader, i);

                if (propName == "cloneForInst")
                {
                    customMaterial.cloneForInst = mat.GetInt("cloneForInst") != 0;
                    continue;
                }

                if (ShaderUtil.IsShaderPropertyHidden(mat.shader, i))
                {
                    continue;
                }

                var n = propName;
                //if (propName.Substring(0, 1) == "_")
                //{
                //    propName = propName.Substring(1);
                //}

                switch (propType)
                {
                case ShaderUtil.ShaderPropertyType.Float:
                case ShaderUtil.ShaderPropertyType.Range:
                    floatArray.Add(new SeinMaterialUniformFloat {
                        name = propName, value = mat.GetFloat(n)
                    });
                    break;

                case ShaderUtil.ShaderPropertyType.Color:
                    vector4Array.Add(new SeinMaterialUniformFloatVec4 {
                        name = propName, value = mat.GetColor(n)
                    });
                    break;

                case ShaderUtil.ShaderPropertyType.Vector:
                    vector4Array.Add(new SeinMaterialUniformFloatVec4 {
                        name = propName, value = mat.GetVector(n)
                    });
                    break;

                case ShaderUtil.ShaderPropertyType.TexEnv:
                    if (mat.GetTexture(n) != null)
                    {
                        textureArray.Add(new SeinMaterialUniformTexture {
                            name = propName, value = (Texture2D)mat.GetTexture(n)
                        });
                    }
                    break;
                }

                customMaterial.uniformsFloat     = floatArray.ToArray();
                customMaterial.uniformsFloatVec4 = vector4Array.ToArray();
                customMaterial.uniformsTexture   = textureArray.ToArray();
            }

            var tempM = new GLTF.Schema.Material();

            customMaterial.transparent = ProcessTransparency(mat, tempM);
            var m = ConvertMaterial(customMaterial, entry);

            return(m);
        }
 public static Texture2D BuildPreviewTexture(int width, int height, Sprite sprite, Material spriteRendererMaterial, bool isPolygon)
 {
   if (!ShaderUtil.hardwareSupportsRectRenderTexture)
     return (Texture2D) null;
   float width1 = sprite.rect.width;
   float height1 = sprite.rect.height;
   Texture2D spriteTexture = UnityEditor.Sprites.SpriteUtility.GetSpriteTexture(sprite, false);
   if (!isPolygon)
     PreviewHelpers.AdjustWidthAndHeightForStaticPreview((int) width1, (int) height1, ref width, ref height);
   SavedRenderTargetState renderTargetState = new SavedRenderTargetState();
   RenderTexture temporary = RenderTexture.GetTemporary(width, height, 0, RenderTextureFormat.Default, RenderTextureReadWrite.Default);
   RenderTexture.active = temporary;
   GL.sRGBWrite = QualitySettings.activeColorSpace == ColorSpace.Linear;
   GL.Clear(true, true, new Color(0.0f, 0.0f, 0.0f, 0.0f));
   Texture texture = (Texture) null;
   Vector4 vector = new Vector4(0.0f, 0.0f, 0.0f, 0.0f);
   bool flag1 = false;
   bool flag2 = false;
   if ((Object) spriteRendererMaterial != (Object) null)
   {
     flag1 = spriteRendererMaterial.HasProperty("_MainTex");
     flag2 = spriteRendererMaterial.HasProperty("_MainTex_TexelSize");
   }
   Material material = (Material) null;
   if ((Object) spriteRendererMaterial != (Object) null)
   {
     if (flag1)
     {
       texture = spriteRendererMaterial.GetTexture("_MainTex");
       spriteRendererMaterial.SetTexture("_MainTex", (Texture) spriteTexture);
     }
     if (flag2)
     {
       vector = spriteRendererMaterial.GetVector("_MainTex_TexelSize");
       spriteRendererMaterial.SetVector("_MainTex_TexelSize", TextureUtil.GetTexelSizeVector((Texture) spriteTexture));
     }
     spriteRendererMaterial.SetPass(0);
   }
   else
   {
     material = new Material(Shader.Find("Hidden/BlitCopy"));
     material.mainTexture = (Texture) spriteTexture;
     material.mainTextureScale = Vector2.one;
     material.mainTextureOffset = Vector2.zero;
     material.SetPass(0);
   }
   float num1 = sprite.rect.width / sprite.bounds.size.x;
   Vector2[] vertices = sprite.vertices;
   Vector2[] uv = sprite.uv;
   ushort[] triangles = sprite.triangles;
   Vector2 pivot = sprite.pivot;
   GL.PushMatrix();
   GL.LoadOrtho();
   GL.Color(new Color(1f, 1f, 1f, 1f));
   GL.Begin(4);
   for (int index = 0; index < triangles.Length; ++index)
   {
     ushort num2 = triangles[index];
     Vector2 vector2_1 = vertices[(int) num2];
     Vector2 vector2_2 = uv[(int) num2];
     GL.TexCoord(new Vector3(vector2_2.x, vector2_2.y, 0.0f));
     GL.Vertex3((vector2_1.x * num1 + pivot.x) / width1, (vector2_1.y * num1 + pivot.y) / height1, 0.0f);
   }
   GL.End();
   GL.PopMatrix();
   GL.sRGBWrite = false;
   if ((Object) spriteRendererMaterial != (Object) null)
   {
     if (flag1)
       spriteRendererMaterial.SetTexture("_MainTex", texture);
     if (flag2)
       spriteRendererMaterial.SetVector("_MainTex_TexelSize", vector);
   }
   Texture2D texture2D = new Texture2D(width, height, TextureFormat.ARGB32, false);
   texture2D.hideFlags = HideFlags.HideAndDontSave;
   texture2D.ReadPixels(new Rect(0.0f, 0.0f, (float) width, (float) height), 0, 0);
   texture2D.Apply();
   RenderTexture.ReleaseTemporary(temporary);
   renderTargetState.Restore();
   if ((Object) material != (Object) null)
     Object.DestroyImmediate((Object) material);
   return texture2D;
 }
示例#34
0
    private static KSerializeMaterialProperty _GetShaderVectorProp(Material mm, string texProp)
    {
        if (mm.HasProperty(texProp))
        {
            KSerializeMaterialProperty shaderProp = new KSerializeMaterialProperty();
            shaderProp.Type = KSerializeMaterialProperty.ShaderType.Vector;
            shaderProp.PropName = texProp;
            Vector4 tex = mm.GetVector(texProp);
            shaderProp.PropValue = tex.ToString();

            return shaderProp;
        }
        return null;
    }
 public static Vector4 GetMaterialVector(System.String name, Material mat)
 {
     return mat.GetVector(name);
 }
        public Uniform(Material material, string uniform, string type)
        {
            Type = type;
            Name = uniform;

            if (Type.Equals("float")) {
                float f = material.GetFloat(Name);
                Value = f.ToString(GLexConfig.HighPrecision);
            }
            else if (Type.Equals("color") || Type.Equals("vector3")) {
                Color color = material.GetColor(Name);
                Value = "[ " + color.r.ToString(GLexConfig.MediumPrecision) + ", " + color.g.ToString(GLexConfig.MediumPrecision) + ", " + color.b.ToString(GLexConfig.MediumPrecision) + " ]";
            }
            else if (Type.Equals("color32") || Type.Equals("vector4")) {
                Vector4 color32 = material.GetVector(Name);
                Value = "[ " + color32.x.ToString(GLexConfig.MediumPrecision) + ", " + color32.y.ToString(GLexConfig.MediumPrecision) + ", " + color32.z.ToString(GLexConfig.MediumPrecision) + ", " + color32.z.ToString(GLexConfig.MediumPrecision) + " ]";
            }
        }
示例#37
0
	public List<MaterialProperty> GetShaderProperties(Material material)
	{
		if(cache.ContainsKey(material.shader.name))
			return cache[material.shader.name];
		
		var list = new List<MaterialProperty>();
		foreach(var m in MaterialProperties)
		{
			if(material.HasProperty(m.name))
			{
				if(m.type == MaterialProperty.PropertyType.unknown)
				{
					try
					{
						var p = material.GetColor(m.name);
						if(p != transparent)
						    list.Add( new MaterialProperty { name = m.name, type = MaterialProperty.PropertyType.color });
					}
					catch
					{
					}
					try
					{
						var p = material.GetFloat(m.name);
						if(p != 0)
						    list.Add( new MaterialProperty { name = m.name, type = MaterialProperty.PropertyType.real });
					}
					catch
					{
					}
					try
					{
						var p = material.GetTexture(m.name);
						if(p!=null)
						    list.Add( new MaterialProperty { name = m.name, type = MaterialProperty.PropertyType.texture });
					}
					catch
					{
					}
					try
					{
						var p = material.GetVector(m.name);
						if(p != Vector4.zero)
						    list.Add( new MaterialProperty { name = m.name, type = MaterialProperty.PropertyType.vector });
					}
					catch
					{
						
					}
					try
					{
						var p = material.GetMatrix(m.name);
						if(p != Matrix4x4.identity)
						     list.Add( new MaterialProperty { name = m.name, type = MaterialProperty.PropertyType.matrix });
					}
					catch
					{
					}
					try
					{
						var p = material.GetTextureOffset(m.name);
						if(p != Vector2.zero)
						     list.Add( new MaterialProperty { name = m.name, type = MaterialProperty.PropertyType.textureOffset });
					}
					catch
					{
					}
					try
					{
						var p = material.GetTextureScale(m.name);
						if(p != Vector2.zero)
						     list.Add( new MaterialProperty { name = m.name, type = MaterialProperty.PropertyType.textureScale });
					}
					catch
					{
					}
				}
				else
				{
					list.Add(m);
				}

					
			}
			
		}
		cache[material.shader.name] = list;
		return list;
	}
		void CopyVector(string propName, string targetPropName, Material sourceMaterial, Material targetMaterial) {
			if (sourceMaterial.HasProperty(propName) && targetMaterial.HasProperty(targetPropName)) {
				targetMaterial.SetVector(targetPropName, sourceMaterial.GetVector(propName));
			}
		}