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);
        }
Esempio n. 2
0
        //from ImporterContext.cs(UniGLTF)
        static void RestoreOlderVersionValues(string Json, glTF GLTF)
        {
            var parsed = UniJSON.JsonParser.Parse(Json);

            for (int i = 0; i < GLTF.images.Count; ++i)
            {
                if (string.IsNullOrEmpty(GLTF.images[i].name))
                {
                    try
                    {
                        var extraName = parsed["images"][i]["extra"]["name"].Value.GetString();
                        if (!string.IsNullOrEmpty(extraName))
                        {
                            //Debug.LogFormat("restore texturename: {0}", extraName);
                            GLTF.images[i].name = extraName;
                        }
                    }
                    catch (Exception)
                    {
                        // do nothing
                    }
                }
            }
            for (int i = 0; i < GLTF.meshes.Count; ++i)
            {
                var mesh = GLTF.meshes[i];
                try
                {
                    for (int j = 0; j < mesh.primitives.Count; ++j)
                    {
                        var primitive = mesh.primitives[j];
                        for (int k = 0; k < primitive.targets.Count; ++k)
                        {
                            var extraName = parsed["meshes"][i]["primitives"][j]["targets"][k]["extra"]["name"].Value.GetString();
                            //Debug.LogFormat("restore morphName: {0}", extraName);
                            primitive.extras.targetNames.Add(extraName);
                        }
                    }
                }
                catch (Exception)
                {
                    // do nothing
                }
            }
#if false
            for (int i = 0; i < GLTF.nodes.Count; ++i)
            {
                var node = GLTF.nodes[i];
                try
                {
                    var extra = parsed["nodes"][i]["extra"]["skinRootBone"].AsInt;
                    //Debug.LogFormat("restore extra: {0}", extra);
                    //node.extras.skinRootBone = extra;
                }
                catch (Exception)
                {
                    // do nothing
                }
            }
#endif
        }
Esempio n. 3
0
 /// <summary>
 /// Create VGO_PS_Renderer from ParticleSystemRenderer.
 /// </summary>
 /// <param name="particleSystemRenderer"></param>
 /// <param name="gltf"></param>
 /// <returns></returns>
 protected virtual VGO_PS_Renderer CreateVgoPsRenderer(ParticleSystemRenderer particleSystemRenderer, glTF gltf)
 {
     return(new VGO_PS_Renderer()
     {
         enabled = particleSystemRenderer.enabled,
         renderMode = particleSystemRenderer.renderMode,
         cameraVelocityScale = particleSystemRenderer.cameraVelocityScale,
         velocityScale = particleSystemRenderer.velocityScale,
         lengthScale = particleSystemRenderer.lengthScale,
         normalDirection = particleSystemRenderer.normalDirection,
         sharedMaterial = GetMaterialIndex(particleSystemRenderer.sharedMaterial, gltf),
         trailMaterialIndex = GetMaterialIndex(particleSystemRenderer.trailMaterial, gltf),
         sortMode = particleSystemRenderer.sortMode,
         sortingFudge = particleSystemRenderer.sortingFudge,
         minParticleSize = particleSystemRenderer.minParticleSize,
         maxParticleSize = particleSystemRenderer.maxParticleSize,
         alignment = particleSystemRenderer.alignment,
         flip = particleSystemRenderer.flip.ReverseZ().ToArray(),
         allowRoll = particleSystemRenderer.allowRoll,
         pivot = particleSystemRenderer.pivot.ReverseZ().ToArray(),
         maskInteraction = particleSystemRenderer.maskInteraction,
         enableGPUInstancing = particleSystemRenderer.enableGPUInstancing,
         shadowCastingMode = particleSystemRenderer.shadowCastingMode,
         receiveShadows = particleSystemRenderer.receiveShadows,
         shadowBias = particleSystemRenderer.shadowBias,
         motionVectorGenerationMode = particleSystemRenderer.motionVectorGenerationMode,
         forceRenderingOff = particleSystemRenderer.forceRenderingOff,
         rendererPriority = particleSystemRenderer.rendererPriority,
         renderingLayerMask = particleSystemRenderer.renderingLayerMask,
         sortingLayerID = particleSystemRenderer.sortingLayerID,
         sortingOrder = particleSystemRenderer.sortingOrder,
         lightProbeUsage = particleSystemRenderer.lightProbeUsage,
         reflectionProbeUsage = particleSystemRenderer.reflectionProbeUsage,
         probeAnchor = VgoTransformConverter.CreateFrom(particleSystemRenderer.probeAnchor),
     });
 }
Esempio n. 4
0
        private static int AddEffekseerEffect(glTF gltf, Effekseer.EffekseerEmitter emitter)
        {
            if (gltf.extensions.Effekseer.effects.FirstOrDefault(x => x.effectName == emitter.effectAsset.name) == null)
            {
                var viewIndex = gltf.ExtendBufferAndGetViewIndex(0, emitter.effectAsset.efkBytes);

                // body
                var effect = new glTF_Effekseer_effect()
                {
                    nodeIndex  = 0,
                    nodeName   = "Root",
                    effectName = emitter.effectAsset.name,
                    scale      = emitter.effectAsset.Scale,
                    body       = new glTF_Effekseer_body()
                    {
                        bufferView = viewIndex
                    },
                    images = new List <glTF_Effekseer_image>(),
                    models = new List <glTF_Effekseer_model>()
                };

                // texture
                foreach (var texture in emitter.effectAsset.textureResources)
                {
                    if (texture == null || texture.texture == null)
                    {
                        Debug.LogWarning("Effekseer Texture Asset is null. " + texture?.path);
                        continue;
                    }
#if UNITY_EDITOR
                    var texturePath     = UnityEditor.AssetDatabase.GetAssetPath(texture.texture);
                    var textureImporter = (UnityEditor.TextureImporter)UnityEditor.TextureImporter.GetAtPath(texturePath);
                    if (textureImporter != null)
                    {
                        textureImporter.isReadable         = true;
                        textureImporter.textureCompression = UnityEditor.TextureImporterCompression.Uncompressed;
                        textureImporter.SaveAndReimport();
                    }
#endif

                    var image = new glTF_Effekseer_image()
                    {
                        bufferView = gltf.ExtendBufferAndGetViewIndex(0, texture.texture.EncodeToPNG()),
                        mimeType   = "image/png"
                    };
                    effect.images.Add(image);
                }

                // model
                foreach (var model in emitter.effectAsset.modelResources)
                {
                    if (model == null || model.asset == null)
                    {
                        Debug.LogWarning("Effekseer Model Asset is null. " + model?.path);
                        continue;
                    }

                    var efkModel = new glTF_Effekseer_model()
                    {
                        bufferView = gltf.ExtendBufferAndGetViewIndex(0, model.asset.bytes)
                    };
                    effect.models.Add(efkModel);
                }

                gltf.extensions.Effekseer.effects.Add(effect);
                int index = gltf.extensions.Effekseer.effects.Count - 1;
                return(index);
            }
            else
            {
                return(gltf.extensions.Effekseer.effects.FindIndex(x => x.effectName == emitter.effectAsset.name));
            }
        }
Esempio n. 5
0
 public VRMExporter(glTF gltf) : base(gltf, new GltfExportSettings())
 {
     gltf.extensionsUsed.Add(glTF_VRM_extensions.ExtensionName);
 }
Esempio n. 6
0
        /// <summary>
        /// Create VGO_ParticleSystem.
        /// </summary>
        /// <param name="particleSystem"></param>
        /// <param name="particleSystemRenderer"></param>
        /// <param name="gltf"></param>
        /// <returns></returns>
        public virtual VGO_ParticleSystem Create(ParticleSystem particleSystem, ParticleSystemRenderer particleSystemRenderer, glTF gltf)
        {
            if (particleSystem == null)
            {
                return(null);
            }

            var vgoParticleSystem = new VGO_ParticleSystem()
            {
                main                      = CreateVgoModule(particleSystem.main),
                emission                  = CreateVgoModule(particleSystem.emission),
                shape                     = CreateVgoModule(particleSystem.shape, gltf),
                velocityOverLifetime      = CreateVgoModule(particleSystem.velocityOverLifetime),
                limitVelocityOverLifetime = CreateVgoModule(particleSystem.limitVelocityOverLifetime),
                inheritVelocity           = CreateVgoModule(particleSystem.inheritVelocity),
                forceOverLifetime         = CreateVgoModule(particleSystem.forceOverLifetime),
                colorOverLifetime         = CreateVgoModule(particleSystem.colorOverLifetime),
                colorBySpeed              = CreateVgoModule(particleSystem.colorBySpeed),
                sizeOverLifetime          = CreateVgoModule(particleSystem.sizeOverLifetime),
                sizeBySpeed               = CreateVgoModule(particleSystem.sizeBySpeed),
                rotationOverLifetime      = CreateVgoModule(particleSystem.rotationOverLifetime),
                rotationBySpeed           = CreateVgoModule(particleSystem.rotationBySpeed),
                externalForces            = CreateVgoModule(particleSystem.externalForces),
                noise                     = CreateVgoModule(particleSystem.noise),
                //Collision = CreateVgoModule(particleSystem.collision),
                //Trigger = CreateVgoModule(particleSystem.trigger),
                //SubEmitters = CreateVgoModule(particleSystem.subEmitters),
                //TextureSheetAnimation = CreateVgoModule(particleSystem.textureSheetAnimation),
                lights = CreateVgoModule(particleSystem.lights),
                trails = CreateVgoModule(particleSystem.trails),
                //CustomData = CreateVgoModule(particleSystem.customData),
                renderer = CreateVgoPsRenderer(particleSystemRenderer, gltf),
            };

            return(vgoParticleSystem);
        }
Esempio n. 7
0
 public static void Migrate(glTF gltf, JsonNode vrm0)
 {
     // Create MToonDefinition(0.x) from JSON(0.x)
     var sourceMaterials = new (Vrm0XMToonValue, glTFMaterial)[gltf.materials.Count];
Esempio n. 8
0
 public VRMExporter(glTF gltf) : base(gltf)
 {
 }
Esempio n. 9
0
        private void ExportSceneLighting(VCIExporter exporter, glTF gltf)
        {
            var lightmapTextureExporter = new LightmapTextureExporter(TextureExporter, gltf);

            var existsLightmappedMesh = false;

            for (var i = 0; i < exporter.Nodes.Count; i++)
            {
                var node     = exporter.Nodes[i];
                var gltfNode = gltf.nodes[i];

                var renderer = node.GetComponent <MeshRenderer>();
                if (renderer != null)
                {
                    var useLightmapExtension = false;
#if UNITY_EDITOR
                    var contributeGi = UnityEditor.GameObjectUtility.GetStaticEditorFlags(node.gameObject)
                                       .HasFlag(UnityEditor.StaticEditorFlags.ContributeGI);
                    var receiveLightmap         = renderer.receiveGI == ReceiveGI.Lightmaps;
                    var isLightmapExistsInScene =
                        LightmapSettings.lightmaps != null && LightmapSettings.lightmaps.Length > 0;
                    useLightmapExtension = contributeGi && receiveLightmap && isLightmapExistsInScene;
#endif

                    if (useLightmapExtension)
                    {
                        var originalRenderer = _originalNodes[i].GetComponent <MeshRenderer>();

                        var lightmapUnityIndex = originalRenderer.lightmapIndex;
                        if (lightmapUnityIndex < 0 || lightmapUnityIndex >= LightmapSettings.lightmaps.Length)
                        {
                            continue;
                        }

                        var lightmapGltfIndex = lightmapTextureExporter.GetOrAddColorTexture(lightmapUnityIndex);

                        if (lightmapGltfIndex >= 0)
                        {
                            var so     = originalRenderer.lightmapScaleOffset;
                            var scale  = new Vector2(so.x, so.y);
                            var offset = new Vector2(so.z, so.w);
                            offset.y = (offset.y + scale.y - 1) * -1.0f;

                            var VCAST_vci_lightmap = new glTF_VCAST_vci_lightmap
                            {
                                lightmap = new glTF_VCAST_vci_Lightmap
                                {
                                    texture = new glTFLightmapTextureInfo {
                                        index = lightmapGltfIndex
                                    },
                                    offset = new[] { offset.x, offset.y },
                                    scale  = new[] { scale.x, scale.y },
                                },
                            };

                            var f = new UniJSON.JsonFormatter();
                            glTF_VCAST_vci_lightmap_Serializer.Serialize(f, VCAST_vci_lightmap);
                            glTFExtensionExport.GetOrCreate(ref gltfNode.extensions).Add(glTF_VCAST_vci_lightmap.ExtensionName, f.GetStore().Bytes);

                            existsLightmappedMesh = true;
                        }
                    }
                }
            }

            var enableLocationLightingExtension = existsLightmappedMesh;
            if (enableLocationLightingExtension)
            {
                var cubemapExporter    = new CubemapTextureExporter(TextureExporter, glTF);
                var skyboxExporter     = new SkyboxExporter(cubemapExporter);
                var lightProbeExporter = new LightProbeExporter();

                var VCAST_vci_location_lighting = new glTF_VCAST_vci_location_lighting
                {
                    locationLighting = new glTF_VCAST_vci_LocationLighting
                    {
                        lightmapCompressionMode =
                            glTF_VCAST_vci_LocationLighting.ConvertLightmapCompressionMode(lightmapTextureExporter
                                                                                           .CompressionType),
                        lightmapDirectionalMode =
                            glTF_VCAST_vci_LocationLighting.ConvertLightmapDirectionalMode(lightmapTextureExporter
                                                                                           .DirectionalType),
                        lightmapTextures = lightmapTextureExporter.RegisteredColorTextureIndexArray
                                           .Select(x => new glTFLightmapTextureInfo {
                            index = x
                        })
                                           .ToArray(),
                        skyboxCubemap = skyboxExporter.Export(1024),
                        lightProbes   = lightProbeExporter.Export(),
                    },
                };

                var f = new UniJSON.JsonFormatter();
                glTF_VCAST_vci_location_lighting_Serializer.Serialize(f, VCAST_vci_location_lighting);
                glTFExtensionExport.GetOrCreate(ref gltf.extensions).Add(glTF_VCAST_vci_location_lighting.ExtensionName, f.GetStore().Bytes);
            }

            for (var i = 0; i < exporter.Nodes.Count; i++)
            {
                var node     = exporter.Nodes[i];
                var gltfNode = gltf.nodes[i];

                var reflectionProbe = _originalNodes[i].GetComponent <ReflectionProbe>();
                if (reflectionProbe == null)
                {
                    continue;
                }

                var exportReflectionProbeExtension = false;
                var isModeActive    = reflectionProbe.mode == ReflectionProbeMode.Baked;
                var texture         = reflectionProbe.bakedTexture;
                var isTextureExists = texture != null && texture.dimension == TextureDimension.Cube;

                exportReflectionProbeExtension = !Application.isPlaying && isModeActive && isTextureExists;
                if (!exportReflectionProbeExtension)
                {
                    continue;
                }

                var reflectionProbeCubemapExporter = new CubemapTextureExporter(TextureExporter, glTF);

                var offset = reflectionProbe.center;
                var size   = reflectionProbe.size;

                var VCAST_vci_reflectionProbe = new glTF_VCAST_vci_reflectionProbe
                {
                    reflectionProbe = new glTF_VCAST_vci_ReflectionProbe
                    {
                        boxOffset        = new[] { -offset.x, offset.y, offset.z }, // invert X-axis
                        boxSize          = new[] { size.x, size.y, size.z },
                        intensity        = reflectionProbe.intensity,
                        useBoxProjection = reflectionProbe.boxProjection,
                        cubemap          = reflectionProbeCubemapExporter.Export(texture, reflectionProbe.resolution,
                                                                                 includeMipmaps: true),
                    },
                };

                var f = new UniJSON.JsonFormatter();
                glTF_VCAST_vci_reflectionProbe_Serializer.Serialize(f, VCAST_vci_reflectionProbe);
                glTFExtensionExport.GetOrCreate(ref gltfNode.extensions).Add(glTF_VCAST_vci_reflectionProbe.ExtensionName, f.GetStore().Bytes);
            }
        }
Esempio n. 10
0
 public VRMExporter(glTF gltf) : base(gltf)
 {
     gltf.extensionsUsed.Add(glTF_VRM_extensions.ExtensionName);
     gltf.extensions.VRM = new glTF_VRM_extensions();
 }
Esempio n. 11
0
        public static void Migrate(glTF gltf, JsonNode json)
        {
            const float centimeterToMeter = 0.01f;

            // Create MToonDefinition(0.x) from JSON(0.x)
            var sourceMaterials = new (MToonValue, glTFMaterial)[gltf.materials.Count];
Esempio n. 12
0
        static byte[] MigrateVrm(glTF gltf, ArraySegment <byte> bin, JsonNode vrm0)
        {
            var meshToNode = CreateMeshToNode(gltf);

            {
                // vrm
                var vrm1 = new UniGLTF.Extensions.VRMC_vrm.VRMC_vrm();

                // meta (required)
                vrm1.Meta = MigrationVrmMeta.Migrate(gltf, vrm0["meta"]);
                // humanoid (required)
                vrm1.Humanoid = MigrationVrmHumanoid.Migrate(vrm0["humanoid"]);

                // blendshape (optional)
                if (vrm0.TryGet("blendShapeMaster", out JsonNode vrm0BlendShape))
                {
                    vrm1.Expressions = new UniGLTF.Extensions.VRMC_vrm.Expressions
                    {
                        Preset = new UniGLTF.Extensions.VRMC_vrm.Preset(),
                        Custom = new Dictionary <string, UniGLTF.Extensions.VRMC_vrm.Expression>(),
                    };
                    foreach (var(preset, customName, expression) in MigrationVrmExpression.Migrate(gltf, vrm0BlendShape, meshToNode))
                    {
                        switch (preset)
                        {
                        case ExpressionPreset.happy: SetIfNull(ref vrm1.Expressions.Preset.Happy, expression); break;

                        case ExpressionPreset.angry: SetIfNull(ref vrm1.Expressions.Preset.Angry, expression); break;

                        case ExpressionPreset.sad: SetIfNull(ref vrm1.Expressions.Preset.Sad, expression); break;

                        case ExpressionPreset.relaxed: SetIfNull(ref vrm1.Expressions.Preset.Relaxed, expression); break;

                        case ExpressionPreset.surprised: SetIfNull(ref vrm1.Expressions.Preset.Surprised, expression); break;

                        case ExpressionPreset.aa: SetIfNull(ref vrm1.Expressions.Preset.Aa, expression); break;

                        case ExpressionPreset.ih: SetIfNull(ref vrm1.Expressions.Preset.Ih, expression); break;

                        case ExpressionPreset.ou: SetIfNull(ref vrm1.Expressions.Preset.Ou, expression); break;

                        case ExpressionPreset.ee: SetIfNull(ref vrm1.Expressions.Preset.Ee, expression); break;

                        case ExpressionPreset.oh: SetIfNull(ref vrm1.Expressions.Preset.Oh, expression); break;

                        case ExpressionPreset.blink: SetIfNull(ref vrm1.Expressions.Preset.Blink, expression); break;

                        case ExpressionPreset.blinkLeft: SetIfNull(ref vrm1.Expressions.Preset.BlinkLeft, expression); break;

                        case ExpressionPreset.blinkRight: SetIfNull(ref vrm1.Expressions.Preset.BlinkRight, expression); break;

                        case ExpressionPreset.lookUp: SetIfNull(ref vrm1.Expressions.Preset.LookUp, expression); break;

                        case ExpressionPreset.lookDown: SetIfNull(ref vrm1.Expressions.Preset.LookDown, expression); break;

                        case ExpressionPreset.lookLeft: SetIfNull(ref vrm1.Expressions.Preset.LookLeft, expression); break;

                        case ExpressionPreset.lookRight: SetIfNull(ref vrm1.Expressions.Preset.LookRight, expression); break;

                        case ExpressionPreset.neutral: SetIfNull(ref vrm1.Expressions.Preset.Neutral, expression); break;

                        case ExpressionPreset.custom:
                            if (vrm1.Expressions.Custom.ContainsKey(customName))
                            {
                                // 同名が既存。先着を有効とする
                            }
                            else
                            {
                                vrm1.Expressions.Custom[customName] = expression;
                            }
                            break;

                        default: throw new NotImplementedException();
                        }
                    }
                }

                // lookat & firstperson (optional)
                if (vrm0.TryGet("firstPerson", out JsonNode vrm0FirstPerson))
                {
                    (vrm1.LookAt, vrm1.FirstPerson) = MigrationVrmLookAtAndFirstPerson.Migrate(gltf, vrm0FirstPerson);
                }

                UniGLTF.Extensions.VRMC_vrm.GltfSerializer.SerializeTo(ref gltf.extensions, vrm1);
            }

            // springBone & collider (optional)
            if (vrm0.TryGet("secondaryAnimation", out JsonNode vrm0SpringBone))
            {
                var springBone = MigrationVrmSpringBone.Migrate(gltf, vrm0SpringBone);
                UniGLTF.Extensions.VRMC_springBone.GltfSerializer.SerializeTo(ref gltf.extensions, springBone);
            }

            // Material
            {
                MigrationMaterials.Migrate(gltf, vrm0);
            }

            // Serialize whole glTF
            ArraySegment <byte> vrm1Json = default;

            {
                var f = new JsonFormatter();
                GltfSerializer.Serialize(f, gltf);
                vrm1Json = f.GetStoreBytes();
            }

            return(Glb.Create(vrm1Json, bin).ToBytes());
        }
Esempio n. 13
0
    public void Export()
    {
        var title     = Title.text;
        var version   = Version.text;
        var author    = Author.text;
        var contact   = Contact.text;
        var reference = Reference.text;
        var license   = License.value;

        if (title == "" || author == "")
        {
            ExportVCI_Text.text = "必須の項目を入力してください";
            return;
        }
        else
        {
            ExportVCI_Text.text = "Export VCI";
        }

        // VCI基本設定
        VRM.name = title;
        var vci = VRM.AddComponent <VCIObject>();

        vci.Meta.title                = title;
        vci.Meta.version              = version;
        vci.Meta.author               = author;
        vci.Meta.contactInformation   = contact;
        vci.Meta.reference            = reference;
        vci.Meta.modelDataLicenseType = (glTF_VCAST_vci_meta.LicenseType)license;

        // luaスクリプト
        var script = new VCIObject.Script
        {
            mimeType     = ScriptMimeType.X_APPLICATION_LUA,
            targetEngine = TargetEngine.MoonSharp,
            source       = lua
        };

        vci.Scripts.Add(script);

        // 不要部位の削除
        DestroyImmediate(VRM.transform.Find("Face").gameObject);
        DestroyImmediate(VRM.transform.Find("Hairs").gameObject);
        DestroyImmediate(VRM.transform.Find("secondary").gameObject);

        // 不要メッシュの透過
        var renderer  = VRM.transform.Find("Body").gameObject.GetComponent <Renderer>();
        var materials = renderer.materials;

        for (int i = 0; i < renderer.materials.Length; i++)
        {
            if (!materials[i].name.Contains("CLOTH"))
            {
                materials[i] = Mat;
            }
        }
        renderer.materials = materials;

        // バージョン差吸収
        string hips = "Root/J_Bip_C_Hips/";

        if (VRM.transform.Find(hips) == null)
        {
            hips = "Root/Global/Position/J_Bip_C_Hips/";
        }

        // 足
        SetAtt(hips + "J_Bip_L_UpperLeg/J_Bip_L_LowerLeg/J_Bip_L_Foot", HumanBodyBones.LeftFoot);
        SetAtt(hips + "J_Bip_R_UpperLeg/J_Bip_R_LowerLeg/J_Bip_R_Foot", HumanBodyBones.RightFoot);
        SetAtt(hips + "J_Bip_L_UpperLeg/J_Bip_L_LowerLeg", HumanBodyBones.LeftLowerLeg);
        SetAtt(hips + "J_Bip_R_UpperLeg/J_Bip_R_LowerLeg", HumanBodyBones.RightLowerLeg);
        SetAtt(hips + "J_Bip_L_UpperLeg", HumanBodyBones.LeftUpperLeg);
        SetAtt(hips + "J_Bip_R_UpperLeg", HumanBodyBones.RightUpperLeg);

        // 腕
        string arm = hips + "J_Bip_C_Spine/J_Bip_C_Chest/J_Bip_C_UpperChest/";

        SetAtt(arm + "J_Bip_L_Shoulder/J_Bip_L_UpperArm/J_Bip_L_LowerArm/J_Bip_L_Hand", HumanBodyBones.LeftHand);
        SetAtt(arm + "J_Bip_R_Shoulder/J_Bip_R_UpperArm/J_Bip_R_LowerArm/J_Bip_R_Hand", HumanBodyBones.RightHand);
        SetAtt(arm + "J_Bip_L_Shoulder/J_Bip_L_UpperArm/J_Bip_L_LowerArm", HumanBodyBones.LeftLowerArm);
        SetAtt(arm + "J_Bip_R_Shoulder/J_Bip_R_UpperArm/J_Bip_R_LowerArm", HumanBodyBones.RightLowerArm);
        SetAtt(arm + "J_Bip_L_Shoulder/J_Bip_L_UpperArm", HumanBodyBones.LeftUpperArm);
        SetAtt(arm + "J_Bip_R_Shoulder/J_Bip_R_UpperArm", HumanBodyBones.RightUpperArm);

        // 体幹
        SetAtt(hips + "J_Bip_C_Spine/J_Bip_C_Chest", HumanBodyBones.Chest);
        SetAtt(hips + "J_Bip_C_Spine", HumanBodyBones.Spine);
        SetAtt(hips, HumanBodyBones.Hips);

        var gltf     = new glTF();
        var exporter = new VCIExporter(gltf);

        exporter.Prepare(VRM);
        exporter.Export();
        var bytes = gltf.ToGlbBytes();
        var path  = Application.dataPath + "/../" + title + ".vci";

        File.WriteAllBytes(path, bytes);

        Destroy(exporter.Copy);
        Destroy(VRM);
    }
Esempio n. 14
0
 public VRMExporter(glTF gltf) : base(gltf, Axises.Z)
 {
     gltf.extensionsUsed.Add(glTF_VRM_extensions.ExtensionName);
 }
Esempio n. 15
0
        public static void _Export(glTF gltf, VRMExporter exporter, GameObject go)
        {
            exporter.Prepare(go);
            exporter.Export();

            // avatar
            var animator = go.GetComponent <Animator>();

            if (animator != null)
            {
                var humanoid = go.GetComponent <VRMHumanoidDescription>();
                UniHumanoid.AvatarDescription description = null;
                var nodes = go.transform.Traverse().Skip(1).ToList();
                {
                    var isCreated = false;
                    if (humanoid != null)
                    {
                        description = humanoid.GetDescription(out isCreated);
                    }

                    if (description != null)
                    {
                        // use description
                        gltf.extensions.VRM.humanoid.Apply(description, nodes);
                    }
                    if (isCreated)
                    {
                        GameObject.DestroyImmediate(description);
                    }
                }

                {
                    // set humanoid bone mapping
                    var avatar = animator.avatar;
                    foreach (HumanBodyBones key in Enum.GetValues(typeof(HumanBodyBones)))
                    {
                        if (key == HumanBodyBones.LastBone)
                        {
                            break;
                        }

                        var transform = animator.GetBoneTransform(key);
                        if (transform != null)
                        {
                            gltf.extensions.VRM.humanoid.SetNodeIndex(key, nodes.IndexOf(transform));
                        }
                    }
                }
            }

            // morph
            var master = go.GetComponent <VRMBlendShapeProxy>();

            if (master != null)
            {
                var avatar = master.BlendShapeAvatar;
                if (avatar != null)
                {
                    var meshes = exporter.Meshes;
                    foreach (var x in avatar.Clips)
                    {
                        gltf.extensions.VRM.blendShapeMaster.Add(x, exporter.Copy.transform, meshes);
                    }
                }
            }

            // secondary
            VRMSpringUtility.ExportSecondary(exporter.Copy.transform, exporter.Nodes,
                                             x => gltf.extensions.VRM.secondaryAnimation.colliderGroups.Add(x),
                                             x => gltf.extensions.VRM.secondaryAnimation.boneGroups.Add(x)
                                             );

#pragma warning disable 0618
            // meta(obsolete)
            {
                var meta = exporter.Copy.GetComponent <VRMMetaInformation>();
                if (meta != null)
                {
                    gltf.extensions.VRM.meta.author             = meta.Author;
                    gltf.extensions.VRM.meta.contactInformation = meta.ContactInformation;
                    gltf.extensions.VRM.meta.title = meta.Title;
                    if (meta.Thumbnail != null)
                    {
                        gltf.extensions.VRM.meta.texture = TextureIO.ExportTexture(gltf, gltf.buffers.Count - 1, meta.Thumbnail, glTFTextureTypes.Unknown);
                    }
                    gltf.extensions.VRM.meta.licenseType     = meta.LicenseType;
                    gltf.extensions.VRM.meta.otherLicenseUrl = meta.OtherLicenseUrl;
                    gltf.extensions.VRM.meta.reference       = meta.Reference;
                }
            }
#pragma warning restore 0618

            // meta
            {
                var _meta = exporter.Copy.GetComponent <VRMMeta>();
                if (_meta != null && _meta.Meta != null)
                {
                    var meta = _meta.Meta;

                    // info
                    gltf.extensions.VRM.meta.version            = meta.Version;
                    gltf.extensions.VRM.meta.author             = meta.Author;
                    gltf.extensions.VRM.meta.contactInformation = meta.ContactInformation;
                    gltf.extensions.VRM.meta.reference          = meta.Reference;
                    gltf.extensions.VRM.meta.title = meta.Title;
                    if (meta.Thumbnail != null)
                    {
                        gltf.extensions.VRM.meta.texture = TextureIO.ExportTexture(gltf, gltf.buffers.Count - 1, meta.Thumbnail, glTFTextureTypes.Unknown);
                    }

                    // ussage pemission
                    gltf.extensions.VRM.meta.allowedUser        = meta.AllowedUser;
                    gltf.extensions.VRM.meta.violentUssage      = meta.ViolentUssage;
                    gltf.extensions.VRM.meta.sexualUssage       = meta.SexualUssage;
                    gltf.extensions.VRM.meta.commercialUssage   = meta.CommercialUssage;
                    gltf.extensions.VRM.meta.otherPermissionUrl = meta.OtherPermissionUrl;

                    // distribution license
                    gltf.extensions.VRM.meta.licenseType = meta.LicenseType;
                    if (meta.LicenseType == LicenseType.Other)
                    {
                        gltf.extensions.VRM.meta.otherLicenseUrl = meta.OtherLicenseUrl;
                    }
                }
            }

            // firstPerson
            var firstPerson = exporter.Copy.GetComponent <VRMFirstPerson>();
            if (firstPerson != null)
            {
                if (firstPerson.FirstPersonBone != null)
                {
                    gltf.extensions.VRM.firstPerson.firstPersonBone       = exporter.Nodes.IndexOf(firstPerson.FirstPersonBone);
                    gltf.extensions.VRM.firstPerson.firstPersonBoneOffset = firstPerson.FirstPersonOffset;
                    gltf.extensions.VRM.firstPerson.meshAnnotations       = firstPerson.Renderers.Select(x => new glTF_VRM_MeshAnnotation
                    {
                        mesh            = exporter.Meshes.IndexOf(x.SharedMesh),
                        firstPersonFlag = x.FirstPersonFlag.ToString(),
                    }).ToList();
                }

                // lookAt
                {
                    var lookAtHead = exporter.Copy.GetComponent <VRMLookAtHead>();
                    var lookAt     = exporter.Copy.GetComponent <VRMLookAt>();
                    if (lookAtHead != null)
                    {
                        var boneApplyer       = exporter.Copy.GetComponent <VRMLookAtBoneApplyer>();
                        var blendShapeApplyer = exporter.Copy.GetComponent <VRMLookAtBlendShapeApplyer>();
                        if (boneApplyer != null)
                        {
                            gltf.extensions.VRM.firstPerson.lookAtType = LookAtType.Bone;
                            gltf.extensions.VRM.firstPerson.lookAtHorizontalInner.Apply(boneApplyer.HorizontalInner);
                            gltf.extensions.VRM.firstPerson.lookAtHorizontalOuter.Apply(boneApplyer.HorizontalOuter);
                            gltf.extensions.VRM.firstPerson.lookAtVerticalDown.Apply(boneApplyer.VerticalDown);
                            gltf.extensions.VRM.firstPerson.lookAtVerticalUp.Apply(boneApplyer.VerticalUp);
                        }
                        else if (blendShapeApplyer != null)
                        {
                            gltf.extensions.VRM.firstPerson.lookAtType = LookAtType.BlendShape;
                            gltf.extensions.VRM.firstPerson.lookAtHorizontalOuter.Apply(blendShapeApplyer.Horizontal);
                            gltf.extensions.VRM.firstPerson.lookAtVerticalDown.Apply(blendShapeApplyer.VerticalDown);
                            gltf.extensions.VRM.firstPerson.lookAtVerticalUp.Apply(blendShapeApplyer.VerticalUp);
                        }
                    }
                    else if (lookAt != null)
                    {
                        gltf.extensions.VRM.firstPerson.lookAtHorizontalInner.Apply(lookAt.HorizontalInner);
                        gltf.extensions.VRM.firstPerson.lookAtHorizontalOuter.Apply(lookAt.HorizontalOuter);
                        gltf.extensions.VRM.firstPerson.lookAtVerticalDown.Apply(lookAt.VerticalDown);
                        gltf.extensions.VRM.firstPerson.lookAtVerticalUp.Apply(lookAt.VerticalUp);
                    }
                }
            }

            // materials
            foreach (var m in exporter.Materials)
            {
                gltf.extensions.VRM.materialProperties.Add(glTF_VRM_Material.CreateFromMaterial(m, exporter.TextureManager.Textures));
            }
        }
Esempio n. 16
0
        public static async Task <Material> CreateAsync(IAwaitCaller awaitCaller, glTF gltf, int m_index, glTF_VRM_Material vrmMaterial, GetTextureAsyncFunc getTexture)
        {
            var item       = vrmMaterial;
            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
                {
                    // #if VRM_DEVELOP
                    //                     Debug.LogWarningFormat("unknown shader {0}.", shaderName);
                    // #endif
                }
                return(await MaterialFactory.DefaultCreateMaterialAsync(awaitCaller, gltf, m_index, getTexture));
            }

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

            // use material.name, because material name may renamed in GltfParser.
            material.name        = gltf.materials[m_index].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 param   = GetTextureParam.Create(gltf, kv.Value, kv.Key, 1, 1);
                var texture = await getTexture(awaitCaller, gltf, param);

                if (texture != null)
                {
                    material.SetTexture(kv.Key, 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);
        }
Esempio n. 17
0
        public static AssetSource _Load(string path)
        {
            var sw = System.Diagnostics.Stopwatch.StartNew();

            IStorage folder    = new FileSystemStorage(System.IO.Path.GetDirectoryName(path));
            var      fileBytes = File.ReadAllBytes(path);

            var zip = LoadZip(fileBytes);

            if (zip != null)
            {
                var found = false;
                foreach (var x in zip.Entries)
                {
                    var ext = System.IO.Path.GetExtension(x.FileName).ToLower();
                    if (ext == ".gltf" ||
                        ext == ".glb" ||
                        ext == ".vrm")
                    {
                        folder    = zip;
                        fileBytes = zip.Extract(x);
                        if (fileBytes.Length == 0)
                        {
                            throw new Exception("empty bytes");
                        }
                        found = true;
                        break;
                    }
                }

                if (!found)
                {
                    throw new Exception("no model file in zip");
                }
            }

            var source = new AssetSource
            {
                Path = path
            };

            try
            {
                // try GLB

                var it = glbImporter.ParseGlbChanks(fileBytes).GetEnumerator();

                if (!it.MoveNext())
                {
                    throw new FormatException();
                }
                var jsonChunk = it.Current;
                if (jsonChunk.ChunkType != GlbChunkType.JSON)
                {
                    throw new FormatException();
                }

                if (!it.MoveNext())
                {
                    throw new FormatException();
                }
                var bytesChunk = it.Current;
                if (bytesChunk.ChunkType != GlbChunkType.BIN)
                {
                    throw new FormatException();
                }

                source.JSON = JsonParser.Parse(new Utf8String(jsonChunk.Bytes));
                source.IO   = new SimpleStorage(bytesChunk.Bytes);
            }
            catch (Exception)
            {
                // try GLTF
                source.JSON = JsonParser.Parse(new Utf8String(fileBytes));
                source.IO   = folder;
            }
            Logger.Info($"Parse: {sw.Elapsed.TotalSeconds} sec");
            sw = System.Diagnostics.Stopwatch.StartNew();

            glTF gltf = null;

            source.JSON.Deserialize(ref gltf);
            source.GLTF = gltf;

            Logger.Info($"Deserialize: {sw.Elapsed.TotalSeconds} sec");

            return(source);
        }