private static glTFMaterial Migrate(JsonNode vrm0XMaterial, string materialName, Dictionary <int, int> renderQueueMapper)
        {
            try
            {
                if (MigrationMaterialUtil.GetShaderName(vrm0XMaterial) != Unity0XShaderName)
                {
                    return(null);
                }

                var baseColorFactor  = MigrationMaterialUtil.GetBaseColorFactor(vrm0XMaterial);
                var baseColorTexture = MigrationMaterialUtil.GetBaseColorTexture(vrm0XMaterial);
                var emissiveTexture  = new glTFMaterialEmissiveTextureInfo
                {
                    index      = baseColorTexture.index,
                    extensions = baseColorTexture.extensions,
                };
                var renderQueue       = MigrationMaterialUtil.GetRenderQueue(vrm0XMaterial) ?? Unity0XDefaultRenderQueue;
                var renderQueueOffset = renderQueueMapper.ContainsKey(renderQueue) ? renderQueueMapper[renderQueue] : 0;

                var mtoonMaterial = new glTFMaterial
                {
                    name       = materialName,
                    extensions = new glTFExtensionExport().Add(
                        glTF_KHR_materials_unlit.ExtensionName,
                        new ArraySegment <byte>(glTF_KHR_materials_unlit.Raw)
                        ),
                    pbrMetallicRoughness = new glTFPbrMetallicRoughness
                    {
                        baseColorFactor  = new[] { 0f, 0f, 0f, baseColorFactor[3] }, // black + _Color.a
                        baseColorTexture = baseColorTexture,                         // _MainTex
                        metallicFactor   = 0f,
                        roughnessFactor  = 1f,
                    },
                    alphaMode       = "BLEND",
                    alphaCutoff     = 0.5f,
                    doubleSided     = false,
                    emissiveFactor  = new[] { baseColorFactor[0], baseColorFactor[1], baseColorFactor[2] }, // _Color.rgb
                    emissiveTexture = emissiveTexture,
                };

                var mtoon10 = new VRMC_materials_mtoon
                {
                    SpecVersion             = MigrationMToon10SpecVersion,
                    TransparentWithZWrite   = true,                 // transparent with zWrite
                    RenderQueueOffsetNumber = renderQueueOffset,
                    ShadeColorFactor        = new[] { 0f, 0f, 0f }, // black
                    OutlineWidthMode        = OutlineWidthMode.none // disable outline
                };
                UniGLTF.Extensions.VRMC_materials_mtoon.GltfSerializer.SerializeTo(ref mtoonMaterial.extensions,
                                                                                   mtoon10);

                return(mtoonMaterial);
            }
            catch (Exception)
            {
                Debug.LogWarning($"Migration failed in VRM/UnlitTransparentZWrite material: {materialName}");
                return(null);
            }
        }
Ejemplo n.º 2
0
 /// <summary>
 /// Create material name.
 /// </summary>
 /// <param name="i"></param>
 /// <param name="src"></param>
 /// <returns></returns>
 protected virtual string CreateMaterialName(int i, glTFMaterial src)
 {
     if ((src == null) || string.IsNullOrEmpty(src.name))
     {
         return(string.Format("material_{0:00}", i));
     }
     return(src.name);
 }
Ejemplo n.º 3
0
        static bool Prefix(ShaderStore __instance, ref Shader __result, glTFMaterial material)
        {
            if (Settings.ReadBool("UseRealToonShader", false))
            {
                __result = Shader.Find("RealToon/Version 5/Default/Default");
                return(false);
            }

            return(true);
        }
Ejemplo n.º 4
0
        public MaterialItemBase CreateMaterial(int i, glTFMaterial src, bool hasVertexColor)
        {
            if (i == 0 && m_materials.Count == 0)
            {
                // dummy
                return(new PBRMaterialItem(i, src));
            }

            return(new MToonMaterialItem(i, src, hasVertexColor, m_materials[i]));
        }
Ejemplo n.º 5
0
        public static int?TryGetRenderQueue(glTFMaterial material, VRMC_materials_mtoon mToon)
        {
            var renderQueueOffset = mToon?.RenderQueueOffsetNumber;

            if (renderQueueOffset.HasValue)
            {
                var renderMode = GetMToonRenderMode(material, mToon);
                return(MToon.Utils.GetRenderQueueRequirement(renderMode).DefaultValue +
                       renderQueueOffset.Value);
            }
            return(default);
Ejemplo n.º 6
0
 private static MToon10DoubleSidedMode GetMToon10DoubleSidedMode(glTFMaterial material, VRMC_materials_mtoon mToon)
 {
     if (material?.doubleSided == true)
     {
         return(MToon10DoubleSidedMode.On);
     }
     else
     {
         return(MToon10DoubleSidedMode.Off);
     }
 }
Ejemplo n.º 7
0
 static glTFImage GetNormalImage(Vrm10Storage storage, glTFMaterial m)
 {
     if (m.normalTexture == null)
     {
         return(null);
     }
     if (!m.normalTexture.index.TryGetValidIndex(storage.TextureCount, out int index))
     {
         return(null);
     }
     return(GetTexture(storage, index));
 }
Ejemplo n.º 8
0
        public static IEnumerable <(string key, Color value)> TryGetAllColors(glTFMaterial material, VRMC_materials_mtoon mToon)
        {
            const ColorSpace gltfColorSpace = ColorSpace.Linear;

            // Rendering
            var baseColor = material?.pbrMetallicRoughness?.baseColorFactor?.ToColor4(gltfColorSpace, ColorSpace.sRGB);

            if (baseColor.HasValue)
            {
                yield return(MToon10Prop.BaseColorFactor.ToUnityShaderLabName(), baseColor.Value);
            }

            // Lighting
            var shadeColor = mToon?.ShadeColorFactor?.ToColor3(gltfColorSpace, ColorSpace.sRGB);

            if (shadeColor.HasValue)
            {
                yield return(MToon10Prop.ShadeColorFactor.ToUnityShaderLabName(), shadeColor.Value);
            }

            // GI

            // Emission
            // Emissive factor should be stored in Linear space
            var emissionColor = material?.emissiveFactor?.ToColor3(gltfColorSpace, ColorSpace.Linear);

            if (emissionColor.HasValue)
            {
                yield return(MToon10Prop.EmissiveFactor.ToUnityShaderLabName(), emissionColor.Value);
            }

            // Rim Lighting
            var rimColor = mToon?.ParametricRimColorFactor?.ToColor3(gltfColorSpace, ColorSpace.sRGB);

            if (rimColor.HasValue)
            {
                yield return(MToon10Prop.ParametricRimColorFactor.ToUnityShaderLabName(), rimColor.Value);
            }

            // Outline
            var outlineColor = mToon?.OutlineColorFactor?.ToColor3(gltfColorSpace, ColorSpace.sRGB);

            if (outlineColor.HasValue)
            {
                yield return(MToon10Prop.OutlineColorFactor.ToUnityShaderLabName(), outlineColor.Value);
            }

            // UV Animation
        }
Ejemplo n.º 9
0
 static bool Prefix(ShaderStore __instance, ref Shader __result, glTFMaterial material)
 {
     if (material == null)
     {
         __result = Shader.Find("Standard");
         return(false);
     }
     if (material.extensions != null && material.extensions.KHR_materials_unlit != null)
     {
         __result = Shader.Find("RealToon/Version 5/Default/Default");
         return(false);
     }
     __result = Shader.Find("Standard");
     return(false);
 }
Ejemplo n.º 10
0
 static glTFImage GetColorImage(Vrm10Storage storage, glTFMaterial m)
 {
     if (m.pbrMetallicRoughness == null)
     {
         return(null);
     }
     if (m.pbrMetallicRoughness.baseColorTexture == null)
     {
         return(null);
     }
     if (!m.pbrMetallicRoughness.baseColorTexture.index.TryGetValidIndex(storage.TextureCount, out int index))
     {
         return(null);
     }
     return(GetTexture(storage, index));
 }
Ejemplo n.º 11
0
        /// <summary>
        /// Create a Particle material.
        /// </summary>
        /// <param name="i"></param>
        /// <param name="src"></param>
        /// <returns></returns>
        protected virtual Material CreateParticleMaterial(int i, glTFMaterial src)
        {
            var shader = m_shaderStore.GetShader(src);

            Material material = new Material(shader);

            material.name = CreateMaterialName(i, src);

#if UNITY_EDITOR
            material.hideFlags = HideFlags.DontUnloadUnusedAsset;
#endif

            ParticleDefinition particleDefinition = CreateParticleDefinition(src.extensions.VGO_materials_particle);

            UniStandardParticle.Utils.SetParticleParametersToMaterial(material, particleDefinition);

            return(material);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Create a MToon material.
        /// </summary>
        /// <param name="i"></param>
        /// <param name="src"></param>
        /// <returns></returns>
        protected virtual Material CreateMtoonMaterial(int i, glTFMaterial src)
        {
            Shader shader = Shader.Find(MToon.Utils.ShaderName);

            Material material = new Material(shader);

            material.name = CreateMaterialName(i, src);

#if UNITY_EDITOR
            material.hideFlags = HideFlags.DontUnloadUnusedAsset;
#endif

            MToonDefinition mtoonDefinition = CreateMtoonDefinition(src.extensions.VRMC_materials_mtoon);

            MToon.Utils.SetMToonParametersToMaterial(material, mtoonDefinition);

            return(material);
        }
Ejemplo n.º 13
0
        public static Material FromGltf(this glTFMaterial x, List <Texture> textures)
        {
            if (UniGLTF.Extensions.VRMC_materials_mtoon.GltfDeserializer.TryGet(x.extensions,
                                                                                out UniGLTF.Extensions.VRMC_materials_mtoon.VRMC_materials_mtoon mtoon))
            {
                // mtoon
                return(MToonAdapter.MToonFromGltf(x, textures, mtoon));
            }

            if (glTF_KHR_materials_unlit.IsEnable(x))
            {
                // unlit
                return(UnlitFromGltf(x, textures));
            }

            // PBR
            return(PBRFromGltf(x, textures));
        }
Ejemplo n.º 14
0
        static void ExportMaterialExtension(Material m, glTFMaterial material)
        {
            // HDR Emission
            if (m.IsKeywordEnabled("_EMISSION") && m.HasProperty("_EmissionColor"))
            {
                var color = m.GetColor("_EmissionColor");
                if (color.maxColorComponent > 1)
                {
                    var extensions = new glTF_VCAST_materials_pbr();

                    extensions.emissiveFactor = new float[] { color.r, color.g, color.b };

                    var f = new UniJSON.JsonFormatter();
                    glTF_VCAST_materials_pbr_Serializer.Serialize(f, extensions);
                    glTFExtensionExport.GetOrCreate(ref material.extensions).Add(glTF_VCAST_materials_pbr.ExtensionName, f.GetStore().Bytes);
                }
            }
        }
Ejemplo n.º 15
0
 private static bool TryGetNormalTexture(GltfParser parser, glTFMaterial src, out (SubAssetKey, TextureImportParam) pair)
 {
     try
     {
         pair = GltfPBRMaterial.NormalTexture(parser, src);
         return(true);
     }
     catch (NullReferenceException)
     {
         pair = default;
         return(false);
     }
     catch (ArgumentOutOfRangeException)
     {
         pair = default;
         return(false);
     }
 }
Ejemplo n.º 16
0
 private static bool TryGetNormalTexture(GltfData data, glTFMaterial src, out (SubAssetKey, TextureDescriptor) pair)
 {
     try
     {
         pair = GltfPbrTextureImporter.NormalTexture(data, src);
         return(true);
     }
     catch (NullReferenceException)
     {
         pair = default;
         return(false);
     }
     catch (ArgumentOutOfRangeException)
     {
         pair = default;
         return(false);
     }
 }
Ejemplo n.º 17
0
        private static MToon10AlphaMode GetMToon10AlphaMode(glTFMaterial material)
        {
            switch (material?.alphaMode)
            {
            case "OPAQUE":
                return(MToon10AlphaMode.Opaque);

            case "MASK":
                return(MToon10AlphaMode.Cutout);

            case "BLEND":
                return(MToon10AlphaMode.Transparent);

            default:
                Debug.LogWarning($"Invalid AlphaMode");
                return(MToon10AlphaMode.Opaque);
            }
        }
Ejemplo n.º 18
0
        private static MToon10OutlineMode GetMToon10OutlineWidthMode(glTFMaterial material, VRMC_materials_mtoon mToon)
        {
            switch (mToon?.OutlineWidthMode)
            {
            case OutlineWidthMode.none:
                return(MToon10OutlineMode.None);

            case OutlineWidthMode.worldCoordinates:
                return(MToon10OutlineMode.World);

            case OutlineWidthMode.screenCoordinates:
                return(MToon10OutlineMode.Screen);

            default:
                // Invalid
                Debug.LogWarning("Invalid outlineWidthMode");
                return(MToon10OutlineMode.None);
            }
        }
Ejemplo n.º 19
0
        public static void LoadCommonParams(this Material self, glTFMaterial material, List <Texture> textures)
        {
            var pbr = material.pbrMetallicRoughness;

            if (pbr.baseColorFactor != null)
            {
                self.BaseColorFactor = LinearColor.FromLiner(pbr.baseColorFactor);
            }
            var baseColorTexture = pbr.baseColorTexture;

            if (baseColorTexture != null && baseColorTexture.index.TryGetValidIndex(textures.Count, out int index))
            {
                self.BaseColorTexture = new TextureInfo(textures[index]);
            }

            self.AlphaMode   = EnumUtil.Parse <VrmLib.AlphaModeType>(material.alphaMode);
            self.AlphaCutoff = material.alphaCutoff;
            self.DoubleSided = material.doubleSided;
        }
Ejemplo n.º 20
0
        public static IEnumerable <(string key, Color value)> TryGetAllColors(glTFMaterial material, VRMC_materials_mtoon mToon)
        {
            const ColorSpace gltfColorSpace = ColorSpace.Linear;

            var baseColor = material?.pbrMetallicRoughness?.baseColorFactor?.ToColor4(gltfColorSpace, ColorSpace.sRGB);

            if (baseColor.HasValue)
            {
                yield return(MToon.Utils.PropColor, baseColor.Value);
            }

            var emissionColor = material?.emissiveFactor?.ToColor3(gltfColorSpace, ColorSpace.Linear);

            if (emissionColor.HasValue)
            {
                yield return(MToon.Utils.PropEmissionColor, emissionColor.Value);
            }

            var shadeColor = mToon?.ShadeColorFactor?.ToColor3(gltfColorSpace, ColorSpace.sRGB);

            if (shadeColor.HasValue)
            {
                yield return(MToon.Utils.PropShadeColor, shadeColor.Value);
            }

            var rimColor = mToon?.ParametricRimColorFactor?.ToColor3(gltfColorSpace, ColorSpace.Linear);

            if (rimColor.HasValue)
            {
                yield return(MToon.Utils.PropRimColor, rimColor.Value);
            }

            var outlineColor = mToon?.OutlineColorFactor?.ToColor3(gltfColorSpace, ColorSpace.sRGB);

            if (outlineColor.HasValue)
            {
                yield return(MToon.Utils.PropOutlineColor, outlineColor.Value);
            }
        }
Ejemplo n.º 21
0
        static glTFMaterial ToGltf(this VrmLib.Material src, List <Texture> textures)
        {
            var material = new glTFMaterial
            {
                name = src.Name,
                pbrMetallicRoughness = new glTFPbrMetallicRoughness
                {
                    baseColorFactor = src.BaseColorFactor.ToFloat4(),
                },
                alphaMode   = CastAlphaMode(src.AlphaMode),
                alphaCutoff = src.AlphaCutoff,
                doubleSided = src.DoubleSided,
            };

            if (src.BaseColorTexture != null)
            {
                material.pbrMetallicRoughness.baseColorTexture = new glTFMaterialBaseColorTextureInfo
                {
                    index = textures.IndexOfNullable(src.BaseColorTexture.Texture).Value,
                };
            }
            return(material);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Create a material.
        /// </summary>
        /// <param name="i"></param>
        /// <param name="src"></param>
        /// <param name="hasVertexColor"></param>
        /// <returns></returns>
        public override Material CreateMaterial(int i, glTFMaterial src, bool hasVertexColor)
        {
            if (src.extensions != null)
            {
                if (src.extensions.VGO_materials_particle != null)
                {
                    return(CreateParticleMaterial(i, src));
                }
                if (src.extensions.VGO_materials_skybox != null)
                {
                    return(CreateSkyboxMaterial(i, src));
                }
                if (src.extensions.KHR_materials_unlit != null)
                {
                    return(CreateUnlitMaterial(i, src, hasVertexColor));
                }
                if (src.extensions.VRMC_materials_mtoon != null)
                {
                    return(CreateMtoonMaterial(i, src));
                }
            }

            return(base.CreateMaterial(i, src, hasVertexColor));
        }
Ejemplo n.º 23
0
 public static IEnumerable <(string key, Vector4 value)> TryGetAllFloatArrays(glTFMaterial material, VRMC_materials_mtoon mToon)
 {
     yield break;
 }
Ejemplo n.º 24
0
 private static MToon10TransparentWithZWriteMode GetMToon10TransparentWithZWriteMode(glTFMaterial material, VRMC_materials_mtoon mtoon)
 {
     if (mtoon?.TransparentWithZWrite == true)
     {
         return(MToon10TransparentWithZWriteMode.On);
     }
     else
     {
         return(MToon10TransparentWithZWriteMode.Off);
     }
 }
Ejemplo n.º 25
0
        public static IEnumerable <(string key, float value)> TryGetAllFloats(glTFMaterial material, VRMC_materials_mtoon mToon)
        {
            // Rendering
            var alphaMode = GetMToon10AlphaMode(material);
            {
                yield return(MToon10Prop.AlphaMode.ToUnityShaderLabName(), (float)alphaMode);
            }

            var transparentWithZWrite = GetMToon10TransparentWithZWriteMode(material, mToon);
            {
                yield return(MToon10Prop.TransparentWithZWrite.ToUnityShaderLabName(), (float)transparentWithZWrite);
            }

            var cutoff = material?.alphaCutoff;

            if (cutoff.HasValue)
            {
                yield return(MToon10Prop.AlphaCutoff.ToUnityShaderLabName(), cutoff.Value);
            }

            var renderQueueOffset = mToon?.RenderQueueOffsetNumber;

            if (renderQueueOffset.HasValue)
            {
                yield return(MToon10Prop.RenderQueueOffsetNumber.ToUnityShaderLabName(), (float)renderQueueOffset);
            }

            var doubleSidedMode = GetMToon10DoubleSidedMode(material, mToon);
            {
                yield return(MToon10Prop.DoubleSided.ToUnityShaderLabName(), (float)doubleSidedMode);
            }

            // Lighting
            var normalScale = material?.normalTexture?.scale;

            if (normalScale.HasValue)
            {
                yield return(MToon10Prop.NormalTextureScale.ToUnityShaderLabName(), normalScale.Value);
            }

            var shadingShift = mToon?.ShadingShiftFactor;

            if (shadingShift.HasValue)
            {
                yield return(MToon10Prop.ShadingShiftFactor.ToUnityShaderLabName(), shadingShift.Value);
            }

            var shadingShiftTextureScale = mToon?.ShadingShiftTexture?.Scale;

            if (shadingShiftTextureScale.HasValue)
            {
                yield return(MToon10Prop.ShadingShiftTextureScale.ToUnityShaderLabName(), shadingShiftTextureScale.Value);
            }

            var shadingToony = mToon?.ShadingToonyFactor;

            if (shadingToony.HasValue)
            {
                yield return(MToon10Prop.ShadingToonyFactor.ToUnityShaderLabName(), shadingToony.Value);
            }

            // GI
            var giEqualization = mToon?.GiEqualizationFactor;

            if (giEqualization.HasValue)
            {
                yield return(MToon10Prop.GiEqualizationFactor.ToUnityShaderLabName(), giEqualization.Value);
            }

            // Emission

            // Rim Lighting
            var rimFresnelPower = mToon?.ParametricRimFresnelPowerFactor;

            if (rimFresnelPower.HasValue)
            {
                yield return(MToon10Prop.ParametricRimFresnelPowerFactor.ToUnityShaderLabName(), rimFresnelPower.Value);
            }

            var rimLift = mToon?.ParametricRimLiftFactor;

            if (rimLift.HasValue)
            {
                yield return(MToon10Prop.ParametricRimLiftFactor.ToUnityShaderLabName(), rimLift.Value);
            }

            var rimLightMix = mToon?.RimLightingMixFactor;

            if (rimLightMix.HasValue)
            {
                yield return(MToon10Prop.RimLightingMixFactor.ToUnityShaderLabName(), rimLightMix.Value);
            }

            // Outline
            var outlineMode = GetMToon10OutlineWidthMode(material, mToon);
            {
                yield return(MToon10Prop.OutlineWidthMode.ToUnityShaderLabName(), (float)outlineMode);
            }

            var outlineWidth = mToon?.OutlineWidthFactor;

            if (outlineWidth.HasValue)
            {
                yield return(MToon10Prop.OutlineWidthFactor.ToUnityShaderLabName(), outlineWidth.Value);
            }

            var outlineLightMix = mToon?.OutlineLightingMixFactor;

            if (outlineLightMix.HasValue)
            {
                yield return(MToon10Prop.OutlineLightingMixFactor.ToUnityShaderLabName(), outlineLightMix.Value);
            }

            // UV Animation
            var uvAnimSpeedScrollX = mToon?.UvAnimationScrollXSpeedFactor;

            if (uvAnimSpeedScrollX.HasValue)
            {
                yield return(MToon10Prop.UvAnimationScrollXSpeedFactor.ToUnityShaderLabName(), uvAnimSpeedScrollX.Value);
            }

            var uvAnimSpeedScrollY = mToon?.UvAnimationScrollYSpeedFactor;

            if (uvAnimSpeedScrollY.HasValue)
            {
                // UV coords conversion.
                // glTF (top-left origin) to Unity (bottom-left origin)
                const float invertY = -1f;

                yield return(MToon10Prop.UvAnimationScrollYSpeedFactor.ToUnityShaderLabName(), uvAnimSpeedScrollY.Value *invertY);
            }

            var uvAnimSpeedRotation = mToon?.UvAnimationRotationSpeedFactor;

            if (uvAnimSpeedRotation.HasValue)
            {
                yield return(MToon10Prop.UvAnimationRotationSpeedFactor.ToUnityShaderLabName(), uvAnimSpeedRotation.Value);
            }

            // UI
            if (true /* TODO: mToon.IsAdvancedMode */)
            {
                yield return(MToon10Prop.EditorEditMode.ToUnityShaderLabName(), 1);
            }
        }
Ejemplo n.º 26
0
        public static bool TryExportMaterialAsMToon(Material src, ITextureExporter textureExporter, out glTFMaterial dst)
        {
            try
            {
                if (src.shader.name != MToon10Meta.UnityShaderName)
                {
                    dst = null;
                    return(false);
                }

                // Get MToon10 Context
                var context = new MToon10Context(src);
                context.Validate();

                // base material
                dst      = glTF_KHR_materials_unlit.CreateDefault();
                dst.name = src.name;

                // vrmc_materials_mtoon ext
                var mtoon = new UniGLTF.Extensions.VRMC_materials_mtoon.VRMC_materials_mtoon();
                mtoon.SpecVersion = MTOON_SPEC_VERSION;

                // Rendering
                dst.alphaMode = ExportAlphaMode(context.AlphaMode);
                mtoon.TransparentWithZWrite   = context.TransparentWithZWriteMode == MToon10TransparentWithZWriteMode.On;
                dst.alphaCutoff               = Mathf.Max(0, context.AlphaCutoff);
                mtoon.RenderQueueOffsetNumber = context.RenderQueueOffsetNumber;
                dst.doubleSided               = context.DoubleSidedMode == MToon10DoubleSidedMode.On;

                // Lighting
                dst.pbrMetallicRoughness = new glTFPbrMetallicRoughness();
                dst.pbrMetallicRoughness.baseColorFactor = context.BaseColorFactorSrgb.ToFloat4(ColorSpace.sRGB, ColorSpace.Linear);
                var baseColorTextureIndex = textureExporter.RegisterExportingAsSRgb(context.BaseColorTexture, context.AlphaMode != MToon10AlphaMode.Opaque);
                if (baseColorTextureIndex != -1)
                {
                    dst.pbrMetallicRoughness.baseColorTexture = new glTFMaterialBaseColorTextureInfo
                    {
                        index = baseColorTextureIndex,
                    };
                }
                mtoon.ShadeColorFactor = context.ShadeColorFactorSrgb.ToFloat3(ColorSpace.sRGB, ColorSpace.Linear);
                var shadeColorTextureIndex = textureExporter.RegisterExportingAsSRgb(context.ShadeColorTexture, needsAlpha: false);
                if (shadeColorTextureIndex != -1)
                {
                    mtoon.ShadeMultiplyTexture = new TextureInfo
                    {
                        Index = shadeColorTextureIndex,
                    };
                }
                var normalTextureIndex = textureExporter.RegisterExportingAsNormal(context.NormalTexture);
                if (normalTextureIndex != -1)
                {
                    dst.normalTexture = new glTFMaterialNormalTextureInfo
                    {
                        index = normalTextureIndex,
                        scale = context.NormalTextureScale,
                    };
                }
                mtoon.ShadingShiftFactor = context.ShadingShiftFactor;
                var shadingShiftTextureIndex = textureExporter.RegisterExportingAsLinear(context.ShadingShiftTexture, needsAlpha: false);
                if (shadingShiftTextureIndex != -1)
                {
                    mtoon.ShadingShiftTexture = new ShadingShiftTextureInfo
                    {
                        Index = shadingShiftTextureIndex,
                        Scale = context.ShadingShiftTextureScale,
                    };
                }
                mtoon.ShadingToonyFactor = context.ShadingToonyFactor;

                // GI
                // TODO: update schema
                mtoon.GiIntensityFactor = context.GiEqualizationFactor;

                // Emission
                dst.emissiveFactor = context.EmissiveFactorLinear.ToFloat3(ColorSpace.Linear, ColorSpace.Linear);
                var emissiveTextureIndex = textureExporter.RegisterExportingAsSRgb(context.EmissiveTexture, needsAlpha: false);
                if (emissiveTextureIndex != -1)
                {
                    dst.emissiveTexture = new glTFMaterialEmissiveTextureInfo
                    {
                        index = emissiveTextureIndex,
                    };
                }

                // Rim Lighting
                var matcapTextureIndex = textureExporter.RegisterExportingAsSRgb(context.MatcapTexture, needsAlpha: false);
                if (matcapTextureIndex != -1)
                {
                    mtoon.MatcapTexture = new TextureInfo
                    {
                        Index = matcapTextureIndex,
                    };
                }
                mtoon.ParametricRimColorFactor        = context.ParametricRimColorFactorSrgb.ToFloat3(ColorSpace.sRGB, ColorSpace.Linear);
                mtoon.ParametricRimFresnelPowerFactor = context.ParametricRimFresnelPowerFactor;
                mtoon.ParametricRimLiftFactor         = context.ParametricRimLiftFactor;
                var rimMultiplyTextureIndex = textureExporter.RegisterExportingAsSRgb(context.RimMultiplyTexture, needsAlpha: false);
                if (rimMultiplyTextureIndex != -1)
                {
                    mtoon.RimMultiplyTexture = new TextureInfo
                    {
                        Index = rimMultiplyTextureIndex,
                    };
                }
                mtoon.RimLightingMixFactor = context.RimLightingMixFactor;

                // Outline
                mtoon.OutlineWidthMode   = ExportOutlineWidthMode(context.OutlineWidthMode);
                mtoon.OutlineWidthFactor = context.OutlineWidthFactor;
                var outlineWidthMultiplyTextureIndex = textureExporter.RegisterExportingAsLinear(context.OutlineWidthMultiplyTexture, needsAlpha: false);
                if (outlineWidthMultiplyTextureIndex != -1)
                {
                    mtoon.OutlineWidthMultiplyTexture = new TextureInfo
                    {
                        Index = outlineWidthMultiplyTextureIndex,
                    };
                }
                mtoon.OutlineColorFactor       = context.OutlineColorFactorSrgb.ToFloat3(ColorSpace.sRGB, ColorSpace.Linear);
                mtoon.OutlineLightingMixFactor = context.OutlineLightingMixFactor;

                // UV Animation
                var uvAnimationMaskTextureIndex = textureExporter.RegisterExportingAsLinear(context.UvAnimationMaskTexture, needsAlpha: false);
                if (uvAnimationMaskTextureIndex != -1)
                {
                    mtoon.UvAnimationMaskTexture = new TextureInfo
                    {
                        Index = uvAnimationMaskTextureIndex,
                    };
                }
                mtoon.UvAnimationScrollXSpeedFactor = context.UvAnimationScrollXSpeedFactor;
                {
                    // Coordinate Conversion
                    const float invertY = -1f;
                    mtoon.UvAnimationScrollYSpeedFactor = context.UvAnimationScrollYSpeedFactor * invertY;
                }
                mtoon.UvAnimationRotationSpeedFactor = context.UvAnimationRotationSpeedFactor;

                // Texture Transforms
                var scale  = context.TextureScale;
                var offset = context.TextureOffset;
                ExportTextureTransform(dst.pbrMetallicRoughness.baseColorTexture, scale, offset);
                ExportTextureTransform(dst.emissiveTexture, scale, offset);
                ExportTextureTransform(dst.normalTexture, scale, offset);
                ExportTextureTransform(mtoon.ShadeMultiplyTexture, scale, offset);
                ExportTextureTransform(mtoon.ShadingShiftTexture, scale, offset);
                ExportTextureTransform(mtoon.MatcapTexture, scale, offset);
                ExportTextureTransform(mtoon.RimMultiplyTexture, scale, offset);
                ExportTextureTransform(mtoon.OutlineWidthMultiplyTexture, scale, offset);
                ExportTextureTransform(mtoon.UvAnimationMaskTexture, scale, offset);

                UniGLTF.Extensions.VRMC_materials_mtoon.GltfSerializer.SerializeTo(ref dst.extensions, mtoon);

                return(true);
            }
            catch (Exception)
            {
                dst = null;
                return(false);
            }
        }
Ejemplo n.º 27
0
        public static IEnumerable <(string key, float value)> TryGetAllFloats(glTFMaterial material, VRMC_materials_mtoon mToon)
        {
            var renderMode = GetMToonRenderMode(material, mToon);
            {
                yield return(MToon.Utils.PropBlendMode, (float)renderMode);
            }

            var cullMode = GetMToonCullMode(material, mToon);
            {
                yield return(MToon.Utils.PropCullMode, (float)cullMode);
            }

            var outlineMode = GetMToonOutlineWidthMode(material, mToon);
            {
                yield return(MToon.Utils.PropOutlineWidthMode, (float)outlineMode);

                // In case of VRM 1.0 MToon, outline color mode is always MixedLighting.
                yield return(MToon.Utils.PropOutlineColorMode, (float)MToon.OutlineColorMode.MixedLighting);
            }

            var cutoff = material?.alphaCutoff;

            if (cutoff.HasValue)
            {
                yield return(MToon.Utils.PropCutoff, cutoff.Value);
            }

            var normalScale = material?.normalTexture?.scale;

            if (normalScale.HasValue)
            {
                yield return("_BumpScale", normalScale.Value);
            }

            var shadingShift = mToon?.ShadingShiftFactor;

            if (shadingShift.HasValue)
            {
                yield return(MToon.Utils.PropShadeShift, shadingShift.Value);
            }

            var shadingShiftTextureScale = mToon?.ShadingShiftTexture?.Scale;

            if (shadingShiftTextureScale.HasValue)
            {
                Debug.LogWarning("Need VRM 1.0 MToon implementation.");
                yield return("_NEED_IMPLEMENTATION_MTOON_1_0_shadingShiftTextureScale", shadingShiftTextureScale.Value);
            }

            var shadingToony = mToon?.ShadingToonyFactor;

            if (shadingToony.HasValue)
            {
                yield return(MToon.Utils.PropShadeToony, shadingToony.Value);
            }

            var giIntensity = mToon?.GiIntensityFactor;

            if (giIntensity.HasValue)
            {
                yield return(MToon.Utils.PropIndirectLightIntensity, giIntensity.Value);
            }

            var rimLightMix = mToon?.RimLightingMixFactor;

            if (rimLightMix.HasValue)
            {
                yield return(MToon.Utils.PropRimLightingMix, rimLightMix.Value);
            }

            var rimFresnelPower = mToon?.ParametricRimFresnelPowerFactor;

            if (rimFresnelPower.HasValue)
            {
                yield return(MToon.Utils.PropRimFresnelPower, rimFresnelPower.Value);
            }

            var rimLift = mToon?.ParametricRimLiftFactor;

            if (rimLift.HasValue)
            {
                yield return(MToon.Utils.PropRimLift, rimLift.Value);
            }

            // Unit conversion.
            // Because Unity implemented MToon uses centimeter unit in width parameter.
            var outlineWidth = mToon?.OutlineWidthFactor;

            if (outlineWidth.HasValue)
            {
                const float meterToCentimeter = 100f;

                yield return(MToon.Utils.PropOutlineWidth, outlineWidth.Value *meterToCentimeter);
            }

            var outlineLightMix = mToon?.OutlineLightingMixFactor;

            if (outlineLightMix.HasValue)
            {
                yield return(MToon.Utils.PropOutlineLightingMix, outlineLightMix.Value);
            }

            var uvAnimSpeedScrollX = mToon?.UvAnimationScrollXSpeedFactor;

            if (uvAnimSpeedScrollX.HasValue)
            {
                yield return(MToon.Utils.PropUvAnimScrollX, uvAnimSpeedScrollX.Value);
            }

            // UV coords conversion.
            // glTF (top-left origin) to Unity (bottom-left origin)
            var uvAnimSpeedScrollY = mToon?.UvAnimationScrollYSpeedFactor;

            if (uvAnimSpeedScrollY.HasValue)
            {
                const float invertY = -1f;

                yield return(MToon.Utils.PropUvAnimScrollY, uvAnimSpeedScrollY.Value *invertY);
            }

            var uvAnimSpeedRotation = mToon?.UvAnimationRotationSpeedFactor;

            if (uvAnimSpeedRotation.HasValue)
            {
                yield return(MToon.Utils.PropUvAnimRotation, uvAnimSpeedRotation.Value);
            }
        }
Ejemplo n.º 28
0
        public static bool TryExportMaterialAsMToon(Material src, ITextureExporter textureExporter, out glTFMaterial dst)
        {
            try
            {
                if (src.shader.name != MToon.Utils.ShaderName)
                {
                    dst = null;
                    return(false);
                }

                // convert MToon intermediate value from UnityEngine.Material
                var def = MToon.Utils.GetMToonParametersFromMaterial(src);

                // gltfMaterial
                dst = new glTFMaterial
                {
                    name = src.name,

                    // Rendering
                    doubleSided = def.Rendering.CullMode == CullMode.Off,
                    alphaMode   = ExportAlphaMode(def.Rendering.RenderMode),
                    alphaCutoff = Mathf.Max(def.Color.CutoutThresholdValue, 0),

                    // Lighting
                    pbrMetallicRoughness = new glTFPbrMetallicRoughness
                    {
                        baseColorFactor  = def.Color.LitColor.ToFloat4(ColorSpace.sRGB, ColorSpace.Linear),
                        baseColorTexture = new glTFMaterialBaseColorTextureInfo
                        {
                            index = textureExporter.ExportAsSRgb(def.Color.LitMultiplyTexture),
                        },
                    },

                    normalTexture = new glTFMaterialNormalTextureInfo
                    {
                        index = textureExporter.ExportAsNormal(def.Lighting.Normal.NormalTexture),
                        scale = def.Lighting.Normal.NormalScaleValue,
                    },

                    // Emission
                    emissiveFactor  = def.Emission.EmissionColor.ToFloat3(ColorSpace.Linear, ColorSpace.Linear),
                    emissiveTexture = new glTFMaterialEmissiveTextureInfo
                    {
                        index = textureExporter.ExportAsSRgb(def.Emission.EmissionMultiplyTexture),
                    },
                };

                const float centimeterToMeter = 0.01f;
                const float invertY           = -1f;

                // VRMC_materials_mtoon
                var mtoon = new UniGLTF.Extensions.VRMC_materials_mtoon.VRMC_materials_mtoon
                {
                    Version = "",

                    // Rendering
                    TransparentWithZWrite   = def.Rendering.RenderMode == RenderMode.TransparentWithZWrite,
                    RenderQueueOffsetNumber = ExportRenderQueueOffset(def.Rendering.RenderMode, def.Rendering.RenderQueueOffsetNumber),

                    // Lighting
                    ShadeColorFactor     = def.Color.ShadeColor.ToFloat3(ColorSpace.sRGB, ColorSpace.Linear),
                    ShadeMultiplyTexture = new TextureInfo
                    {
                        Index = textureExporter.ExportAsSRgb(def.Color.ShadeMultiplyTexture),
                    },
                    ShadingToonyFactor  = def.Lighting.LitAndShadeMixing.ShadingToonyValue,
                    ShadingShiftFactor  = def.Lighting.LitAndShadeMixing.ShadingShiftValue,
                    ShadingShiftTexture = null,

                    // Global Illumination
                    GiIntensityFactor = def.Lighting.LightingInfluence.GiIntensityValue,

                    // Rim Lighting
                    MatcapTexture = new TextureInfo
                    {
                        Index = textureExporter.ExportAsSRgb(def.MatCap.AdditiveTexture),
                    },
                    ParametricRimColorFactor        = def.Rim.RimColor.ToFloat3(ColorSpace.Linear, ColorSpace.Linear),
                    ParametricRimFresnelPowerFactor = def.Rim.RimFresnelPowerValue,
                    ParametricRimLiftFactor         = def.Rim.RimLiftValue,
                    RimMultiplyTexture = new TextureInfo
                    {
                        Index = textureExporter.ExportAsSRgb(def.Rim.RimMultiplyTexture),
                    },
                    RimLightingMixFactor = def.Rim.RimLightingMixValue,

                    // Outline
                    OutlineWidthMode            = ExportOutlineWidthMode(def.Outline.OutlineWidthMode),
                    OutlineWidthFactor          = def.Outline.OutlineWidthValue * centimeterToMeter,
                    OutlineWidthMultiplyTexture = new TextureInfo
                    {
                        Index = textureExporter.ExportAsLinear(def.Outline.OutlineWidthMultiplyTexture),
                    },
                    OutlineColorFactor       = def.Outline.OutlineColor.ToFloat3(ColorSpace.sRGB, ColorSpace.Linear),
                    OutlineLightingMixFactor = ExportOutlineLightingMixFactor(def.Outline.OutlineColorMode, def.Outline.OutlineLightingMixValue),

                    // UV Anim
                    UvAnimationMaskTexture = new TextureInfo
                    {
                        Index = textureExporter.ExportAsLinear(def.TextureOption.UvAnimationMaskTexture),
                    },
                    UvAnimationScrollXSpeedFactor  = def.TextureOption.UvAnimationScrollXSpeedValue,
                    UvAnimationScrollYSpeedFactor  = def.TextureOption.UvAnimationScrollYSpeedValue * invertY,
                    UvAnimationRotationSpeedFactor = def.TextureOption.UvAnimationRotationSpeedValue,
                };

                // Texture Transforms
                var scale  = def.TextureOption.MainTextureLeftBottomOriginScale;
                var offset = def.TextureOption.MainTextureLeftBottomOriginOffset;
                ExportTextureTransform(dst.pbrMetallicRoughness.baseColorTexture, scale, offset);
                ExportTextureTransform(dst.emissiveTexture, scale, offset);
                ExportTextureTransform(dst.normalTexture, scale, offset);
                ExportTextureTransform(mtoon.ShadeMultiplyTexture, scale, offset);
                ExportTextureTransform(mtoon.MatcapTexture, scale, offset);
                ExportTextureTransform(mtoon.RimMultiplyTexture, scale, offset);
                ExportTextureTransform(mtoon.OutlineWidthMultiplyTexture, scale, offset);
                ExportTextureTransform(mtoon.UvAnimationMaskTexture, scale, offset);

                UniGLTF.Extensions.VRMC_materials_mtoon.GltfSerializer.SerializeTo(ref dst.extensions, mtoon);

                return(true);
            }
            catch (Exception e)
            {
                dst = null;
                return(false);
            }
        }
Ejemplo n.º 29
0
        public override Material CreateMaterial(int i, glTFMaterial src)
        {
            if (i == 0 && m_materials.Count == 0)
            {
                // dummy
                return(new Material(Shader.Find("Standard")));
            }

            var item       = m_materials[i];
            var shaderName = item.shader;
            var shader     = Shader.Find(shaderName);

            if (shader == null)
            {
                //
                // no shader
                //
                if (VRM_SHADER_NAMES.Contains(shaderName))
                {
                    Debug.LogErrorFormat("shader {0} not found. set Assets/VRM/Shaders/VRMShaders to Edit - project setting - Graphics - preloaded shaders", shaderName);
                }
                else
                {
                    Debug.LogWarningFormat("unknown shader {0}.", shaderName);
                }
                return(base.CreateMaterial(i, src));
            }

            //
            // restore VRM material
            //
            var material = new Material(shader);

            material.name        = item.name;
            material.renderQueue = item.renderQueue;

            foreach (var kv in item.floatProperties)
            {
                material.SetFloat(kv.Key, kv.Value);
            }
            foreach (var kv in item.vectorProperties)
            {
                if (item.textureProperties.ContainsKey(kv.Key))
                {
                    // texture offset & scale
                    material.SetTextureOffset(kv.Key, new Vector2(kv.Value[0], kv.Value[1]));
                    material.SetTextureScale(kv.Key, new Vector2(kv.Value[2], kv.Value[3]));
                }
                else
                {
                    // vector4
                    var v = new Vector4(kv.Value[0], kv.Value[1], kv.Value[2], kv.Value[3]);
                    material.SetVector(kv.Key, v);
                }
            }
            foreach (var kv in item.textureProperties)
            {
                var texture = Context.GetTexture(kv.Value);
                if (texture != null)
                {
                    var converted = texture.ConvertTexture(kv.Key);
                    if (converted != null)
                    {
                        material.SetTexture(kv.Key, converted);
                    }
                    else
                    {
                        material.SetTexture(kv.Key, texture.Texture);
                    }
                }
            }
            foreach (var kv in item.keywordMap)
            {
                if (kv.Value)
                {
                    material.EnableKeyword(kv.Key);
                }
                else
                {
                    material.DisableKeyword(kv.Key);
                }
            }
            foreach (var kv in item.tagMap)
            {
                material.SetOverrideTag(kv.Key, kv.Value);
            }

            if (shaderName == MToon.Utils.ShaderName)
            {
                // TODO: Material拡張にMToonの項目が追加されたら旧バージョンのshaderPropから変換をかける
                // インポート時にUniVRMに含まれるMToonのバージョンに上書きする
                material.SetFloat(MToon.Utils.PropVersion, MToon.Utils.VersionNumber);
            }

            return(material);
        }
        public override Material CreateMaterial(glTF gltf, int i, glTFMaterial src)
        {
            if (i == 0 && m_materials.Count == 0)
            {
                return(base.CreateMaterial(gltf, i, src));
            }

            var item       = m_materials[i];
            var shaderName = item.shader;
            var shader     = Shader.Find(shaderName);

            if (shader == null)
            {
                //
                // no shader
                //
                if (VRM_SHADER_NAMES.Contains(shaderName))
                {
                    Debug.LogErrorFormat(
                        "shader {0} not found. set Assets/VRM/Shaders/VRMShaders to Edit - project setting - Graphics - preloaded shaders",
                        shaderName);
                }
                else
                {
                    Debug.LogFormat("unknown shader {0}.", shaderName);
                }
                return(base.CreateMaterial(gltf, i, src));
            }

            //
            // restore VRM material
            //
            var material = new Material(shader);

            material.name        = item.name;
            material.renderQueue = item.renderQueue;

            foreach (var kv in item.floatProperties)
            {
                material.SetFloat(kv.Key, kv.Value);
            }
            foreach (var kv in item.vectorProperties)
            {
                if (item.textureProperties.ContainsKey(kv.Key))
                {
                    // texture offset & scale
                    material.SetTextureOffset(kv.Key, new Vector2(kv.Value[0], kv.Value[1]));
                    material.SetTextureScale(kv.Key, new Vector2(kv.Value[2], kv.Value[3]));
                }
                else
                {
                    // vector4
                    var v = new Vector4(kv.Value[0], kv.Value[1], kv.Value[2], kv.Value[3]);
                    material.SetVector(kv.Key, v);
                }
            }

            foreach (var kv in item.textureProperties)
            {
                var texture = Context.GetTexture(kv.Value);
                if (texture != null)
                {
                    var converted = texture.ConvertTexture(kv.Key);
                    if (converted != null)
                    {
                        material.SetTexture(kv.Key, converted);
                    }
                    else
                    {
                        material.SetTexture(kv.Key, texture.Texture);
                    }
                }
            }

            foreach (var kv in item.keywordMap)
            {
                if (kv.Value)
                {
                    material.EnableKeyword(kv.Key);
                }
                else
                {
                    material.DisableKeyword(kv.Key);
                }
            }
            foreach (var kv in item.tagMap)
            {
                material.SetOverrideTag(kv.Key, kv.Value);
            }

            return(material);
        }