Beispiel #1
0
        /// <summary>
        /// Avatarを生成する
        /// </summary>
        public static Avatar GenerateAvatar(Transform root, HumanDescription humanDescription, ICollection <SkeletonInfo> HumanSkeletonInfos)
        {
            List <SkeletonBone> skeletonList = new List <SkeletonBone>();

            HumanSkeletonInfos.ToList().ForEach(_ => skeletonList.Add(_.GetSkeletonBone()));
            var skleton = skeletonList.ToArray();

            humanDescription.skeleton = skleton;

            // AvatarBuilder生成時はanimatorがあるコンポーネントは「parent = null」にする必要がある
            Transform tmp_pare = root.parent; // tmp保存

            root.parent = null;               // 親なしにする

            var ret = AvatarBuilder.BuildHumanAvatar(root.gameObject, humanDescription);

            root.parent = tmp_pare; // 親を元に戻す

            // 要らないのでは?
            //humanDescription.skeleton = skleton;

            /*
             * // unity2017から仕様が変わったのか、avatar更新後に初期値を設定する必要があるようになった
             * // ⇒ 修正。HumanPoseHandlerで設定したほうが直接的に修正できる
             * foreach (var info in HumanSkeletonInfos)
             * {
             *  info.transform.localPosition = info.Position;
             *  info.transform.localRotation = info.Rotation;
             * }*/


            return(ret);
        }
Beispiel #2
0
        void Initialize()
        {
            var skeletonBuilder = new SkeletonBuilder(this.transform);

            skeletonBuilder.AddBasicSkeleton(new SkeletonBuilderParams());

            var leftHandRotation = Quaternion.Euler(0, 180, 180);

            skeletonBuilder.UpdateRotation(HumanBodyBones.LeftHand, leftHandRotation);

            var rightHandRotation = Quaternion.Euler(0, 0, 0);

            skeletonBuilder.UpdateRotation(HumanBodyBones.RightHand, rightHandRotation);

            AddHandSkeletonBones(skeletonBuilder, true);  // Left

            AddHandSkeletonBones(skeletonBuilder, false); // Right

            _Skeleton = skeletonBuilder.Skeleton;

            var avatar = AvatarBuilder.BuildHumanAvatar(this.gameObject, skeletonBuilder.GetHumanDescription());

            _SrcPoseHandler = new HumanPoseHandler(avatar, this.transform);

            if (_VisualizeBones && _XYZAxisPrefab != null)
            {
                foreach (var bone in skeletonBuilder.Skeleton.Values)
                {
                    GameObject axis = GameObject.Instantiate(_XYZAxisPrefab, Vector3.zero, Quaternion.identity, bone);
                    axis.transform.localScale    = new Vector3(_AxisObjectScale, _AxisObjectScale, _AxisObjectScale);
                    axis.transform.localPosition = Vector3.zero;
                    axis.transform.localRotation = Quaternion.identity;
                }
            }
        }
        bool CreatePlayableGraph()
        {
            var animator = GetComponent <Animator>();

            if (animator.avatar == null)
            {
                animator.avatar      = AvatarBuilder.BuildGenericAvatar(animator.gameObject, transform.name);
                animator.avatar.name = "Avatar";
            }

            var deltaTimeProperty = animator.BindSceneProperty(transform, typeof(Kinematica), "_deltaTime");

            job = new UpdateAnimationPoseJob();
            if (!job.Setup(animator,
                           GetComponentsInChildren <Transform>(), ref Synthesizer.Ref, deltaTimeProperty))
            {
                return(false);
            }

            playableGraph =
                PlayableGraph.Create(
                    $"Kinematica_{animator.transform.name}");

            var output = AnimationPlayableOutput.Create(playableGraph, "output", animator);

            var playable = AnimationScriptPlayable.Create(playableGraph, job);

            output.SetSourcePlayable(playable);

            playableGraph.Play();

            return(true);
        }
    private Avatar CreateAvatar(GameObject go)
    {
        HumanDescription desc     = CreateHumanDescription(go);
        Transform        parent   = go.transform.parent;
        Vector3          position = go.transform.position;
        Quaternion       rotation = go.transform.rotation;

        go.transform.parent   = null;
        go.transform.position = Vector3.zero;
        go.transform.rotation = Quaternion.identity;
        Avatar avatar = AvatarBuilder.BuildHumanAvatar(go, desc);

        go.transform.parent   = parent;
        go.transform.position = position;
        go.transform.rotation = rotation;
        if (avatar == null)
        {
            Debug.LogError("Something went wrong building the avatar.");
            return(null);
        }
        if (!avatar.isValid)
        {
            Debug.LogError("Avatar is invalid.");
            return(null);
        }
        avatar.name = "avatar";
        return(avatar);
    }
        /// <summary>
        /// Creates a generic avatar for a UMA character.
        /// </summary>
        /// <returns>The generic avatar.</returns>
        /// <param name="umaData">UMA data.</param>
        public static Avatar CreateGenericAvatar(UMAData umaData)
        {
            Avatar res = AvatarBuilder.BuildGenericAvatar(umaData.gameObject, umaData.umaRecipe.GetRace().genericRootMotionTransformName);

            res.name = umaData.name;
            return(res);
        }
Beispiel #6
0
        public override object WriteTo(object obj)
        {
            if (obj is Avatar)
            {
                obj = base.WriteTo(obj);
                if (obj == null)
                {
                    return(null);
                }
                return(obj);
            }

            Animator animator = (Animator)obj;

            if (isHuman)
            {
                HumanDescription desc = (HumanDescription)humanDescription.WriteTo(new HumanDescription());
                desc.skeleton[0].name = animator.gameObject.name;
                animator.avatar       = AvatarBuilder.BuildHumanAvatar(animator.gameObject, desc);
                base.WriteTo(animator.avatar);
            }
            else
            {
                animator.avatar = AvatarBuilder.BuildGenericAvatar(animator.gameObject, "");
            }

            return(obj);
        }
Beispiel #7
0
    public static void CreateAvatar()
    {
        GameObject go = Selection.activeGameObject;

        if (go != null && go.GetComponent("Animator") != null)
        {
            HumanDescription hd = new HumanDescription();

            Dictionary <string, string> boneName = new System.Collections.Generic.Dictionary <string, string>();
            boneName["Chest"]         = "spine";
            boneName["Head"]          = "head";
            boneName["Hips"]          = "hip";
            boneName["LeftFoot"]      = "footL";
            boneName["LeftHand"]      = "handL";
            boneName["LeftLowerArm"]  = "elbowL";
            boneName["LeftLowerLeg"]  = "kneeL";
            boneName["LeftShoulder"]  = "clavL";
            boneName["LeftUpperArm"]  = "armL";
            boneName["LeftUpperLeg"]  = "legL";
            boneName["RightFoot"]     = "footR";
            boneName["RightHand"]     = "handR";
            boneName["RightLowerArm"] = "elbowR";
            boneName["RightLowerLeg"] = "kneeR";
            boneName["RightShoulder"] = "clavR";
            boneName["RightUpperArm"] = "armR";
            boneName["RightUpperLeg"] = "legR";
            boneName["Spine"]         = "spine2";
            string[]    humanName  = HumanTrait.BoneName;
            HumanBone[] humanBones = new HumanBone[boneName.Count];
            int         j          = 0;
            int         i          = 0;
            while (i < humanName.Length)
            {
                if (boneName.ContainsKey(humanName[i]))
                {
                    HumanBone humanBone = new HumanBone();
                    humanBone.humanName = humanName[i];
                    humanBone.boneName  = boneName[humanName[i]];
                    humanBone.limit.useDefaultValues = true;
                    humanBones[j++] = humanBone;
                }
                i++;
            }

            hd.human = humanBones;

            //hd.skeleton = new SkeletonBone[18];
            //hd.skeleton[0].name = ("Hips") ;
            Avatar avatar = AvatarBuilder.BuildHumanAvatar(go, hd);

            avatar.name = (go.name + "_Avatar");
            Debug.Log(avatar.isHuman ? "is human" : "is generic");

            Animator animator = go.GetComponent("Animator") as Animator;
            animator.avatar = avatar;

            string path = AssetDatabase.GenerateUniqueAssetPath(Puppet2D_Editor._puppet2DPath + "/Animation/" + avatar.name + ".asset");
            AssetDatabase.CreateAsset(avatar, path);
        }
    }
Beispiel #8
0
    public static Avatar CreateAvatar(GameObject root, UMA.UmaTPose umaTPose)
    {
        HumanDescription description = CreateHumanDescription(root, umaTPose);
        Avatar           res         = AvatarBuilder.BuildHumanAvatar(root, description);

        return(res);
    }
        public static Avatar LoadHumanoidAvatar(Transform root, Dictionary <Transform, VrmLib.HumanoidBones> boneMap)
        {
            var description = new HumanDescription
            {
                skeleton = root.Traverse()
                           .Select(x => x.ToSkeletonBone()).ToArray(),
                human = boneMap
                        .Select(x => new HumanBone
                {
                    boneName  = x.Key.name,
                    humanName = s_humanTranitBoneNameMap[x.Value],
                    limit     = new HumanLimit
                    {
                        useDefaultValues = true,
                    }
                }).ToArray(),

                armStretch        = 0.05f,
                legStretch        = 0.05f,
                upperArmTwist     = 0.5f,
                lowerArmTwist     = 0.5f,
                upperLegTwist     = 0.5f,
                lowerLegTwist     = 0.5f,
                feetSpacing       = 0,
                hasTranslationDoF = false,
            };

            return(AvatarBuilder.BuildHumanAvatar(root.gameObject, description));
        }
Beispiel #10
0
        private void BuildMecanimAvatarFromQtmTPose()
        {
            var humanBones = new List <HumanBone>(mQtmSkeletonCache.Segments.Count);

            for (int index = 0; index < HumanTrait.BoneName.Length; index++)
            {
                var humanBoneName = HumanTrait.BoneName[index];
                if (mMecanimToQtmSegmentNames.ContainsKey(humanBoneName))
                {
                    var bone = new HumanBone()
                    {
                        humanName = humanBoneName,
                        boneName  = mMecanimToQtmSegmentNames[humanBoneName],
                    };
                    bone.limit.useDefaultValues = true;
                    humanBones.Add(bone);
                }
            }

            var skeletonBones = new List <SkeletonBone>(mQtmSkeletonCache.Segments.Count + 1);

            skeletonBones.Add(new SkeletonBone()
            {
                name     = this.SkeletonName,
                position = Vector3.zero,
                // In QTM default poses are facing +Y which becomes -Z in Unity.
                // We rotate 180 degrees to match unity forward.
                rotation = Quaternion.AngleAxis(180, Vector3.up),
                scale    = Vector3.one,
            });

            foreach (var segment in mQtmSkeletonCache.Segments)
            {
                skeletonBones.Add(new SkeletonBone()
                {
                    name     = this.SkeletonName + "_" + segment.Value.Name,
                    position = segment.Value.TPosition,
                    rotation = segment.Value.TRotation,
                    scale    = Vector3.one,
                });
            }

            mSourceAvatar = AvatarBuilder.BuildHumanAvatar(mStreamedRootObject,
                                                           new HumanDescription()
            {
                human    = humanBones.ToArray(),
                skeleton = skeletonBones.ToArray(),
            }
                                                           );
            if (mSourceAvatar.isValid == false || mSourceAvatar.isHuman == false)
            {
                this.enabled = false;
                return;
            }

            mSourcePoseHandler     = new HumanPoseHandler(mSourceAvatar, mStreamedRootObject.transform);
            mDestiationPoseHandler = new HumanPoseHandler(DestinationAvatar, this.transform);
        }
Beispiel #11
0
        private void BuildMecanimAvatarFromQtmTPose()
        {
            var humanBones = new List <HumanBone>(mQtmSkeletonCache.Segments.Count);

            for (int index = 0; index < HumanTrait.BoneName.Length; index++)
            {
                var humanBoneName = HumanTrait.BoneName[index];
                if (mMecanimToQtmSegmentNames.ContainsKey(humanBoneName))
                {
                    var bone = new HumanBone()
                    {
                        humanName = humanBoneName,
                        boneName  = mMecanimToQtmSegmentNames[humanBoneName],
                    };
                    bone.limit.useDefaultValues = true;
                    humanBones.Add(bone);
                }
            }

            // Set up the T-pose and game object name mappings.
            var skeletonBones = new List <SkeletonBone>(mQtmSkeletonCache.Segments.Count + 1);

            skeletonBones.Add(new SkeletonBone()
            {
                name     = this.SkeletonName,
                position = Vector3.zero,
                rotation = Quaternion.identity,
                scale    = Vector3.one,
            });

            // Create remaining T-Pose bone definitions from Qtm segments
            foreach (var segment in mQtmSkeletonCache.Segments.ToList())
            {
                skeletonBones.Add(new SkeletonBone()
                {
                    name     = this.SkeletonName + "_" + segment.Value.Name,
                    position = segment.Value.TPosition,
                    rotation = Quaternion.identity,
                    scale    = Vector3.one,
                });
            }

            mSourceAvatar = AvatarBuilder.BuildHumanAvatar(mStreamedRootObject,
                                                           new HumanDescription()
            {
                human    = humanBones.ToArray(),
                skeleton = skeletonBones.ToArray(),
            }
                                                           );
            if (mSourceAvatar.isValid == false || mSourceAvatar.isHuman == false)
            {
                this.enabled = false;
                return;
            }

            mSourcePoseHandler     = new HumanPoseHandler(mSourceAvatar, mStreamedRootObject.transform);
            mDestiationPoseHandler = new HumanPoseHandler(DestinationAvatar, this.transform);
        }
        /// <summary>
        /// Builds the object avatar, based on pre-defined templates (Mixamo, Biped), or based on the <see cref="TriLib.AvatarLoader.CustomBoneNames"></see>, if it's not null or empty.
        /// </summary>
        /// <returns><c>true</c> if avatar was built, <c>false</c> otherwise.</returns>
        private bool BuildAvatar()
        {
            var animator = CurrentAvatar.GetComponent <Animator>();

            if (animator == null)
            {
                #if ASSIMP_OUTPUT_MESSAGES
                Debug.LogError("No Animator Component found on current Avatar.");
                #endif
                return(false);
            }
            var skeletonBones  = new List <SkeletonBone>();
            var humanBones     = new List <HumanBone>();
            var boneTransforms = FindOutBoneTransforms(CurrentAvatar);
            if (boneTransforms.Count == 0)
            {
#if ASSIMP_OUTPUT_MESSAGES
                Debug.LogError("No suitable bones format found");
#endif
                return(false);
            }
            foreach (var boneTransform in boneTransforms)
            {
                humanBones.Add(CreateHumanBone(boneTransform.Key, boneTransform.Value.name));
            }
            var transforms    = CurrentAvatar.GetComponentsInChildren <Transform>();
            var rootTransform = transforms[1];
            skeletonBones.Add(CreateSkeletonBone(rootTransform));
            rootTransform.localEulerAngles = Vector3.zero;
            for (var i = 0; i < transforms.Length; i++)
            {
                var childTransform = transforms[i];
                var meshRenderers  = childTransform.GetComponentsInChildren <MeshRenderer>();
                if (meshRenderers.Length > 0)
                {
                    continue;
                }
                var skinnedMeshRenderers = childTransform.GetComponentsInChildren <SkinnedMeshRenderer>();
                if (skinnedMeshRenderers.Length > 0)
                {
                    continue;
                }
                skeletonBones.Add(CreateSkeletonBone(childTransform));
            }
            var humanDescription = new HumanDescription();
            humanDescription.armStretch        = ArmStretch;
            humanDescription.feetSpacing       = FeetSpacing;
            humanDescription.hasTranslationDoF = HasTranslationDof;
            humanDescription.legStretch        = LegStretch;
            humanDescription.lowerArmTwist     = LowerArmTwist;
            humanDescription.lowerLegTwist     = LowerLegTwist;
            humanDescription.upperArmTwist     = UpperArmTwist;
            humanDescription.upperLegTwist     = UpperLegTwist;
            humanDescription.skeleton          = skeletonBones.ToArray();
            humanDescription.human             = humanBones.ToArray();
            animator.avatar = AvatarBuilder.BuildHumanAvatar(CurrentAvatar, humanDescription);
            return(true);
        }
Beispiel #13
0
        public void Awake()
        {
            _Animator = GetComponent <Animator>();
            HumanDescription description = AvatarUtils.CreateHumanDescription(gameObject);
            Avatar           avatar      = AvatarBuilder.BuildHumanAvatar(gameObject, description);

            avatar.name      = gameObject.name;
            _Animator.avatar = avatar;
        }
Beispiel #14
0
        /// <summary>
        /// Creates a human (biped) avatar for a UMA character.
        /// </summary>
        /// <returns>The human avatar.</returns>
        /// <param name="umaData">UMA data.</param>
        /// <param name="umaTPose">UMA TPose.</param>
        public static Avatar CreateAvatar(UMAData umaData, UmaTPose umaTPose)
        {
            umaTPose.DeSerialize();
            HumanDescription description = CreateHumanDescription(umaData, umaTPose);
            //DebugLogHumanAvatar(umaData.gameObject, description);
            Avatar res = AvatarBuilder.BuildHumanAvatar(umaData.gameObject, description);

            return(res);
        }
Beispiel #15
0
    static int BuildGenericAvatar(IntPtr L)
    {
        LuaScriptMgr.CheckArgsCount(L, 2);
        GameObject arg0 = LuaScriptMgr.GetNetObject <GameObject>(L, 1);
        string     arg1 = LuaScriptMgr.GetLuaString(L, 2);
        Avatar     o    = AvatarBuilder.BuildGenericAvatar(arg0, arg1);

        LuaScriptMgr.Push(L, o);
        return(1);
    }
Beispiel #16
0
    static int BuildHumanAvatar(IntPtr L)
    {
        LuaScriptMgr.CheckArgsCount(L, 2);
        GameObject       arg0 = LuaScriptMgr.GetNetObject <GameObject>(L, 1);
        HumanDescription arg1 = LuaScriptMgr.GetNetObject <HumanDescription>(L, 2);
        Avatar           o    = AvatarBuilder.BuildHumanAvatar(arg0, arg1);

        LuaScriptMgr.Push(L, o);
        return(1);
    }
        private async Task <bool> BuildAvatar()
        {
            // HumanBoneのためのリストを取得する
            List <HumanBone> humanBones = new List <HumanBone>();

            string[] boneNames = HumanTrait.BoneName;
            await Task.Run(() =>
            {
                foreach (string humanBoneName in boneNames)
                {
                    if (!MMDModel.Unity_MMDBoneNameDictionary.ContainsKey(humanBoneName))
                    {
                        continue;
                    }
                    if (MMDModel.Unity_MMDBoneNameDictionary[humanBoneName] == null)
                    {
                        continue;
                    }
                    HumanBone humanBone = new HumanBone();
                    humanBone.humanName = humanBoneName;
                    humanBone.boneName  = MMDModel.Unity_MMDBoneNameDictionary[humanBoneName];
                    humanBone.limit.useDefaultValues = true;
                    humanBones.Add(humanBone);
                }
            });

            // HumanDescription(関節の曲がり方などを定義した構造体)
            HumanDescription humanDesc = new HumanDescription();

            humanDesc.human    = humanBones.ToArray();
            humanDesc.skeleton = GetTransforms(transform).ToArray();

            humanDesc.upperArmTwist = 0.5f;
            humanDesc.lowerArmTwist = 0.5f;
            humanDesc.upperLegTwist = 0.5f;
            humanDesc.lowerLegTwist = 0.5f;
            humanDesc.armStretch    = 0.05f;
            humanDesc.legStretch    = 0.05f;
            humanDesc.feetSpacing   = 0.05f;

            // アバターオブジェクトをビルド
            Avatar avatar = AvatarBuilder.BuildHumanAvatar(gameObject, humanDesc);

            avatar.name = gameObject.name + AvatarNameTail;
            if (!avatar.isValid || !avatar.isHuman)
            {
                UnityEngine.Debug.Log("Error when building avatar");
                return(false);
            }
            animator                           = gameObject.AddComponent <Animator>();
            animator.avatar                    = avatar;
            animator.applyRootMotion           = true;
            animator.runtimeAnimatorController = RuntimeAnimatorController;
            return(true);
        }
Beispiel #18
0
                private static Avatar GetDummyAvatar()
                {
                    if (_dummyAvatar == null)
                    {
                        GameObject temp = new GameObject();
                        _dummyAvatar      = AvatarBuilder.BuildGenericAvatar(temp, "");
                        _dummyAvatar.name = "GPU Animated Avatar";
                        Destroy(temp);
                    }

                    return(_dummyAvatar);
                }
Beispiel #19
0
        private static void LoadHumanoidObsolete(VRMImporterContext context)
        {
            var parsed   = context.Json.ParseAsJson()["extensions"]["VRM"];
            var skeleton = context.Root.transform.Traverse().Select(x => ToSkeletonBone(x)).ToArray();

            var description = new HumanDescription
            {
                human = parsed[HUMANOID_KEY]["bones"]
                        .ObjectItems
                        .Select(x => new { x.Key, Index = x.Value.GetInt32() })
                        .Where(x => x.Index != -1)
                        .Select(x =>
                {
                    var humanBone = EnumUtil.TryParseOrDefault <HumanBodyBones>(x.Key);
                    var hb        = new HumanBone
                    {
                        boneName  = context.Nodes[x.Index].name,
                        humanName = ToHumanBoneName(humanBone)
                    };
                    hb.limit.useDefaultValues = true;
                    return(hb);
                }).ToArray(),
                skeleton      = skeleton,
                lowerArmTwist = 0.5f,
                upperArmTwist = 0.5f,
                upperLegTwist = 0.5f,
                lowerLegTwist = 0.5f,
                armStretch    = 0.05f,
                legStretch    = 0.05f,
                feetSpacing   = 0.0f,
            };

            context.HumanoidAvatar      = AvatarBuilder.BuildHumanAvatar(context.Root, description);
            context.HumanoidAvatar.name = Path.GetFileNameWithoutExtension(context.Path);

            context.AvatarDescription      = UniHumanoid.AvatarDescription.CreateFrom(description);
            context.AvatarDescription.name = "AvatarDescription";
            var humanoid = context.Root.AddComponent <VRMHumanoidDescription>();

            humanoid.Avatar      = context.HumanoidAvatar;
            humanoid.Description = context.AvatarDescription;

            var animator = context.Root.GetComponent <Animator>();

            if (animator == null)
            {
                animator = context.Root.AddComponent <Animator>();
            }
            animator.avatar = context.HumanoidAvatar;
        }
Beispiel #20
0
        private static void CreateAvatar()
        {
            GameObject activeGameObject = Selection.activeGameObject;

            if (activeGameObject != null)
            {
                Avatar avatar = AvatarBuilder.BuildGenericAvatar(activeGameObject, "");
                avatar.name = activeGameObject.name;
                Debug.Log(avatar.isHuman ? "is human" : "is generic");

                var path = string.Format("Assets/{0}.ht", avatar.name.Replace(':', '_'));
                AssetDatabase.CreateAsset(avatar, path);
            }
        }
Beispiel #21
0
        public Avatar Create()
        {
            // check if it's a valid mecanim avatar
            var boneName = HumanTrait.BoneName;

            for (var x = 0; x < boneName.Length; x++)
            {
                if (!HumanTrait.RequiredBone(x))
                {
                    continue;
                }
                var requiredBoneType = Naming.MecanimNameToBoneType(boneName[x]);
                if (!_boneMapping.ContainsKey(requiredBoneType))
                {
                    return(AvatarBuilder.BuildGenericAvatar(_root, ""));
                }
            }

            var humanBones    = new HumanBone[_boneMapping.Count];
            var skeletonBones = GetSkeletonBones();

            for (var x = 0; x < _boneMapping.Count; x++)
            {
                var item            = _boneMapping.ElementAt(x);
                var boneType        = item.Key;
                var go              = item.Value;
                var mecanimBoneName = Naming.BoneTypeToMecanimName(boneType);
                if (mecanimBoneName == "default")
                {
                    mecanimBoneName = go.name;
                }

                var humanBone = new HumanBone
                {
                    humanName = mecanimBoneName,
                    boneName  = go.name,
                    limit     = { useDefaultValues = true }
                };
                humanBones[x] = humanBone;
            }

            var humanDescription = new HumanDescription()
            {
                skeleton = skeletonBones,
                human    = humanBones
            };

            return(AvatarBuilder.BuildHumanAvatar(_root, humanDescription));
        }
Beispiel #22
0
        public string UploadAvatar(IFormFile file, string key)
        {
            if (file.Length >= 300000)
            {
                throw new Exception("Uploaded image may not exceed 300 kb, please upload a smaller image.");
            }

            try
            {
                using (var readStream = file.OpenReadStream())
                {
                    using (var img = Image.FromStream(readStream))
                    {
                        if (!img.RawFormat.Equals(ImageFormat.Jpeg) && !img.RawFormat.Equals(ImageFormat.Png))
                        {
                            throw new Exception("Uploaded file is not recognized as an image.");
                        }

                        var fileName = key + ".png";

                        try
                        {
                            // Check if previous avatar exists
                            var avatar = _avatarDirectoryInfo.GetFile(fileName);
                            if (avatar.Exists)
                            {
                                // delete the file
                                avatar.Delete();
                            }

                            // finally, build the image
                            AvatarBuilder.Build(readStream, fileName);
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Uploaded file is not recognized as a valid image.", ex);
                        }

                        return(key);
                    }
                }
            }
            catch (Exception)
            {
                throw new Exception("Uploaded file is not recognized as an image.");
            }
        }
Beispiel #23
0
    public static int constructor(IntPtr l)
    {
        int result;

        try
        {
            AvatarBuilder o = new AvatarBuilder();
            LuaObject.pushValue(l, true);
            LuaObject.pushValue(l, o);
            result = 2;
        }
        catch (Exception e)
        {
            result = LuaObject.error(l, e);
        }
        return(result);
    }
Beispiel #24
0
    static int _CreateAvatarBuilder(IntPtr L)
    {
        int count = LuaDLL.lua_gettop(L);

        if (count == 0)
        {
            AvatarBuilder obj = new AvatarBuilder();
            LuaScriptMgr.PushObject(L, obj);
            return(1);
        }
        else
        {
            LuaDLL.luaL_error(L, "invalid arguments to method: AvatarBuilder.New");
        }

        return(0);
    }
Beispiel #25
0
    // Use this for initialization
    void Start()
    {
        SkinnedMeshRenderer rend = gameObject.GetComponent <SkinnedMeshRenderer>();

        mesh = new Mesh();

        Utils.LoadMesh(meshpath, mesh, rend, transform);
        Animation anim = GetComponent <Animation>();

        Utils.LoadAnim(anipath, anim);
        //anim.Play("test");
        //anim.Play("站立01");

        avatar      = AvatarBuilder.BuildGenericAvatar(gameObject, "");
        avatar.name = "Bob";
        Debug.Log(avatar.isHuman ? "is human" : "is generic");
    }
Beispiel #26
0
        public static Avatar LoadHumanoidAvatar(Transform root, Dictionary <Transform, VrmLib.HumanoidBones> boneMap)
        {
            var description = new HumanDescription
            {
                skeleton = root.Traverse()
                           .Select(x => x.ToSkeletonBone()).ToArray(),
                human = root.Traverse()
                        .Where(x => boneMap.ContainsKey(x))
                        .Select(x => new HumanBone
                {
                    boneName  = x.name,
                    humanName = s_humanTranitBoneNameMap[boneMap[x]],
                }).ToArray(),
            };

            return(AvatarBuilder.BuildHumanAvatar(root.gameObject, description));
        }
        static void CreateAvatar(SpineArmatureEditor armatureEditor, Animator animator, string path)
        {
            Avatar avatar = AvatarBuilder.BuildGenericAvatar(armatureEditor.armature.gameObject, "");

            animator.avatar = avatar;
            AvatarMask avatarMask = new AvatarMask();

            string[] transofrmPaths = GetTransformPaths(armatureEditor);
            avatarMask.transformCount = transofrmPaths.Length;
            for (int i = 0; i < transofrmPaths.Length; i++)
            {
                avatarMask.SetTransformPath(i, transofrmPaths[i]);
                avatarMask.SetTransformActive(i, true);
            }
            AssetDatabase.CreateAsset(avatar, path + "/" + armatureEditor.armature.name + "Avatar.asset");
            AssetDatabase.CreateAsset(avatarMask, path + "/" + armatureEditor.armature.name + "Mask.asset");
        }
Beispiel #28
0
    //the createCharacter function takes in the parameters to import in a character from the Resources folder
    // parameters:
    // string assetName: the file name (minus the extension) of the rigged model for the humanoid character you want to import in (required)
    // the rest of the parameters are optional, but recommended
    //  string skeletonfile: text file name (minus the extension) in the Resources folder that describes a mapping from your bone names to Unity's bone names
    //  string tposefile: text file name (minus extension) that contains the transforms that put your character in tpose. can use AvatarUtils to do this
    //  bool useLocalPositionAndScale: if you are using multiple characters with the same rig but potentially different sizes, you'll want to set this to true
    //                              effectively this uses the tposefile rotations only, ignoring the position and rotation
    //  string animatorfile: file name of an AnimatorController in the Resources folder to add to your character upon instantiation
    GameObject createCharacter(string assetName, string skeletonfile = "", string tposefile = "", string animatorfile = "", bool useLocalPositionAndScale = true)
    {
        //Import in a FBX file from resources and set position
        GameObject character = (GameObject)Instantiate(Resources.Load(assetName));
        GameObject root      = GameObject.Find(assetName);

        if (character == null)
        {
            Debug.LogError("File " + assetName + " not loaded in from resources correctly. Cannot make character.");
            return(null);
        }

        //set up the description for the humanoid, given parameters
        HumanDescription desc = setupHumanDescription(character, skeletonfile: skeletonfile, tposefile: tposefile, useLocalPositionAndScale: useLocalPositionAndScale);

        //if the gameobject we created for our character doesn't have an animator component, add one
        if (character.GetComponent <Animator>() == null)
        {
            character.AddComponent <Animator>();
        }

        //create the avatar using that gameobject and the human description we created
        Avatar a = AvatarBuilder.BuildHumanAvatar(root, desc);

        if (a == null)
        {
            Debug.LogError("Something went wrong building the avatar from the provided character and human description. Check your error log for clues.");
            return(null);
        }
        character.GetComponent <Animator>().avatar = a;

        //if there was a file specified to use as its animator controller, load it in from resources
        if (animatorfile != "")
        {
            RuntimeAnimatorController c = (RuntimeAnimatorController)Instantiate(Resources.Load(animatorfile));
            if (c == null)
            {
                Debug.LogError("File " + assetName + " not loaded in from resources correctly. Cannot add animation controller.");
                return(null);
            }
            character.GetComponent <Animator>().runtimeAnimatorController = c;
        }

        return(character);
    }
        public static void builAvatarMask(GameObject gameObject, SpineData spineData, Animator animator, string directory, string name)
        {
            Avatar avatar = AvatarBuilder.BuildGenericAvatar(gameObject, "");

            animator.avatar = avatar;
            AvatarMask avatarMask = new AvatarMask();

            string[] transofrmPaths = getTransformPaths(gameObject, spineData);
            avatarMask.transformCount = transofrmPaths.Length;
            for (int i = 0; i < transofrmPaths.Length; i++)
            {
                avatarMask.SetTransformPath(i, transofrmPaths[i]);
                avatarMask.SetTransformActive(i, true);
            }
            createFolderIfNoExists(directory, ANIMATION_FOLDER);
            AssetDatabase.CreateAsset(avatar, directory + "/" + ANIMATION_FOLDER + "/" + name + ".anim.asset");
            AssetDatabase.CreateAsset(avatarMask, directory + "/" + ANIMATION_FOLDER + "/" + name + ".mask.asset");
        }
Beispiel #30
0
    public static Avatar Build(List <string> boneNames, List <Transform> matchingBones, GameObject topObject)
    {
        HumanBone[]      humanBones = new HumanBone[boneNames.Count];
        List <Transform> bones      = new List <Transform>();

        for (int i = 0; i < boneNames.Count; i++)
        {
            if (matchingBones[i] == null)
            {
                continue;
            }
            humanBones[i]           = new HumanBone();
            humanBones[i].boneName  = matchingBones[i].name;
            humanBones[i].humanName = boneNames[i];
            humanBones[i].limit.useDefaultValues = true;
            AddParentRecursive(bones, matchingBones[i], topObject.transform);
        }

        HumanDescription hd = new HumanDescription();

        hd.human = humanBones;
        SkinnedMeshRenderer smr = topObject.GetComponentInChildren <SkinnedMeshRenderer>();

        //Transform[] bones=new Transform[smr.bones.Length+1];
        //System.Array.Copy(smr.bones,bones,smr.bones.Length);
        //bones[smr.bones.Length]=smr.bones[0].parent;



        SkeletonBone[] skeleton = new SkeletonBone[bones.Count];
        for (int i = 0; i < bones.Count; i++)
        {
            skeleton[i]          = new SkeletonBone();
            skeleton[i].name     = bones[i].name;
            skeleton[i].position = bones[i].localPosition;
            skeleton[i].rotation = bones[i].localRotation;
            skeleton[i].scale    = bones[i].localScale;
        }
        hd.skeleton = skeleton;
        Avatar avatar = AvatarBuilder.BuildHumanAvatar(topObject, hd);

        return(avatar);
    }