public GetColor ( int nameID ) : Color | ||
nameID | int | The name ID of the property retrieved by Shader.PropertyToID. |
return | Color |
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; }
private static float _GetColor(Material obj, MaterialPropertyType pType, string paramName) { Color c; if(paramName == null || paramName.Length == 0) { c = obj.color; } else { c = obj.GetColor(paramName); } switch(pType) { case MaterialPropertyType.Color_R: return c.r; case MaterialPropertyType.Color_G: return c.g; case MaterialPropertyType.Color_B: return c.b; case MaterialPropertyType.Color_RGB: return c.r; case MaterialPropertyType.Color_A: return c.a; case MaterialPropertyType.Color_R_Relative: return c.r; case MaterialPropertyType.Color_G_Relative: return c.g; case MaterialPropertyType.Color_B_Relative: return c.b; case MaterialPropertyType.Color_RGB_Relative: return c.r; case MaterialPropertyType.Color_A_Relative: return c.a; } return 0.0f; }
IEnumerator Grow() { float f = 0; float t = 0; Vector3 originalScale = transform.localScale; Vector3 targetScale = originalScale * EndScale; Material originalMaterial = new Material(renderer.material); Color originalColor = originalMaterial.GetColor("_TintColor"); Color targetColor = new Color(originalColor.r, originalColor.g, originalColor.b, 0F); renderer.material = originalMaterial; while (f <= duration) { t = f / duration; transform.localScale = Vector3.Lerp(originalScale, targetScale, t); originalMaterial.SetColor("_TintColor", Color.Lerp(originalColor, targetColor, t)); f += Time.deltaTime; yield return new WaitForEndOfFrame(); } if (mode == FXmode.DestroyAtEnd) Destroy(gameObject); else if (mode == FXmode.Loop) Play(); }
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 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 GetColor(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.Color o = obj.GetColor(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.Color o = obj.GetColor(arg0); ToLua.Push(L, o); return(1); } else { return(LuaDLL.luaL_throw(L, "invalid arguments to method: UnityEngine.Material.GetColor")); } } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
/// <summary> /// /// </summary> void Awake() { m_Transform = transform; m_ForceShow = false; // if a light is present in the prefab we will cache and use it m_Light = GetComponent <Light>(); if (m_Light != null) { m_LightIntensity = m_Light.intensity; m_Light.intensity = 0.0f; } m_Renderer = GetComponent <Renderer>(); if (m_Renderer != null) { m_Material = GetComponent <Renderer>().material; if (m_Material != null) { // the muzzleflash is meant to use the 'Particles/Additive' // (unity default) shader which has the 'TintColor' property m_Color = m_Material.GetColor("_TintColor"); m_Color.a = 0.0f; } } }
void Start() { colorSmooth = Random.Range(smooth.min, smooth.max); _colorSmooth = colorSmooth; mat = GetComponent<Renderer>().materials[materialIndex]; toColor = mat.GetColor("_EmissionColor"); }
public void SetFromToCurrent() { if (_material = material) { from = _material.GetColor(propertyID); } }
static public int GetColor(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.GetColor(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.GetColor(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)); } }
// Use this for initialization void Awake() { colorRenderer = GetComponent<Renderer>(); mat = colorRenderer.material; originalColor = mat.GetColor("_EmissionColor"); baseColor = originalColor; }
public override void OnRecord() { if (_material = material) { _original = _material.GetColor(propertyID); } }
static public int GetColor(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.Color ret = self.GetColor(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.Color ret = self.GetColor(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); } }
IEnumerator Test( Material mat, Color newColor ) { Color orgColor = mat.GetColor("_EmissionColor"); mat.SetColor("_EmissionColor", newColor); yield return new WaitForSeconds(0.5f); mat.SetColor("_EmissionColor", orgColor); }
/// <summary> /// /// </summary> void Awake() { m_Transform = transform; m_ForceShow = false; // if a light is present in the prefab we will cache and use it m_Light = GetComponent<Light>(); if (m_Light != null) { m_LightIntensity = m_Light.intensity; m_Light.intensity = 0.0f; } m_Renderer = GetComponent<Renderer>(); if (m_Renderer != null) { m_Material = GetComponent<Renderer>().material; if (m_Material != null) { // the muzzleflash is meant to use the 'Particles/Additive' // (unity default) shader which has the 'TintColor' property m_Color = m_Material.GetColor("_TintColor"); m_Color.a = 0.0f; } } }
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; }
// Use this for initialization void Start() { flashMat = redFlash.renderer.material; Color color = flashMat.GetColor("_Color"); color.a = 0; redFlash.renderer.material.SetColor("_Color", color); }
public void Init(TurnBasedUnit parentShip) { trans = transform; shieldMat = renderer.material; originalColour = shieldMat.GetColor("_Color"); ParentShip = parentShip; }
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); }
/// <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; } } } }
void Start() { material = GetComponent<ParticleSystem> ().renderer.material; tintColor = material.GetColor("_TintColor"); step = (targetAlpha / 255 - tintColor.a) / time; }
public override void AssignNewShaderToMaterial(Material material, Shader oldShader, Shader newShader) { if (material.HasProperty("_Emission")) { material.SetColor("_EmissionColor", material.GetColor("_Emission")); } base.AssignNewShaderToMaterial(material, oldShader, newShader); if ((oldShader == null) || !oldShader.name.Contains("Legacy Shaders/")) { SetupMaterialWithBlendMode(material, (BlendMode) ((int) material.GetFloat("_Mode"))); } else { BlendMode opaque = BlendMode.Opaque; if (oldShader.name.Contains("/Transparent/Cutout/")) { opaque = BlendMode.Cutout; } else if (oldShader.name.Contains("/Transparent/")) { opaque = BlendMode.Fade; } material.SetFloat("_Mode", (float) opaque); Material[] mats = new Material[] { material }; this.DetermineWorkflow(MaterialEditor.GetMaterialProperties(mats)); MaterialChanged(material, this.m_WorkflowMode); } }
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; }
// Use this for initialization void Start() { myLight = GetComponentInChildren<Light>(); myMat = GetComponent<Renderer>().material; LightColor = myMat.GetColor("_EmissionColor"); myMat.SetColor("_EmissionColor",DarkColor); MidColor = new Color(LightColor.r/2,LightColor.g/2,LightColor.b/2); }
void Start() { reaktor.Initialize(this); material = GetComponent<Kvant.Wall>().material; originalColor = material.GetColor("_Emission"); UpdateEmission(0); }
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); }
void Awake() { leftP.emissionRate = baseEmission; rightP.emissionRate = baseEmission; _material = GetComponent<SpriteRenderer>().material; _defaultAlpha = _material.GetColor("_Color").a; _collider = GetComponent<PolygonCollider2D>(); }
/// <summary> /// Changes the color of the given material /// </summary> /// <param name="material"></param> /// <param name="color"></param> public IEnumerator ChangeColor(Material material, Color color, float seconds) { Color currentColor = material.GetColor("_EmissionColor"); material.SetColor("_EmissionColor", color); yield return new WaitForSeconds(seconds); // Reset color to initial one if (seconds > 0) { material.SetColor("_EmissionColor", currentColor); } }
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 Awake() { base.Awake (); mMat = renderer.material; mOriginalColor =(mTargetColor != "")? mMat.GetColor( mTargetColor): Color.white; #if !UNITY_TOUCH GameController.mKeyboardEvent +=OnKeyEvent; #endif }
public static Color GetMaterialColor(Material mat, Color defaultColor) { string[] propertyNames = { "_Color", "_TintColor", "_EmisColor" }; if (mat != null) foreach (string name in propertyNames) if (mat.HasProperty(name)) return mat.GetColor(name); return defaultColor; }
protected static bool TryGetTintColor(Material material, out Color color) { if (material.HasProperty("_TintColor")) { color = material.GetColor("_TintColor"); return true; } color = new Color(); return false; }
void Awake() { Renderer renderer = GetComponent<Renderer> (); mat = Material.Instantiate (renderer.sharedMaterial); mat.hideFlags = HideFlags.DontSave; renderer.sharedMaterial = mat; scales = transform.localScale; color = mat.GetColor ("_Color"); SetAlpha (0f); }
static JsonData getMetalData(UnityEngine.Material mat, Paladin paladin = null) { var ret = new JsonData(); ret["type"] = mat.name; var param = new JsonData(); param["eta"] = Util.fromColor(mat.GetColor("_eta")); param["k"] = Util.fromColor(mat.GetColor("k")); param["uRough"] = mat.GetFloat("_uRoughness"); param["vRough"] = mat.GetFloat("_vRoughness"); param["rough"] = null; bool remap = mat.GetInt("_remapRoughness") != 0; param["remapRough"] = remap; ret["param"] = param; return(ret); }
public override void Start() { ballController.arrow.SetActive (true); // Debug.Log ("Loading State" + " : " + ballController.gameObject.transform); arrowMat = ballController.arrow.transform.GetChild (0).GetComponent<Renderer> ().material; lastColor = arrowMat.GetColor ("_EmissionColor"); arrowMat.SetColor ("_EmissionColor", new Color (0.6f, 0, 0)); //ballController.setBallColor (new Color (1f, 0.6f, 0.2f)); }
public void ApplyOpaque(Color col) { rend = this.gameObject.GetComponent<Renderer>().material; rend.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); rend.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero); rend.SetInt("_ZWrite", 1); rend.DisableKeyword("_ALPHATEST_ON"); rend.DisableKeyword("_ALPHABLEND_ON"); rend.DisableKeyword("_ALPHAPREMULTIPLY_ON"); rend.renderQueue = -1; StartCoroutine(colorLerp1(rend.GetColor("_Color"), col)); }
/// <summary> /// Smoothly changes current color of material to target color /// </summary> /// <param name="material">target material</param> /// <param name="newColor">target color</param> /// <param name="duration">time in seconds</param> /// <returns></returns> public IEnumerator ChangeColor(Material material, Color newColor, float seconds, float duration) { Color startColor = material.GetColor("_EmissionColor"); float progress = 0; float increment = 0.0416f; //The amount of change to apply. while (progress < 1) { material.SetColor("_EmissionColor", Color.Lerp(startColor, newColor, progress)); progress += increment; yield return new WaitForSeconds(seconds); } }
static JsonData getMirrorData(UnityEngine.Material mat, Paladin paladin = null) { var ret = new JsonData(); ret["type"] = mat.name; var param = new JsonData(); param["Kr"] = Util.fromColor(mat.GetColor("_Kr")); ret["param"] = param; return(ret); }
static JsonData getGlassData(UnityEngine.Material mat, Paladin paladin = null) { var ret = new JsonData(); ret["type"] = mat.name; var param = new JsonData(); param["Kr"] = Util.fromColor(mat.GetColor("_Kr")); param["Kt"] = Util.fromColor(mat.GetColor("_Kt")); param["uRough"] = mat.GetFloat("_uRoughness"); param["vRough"] = mat.GetFloat("_vRoughness"); param["eta"] = mat.GetFloat("_eta"); bool remap = mat.GetInt("_remapRoughness") != 0; bool thin = mat.GetInt("_thin") != 0; param["remapRough"] = remap; param["thin"] = thin; ret["param"] = param; return(ret); }
public static Color GetObjectEmissionColor(GameObject obj) { Renderer r = obj.GetComponent <Renderer>(); if (r) { UMaterial material = r.sharedMaterial; if (material.HasProperty("_EmissionColor")) { return(material.GetColor("_EmissionColor")); } } return(Color.white); }
static JsonData getMatteData(UnityEngine.Material mat, Paladin paladin = null) { var ret = new JsonData(); ret["type"] = mat.name; var param = new JsonData(); param["Kd"] = Util.fromColor(mat.GetColor("_Kd")); param["sigma"] = mat.GetFloat("_sigma"); ret["param"] = param; return(ret); }
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); }
// 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); } }
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); }
static bool ExportPbrMetallicRoughness( UnityEngine.Material uMaterial, Material material, int mainTexProperty, OrmImageExport ormImageExport, IGltfWritable gltf, ICodeLogger logger ) { var success = true; var pbr = new PbrMetallicRoughness { metallicFactor = 0, roughnessFactor = 1.0f }; var hasAlphaSmoothness = uMaterial.IsKeywordEnabled(k_KeywordSmoothnessTextureAlbedoChannelA); 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_TintColor)) { //particles use _TintColor instead of _Color float white = 1; if (uMaterial.HasProperty(k_Color)) { var c = uMaterial.GetColor(k_Color); white = (c.r + c.g + c.b) / 3.0f; //multiply alpha by overall whiteness of TintColor } pbr.baseColor = uMaterial.GetColor(k_TintColor) * white; } if (uMaterial.HasProperty(mainTexProperty)) { // TODO if additive particle, render black into alpha // TODO use private Material.GetFirstPropertyNameIdByAttribute here, supported from 2020.1+ var mainTex = uMaterial.GetTexture(mainTexProperty); if (mainTex) { if (mainTex is Texture2D) { pbr.baseColorTexture = ExportTextureInfo( mainTex, gltf, // Force RGB for the baseColor, so that the alpha (which is smoothness) // is not used for alpha-opacity hasAlphaSmoothness ? ImageExportBase.Format.Jpg : ImageExportBase.Format.Unknown ); if (pbr.baseColorTexture != null) { ExportTextureTransform(pbr.baseColorTexture, uMaterial, mainTexProperty, gltf); } } else { logger?.Error(LogCode.TextureInvalidType, "main", uMaterial.name); success = false; } } } if (uMaterial.HasProperty(k_Metallic) && !HasMetallicGlossMap(uMaterial)) { pbr.metallicFactor = uMaterial.GetFloat(k_Metallic); } if (uMaterial.HasProperty(k_Glossiness) || uMaterial.HasProperty(k_Smoothness)) { var smoothnessPropId = uMaterial.HasProperty(k_Smoothness) ? k_Smoothness : k_Glossiness; var metallicGlossMap = uMaterial.HasProperty(k_MetallicGlossMap) ? uMaterial.GetTexture(k_MetallicGlossMap) : null; var smoothness = uMaterial.GetFloat(smoothnessPropId); pbr.roughnessFactor = (metallicGlossMap != null || hasAlphaSmoothness) && uMaterial.HasProperty(k_GlossMapScale) ? uMaterial.GetFloat(k_GlossMapScale) : 1f - smoothness; } if (uMaterial.HasProperty(k_MetallicGlossMap)) { var mrTex = uMaterial.GetTexture(k_MetallicGlossMap); if (mrTex != null) { if (mrTex is Texture2D mrTex2d) { pbr.metallicRoughnessTexture = pbr.metallicRoughnessTexture ?? new TextureInfo(); ormImageExport.SetMetalGlossTexture(mrTex2d); if (HasMetallicGlossMap(uMaterial)) { pbr.metallicFactor = 1.0f; } ExportTextureTransform(pbr.metallicRoughnessTexture, uMaterial, k_MetallicGlossMap, gltf); } else { logger?.Error(LogCode.TextureInvalidType, "metallic/gloss", uMaterial.name); success = false; } } } if (uMaterial.IsKeywordEnabled(k_KeywordSmoothnessTextureAlbedoChannelA)) { var smoothnessTex = uMaterial.GetTexture(mainTexProperty) as Texture2D; if (smoothnessTex != null) { pbr.metallicRoughnessTexture = pbr.metallicRoughnessTexture ?? new TextureInfo(); ormImageExport.SetSmoothnessTexture(smoothnessTex); ExportTextureTransform(pbr.metallicRoughnessTexture, uMaterial, mainTexProperty, gltf); } } material.pbrMetallicRoughness = pbr; return(success); }
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); }
/// <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); }
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); }
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); }
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; } } }
/// <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); }
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); }
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); }
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 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); }
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); }
/// <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 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; } } }