Exemplo n.º 1
0
 public static void SaveJson(VrmLib.Model model, string path)
 {
     using (var stream = new System.IO.StreamWriter(path))
     {
         stream.Write(GetJsonString(model));
     }
 }
Exemplo n.º 2
0
        /// <summary>
        /// GameObject to VrmLib.Model
        /// </summary>
        /// <param name="root"></param>
        /// <returns></returns>
        public VrmLib.Model Export(GameObject root)
        {
            Model = new VrmLib.Model(VrmLib.Coordinates.Unity);

            _Export(root);

            // humanoid
            {
                var humanoid = root.GetComponent <UniHumanoid.Humanoid>();
                if (humanoid is null)
                {
                    humanoid = root.AddComponent <UniHumanoid.Humanoid>();
                    humanoid.AssignBonesFromAnimator();
                }

                foreach (HumanBodyBones humanBoneType in Enum.GetValues(typeof(HumanBodyBones)))
                {
                    var transform = humanoid.GetBoneTransform(humanBoneType);
                    if (transform != null && Nodes.TryGetValue(transform.gameObject, out VrmLib.Node node))
                    {
                        node.HumanoidBone = (VrmLib.HumanoidBones)Enum.Parse(typeof(VrmLib.HumanoidBones), humanBoneType.ToString(), true);
                    }
                }
            }

            return(Model);
        }
Exemplo n.º 3
0
 public static void SaveVrm(VrmLib.Model model, string path)
 {
     using (var stream = new System.IO.StreamWriter(path))
     {
         stream.Write(model.ToGlb());
     }
 }
Exemplo n.º 4
0
        private VrmLib.Model CreateVrmModel(string path)
        {
            var bytes = File.ReadAllBytes(path);

            if (!VrmLib.Glb.TryParse(bytes, out VrmLib.Glb glb, out Exception ex))
            {
                throw ex;
            }

            // version check
            VrmLib.Model       model = null;
            VrmLib.IVrmStorage storage;
            if (VRMVersionCheck.IsVrm10(glb.Json.Bytes.ToArray()))
            {
                storage = new Vrm10.Vrm10Storage(glb.Json.Bytes, glb.Binary.Bytes);
                model   = VrmLib.ModelLoader.Load(storage, Path.GetFileName(path));
                model.ConvertCoordinate(VrmLib.Coordinates.Unity, ignoreVrm: true);
            }
            else
            {
                throw new NotImplementedException();
            }

            return(model);
        }
Exemplo n.º 5
0
        static byte[] GetGlb(VrmLib.Model model)
        {
            // export vrm-1.0
            var exporter = new Vrm10.Vrm10Exporter();
            var option   = new VrmLib.ExportArgs
            {
                vrm = false
            };
            var glbBytes10 = exporter.Export(model, option);
            var glb10      = VrmLib.Glb.Parse(glbBytes10);

            return(glb10.ToBytes());
        }
Exemplo n.º 6
0
    public static string GetJsonString(VrmLib.Model model)
    {
        // export vrm-1.0
        var exporter10 = new Vrm10.Vrm10Exporter();
        var option     = new VrmLib.ExportArgs
        {
            // vrm = false
        };
        var glbBytes10 = exporter10.Export(model, option);
        var glb10      = VrmLib.Glb.Parse(glbBytes10);

        return(System.Text.Encoding.UTF8.GetString(glb10.Json.Bytes.Array, glb10.Json.Bytes.Offset, glb10.Json.Bytes.Count));
    }
Exemplo n.º 7
0
        public static byte[] ToGlb(this VrmLib.Model model)
        {
            // export vrm-1.0
            var exporter10 = new Vrm10Exporter();
            var option     = new VrmLib.ExportArgs
            {
                // vrm = false
            };
            var glbBytes10 = exporter10.Export(model, option);
            var glb10      = UniGLTF.Glb.Parse(glbBytes10);

            return(glb10.ToBytes());
        }
Exemplo n.º 8
0
        public static byte[] ToGlb(this VrmLib.Model model)
        {
            // export vrm-1.0
            var exporter10 = new Vrm10Exporter(_ => false);
            var option     = new VrmLib.ExportArgs
            {
                // vrm = false
            };

            exporter10.Export(null, model, null, option);
            var glb10 = UniGLTF.Glb.Parse(exporter10.Storage.ToBytes());

            return(glb10.ToBytes());
        }
Exemplo n.º 9
0
        static public ModelAsset ToUnityAsset(VrmLib.Model model, string assetPath, IExternalUnityObject scriptedImporter)
        {
            var modelAsset = new ModelAsset();

            CreateTextureAsset(model, modelAsset, scriptedImporter);
            CreateMaterialAsset(model, modelAsset, scriptedImporter);
            CreateMeshAsset(model, modelAsset);

            // node
            RuntimeUnityBuilder.CreateNodes(model.Root, null, modelAsset.Map.Nodes);
            modelAsset.Root = modelAsset.Map.Nodes[model.Root];

            // renderer
            var map = modelAsset.Map;

            foreach (var(node, go) in map.Nodes)
            {
                if (node.MeshGroup is null)
                {
                    continue;
                }

                if (node.MeshGroup.Meshes.Count > 1)
                {
                    throw new NotImplementedException("invalid isolated vertexbuffer");
                }

                var renderer = RuntimeUnityBuilder.CreateRenderer(node, go, map);
                map.Renderers.Add(node, renderer);
                modelAsset.Renderers.Add(renderer);
            }

            if (model.Vrm != null)
            {
                // humanoid
                var humanoid = modelAsset.Root.AddComponent <MeshUtility.Humanoid>();
                humanoid.AssignBones(modelAsset.Map.Nodes.Select(x => (x.Key.HumanoidBone.GetValueOrDefault().ToUnity(), x.Value.transform)));
                modelAsset.HumanoidAvatar      = humanoid.CreateAvatar();
                modelAsset.HumanoidAvatar.name = "VRM";

                var animator = modelAsset.Root.AddComponent <Animator>();
                animator.avatar = modelAsset.HumanoidAvatar;
            }

            return(modelAsset);
        }
Exemplo n.º 10
0
        private Model CreateGlbModel(string path)
        {
            var bytes = File.ReadAllBytes(path);

            if (!VrmLib.Glb.TryParse(bytes, out VrmLib.Glb glb, out Exception ex))
            {
                throw ex;
            }

            VrmLib.Model       model = null;
            VrmLib.IVrmStorage storage;
            storage = new Vrm10Storage(glb.Json.Bytes, glb.Binary.Bytes);
            model   = VrmLib.ModelLoader.Load(storage, Path.GetFileNameWithoutExtension(path));
            model.ConvertCoordinate(VrmLib.Coordinates.Unity);

            return(model);
        }
Exemplo n.º 11
0
        static private void CreateMaterialAsset(VrmLib.Model model, ModelAsset modelAsset, IExternalUnityObject scriptedImporter)
        {
            var externalObjects = scriptedImporter.GetExternalUnityObjects <UnityEngine.Material>();

            foreach (var src in model.Materials)
            {
                if (externalObjects.ContainsKey(src.Name))
                {
                    modelAsset.Map.Materials.Add(src, externalObjects[src.Name]);
                    modelAsset.Materials.Add(externalObjects[src.Name]);
                }
                else
                {
                    // TODO: material has VertexColor
                    var material = RuntimeUnityMaterialBuilder.CreateMaterialAsset(src, hasVertexColor: false, modelAsset.Map.Textures);
                    material.name = src.Name;
                    modelAsset.Map.Materials.Add(src, material);
                    modelAsset.Materials.Add(material);
                }
            }
        }
Exemplo n.º 12
0
 static private void CreateMeshAsset(VrmLib.Model model, ModelAsset modelAsset)
 {
     for (int i = 0; i < model.MeshGroups.Count; ++i)
     {
         var src = model.MeshGroups[i];
         if (src.Meshes.Count == 1)
         {
             // submesh 方式
             var mesh = new UnityEngine.Mesh();
             mesh.name = src.Name;
             mesh.LoadMesh(src.Meshes[0], src.Skin);
             modelAsset.Map.Meshes.Add(src, mesh);
             modelAsset.Meshes.Add(mesh);
         }
         else
         {
             // 頂点バッファの連結が必用
             throw new NotImplementedException();
         }
     }
 }
Exemplo n.º 13
0
        /// <summary>
        /// GameObject to VrmLib.Model
        /// </summary>
        /// <param name="root"></param>
        /// <returns></returns>
        public VrmLib.Model Export(INativeArrayManager arrayManager, GameObject root)
        {
            Model = new VrmLib.Model(VrmLib.Coordinates.Unity);

            _Export(arrayManager, root);

            // humanoid
            {
                var humanoid = root.GetComponent <UniHumanoid.Humanoid>();
                if (humanoid is null)
                {
                    humanoid = root.AddComponent <UniHumanoid.Humanoid>();
                    humanoid.AssignBonesFromAnimator();
                }

                foreach (HumanBodyBones humanBoneType in Enum.GetValues(typeof(HumanBodyBones)))
                {
                    var transform = humanoid.GetBoneTransform(humanBoneType);
                    if (transform != null && Nodes.TryGetValue(transform.gameObject, out VrmLib.Node node))
                    {
                        switch (humanBoneType)
                        {
                        // https://github.com/vrm-c/vrm-specification/issues/380
                        case HumanBodyBones.LeftThumbProximal: node.HumanoidBone = VrmLib.HumanoidBones.leftThumbMetacarpal; break;

                        case HumanBodyBones.LeftThumbIntermediate: node.HumanoidBone = VrmLib.HumanoidBones.leftThumbProximal; break;

                        case HumanBodyBones.RightThumbProximal: node.HumanoidBone = VrmLib.HumanoidBones.rightThumbMetacarpal; break;

                        case HumanBodyBones.RightThumbIntermediate: node.HumanoidBone = VrmLib.HumanoidBones.rightThumbProximal; break;

                        default: node.HumanoidBone = (VrmLib.HumanoidBones)Enum.Parse(typeof(VrmLib.HumanoidBones), humanBoneType.ToString(), true); break;
                        }
                    }
                }
            }

            return(Model);
        }
Exemplo n.º 14
0
        /// <summary>
        /// metaObject が null のときは、root から取得する
        /// </summary>
        public VrmLib.Model ToModelFrom10(GameObject root, VRM10MetaObject metaObject = null)
        {
            Model = new VrmLib.Model(VrmLib.Coordinates.Unity);

            if (metaObject is null)
            {
                var vrmController = root.GetComponent <VRM10Controller>();
                if (vrmController is null || vrmController.Meta is null)
                {
                    throw new NullReferenceException("metaObject is null");
                }
                metaObject = vrmController.Meta;
            }

            ToGlbModel(root);

            // humanoid
            {
                var humanoid = root.GetComponent <MeshUtility.Humanoid>();
                if (humanoid is null)
                {
                    humanoid = root.AddComponent <MeshUtility.Humanoid>();
                    humanoid.AssignBonesFromAnimator();
                }

                foreach (HumanBodyBones humanBoneType in Enum.GetValues(typeof(HumanBodyBones)))
                {
                    var transform = humanoid.GetBoneTransform(humanBoneType);
                    if (transform != null && Nodes.TryGetValue(transform.gameObject, out VrmLib.Node node))
                    {
                        node.HumanoidBone = (VrmLib.HumanoidBones)Enum.Parse(typeof(VrmLib.HumanoidBones), humanBoneType.ToString(), true);
                    }
                }
            }

            return(Model);
        }
Exemplo n.º 15
0
        static private void CreateTextureAsset(VrmLib.Model model, ModelAsset modelAsset, IExternalUnityObject scriptedImporter)
        {
            var externalObjects = scriptedImporter.GetExternalUnityObjects <Texture2D>();

            // textures
            for (int i = 0; i < model.Textures.Count; ++i)
            {
                if (model.Textures[i] is VrmLib.ImageTexture imageTexture)
                {
                    if (string.IsNullOrEmpty(model.Textures[i].Name))
                    {
                        model.Textures[i].Name = string.Format("{0}_img{1}", model.Root.Name, i);
                    }
                    if (externalObjects.ContainsKey(model.Textures[i].Name))
                    {
                        modelAsset.Map.Textures.Add(imageTexture, externalObjects[model.Textures[i].Name]);
                        modelAsset.Textures.Add(externalObjects[model.Textures[i].Name]);
                    }
                    else
                    {
                        var name = !string.IsNullOrEmpty(imageTexture.Name)
                            ? imageTexture.Name
                            : string.Format("{0}_img{1}", model.Root.Name, i);

                        var texture = RuntimeUnityBuilder.CreateTexture(imageTexture);
                        texture.name = name;

                        modelAsset.Map.Textures.Add(imageTexture, texture);
                        modelAsset.Textures.Add(texture);
                    }
                }
                else
                {
                    Debug.LogWarning($"{i} not ImageTexture");
                }
            }
        }
Exemplo n.º 16
0
        VrmLib.Model _Export(GameObject root)
        {
            if (Model == null)
            {
                Model = new VrmLib.Model(VrmLib.Coordinates.Unity);
            }

            // node
            {
                Model.Root.Name = root.name;
                CreateNodes(root.transform, Model.Root, Nodes);
                Model.Nodes = Nodes
                              .Where(x => x.Value != Model.Root)
                              .Select(x => x.Value).ToList();
            }

            // material and textures
            var rendererComponents = root.GetComponentsInChildren <Renderer>();

            {
                foreach (var renderer in rendererComponents)
                {
                    var materials = renderer.sharedMaterials; // avoid copy
                    foreach (var material in materials)
                    {
                        if (Materials.Contains(material))
                        {
                            continue;
                        }

                        Model.Materials.Add(material);
                        Materials.Add(material);
                    }
                }
            }

            // mesh
            {
                foreach (var renderer in rendererComponents)
                {
                    if (renderer is SkinnedMeshRenderer skinnedMeshRenderer)
                    {
                        if (skinnedMeshRenderer.sharedMesh != null)
                        {
                            var mesh = CreateMesh(skinnedMeshRenderer.sharedMesh, skinnedMeshRenderer, Materials);
                            var skin = CreateSkin(skinnedMeshRenderer, Nodes, root);
                            if (skin != null)
                            {
                                // blendshape only で skinning が無いやつがある
                                mesh.Skin = skin;
                                Model.Skins.Add(mesh.Skin);
                            }
                            Model.MeshGroups.Add(mesh);
                            Nodes[renderer.gameObject].MeshGroup = mesh;
                            Meshes.Add(skinnedMeshRenderer.sharedMesh, mesh);
                        }
                    }
                    else if (renderer is MeshRenderer meshRenderer)
                    {
                        var filter = meshRenderer.gameObject.GetComponent <MeshFilter>();
                        if (filter != null && filter.sharedMesh != null)
                        {
                            var mesh = CreateMesh(filter.sharedMesh, meshRenderer, Materials);
                            Model.MeshGroups.Add(mesh);
                            Nodes[renderer.gameObject].MeshGroup = mesh;
                            if (!Meshes.ContainsKey(filter.sharedMesh))
                            {
                                Meshes.Add(filter.sharedMesh, mesh);
                            }
                        }
                    }
                }
            }

            return(Model);
        }
Exemplo n.º 17
0
        /// <summary>
        /// モデル(Transform + Renderer)を構築する。
        /// <summary>
        public static ModelAsset ToUnityAsset(VrmLib.Model model, bool showMesh = true)
        {
            var modelAsset = new ModelAsset();

            // texture
            for (int i = 0; i < model.Textures.Count; ++i)
            {
                var src  = model.Textures[i];
                var name = !string.IsNullOrEmpty(src.Name)
                    ? src.Name
                    : string.Format("{0}_img{1}", model.Root.Name, i);
                if (src is VrmLib.ImageTexture imageTexture)
                {
                    var texture = CreateTexture(imageTexture);
                    texture.name = name;
                    modelAsset.Map.Textures.Add(src, texture);
                    modelAsset.Textures.Add(texture);
                }
                else
                {
                    Debug.LogWarning($"{name} not ImageTexture");
                }
            }

            // material
            foreach (var src in model.Materials)
            {
                // TODO: material has VertexColor
                var material = RuntimeUnityMaterialBuilder.CreateMaterialAsset(src, hasVertexColor: false, modelAsset.Map.Textures);
                material.name = src.Name;
                modelAsset.Map.Materials.Add(src, material);
                modelAsset.Materials.Add(material);
            }

            // mesh
            for (int i = 0; i < model.MeshGroups.Count; ++i)
            {
                var src = model.MeshGroups[i];
                if (src.Meshes.Count == 1)
                {
                    // submesh 方式
                    var mesh = new UnityEngine.Mesh();
                    mesh.name = src.Name;
                    mesh.LoadMesh(src.Meshes[0], src.Skin);
                    modelAsset.Map.Meshes.Add(src, mesh);
                    modelAsset.Meshes.Add(mesh);
                }
                else
                {
                    // 頂点バッファの連結が必用
                    throw new NotImplementedException();
                }
            }

            // node: recursive
            CreateNodes(model.Root, null, modelAsset.Map.Nodes);
            modelAsset.Root = modelAsset.Map.Nodes[model.Root];

            // renderer
            var map = modelAsset.Map;

            foreach (var(node, go) in map.Nodes)
            {
                if (node.MeshGroup is null)
                {
                    continue;
                }

                if (node.MeshGroup.Meshes.Count > 1)
                {
                    throw new NotImplementedException("invalid isolated vertexbuffer");
                }

                var renderer = CreateRenderer(node, go, map);
                if (!showMesh)
                {
                    renderer.enabled = false;
                }
                map.Renderers.Add(node, renderer);
                modelAsset.Renderers.Add(renderer);
            }

            var humanoid = modelAsset.Root.AddComponent <MeshUtility.Humanoid>();

            humanoid.AssignBones(map.Nodes.Select(x => (x.Key.HumanoidBone.GetValueOrDefault().ToUnity(), x.Value.transform)));
            modelAsset.HumanoidAvatar      = humanoid.CreateAvatar();
            modelAsset.HumanoidAvatar.name = "VRM";

            var animator = modelAsset.Root.AddComponent <Animator>();

            animator.avatar = modelAsset.HumanoidAvatar;

            return(modelAsset);
        }
Exemplo n.º 18
0
        /// <summary>
        /// metaObject が null のときは、root から取得する
        /// </summary>
        public VrmLib.Model ToModelFrom10(GameObject root, VRM10MetaObject metaObject = null)
        {
            Model = new VrmLib.Model(VrmLib.Coordinates.Unity);

            if (metaObject is null)
            {
                var vrmController = root.GetComponent <VRM10Controller>();
                if (vrmController is null || vrmController.Meta is null)
                {
                    throw new NullReferenceException("metaObject is null");
                }
                metaObject = vrmController.Meta;
            }

            ToGlbModel(root);

            // meta
            var meta = new VrmLib.Meta();

            meta.Name    = metaObject.Name;
            meta.Version = metaObject.Version;
            meta.CopyrightInformation = metaObject.CopyrightInformation;
            meta.Authors.AddRange(metaObject.Authors);
            meta.ContactInformation = metaObject.ContactInformation;
            meta.Reference          = metaObject.Reference;
            meta.Thumbnail          = metaObject.Thumbnail.ToPngImage(VrmLib.ImageUsage.None);

            meta.AvatarPermission = new VrmLib.AvatarPermission
            {
                AvatarUsage           = metaObject.AllowedUser,
                IsAllowedViolentUsage = metaObject.ViolentUsage,
                IsAllowedSexualUsage  = metaObject.SexualUsage,
                CommercialUsage       = metaObject.CommercialUsage,
                IsAllowedGameUsage    = metaObject.GameUsage,
                IsAllowedPoliticalOrReligiousUsage = metaObject.PoliticalOrReligiousUsage,
                OtherPermissionUrl = metaObject.OtherPermissionUrl,
            };
            meta.RedistributionLicense = new VrmLib.RedistributionLicense
            {
                CreditNotation        = metaObject.CreditNotation,
                IsAllowRedistribution = metaObject.Redistribution,
                ModificationLicense   = metaObject.ModificationLicense,
                OtherLicenseUrl       = metaObject.OtherLicenseUrl,
            };
            Model.Vrm = new VrmLib.Vrm(meta, UniVRM10.VRMVersion.VERSION, UniVRM10.VRMSpecVersion.Version);

            // humanoid
            {
                var humanoid = root.GetComponent <MeshUtility.Humanoid>();
                if (humanoid is null)
                {
                    humanoid = root.AddComponent <MeshUtility.Humanoid>();
                    humanoid.AssignBonesFromAnimator();
                }

                foreach (HumanBodyBones humanBoneType in Enum.GetValues(typeof(HumanBodyBones)))
                {
                    var transform = humanoid.GetBoneTransform(humanBoneType);
                    if (transform != null && Nodes.TryGetValue(transform.gameObject, out VrmLib.Node node))
                    {
                        node.HumanoidBone = (VrmLib.HumanoidBones)Enum.Parse(typeof(VrmLib.HumanoidBones), humanBoneType.ToString(), true);
                    }
                }
            }


            // blendShape
            var controller = root.GetComponent <UniVRM10.VRM10Controller>();

            if (controller != null)
            {
                {
                    Model.Vrm.ExpressionManager = new VrmLib.ExpressionManager();
                    if (controller != null)
                    {
                        foreach (var clip in controller.Expression.ExpressionAvatar.Clips)
                        {
                            var expression = ToVrmLib(clip, root);
                            if (expression != null)
                            {
                                Model.Vrm.ExpressionManager.ExpressionList.Add(expression);
                            }
                        }
                    }
                }

                // firstPerson
                {
                    var firstPerson = new VrmLib.FirstPerson();
                    if (controller != null)
                    {
                        foreach (var annotation in controller.FirstPerson.Renderers)
                        {
                            firstPerson.Annotations.Add(
                                new VrmLib.FirstPersonMeshAnnotation(Nodes[annotation.Renderer.gameObject],
                                                                     annotation.FirstPersonFlag)
                                );
                        }
                        Model.Vrm.FirstPerson = firstPerson;
                    }
                }

                // lookAt
                {
                    var lookAt = new VrmLib.LookAt();
                    if (controller != null)
                    {
                        if (controller.LookAt.LookAtType == VRM10ControllerLookAt.LookAtTypes.Expression)
                        {
                            lookAt.HorizontalInner = new VrmLib.LookAtRangeMap();
                            lookAt.HorizontalOuter = new VrmLib.LookAtRangeMap()
                            {
                                InputMaxValue = controller.LookAt.HorizontalOuter.CurveXRangeDegree,
                                OutputScaling = controller.LookAt.HorizontalOuter.CurveYRangeDegree
                            };
                            lookAt.VerticalUp = new VrmLib.LookAtRangeMap()
                            {
                                InputMaxValue = controller.LookAt.VerticalUp.CurveXRangeDegree,
                                OutputScaling = controller.LookAt.VerticalUp.CurveYRangeDegree,
                            };
                            lookAt.VerticalDown = new VrmLib.LookAtRangeMap()
                            {
                                InputMaxValue = controller.LookAt.VerticalDown.CurveXRangeDegree,
                                OutputScaling = controller.LookAt.VerticalDown.CurveYRangeDegree,
                            };
                        }
                        else if (controller.LookAt.LookAtType == VRM10ControllerLookAt.LookAtTypes.Bone)
                        {
                            lookAt.HorizontalInner = new VrmLib.LookAtRangeMap()
                            {
                                InputMaxValue = controller.LookAt.HorizontalInner.CurveXRangeDegree,
                                OutputScaling = controller.LookAt.HorizontalInner.CurveYRangeDegree
                            };
                            lookAt.HorizontalOuter = new VrmLib.LookAtRangeMap()
                            {
                                InputMaxValue = controller.LookAt.HorizontalOuter.CurveXRangeDegree,
                                OutputScaling = controller.LookAt.HorizontalOuter.CurveYRangeDegree
                            };
                            lookAt.VerticalUp = new VrmLib.LookAtRangeMap()
                            {
                                InputMaxValue = controller.LookAt.VerticalUp.CurveXRangeDegree,
                                OutputScaling = controller.LookAt.VerticalUp.CurveYRangeDegree,
                            };
                            lookAt.VerticalDown = new VrmLib.LookAtRangeMap()
                            {
                                InputMaxValue = controller.LookAt.VerticalDown.CurveXRangeDegree,
                                OutputScaling = controller.LookAt.VerticalDown.CurveYRangeDegree,
                            };
                        }
                        lookAt.OffsetFromHeadBone = controller.LookAt.OffsetFromHead.ToNumericsVector3();
                    }
                    Model.Vrm.LookAt = lookAt;
                }

                // springBone
                {
                    var springBoneManager = controller.SpringBone;
                    foreach (var springBone in springBoneManager.Springs)
                    {
                        var vrmSpringBone = new VrmLib.SpringBone()
                        {
                            Comment = springBone.m_comment,
                            Origin  = (springBone.m_center != null) ? Nodes[springBone.m_center.gameObject] : null,
                        };

                        foreach (var joint in springBone.Joints)
                        {
                            vrmSpringBone.Joints.Add(new VrmLib.SpringJoint(Nodes[joint.Transform.gameObject])
                            {
                                Stiffness    = joint.m_stiffnessForce,
                                GravityPower = joint.m_gravityPower,
                                GravityDir   = joint.m_gravityDir.ToNumericsVector3(),
                                DragForce    = joint.m_dragForce,
                                HitRadius    = joint.m_jointRadius,
                                Exclude      = joint.m_exclude,
                            });
                        }

                        foreach (var colliderGroup in springBone.ColliderGroups)
                        {
                            var colliderGroups = colliderGroup.Colliders.Select(x =>
                            {
                                switch (x.ColliderType)
                                {
                                case VRM10SpringBoneColliderTypes.Sphere:
                                    return(VrmLib.VrmSpringBoneCollider.CreateSphere(x.Offset.ToNumericsVector3(), x.Radius));

                                case VRM10SpringBoneColliderTypes.Capsule:
                                    return(VrmLib.VrmSpringBoneCollider.CreateCapsule(x.Offset.ToNumericsVector3(), x.Radius, x.Tail.ToNumericsVector3()));

                                default:
                                    throw new NotImplementedException();
                                }
                            });
                            var vrmColliderGroup = new VrmLib.SpringBoneColliderGroup(Nodes[colliderGroup.gameObject], colliderGroups);
                            vrmSpringBone.Colliders.Add(vrmColliderGroup);
                        }

                        Model.Vrm.SpringBone.Springs.Add(vrmSpringBone);
                    }
                }
            }

            return(Model);
        }
Exemplo n.º 19
0
        public override void OnImportAsset(AssetImportContext ctx)
        {
            Debug.Log("OnImportAsset to " + ctx.assetPath);

            try
            {
                // Create Vrm Model
                VrmLib.Model model = VrmLoader.CreateVrmModel(ctx.assetPath);
                Debug.Log($"VrmLoader.CreateVrmModel: {model}");

                // Build Unity Model
                var assets = EditorUnityBuilder.ToUnityAsset(model, assetPath, this);
                ComponentBuilder.Build10(model, assets);

                // Texture
                var externalTextures = this.GetExternalUnityObjects <UnityEngine.Texture2D>();
                foreach (var texture in assets.Textures)
                {
                    if (texture == null)
                    {
                        continue;
                    }

                    if (externalTextures.ContainsValue(texture))
                    {
                    }
                    else
                    {
                        ctx.AddObjectToAsset(texture.name, texture);
                    }
                }

                // Material
                var externalMaterials = this.GetExternalUnityObjects <UnityEngine.Material>();
                foreach (var material in assets.Materials)
                {
                    if (material == null)
                    {
                        continue;
                    }

                    if (externalMaterials.ContainsValue(material))
                    {
                    }
                    else
                    {
                        ctx.AddObjectToAsset(material.name, material);
                    }
                }

                // Mesh
                foreach (var mesh in assets.Meshes)
                {
                    ctx.AddObjectToAsset(mesh.name, mesh);
                }

                //// ScriptableObject
                // avatar
                ctx.AddObjectToAsset("avatar", assets.HumanoidAvatar);

                // meta
                {
                    var external = this.GetExternalUnityObjects <UniVRM10.VRMMetaObject>().FirstOrDefault();
                    if (external.Value != null)
                    {
                        var metaComponent = assets.Root.GetComponent <VRMMeta>();
                        if (metaComponent != null)
                        {
                            metaComponent.Meta = external.Value;
                        }
                    }
                    else
                    {
                        var meta = assets.ScriptableObjects
                                   .FirstOrDefault(x => x.GetType() == typeof(UniVRM10.VRMMetaObject)) as UniVRM10.VRMMetaObject;
                        if (meta != null)
                        {
                            meta.name = "meta";
                            ctx.AddObjectToAsset(meta.name, meta);
                        }
                    }
                }

                // blendShape
                {
                    var external = this.GetExternalUnityObjects <UniVRM10.BlendShapeClip>();
                    if (external.Any())
                    {
                    }
                    else
                    {
                        var blendShapeClips = assets.ScriptableObjects
                                              .Where(x => x.GetType() == typeof(UniVRM10.BlendShapeClip))
                                              .Select(x => x as UniVRM10.BlendShapeClip);
                        foreach (var clip in blendShapeClips)
                        {
                            clip.name = clip.BlendShapeName;
                            ctx.AddObjectToAsset(clip.BlendShapeName, clip);
                        }
                    }
                }
                {
                    var external = this.GetExternalUnityObjects <UniVRM10.BlendShapeAvatar>().FirstOrDefault();
                    if (external.Value != null)
                    {
                        var blendShapeComponent = assets.Root.GetComponent <VRMController>();
                        if (blendShapeComponent != null)
                        {
                            blendShapeComponent.BlendShapeAvatar = external.Value;
                        }
                    }
                    else
                    {
                        var blendShapeAvatar = assets.ScriptableObjects
                                               .FirstOrDefault(x => x.GetType() == typeof(UniVRM10.BlendShapeAvatar)) as UniVRM10.BlendShapeAvatar;
                        if (blendShapeAvatar != null)
                        {
                            blendShapeAvatar.name = "blendShapeAvatar";
                            ctx.AddObjectToAsset(blendShapeAvatar.name, blendShapeAvatar);
                        }
                    }
                }

                // Root
                ctx.AddObjectToAsset(assets.Root.name, assets.Root);
                ctx.SetMainObject(assets.Root);
            }
            catch (System.Exception ex)
            {
                Debug.LogError(ex);
            }
        }
Exemplo n.º 20
0
        public override void OnImportAsset(AssetImportContext ctx)
        {
            Debug.Log("OnImportAsset to " + ctx.assetPath);

            try
            {
                // Create model
                VrmLib.Model model = CreateGlbModel(ctx.assetPath);
                Debug.Log($"ModelLoader.Load: {model}");

                // Build Unity Model
                var assets = EditorUnityBuilder.ToUnityAsset(model, assetPath, this);

                // Texture
                var externalTextures = this.GetExternalUnityObjects <UnityEngine.Texture2D>();
                foreach (var texture in assets.Textures)
                {
                    if (texture == null)
                    {
                        continue;
                    }

                    if (externalTextures.ContainsValue(texture))
                    {
                    }
                    else
                    {
                        ctx.AddObjectToAsset(texture.name, texture);
                    }
                }

                // Material
                var externalMaterials = this.GetExternalUnityObjects <UnityEngine.Material>();
                foreach (var material in assets.Materials)
                {
                    if (material == null)
                    {
                        continue;
                    }

                    if (externalMaterials.ContainsValue(material))
                    {
                    }
                    else
                    {
                        ctx.AddObjectToAsset(material.name, material);
                    }
                }

                // Mesh
                foreach (var mesh in assets.Meshes)
                {
                    ctx.AddObjectToAsset(mesh.name, mesh);
                }

                // Root
                ctx.AddObjectToAsset(assets.Root.name, assets.Root);
                ctx.SetMainObject(assets.Root);
            }
            catch (System.Exception ex)
            {
                Debug.LogError(ex);
            }
        }