GetFloat() private method

private GetFloat ( int nameID ) : float
nameID int
return float
        private static bool ProcessTransparency(UnityEngine.Material mat, GLTF.Schema.Material material)
        {
            if (!mat.HasProperty("_Mode"))
            {
                return(false);
            }

            switch ((int)mat.GetFloat("_Mode"))
            {
            // Opaque
            case 0:
                material.AlphaMode = AlphaMode.OPAQUE;
                return(false);

            // Cutout
            case 1:
                material.AlphaMode   = AlphaMode.MASK;
                material.AlphaCutoff = mat.GetFloat("_Cutoff");
                break;

            // Transparent
            case 2:
            case 3:
                material.AlphaMode = AlphaMode.BLEND;
                break;
            }

            return(true);
        }
        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_beginFloat = m_Material.GetFloat(m_property);
            }
            else if (m_propertyID != -1)
            {
                m_beginFloat = m_Material.GetFloat(m_propertyID);
            } // end if
        }
Exemplo n.º 3
0
		bool checkSpecUsage(Material mat, string label) {
			if ((label.IndexOf("layer Spec+Gloss")<0) && (label.IndexOf("gloss mask")<0) && (label.IndexOf("Spec (RGB)")<0)) return true;
			if (!mat.HasProperty("_DirectSpec")) return true;
			if (!mat.HasProperty("_IBLSpec")) return true;
			if (mat.GetFloat("_DirectSpec")==0 && mat.GetFloat("_IBLSpec")==0) return false;
			return true;
		}
Exemplo n.º 4
0
	void Update()
	{
		terrain = GetComponent<Terrain>();
		tData = terrain ? terrain.terrainData : null;
		tMaterial = terrain ? terrain.materialTemplate : null;
		if (!terrain || !tData || !tMaterial)
			return;
		
		if(disableBasemap && !Application.isPlaying && GetComponent<Terrain>().basemapDistance != 1000000) // only reset on update in edit mode
			GetComponent<Terrain>().basemapDistance = 1000000;
		if (cutoutMode)
		{
			if (tMaterial.HasProperty("_CutoutModeHideAlpha") && tMaterial.GetFloat("_CutoutModeHideAlpha") != cutoutModeHideAlpha)
				tMaterial.SetFloat("_CutoutModeHideAlpha", cutoutModeHideAlpha);
		}
		else
			if (tMaterial.HasProperty("_CutoutModeHideAlpha") && tMaterial.GetFloat("_CutoutModeHideAlpha") != -1)
				tMaterial.SetFloat("_CutoutModeHideAlpha", -1);

		if (!Application.isPlaying)
			ApplyTransparencyMap();
		else
			if (!transparencyMap && autoUpdateTransparencyMap)
			{
				UpdateTransparencyMap();
				ApplyTransparencyMap();
			}
			else
				ApplyTransparencyMap();
	}
        /// <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;
                    }
                }
            }

        }
Exemplo n.º 6
0
	// Use this for initialization
	void Start () {
        heatMaterial = heat.renderer.material;
        defaultStrength = heatMaterial.GetFloat("strength");
        strength = defaultStrength;
        defaultTransparency = heatMaterial.GetFloat("transparency");
        transparency = defaultTransparency;
	}
        private PbrMetallicRoughness ExportPBRMetallicRoughness(UnityEngine.Material material)
        {
            var pbr = new PbrMetallicRoughness();

            if (material.HasProperty("_Color"))
            {
                pbr.BaseColorFactor = material.GetColor("_Color").ToNumericsColorRaw();
            }

            if (material.HasProperty("_MainTex"))
            {
                var mainTex = material.GetTexture("_MainTex");

                if (mainTex != null)
                {
                    pbr.BaseColorTexture = ExportTextureInfo(mainTex);
                    ExportTextureTransform(pbr.BaseColorTexture, material, "_MainTex");
                }
            }

            if (material.HasProperty("_Metallic"))
            {
                pbr.MetallicFactor = material.GetFloat("_Metallic");
            }

            if (material.HasProperty("_Roughness"))
            {
                pbr.RoughnessFactor = material.GetFloat("_Roughness");
            }
            else if (material.HasProperty("_Glossiness"))
            {
                pbr.RoughnessFactor = 1 - material.GetFloat("_Glossiness");
            }

            if (material.HasProperty("_MetallicRoughnessMap"))
            {
                var mrTex = material.GetTexture("_MetallicRoughnessMap");

                if (mrTex != null)
                {
                    pbr.MetallicRoughnessTexture = ExportTextureInfo(mrTex);
                    ExportTextureTransform(pbr.MetallicRoughnessTexture, material, "_MetallicRoughnessMap");
                }
            }
            else if (material.HasProperty("_MetallicGlossMap"))
            {
                var mgTex = material.GetTexture("_MetallicGlossMap");

                if (mgTex != null)
                {
                    pbr.MetallicRoughnessTexture = ExportTextureInfo(mgTex);
                    ExportTextureTransform(pbr.MetallicRoughnessTexture, material, "_MetallicGlossMap");
                }
            }

            return(pbr);
        }
        // Function to calculate padding required for Outline Width & Dilation for proper text alignment
        public static Vector4 GetFontExtent(Material material)
        {
            if (!material.HasProperty(ShaderUtilities.ID_GradientScale))
                return Vector4.zero;   // We are using an non SDF Shader.

            float scaleRatioA = material.GetFloat(ID_ScaleRatio_A);
            float faceDilate = material.GetFloat(ID_FaceDilate) * scaleRatioA;
            float outlineThickness = material.GetFloat(ID_OutlineWidth) * scaleRatioA;

            float extent = Mathf.Min(1, faceDilate + outlineThickness);
            extent *= material.GetFloat(ID_GradientScale);

            return new Vector4(extent, extent, extent, extent);
        }
Exemplo n.º 9
0
 public void SetToToCurrent()
 {
     if (_material = material)
     {
         to = _material.GetFloat(propertyID);
     }
 }
Exemplo n.º 10
0
 public void SetFromToCurrent()
 {
     if (_material = material)
     {
         from = _material.GetFloat(propertyID);
     }
 }
Exemplo n.º 11
0
 public override void OnRecord()
 {
     if (_material = material)
     {
         _original = _material.GetFloat(propertyID);
     }
 }
Exemplo n.º 12
0
        static NormalTextureInfo ExportNormalTextureInfo(
            UnityEngine.Texture texture,
            TextureMapType textureMapType,
            UnityEngine.Material material,
            IGltfWritable gltf
            )
        {
            var imageId = gltf.AddImage(texture);

            if (imageId < 0)
            {
                return(null);
            }
            var textureId = gltf.AddTexture(imageId);
            var info      = new NormalTextureInfo {
                index = textureId,
                // texCoord = 0 // TODO: figure out which UV set was used
            };

            if (material.HasProperty(MaterialGenerator.bumpScalePropId))
            {
                info.scale = material.GetFloat(MaterialGenerator.bumpScalePropId);
            }

            return(info);
        }
Exemplo n.º 13
0
 static public int GetFloat(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.GetFloat(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.GetFloat(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));
     }
 }
Exemplo n.º 14
0
        /// <summary>
        /// Export a normal texture from Unity to glTF.
        /// </summary>
        /// <param name="texture">Normal texture to export</param>
        /// <param name="material">Material the normal is used on</param>
        /// <param name="gltf">Context glTF to export to</param>
        /// <returns>glTF texture info</returns>
        protected static NormalTextureInfo ExportNormalTextureInfo(
            UnityEngine.Texture texture,
            UnityEngine.Material material,
            IGltfWritable gltf
            )
        {
            var texture2d = texture as Texture2D;

            if (texture2d == null)
            {
                return(null);
            }
            var imageExport = new NormalImageExport(texture2d);

            if (AddImageExport(gltf, imageExport, out var textureId))
            {
                var info = new NormalTextureInfo {
                    index = textureId,
                    // texCoord = 0 // TODO: figure out which UV set was used
                };

                if (material.HasProperty(MaterialGenerator.bumpScalePropId))
                {
                    info.scale = material.GetFloat(MaterialGenerator.bumpScalePropId);
                }
                return(info);
            }
            return(null);
        }
Exemplo n.º 15
0
        protected StandardMap(Material mat, int MaxLOD = 1000)
        {
            mat.shader.maximumLOD = MaxLOD;
            _material             = mat;

            if (mat.HasProperty(_Cutoff))
            {
                _alphaCutoff = mat.GetFloat(_Cutoff);
            }

            switch (mat.renderQueue)
            {
            case (int)RenderQueue.AlphaTest:
                _alphaMode = AlphaMode.MASK;
                break;

            case (int)RenderQueue.Transparent:
                _alphaMode = AlphaMode.BLEND;
                break;

            case (int)RenderQueue.Geometry:
            default:
                _alphaMode = AlphaMode.OPAQUE;
                break;
            }
        }
Exemplo n.º 16
0
 public override void AssignNewShaderToMaterial(Material material, Shader oldShader, Shader newShader)
 {
     if (material.HasProperty("_Emission"))
     {
         material.SetColor("_EmissionColor", material.GetColor("_Emission"));
     }
     base.AssignNewShaderToMaterial(material, oldShader, newShader);
     if ((oldShader == null) || !oldShader.name.Contains("Legacy Shaders/"))
     {
         SetupMaterialWithBlendMode(material, (BlendMode) ((int) material.GetFloat("_Mode")));
     }
     else
     {
         BlendMode opaque = BlendMode.Opaque;
         if (oldShader.name.Contains("/Transparent/Cutout/"))
         {
             opaque = BlendMode.Cutout;
         }
         else if (oldShader.name.Contains("/Transparent/"))
         {
             opaque = BlendMode.Fade;
         }
         material.SetFloat("_Mode", (float) opaque);
         Material[] mats = new Material[] { material };
         this.DetermineWorkflow(MaterialEditor.GetMaterialProperties(mats));
         MaterialChanged(material, this.m_WorkflowMode);
     }
 }
Exemplo n.º 17
0
    void Awake()
    {
        // make a private material
        animatedMaterial = Object.Instantiate(Helpers.LoadResource<Material>("TrillingFastPoint")) as Material;
        animatedMaterial.name = animatedMaterial.name.Replace("(Clone)", "");
        tunnelDDef = animatedMaterial.GetFloat("_TunnelD");
        tunnelDWarp = animatedMaterial.GetFloat("_TunnelDMax");
        tunnelRDef = animatedMaterial.GetFloat("_TunnelRadius");
        tunnelRWarp = animatedMaterial.GetFloat("_TunnelRadiusMax");

        if (renderer != null)
            renderer.sharedMaterial = animatedMaterial;
        foreach(MeshRenderer mr in GetComponentsInChildren<MeshRenderer>()) {
            mr.sharedMaterial = animatedMaterial;
        }
    }
Exemplo n.º 18
0
 static public int GetFloat(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);
             System.Single ret = self.GetFloat(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);
             System.Single ret = self.GetFloat(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);
     }
 }
Exemplo n.º 19
0
    static int GetFloat(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);
                float o    = obj.GetFloat(arg0);
                LuaDLL.lua_pushnumber(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);
                float  o    = obj.GetFloat(arg0);
                LuaDLL.lua_pushnumber(L, o);
                return(1);
            }
            else
            {
                return(LuaDLL.luaL_throw(L, "invalid arguments to method: UnityEngine.Material.GetFloat"));
            }
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e));
        }
    }
Exemplo n.º 20
0
 void checkRenderingMode(Material mat)
 {
     if (mat.GetFloat ("_Mode") != 3)
     {
         Debug.LogError ("Make sure the fadable material has a rendering mode of Transparent");
     }
 }
        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;
            }
        }
Exemplo n.º 22
0
		public static void SetMaterialKeywords(Material material, WorkflowMode workflowMode)
		{
			// 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"));
			if (workflowMode == WorkflowMode.Specular && material.HasProperty("_SpecGlossMap"))
				SetKeyword(material, "_SPECGLOSSMAP", material.GetTexture("_SpecGlossMap"));
			else if (workflowMode == WorkflowMode.Metallic && material.HasProperty("_MetallicGlossMap"))
				SetKeyword(material, "_METALLICGLOSSMAP", material.GetTexture("_MetallicGlossMap"));
			SetKeyword(material, "_PARALLAXMAP", material.GetTexture("_ParallaxMap"));
			SetKeyword(material, "_DETAIL_MULX2", material.GetTexture("_DetailAlbedoMap") || material.GetTexture("_DetailNormalMap"));

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

			// 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;
			}

			SetKeyword(material, "_VERTEXCOLOR", material.GetFloat("_IntensityVC") > 0f);
		}
Exemplo n.º 23
0
	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;
	}
Exemplo n.º 24
0
	void Awake () 
	{
		material = GetComponent<Renderer>().material;
		cubemap = (Cubemap)material.GetTexture("_Cube");
		rendererArray = GetComponentsInChildren<Renderer>();
		rotation = material.GetFloat("_Rotation");
		bookArray = GetComponentsInChildren<Book>();
	}
Exemplo n.º 25
0
 private void Awake()
 {
     Material m = new Material(renderer.material);
     renderer.material = m;
     originalShininess = m.GetFloat("_Shininess");
     glow = transform.Find("crystal glow").gameObject;
     glow.SetActive(false);
 }
	void Start()
	{
		if(gameObject.GetComponent<Renderer>().material)
		{
			meshMaterials = gameObject.GetComponent<Renderer>().material;
			originalRimPower = meshMaterials.GetFloat ("_RimPower");
			originalRimStrength = meshMaterials.GetFloat ("_RimStrength");

			ShineRim();

			Invoke ("ReturnToOriginalRim", timer);
		}
		else
		{
			this.enabled = false;
		}
	}
Exemplo n.º 27
0
    void Start()
    {
        lastParentPos = transform.parent.position;
        maxDistance = transform.localPosition.z;

        if (fadeLayer) {
            origMaterial = fadeLayer.sharedMaterial;
            oldScale = noiseScale = origMaterial.GetFloat("NoiseScale");
        }
    }
Exemplo n.º 28
0
    static JsonData getMetalData(UnityEngine.Material mat, Paladin paladin = null)
    {
        var ret = new JsonData();

        ret["type"] = mat.name;

        var param = new JsonData();

        param["eta"]    = Util.fromColor(mat.GetColor("_eta"));
        param["k"]      = Util.fromColor(mat.GetColor("k"));
        param["uRough"] = mat.GetFloat("_uRoughness");
        param["vRough"] = mat.GetFloat("_vRoughness");
        param["rough"]  = null;
        bool remap = mat.GetInt("_remapRoughness") != 0;

        param["remapRough"] = remap;
        ret["param"]        = param;

        return(ret);
    }
Exemplo n.º 29
0
        public MaterialProperty(Material material, string propertyName, float floatVal)
        {
            this.material = material;
            this.propertyName = propertyName;

            type = typeof (float);

            if (material.HasProperty(propertyName)) {
                value = material.GetFloat(propertyName);
                material.SetFloat(propertyName, floatVal);
            }
        }
        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);
        }
Exemplo n.º 31
0
    static JsonData getGlassData(UnityEngine.Material mat, Paladin paladin = null)
    {
        var ret = new JsonData();

        ret["type"] = mat.name;

        var param = new JsonData();

        param["Kr"]     = Util.fromColor(mat.GetColor("_Kr"));
        param["Kt"]     = Util.fromColor(mat.GetColor("_Kt"));
        param["uRough"] = mat.GetFloat("_uRoughness");
        param["vRough"] = mat.GetFloat("_vRoughness");
        param["eta"]    = mat.GetFloat("_eta");
        bool remap = mat.GetInt("_remapRoughness") != 0;
        bool thin  = mat.GetInt("_thin") != 0;

        param["remapRough"] = remap;
        param["thin"]       = thin;
        ret["param"]        = param;

        return(ret);
    }
        private NormalTextureInfo ExportNormalTextureInfo(UnityEngine.Texture texture, UnityEngine.Material material)
        {
            var info = new NormalTextureInfo();

            info.Index = ExportTexture(texture);

            if (material.HasProperty("_BumpScale"))
            {
                info.Scale = material.GetFloat("_BumpScale");
            }

            return(info);
        }
        private OcclusionTextureInfo ExportOcclusionTextureInfo(UnityEngine.Texture texture, UnityEngine.Material material)
        {
            var info = new OcclusionTextureInfo();

            info.Index = ExportTexture(texture);

            if (material.HasProperty("_OcclusionStrength"))
            {
                info.Strength = material.GetFloat("_OcclusionStrength");
            }

            return(info);
        }
Exemplo n.º 34
0
    static JsonData getMatteData(UnityEngine.Material mat, Paladin paladin = null)
    {
        var ret = new JsonData();

        ret["type"] = mat.name;

        var param = new JsonData();

        param["Kd"]    = Util.fromColor(mat.GetColor("_Kd"));
        param["sigma"] = mat.GetFloat("_sigma");
        ret["param"]   = param;

        return(ret);
    }
Exemplo n.º 35
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);
                    }

                }
            }

        }
Exemplo n.º 36
0
    public Sphere GetSphere()
    {
        var trans      = transform;
        var pos        = trans.position;
        var smoothness = m_UnityMaterial.GetFloat(Smoothness);

        return(new Sphere
        {
            material =
            {
                albedo    = m_UnityMaterial.GetAlbedo(),
                fuzziness = (1f - smoothness),
                type      = m_MaterialType
            },
            radius = trans.localScale.x / 2,
            center = pos,
        });
    }
        // This is a hack for GI. PVR looks in the shader for a texture named "_MainTex" to extract the opacity of the material for baking. In the same manner, "_Cutoff" and "_Color" are also necessary.
        // Since we don't have those parameters in our shaders we need to provide a "fake" useless version of them with the right values for the GI to work.
        private static void SetupMainTexForAlphaTestGI(UnityEngine.Material unityMaterial, string colorMapPropertyName, string colorPropertyName)
        {
            if (unityMaterial.HasProperty(colorMapPropertyName))
            {
                var mainTex = unityMaterial.GetTexture(colorMapPropertyName);
                unityMaterial.SetTexture(MainTex, mainTex);
            }

            if (unityMaterial.HasProperty(colorPropertyName))
            {
                var color = unityMaterial.GetColor(colorPropertyName);
                unityMaterial.SetColor(Color, color);
            }

            if (unityMaterial.HasProperty("_AlphaCutoff"))
            {
                var cutoff = unityMaterial.GetFloat(AlphaCutoff);
                unityMaterial.SetFloat(Cutoff, cutoff);
            }
        }
Exemplo n.º 38
0
        // Scale Ratios to ensure property ranges are optimum in Material Editor  
        public static void UpdateShaderRatios(Material mat, bool isBold)
        {
            float ratio_A = 1;
            float ratio_B = 1;
            float ratio_C = 1;

            bool isRatioEnabled = !mat.shaderKeywords.Contains(Keyword_Ratios);

            // Compute Ratio A
            float scale = mat.GetFloat(ID_GradientScale);
            float faceDilate = mat.GetFloat(ID_FaceDilate);
            float outlineThickness = mat.GetFloat(ID_OutlineWidth);
            float outlineSoftness = mat.GetFloat(ID_OutlineSoftness);
            float weight = !isBold ? mat.GetFloat(ID_WeightNormal) * 2 / scale : mat.GetFloat(ID_WeightBold) * 2 / scale;        
           
            float t = Mathf.Max(1, weight + faceDilate + outlineThickness + outlineSoftness);

            ratio_A = isRatioEnabled ? (scale - m_clamp) / (scale * t) : 1;
            mat.SetFloat(ID_ScaleRatio_A, ratio_A);

            // Compute Ratio B
            if (mat.HasProperty(ID_GlowOffset))
            {
                float glowOffset = mat.GetFloat(ID_GlowOffset);
                float glowOuter = mat.GetFloat(ID_GlowOuter);
                float range = (weight + faceDilate) * (scale - m_clamp);              
 
                t = Mathf.Max(1, glowOffset + glowOuter);

                ratio_B = isRatioEnabled ? Mathf.Max(0, scale - m_clamp - range) / (scale * t) : 1;
                mat.SetFloat(ID_ScaleRatio_B, ratio_B);
            }

            // Compute Ratio C
            if (mat.HasProperty(ID_UnderlayOffsetX))
            {
                float underlayOffsetX = mat.GetFloat(ID_UnderlayOffsetX);
                float underlayOffsetY = mat.GetFloat(ID_UnderlayOffsetY);
                float underlayDilate = mat.GetFloat(ID_UnderlayDilate);
                float underlaySoftness = mat.GetFloat(ID_UnderlaySoftness);

                float range = (weight + faceDilate) * (scale - m_clamp);
                t = Mathf.Max(1, Mathf.Max(Mathf.Abs(underlayOffsetX), Mathf.Abs(underlayOffsetY)) + underlayDilate + underlaySoftness);

                ratio_C = isRatioEnabled ? Mathf.Max(0, scale - m_clamp - range) / (scale * t) : 1;
                mat.SetFloat(ID_ScaleRatio_C, ratio_C);
            }
        }
Exemplo n.º 39
0
        /// <summary>
        /// Applies alpha mode and cutoff
        /// </summary>
        /// <param name="uMaterial">Source Unity Material</param>
        /// <param name="material">glTF material to apply settings on</param>
        protected static void SetAlphaModeAndCutoff(UnityEngine.Material uMaterial, Material material)
        {
            switch (uMaterial.GetTag("RenderType", false, ""))
            {
            case "TransparentCutout":
                if (uMaterial.HasProperty(k_Cutoff))
                {
                    material.alphaCutoff = uMaterial.GetFloat(k_Cutoff);
                }
                material.alphaModeEnum = Material.AlphaMode.MASK;
                break;

            case "Transparent":
            case "Fade":
                material.alphaModeEnum = Material.AlphaMode.BLEND;
                break;

            default:
                material.alphaModeEnum = Material.AlphaMode.OPAQUE;
                break;
            }
        }
Exemplo n.º 40
0
        static VrmLib.PBRMaterial ExportStandard(UnityEngine.Material src, GetOrCreateTextureDelegate map)
        {
            var material = new VrmLib.PBRMaterial(src.name)
            {
            };

            switch (src.GetTag("RenderType", true))
            {
            case "Transparent":
                material.AlphaMode = VrmLib.AlphaModeType.BLEND;
                break;

            case "TransparentCutout":
                material.AlphaMode   = VrmLib.AlphaModeType.MASK;
                material.AlphaCutoff = src.GetFloat("_Cutoff");
                break;

            default:
                material.AlphaMode = VrmLib.AlphaModeType.OPAQUE;
                break;
            }

            if (src.HasProperty("_Color"))
            {
                material.BaseColorFactor = src.color.linear.FromUnitySrgbToLinear();
            }

            if (src.HasProperty("_MainTex"))
            {
                material.BaseColorTexture = map(src, src.GetTexture("_MainTex"), VrmLib.Texture.ColorSpaceTypes.Srgb, VrmLib.Texture.TextureTypes.Default);
            }

            if (src.HasProperty("_MetallicGlossMap"))
            {
                // float smoothness = 0.0f;
                // if (m.HasProperty("_GlossMapScale"))
                // {
                //     smoothness = m.GetFloat("_GlossMapScale");
                // }

                material.MetallicRoughnessTexture = map(
                    src,
                    src.GetTexture("_MetallicGlossMap"),
                    VrmLib.Texture.ColorSpaceTypes.Linear,
                    VrmLib.Texture.TextureTypes.MetallicRoughness)?.Texture;
                if (material.MetallicRoughnessTexture != null)
                {
                    material.MetallicFactor = 1.0f;
                    // Set 1.0f as hard-coded. See: https://github.com/vrm-c/UniVRM/issues/212.
                    material.RoughnessFactor = 1.0f;
                }
            }

            if (material.MetallicRoughnessTexture == null)
            {
                if (src.HasProperty("_Metallic"))
                {
                    material.MetallicFactor = src.GetFloat("_Metallic");
                }

                if (src.HasProperty("_Glossiness"))
                {
                    material.RoughnessFactor = 1.0f - src.GetFloat("_Glossiness");
                }
            }

            if (src.HasProperty("_BumpMap"))
            {
                material.NormalTexture = map(src, src.GetTexture("_BumpMap"), VrmLib.Texture.ColorSpaceTypes.Linear, VrmLib.Texture.TextureTypes.NormalMap)?.Texture;

                if (src.HasProperty("_BumpScale"))
                {
                    material.NormalTextureScale = src.GetFloat("_BumpScale");
                }
            }

            if (src.HasProperty("_OcclusionMap"))
            {
                material.OcclusionTexture = map(src, src.GetTexture("_OcclusionMap"), VrmLib.Texture.ColorSpaceTypes.Linear, VrmLib.Texture.TextureTypes.Occlusion)?.Texture;

                if (src.HasProperty("_OcclusionStrength"))
                {
                    material.OcclusionTextureStrength = src.GetFloat("_OcclusionStrength");
                }
            }

            if (src.IsKeywordEnabled("_EMISSION"))
            {
                if (src.HasProperty("_EmissionColor"))
                {
                    var color = src.GetColor("_EmissionColor");
                    if (color.maxColorComponent > 1)
                    {
                        color /= color.maxColorComponent;
                    }
                    material.EmissiveFactor = new System.Numerics.Vector3(color.r, color.g, color.b);
                }

                if (src.HasProperty("_EmissionMap"))
                {
                    material.EmissiveTexture = map(src, src.GetTexture("_EmissionMap"), VrmLib.Texture.ColorSpaceTypes.Srgb, VrmLib.Texture.TextureTypes.Emissive)?.Texture;
                }
            }

            return(material);
        }
Exemplo n.º 41
0
 // helper functions to retrieve & set material values
 public static float GetMaterialFloat(System.String name, Material mat)
 {
     return mat.GetFloat(name);
 }
Exemplo n.º 42
0
        public VrmLib.TextureInfo GetOrCreateTexture(UnityEngine.Material material, UnityEngine.Texture srcTexture, VrmLib.Texture.ColorSpaceTypes colorSpace, VrmLib.Texture.TextureTypes textureType)
        {
            var texture = srcTexture as Texture2D;

            if (texture is null)
            {
                return(null);
            }

            if (!Textures.TryGetValue(texture, out VrmLib.TextureInfo info))
            {
                UnityEngine.Material converter = null;
                if (textureType == VrmLib.Texture.TextureTypes.NormalMap)
                {
                    converter = TextureConvertMaterial.GetNormalMapConvertUnityToGltf();
                }
                else if (textureType == VrmLib.Texture.TextureTypes.MetallicRoughness)
                {
                    float smoothness = 0.0f;
                    if (material.HasProperty("_GlossMapScale"))
                    {
                        smoothness = material.GetFloat("_GlossMapScale");
                    }

                    converter = TextureConvertMaterial.GetMetallicRoughnessUnityToGltf(smoothness);
                }
                else if (textureType == VrmLib.Texture.TextureTypes.Occlusion)
                {
                    converter = TextureConvertMaterial.GetOcclusionUnityToGltf();
                }

                var(bytes, mime) = GetImageEncodedBytes(
                    texture,
                    (colorSpace == VrmLib.Texture.ColorSpaceTypes.Linear) ? RenderTextureReadWrite.Linear : RenderTextureReadWrite.sRGB,
                    converter
                    );

                if (converter != null)
                {
                    UnityEngine.Object.DestroyImmediate(converter);
                }

                var sampler = new VrmLib.TextureSampler
                {
                    MagFilter = texture.filterMode.ToVrmLibMagFilter(),
                    MinFilter = texture.filterMode.ToVrmLibMinFilter(),
                    WrapS     = texture.wrapMode.ToVrmLib(),
                    WrapT     = texture.wrapMode.ToVrmLib(),
                };
                var image = new VrmLib.Image(texture.name, mime, VrmLib.ImageUsage.None, new ArraySegment <byte>(bytes));
                info = new VrmLib.TextureInfo(new VrmLib.ImageTexture(texture.name, sampler, image, colorSpace, textureType));
                Textures.Add(texture, info);

                if (Model != null)
                {
                    Model.Images.Add(image);
                    Model.Textures.Add(info.Texture);
                }
            }

            return(info);
        }
Exemplo n.º 43
0
        static bool ExportPbrMetallicRoughness(
            UnityEngine.Material uMaterial,
            Material material,
            IGltfWritable gltf,
            ICodeLogger logger
            )
        {
            var success = true;
            var pbr     = new PbrMetallicRoughness {
                metallicFactor = 0, roughnessFactor = 1.0f
            };

            MaskMapImageExport ormImageExport = null;

            if (uMaterial.IsKeywordEnabled(k_KeywordMaskMap) && uMaterial.HasProperty(k_MaskMap))
            {
                var maskMap = uMaterial.GetTexture(k_MaskMap) as Texture2D;
                if (maskMap != null)
                {
                    ormImageExport = new MaskMapImageExport(maskMap);
                    if (AddImageExport(gltf, ormImageExport, out var ormTextureId))
                    {
                        // TODO: smartly detect if metallic roughness channels are used and not create the
                        // texture info if not.
                        pbr.metallicRoughnessTexture = new TextureInfo {
                            index = ormTextureId
                        };
                        ExportTextureTransform(pbr.metallicRoughnessTexture, uMaterial, k_MaskMap, gltf);

                        // TODO: smartly detect if occlusion channel is used and not create the
                        // texture info if not.
                        material.occlusionTexture = new OcclusionTextureInfo {
                            index = ormTextureId
                        };
                        if (uMaterial.HasProperty(k_AORemapMin))
                        {
                            var occMin = uMaterial.GetFloat(k_AORemapMin);
                            material.occlusionTexture.strength = math.clamp(1 - occMin, 0, 1);
                            var occMax = uMaterial.GetFloat(k_AORemapMax);
                            if (occMax < 1f)
                            {
                                // TODO: remap texture values
                                logger?.Warning(LogCode.RemapUnsupported, "AO");
                            }
                        }
                    }
                }
            }

            if (uMaterial.HasProperty(k_BaseColor))
            {
                pbr.baseColor = uMaterial.GetColor(k_BaseColor);
            }
            else
            if (uMaterial.HasProperty(k_Color))
            {
                pbr.baseColor = uMaterial.GetColor(k_Color);
            }

            if (uMaterial.HasProperty(k_BaseColorMap))
            {
                // TODO if additive particle, render black into alpha
                // TODO use private Material.GetFirstPropertyNameIdByAttribute here, supported from 2020.1+
                var mainTex = uMaterial.GetTexture(k_BaseColorMap);

                if (mainTex)
                {
                    if (mainTex is Texture2D)
                    {
                        pbr.baseColorTexture = ExportTextureInfo(mainTex, gltf);
                        ExportTextureTransform(pbr.baseColorTexture, uMaterial, k_BaseColorMap, gltf);
                    }
                    else
                    {
                        logger?.Error(LogCode.TextureInvalidType, "main", uMaterial.name);
                        success = false;
                    }
                }
            }

            if (uMaterial.HasProperty(k_Metallic))
            {
                pbr.metallicFactor = uMaterial.GetFloat(k_Metallic);
            }

            if (ormImageExport != null && uMaterial.HasProperty(k_SmoothnessRemapMax))
            {
                pbr.roughnessFactor = uMaterial.GetFloat(k_SmoothnessRemapMax);
                if (uMaterial.HasProperty(k_SmoothnessRemapMin) && uMaterial.GetFloat(k_SmoothnessRemapMin) > 0)
                {
                    logger?.Warning(LogCode.RemapUnsupported, "Smoothness");
                }
            }
            else
            if (uMaterial.HasProperty(k_Smoothness))
            {
                pbr.roughnessFactor = 1f - uMaterial.GetFloat(k_Smoothness);
            }

            material.pbrMetallicRoughness = pbr;
            return(success);
        }
Exemplo n.º 44
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);
        }
Exemplo n.º 45
0
 private bool GUIMaterialSlider(Material material, string propertyID, string contentID)
 {
     bool flag = false;
     this.GUIPropBegin();
     float @float = material.GetFloat(propertyID);
     float num2 = EditorGUILayout.Slider(TreeEditorHelper.GetGUIContent(contentID), @float, 0f, 1f, new GUILayoutOption[0]);
     if (num2 != @float)
     {
         Undo.RegisterCompleteObjectUndo(material, "Material");
         material.SetFloat(propertyID, num2);
         flag = true;
     }
     this.GUIPropEnd();
     return flag;
 }
Exemplo n.º 46
0
        // Function to determine how much extra padding is required as a result of material properties like dilate, outline thickness, softness, glow, etc...
        public static float GetPadding(Material material, bool enableExtraPadding, bool isBold)
        {
            //Debug.Log("GetPadding() called.");

            if (isInitialized == false)
                GetShaderPropertyIDs();

            // Return if Material is null
            if (material == null) return 0;

            int extraPadding = enableExtraPadding ? 4 : 0;

            if (!material.HasProperty(ID_GradientScale))
                return extraPadding;   // We are using an non SDF Shader.

            Vector4 padding = Vector4.zero;
            Vector4 maxPadding = Vector4.zero;

            float faceDilate = 0;
            float faceSoftness = 0;
            float outlineThickness = 0;
            float scaleRatio_A = 0;
            float scaleRatio_B = 0;
            float scaleRatio_C = 0;

            float glowOffset = 0;
            float glowOuter = 0;

            float uniformPadding = 0;
            // Iterate through each of the assigned materials to find the max values to set the padding.

            // Update Shader Ratios prior to computing padding
            UpdateShaderRatios(material, isBold);

            string[] shaderKeywords = material.shaderKeywords;

            if (material.HasProperty(ID_ScaleRatio_A))
                scaleRatio_A = material.GetFloat(ID_ScaleRatio_A);

            if (material.HasProperty(ID_FaceDilate))
                faceDilate = material.GetFloat(ID_FaceDilate) * scaleRatio_A;

            if (material.HasProperty(ID_OutlineSoftness))
                faceSoftness = material.GetFloat(ID_OutlineSoftness) * scaleRatio_A;

            if (material.HasProperty(ID_OutlineWidth))
                outlineThickness = material.GetFloat(ID_OutlineWidth) * scaleRatio_A;

            uniformPadding = outlineThickness + faceSoftness + faceDilate;

            // Glow padding contribution
            if (material.HasProperty(ID_GlowOffset) && shaderKeywords.Contains(Keyword_Glow)) // Generates GC
            {
                if (material.HasProperty(ID_ScaleRatio_B))
                    scaleRatio_B = material.GetFloat(ID_ScaleRatio_B);

                glowOffset = material.GetFloat(ID_GlowOffset) * scaleRatio_B;
                glowOuter = material.GetFloat(ID_GlowOuter) * scaleRatio_B;
            }

            uniformPadding = Mathf.Max(uniformPadding, faceDilate + glowOffset + glowOuter);

            // Underlay padding contribution
            if (material.HasProperty(ID_UnderlaySoftness) && shaderKeywords.Contains(Keyword_Underlay)) // Generates GC
            {
                if (material.HasProperty(ID_ScaleRatio_C))
                    scaleRatio_C = material.GetFloat(ID_ScaleRatio_C);

                float offsetX = material.GetFloat(ID_UnderlayOffsetX) * scaleRatio_C;
                float offsetY = material.GetFloat(ID_UnderlayOffsetY) * scaleRatio_C;
                float dilate = material.GetFloat(ID_UnderlayDilate) * scaleRatio_C;
                float softness = material.GetFloat(ID_UnderlaySoftness) * scaleRatio_C;

                padding.x = Mathf.Max(padding.x, faceDilate + dilate + softness - offsetX);
                padding.y = Mathf.Max(padding.y, faceDilate + dilate + softness - offsetY);
                padding.z = Mathf.Max(padding.z, faceDilate + dilate + softness + offsetX);
                padding.w = Mathf.Max(padding.w, faceDilate + dilate + softness + offsetY);
            }

            padding.x = Mathf.Max(padding.x, uniformPadding);
            padding.y = Mathf.Max(padding.y, uniformPadding);
            padding.z = Mathf.Max(padding.z, uniformPadding);
            padding.w = Mathf.Max(padding.w, uniformPadding);

            padding.x += extraPadding;
            padding.y += extraPadding;
            padding.z += extraPadding;
            padding.w += extraPadding;

            padding.x = Mathf.Min(padding.x, 1);
            padding.y = Mathf.Min(padding.y, 1);
            padding.z = Mathf.Min(padding.z, 1);
            padding.w = Mathf.Min(padding.w, 1);

            maxPadding.x = maxPadding.x < padding.x ? padding.x : maxPadding.x;
            maxPadding.y = maxPadding.y < padding.y ? padding.y : maxPadding.y;
            maxPadding.z = maxPadding.z < padding.z ? padding.z : maxPadding.z;
            maxPadding.w = maxPadding.w < padding.w ? padding.w : maxPadding.w;

            float gradientScale = material.GetFloat(ID_GradientScale);
            padding *= gradientScale;

            // Set UniformPadding to the maximum value of any of its components.
            uniformPadding = Mathf.Max(padding.x, padding.y);
            uniformPadding = Mathf.Max(padding.z, uniformPadding);
            uniformPadding = Mathf.Max(padding.w, uniformPadding);

            return uniformPadding + 0.5f;
        }
Exemplo n.º 47
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);
    }
Exemplo n.º 48
0
        public VrmLib.Material Export10(UnityEngine.Material src, GetOrCreateTextureDelegate map)
        {
            switch (src.shader.name)
            {
            case "VRM/MToon":
            {
                var def = MToon.Utils.GetMToonParametersFromMaterial(src);
                return(new VrmLib.MToonMaterial(src.name)
                    {
                        Definition = def.ToVrmLib(src, map),
                    });
            }

            case "Unlit/Color":
                return(new VrmLib.UnlitMaterial(src.name)
                {
                    BaseColorFactor = src.color.FromUnitySrgbToLinear(),
                });

            case "Unlit/Texture":
                return(new VrmLib.UnlitMaterial(src.name)
                {
                    BaseColorTexture = map(src, src.mainTexture as Texture2D, VrmLib.Texture.ColorSpaceTypes.Srgb, VrmLib.Texture.TextureTypes.Default),
                });

            case "Unlit/Transparent":
                return(new VrmLib.UnlitMaterial(src.name)
                {
                    BaseColorTexture = map(src, src.mainTexture as Texture2D, VrmLib.Texture.ColorSpaceTypes.Srgb, VrmLib.Texture.TextureTypes.Default),
                    AlphaMode = VrmLib.AlphaModeType.BLEND,
                });

            case "Unlit/Transparent Cutout":
                return(new VrmLib.UnlitMaterial(src.name)
                {
                    BaseColorTexture = map(src, src.mainTexture as Texture2D, VrmLib.Texture.ColorSpaceTypes.Srgb, VrmLib.Texture.TextureTypes.Default),
                    AlphaMode = VrmLib.AlphaModeType.MASK,
                    AlphaCutoff = src.GetFloat("_Cutoff"),
                });

            case "UniGLTF/UniUnlit":
            case "VRM/UniUnlit":
            {
                var material = new VrmLib.UnlitMaterial(src.name)
                {
                    BaseColorFactor  = src.color.FromUnitySrgbToLinear(),
                    BaseColorTexture = map(src, src.mainTexture as Texture2D, VrmLib.Texture.ColorSpaceTypes.Srgb, VrmLib.Texture.TextureTypes.Default),
                    AlphaMode        = GetAlphaMode(src),
                    DoubleSided      = UniGLTF.UniUnlit.Utils.GetCullMode(src) == UniGLTF.UniUnlit.UniUnlitCullMode.Off,
                };
                if (material.AlphaMode == VrmLib.AlphaModeType.MASK)
                {
                    material.AlphaCutoff = src.GetFloat("_Cutoff");
                }
                // TODO: VertexColorMode
                return(material);
            }

            default:
                return(ExportStandard(src, map));
            }
        }
        private MaterialId ExportMaterial(UnityEngine.Material materialObj)
        {
            MaterialId id = GetMaterialId(_root, materialObj);

            if (id != null)
            {
                return(id);
            }

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

            if (ExportNames)
            {
                material.Name = materialObj.name;
            }

            if (materialObj.HasProperty("_Cutoff"))
            {
                material.AlphaCutoff = materialObj.GetFloat("_Cutoff");
            }

            switch (materialObj.GetTag("RenderType", false, ""))
            {
            case "TransparentCutout":
                material.AlphaMode = AlphaMode.MASK;
                break;

            case "Transparent":
                material.AlphaMode = AlphaMode.BLEND;
                break;

            default:
                material.AlphaMode = AlphaMode.OPAQUE;
                break;
            }

            material.DoubleSided = materialObj.HasProperty("_Cull") &&
                                   materialObj.GetInt("_Cull") == (float)UnityEngine.Rendering.CullMode.Off;

            if (materialObj.HasProperty("_EmissionColor"))
            {
                material.EmissiveFactor = materialObj.GetColor("_EmissionColor").ToNumericsColorRaw();
            }

            if (materialObj.HasProperty("_EmissionMap"))
            {
                var emissionTex = materialObj.GetTexture("_EmissionMap");

                if (emissionTex != null)
                {
                    material.EmissiveTexture = ExportTextureInfo(emissionTex);

                    ExportTextureTransform(material.EmissiveTexture, materialObj, "_EmissionMap");
                }
            }

            if (materialObj.HasProperty("_BumpMap"))
            {
                var normalTex = materialObj.GetTexture("_BumpMap");

                if (normalTex != null)
                {
                    material.NormalTexture = ExportNormalTextureInfo(normalTex, materialObj);
                    ExportTextureTransform(material.NormalTexture, materialObj, "_BumpMap");
                }
            }

            if (materialObj.HasProperty("_OcclusionMap"))
            {
                var occTex = materialObj.GetTexture("_OcclusionMap");
                if (occTex != null)
                {
                    material.OcclusionTexture = ExportOcclusionTextureInfo(occTex, materialObj);
                    ExportTextureTransform(material.OcclusionTexture, materialObj, "_OcclusionMap");
                }
            }

            switch (materialObj.shader.name)
            {
            case "Standard":
            case "GLTF/GLTFStandard":
                material.PbrMetallicRoughness = ExportPBRMetallicRoughness(materialObj);
                break;

            case "GLTF/GLTFConstant":
                material.CommonConstant = ExportCommonConstant(materialObj);
                break;
            }

            _materials.Add(materialObj);

            id = new MaterialId {
                Id   = _root.Materials.Count,
                Root = _root
            };
            _root.Materials.Add(material);

            return(id);
        }
Exemplo n.º 50
0
	//Convert one Material from TCP1 to TCP2
	static private void ConvertMaterial(Material m)
	{
		if(m == null)
			return;

		if(m.shader == null)
			return;

		string originalShader = m.shader.name;

		if(originalShader.Contains("Toony Colors Pro 2"))
		{
			Debug.LogWarning("Skipping '" + m.name + "'\nMaterial already has TCP2 shader");
			return;
		}
		else if(!originalShader.Contains("Toony Colors Pro/"))
		{
			Debug.LogWarning("Skipping '" + m.name + "'\nMaterial doesn't have TCP1 shader");
			return;
		}

		// Keyword list
		List<string> tcp2Keywords = new List<string>();
		tcp2Keywords.Add("TCP2_RAMPTEXT");	//TCP1 only supports textured ramps

		// Analyze shader name to determine its features
		string[] nameParts = originalShader.Split(new string[]{"/"}, System.StringSplitOptions.RemoveEmptyEntries);

		if(nameParts.Length != 4)
		{
			Debug.LogWarning("Skipping '" + m.name + "'\nIconrrect number of parts in the name");
			return;
		}

		// 0 = Toony Colors Pro
		// 1 = Normal, Outline, OutlineConst, Outline Z-Correct, OutlineConst Z-Correct, Rim Outline
		// 2 = OneDirLight, MultipleLights
		// 3 = Basic, Basic Rim, Bumped, Bumped Rim, Bumped Specular, Bumped Specular Rim, Specular, Specular Rim

		switch(nameParts[1])
		{
			case "Normal":					break;
			case "Outline":					tcp2Keywords.Add("OUTLINES");	break;
			case "OutlineConst":			tcp2Keywords.Add("OUTLINES"); tcp2Keywords.Add("TCP2_OUTLINE_CONST_SIZE");	break;
			case "Outline Z-Correct":		tcp2Keywords.Add("OUTLINES"); tcp2Keywords.Add("TCP2_ZSMOOTH_ON");	break;
			case "OutlineConst Z-Correct":	tcp2Keywords.Add("OUTLINES"); tcp2Keywords.Add("TCP2_OUTLINE_CONST_SIZE"); tcp2Keywords.Add("TCP2_ZSMOOTH_ON");	break;
			case "Rim Outline":				tcp2Keywords.Add("TCP2_RIMO"); break;

			default: Debug.LogWarning("Material: " + m.name + ", Shader: " + originalShader + "\nUnrecognized nameParts[1]: '" + nameParts[1] + "'"); break;
		}

		bool isMobile = false;
		switch(nameParts[2])
		{
			case "OneDirLight":		isMobile = true; break;
			case "MultipleLights":	isMobile = false; break;
			
			default: Debug.LogWarning("Material: " + m.name + ", Shader: " + originalShader + "\nUnrecognized nameParts[2]: '" + nameParts[2] + "'"); break;
		}

		if(nameParts[3].Contains("Bumped"))			tcp2Keywords.Add("TCP2_BUMP");
		if(nameParts[3].Contains("Rim"))			tcp2Keywords.Add("TCP2_RIM");
		if(nameParts[3].Contains("Specular"))		tcp2Keywords.Add("TCP2_SPEC");

		string features = originalShader + "\nMOBILE: " + isMobile.ToString();
		foreach(string kw in tcp2Keywords)
		{
			features += "\n" + kw;
		}

		// Variables conversion
		Color highlightColor = m.HasProperty("_Color") ? m.GetColor("_Color") : Color.white;
		float rimMin = m.HasProperty("_RimPower") ? (m.GetFloat("_RimPower") / 4f) : 0.5f;
		float outline = m.HasProperty("_Outline") ? (m.GetFloat("_Outline") * 100f) : 1.0f;

		//Find TCP2 Shader
		string[] keywords = tcp2Keywords.ToArray();
		string tcp2ShaderName = GetShaderFromKeywords(isMobile, keywords);

		Shader tcp2Shader = Shader.Find(tcp2ShaderName);
		if(tcp2Shader == null)
		{
			Debug.LogWarning("Skipping '" + m.name + "'\nCouldn't find corresponding TCP2 shader\nGenerated shader name: " + tcp2ShaderName);
			return;
		}
		else
		{
			// Valid TCP2 Shader found
			Undo.RecordObject(m, string.Format("Material TCP2 conversion", m.name));
			m.shader = tcp2Shader;
			m.shaderKeywords = keywords;

			// Set converted variables
			//Highlight Color
			if(m.HasProperty("_HColor"))
			{
				m.SetColor("_HColor", highlightColor);
				m.SetColor("_Color", Color.white);
			}
			else
			{
				Debug.LogWarning("Property _HColor not found in resulting TCP2 shader:\n" + tcp2ShaderName);
			}
			//Rim power
			if(m.HasProperty("_RimMin"))
			{
				m.SetFloat("_RimMin", rimMin);
			}
			//Outline width
			if(m.HasProperty("_Outline"))
			{
				m.SetFloat("_Outline", outline);
			}

			EditorUtility.SetDirty(m);
		}
	}
Exemplo n.º 51
0
        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);
        }
Exemplo n.º 52
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);
        }
Exemplo n.º 53
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);
        }
        Color GetColorIfNoTexture(Material mat, ShaderTextureProperty texProperty)
        {
            if (texProperty.isNormalMap){
                return new Color(.5f,.5f,1f);
            } else if (texProperty.name.Equals("_MainTex")){
                if (mat != null && mat.HasProperty("_Color")){
                    try{ //need try because can't garantee _Color is a color
                        return mat.GetColor("_Color");
                    } catch (Exception){}
                }
            } else if (texProperty.name.Equals ("_SpecGlossMap")){
                if (mat != null && mat.HasProperty("_SpecColor")){
                    try{ //need try because can't garantee _Color is a color
                        Color c = mat.GetColor("_SpecColor");
                        if (mat.HasProperty("_Glossiness")){
                            try{
                                c.a = mat.GetFloat("_Glossiness");
                            } catch (Exception){}
                        }
                        Debug.LogWarning(c);
                        return c;
                    } catch (Exception){}
                }
            } else if (texProperty.name.Equals("_MetallicGlossMap")){
                if (mat != null && mat.HasProperty("_Metallic")){
                    try{ //need try because can't garantee _Metallic is a float
                        float v = mat.GetFloat("_Metallic");
                        Color c = new Color(v,v,v);
                        if (mat.HasProperty("_Glossiness")){
                            try{
                                c.a = mat.GetFloat("_Glossiness");
                            } catch (Exception){}
                        }
                        return c;
                    } catch (Exception){}
                }
            } else if (texProperty.name.Equals("_ParallaxMap")){
                return new Color(0f,0f,0f,0f);
            } else if (texProperty.name.Equals("_OcclusionMap")){
                return new Color(1f,1f,1f,1f);
            } else if (texProperty.name.Equals("_EmissionMap")){
                if (mat != null){
                    if (mat.HasProperty("_EmissionScaleUI")){
                        //Standard shader has weird behavior if EmissionMap has never
                        //been set then no EmissionColorUI color picker. If has ever
                        //been set then is EmissionColorUI color picker.
                        if (mat.HasProperty("_EmissionColor") &&
                            mat.HasProperty ("_EmissionColorUI")){
                            try{
                                Color c1 = mat.GetColor("_EmissionColor");
                                Color c2 = mat.GetColor("_EmissionColorUI");
                                float f = mat.GetFloat("_EmissionScaleUI");
                                if (c1 == new Color(0f,0f,0f,0f) &&
                                    c2 == new Color(1f,1f,1f,1f)){
                                    //is virgin Emission values
                                    return new Color(f,f,f,f);
                                } else { //non virgin Emission values
                                    return c2;
                                }
                            } catch(Exception){}

                        } else {
                            try{ //need try because can't garantee _Color is a color
                                float f = mat.GetFloat("_EmissionScaleUI");
                                return new Color(f,f,f,f);
                            } catch (Exception){}
                        }
                    }
                }
            } else if (texProperty.name.Equals("_DetailMask")){
                return new Color(0f,0f,0f,0f);
            }
            return new Color(1f,1f,1f,0f);
        }
        private BabylonMaterial DumpMaterial(Material material, Renderer renderer)
        {
            if (!materialsDictionary.ContainsKey(material.name))
            {
                var bMat = new BabylonMaterial
                {
                    name = material.name,
                    id = Guid.NewGuid().ToString(),
                    diffuse = new float[4],
                    specular = new float[4]
                };

                bMat.diffuse[0] = 1.0f;
                bMat.diffuse[1] = 1.0f;
                bMat.diffuse[2] = 1.0f;
                bMat.diffuse[3] = 1.0f;

                if (material.HasProperty("_Color"))
                {
                    bMat.diffuse = material.color.ToFloat();
                }

                if (material.HasProperty("_SpecColor"))
                {
                    var specColor = material.GetColor("_SpecColor");
                    bMat.specular = specColor.ToFloat();
                }

                if (material.HasProperty("_Shininess"))
                {
                    var specShininess = material.GetFloat("_Shininess");
                    bMat.specularPower = specShininess * 128;
                }

                if (material.HasProperty("_Emission"))
                {
                    var emissiveColor = material.GetColor("_Emission");
                    bMat.emissive = emissiveColor.ToFloat();
                }

                if (material.mainTexture)
                {
                    var mainTexturePath = AssetDatabase.GetAssetPath(material.mainTexture);
                    bMat.diffuseTexture = new BabylonTexture
                    {
                        uScale = material.mainTextureScale.x,
                        vScale = material.mainTextureScale.y,
                        uOffset = material.mainTextureOffset.x,
                        vOffset = material.mainTextureOffset.y
                    };

                    var mainTexture2D = material.mainTexture as Texture2D;

                    CopyTexture(mainTexturePath, mainTexture2D, bMat.diffuseTexture);

                    var alphaCuttOff = 0f;

                    if (material.HasProperty("_Cutoff"))
                    {
                        alphaCuttOff = material.GetFloat("_Cutoff");
                    }

                    if ((mainTexture2D && mainTexture2D.alphaIsTransparency) || alphaCuttOff > 0)
                    {
                        bMat.diffuseTexture.hasAlpha = true;
                        bMat.backFaceCulling = false;
                    }

                    bMat.diffuse[0] = 1.0f;
                    bMat.diffuse[1] = 1.0f;
                    bMat.diffuse[2] = 1.0f;
                    bMat.diffuse[3] = 1.0f;
                }

                bMat.bumpTexture = DumpTextureFromMaterial(material, "_BumpMap");
                bMat.emissiveTexture = DumpTextureFromMaterial(material, "_Illum");
                bMat.ambientTexture = DumpTextureFromMaterial(material, "_LightMap");
                bMat.reflectionTexture = DumpTextureFromMaterial(material, "_Cube");

                //if (bMat.ambientTexture == null && renderer.lightmapIndex >= 0 && renderer.lightmapIndex != 255 && LightmapSettings.lightmaps.Length > renderer.lightmapIndex)
                //{
                //    var lightmap = LightmapSettings.lightmaps[renderer.lightmapIndex].lightmapFar;
                //    bMat.ambientTexture = DumpTexture(lightmap);
                //    bMat.ambientTexture.coordinatesIndex = 1;

                //    bMat.ambientTexture.uScale = renderer.lightmapTilingOffset.x;
                //    bMat.ambientTexture.vScale = renderer.lightmapTilingOffset.y;

                //    bMat.ambientTexture.uOffset = renderer.lightmapTilingOffset.z;
                //    bMat.ambientTexture.vOffset = renderer.lightmapTilingOffset.w;
                //}

                materialsDictionary.Add(bMat.name, bMat);
                return bMat;
            }

            return materialsDictionary[material.name];
        }
Exemplo n.º 56
0
        private BabylonMaterial DumpMaterial(Material material, Renderer renderer)
        {
            var materialNotSupported = false; 

            if (!materialsDictionary.ContainsKey(material.name))
            {
                var bMat = new BabylonStandardMaterial
                {
                    name = material.name,
                    id = Guid.NewGuid().ToString(),
                    diffuse = new float[4],
                    specular = new float[4]
                };

                bMat.diffuse[0] = 1.0f;
                bMat.diffuse[1] = 1.0f;
                bMat.diffuse[2] = 1.0f;
                bMat.diffuse[3] = 1.0f;

                if (material.HasProperty("_Color"))
                {
                    bMat.diffuse = material.color.ToFloat();
                }

                if (material.HasProperty("_SpecColor"))
                {
                    var specColor = material.GetColor("_SpecColor");
                    bMat.specular = specColor.ToFloat();
                }

                if (material.HasProperty("_Shininess"))
                {
                    var specShininess = material.GetFloat("_Shininess");
                    bMat.specularPower = specShininess * 128;
                }

                if (material.HasProperty("_Emission"))
                {
                    var emissiveColor = material.GetColor("_Emission");
                    bMat.emissive = emissiveColor.ToFloat();
                }

                if (material.mainTexture && material.mainTexture.GetType().FullName == "UnityEngine.ProceduralTexture")
                {
                    materialNotSupported = true;
                    Debug.LogWarning("ProceduralTexture: " + material.mainTexture.name + " not supported by Babylon.js");
                }

                if (material.mainTexture && !(materialNotSupported))
                {
                    var mainTexturePath = AssetDatabase.GetAssetPath(material.mainTexture);
                    bMat.diffuseTexture = new BabylonTexture
                    {
                        uScale = material.mainTextureScale.x,
                        vScale = material.mainTextureScale.y,
                        uOffset = material.mainTextureOffset.x,
                        vOffset = material.mainTextureOffset.y
                    };

                    var mainTexture2D = material.mainTexture as Texture2D;

                    CopyTexture(mainTexturePath, mainTexture2D, bMat.diffuseTexture);

                    var alphaCuttOff = 0f;

                    if (material.HasProperty("_Cutoff"))
                    {
                        alphaCuttOff = material.GetFloat("_Cutoff");
                    }

                    if ((mainTexture2D && mainTexture2D.alphaIsTransparency) || alphaCuttOff > 0)
                    {
                        bMat.diffuseTexture.hasAlpha = true;
                        bMat.backFaceCulling = false;
                    }

                    bMat.diffuse[0] = 1.0f;
                    bMat.diffuse[1] = 1.0f;
                    bMat.diffuse[2] = 1.0f;
                    bMat.diffuse[3] = 1.0f;
                }

                bMat.bumpTexture = DumpTextureFromMaterial(material, "_BumpMap");
                bMat.emissiveTexture = DumpTextureFromMaterial(material, "_Illum");
                bMat.ambientTexture = DumpTextureFromMaterial(material, "_LightMap");
                bMat.reflectionTexture = DumpTextureFromMaterial(material, "_Cube");

                if (bMat.ambientTexture == null && renderer.lightmapIndex >= 0 && renderer.lightmapIndex != 255 && LightmapSettings.lightmaps.Length > renderer.lightmapIndex)
                {
                    var lightmap = LightmapSettings.lightmaps[renderer.lightmapIndex].lightmapFar;
                    bMat.lightmapTexture = DumpTexture(lightmap, isLightmap: true);
                    bMat.lightmapTexture.coordinatesIndex = 1;
                    bMat.useLightmapAsShadowmap = true;

                    bMat.lightmapTexture.uScale = renderer.lightmapScaleOffset.x;
                    bMat.lightmapTexture.vScale = renderer.lightmapScaleOffset.y;

                    bMat.lightmapTexture.uOffset = renderer.lightmapScaleOffset.z;
                    bMat.lightmapTexture.vOffset = renderer.lightmapScaleOffset.w;
                }

                materialsDictionary.Add(bMat.name, bMat);
                return bMat;
            }

            return materialsDictionary[material.name];
        }
Exemplo n.º 57
0
 private static float GetMaterialFloat(Material material, string propertyID, out bool success)
 {
     success = false;
     if (!material.HasProperty(propertyID))
     {
         return 0f;
     }
     success = true;
     return material.GetFloat(propertyID);
 }
Exemplo n.º 58
0
        private BabylonMaterial DumpPBRMaterial(Material material, Renderer renderer)
        {
            if (!materialsDictionary.ContainsKey(material.name))
            {
                var bMat = new BabylonPBRMaterial
                {
                    name = material.name,
                    id = Guid.NewGuid().ToString(),
                    albedoColor = new float[4]
                };

                if (material.HasProperty("_Color"))
                {
                    bMat.albedoColor = material.color.ToFloat();
                }

                bMat.albedoTexture = DumpTextureFromMaterial(material, "_MainTex");

                if (material.HasProperty("_Glossiness"))
                {
                    bMat.microSurface = material.GetFloat("_Glossiness");
                }

                if (material.HasProperty("_Metallic"))
                {
                    var metallic = material.GetFloat("_Metallic");
                    bMat.reflectivityColor = new float[] { metallic, metallic, metallic };
                }

                bMat.bumpTexture = DumpTextureFromMaterial(material, "_BumpMap");

                materialsDictionary.Add(bMat.name, bMat);
                return bMat;
            }

            return materialsDictionary[material.name];
        }
Exemplo n.º 59
0
        private static GLTF.Schema.Material ConvertSeinPBRMaterial(UnityEngine.Material mat, ExporterEntry entry)
        {
            var material = new GLTF.Schema.Material();

            material.Name = mat.name;

            bool isMetal = mat.GetInt("workflow") == 0;
            bool isUnlit = mat.GetInt("unlit") == 1;

            if (!isMetal)
            {
                // special
                entry.AddExtension("KHR_materials_pbrSpecularGlossiness");
                material.Extensions = new Dictionary <string, Extension>();
            }
            else
            {
                material.PbrMetallicRoughness = new PbrMetallicRoughness();
            }
            bool hasTransparency = ProcessTransparency(mat, material);

            if (isUnlit || isMetal)
            {
                if (mat.GetTexture("_baseColorMap") != null)
                {
                    var id = entry.SaveTexture((Texture2D)mat.GetTexture("_baseColorMap"), hasTransparency);
                    material.PbrMetallicRoughness.BaseColorTexture = new TextureInfo {
                        Index = id
                    };
                }

                if (mat.GetColor("_baseColor") != null)
                {
                    Color c = mat.GetColor("_baseColor");
                    material.PbrMetallicRoughness.BaseColorFactor = Utils.ExportColor(c);
                }
            }

            if (isUnlit)
            {
                if (material.Extensions == null)
                {
                    material.Extensions = new Dictionary <string, Extension>();
                }
                ExtensionManager.Serialize(ExtensionManager.GetExtensionName(typeof(KHR_materials_unlitExtensionFactory)), entry, material.Extensions);
            }
            else if (isMetal)
            {
                bool hasPBRMap = mat.GetTexture("_metallicMap") != null;
                if (hasPBRMap)
                {
                    Texture2D metallicTexture  = (Texture2D)mat.GetTexture("_metallicMap");
                    Texture2D roughnessTexture = (Texture2D)mat.GetTexture("_roughnessMap");
                    Texture2D occlusion        = (Texture2D)mat.GetTexture("_occlusionMap");

                    var metalRoughTextureAo = CreateOcclusionMetallicRoughnessTexture(
                        ref metallicTexture, ref roughnessTexture, ref occlusion
                        );
                    var assetPath = AssetDatabase.GetAssetPath(metallicTexture);
                    var ext       = Path.GetExtension(assetPath);
                    var id        = entry.SaveTexture(metalRoughTextureAo, hasTransparency, assetPath.Replace(ext, "-orm") + ext);
                    material.PbrMetallicRoughness.MetallicRoughnessTexture = new TextureInfo {
                        Index = id
                    };

                    if (occlusion != null)
                    {
                        material.OcclusionTexture = new OcclusionTextureInfo
                        {
                            Index    = id,
                            Strength = mat.GetFloat("_occlusionStrength")
                        };
                    }
                }

                material.PbrMetallicRoughness.MetallicFactor  = mat.GetFloat("_metallic");
                material.PbrMetallicRoughness.RoughnessFactor = mat.GetFloat("_roughness");
            }
            else
            {
                TextureInfo specGlossMap = null;
                TextureInfo diffuseMap   = null;
                var         diffuseColor = new GLTF.Math.Color();

                if (mat.GetTexture("_baseColorMap") != null)
                {
                    var id = entry.SaveTexture((Texture2D)mat.GetTexture("_baseColorMap"), hasTransparency);
                    diffuseMap = new TextureInfo {
                        Index = id
                    };
                }

                if (mat.GetColor("_baseColor") != null)
                {
                    Color c = mat.GetColor("_baseColor");
                    diffuseColor = Utils.ExportColor(c);
                }

                bool hasPBRMap = mat.GetTexture("_specularGlossinessMap") != null;

                if (hasPBRMap)
                {
                    specGlossMap = new TextureInfo {
                        Index = entry.SaveTexture((Texture2D)mat.GetTexture("_specularGlossinessMap"), true)
                    };
                }

                var specularFactor   = hasPBRMap ? Color.white : (Color)Utils.ExportColorVec4(mat.GetColor("_specular"));
                var glossinessFactor = hasPBRMap ? 1.0f : mat.GetFloat("_glossiness");

                if (material.Extensions == null)
                {
                    material.Extensions = new Dictionary <string, Extension>();
                }
                material.Extensions.Add(
                    "KHR_materials_pbrSpecularGlossiness",
                    new KHR_materials_pbrSpecularGlossinessExtension(
                        diffuseColor, diffuseMap,
                        new GLTF.Math.Vector3(specularFactor.r, specularFactor.g, specularFactor.b),
                        glossinessFactor, specGlossMap
                        )
                    );

                Texture2D occlusion = (Texture2D)mat.GetTexture("_occlusionMap");
                if (occlusion != null)
                {
                    material.OcclusionTexture = new OcclusionTextureInfo
                    {
                        Index    = entry.SaveTexture((Texture2D)mat.GetTexture("_occlusionMap"), false),
                        Strength = mat.GetFloat("_occlusionStrength")
                    };
                }
            }

            if (mat.GetTexture("_normalMap") != null)
            {
                material.NormalTexture = new NormalTextureInfo
                {
                    Index = entry.SaveTexture((Texture2D)mat.GetTexture("_normalMap"), false),
                };
            }

            if (mat.GetTexture("_emissionMap") != null)
            {
                material.EmissiveTexture = new TextureInfo
                {
                    Index = entry.SaveTexture((Texture2D)mat.GetTexture("_emissionMap"), false),
                };
            }

            var emissive = mat.GetColor("_emission");

            if (!emissive.Equals(new Color(0, 0, 0)))
            {
                material.EmissiveFactor = Utils.ExportColor(emissive);
            }

            if (mat.GetInt("envReflection") != (int)SeinPBRShaderGUI.EnvReflection.Off || (ExporterSettings.Lighting.ambient && (RenderSettings.ambientMode == UnityEngine.Rendering.AmbientMode.Skybox || RenderSettings.ambientMode == UnityEngine.Rendering.AmbientMode.Trilight)))
            {
                if (material.Extensions == null)
                {
                    material.Extensions = new Dictionary <string, Extension>();
                }
                ExtensionManager.Serialize(ExtensionManager.GetExtensionName(typeof(Sein_imageBasedLightingExtensionFactory)), entry, material.Extensions, mat);
            }

            return(material);
        }
Exemplo n.º 60
0
        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;
                }
            }
        }