} //GetBones private static void GetMeshes(Transform transform, List<SkinnedMeshRenderer> meshes, List<UnityEngine.Material> materials, List<UnityEngine.Texture> textures) { foreach (Transform t in transform) { if (t.GetComponent<SkinnedMeshRenderer>()) { SkinnedMeshRenderer mesh = t.gameObject.GetComponent<SkinnedMeshRenderer>(); meshes.Add(t.gameObject.GetComponent<SkinnedMeshRenderer>()); UnityEngine.Material material = mesh.sharedMaterial; if (!materials.Contains(material)) { materials.Add(material); if (material.HasProperty("_Base_Tex_SRGB")) { UnityEngine.Texture texture = material.GetTexture("_Base_Tex_SRGB"); if (texture != null) { if (!textures.Contains(texture)) { textures.Add(material.GetTexture("_Base_Tex_SRGB")); } //if } //if } //if } //if } //if } //foreach } //GetMeshes
static void SetMaterialKeywords(Material material) { SetKeyword(material, "_METALLICGLOSSMAP", material.GetTexture("_MetallicGlossMap")); SetKeyword(material, "_NORMALMAP", material.GetTexture("_BumpMap")); var emissive = material.GetColor("_EmissionColor").maxColorComponent > 0.1f / 255; SetKeyword(material, "_EMISSION", emissive); }
public static void CheckTexture (string n, Material m, List<string> l) { Debug.Log( "Has property " + n + " " + m.HasProperty (n) ); Debug.Log( "Get texture " + n + " " + m.GetTexture(n) ); if (m.HasProperty (n) && m.GetTexture(n) != null) { l.Add (n); } }
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); }
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); }
static void AddTexturesInMaterialToList(ref ArrayList list, Material material) { // look for textures found in the built in shaders string[] builtInShadersTextureNames = {"_MainTex", "_BumpMap", "_Detail", "_ColorControl", "_ColorControlCube", "_ReflectionTex", "_RefractionTex", "_Fresnel", "_LightMap", "_Cube", "_FrontTex", "_BackTex", "_LeftTex", "_RightTex", "_UpTex", "_DownTex", "_Tex"}; foreach (string textureName in builtInShadersTextureNames) { if (material.GetTexture(textureName) != null) list.Add(material.GetTexture(textureName)); } }
static public int GetTexture(IntPtr l) { try{ if (matchType(l, 2, typeof(System.String))) { UnityEngine.Material self = (UnityEngine.Material)checkSelf(l); System.String a1; checkType(l, 2, out a1); UnityEngine.Texture ret = self.GetTexture(a1); pushValue(l, ret); return(1); } else if (matchType(l, 2, typeof(System.Int32))) { UnityEngine.Material self = (UnityEngine.Material)checkSelf(l); System.Int32 a1; checkType(l, 2, out a1); UnityEngine.Texture ret = self.GetTexture(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); } }
static public int GetTexture(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.GetTexture(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.GetTexture(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)); } }
/// <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; } } } }
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; } }
static int GetTexture(IntPtr L) { try { int count = LuaDLL.lua_gettop(L); if (count == 2 && TypeChecker.CheckTypes(L, 1, typeof(UnityEngine.Material), typeof(int))) { UnityEngine.Material obj = (UnityEngine.Material)ToLua.ToObject(L, 1); int arg0 = (int)LuaDLL.lua_tonumber(L, 2); UnityEngine.Texture o = obj.GetTexture(arg0); ToLua.Push(L, o); return(1); } else if (count == 2 && TypeChecker.CheckTypes(L, 1, typeof(UnityEngine.Material), typeof(string))) { UnityEngine.Material obj = (UnityEngine.Material)ToLua.ToObject(L, 1); string arg0 = ToLua.ToString(L, 2); UnityEngine.Texture o = obj.GetTexture(arg0); ToLua.Push(L, o); return(1); } else { return(LuaDLL.luaL_throw(L, "invalid arguments to method: UnityEngine.Material.GetTexture")); } } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
static void ExportUnlit(Material material, UnityEngine.Material uMaterial, IGltfWritable gltf, ICodeLogger logger) { gltf.RegisterExtensionUsage(Extension.MaterialsUnlit); material.extensions = material.extensions ?? new MaterialExtension(); material.extensions.KHR_materials_unlit = new MaterialUnlit(); var pbr = material.pbrMetallicRoughness ?? new PbrMetallicRoughness(); if (uMaterial.HasProperty(k_Color)) { pbr.baseColor = uMaterial.GetColor(k_Color); } if (uMaterial.HasProperty(k_MainTex)) { var mainTex = uMaterial.GetTexture(k_MainTex); if (mainTex != null) { if (mainTex is Texture2D) { pbr.baseColorTexture = ExportTextureInfo(mainTex, TextureMapType.Main, gltf); ExportTextureTransform(pbr.baseColorTexture, uMaterial, k_MainTex, gltf); } else { logger?.Error(LogCode.TextureInvalidType, "main", material.name); } } } material.pbrMetallicRoughness = pbr; }
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; }
public static string CheckMaterial(Material mat, BuildTarget buildTarget) { if (mat == null || mat.shader == null) { return null; } string shaderName = mat.shader.name; int lOD = ShaderUtil.GetLOD(mat.shader); bool flag = Array.Exists<string>(PerformanceChecks.kShadersWithMobileVariants, (string s) => s == shaderName); bool flag2 = PerformanceChecks.IsMobileBuildTarget(buildTarget); if (buildTarget == BuildTarget.Android && ShaderUtil.HasClip(mat.shader)) { return PerformanceChecks.FormattedTextContent("PerformanceChecks.ShaderWithClipAndroid", new object[0]); } if (!(mat.GetTag("PerformanceChecks", true).ToLower() == "false")) { if (flag) { if (flag2 && mat.HasProperty("_Color") && mat.GetColor("_Color") == new Color(1f, 1f, 1f, 1f)) { return PerformanceChecks.FormattedTextContent("PerformanceChecks.ShaderUsesWhiteColor", new object[] { "Mobile/" + shaderName }); } if (flag2 && shaderName.StartsWith("Particles/")) { return PerformanceChecks.FormattedTextContent("PerformanceChecks.ShaderHasMobileVariant", new object[] { "Mobile/" + shaderName }); } if (shaderName == "RenderFX/Skybox" && mat.HasProperty("_Tint") && mat.GetColor("_Tint") == new Color(0.5f, 0.5f, 0.5f, 0.5f)) { return PerformanceChecks.FormattedTextContent("PerformanceChecks.ShaderMobileSkybox", new object[] { "Mobile/Skybox" }); } } if (lOD >= 300 && flag2 && !shaderName.StartsWith("Mobile/")) { return PerformanceChecks.FormattedTextContent("PerformanceChecks.ShaderExpensive", new object[0]); } if (shaderName.Contains("VertexLit") && mat.HasProperty("_Emission")) { Color color = mat.GetColor("_Emission"); if (color.r >= 0.5f && color.g >= 0.5f && color.b >= 0.5f) { return PerformanceChecks.FormattedTextContent("PerformanceChecks.ShaderUseUnlit", new object[0]); } } if (mat.HasProperty("_BumpMap") && mat.GetTexture("_BumpMap") == null) { return PerformanceChecks.FormattedTextContent("PerformanceChecks.ShaderNoNormalMap", new object[0]); } } return null; }
void Awake () { material = GetComponent<Renderer>().material; cubemap = (Cubemap)material.GetTexture("_Cube"); rendererArray = GetComponentsInChildren<Renderer>(); rotation = material.GetFloat("_Rotation"); bookArray = GetComponentsInChildren<Book>(); }
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); }
public void ProcGUI(Maid maid, string slotName, Material material, string propName) { // material 抽出 => texture 抽出 var tex2d = material.GetTexture(propName) as Texture2D; if (tex2d == null || string.IsNullOrEmpty(tex2d.name)) return ; var key = CreateKey(maid.Param.status.guid, slotName, material.name, tex2d.name); FilterParam fp = filterParams.GetOrAdd(key.ToString()); fp.ProcGUI(tex2d); }
public void SetSkybox(float blend, Material skybox1, Material skybox2) { foreach (Material mtl in transform.renderer.materials) { string texName = "_" + mtl.name.Replace(" (Instance)","").Substring(6) + "Tex"; mtl.SetFloat("_Blend", blend); mtl.SetTexture("_MainTex", skybox1.GetTexture(texName)); mtl.SetTexture("_SubTex", skybox2.GetTexture(texName)); } }
void Awake() { _material = GetComponent<Renderer>().material; _texture = _material.GetTexture(TexturePropertyName); _matSize = System.Math.Min(_texture.width, _texture.height); _material.SetTextureScale(TexturePropertyName, new Vector2(1f / ((float)XCells), 1f / ((float)YCells))); SetSpriteIndex(0); }
private void Awake() { if (instance == null) { instance = this; } else if (instance != this) { Destroy(gameObject); return; } mainTexture = defMat.GetTexture("_MainTex"); }
public void WriteToJson(IResMgr resmgr, Material mat, MyJson.JsonNode_Object json) { json["shaderName"] = new MyJson.JsonNode_ValueString(this.shaderName); if (jsonConfig.ContainsKey("params")) { foreach (var item in jsonConfig["params"].asDict()) { //Debug.Log(item.Value); string type = item.Value.asDict()["type"].AsString(); string flag = item.Value.asDict()["flags"].AsString(); string name = item.Value.asDict()["name"].AsString(); if (type == "Float" || type == "Range") { json[name] = new MyJson.JsonNode_ValueNumber(mat.GetFloat(name)); } else if (type == "Vector") { json[name] = new MyJson.JsonNode_ValueString(StringHelper.ToString(mat.GetVector(name))); } else if (type == "Color") { json[name] = new MyJson.JsonNode_ValueString(StringHelper.ToString((Color32)mat.GetColor(name))); } else if (type == "Texture") { string texdim = item.Value.asDict()["texdim"].AsString(); var tex = mat.GetTexture(name); if (tex != null) { if (texdim == "Tex2D") { string texname = resmgr.SaveTexture(tex as Texture2D); json[name] = new MyJson.JsonNode_ValueString(texname); } else { throw new Exception("not support texdim:" + texdim); } } } else { throw new Exception("not support type:" + type); } } } }
/// <summary> /// Uses shader util to get all of the textures referenced by this material /// </summary> /// <returns>The all textures.</returns> /// <param name="mat">Mat.</param> public static IEnumerable<Texture> GetAllTextures(Material mat) { List<Texture> allTextures = new List<Texture>(); int count = ShaderUtil.GetPropertyCount(mat.shader); for (int i = 0; i < count; i++) { if (ShaderUtil.GetPropertyType(mat.shader, i) == ShaderUtil.ShaderPropertyType.TexEnv) { string propertyName = ShaderUtil.GetPropertyName(mat.shader, i); allTextures.Add(mat.GetTexture(propertyName)); } } return allTextures; }
void Start() { player = GameObject.FindWithTag("Player"); agent = GetComponent<NavMeshAgent>(); startPosition = transform.position; seenByCharacter = false; agent.speed = GlobalVariables.Instance.minotaurusSpeed; mat = GetComponentInChildren<MeshRenderer>().material; glowy = mat.GetTexture("_Illum"); mat.SetTexture("_Illum", schwarz); }
public bool UpdateTex(Maid maid, Material mat, EditTarget texEdit) { var tex2d = mat.GetTexture(texEdit.propName) as Texture2D; if (tex2d == null || string.IsNullOrEmpty(tex2d.name)) return false; var key = CreateKey(maid.Param.status.guid, texEdit.slotName, mat.name, tex2d.name); FilterParam filterParam = filterParams.GetOrAdd(key.ToString()); // スライダー変更がなければ何もしない if (!filterParam.IsDirty) return false; //LogUtil.DebugLogF("Update Texture. slot={0}, material={0}, tex={1}", texEdit.slotName, mat.name, tex2d.name); FilterTexture(tex2d, filterParam); return true; }
// called before first Update void Start() { cameraDist = cameraOffset; cameraDistSpeed = 0f; // get current material defaultMaterial = charRenderer.sharedMaterial; // clone editor's material transparencyMaterial = new Material(transparencyMaterial); // Copy texture to transparency material transparencyMaterial.SetTexture("_MainTex", defaultMaterial.GetTexture("_MainTex")); transparencyMaterial.color = defaultMaterial.color; aimDirection = Vector3.forward; }
// Going to have to allow submesh support so need to say which material we are effecting // Same for all uv mods really, see how max does it, prob mat id, max 32 mats possibly void Init() { MeshRenderer mr = GetComponent<MeshRenderer>(); mat = mr.sharedMaterial; if ( mat != null ) { Texture tex = mat.GetTexture("_MainTex"); if ( tex != null ) { twidth = tex.width; theight = tex.height; } } }
public void StartAnimation(Texture[] frames, Material material, float durationSec, Action onFinish, float secPerFrame, bool loop) { Debug.Log ("StartAnimation"); this.frames = frames; this.material = material; if (secPerFrame < 0) { this.secPerFrame = durationSec / frames.GetLength (0); } else { this.secPerFrame = secPerFrame; } this.loop = loop; this.oldTexture = material.GetTexture("_MainTex"); playingAnimation = true; currentFrameIndex = -1; lastFrameChangeTime = 0; this.onFinish = onFinish; }
public static Dictionary<string,Texture> getTextures(Material material){ string assetPath=AssetDatabase.GetAssetPath(material); if (String.IsNullOrEmpty(assetPath)) return null; Shader shader=material.shader; Dictionary<string,Texture> textures=new Dictionary<string, Texture>(); for (int i = 0; i < ShaderUtil.GetPropertyCount(shader) ; i++) { if (ShaderUtil.GetPropertyType(shader,i) == ShaderUtil.ShaderPropertyType.TexEnv){ string propertyName=ShaderUtil.GetPropertyName(shader,i); textures.Add(propertyName, material.GetTexture(propertyName)); } } return textures; }
public static string CheckMaterial(Material mat, BuildTarget buildTarget) { // ISSUE: object of a compiler-generated type is created // ISSUE: variable of a compiler-generated type PerformanceChecks.\u003CCheckMaterial\u003Ec__AnonStoreyBE materialCAnonStoreyBe = new PerformanceChecks.\u003CCheckMaterial\u003Ec__AnonStoreyBE(); if ((UnityEngine.Object) mat == (UnityEngine.Object) null || (UnityEngine.Object) mat.shader == (UnityEngine.Object) null) return (string) null; // ISSUE: reference to a compiler-generated field materialCAnonStoreyBe.shaderName = mat.shader.name; int lod = ShaderUtil.GetLOD(mat.shader); // ISSUE: reference to a compiler-generated method bool flag1 = Array.Exists<string>(PerformanceChecks.kShadersWithMobileVariants, new Predicate<string>(materialCAnonStoreyBe.\u003C\u003Em__22D)); bool flag2 = PerformanceChecks.IsMobileBuildTarget(buildTarget); if (!(mat.GetTag("PerformanceChecks", true).ToLower() == "false")) { if (flag1) { if (flag2 && mat.HasProperty("_Color") && mat.GetColor("_Color") == new Color(1f, 1f, 1f, 1f)) { // ISSUE: reference to a compiler-generated field return PerformanceChecks.FormattedTextContent("Shader is using white color which does nothing; Consider using {0} shader for performance.", (object) ("Mobile/" + materialCAnonStoreyBe.shaderName)); } // ISSUE: reference to a compiler-generated field if (flag2 && materialCAnonStoreyBe.shaderName.StartsWith("Particles/")) { // ISSUE: reference to a compiler-generated field return PerformanceChecks.FormattedTextContent("Consider using {0} shader on this platform for performance.", (object) ("Mobile/" + materialCAnonStoreyBe.shaderName)); } // ISSUE: reference to a compiler-generated field if (materialCAnonStoreyBe.shaderName == "RenderFX/Skybox" && mat.HasProperty("_Tint") && mat.GetColor("_Tint") == new Color(0.5f, 0.5f, 0.5f, 0.5f)) return PerformanceChecks.FormattedTextContent("Skybox shader is using gray color which does nothing; Consider using {0} shader for performance.", (object) "Mobile/Skybox"); } // ISSUE: reference to a compiler-generated field if (lod >= 300 && flag2 && !materialCAnonStoreyBe.shaderName.StartsWith("Mobile/")) return PerformanceChecks.FormattedTextContent("Shader might be expensive on this platform. Consider switching to a simpler shader; look under Mobile shaders."); // ISSUE: reference to a compiler-generated field if (materialCAnonStoreyBe.shaderName.Contains("VertexLit") && mat.HasProperty("_Emission")) { Color color = mat.GetColor("_Emission"); if ((double) color.r >= 0.5 && (double) color.g >= 0.5 && (double) color.b >= 0.5) return PerformanceChecks.FormattedTextContent("Looks like you're using VertexLit shader to simulate an unlit object (white emissive). Use one of Unlit shaders instead for performance."); } if (mat.HasProperty("_BumpMap") && (UnityEngine.Object) mat.GetTexture("_BumpMap") == (UnityEngine.Object) null) return PerformanceChecks.FormattedTextContent("Normal mapped shader without a normal map. Consider using a non-normal mapped shader for performance."); } return (string) null; }
private static void CreateMaterialAsset(UnityEngine.Material material, string assetName) { var prefabName = Path.GetFileNameWithoutExtension(assetName); var directorty = Path.GetDirectoryName(assetName); var noiseTexture = material.GetTexture("_NoiseTexture"); if (noiseTexture != null && !AssetDatabase.Contains(noiseTexture)) { AssetDatabase.CreateAsset(noiseTexture, Path.Combine(directorty, prefabName + "_noiseTexture.asset")); } if (!AssetDatabase.Contains(material)) { AssetDatabase.CreateAsset(material, Path.Combine(directorty, prefabName + ".mat")); } }
// Function used to find all materials which reference a font atlas so we can update all their references. public static Material[] FindMaterialReferences(Material mat) { // Find all Materials used in the project. Material[] mats = Resources.FindObjectsOfTypeAll<Material>(); List<Material> refs = new List<Material>(); for (int i = 0; i < mats.Length; i++) { if (mats[i].HasProperty(ShaderUtilities.ID_MainTex) && mats[i].GetTexture(ShaderUtilities.ID_MainTex) == mat.GetTexture(ShaderUtilities.ID_MainTex)) { refs.Add(mats[i]); //Debug.Log(mats[i].name); } } return refs.ToArray(); }
private string GetKey(Maid maid, string slotName, Material material, string propName) { if (maid == null || material == null || string.IsNullOrEmpty(propName)) { return null; } Texture2D tex2d = material.GetTexture(propName) as Texture2D; if (tex2d == null || string.IsNullOrEmpty(tex2d.name)) { return null; } return string.Format("{0}/{1}/{2}/{3}" , maid.Param.status.guid , slotName , material.name , tex2d.name); }
public StandardMaterial(UnityEngine.Material source, UnityEngine.MeshRenderer instanceData) : base(source, instanceData) { diffuseColor = source.color; uvOffset = source.mainTextureOffset; uvScale = source.mainTextureScale; diffuseTexture = ResourceCache.Instance.GetTexture(source.mainTexture); if (diffuseTexture == null) { diffuseTexture = ResourceCache.Instance.GetTexture(UnityEngine.Texture2D.whiteTexture); } normalTexture = ResourceCache.Instance.GetTexture(source.GetTexture("_BumpMap")); if (instanceData.lightmapIndex >= 0) { lightmapTexture = ResourceCache.Instance.GetTexture(LightmapSettings.lightmaps[instanceData.lightmapIndex].lightmapColor); } }
// 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); } }
public void SaveTextures(Material material) { Cache(); List<String> keys = cache.Keys.Select(x=>(string)x).ToList(); foreach (String key in keys) { String name = key; object obj = cache[key]; if ( obj == null ) { Texture2D value = (Texture2D)material.GetTexture(name); if( value != null ) { cache[key] = value; } } } }
private MaterialCommonConstant ExportCommonConstant(UnityEngine.Material materialObj) { if (_root.ExtensionsUsed == null) { _root.ExtensionsUsed = new List <string>(new string[] { "KHR_materials_common" }); } else if (!_root.ExtensionsUsed.Contains("KHR_materials_common")) { _root.ExtensionsUsed.Add("KHR_materials_common"); } var constant = new MaterialCommonConstant(); if (materialObj.HasProperty("_AmbientFactor")) { constant.AmbientFactor = materialObj.GetColor("_AmbientFactor").ToNumericsColorRaw(); } if (materialObj.HasProperty("_LightMap")) { var lmTex = materialObj.GetTexture("_LightMap"); if (lmTex != null) { constant.LightmapTexture = ExportTextureInfo(lmTex); ExportTextureTransform(constant.LightmapTexture, materialObj, "_LightMap"); } } if (materialObj.HasProperty("_LightFactor")) { constant.LightmapFactor = materialObj.GetColor("_LightFactor").ToNumericsColorRaw(); } return(constant); }
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); }
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); }
public SkyboxMaterial(UnityEngine.Material source) : base(source) { texture = ResourceCache.Instance.GetTexture(source.GetTexture("_Tex")); cullSettings = new CullSettings(); }
MaterialDescriptionFromUnityMaterial(UnityEngine.Material unityMaterial) { var result = new Model.AnimatedExportObjectModelDescription.MaterialsDescription.Material(); result.name = unityMaterial.name; result.mainTexture = ConvertUnityTextureToTextureDescription("_Tex0", unityMaterial.GetTexture("_Tex0")); result.mainTextureOffset = new Vector2d(unityMaterial.mainTextureOffset.x, unityMaterial.mainTextureOffset.y); result.mainTextureScale = new Vector2d(unityMaterial.mainTextureScale.x, unityMaterial.mainTextureScale.y); return(result); }
private static void FillInNulls(Material mat, ShaderProperties property) { if (mat.HasProperty(property.propertyName)) { if (mat.GetTexture(property.propertyName) == null) { mat.SetTexture(property.propertyName, defaultTexture); } } }
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); }
/// <summary> /// Changes the font to be used for this text object. /// </summary> /// <param name="newFont">Reference to the SpriteFont to be used for this text object.</param> /// <param name="fontMaterial">The material to use for the new font.</param> public void SetFont(SpriteFont newFont, Material fontMaterial) { font = newFont.fontDef; spriteFont = newFont; renderer.sharedMaterial = fontMaterial; texture = fontMaterial.GetTexture("_MainTex"); SetPixelToUV(texture); lineSpaceSize = lineSpacing * spriteFont.LineHeight * worldUnitsPerTexel; CalcSize(); LayoutText(); }
static bool ExportPbrMetallicRoughness(UnityEngine.Material material, out PbrMetallicRoughness pbr, IGltfWritable gltf, ICodeLogger logger) { var success = true; pbr = new PbrMetallicRoughness { metallicFactor = 0, roughnessFactor = 1.0f }; if (material.HasProperty(k_BaseColor)) { pbr.baseColor = material.GetColor(k_BaseColor); } else if (material.HasProperty(k_Color)) { pbr.baseColor = material.GetColor(k_Color); } if (material.HasProperty(k_TintColor)) { //particles use _TintColor instead of _Color float white = 1; if (material.HasProperty(k_Color)) { var c = material.GetColor(k_Color); white = (c.r + c.g + c.b) / 3.0f; //multiply alpha by overall whiteness of TintColor } pbr.baseColor = material.GetColor(k_TintColor) * white; } if (material.HasProperty(k_MainTex) || material.HasProperty("_BaseMap")) { // TODO if additive particle, render black into alpha // TODO use private Material.GetFirstPropertyNameIdByAttribute here, supported from 2020.1+ var mainTexProperty = material.HasProperty(k_BaseMap) ? k_BaseMap : k_MainTex; var mainTex = material.GetTexture(mainTexProperty); if (mainTex) { if (mainTex is Texture2D) { pbr.baseColorTexture = ExportTextureInfo(mainTex, TextureMapType.Main, gltf); ExportTextureTransform(pbr.baseColorTexture, material, mainTexProperty, gltf); } else { logger?.Error(LogCode.TextureInvalidType, "main", material.name); success = false; } } } if (material.HasProperty(k_Metallic) && !material.IsKeywordEnabled("_METALLICGLOSSMAP")) { pbr.metallicFactor = material.GetFloat(k_Metallic); } if (material.HasProperty(k_Glossiness) || material.HasProperty(k_Smoothness)) { var smoothnessPropertyName = material.HasProperty(k_Smoothness) ? k_Smoothness : k_Glossiness; var metallicGlossMap = material.GetTexture(k_MetallicGlossMap); float smoothness = material.GetFloat(smoothnessPropertyName); // legacy workaround: the UnityGLTF shaders misuse k_Glossiness as roughness but don't have a keyword for it. if (material.shader.name.Equals("GLTF/PbrMetallicRoughness", StringComparison.Ordinal)) { smoothness = 1 - smoothness; } pbr.roughnessFactor = (metallicGlossMap != null && material.HasProperty(k_GlossMapScale)) ? material.GetFloat(k_GlossMapScale) : 1f - smoothness; } if (material.HasProperty(k_MetallicGlossMap)) { var mrTex = material.GetTexture(k_MetallicGlossMap); if (mrTex != null) { if (mrTex is Texture2D) { // pbr.metallicRoughnessTexture = ExportTextureInfo(mrTex, TextureMapType.MetallicGloss); // if (material.IsKeywordEnabled("_METALLICGLOSSMAP")) // pbr.metallicFactor = 1.0f; // ExportTextureTransform(pbr.MetallicRoughnessTexture, material, k_MetallicGlossMap); } else { logger?.Error(LogCode.TextureInvalidType, "metallic/gloss", material.name); success = false; } } } return(success); }
static JsonData getUnityMatData(UnityEngine.Material mat, Paladin paladin = null) { var ret = new JsonData(); ret["type"] = mat.name; var param = new JsonData(); var albedo = new JsonData(); var color = Util.fromColor(mat.GetColor("_Color")); albedo.Add(color); var uvOffset = mat.GetVector("_MainTex_ST"); var mainTex = mat.GetTexture("_MainTex"); var texData = new JsonData(); if (mainTex != null) { texData["type"] = "image"; var srcFn = AssetDatabase.GetAssetPath(mainTex); var idx = srcFn.LastIndexOf("/"); var dstFn = paladin.outputDir + "/" + paladin.outputName + srcFn.Substring(idx); var fn = srcFn.Substring(idx + 1); if (!File.Exists(dstFn)) { FileUtil.CopyFileOrDirectory(srcFn, dstFn); } texData["param"] = new JsonData(); texData["subtype"] = "spectrum"; if (uvOffset != null) { texData["param"]["uvOffset"] = Util.fromVec4(uvOffset); } texData["param"]["fileName"] = fn; texData["param"]["fromBasePath"] = true; } else { texData.Add(1); texData.Add(1); texData.Add(1); } albedo.Add(texData); param["albedo"] = albedo; param["bumpScale"] = mat.GetFloat("_BumpScale"); var emission = mat.GetColor("_EmissionColor"); if (emission != null) { var emissionData = new JsonData(); param["emission"] = emissionData; emissionData["Le"] = new JsonData(); emissionData["Le"]["colorType"] = 1; emissionData["Le"]["color"] = Util.fromColor(emission); } var normalMap = mat.GetTexture("_BumpMap"); if (normalMap != null) { var normalMapData = new JsonData(); var srcFn = AssetDatabase.GetAssetPath(normalMap); var idx = srcFn.LastIndexOf("/"); var dstFn = paladin.outputDir + "/" + paladin.outputName + srcFn.Substring(idx); var fn = srcFn.Substring(idx + 1); if (!File.Exists(dstFn)) { FileUtil.CopyFileOrDirectory(srcFn, dstFn); } normalMapData["param"] = new JsonData(); normalMapData["subtype"] = "spectrum"; normalMapData["type"] = "image"; normalMapData["param"]["fileName"] = fn; normalMapData["param"]["fromBasePath"] = true; if (uvOffset != null) { normalMapData["param"]["uvOffset"] = Util.fromVec4(uvOffset); } param["normalMap"] = normalMapData; } var bumpMap = mat.GetTexture("_ParallaxMap"); if (bumpMap != null) { var bumpMapData = new JsonData(); var srcFn = AssetDatabase.GetAssetPath(bumpMap); var idx = srcFn.LastIndexOf("/"); var dstFn = paladin.outputDir + "/" + paladin.outputName + srcFn.Substring(idx); var fn = srcFn.Substring(idx + 1); if (!File.Exists(dstFn)) { FileUtil.CopyFileOrDirectory(srcFn, dstFn); } bumpMapData["param"] = new JsonData(); bumpMapData["subtype"] = "spectrum"; bumpMapData["type"] = "image"; bumpMapData["param"]["fileName"] = fn; bumpMapData["param"]["fromBasePath"] = true; if (uvOffset != null) { bumpMapData["param"]["uvOffset"] = Util.fromVec4(uvOffset); } param["bumpMap"] = bumpMapData; } param["roughness"] = 1 - mat.GetFloat("_Glossiness"); param["metallic"] = mat.GetFloat("_Metallic"); ret["param"] = param; return(ret); }
private static GLTF.Schema.Material ConvertSeinCustomMaterial(UnityEngine.Material mat, ExporterEntry entry) { if (_tempGO == null) { _tempGO = new GameObject(); } var customMaterial = _tempGO.AddComponent <SeinCustomMaterial>(); var className = mat.shader.name.Replace("Sein/", ""); if (!className.Contains("Material")) { className += "Material"; } customMaterial.className = className; customMaterial.renderOrder = mat.renderQueue; var floatArray = new List <SeinMaterialUniformFloat>(); var vector4Array = new List <SeinMaterialUniformFloatVec4>(); var textureArray = new List <SeinMaterialUniformTexture>(); for (int i = 0; i < ShaderUtil.GetPropertyCount(mat.shader); i += 1) { var propType = ShaderUtil.GetPropertyType(mat.shader, i); var propName = ShaderUtil.GetPropertyName(mat.shader, i); if (propName == "cloneForInst") { customMaterial.cloneForInst = mat.GetInt("cloneForInst") != 0; continue; } if (ShaderUtil.IsShaderPropertyHidden(mat.shader, i)) { continue; } var n = propName; //if (propName.Substring(0, 1) == "_") //{ // propName = propName.Substring(1); //} switch (propType) { case ShaderUtil.ShaderPropertyType.Float: case ShaderUtil.ShaderPropertyType.Range: floatArray.Add(new SeinMaterialUniformFloat { name = propName, value = mat.GetFloat(n) }); break; case ShaderUtil.ShaderPropertyType.Color: vector4Array.Add(new SeinMaterialUniformFloatVec4 { name = propName, value = mat.GetColor(n) }); break; case ShaderUtil.ShaderPropertyType.Vector: vector4Array.Add(new SeinMaterialUniformFloatVec4 { name = propName, value = mat.GetVector(n) }); break; case ShaderUtil.ShaderPropertyType.TexEnv: if (mat.GetTexture(n) != null) { textureArray.Add(new SeinMaterialUniformTexture { name = propName, value = (Texture2D)mat.GetTexture(n) }); } break; } customMaterial.uniformsFloat = floatArray.ToArray(); customMaterial.uniformsFloatVec4 = vector4Array.ToArray(); customMaterial.uniformsTexture = textureArray.ToArray(); } var tempM = new GLTF.Schema.Material(); customMaterial.transparent = ProcessTransparency(mat, tempM); var m = ConvertMaterial(customMaterial, entry); return(m); }
public 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; } } }
public static Texture GetMaterialTexture(System.String theName, Material mat) { return mat.GetTexture(theName); }
/** * Tries to extract texture channels from a blend material. * @todo - build normals as well? */ public static Texture2D[] GetBlendTextures(Material material) { string src = GetSource(material.shader); int expectedTextureCount = GetTextureChannelCount(src); MatchCollection non_bump_textures = Regex.Matches(src, "_.*?\\s\\(\".*?\", 2D\\)\\s=\\s\"[^(bump)|(gray)]*?\""); Texture2D[] textures = new Texture2D[ expectedTextureCount ]; int i = 0; foreach(Match m in non_bump_textures) { int space = m.Value.IndexOf(" "); if(space < 0) { textures[i] = null; } else { string prop = m.Value.Substring(0, space); if( material.HasProperty(prop) ) textures[i] = material.GetTexture(prop) as Texture2D; else textures[i] = null; } if(++i >= expectedTextureCount) break; } return textures; }
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); }
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); }
/// <summary> /// Converts a Unity material to a glTF material. /// </summary> /// <param name="uMaterial">Source material</param> /// <param name="material">Resulting material</param> /// <param name="gltf">Associated IGltfWriter. Is used for adding images and textures.</param> /// <param name="logger">Logger used for reporting</param> /// <returns>True if no errors occured, false otherwise</returns> public override bool ConvertMaterial(UnityEngine.Material uMaterial, out Material material, IGltfWritable gltf, ICodeLogger logger) { var success = true; material = new Material { name = uMaterial.name, pbrMetallicRoughness = new PbrMetallicRoughness { metallicFactor = 0, roughnessFactor = 1.0f } }; SetAlphaModeAndCutoff(uMaterial, material); material.doubleSided = IsDoubleSided(uMaterial); // // Emission // if (uMaterial.HasProperty(k_EmissiveColor)) { var emissionColor = uMaterial.GetColor(k_EmissiveColor); // Clamp emissiveColor to 0..1 var maxFactor = math.max(emissionColor.r, math.max(emissionColor.g, emissionColor.b)); if (maxFactor > 1f) { emissionColor.r /= maxFactor; emissionColor.g /= maxFactor; emissionColor.b /= maxFactor; // TODO: use maxFactor as emissiveStrength (KHR_materials_emissive_strength) } material.emissive = emissionColor; } if (uMaterial.HasProperty(k_EmissionColorMap)) { var emissionTex = uMaterial.GetTexture(k_EmissionColorMap); if (emissionTex != null) { if (emissionTex is Texture2D) { material.emissiveTexture = ExportTextureInfo(emissionTex, gltf); ExportTextureTransform(material.emissiveTexture, uMaterial, k_EmissionColorMap, gltf); } else { logger?.Error(LogCode.TextureInvalidType, "emission", material.name); success = false; } } } // // Normal Map // if ( uMaterial.HasProperty(k_NormalMap) && uMaterial.IsKeywordEnabled(k_KeywordNormalMapTangentSpace) ) { var normalTex = uMaterial.GetTexture(k_NormalMap); if (normalTex != null) { if (normalTex is Texture2D) { material.normalTexture = ExportNormalTextureInfo(normalTex, uMaterial, gltf); ExportTextureTransform(material.normalTexture, uMaterial, k_NormalMap, gltf); } else { logger?.Error(LogCode.TextureInvalidType, "normal", uMaterial.name); success = false; } } } var mainTexProperty = uMaterial.HasProperty(k_BaseColorMap) ? k_BaseColorMap : k_MainTex; if (IsUnlit(uMaterial)) { ExportUnlit(material, uMaterial, mainTexProperty, gltf, logger); } else { success &= ExportPbrMetallicRoughness( uMaterial, material, gltf, logger ); } return(success); }
/// <summary> /// Converts a Unity material to a glTF material. /// </summary> /// <param name="uMaterial">Source material</param> /// <param name="material">Resulting material</param> /// <param name="gltf">Associated IGltfWriter. Is used for adding images and textures.</param> /// <param name="logger">Logger used for reporting</param> /// <returns>True if no errors occured, false otherwise</returns> internal static bool ConvertMaterial(UnityEngine.Material uMaterial, out Material material, IGltfWritable gltf, ICodeLogger logger) { var success = true; material = new Material { name = uMaterial.name, pbrMetallicRoughness = new PbrMetallicRoughness { metallicFactor = 0, roughnessFactor = 1.0f } }; 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; } material.doubleSided = uMaterial.HasProperty(k_Cull) && uMaterial.GetInt(k_Cull) == (int)CullMode.Off; if (uMaterial.IsKeywordEnabled("_EMISSION")) { if (uMaterial.HasProperty(k_EmissionColor)) { material.emissive = uMaterial.GetColor(k_EmissionColor); } if (uMaterial.HasProperty(k_EmissionMap)) { // var emissionTex = uMaterial.GetTexture(k_EmissionMap); // // if (emissionTex != null) { // if(emissionTex is Texture2D) { // material.emissiveTexture = ExportTextureInfo(emissionTex, TextureMapType.Emission); // ExportTextureTransform(material.EmissiveTexture, uMaterial, "_EmissionMap"); // } else { // logger?.Error(LogCode.TextureInvalidType, "emission", material.name ); // success = false; // } // } } } if ( uMaterial.HasProperty(k_BumpMap) && (uMaterial.IsKeywordEnabled(Materials.Constants.kwNormalMap) || uMaterial.IsKeywordEnabled(k_KeywordBumpMap)) ) { var normalTex = uMaterial.GetTexture(k_BumpMap); if (normalTex != null) { if (normalTex is Texture2D) { material.normalTexture = ExportNormalTextureInfo(normalTex, TextureMapType.Bump, uMaterial, gltf); ExportTextureTransform(material.normalTexture, uMaterial, k_BumpMap, gltf); } else { logger?.Error(LogCode.TextureInvalidType, "normal", uMaterial.name); success = false; } } } if (uMaterial.HasProperty(k_OcclusionMap)) { var occTex = uMaterial.GetTexture(k_OcclusionMap); if (occTex != null) { // if(occTex is Texture2D) { // material.occlusionTexture = ExportOcclusionTextureInfo(occTex, TextureMapType.Occlusion, uMaterial); // ExportTextureTransform(material.OcclusionTexture, uMaterial, "_OcclusionMap"); // } else { // logger?.Error(LogCode.TextureInvalidType, "occlusion", material.name ); // success = false; // } } } if (IsUnlit(uMaterial)) { ExportUnlit(material, uMaterial, gltf, logger); } else if (IsPbrMetallicRoughness(uMaterial)) { success &= ExportPbrMetallicRoughness(uMaterial, out material.pbrMetallicRoughness, gltf, logger); } else if (IsPbrSpecularGlossiness(uMaterial)) { // ExportPBRSpecularGlossiness(material, uMaterial); } else if (uMaterial.HasProperty(k_BaseMap)) { var mainTex = uMaterial.GetTexture(k_BaseMap); material.pbrMetallicRoughness = new PbrMetallicRoughness { baseColor = uMaterial.HasProperty(k_BaseColor) ? uMaterial.GetColor(k_BaseColor) : Color.white, baseColorTexture = mainTex == null ? null : ExportTextureInfo(mainTex, TextureMapType.Main, gltf) }; } else if (uMaterial.HasProperty(k_ColorTexture)) { var mainTex = uMaterial.GetTexture(k_ColorTexture); material.pbrMetallicRoughness = new PbrMetallicRoughness { baseColor = uMaterial.HasProperty(k_BaseColor) ? uMaterial.GetColor(k_BaseColor) : Color.white, baseColorTexture = mainTex == null ? null : ExportTextureInfo(mainTex, TextureMapType.Main, gltf) }; } else if (uMaterial.HasProperty(k_MainTex)) //else export main texture { var mainTex = uMaterial.GetTexture(k_MainTex); if (mainTex != null) { material.pbrMetallicRoughness = new PbrMetallicRoughness { metallicFactor = 0, roughnessFactor = 1.0f, baseColorTexture = ExportTextureInfo(mainTex, TextureMapType.Main, gltf) }; // ExportTextureTransform(material.pbrMetallicRoughness.baseColorTexture, uMaterial, "_MainTex"); } if (uMaterial.HasProperty(k_TintColor)) { //particles use _TintColor instead of _Color material.pbrMetallicRoughness = material.pbrMetallicRoughness ?? new PbrMetallicRoughness { metallicFactor = 0, roughnessFactor = 1.0f }; material.pbrMetallicRoughness.baseColor = uMaterial.GetColor(k_TintColor); } material.doubleSided = true; } return(success); }
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); }
private static List<Texture> GetTextures(Material mat) { List<Texture> textures = new List<Texture>(); for(int i = 0; i < ShaderUtil.GetPropertyCount(mat.shader); i++) { if( ShaderUtil.GetPropertyType(mat.shader, i) == ShaderUtil.ShaderPropertyType.TexEnv ) { Texture t = mat.GetTexture( ShaderUtil.GetPropertyName(mat.shader, i)); if(t != null) textures.Add(t); } } return textures; }
public static ByteBuffer Save(UnityEngine.Material material) { FlatBufferBuilder builder = new FlatBufferBuilder(InitBufferSize); int count = ShaderUtil.GetPropertyCount(material.shader); List <Offset <ShaderProperty> > listOffShaderProperties = new List <Offset <ShaderProperty> >(); for (int i = 0; i < count; i++) { string name = ShaderUtil.GetPropertyName(material.shader, i); ShaderUtil.ShaderPropertyType type = ShaderUtil.GetPropertyType(material.shader, i); Schema.ShaderPropertyValue valueType = ShaderPropertyValue.NONE; int valueOffset = -1; switch (type) { case ShaderUtil.ShaderPropertyType.Color: { UnityEngine.Color c = material.GetColor(name); ShaderPropertyColor.StartShaderPropertyColor(builder); ShaderPropertyColor.AddColor(builder, Schema.Color.CreateColor(builder, c.a, c.b, c.g, c.r)); Offset <ShaderPropertyColor> offset = ShaderPropertyColor.EndShaderPropertyColor(builder); valueType = ShaderPropertyValue.ShaderPropertyColor; valueOffset = offset.Value; } break; case ShaderUtil.ShaderPropertyType.Vector: { Vector4 v = material.GetVector(name); ShaderPropertyVector.StartShaderPropertyVector(builder); ShaderPropertyVector.AddVector(builder, Schema.Vec4.CreateVec4(builder, v.x, v.y, v.z, v.w)); Offset <ShaderPropertyVector> offset = ShaderPropertyVector.EndShaderPropertyVector(builder); valueType = ShaderPropertyValue.ShaderPropertyVector; valueOffset = offset.Value; } break; case ShaderUtil.ShaderPropertyType.Range: case ShaderUtil.ShaderPropertyType.Float: { float f = material.GetFloat(name); ShaderPropertyFloat.StartShaderPropertyFloat(builder); ShaderPropertyFloat.AddValue(builder, f); Offset <ShaderPropertyFloat> offset = ShaderPropertyFloat.EndShaderPropertyFloat(builder); valueType = ShaderPropertyValue.ShaderPropertyFloat; valueOffset = offset.Value; } break; case ShaderUtil.ShaderPropertyType.TexEnv: { UnityEngine.Texture t = material.GetTexture(name); string textureName = "$NULL_TEXTURE"; if (t != null) { textureName = AssetDatabase.GetAssetPath(t.GetInstanceID()); if (string.IsNullOrEmpty(textureName)) { textureName = t.name; } else { textureName = textureName.Substring(ArtWork.path.Length); textureName = System.IO.Path.GetDirectoryName(textureName) + "/" + System.IO.Path.GetFileNameWithoutExtension(textureName); } } Vector2 toffset = material.GetTextureOffset(name); Vector2 tscale = material.GetTextureScale(name); StringOffset pathOffset = builder.CreateString(textureName); ShaderPropertyTexture.StartShaderPropertyTexture(builder); ShaderPropertyTexture.AddName(builder, pathOffset); ShaderPropertyTexture.AddOffset(builder, Vec2.CreateVec2(builder, toffset.x, toffset.y)); ShaderPropertyTexture.AddScale(builder, Vec2.CreateVec2(builder, tscale.x, tscale.y)); Offset <ShaderPropertyTexture> offset = ShaderPropertyTexture.EndShaderPropertyTexture(builder); valueType = ShaderPropertyValue.ShaderPropertyTexture; valueOffset = offset.Value; } break; } if (valueOffset >= 0) { listOffShaderProperties.Add( ShaderProperty.CreateShaderProperty( builder, builder.CreateString(name), (Schema.ShaderPropertyType)type, valueType, valueOffset )); } } StringOffset offMaterialName = builder.CreateString(material.name); StringOffset offShader = builder.CreateString(material.shader.name); Offset <Schema.Material> offMaterial = Schema.Material.CreateMaterial( builder, offMaterialName, offShader, Schema.Material.CreatePropertiesVector(builder, listOffShaderProperties.ToArray())); builder.Finish(offMaterial.Value); return(builder.DataBuffer); }
private BabylonTexture DumpTextureFromMaterial(Material material, string name) { if (!material.HasProperty(name)) { return null; } var texture = material.GetTexture(name); return DumpTexture(texture, material, name); }
private void SetEdgesKeywords(UnityEngine.Material material, string firstEdgeName, string secondEdgeName) { bool isSettingTopBottomEdgesKeywords = firstEdgeName == "Top"; bool areFirstSecondEdgesEnabled = material.GetInt("_Waterfall2D_Is" + firstEdgeName + secondEdgeName + "EdgesEnabled") == 1; bool isFirstEdgeEnabled = material.GetInt("_Waterfall2D_Is" + firstEdgeName + "EdgeEnabled") == 1; bool isSecondEdgeEnabled = material.GetInt("_Waterfall2D_Is" + secondEdgeName + "EdgeEnabled") == 1; bool areFirstSecondEdgesUsingSameTexture = material.GetInt("_Waterfall2D_Is" + firstEdgeName + secondEdgeName + "EdgesUseSameTextureEnabled") == 1; if (!areFirstSecondEdgesUsingSameTexture) { isFirstEdgeEnabled &= material.GetTexture("_" + firstEdgeName + "EdgeTexture") != null; isSecondEdgeEnabled &= material.GetTexture("_" + secondEdgeName + "EdgeTexture") != null; } else { areFirstSecondEdgesEnabled &= material.GetTexture("_" + firstEdgeName + secondEdgeName + "EdgesTexture") != null; } bool isFirstSecondEdgesDistortionEffectEnabled = material.GetInt("_Waterfall2D_Is" + firstEdgeName + secondEdgeName + "EdgesNoiseEnabled") == 1; bool isFirstEdgeTextureSheetEnabled = material.GetInt("_Waterfall2D_Is" + firstEdgeName + "EdgeTextureSheetEnabled") == 1; bool isSecondEdgeTextureSheetEnabled = material.GetInt("_Waterfall2D_Is" + secondEdgeName + "EdgeTextureSheetEnabled") == 1; bool isFirstSecondEdgesTextureSheetEnabled = material.GetInt("_Waterfall2D_Is" + firstEdgeName + secondEdgeName + "EdgesTextureSheetEnabled") == 1; bool isFirstEdgeTextureSheetLerpEnabled = material.GetInt("_Waterfall2D_Is" + firstEdgeName + "EdgeTextureSheetWithLerpEnabled") == 1; bool isSecondEdgeTextureSheetLerpEnabled = material.GetInt("_Waterfall2D_Is" + secondEdgeName + "EdgeTextureSheetWithLerpEnabled") == 1; bool isFirstSecondEdgesTextureSheetLerpEnabled = material.GetInt("_Waterfall2D_Is" + firstEdgeName + secondEdgeName + "EdgesTextureSheetWithLerpEnabled") == 1; Vector4 firstEdgeTextureTilingModeParameters = material.GetVector("_" + firstEdgeName + "EdgeTextureTilingParameters"); Vector4 secondEdgeTextureTilingModeParameters = material.GetVector("_" + secondEdgeName + "EdgeTextureTilingParameters"); Vector4 firstSecondEdgesTextureTilingModeParameters = material.GetVector("_" + firstEdgeName + secondEdgeName + "EdgesTextureTilingParameters"); bool isFirstEdgeTextureTilingModeSetToStretch = firstEdgeTextureTilingModeParameters.x == 1f; bool isFirstEdgeTextureStretchTilingModeKeepAspect = firstEdgeTextureTilingModeParameters.y == 1f; bool isFirstEdgeTextureStretchTilingModeAutoX = firstEdgeTextureTilingModeParameters.z == 1f; bool isSecondEdgeTextureTilingModeSetToStretch = secondEdgeTextureTilingModeParameters.x == 1f; bool isSecondEdgeTextureStretchTilingModeKeepAspect = secondEdgeTextureTilingModeParameters.y == 1f; bool isSecondEdgeTextureStretchTilingModeAutoX = secondEdgeTextureTilingModeParameters.z == 1f; bool isFirstSecondEdgesTextureTilingModeSetToStretch = firstSecondEdgesTextureTilingModeParameters.x == 1f; bool isFirstSecondEdgesTextureStretchTilingModeKeepAspect = firstSecondEdgesTextureTilingModeParameters.y == 1f; bool isFirstSecondEdgesTextureStretchTilingModeAutoX = firstSecondEdgesTextureTilingModeParameters.z == 1f; Vector4 textureFlippingParametes = material.GetVector("_" + firstEdgeName + secondEdgeName + "EdgesTextureFlipParameters"); bool isTextureFlippingEnabled = textureFlippingParametes.x == 1f; bool isTextureFlippingFirstEdge = textureFlippingParametes.y == 1f; bool isFirstSecondEdgesAbsoluteThicknessAndOffsetAbsolute = material.GetInt("_Waterfall2D_Is" + firstEdgeName + secondEdgeName + "EdgesAbsoluteThicknessAndOffsetEnabled") == 1; SetKeywordState(material, "Waterfall2D_" + firstEdgeName + secondEdgeName + "EdgesSameTexture", areFirstSecondEdgesEnabled && isFirstEdgeEnabled && isSecondEdgeEnabled && areFirstSecondEdgesUsingSameTexture && !isFirstSecondEdgesTextureSheetEnabled && !(isFirstSecondEdgesTextureSheetEnabled && isFirstSecondEdgesTextureSheetLerpEnabled)); SetKeywordState(material, "Waterfall2D_" + firstEdgeName + secondEdgeName + "EdgesSameTextureSheet", areFirstSecondEdgesEnabled && isFirstEdgeEnabled && isSecondEdgeEnabled && areFirstSecondEdgesUsingSameTexture && isFirstSecondEdgesTextureSheetEnabled && !isFirstSecondEdgesTextureSheetLerpEnabled); SetKeywordState(material, "Waterfall2D_" + firstEdgeName + secondEdgeName + "EdgesSameTextureSheetWithLerp", areFirstSecondEdgesEnabled && isFirstEdgeEnabled && isSecondEdgeEnabled && areFirstSecondEdgesUsingSameTexture && isFirstSecondEdgesTextureSheetEnabled && isFirstSecondEdgesTextureSheetLerpEnabled); SetKeywordState(material, "Waterfall2D_" + firstEdgeName + "Edge", areFirstSecondEdgesEnabled && isFirstEdgeEnabled && !(isSecondEdgeEnabled && areFirstSecondEdgesUsingSameTexture) && !isFirstEdgeTextureSheetEnabled && !(isFirstEdgeTextureSheetEnabled && isFirstEdgeTextureSheetLerpEnabled)); SetKeywordState(material, "Waterfall2D_" + firstEdgeName + "EdgeTextureSheet", areFirstSecondEdgesEnabled && isFirstEdgeEnabled && !(isSecondEdgeEnabled && areFirstSecondEdgesUsingSameTexture) && isFirstEdgeTextureSheetEnabled && !isFirstEdgeTextureSheetLerpEnabled); SetKeywordState(material, "Waterfall2D_" + firstEdgeName + "EdgeTextureSheetWithLerp", areFirstSecondEdgesEnabled && isFirstEdgeEnabled && !(isSecondEdgeEnabled && areFirstSecondEdgesUsingSameTexture) && isFirstEdgeTextureSheetEnabled && isFirstEdgeTextureSheetLerpEnabled); SetKeywordState(material, "Waterfall2D_" + secondEdgeName + "Edge", areFirstSecondEdgesEnabled && isSecondEdgeEnabled && !(isFirstEdgeEnabled && areFirstSecondEdgesUsingSameTexture) && !isSecondEdgeTextureSheetEnabled && !(isSecondEdgeTextureSheetEnabled && isSecondEdgeTextureSheetLerpEnabled)); SetKeywordState(material, "Waterfall2D_" + secondEdgeName + "EdgeTextureSheet", areFirstSecondEdgesEnabled && isSecondEdgeEnabled && !(isFirstEdgeEnabled && areFirstSecondEdgesUsingSameTexture) && isSecondEdgeTextureSheetEnabled && !isSecondEdgeTextureSheetLerpEnabled); SetKeywordState(material, "Waterfall2D_" + secondEdgeName + "EdgeTextureSheetWithLerp", areFirstSecondEdgesEnabled && isSecondEdgeEnabled && !(isFirstEdgeEnabled && areFirstSecondEdgesUsingSameTexture) && isSecondEdgeTextureSheetEnabled && isSecondEdgeTextureSheetLerpEnabled); SetKeywordState(material, "Waterfall2D_" + firstEdgeName + secondEdgeName + "EdgesNoise", areFirstSecondEdgesEnabled && (isFirstEdgeEnabled || isSecondEdgeEnabled) && isFirstSecondEdgesDistortionEffectEnabled); SetKeywordState(material, "Waterfall2D_" + firstEdgeName + "EdgeTextureStretch", areFirstSecondEdgesEnabled && isFirstEdgeEnabled && !(isSecondEdgeEnabled && areFirstSecondEdgesUsingSameTexture) && isFirstEdgeTextureTilingModeSetToStretch && !isFirstEdgeTextureStretchTilingModeKeepAspect); SetKeywordState(material, "Waterfall2D_" + firstEdgeName + "EdgeTextureStretchAutoX", areFirstSecondEdgesEnabled && isFirstEdgeEnabled && !(isSecondEdgeEnabled && areFirstSecondEdgesUsingSameTexture) && isFirstEdgeTextureTilingModeSetToStretch && isFirstEdgeTextureStretchTilingModeKeepAspect && isFirstEdgeTextureStretchTilingModeAutoX); SetKeywordState(material, "Waterfall2D_" + firstEdgeName + "EdgeTextureStretchAutoY", areFirstSecondEdgesEnabled && isFirstEdgeEnabled && !(isSecondEdgeEnabled && areFirstSecondEdgesUsingSameTexture) && isFirstEdgeTextureTilingModeSetToStretch && isFirstEdgeTextureStretchTilingModeKeepAspect && !isFirstEdgeTextureStretchTilingModeAutoX); SetKeywordState(material, "Waterfall2D_" + secondEdgeName + "EdgeTextureStretch", areFirstSecondEdgesEnabled && isSecondEdgeEnabled && !(isFirstEdgeEnabled && areFirstSecondEdgesUsingSameTexture) && isSecondEdgeTextureTilingModeSetToStretch && !isSecondEdgeTextureStretchTilingModeKeepAspect); SetKeywordState(material, "Waterfall2D_" + secondEdgeName + "EdgeTextureStretchAutoX", areFirstSecondEdgesEnabled && isSecondEdgeEnabled && !(isFirstEdgeEnabled && areFirstSecondEdgesUsingSameTexture) && isSecondEdgeTextureTilingModeSetToStretch && isSecondEdgeTextureStretchTilingModeKeepAspect && isSecondEdgeTextureStretchTilingModeAutoX); SetKeywordState(material, "Waterfall2D_" + secondEdgeName + "EdgeTextureStretchAutoY", areFirstSecondEdgesEnabled && isSecondEdgeEnabled && !(isFirstEdgeEnabled && areFirstSecondEdgesUsingSameTexture) && isSecondEdgeTextureTilingModeSetToStretch && isSecondEdgeTextureStretchTilingModeKeepAspect && !isSecondEdgeTextureStretchTilingModeAutoX); SetKeywordState(material, "Waterfall2D_" + firstEdgeName + secondEdgeName + "EdgesTextureStretch", areFirstSecondEdgesEnabled && isFirstEdgeEnabled && isSecondEdgeEnabled && areFirstSecondEdgesUsingSameTexture && isFirstSecondEdgesTextureTilingModeSetToStretch && !isFirstSecondEdgesTextureStretchTilingModeKeepAspect); SetKeywordState(material, "Waterfall2D_" + firstEdgeName + secondEdgeName + "EdgesTextureStretchAutoX", areFirstSecondEdgesEnabled && isFirstEdgeEnabled && isSecondEdgeEnabled && areFirstSecondEdgesUsingSameTexture && isFirstSecondEdgesTextureTilingModeSetToStretch && isFirstSecondEdgesTextureStretchTilingModeKeepAspect && isFirstSecondEdgesTextureStretchTilingModeAutoX); SetKeywordState(material, "Waterfall2D_" + firstEdgeName + secondEdgeName + "EdgesTextureStretchAutoY", areFirstSecondEdgesEnabled && isFirstEdgeEnabled && isSecondEdgeEnabled && areFirstSecondEdgesUsingSameTexture && isFirstSecondEdgesTextureTilingModeSetToStretch && isFirstSecondEdgesTextureStretchTilingModeKeepAspect && !isFirstSecondEdgesTextureStretchTilingModeAutoX); SetKeywordState(material, "Waterfall2D_" + firstEdgeName + secondEdgeName + "EdgesFlip" + firstEdgeName + "Edge" + (isSettingTopBottomEdgesKeywords ? "Y" : "X"), areFirstSecondEdgesEnabled && isFirstEdgeEnabled && isSecondEdgeEnabled && areFirstSecondEdgesUsingSameTexture && isTextureFlippingEnabled && isTextureFlippingFirstEdge); SetKeywordState(material, "Waterfall2D_" + firstEdgeName + secondEdgeName + "EdgesFlip" + secondEdgeName + "Edge" + (isSettingTopBottomEdgesKeywords ? "Y" : "X"), areFirstSecondEdgesEnabled && isFirstEdgeEnabled && isSecondEdgeEnabled && areFirstSecondEdgesUsingSameTexture && isTextureFlippingEnabled && !isTextureFlippingFirstEdge); SetKeywordState(material, "Waterfall2D_" + firstEdgeName + secondEdgeName + "EdgesAbsoluteThicknessAndOffset", areFirstSecondEdgesEnabled && (isFirstEdgeEnabled || isSecondEdgeEnabled) && isFirstSecondEdgesAbsoluteThicknessAndOffsetAbsolute); if (!isSettingTopBottomEdgesKeywords) { bool isTextureAlphaCutoffEnabled = FindProperty("_Waterfall2D_Is" + firstEdgeName + secondEdgeName + "EdgesTextureAlphaCutoffEnabled", _materialProperties).floatValue == 1f; SetKeywordState(material, "Waterfall2D_" + firstEdgeName + secondEdgeName + "EdgesTextureAlphaCutoff", (areFirstSecondEdgesEnabled || isFirstEdgeEnabled || isSecondEdgeEnabled) && isTextureAlphaCutoffEnabled); } }
/// <summary> /// Converts a Unity material to a glTF material. /// </summary> /// <param name="uMaterial">Source material</param> /// <param name="material">Resulting material</param> /// <param name="gltf">Associated IGltfWriter. Is used for adding images and textures.</param> /// <param name="logger">Logger used for reporting</param> /// <returns>True if no errors occured, false otherwise</returns> public override bool ConvertMaterial(UnityEngine.Material uMaterial, out Material material, IGltfWritable gltf, ICodeLogger logger) { var success = true; material = new Material { name = uMaterial.name, pbrMetallicRoughness = new PbrMetallicRoughness { metallicFactor = 0, roughnessFactor = 1.0f } }; SetAlphaModeAndCutoff(uMaterial, material); material.doubleSided = IsDoubleSided(uMaterial); if (uMaterial.IsKeywordEnabled(k_KeywordEmission)) { if (uMaterial.HasProperty(k_EmissionColor)) { var emissionColor = uMaterial.GetColor(k_EmissionColor); // Clamp emissionColor to 0..1 var maxFactor = math.max(emissionColor.r, math.max(emissionColor.g, emissionColor.b)); if (maxFactor > 1f) { emissionColor.r /= maxFactor; emissionColor.g /= maxFactor; emissionColor.b /= maxFactor; // TODO: use maxFactor as emissiveStrength (KHR_materials_emissive_strength) } material.emissive = emissionColor; } if (uMaterial.HasProperty(k_EmissionMap)) { var emissionTex = uMaterial.GetTexture(k_EmissionMap); if (emissionTex != null) { if (emissionTex is Texture2D) { material.emissiveTexture = ExportTextureInfo(emissionTex, gltf); if (material.emissiveTexture != null) { ExportTextureTransform(material.emissiveTexture, uMaterial, k_EmissionMap, gltf); } } else { logger?.Error(LogCode.TextureInvalidType, "emission", material.name); success = false; } } } } if ( uMaterial.HasProperty(k_BumpMap) && (uMaterial.IsKeywordEnabled(Materials.Constants.kwNormalMap) || uMaterial.IsKeywordEnabled(k_KeywordBumpMap)) ) { var normalTex = uMaterial.GetTexture(k_BumpMap); if (normalTex != null) { if (normalTex is Texture2D) { material.normalTexture = ExportNormalTextureInfo(normalTex, uMaterial, gltf); if (material.normalTexture != null) { ExportTextureTransform(material.normalTexture, uMaterial, k_BumpMap, gltf); } } else { logger?.Error(LogCode.TextureInvalidType, "normal", uMaterial.name); success = false; } } } var isPbrMetallicRoughness = IsPbrMetallicRoughness(uMaterial); var needsMetalRoughTexture = isPbrMetallicRoughness && ( HasMetallicGlossMap(uMaterial) || uMaterial.IsKeywordEnabled(k_KeywordSmoothnessTextureAlbedoChannelA) ); OrmImageExport ormImageExport = null; var mainTexProperty = k_MainTex; if (uMaterial.HasProperty(k_BaseMap)) { mainTexProperty = k_BaseMap; } else if (uMaterial.HasProperty(k_ColorTexture)) { mainTexProperty = k_ColorTexture; } if (needsMetalRoughTexture) { ormImageExport = new OrmImageExport(); } if (IsUnlit(uMaterial)) { ExportUnlit(material, uMaterial, mainTexProperty, gltf, logger); } else if (isPbrMetallicRoughness) { success &= ExportPbrMetallicRoughness( uMaterial, material, mainTexProperty, ormImageExport, gltf, logger ); } else if (uMaterial.HasProperty(mainTexProperty)) { var mainTex = uMaterial.GetTexture(mainTexProperty); material.pbrMetallicRoughness = new PbrMetallicRoughness { metallicFactor = 0, roughnessFactor = 1.0f, baseColor = uMaterial.HasProperty(k_BaseColor) ? uMaterial.GetColor(k_BaseColor) : Color.white }; if (mainTex != null) { material.pbrMetallicRoughness.baseColorTexture = ExportTextureInfo(mainTex, gltf); if (material.pbrMetallicRoughness.baseColorTexture != null) { ExportTextureTransform(material.pbrMetallicRoughness.baseColorTexture, uMaterial, mainTexProperty, gltf); } } if (uMaterial.HasProperty(k_TintColor)) { //particles use _TintColor instead of _Color material.pbrMetallicRoughness.baseColor = uMaterial.GetColor(k_TintColor); } } if (uMaterial.HasProperty(k_OcclusionMap)) { var occTex = uMaterial.GetTexture(k_OcclusionMap); if (occTex != null) { if (occTex is Texture2D occTex2d) { if (ormImageExport == null) { material.occlusionTexture = ExportOcclusionTextureInfo(occTex2d, uMaterial, gltf); } else { material.occlusionTexture = new OcclusionTextureInfo(); ormImageExport.SetOcclusionTexture(occTex2d); } if (material.occlusionTexture != null) { ExportTextureTransform( material.occlusionTexture, uMaterial, mainTexProperty, // Standard and Lit re-use main texture transform gltf ); } } else { logger?.Error(LogCode.TextureInvalidType, "occlusion", material.name); success = false; } } } if (ormImageExport != null && material.pbrMetallicRoughness != null) { if (AddImageExport(gltf, ormImageExport, out var ormTextureId)) { if (material.pbrMetallicRoughness.metallicRoughnessTexture != null) { material.pbrMetallicRoughness.metallicRoughnessTexture.index = ormTextureId; ExportTextureTransform(material.pbrMetallicRoughness.metallicRoughnessTexture, uMaterial, k_MetallicGlossMap, gltf); } if (ormImageExport.hasOcclusion) { material.occlusionTexture.index = ormTextureId; } } #if UNITY_IMAGECONVERSION else { logger?.Error(LogCode.ExportImageFailed); } #endif } if (material.occlusionTexture != null) { if (uMaterial.HasProperty(MaterialGenerator.occlusionStrengthPropId)) { material.occlusionTexture.strength = uMaterial.GetFloat(MaterialGenerator.occlusionStrengthPropId); } } return(success); }
public void EqualSource() { Assert.AreEqual(material.Name, originMaterial.name); Assert.AreEqual(material.Shader, originMaterial.shader.name); for (int i = 0; i < material.PropertiesLength; i++) { Schema.ShaderProperty p = material.GetProperties(i); Assert.IsTrue(originMaterial.HasProperty(p.Names)); switch (p.Type) { case ShaderPropertyType.Float: case ShaderPropertyType.Range: { Assert.AreEqual(p.ValueType, ShaderPropertyValue.ShaderPropertyFloat); float originValue = originMaterial.GetFloat(p.Names); ShaderPropertyFloat f = p.GetValue <ShaderPropertyFloat>(new ShaderPropertyFloat()); Assert.AreEqual(f.Value, originValue); } break; case ShaderPropertyType.Color: { Assert.AreEqual(p.ValueType, ShaderPropertyValue.ShaderPropertyColor); UnityEngine.Color originValue = originMaterial.GetColor(p.Names); ShaderPropertyColor c = p.GetValue <ShaderPropertyColor>(new ShaderPropertyColor()); Assert.AreEqual(originValue.a, c.Color.A); Assert.AreEqual(originValue.g, c.Color.G); Assert.AreEqual(originValue.b, c.Color.B); Assert.AreEqual(originValue.r, c.Color.R); } break; case ShaderPropertyType.Vector: { Assert.AreEqual(p.ValueType, ShaderPropertyValue.ShaderPropertyVector); UnityEngine.Vector4 originValue = originMaterial.GetVector(p.Names); ShaderPropertyVector v = p.GetValue <ShaderPropertyVector>(new ShaderPropertyVector()); Assert.AreEqual(originValue.x, v.Vector.X); Assert.AreEqual(originValue.y, v.Vector.Y); Assert.AreEqual(originValue.z, v.Vector.Z); Assert.AreEqual(originValue.w, v.Vector.W); } break; case ShaderPropertyType.TexEnv: { Assert.AreEqual(p.ValueType, ShaderPropertyValue.ShaderPropertyTexture); UnityEngine.Texture texture = originMaterial.GetTexture(p.Names); Vector2 offset = originMaterial.GetTextureOffset(p.Names); Vector2 scale = originMaterial.GetTextureScale(p.Names); Assert.IsFalse(texture == null); ShaderPropertyTexture t = p.GetValue <ShaderPropertyTexture>(new ShaderPropertyTexture()); Assert.AreEqual(texture.name, t.Name); Assert.AreEqual(offset.x, t.Offset.X); Assert.AreEqual(offset.y, t.Offset.Y); Assert.AreEqual(scale.x, t.Scale.X); Assert.AreEqual(scale.y, t.Scale.Y); } break; } } }