/// <summary> /// Initializes the primary mesh material. /// Note: for good explanation of Renderer.materials see http://answers.unity3d.com/questions/228744/material-versus-shared-material.html /// </summary> /// <param name="material">The material.</param> private void InitializePrimaryMeshMaterial(Material material) { if (!material.IsKeywordEnabled(UnityConstants.StdShader_RenderModeKeyword_FadeTransparency)) { material.EnableKeyword(UnityConstants.StdShader_RenderModeKeyword_FadeTransparency); } if (!material.IsKeywordEnabled(UnityConstants.StdShader_MapKeyword_Metallic)) { material.EnableKeyword(UnityConstants.StdShader_MapKeyword_Metallic); } /******************************************************************************************* * These values were set when I wasn't using the metal material's MetallicMap, opting * instead to set these. UNCLEAR Why I don't know, but not using the MatallicMap kept the * colors from showing up on the element unless the shader tab was clicked in the inspector. * * if (material.GetFloat(UnityConstants.StdShader_Property_MetallicFloat) != 0.25F) { * material.SetFloat(UnityConstants.StdShader_Property_MetallicFloat, 0.25F); * } * if (material.GetFloat(UnityConstants.StdShader_Property_SmoothnessFloat) != 0.4F) { * material.SetFloat(UnityConstants.StdShader_Property_SmoothnessFloat, 0.4F); * } *******************************************************************************************/ if (!material.IsKeywordEnabled(UnityConstants.StdShader_MapKeyword_Normal)) { material.EnableKeyword(UnityConstants.StdShader_MapKeyword_Normal); } if (material.GetFloat(UnityConstants.StdShader_Property_NormalScaleFloat) != 1.25F) { material.SetFloat(UnityConstants.StdShader_Property_NormalScaleFloat, 1.25F); } }
static bool HasMetallicGlossMap(UnityEngine.Material uMaterial) { return(uMaterial.IsKeywordEnabled(k_KeywordMetallicGlossMap) // Built-In Standard #if USING_URP || USING_HDRP || uMaterial.IsKeywordEnabled(k_KeywordMetallicSpecGlossMap) // URP Lit #endif ); }
private void InitializePrimaryMeshMaterial(Material material) { // no need to enable RenderingMode.Opaque as it is the default // for now, color is green if (material.IsKeywordEnabled(UnityConstants.StdShader_MapKeyword_Metallic)) { material.EnableKeyword(UnityConstants.StdShader_MapKeyword_Metallic); } material.SetFloat(UnityConstants.StdShader_Property_MetallicFloat, Constants.ZeroF); material.SetFloat(UnityConstants.StdShader_Property_SmoothnessFloat, 0.20F); if (!material.IsKeywordEnabled(UnityConstants.StdShader_MapKeyword_Normal)) { material.EnableKeyword(UnityConstants.StdShader_MapKeyword_Normal); } material.SetFloat(UnityConstants.StdShader_Property_NormalScaleFloat, 1F); }
public void FindProperties(Material material, MaterialProperty[] props) { m_LightingMode = FindProperty ("_LightingMode", props, false); m_BlendMode = FindProperty ("_BlendMode", props, false); m_AlphaMode = FindProperty ("_AlphaMode", props, false); m_MainTexture = FindProperty ("_MainTex", props); m_TintColor = FindProperty ("_TintColor", props); m_Cutoff = FindProperty ("_Cutoff", props, false); m_Thickness = FindProperty ("_Thickness", props, false); m_InvFade = FindProperty ("_InvFade", props, false); m_DistanceFadeStart = FindProperty ("_FadeStart", props, false); m_DistanceFadeEnd = FindProperty ("_FadeEnd", props, false); m_SoftParticles = material.IsKeywordEnabled ("SOFTPARTICLE_ON") ? true : false; m_DistanceFade = material.IsKeywordEnabled ("DISTANCEFADE_ON") ? true : false; }
public void EnsureKeyword(Material material, string name, bool enabled) { if (enabled != material.IsKeywordEnabled(name)) { if (enabled) material.EnableKeyword(name); else material.DisableKeyword(name); } }
static public int IsKeywordEnabled(IntPtr l) { try { UnityEngine.Material self = (UnityEngine.Material)checkSelf(l); System.String a1; checkType(l, 2, out a1); var ret = self.IsKeywordEnabled(a1); pushValue(l, true); pushValue(l, ret); return(2); } catch (Exception e) { return(error(l, e)); } }
static int IsKeywordEnabled(IntPtr L) { try { ToLua.CheckArgsCount(L, 2); UnityEngine.Material obj = (UnityEngine.Material)ToLua.CheckObject(L, 1, typeof(UnityEngine.Material)); string arg0 = ToLua.CheckString(L, 2); bool o = obj.IsKeywordEnabled(arg0); LuaDLL.lua_pushboolean(L, o); return(1); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
bool UseMeshNormalsCheckbox (Material material) { EditorGUI.BeginChangeCheck(); bool fixedNormals = material.IsKeywordEnabled(_FIXED_NORMALS); bool fixedNormalsBackRendering = material.IsKeywordEnabled(_FIXED_NORMALS_BACK_RENDERING); bool meshNormals = EditorGUILayout.Toggle(new GUIContent("Use Mesh Normals", "If this is unticked, a Fixed Normal value will be used instead of the vertex normals on the mesh. Using a fixed normal is better for performance and can result in better looking lighting effects on 2d objects."), !fixedNormals && !fixedNormalsBackRendering); if (EditorGUI.EndChangeCheck()) { SetKeyword(material, _FIXED_NORMALS, meshNormals ? false : fixedNormalsBackRendering ? false : true); SetKeyword(material, _FIXED_NORMALS_BACK_RENDERING, meshNormals ? false : fixedNormalsBackRendering); } return meshNormals; }
public virtual void DoDissolveArea(Material material) { m_MaterialEditor.TexturePropertySingleLine(Styles.dissolveMapText, dissolveMap); ShowDissolveMap(material); m_MaterialEditor.TexturePropertySingleLine(Styles.directionMapText, directionMap); if (substituteMap != null) { m_MaterialEditor.TexturePropertySingleLine(Styles.substituteText, substituteMap); } if (substituteColor != null) { m_MaterialEditor.ColorProperty(substituteColor, Styles.substituteColorText.text); } m_MaterialEditor.ShaderProperty(dissolveGlow, Styles.burnInText.text); if (material.IsKeywordEnabled("_DISSOLVEGLOW_ON")) { if (glowFollow != null) { m_MaterialEditor.ShaderProperty(glowFollow, Styles.glowFollowText.text); } m_MaterialEditor.ColorProperty(glowColor, Styles.burnColorText.text); m_MaterialEditor.FloatProperty(glowIntensity, Styles.burnIntensity.text); } if (!material.IsKeywordEnabled("_EDGECOLORRAMP_USE")) { m_MaterialEditor.ShaderProperty(colorBlend, Styles.blendColorsText.text); m_MaterialEditor.ColorProperty(outerEdgeColor, Styles.outerEdgeText.text); if (!material.IsKeywordEnabled("_COLORBLENDING_ON")) { m_MaterialEditor.ShaderProperty(outerEdgeThickness, Styles.edgeThicknessText.text, MaterialEditor.kMiniTextureFieldLabelIndentLevel+1); } m_MaterialEditor.ColorProperty(innerEdgeColor, Styles.innerEdgeText.text); if (!material.IsKeywordEnabled("_COLORBLENDING_ON")) { m_MaterialEditor.ShaderProperty(innerEdgeThickness, Styles.edgeThicknessText.text, MaterialEditor.kMiniTextureFieldLabelIndentLevel+1); } else { m_MaterialEditor.ShaderProperty(innerEdgeThickness, Styles.edgeThicknessSoloText.text); } } else { m_MaterialEditor.TexturePropertySingleLine(Styles.edgeColorRampText, edgeColorRamp); m_MaterialEditor.ShaderProperty(innerEdgeThickness, Styles.edgeThicknessSoloText.text); } EditorGUILayout.Space(); EditorGUI.indentLevel++; m_AdvancedSettings = EditorGUILayout.Foldout(m_AdvancedSettings, Styles.advancedSettings); if (m_AdvancedSettings) { EditorGUI.indentLevel++; EditorGUILayout.Space(); DoAdvancedArea(material); EditorGUI.indentLevel--; } EditorGUI.indentLevel--; }
protected virtual void ShaderPropertiesGUI (Material material) { using (new EditorGUILayout.HorizontalScope()) { GUILayout.FlexibleSpace(); var showAdvancedLabel = new GUIContent("Show Advanced", "Show extra options under all sections. This only affects the inspector. The Material's resulting shader is still compiled/optimized based on what features you actually use and don't use."); float lw = GUI.skin.toggle.CalcSize(showAdvancedLabel).x; EditorGUIUtility.labelWidth = lw; showAdvanced = EditorGUILayout.Toggle(showAdvancedLabel, showAdvanced); EditorGUIUtility.labelWidth = 0f; } EditorGUILayout.Space(); EditorGUI.BeginChangeCheck(); { LightingModePopup(); BlendModePopup(); if (showAdvanced) { EditorGUILayout.Space(); EditorGUI.BeginChangeCheck(); int renderQueue = EditorGUILayout.IntSlider("Renderer Queue Offset", (int)_renderQueue.floatValue, 0, 49); if (EditorGUI.EndChangeCheck()) material.SetInt("_RenderQueue", renderQueue); EditorGUI.BeginChangeCheck(); eCulling culling = (eCulling)Mathf.RoundToInt(_culling.floatValue); culling = (eCulling)EditorGUILayout.EnumPopup("Culling", culling); if (EditorGUI.EndChangeCheck()) material.SetInt("_Cull", (int)culling); EditorGUI.BeginChangeCheck(); bool fog = EditorGUILayout.Toggle("Use fog", material.IsKeywordEnabled("_FOG")); if (EditorGUI.EndChangeCheck()) SetKeyword(material, "_FOG", fog); EditorGUI.BeginChangeCheck(); bool enabled = EditorGUILayout.Toggle( new GUIContent( "Use Spherical Harmonics", "Enable to use spherical harmonics to calculate ambient light / light probes. In vertex-lit mode this will be approximated from scenes ambient trilight settings."), material.IsKeywordEnabled(_SPHERICAL_HARMONICS) ); if (EditorGUI.EndChangeCheck()) SetKeyword(material, _SPHERICAL_HARMONICS, enabled); } using (new SpineInspectorUtility.BoxScope()) RenderTextureProperties("Main Maps", material); if (showAdvanced) { using (new SpineInspectorUtility.BoxScope()) { Heading("Depth and Cast Shadow"); EditorGUI.BeginChangeCheck(); bool writeTodepth = EditorGUILayout.Toggle(new GUIContent("Write to Depth", "Write to Depth Buffer by clipping alpha."), _writeToDepth.floatValue != 0.0f); if (EditorGUI.EndChangeCheck()) material.SetInt("_ZWrite", writeTodepth ? 1 : 0); if (writeTodepth) _materialEditor.RangeProperty(_depthAlphaCutoff, "Depth Alpha Cutoff"); EditorGUILayout.Space(); _materialEditor.RangeProperty(_shadowAlphaCutoff, "Shadow Alpha Cutoff"); } if (_fixedNormal != null) { using (new SpineInspectorUtility.BoxScope()) { Heading("Normals"); bool meshNormals = UseMeshNormalsCheckbox(material); if (!meshNormals) { Vector3 normal; EditorGUI.BeginChangeCheck(); normal = showAdvanced ? EditorGUILayout.Vector3Field(new GUIContent("Fixed Normal", "Defined in Camera Space. Should normally be (0,0,-1)."), _fixedNormal.vectorValue) : (Vector3)_fixedNormal.vectorValue; if (EditorGUI.EndChangeCheck()) _fixedNormal.vectorValue = new Vector4(normal.x, normal.y, normal.z, 1.0f); bool backRendering; EditorGUI.BeginChangeCheck(); if (showAdvanced) { backRendering = EditorGUILayout.Toggle(new GUIContent("Fixed Normal Back Rendering", "Tick only if you are going to rotate the sprite to face away from the camera, the fixed normal will be flipped to compensate."), material.IsKeywordEnabled(_FIXED_NORMALS_BACK_RENDERING)); } else { backRendering = material.IsKeywordEnabled(_FIXED_NORMALS_BACK_RENDERING); } if (EditorGUI.EndChangeCheck()) { SetKeyword(material, _FIXED_NORMALS_BACK_RENDERING, backRendering); SetKeyword(material, _FIXED_NORMALS, !backRendering); } } } } } else { using (new SpineInspectorUtility.BoxScope()) { EditorGUI.BeginChangeCheck(); bool writeTodepth = EditorGUILayout.Toggle(new GUIContent("Write to Depth", "Write to Depth Buffer by clipping alpha."), _writeToDepth.floatValue != 0.0f); if (EditorGUI.EndChangeCheck()) material.SetInt("_ZWrite", writeTodepth ? 1 : 0); if (_fixedNormal != null) UseMeshNormalsCheckbox(material); } } using (new SpineInspectorUtility.BoxScope()) RenderColorProperties("Color Adjustment", material); if (_emissionMap != null && _emissionColor != null && _rimColor != null) { Heading("Extra Lighting"); if (_emissionMap != null && _emissionColor != null) using (new SpineInspectorUtility.BoxScope()) RenderEmissionProperties(material); if (_rimColor != null) using (new SpineInspectorUtility.BoxScope()) RenderRimLightingProperties(material); } } if (EditorGUI.EndChangeCheck()) { MaterialChanged(material); } }
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")); SetKeyword (material, "_SUBMAP", material.GetTexture ("_SubTex")); SetKeyword (material, "_DISSOLVEMAP", material.GetTexture ("_DissolveMap"));// || material.IsKeywordEnabled("_PAINT_ON")); SetKeyword (material, "_DIRECTIONMAP", material.GetTexture ("_DirectionMap")); if (workflowMode == WorkflowMode.Specular) SetKeyword (material, "_SPECGLOSSMAP", material.GetTexture ("_SpecGlossMap")); else if (workflowMode == WorkflowMode.Metallic) 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")) || material.IsKeywordEnabled("_DISSOLVEGLOW_ON") || material.IsKeywordEnabled("_EDGEGLOW_ON"); 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; } }
private void InitializePrimaryMeshMaterial(Material material) { if (!material.IsKeywordEnabled(UnityConstants.StdShader_RenderModeKeyword_CutoutTransparency)) { material.EnableKeyword(UnityConstants.StdShader_RenderModeKeyword_CutoutTransparency); } material.SetFloat(UnityConstants.StdShader_Property_AlphaCutoffFloat, 0.2F); }
static bool ToggleHeadingKeyword (string label, Material material, string keyword) { int i = EditorGUI.indentLevel; var o = EditorStyles.label.fontStyle; EditorGUI.indentLevel = 0; EditorStyles.label.fontStyle = FontStyle.Bold; EditorGUI.BeginChangeCheck(); bool r = EditorGUILayout.Toggle(new GUIContent(label, string.Format("This checkbox sets shader keyword: '{0}', which causes the Material to use extra shader features.", keyword)), material.IsKeywordEnabled(keyword)); if (EditorGUI.EndChangeCheck()) SetKeyword(material, keyword, r); EditorStyles.label.fontStyle = o; EditorGUI.indentLevel = i; return r; }
bool HasValidEmissiveKeyword(Material material) { // Material animation might be out of sync with the material keyword. // So if the emission support is disabled on the material, but the property blocks have a value that requires it, then we need to show a warning. // (note: (Renderer MaterialPropertyBlock applies its values to emissionColorForRendering)) bool hasEmissionKeyword = material.IsKeywordEnabled ("_EMISSION"); if (!hasEmissionKeyword && ShouldEmissionBeEnabled (emissionColorForRendering.colorValue)) return false; else return true; }
//Toogle a Shader feature private void ToggleFeature(Material _matTarget, string label, ShaderFeature feature, float height = 20f, bool disableGroup = true) { var setter = _matTarget.IsKeywordEnabled(feature.GetString()); var lbl = (setter) ? ("Disable " + label) : ("Enable " + label); if (GUILayout.Button(lbl, GUILayout.Height(height))) { setter = !setter; if (setter) { _matTarget.EnableKeyword(feature.GetString()); } else { _matTarget.DisableKeyword(feature.GetString()); } } //Set this to false to not disabled the remaining GUI components if (disableGroup) EditorGUI.BeginDisabledGroup(!setter); }
/// <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 bool HasValidEmissiveKeyword(Material material) { return material.IsKeywordEnabled("_EMISSION") || !StandardShaderGUI.ShouldEmissionBeEnabled(this.emissionColorForRendering.colorValue); }
void SetKeyword(Material m, bool state, string name) { if (state == m.IsKeywordEnabled(name)) return; if (state) m.EnableKeyword(name); else m.DisableKeyword(name); }
/// <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); }
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); }
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 void SetRenderQueue (Material material, string queue) { bool meshNormal = true; if (material.HasProperty("_FixedNormal")) { bool fixedNormals = material.IsKeywordEnabled(_FIXED_NORMALS); bool fixedNormalsBackRendering = material.IsKeywordEnabled(_FIXED_NORMALS_BACK_RENDERING); meshNormal = !fixedNormals && !fixedNormalsBackRendering; } material.SetOverrideTag("RenderType", meshNormal ? queue : "Sprite"); }
static void SetMaterialKeywords(Material material) { // Note: keywords must be based on Material value not on MaterialProperty due to multi-edit & material animation // (MaterialProperty value might come from renderer material property block) SetKeyword (material, "_NORMALMAP", material.GetTexture ("_BumpMap") || material.GetTexture ("_DetailNormalMap")); SpecularMode specularMode = ( SpecularMode )material.GetInt( "_SpecularMode" ); if ( specularMode == SpecularMode.BlinnPhong ) { SetKeyword( material, "_SPECGLOSSMAP", material.GetTexture( "_SpecGlossMap" ) ); } else if ( specularMode == SpecularMode.Metallic ) { SetKeyword( material, "_METALLICGLOSSMAP", material.GetTexture( "_MetallicGlossMap" ) ); } SetKeyword( material, "S_SPECULAR_NONE", specularMode == SpecularMode.None ); SetKeyword( material, "S_SPECULAR_BLINNPHONG", specularMode == SpecularMode.BlinnPhong ); SetKeyword( material, "S_SPECULAR_METALLIC", specularMode == SpecularMode.Metallic ); SetKeyword( material, "S_OCCLUSION", material.GetTexture("_OcclusionMap") ); SetKeyword( material, "_PARALLAXMAP", material.GetTexture("_ParallaxMap")); SetKeyword( material, "_DETAIL_MULX2", material.GetTexture("_DetailAlbedoMap") || material.GetTexture("_DetailNormalMap")); SetKeyword( material, "S_OVERRIDE_LIGHTMAP", material.GetTexture( "g_tOverrideLightmap" ) ); SetKeyword( material, "S_UNLIT", material.GetInt( "g_bUnlit" ) == 1 ); SetKeyword( material, "S_RECEIVE_SHADOWS", material.GetInt( "g_bReceiveShadows" ) == 1 ); SetKeyword( material, "S_WORLD_ALIGNED_TEXTURE", material.GetInt( "g_bWorldAlignedTexture" ) == 1 ); bool shouldEmissionBeEnabled = ShouldEmissionBeEnabled (material.GetColor("_EmissionColor")); SetKeyword (material, "_EMISSION", shouldEmissionBeEnabled); if ( material.IsKeywordEnabled( "S_RENDER_BACKFACES" ) ) { material.SetInt( "_Cull", ( int )UnityEngine.Rendering.CullMode.Off ); } else { material.SetInt( "_Cull", ( int )UnityEngine.Rendering.CullMode.Back ); } // Setup lightmap emissive flags MaterialGlobalIlluminationFlags flags = material.globalIlluminationFlags; if ((flags & (MaterialGlobalIlluminationFlags.BakedEmissive | MaterialGlobalIlluminationFlags.RealtimeEmissive)) != 0) { flags &= ~MaterialGlobalIlluminationFlags.EmissiveIsBlack; if (!shouldEmissionBeEnabled) flags |= MaterialGlobalIlluminationFlags.EmissiveIsBlack; material.globalIlluminationFlags = flags; } // Reflectance constants float flReflectanceMin = material.GetFloat( "g_flReflectanceMin" ); float flReflectanceMax = material.GetFloat( "g_flReflectanceMax" ); material.SetFloat( "g_flReflectanceScale", Mathf.Max( flReflectanceMin, flReflectanceMax ) - flReflectanceMin ); material.SetFloat( "g_flReflectanceBias", flReflectanceMin ); // World aligned texture constants Vector4 worldAlignedTextureNormal = material.GetVector( "g_vWorldAlignedTextureNormal" ); Vector3 normal = new Vector3( worldAlignedTextureNormal.x, worldAlignedTextureNormal.y, worldAlignedTextureNormal.z ); normal = ( normal.sqrMagnitude > 0.0f ) ? normal : Vector3.up; Vector3 tangentU = Vector3.zero, tangentV = Vector3.zero; Vector3.OrthoNormalize( ref normal, ref tangentU, ref tangentV ); material.SetVector( "g_vWorldAlignedNormalTangentU", new Vector4( tangentU.x, tangentU.y, tangentU.z, 0.0f ) ); material.SetVector( "g_vWorldAlignedNormalTangentV", new Vector4( tangentV.x, tangentV.y, tangentV.z, 0.0f ) ); // Static combo skips if ( material.GetInt( "g_bUnlit" ) == 1 ) { material.DisableKeyword( "_NORMALMAP" ); material.EnableKeyword( "S_SPECULAR_NONE" ); material.DisableKeyword( "S_SPECULAR_BLINNPHONG" ); material.DisableKeyword( "S_SPECULAR_METALLIC" ); material.DisableKeyword( "_METALLICGLOSSMAP" ); material.DisableKeyword( "_SPECGLOSSMAP" ); material.DisableKeyword( "S_OVERRIDE_LIGHTMAP" ); material.DisableKeyword( "S_RECEIVE_SHADOWS" ); } }
static eBlendMode GetMaterialBlendMode (Material material) { if (material.IsKeywordEnabled(PremultipledAlpha)) return eBlendMode.PreMultipliedAlpha; if (material.IsKeywordEnabled(Multiply)) return eBlendMode.Multiply; if (material.IsKeywordEnabled(Multiply2x)) return eBlendMode.Multiplyx2; if (material.IsKeywordEnabled(Additive)) return eBlendMode.Additive; if (material.IsKeywordEnabled(SoftAdditive)) return eBlendMode.SoftAdditive; return eBlendMode.StandardAlpha; }
//This method usually get's invoked by the Widget public static void CreatCollectionFromMaterial(Material sourceMat) { //Set up the path and give a prompt var path = EditorUtility.SaveFilePanelInProject( string.Format("Save a new Properties Collection from [{0}]", Selection.activeGameObject.name), string.Format("PropsCollection_{0}.asset", sourceMat.name), "asset", string.Format("Save a new Properties Collection from [{0}]", sourceMat.name)); //Abbort if the user presses the Cancel button if (string.IsNullOrEmpty(path)) return; //Create a new Properties Collection object var obj = ScriptableObject.CreateInstance<PropertiesCollection>(); //We make some helper lists that will cast later back into an array var listFloatTargets = new List<PropertiesCollection.FloatTargets>(); var listTintTargets = new List<PropertiesCollection.TintTargets>(); var listTextureTargets = new List<PropertiesCollection.TextureTargets>(); var listFeatureTargets = new List<PropertiesCollection.FeatureTargets>(); //Float Properties //We cast the Enum to an Array to use it lenghts for iterating through it var floatNames = Enum.GetNames(typeof(ShaderFloat)); foreach (var item in floatNames) { //Parse the string back to the Enum var enumParsed = (ShaderFloat)Enum.Parse(typeof(ShaderFloat), item); if (sourceMat.HasProperty(enumParsed.GetString())) { var target = new PropertiesCollection.FloatTargets(); target.Target = enumParsed; target.Value = sourceMat.GetFloat(enumParsed.GetString()); listFloatTargets.Add(target); } } //Tints //We cast the Enum to an Array to use it lenghts for iterating through it var colorNames = Enum.GetNames(typeof(ShaderColor)); foreach (var item in colorNames) { //Parse the string back to the Enum var enumParsed = (ShaderColor)Enum.Parse(typeof(ShaderColor), item); if (sourceMat.HasProperty(enumParsed.GetString())) { var target = new PropertiesCollection.TintTargets(); target.Target = enumParsed; target.Value = sourceMat.GetColor(enumParsed.GetString()); listTintTargets.Add(target); } } //Textures //We cast the Enum to an Array to use it lenghts for iterating through it var texNames = Enum.GetNames(typeof(ShaderTexture)); foreach (var item in texNames) { //Parse the string back to the Enum var enumParsed = (ShaderTexture)Enum.Parse(typeof(ShaderTexture), item); if (sourceMat.HasProperty(enumParsed.GetString())) { var target = new PropertiesCollection.TextureTargets(); target.Target = enumParsed; var tex = sourceMat.GetTexture(enumParsed.GetString()); if(tex != null) target.Value = tex; listTextureTargets.Add(target); } } //Keywords //We cast the Enum to an Array to use it lenghts for iterating through it var featureNames = Enum.GetNames(typeof(ShaderFeatureRuntime)); foreach (var item in featureNames) { //Parse the string back to the Enum var enumParsed = (ShaderFeatureRuntime)Enum.Parse(typeof(ShaderFeatureRuntime), item); if(sourceMat.IsKeywordEnabled(enumParsed.GetString())) { var target = new PropertiesCollection.FeatureTargets(); target.Target = enumParsed; target.Value = true; listFeatureTargets.Add(target); } } //Set the Collection Name by the Material Name obj.CollectionName = sourceMat.name; //Fill the Properties Collection Array from the Helper Lists obj.Floats = listFloatTargets.ToArray(); obj.Tints = listTintTargets.ToArray(); obj.Textures = listTextureTargets.ToArray(); obj.Features = listFeatureTargets.ToArray(); //Store the object as Asset on our Project AssetDatabase.CreateAsset(obj, path); Debug.Log(string.Format("A happy new Properties Collection has been saved in:\n " + path)); //We are done and focus the active object in the Editor to this Selection.activeObject = obj; }
private bool HasValidEmissiveKeyword(Material material) { if (!material.IsKeywordEnabled("_EMISSION") && ShouldEmissionBeEnabled(material, this.emissionColorForRendering.colorValue)) { return false; } return true; }
private bool HasValidTemperatureKeyword(Material material) { bool hasTemperatureKeyword = material.IsKeywordEnabled("_TEMPERATURE"); if (!hasTemperatureKeyword && ShouldTemperatureBeEnabled(material)) return false; else return true; }
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> /// 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); }
private void InitializePrimaryMeshMaterial(Material material) { if (material.IsKeywordEnabled(UnityConstants.StdShader_RenderModeKeyword_FadeTransparency)) { material.EnableKeyword(UnityConstants.StdShader_RenderModeKeyword_FadeTransparency); } }
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); }