示例#1
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 = 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));
        }
示例#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;
                }
            }
        }
    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);
    }
示例#4
0
    public static Avatar CreateAvatar(GameObject root, UMA.UmaTPose umaTPose)
    {
        HumanDescription description = CreateHumanDescription(root, umaTPose);
        Avatar           res         = AvatarBuilder.BuildHumanAvatar(root, description);

        return(res);
    }
示例#5
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);
        }
    }
示例#6
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);
        }
示例#7
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);
        }
示例#8
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);
        }
示例#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);
        }
示例#11
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);
        }
示例#12
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;
        }
示例#13
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);
        }
示例#15
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;
        }
示例#16
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));
        }
示例#17
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));
        }
示例#18
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);
    }
示例#19
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);
    }
示例#20
0
        /// <summary>
        /// <see cref="Avatar"/>を作成して保存し、アバターに設定します。
        /// </summary>
        /// <param name="avatar"></param>
        /// <param name="humanDescriptionModifier"><see cref="AvatarDescription.ToHumanDescription"/>によって生成された<see cref="HumanDescription"/>を変更するコールバック関数。
        ///     再度メソッドを呼び出すと変更は失われます。</param>
        private static void ApplyAvatarDescription(
            GameObject avatar,
            Action <HumanDescription> humanDescriptionModifier = null
            )
        {
            var humanoidDescription             = avatar.GetComponent <VRMHumanoidDescription>();
            AvatarDescription avatarDescription = humanoidDescription.Description;
            var humanDescription = avatarDescription.ToHumanDescription(avatar.transform);

            if (humanDescriptionModifier != null)
            {
                humanDescriptionModifier(humanDescription);
            }
            Avatar humanoidRig = AvatarBuilder.BuildHumanAvatar(avatar, humanDescription);

            humanoidRig.name = humanoidDescription.Avatar.name;
            EditorUtility.CopySerialized(humanoidRig, humanoidDescription.Avatar);
            PrefabUtility.RecordPrefabInstancePropertyModifications(avatar);
            EditorUtility.SetDirty(humanoidDescription.Avatar);
        }
示例#21
0
    public static int BuildHumanAvatar_s(IntPtr l)
    {
        int result;

        try
        {
            GameObject go;
            LuaObject.checkType <GameObject>(l, 1, out go);
            HumanDescription humanDescription;
            LuaObject.checkValueType <HumanDescription>(l, 2, out humanDescription);
            Avatar o = AvatarBuilder.BuildHumanAvatar(go, humanDescription);
            LuaObject.pushValue(l, true);
            LuaObject.pushValue(l, o);
            result = 2;
        }
        catch (Exception e)
        {
            result = LuaObject.error(l, e);
        }
        return(result);
    }
示例#22
0
    /// <summary>
    /// 人型アバダーを設定する
    /// </summary>
    /// <returns>アニメーター</returns>
    /// <remarks>
    /// モデルに依ってボーン構成に差が有るが、MMD標準モデルとの一致を優先する
    /// </remarks>
    public Animator SettingHumanAvatar()
    {
        //生成済みのボーンをUnity推奨ポーズに設定
        SetRequirePose();

        //アバタールートトランスフォームの取得
        Transform avatar_root_transform = root_game_object_.transform.Find("Model");

        if (null == avatar_root_transform)
        {
            //ルートゲームオブジェクト直下にモデルルートオブジェクトが無い(PMDConverter)なら
            //ルートゲームオブジェクトをアバタールートオブジェクトとする
            avatar_root_transform = root_game_object_.transform;
        }

        //ヒューマノイドアバター作成
        HumanDescription description = new HumanDescription();

        description.human         = CreateHumanBone();
        description.skeleton      = CreateSkeletonBone();
        description.lowerArmTwist = 0.0f;
        description.upperArmTwist = 0.0f;
        description.upperLegTwist = 0.0f;
        description.lowerLegTwist = 0.0f;
        description.armStretch    = 0.0f;
        description.legStretch    = 0.0f;
        description.feetSpacing   = 0.0f;
        avatar_ = AvatarBuilder.BuildHumanAvatar(avatar_root_transform.gameObject, description);

        //アバターをアニメーターに設定
        animator_        = root_game_object_.AddComponent <Animator>();
        animator_.avatar = avatar_;

        //IKの無効化
        DisableIk();

        return(animator_);
    }
 public Avatar CreateAvatar(Transform root)
 {
     return(AvatarBuilder.BuildHumanAvatar(root.gameObject, ToHumanDescription(root)));
 }
示例#24
0
    // Attempts to remap a mecanim rig so that the upper chest bone
    // is blank, by moving the upper chest bone to chest and rebuilding
    // CURRENTLY DOES NOT WORK!
    void UpperChestFix(VRCSDK2.VRC_AvatarDescriptor ad, GameObject avObj, Animator anim)
    {
        // if upper chest was mapped we need to reconfigure rig
        // by moving upper chest to chest
        Transform pelvis     = anim.GetBoneTransform(HumanBodyBones.Hips);
        Transform upchest    = anim.GetBoneTransform(HumanBodyBones.UpperChest);
        Transform chest      = anim.GetBoneTransform(HumanBodyBones.Chest);
        Transform torso      = anim.GetBoneTransform(HumanBodyBones.Spine);
        Avatar    origAvatar = anim.avatar;

        if (upchest != null)
        {
            // get every child transform of the animator
            Transform[] allBones = anim.GetComponentsInChildren <Transform>();

            // get a list of the extra spine bones between spine and pelvis
            List <Transform> extras = FindBonesBetween(torso, pelvis);

            HumanDescription desc = new HumanDescription();
            desc.upperArmTwist = 0.5f;
            desc.lowerArmTwist = 0.5f;
            desc.upperLegTwist = 0.5f;
            desc.lowerLegTwist = 0.5f;
            desc.armStretch    = 0.05f;
            desc.legStretch    = 0.05f;
            desc.feetSpacing   = 0.0f;
            List <HumanBone>               hbList   = new List <HumanBone>();
            List <SkeletonBone>            sbList   = new List <SkeletonBone>();
            HumanBodyBones[]               hbbArray = (HumanBodyBones[])System.Enum.GetValues(typeof(HumanBodyBones));
            Dictionary <Transform, string> hbbDict  = new Dictionary <Transform, string>();

            for (int i = 0; i < hbbArray.Length; i++)
            {
                Transform t = anim.GetBoneTransform(hbbArray[i]);
                string    n = hbbArray[i].ToString();
                if (t != null && n != "LastBone")
                {
                    hbbDict[t] = n;
                    //Debug.LogError("Dictionary Added:"+hbbArray[i].ToString());
                }
            }

            foreach (Transform bt in allBones)
            {
                // map the human bones
                if (hbbDict.Keys.Contains(bt))
                {
                    string hbName = hbbDict[bt];
                    //Debug.LogError("Processing: "+hbName);
                    if (hbName != "Spine" && bt != null && !extras.Contains(bt))
                    {
                        if (bt == upchest)
                        {
                            hbName = "Chest";
                        }
                        else if (bt == chest)
                        {
                            hbName = "Spine";
                        }
                        HumanBone hb = new HumanBone();
                        hb.boneName  = bt.name;
                        hb.humanName = hbName;
                        //Debug.Log("Mapped human bone:" + hb.humanName + " to " + hb.boneName);
                        hbList.Add(hb);
                    }
                    else
                    {
                        //Debug.LogError("Skipped:" + hbbDict[bt]);
                    }
                }

                if (bt != null)
                {
                    // THESE POSITIONS/ROTATIONS MUST BE FOR TPOSE !!!
                    SkeletonBone sb = new SkeletonBone();
                    sb.name     = bt.name;
                    sb.position = bt.position;
                    sb.rotation = bt.rotation;
                    sb.scale    = bt.localScale;
                    sbList.Add(sb);
                }
            }

            // add any root bones above hip
            Transform root = pelvis.parent;
            while (root != null && root != anim.transform)
            {
                // THESE POSITIONS/ROTATIONS MUST BE FOR TPOSE !!!
                SkeletonBone sb = new SkeletonBone();
                sb.name     = root.name;
                sb.position = root.position;
                sb.rotation = root.rotation;
                sb.scale    = root.localScale;
                sbList.Add(sb);
                root = root.parent;
            }

            desc.human    = hbList.ToArray();
            desc.skeleton = sbList.ToArray();
            anim.avatar   = AvatarBuilder.BuildHumanAvatar(avObj, desc);
            if (anim.avatar.isValid && anim.avatar.isHuman)
            {
                anim.avatar.name = "{ADJUSTED}" + origAvatar.name;
                // shift all the bone mappings
                torso   = chest;
                chest   = upchest;
                upchest = null;
            }
            else
            {
                OnGUIError(ad, "Automatic rig adjustment on " + origAvatar.name + " failed. You will need to manually configure the humanoid rig. Make sure the UpperChest slot is empty.");
                anim.avatar = origAvatar;
                return;
            }
        }

        if (anim.avatar.name.StartsWith("{ADJUSTED}"))
        {
            OnGUIWarning(ad, "Your rig has the UPPERCHEST mapped in the Humanoid Rig, and was automatically corrected " +
                         "to use the CHEST instead. If you run into issues we recommend leaving the " +
                         "UPPERCHEST blank and mapping your top spine bone to the CHEST.");
        }
    }
    /// <summary>
    /// Constructs the source Avatar and pose handlers for Mecanim retargeting.
    /// </summary>
    /// <param name="rootObjectName"></param>
    private void MecanimSetup(string rootObjectName)
    {
        string[] humanTraitBoneNames = HumanTrait.BoneName;

        // Set up the mapping between Mecanim human anatomy and OptiTrack skeleton representations.
        List <HumanBone> humanBones = new List <HumanBone>(m_skeletonDef.Bones.Count);

        for (int humanBoneNameIdx = 0; humanBoneNameIdx < humanTraitBoneNames.Length; ++humanBoneNameIdx)
        {
            string humanBoneName = humanTraitBoneNames[humanBoneNameIdx];
            if (m_cachedMecanimBoneNameMap.ContainsKey(humanBoneName))
            {
                HumanBone humanBone = new HumanBone();
                humanBone.humanName = humanBoneName;
                humanBone.boneName  = m_cachedMecanimBoneNameMap[humanBoneName];
                humanBone.limit.useDefaultValues = true;

                humanBones.Add(humanBone);
            }
        }

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

        // Special case: Create the root bone.
        {
            SkeletonBone rootBone = new SkeletonBone();
            rootBone.name     = rootObjectName;
            rootBone.position = Vector3.zero;
            rootBone.rotation = Quaternion.identity;
            rootBone.scale    = Vector3.one;

            skeletonBones.Add(rootBone);
        }

        // Create remaining retargeted bone definitions.
        for (int boneDefIdx = 0; boneDefIdx < m_skeletonDef.Bones.Count; ++boneDefIdx)
        {
            OptitrackSkeletonDefinition.BoneDefinition boneDef = m_skeletonDef.Bones[boneDefIdx];

            SkeletonBone skelBone = new SkeletonBone();
            skelBone.name     = boneDef.Name;
            skelBone.position = boneDef.Offset;
            skelBone.rotation = Quaternion.identity;
            skelBone.scale    = Vector3.one;

            skeletonBones.Add(skelBone);
        }

        // Now set up the HumanDescription for the retargeting source Avatar.
        HumanDescription humanDesc = new HumanDescription();

        humanDesc.human    = humanBones.ToArray();
        humanDesc.skeleton = skeletonBones.ToArray();

        // These all correspond to default values.
        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.0f;
        humanDesc.hasTranslationDoF = false;

        // Finally, take the description and build the Avatar and pose handlers.
        m_srcAvatar = AvatarBuilder.BuildHumanAvatar(m_rootObject, humanDesc);

        if (m_srcAvatar.isValid == false || m_srcAvatar.isHuman == false)
        {
            Debug.LogError(GetType().FullName + ": Unable to create source Avatar for retargeting. Check that your Skeleton Asset Name and Bone Naming Convention are configured correctly.", this);
            this.enabled = false;
            return;
        }

        m_srcPoseHandler  = new HumanPoseHandler(m_srcAvatar, m_rootObject.transform);
        m_destPoseHandler = new HumanPoseHandler(DestinationAvatar, this.transform);
    }
示例#26
0
        public override void PostHook(NodeImporter impoter, Transform trans, VGltf.Types.Node gltfNode)
        {
            if (!GE.ContainsExtensionUsed(impoter.Container.Gltf, AvatarType.ExtensionName))
            {
                return;
            }

            AvatarType extAvatar;

            if (!gltfNode.GetExtension(AvatarType.ExtensionName, out extAvatar))
            {
                return;
            }

            var extHD = extAvatar.HumanDescription;

            var hd = new HumanDescription();

            hd.upperArmTwist = extHD.UpperArmTwist;
            hd.lowerArmTwist = extHD.LowerArmTwist;
            hd.upperLegTwist = extHD.UpperLegTwist;
            hd.lowerLegTwist = extHD.LowerLegTwist;
            hd.armStretch    = extHD.ArmStretch;
            hd.legStretch    = extHD.LegStretch;
            hd.feetSpacing   = extHD.FeetSpacing;

            hd.skeleton = extHD.Skeleton.Select(s =>
            {
                // TODO: Coord
                return(new SkeletonBone
                {
                    name = s.Name,
                    position = PrimitiveImporter.AsVector3(s.Position),
                    rotation = PrimitiveImporter.AsQuaternion(s.Rotation),
                    scale = PrimitiveImporter.AsVector3(s.Scale),
                });
            }).ToArray();

            hd.human = extHD.Human.Select(h =>
            {
                var extLimit = h.Limit;
                var limit    = new HumanLimit
                {
                    useDefaultValues = extLimit.UseDefaultValues,
                    min        = PrimitiveImporter.AsVector3(extLimit.Min),
                    max        = PrimitiveImporter.AsVector3(extLimit.Max),
                    center     = PrimitiveImporter.AsVector3(extLimit.Center),
                    axisLength = extLimit.AxisLength,
                };

                return(new HumanBone
                {
                    boneName = h.BoneName,
                    humanName = h.HumanName,
                    limit = limit,
                });
            }).ToArray();

            var go   = trans.gameObject;
            var anim = go.AddComponent <Animator>();

            anim.avatar = AvatarBuilder.BuildHumanAvatar(go, hd);
        }
示例#27
0
        private static Avatar GetVoxelAvatarInRoot(Transform root)
        {
            var humanBones    = new List <HumanBone>();
            var skeletonBones = new List <SkeletonBone> {
                new SkeletonBone()
                {
                    name     = root.name,
                    position = root.localPosition,
                    rotation = root.localRotation,
                    scale    = root.localScale,
                }
            };

            var rootChild = root.GetChild(0);

            if (rootChild)
            {
                skeletonBones.Add(new SkeletonBone()
                {
                    name     = rootChild.name,
                    position = rootChild.localPosition,
                    rotation = rootChild.localRotation,
                    scale    = rootChild.localScale,
                });
            }

            // Hips
            var hipsTF = LookForHumanBone(root, "Hips", (hips, hipBone, hipSkel) => {
                humanBones.Add(hipBone);
                skeletonBones.Add(hipSkel);

                // Spine
                LookForHumanBone(hips, "Spine", (spine, spineBone, spineSkel) => {
                    humanBones.Add(spineBone);
                    skeletonBones.Add(spineSkel);

                    // Chest
                    LookForHumanBone(spine, "Chest", (chest, chestBone, chestSkel) => {
                        humanBones.Add(chestBone);
                        skeletonBones.Add(chestSkel);

                        // _UpperChest
                        LookForHumanBone(chest, "UpperChest", (upperChest, upperChestBone, upperChestSkel) => {
                            if (upperChest)
                            {
                                humanBones.Add(upperChestBone);
                                skeletonBones.Add(upperChestSkel);
                            }

                            var upperChestRoot = upperChest ? upperChest : chest;



                            // Neck
                            LookForHumanBone(upperChestRoot, "Neck", (neck, neckBone, neckSkel) => {
                                humanBones.Add(neckBone);
                                skeletonBones.Add(neckSkel);

                                // Head
                                LookForHumanBone(neck, "Head", (head, headBone, headSkel) => {
                                    humanBones.Add(headBone);
                                    skeletonBones.Add(headSkel);

                                    // _LeftEye
                                    LookForHumanBone(head, "LeftEye", (leftEye, leftEyeBone, leftEyeSkel) => {
                                        if (leftEye)
                                        {
                                            humanBones.Add(leftEyeBone);
                                            skeletonBones.Add(leftEyeSkel);
                                        }
                                    }, true);

                                    // _RightEye
                                    LookForHumanBone(head, "RightEye", (rightEye, rightEyeBone, rightEyeSkel) => {
                                        if (rightEye)
                                        {
                                            humanBones.Add(rightEyeBone);
                                            skeletonBones.Add(rightEyeSkel);
                                        }
                                    }, true);

                                    // _Jaw
                                    LookForHumanBone(head, "Jaw", (jaw, jawBone, jawSkel) => {
                                        if (jaw)
                                        {
                                            humanBones.Add(jawBone);
                                            skeletonBones.Add(jawSkel);
                                        }
                                    }, true);
                                });
                            });



                            // _LeftShoulder
                            LookForHumanBone(upperChestRoot, "LeftShoulder", (leftShoulder, leftShoulderBone, leftShoulderSkel) => {
                                if (leftShoulder)
                                {
                                    humanBones.Add(leftShoulderBone);
                                    skeletonBones.Add(leftShoulderSkel);
                                }

                                var leftShoulderRoot = leftShoulder ? leftShoulder : upperChestRoot;


                                // LeftUpperArm
                                LookForHumanBone(leftShoulderRoot, "LeftUpperArm", (leftUpperArm, leftUpperArmBone, leftUpperArmSkel) => {
                                    humanBones.Add(leftUpperArmBone);
                                    skeletonBones.Add(leftUpperArmSkel);

                                    // LeftLowerArm
                                    LookForHumanBone(leftUpperArm, "LeftLowerArm", (leftLowerArm, leftLowerArmBone, leftLowerArmSkel) => {
                                        humanBones.Add(leftLowerArmBone);
                                        skeletonBones.Add(leftLowerArmSkel);

                                        // LeftHand
                                        LookForHumanBone(leftLowerArm, "LeftHand", (leftHand, leftHandBone, leftHandSkel) => {
                                            humanBones.Add(leftHandBone);
                                            skeletonBones.Add(leftHandSkel);

                                            // Left Thumb Proximal
                                            LookForHumanBone(leftHand, "Left Thumb Proximal", (leftThumbProximal, leftThumbProximalBone, leftThumbProximalSkel) => {
                                                humanBones.Add(leftThumbProximalBone);
                                                skeletonBones.Add(leftThumbProximalSkel);

                                                // Left Thumb Intermediate
                                                LookForHumanBone(leftThumbProximal, "Left Thumb Intermediate", (leftThumbIntermediate, leftThumbIntermediateBone, leftThumbIntermediateSkel) => {
                                                    humanBones.Add(leftThumbIntermediateBone);
                                                    skeletonBones.Add(leftThumbIntermediateSkel);

                                                    // Left Thumb Distal
                                                    LookForHumanBone(leftThumbIntermediate, "Left Thumb Distal", (leftThumbDistal, leftThumbDistalBone, leftThumbDistalSkel) => {
                                                        humanBones.Add(leftThumbDistalBone);
                                                        skeletonBones.Add(leftThumbDistalSkel);
                                                    });
                                                });
                                            });


                                            // Left Index Proximal
                                            LookForHumanBone(leftHand, "Left Index Proximal", (leftIndexProximal, leftIndexProximalBone, leftIndexProximalSkel) => {
                                                humanBones.Add(leftIndexProximalBone);
                                                skeletonBones.Add(leftIndexProximalSkel);

                                                // Left Index Intermediate
                                                LookForHumanBone(leftIndexProximal, "Left Index Intermediate", (leftIndexIntermediate, leftIndexIntermediateBone, leftIndexIntermediateSkel) => {
                                                    humanBones.Add(leftIndexIntermediateBone);
                                                    skeletonBones.Add(leftIndexIntermediateSkel);

                                                    // Left Index Distal
                                                    LookForHumanBone(leftIndexIntermediate, "Left Index Distal", (leftIndexDistal, leftIndexDistalBone, leftIndexDistalSkel) => {
                                                        humanBones.Add(leftIndexDistalBone);
                                                        skeletonBones.Add(leftIndexDistalSkel);
                                                    });
                                                });
                                            });


                                            // Left Middle Proximal
                                            LookForHumanBone(leftHand, "Left Middle Proximal", (leftMiddleProximal, leftMiddleProximalBone, leftMiddleProximalSkel) => {
                                                humanBones.Add(leftMiddleProximalBone);
                                                skeletonBones.Add(leftMiddleProximalSkel);

                                                // Left Middle Intermediate
                                                LookForHumanBone(leftMiddleProximal, "Left Middle Intermediate", (leftMiddleIntermediate, leftMiddleIntermediateBone, leftMiddleIntermediateSkel) => {
                                                    humanBones.Add(leftMiddleIntermediateBone);
                                                    skeletonBones.Add(leftMiddleIntermediateSkel);

                                                    // Left Middle Distal
                                                    LookForHumanBone(leftMiddleIntermediate, "Left Middle Distal", (leftMiddleDistal, leftMiddleDistalBone, leftMiddleDistalSkel) => {
                                                        humanBones.Add(leftMiddleDistalBone);
                                                        skeletonBones.Add(leftMiddleDistalSkel);
                                                    });
                                                });
                                            });


                                            // Left Ring Proximal
                                            LookForHumanBone(leftHand, "Left Ring Proximal", (leftRingProximal, leftRingProximalBone, leftRingProximalSkel) => {
                                                humanBones.Add(leftRingProximalBone);
                                                skeletonBones.Add(leftRingProximalSkel);

                                                // Left Ring Intermediate
                                                LookForHumanBone(leftRingProximal, "Left Ring Intermediate", (leftRingIntermediate, leftRingIntermediateBone, leftRingIntermediateSkel) => {
                                                    humanBones.Add(leftRingIntermediateBone);
                                                    skeletonBones.Add(leftRingIntermediateSkel);

                                                    // Left Ring Distal
                                                    LookForHumanBone(leftRingIntermediate, "Left Ring Distal", (leftRingDistal, leftRingDistalBone, leftRingDistalSkel) => {
                                                        humanBones.Add(leftRingDistalBone);
                                                        skeletonBones.Add(leftRingDistalSkel);
                                                    });
                                                });
                                            });


                                            // Left Little Proximal
                                            LookForHumanBone(leftHand, "Left Little Proximal", (leftLittleProximal, leftLittleProximalBone, leftLittleProximalSkel) => {
                                                humanBones.Add(leftLittleProximalBone);
                                                skeletonBones.Add(leftLittleProximalSkel);

                                                // Left Little Intermediate
                                                LookForHumanBone(leftLittleProximal, "Left Little Intermediate", (leftLittleIntermediate, leftLittleIntermediateBone, leftLittleIntermediateSkel) => {
                                                    humanBones.Add(leftLittleIntermediateBone);
                                                    skeletonBones.Add(leftLittleIntermediateSkel);

                                                    // Left Little Distal
                                                    LookForHumanBone(leftLittleIntermediate, "Left Little Distal", (leftLittleDistal, leftLittleDistalBone, leftLittleDistalSkel) => {
                                                        humanBones.Add(leftLittleDistalBone);
                                                        skeletonBones.Add(leftLittleDistalSkel);
                                                    });
                                                });
                                            });
                                        });
                                    });
                                });
                            }, true);



                            // _RightShoulder
                            LookForHumanBone(upperChestRoot, "RightShoulder", (leftShoulder, leftShoulderBone, leftShoulderSkel) => {
                                if (leftShoulder)
                                {
                                    humanBones.Add(leftShoulderBone);
                                    skeletonBones.Add(leftShoulderSkel);
                                }

                                var leftShoulderRoot = leftShoulder ? leftShoulder : upperChestRoot;


                                // RightUpperArm
                                LookForHumanBone(leftShoulderRoot, "RightUpperArm", (leftUpperArm, leftUpperArmBone, leftUpperArmSkel) => {
                                    humanBones.Add(leftUpperArmBone);
                                    skeletonBones.Add(leftUpperArmSkel);

                                    // RightLowerArm
                                    LookForHumanBone(leftUpperArm, "RightLowerArm", (leftLowerArm, leftLowerArmBone, leftLowerArmSkel) => {
                                        humanBones.Add(leftLowerArmBone);
                                        skeletonBones.Add(leftLowerArmSkel);

                                        // RightHand
                                        LookForHumanBone(leftLowerArm, "RightHand", (leftHand, leftHandBone, leftHandSkel) => {
                                            humanBones.Add(leftHandBone);
                                            skeletonBones.Add(leftHandSkel);

                                            // Right Thumb Proximal
                                            LookForHumanBone(leftHand, "Right Thumb Proximal", (leftThumbProximal, leftThumbProximalBone, leftThumbProximalSkel) => {
                                                humanBones.Add(leftThumbProximalBone);
                                                skeletonBones.Add(leftThumbProximalSkel);

                                                // Right Thumb Intermediate
                                                LookForHumanBone(leftThumbProximal, "Right Thumb Intermediate", (leftThumbIntermediate, leftThumbIntermediateBone, leftThumbIntermediateSkel) => {
                                                    humanBones.Add(leftThumbIntermediateBone);
                                                    skeletonBones.Add(leftThumbIntermediateSkel);

                                                    // Right Thumb Distal
                                                    LookForHumanBone(leftThumbIntermediate, "Right Thumb Distal", (leftThumbDistal, leftThumbDistalBone, leftThumbDistalSkel) => {
                                                        humanBones.Add(leftThumbDistalBone);
                                                        skeletonBones.Add(leftThumbDistalSkel);
                                                    });
                                                });
                                            });


                                            // Right Index Proximal
                                            LookForHumanBone(leftHand, "Right Index Proximal", (leftIndexProximal, leftIndexProximalBone, leftIndexProximalSkel) => {
                                                humanBones.Add(leftIndexProximalBone);
                                                skeletonBones.Add(leftIndexProximalSkel);

                                                // Right Index Intermediate
                                                LookForHumanBone(leftIndexProximal, "Right Index Intermediate", (leftIndexIntermediate, leftIndexIntermediateBone, leftIndexIntermediateSkel) => {
                                                    humanBones.Add(leftIndexIntermediateBone);
                                                    skeletonBones.Add(leftIndexIntermediateSkel);

                                                    // Right Index Distal
                                                    LookForHumanBone(leftIndexIntermediate, "Right Index Distal", (leftIndexDistal, leftIndexDistalBone, leftIndexDistalSkel) => {
                                                        humanBones.Add(leftIndexDistalBone);
                                                        skeletonBones.Add(leftIndexDistalSkel);
                                                    });
                                                });
                                            });


                                            // Right Middle Proximal
                                            LookForHumanBone(leftHand, "Right Middle Proximal", (leftMiddleProximal, leftMiddleProximalBone, leftMiddleProximalSkel) => {
                                                humanBones.Add(leftMiddleProximalBone);
                                                skeletonBones.Add(leftMiddleProximalSkel);

                                                // Right Middle Intermediate
                                                LookForHumanBone(leftMiddleProximal, "Right Middle Intermediate", (leftMiddleIntermediate, leftMiddleIntermediateBone, leftMiddleIntermediateSkel) => {
                                                    humanBones.Add(leftMiddleIntermediateBone);
                                                    skeletonBones.Add(leftMiddleIntermediateSkel);

                                                    // Right Middle Distal
                                                    LookForHumanBone(leftMiddleIntermediate, "Right Middle Distal", (leftMiddleDistal, leftMiddleDistalBone, leftMiddleDistalSkel) => {
                                                        humanBones.Add(leftMiddleDistalBone);
                                                        skeletonBones.Add(leftMiddleDistalSkel);
                                                    });
                                                });
                                            });


                                            // Right Ring Proximal
                                            LookForHumanBone(leftHand, "Right Ring Proximal", (leftRingProximal, leftRingProximalBone, leftRingProximalSkel) => {
                                                humanBones.Add(leftRingProximalBone);
                                                skeletonBones.Add(leftRingProximalSkel);

                                                // Right Ring Intermediate
                                                LookForHumanBone(leftRingProximal, "Right Ring Intermediate", (leftRingIntermediate, leftRingIntermediateBone, leftRingIntermediateSkel) => {
                                                    humanBones.Add(leftRingIntermediateBone);
                                                    skeletonBones.Add(leftRingIntermediateSkel);

                                                    // Right Ring Distal
                                                    LookForHumanBone(leftRingIntermediate, "Right Ring Distal", (leftRingDistal, leftRingDistalBone, leftRingDistalSkel) => {
                                                        humanBones.Add(leftRingDistalBone);
                                                        skeletonBones.Add(leftRingDistalSkel);
                                                    });
                                                });
                                            });


                                            // Right Little Proximal
                                            LookForHumanBone(leftHand, "Right Little Proximal", (leftLittleProximal, leftLittleProximalBone, leftLittleProximalSkel) => {
                                                humanBones.Add(leftLittleProximalBone);
                                                skeletonBones.Add(leftLittleProximalSkel);

                                                // Right Little Intermediate
                                                LookForHumanBone(leftLittleProximal, "Right Little Intermediate", (leftLittleIntermediate, leftLittleIntermediateBone, leftLittleIntermediateSkel) => {
                                                    humanBones.Add(leftLittleIntermediateBone);
                                                    skeletonBones.Add(leftLittleIntermediateSkel);

                                                    // Right Little Distal
                                                    LookForHumanBone(leftLittleIntermediate, "Right Little Distal", (leftLittleDistal, leftLittleDistalBone, leftLittleDistalSkel) => {
                                                        humanBones.Add(leftLittleDistalBone);
                                                        skeletonBones.Add(leftLittleDistalSkel);
                                                    });
                                                });
                                            });
                                        });
                                    });
                                });
                            }, true);
                        }, true);
                    });
                });

                // LeftUpperLeg
                LookForHumanBone(hips, "LeftUpperLeg", (leftUpperLeg, leftUpperLegBone, leftUpperLegSkel) => {
                    humanBones.Add(leftUpperLegBone);
                    skeletonBones.Add(leftUpperLegSkel);

                    // LeftLowerLeg
                    LookForHumanBone(leftUpperLeg, "LeftLowerLeg", (leftLowerLeg, leftLowerLegBone, leftLowerLegSkel) => {
                        humanBones.Add(leftLowerLegBone);
                        skeletonBones.Add(leftLowerLegSkel);

                        // LeftFoot
                        LookForHumanBone(leftLowerLeg, "LeftFoot", (leftFoot, leftFootBone, leftFootSkel) => {
                            humanBones.Add(leftFootBone);
                            skeletonBones.Add(leftFootSkel);

                            // _LeftToes
                            LookForHumanBone(leftFoot, "LeftToes", (leftToes, leftToesBone, leftToesSkel) => {
                                humanBones.Add(leftToesBone);
                                skeletonBones.Add(leftToesSkel);
                            });
                        });
                    });
                });

                // RightUpperLeg
                LookForHumanBone(hips, "RightUpperLeg", (leftUpperLeg, leftUpperLegBone, leftUpperLegSkel) => {
                    humanBones.Add(leftUpperLegBone);
                    skeletonBones.Add(leftUpperLegSkel);

                    // RightLowerLeg
                    LookForHumanBone(leftUpperLeg, "RightLowerLeg", (leftLowerLeg, leftLowerLegBone, leftLowerLegSkel) => {
                        humanBones.Add(leftLowerLegBone);
                        skeletonBones.Add(leftLowerLegSkel);

                        // RightFoot
                        LookForHumanBone(leftLowerLeg, "RightFoot", (leftFoot, leftFootBone, leftFootSkel) => {
                            humanBones.Add(leftFootBone);
                            skeletonBones.Add(leftFootSkel);

                            // _RightToes
                            LookForHumanBone(leftFoot, "RightToes", (leftToes, leftToesBone, leftToesSkel) => {
                                humanBones.Add(leftToesBone);
                                skeletonBones.Add(leftToesSkel);
                            });
                        });
                    });
                });
            });

            if (hipsTF)
            {
                var avatar = AvatarBuilder.BuildHumanAvatar(root.gameObject, new HumanDescription()
                {
                    human             = humanBones.ToArray(),
                    skeleton          = skeletonBones.ToArray(),
                    lowerArmTwist     = 0,
                    upperArmTwist     = 0,
                    upperLegTwist     = 0,
                    lowerLegTwist     = 0,
                    armStretch        = 0,
                    legStretch        = 0,
                    feetSpacing       = 0,
                    hasTranslationDoF = false,
                });
                avatar.name = "Avatar";
                return(avatar);
            }
            else
            {
                return(null);
            }
        }
示例#28
0
    // Use this for initialization
    void Start()
    {
        if (animator == null)
        {
            animator = GetComponent <Animator>();
        }


        bones  = new List <HumanBone>();
        sbones = new List <SkeletonBone>();

        HumanDescription desc = new HumanDescription();

        desc.armStretch    = armStretch;
        desc.feetSpacing   = feetSpacing;
        desc.legStretch    = legStretch;
        desc.lowerArmTwist = lowerArmTwist;
        desc.lowerLegTwist = lowerLegTwist;
        desc.upperArmTwist = upperArmTwist;
        desc.upperLegTwist = upperLegTwist;

        AddBone("Hips", hips);
        AddBone("LeftUpperLeg", leftUpperLeg);
        AddBone("RightUpperLeg", rightUpperLeg);

        AddBone("LeftLowerLeg", leftLowerLeg);
        AddBone("RightLowerLeg", rightLowerLeg);

        AddBone("LeftFoot", leftFoot);
        AddBone("RightFoot", rightFoot);


        AddBone("Spine", spine);

        if (chest != null)
        {
            AddBone("Chest", chest);
        }

        if (neck != null)
        {
            AddBone("Neck", neck);
        }

        AddBone("Head", head);


        if (leftShoulder != null)
        {
            AddBone("LeftShoulder", leftShoulder);
        }
        AddBone("LeftUpperArm", leftUpperArm);

        if (rightShoulder != null)
        {
            AddBone("RightShoulder", rightShoulder);
        }
        AddBone("RightUpperArm", rightUpperArm);



        AddBone("LeftLowerArm", leftLowerArm);
        AddBone("RightLowerArm", rightLowerArm);



        AddBone("LeftHand", leftHand);
        AddBone("RightHand", rightHand);

        AddBone("Root", transform);


        desc.human    = bones.ToArray();
        desc.skeleton = sbones.ToArray();

        Avatar avatar = AvatarBuilder.BuildHumanAvatar(gameObject, desc);

        avatar.name = "Skeletor Auto Avatar";

        animator.avatar = avatar;
    }
    static void CreateNewAvatar()
    {
        UnityEngine.GameObject o = Selection.activeGameObject;

        System.Collections.Generic.Dictionary <string, string> boneName = new System.Collections.Generic.Dictionary <string, string>();
        boneName["Chest"]         = "Neck_Root";
        boneName["Head"]          = "Head_Root";
        boneName["Hips"]          = "Hips";
        boneName["LeftFoot"]      = "Back_Foot";
        boneName["LeftHand"]      = "Back_Hand";
        boneName["LeftLowerArm"]  = "Back_Wrist";
        boneName["LeftLowerLeg"]  = "Back_Ankle";
        boneName["LeftShoulder"]  = "Back_Shoulder_Root";
        boneName["LeftUpperArm"]  = "Back_Elbow";
        boneName["LeftUpperLeg"]  = "Back_Knee";
        boneName["RightFoot"]     = "Front_Foot";
        boneName["RightHand"]     = "Front_Hand";
        boneName["RightLowerArm"] = "Front_Wrist";
        boneName["RightLowerLeg"] = "Front_Ankle";
        boneName["RightShoulder"] = "Front_Shoulder_Root";
        boneName["RightUpperArm"] = "Front_Elbow";
        boneName["RightUpperLeg"] = "Front_Knee";
        boneName["Spine"]         = "Center_Spine";

        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++;
        }

        HumanDescription hd = new HumanDescription();

        hd.human = humanBones;

        Transform[] t = o.GetComponentsInChildren <Transform> ();

        SkeletonBone[] bones = new SkeletonBone[t.Length];

        for (int b = 0; b < t.Length; b++)
        {
            bones [b]          = new SkeletonBone();
            bones [b].name     = t [b].name;
            bones [b].position = t [b].localPosition;
            bones [b].rotation = t [b].localRotation;
            bones [b].scale    = t [b].localScale;
        }

        hd.skeleton = bones;

        Avatar a = AvatarBuilder.BuildHumanAvatar(o, hd);

        AssetDatabase.CreateAsset(a, "Assets/" + o.name + "_human.asset");
    }
示例#30
0
    /*
     *
     * Convert Meshes
     */
    public Dictionary <long, Mesh> ConvertMeshes(AMF amf, Dictionary <string, Material> mats, Dictionary <string, AMFShaderInfo> matHelpers, GameObject root)
    {
        //List<Mesh> meshList = new List<Mesh>();
        Dictionary <long, Mesh> meshCache = new Dictionary <long, Mesh>();
        float             meshComplete    = 0;
        float             totalMeshCount  = 0;
        List <GameObject> meshNodes       = new List <GameObject>();
        List <Transform>  nodes           = null;

        if (CreateSkinnedMeshes)
        {
            nodes           = CreateRigging(amf);
            nodes[0].parent = root.transform;
            Animator anim = root.AddComponent <Animator>();
            //Transform rigRoot=root.GetComponentInChildren<SkinnedMeshRenderer>().rootBone;
            if (copyAvatar)
            {
                //ctx.AddObjectToAsset(m_LastHumanDescriptionAvatarSource.name,m_LastHumanDescriptionAvatarSource);
                anim.avatar = m_LastHumanDescriptionAvatarSource;
            }
            else
            {
                //EditorUtility.DisplayProgressBar("Parsing "+ctx.assetPath,"Creating Avatar",(5f/5f));
                List <string>    reports = new List <string>();
                HumanDescription hd      = new HumanDescription();
                AvatarSetupTool.SkeletonBone[] skeletonBones;
                bool hasTranslationDOF;
                reports = AvatarSetupTool.SetupHumanSkeleton(nodes[0].parent.gameObject, ref hd.human, out skeletonBones, out hasTranslationDOF);
                hd.hasTranslationDoF = hasTranslationDOF;
                SkeletonBone[] sb = new SkeletonBone[skeletonBones.Length + 1];
                Array.Copy(Array.ConvertAll(skeletonBones, (p => (SkeletonBone)p)), sb, sb.Length - 1);
                sb[sb.Length - 1].name     = nodes[0].parent.name;
                sb[sb.Length - 1].position = nodes[0].parent.localPosition;
                sb[sb.Length - 1].rotation = nodes[0].parent.localRotation;
                sb[sb.Length - 1].scale    = nodes[0].parent.localScale;
                hd.skeleton = sb;
                Avatar a;
                if (rigType == RigType.Humanoid)
                {
                    a = AvatarBuilder.BuildHumanAvatar(nodes[0].parent.gameObject, hd);
                }
                else
                {
                    a = AvatarBuilder.BuildGenericAvatar(nodes[0].parent.gameObject, nodes[0].parent.name);
                }
                a.name = root.name + "Avatar";
                //ctx.AddObjectToAsset(a.name,a);
                anim.avatar = a;
            }
        }


        foreach (AMF_RegionInfo ri in amf.regionInfo)
        {
            totalMeshCount += ri.permutations.Count;
        }

        for (int ri = 0; ri < amf.regionInfo.Count; ri++)
        {
            GameObject riNode = new GameObject(amf.regionInfo[ri].name);
            GameObjectUtility.SetParentAndAlign(riNode, root);
            foreach (AMF_Permutations perm in amf.regionInfo[ri].permutations)
            {
                EditorUtility.DisplayProgressBar("Creating Meshes", perm.pName, (meshComplete / totalMeshCount));
                Mesh temp;
                if (createDuplicateInstances || !meshCache.ContainsKey(perm.vAddress))
                {
                    temp = ConvertInstanceToMesh(perm);
                    //we have to flip the normals due to the coordinate system translation
                    temp.FlipNormals();
                    temp.RecalculateNormals();
                    if (GenerateLightmapUVs)
                    {
                        EditorUtility.DisplayProgressBar("Generating Lightmap UVs", perm.pName, (meshComplete / totalMeshCount));
                        uvSettings.angleError = angleError;
                        uvSettings.areaError  = areaError;
                        uvSettings.hardAngle  = hardAngle;
                        uvSettings.packMargin = packMargin;
                        Unwrapping.GenerateSecondaryUVSet(temp, uvSettings);
                    }
                    meshCache.Add(perm.vAddress, temp);
                }
                else
                {
                    temp = meshCache[perm.vAddress];
                }
                GameObject meshNode = new GameObject(perm.pName);
                Matrix4x4  matr     = Matrix4x4.identity;
                if (!float.IsNaN(perm.mult))
                {
                    Matrix4x4 scalerM = new Matrix4x4();
                    scalerM.SetRow(0, new Vector4(100f * m_FileScaleFactor, 0));
                    scalerM.SetRow(1, new Vector4(0, 100f * m_FileScaleFactor));
                    scalerM.SetRow(2, new Vector4(0, 0, 100f * m_FileScaleFactor));
                    scalerM.SetRow(3, new Vector4(0, 0, 0, 1));
                    matr.SetRow(0, new Vector4(perm.mult, 0));
                    matr.SetRow(1, new Vector4(0, perm.mult));
                    matr.SetRow(2, new Vector4(0, 0, perm.mult));
                    matr.SetRow(3, new Vector4(0, 0, 0, 1));
                    matr *= perm.matrix4x4;
                    matr *= scalerM;
                    Matrix4x4 unityMatr = matr.Convert3DSMatrixToUnity();
                    meshNode.transform.localScale    = unityMatr.ExtractScale();
                    meshNode.transform.localRotation = unityMatr.GetRotation();
                    meshNode.transform.localPosition = unityMatr.ExtractPosition();
                }
                else
                {
                    meshNode.transform.localScale = new Vector3(m_FileScaleFactor, m_FileScaleFactor, m_FileScaleFactor);
                }

                //GameObjectUtility.SetParentAndAlign(meshNode,riNode);

                //meshNode.transform.localToWorldMatrix=matr;


                Renderer mr;
                if (temp.boneWeights.Length > 0 && CreateSkinnedMeshes)
                {
                    mr = meshNode.AddComponent <SkinnedMeshRenderer>();
                    meshNode.transform.localRotation = Quaternion.Euler(0, 90, 0);
                    Matrix4x4[] bindPoses = new Matrix4x4[nodes.Count];
                    for (int m = 0; m < bindPoses.Length; m++)
                    {
                        bindPoses[m] = nodes[m].worldToLocalMatrix * meshNode.transform.localToWorldMatrix;
                    }
                    temp.bindposes = bindPoses;
                    ((SkinnedMeshRenderer)mr).sharedMesh = temp;
                    ((SkinnedMeshRenderer)mr).bones      = nodes.ToArray();
                    ((SkinnedMeshRenderer)mr).rootBone   = nodes[0];
                }
                else
                {
                    MeshFilter mf = meshNode.AddComponent <MeshFilter>();
                    mf.sharedMesh = temp;
                    mr            = meshNode.AddComponent <MeshRenderer>();
                    if (RecenterPivots && !splitSubmeshes)
                    {
                        //for safety, lets guard this against splitting submeshes.
                        mf.RecenterPivot();
                    }
                }


                meshNode.transform.parent = riNode.transform;
                if (GenerateMeshCollidersOnClusters && amf.regionInfo[ri].name.Equals("Clusters"))
                {
                    MeshCollider mc = meshNode.AddComponent <MeshCollider>();
                    mc.sharedMesh = temp;
                }
                Material[]           materials = new Material[temp.subMeshCount];
                List <AMFShaderInfo> si        = new List <AMFShaderInfo>();
                for (int i = 0; i < materials.Length; i++)
                {
                    materials[i] = mats[amf.shaderInfos[perm.meshes[i].shaderIndex].sName];
                    si.Add(matHelpers[amf.shaderInfos[perm.meshes[i].shaderIndex].sName]);
                    //si[i].SaveData(amf.shaderInfos[perm.meshes[i].shaderIndex]);
                }
                mr.sharedMaterials = materials;



                AMFMaterialHelper mh = meshNode.AddComponent <AMFMaterialHelper>();
                mh.shaderSettings = si;

                //mh.SaveData(amf.shaderInfos[perm.meshes[0].shaderIndex]);
                //Debug.LogFormat("Transform: Pos:{0} Rot:{1} Scale:{2}",perm.matrix4x4.ExtractPosition(),perm.matrix4x4.ExtractRotation(),perm.matrix4x4.ExtractScale());
                meshComplete++;
                meshNodes.Add(meshNode);
            }
        }

        //This is annoying to do this here, but we have to wait until after the mesh cache is fully populated before we start splitting submeshes out.
        if (splitSubmeshes)
        {
            meshCache.Clear();
            long fakeKey = 0;
            foreach (GameObject go in meshNodes)
            {
                MeshFilter mf = go.GetComponent <MeshFilter>();
                if (mf != null && mf.sharedMesh.subMeshCount > 1)
                {
                    Renderer r = go.GetComponent <MeshRenderer>();
                    for (int i = 0; i < mf.sharedMesh.subMeshCount; i++)
                    {
                        int        matIndex = Mathf.Min(i, r.sharedMaterials.Length);
                        GameObject tempGo   = new GameObject(go.name + "_" + r.sharedMaterials[matIndex].name);
                        MeshFilter tempMF   = tempGo.AddComponent <MeshFilter>();
                        tempMF.sharedMesh = mf.sharedMesh.ExtractSubmesh(i);

                        tempGo.AddComponent <MeshRenderer>().sharedMaterial = r.sharedMaterials[matIndex];
                        GameObjectUtility.SetParentAndAlign(tempGo, go);
                        if (RecenterPivots)
                        {
                            tempMF.RecenterPivot();
                        }
                        meshCache.Add(fakeKey, tempGo.GetComponent <MeshFilter>().sharedMesh);
                        fakeKey++;
                    }
                    DestroyImmediate(mf);
                    DestroyImmediate(r);
                }
                else
                {
                    if (RecenterPivots)
                    {
                        go.GetComponent <MeshFilter>().RecenterPivot();
                    }
                    meshCache.Add(fakeKey, go.GetComponent <MeshFilter>().sharedMesh);
                    fakeKey++;
                }
            }
        }

        return(meshCache);
    }