add Physics support

This commit is contained in:
1605296300@qq.com
2022-08-10 16:54:20 +08:00
parent 33c8d35c84
commit f797fbb2fd
855 changed files with 649609 additions and 98 deletions
@@ -0,0 +1,63 @@
using UnityEditor;
using UnityEngine;
namespace RootMotion.Dynamics {
// Custom drawer for BehaviourPuppet MasterProps.
[CustomPropertyDrawer (typeof (BehaviourPuppet.MasterProps))]
public class BehaviourPuppetMasterPropsDrawer : PropertyDrawer {
private float lineHeight = 22f;
public override float GetPropertyHeight(SerializedProperty prop, GUIContent label) {
lineHeight = base.GetPropertyHeight(prop, label);
int enumValueIndex = prop.FindPropertyRelative("normalMode").enumValueIndex;
switch(enumValueIndex) {
case 1: return lineHeight * 2;
case 2: return lineHeight * 3;
default: return lineHeight;
}
}
private void NextLine(ref Rect pos) {
pos = EditorGUI.IndentedRect(pos);
pos.width -= pos.x - pos.x;
pos.x = pos.x;
pos.y += lineHeight;
pos.height = lineHeight;
}
public override void OnGUI (Rect pos, SerializedProperty prop, GUIContent label) {
int indent = EditorGUI.indentLevel;
EditorGUI.indentLevel = 0;
EditorGUI.BeginChangeCheck();
EditorGUI.PropertyField (new Rect(pos.x, pos.y, pos.width, lineHeight), prop.FindPropertyRelative ("normalMode"), new GUIContent("Normal Mode", "Active mode keeps the puppet and it's mapping active at all times. " +
"Unmapped mode blends in mapping only if the puppet becomes in contact with something and blends out again later to maintain 100% animation accuracy while not in contact. " +
"If Kinematic, will set the PuppetMaster.mode to Active when any of the muscles collides with something (static colliders are ignored if 'Activate On Static Collisions' is false) or is hit. PuppetMaster.mode will be set to Kinematic when all muscles are pinned and the puppet is in normal Puppet state. This will increase performance and enable you to have full animation accuracy when PuppetMaster is not needed. Note that collision events are only broadcasted if one of the Rigidbodies is not kinematic, so if you need 2 characters to wake up each other, one has to be active."));
int enumValueIndex = prop.FindPropertyRelative("normalMode").enumValueIndex;
switch(enumValueIndex) {
case 1:
NextLine(ref pos);
EditorGUI.PropertyField (pos, prop.FindPropertyRelative ("mappingBlendSpeed"), new GUIContent("Mapping Blend Speed", "The speed of blending in mapping in case of contact."));
break;
case 2:
NextLine(ref pos);
EditorGUI.PropertyField (pos, prop.FindPropertyRelative ("activateOnStaticCollisions"), new GUIContent("Activate On Static Collisions", "The speed of blending in mapping in case of contact."));
NextLine(ref pos);
EditorGUI.PropertyField (pos, prop.FindPropertyRelative ("activateOnImpulse"), new GUIContent("Activate On Impulse", "Minimum collision impulse for activating the puppet."));
break;
default: break;
}
EditorGUI.EndChangeCheck();
EditorGUI.indentLevel = indent;
}
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 78a5ae1e71291429f8916d4c02a498b7
timeCreated: 1452015016
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,254 @@
using UnityEngine;
using System.Collections;
using UnityEditor;
namespace RootMotion.Dynamics
{
[CustomEditor(typeof(PropMuscle))]
public class PropMuscleInspector : Editor
{
private PropMuscle script { get { return target as PropMuscle; } }
private GUIStyle style = new GUIStyle();
private GUIStyle miniLabelStyle = new GUIStyle();
private static Color pro = new Color(0.5f, 0.7f, 0.3f, 1f);
private static Color free = new Color(0.2f, 0.3f, 0.1f, 1f);
private static Color sceneColor = new Color(0.2f, 0.7f, 1f);
public override void OnInspectorGUI()
{
if (script == null) return;
serializedObject.Update();
style.wordWrap = true;
style.normal.textColor = EditorGUIUtility.isProSkin ? pro : free;
miniLabelStyle.wordWrap = true;
miniLabelStyle.fontSize = 10;
miniLabelStyle.normal.textColor = EditorStyles.miniLabel.normal.textColor;
if (!Application.isPlaying)
{
if (GUILayout.Button("Remove This Prop Muscle"))
{
//int index = script.muscle.index;
//Debug.Log(index);
var puppetMasterS = new SerializedObject(script.puppetMaster);
SerializedProperty muscles = puppetMasterS.FindProperty("muscles");
int index = 0;
ConfigurableJoint joint = script.GetComponent<ConfigurableJoint>();
for (int i = 0; i < puppetMasterS.FindProperty("muscles").arraySize; i++)
{
muscles.GetArrayElementAtIndex(i).FindPropertyRelative("index").intValue = i;
if (muscles.GetArrayElementAtIndex(i).FindPropertyRelative("joint").objectReferenceValue == joint) index = i;
}
/*
if (script.muscle.additionalPin != null)
{
script.muscle.additionalPin.gameObject.hideFlags = HideFlags.None;
script.muscle.additionalPinTarget.gameObject.hideFlags = HideFlags.None;
}
script.muscle.target.gameObject.hideFlags = HideFlags.None;
*/
var target = script.muscle.target;
muscles.DeleteArrayElementAtIndex(index);
for (int i = 0; i < puppetMasterS.FindProperty("muscles").arraySize; i++)
{
muscles.GetArrayElementAtIndex(i).FindPropertyRelative("index").intValue = i;
}
puppetMasterS.ApplyModifiedProperties();
PuppetMasterInspector.DestroyImmediateSafe(target.gameObject);
PuppetMasterInspector.DestroyImmediateSafe(script.gameObject);
return;
}
}
DrawDefaultInspector();
//GUILayout.Space(10);
if (!Application.isPlaying)
{
if (script.muscle.additionalPin == null)
{
if (GUILayout.Button("Add Additional Pin"))
{
AddAdditionalPin();
}
}
else
{
if (GUILayout.Button("Remove Additional Pin"))
{
RemoveAdditionalPin();
}
}
EditorGUILayout.LabelField("Additional Pins help to pin this prop muscle to animation from another point. Without it, the prop muscle would be actuated by Muscle Spring only, which is likely not enough to follow fast swinging animations. Move the additional pin by 'Additional Pin Offset' towards the end of the prop (tip of the sword).", miniLabelStyle);
}
serializedObject.ApplyModifiedProperties();
}
private bool AddAdditionalPin()
{
if (script.muscle.additionalPin != null) return false;
ConfigurableJoint additionalJoint = null;
Transform additionalTarget = null;
AddAdditionalPinUnserialized(script, out additionalJoint, out additionalTarget);
var puppetMasterS = new SerializedObject(script.puppetMaster);
puppetMasterS.FindProperty("muscles").GetArrayElementAtIndex(script.muscle.index).FindPropertyRelative("additionalPin").objectReferenceValue = additionalJoint;
puppetMasterS.FindProperty("muscles").GetArrayElementAtIndex(script.muscle.index).FindPropertyRelative("additionalPinTarget").objectReferenceValue = additionalTarget;
puppetMasterS.ApplyModifiedProperties();
serializedObject.ApplyModifiedProperties();
//muscle.additionalPin.gameObject.hideFlags = HideFlags.HideInHierarchy;
//muscle.additionalPinTarget.gameObject.hideFlags = HideFlags.HideInHierarchy;
return true;
}
public static void AddAdditionalPinUnserialized(PropMuscle script, out ConfigurableJoint joint, out Transform target)
{
var addGO = new GameObject("Additional Pin");
addGO.gameObject.layer = script.gameObject.layer;
addGO.transform.parent = script.transform;
addGO.transform.localPosition = script.additionalPinOffset;
addGO.transform.localRotation = Quaternion.identity;
//script.lastAdditionalPinOffset = additionalPinOffset;
addGO.AddComponent<Rigidbody>();
joint = addGO.AddComponent<ConfigurableJoint>();
joint.connectedBody = script.muscle.joint.GetComponent<Rigidbody>();
joint.autoConfigureConnectedAnchor = false;
joint.connectedAnchor = script.additionalPinOffset;
joint.xMotion = ConfigurableJointMotion.Locked;
joint.yMotion = ConfigurableJointMotion.Locked;
joint.zMotion = ConfigurableJointMotion.Locked;
joint.angularXMotion = ConfigurableJointMotion.Locked;
joint.angularYMotion = ConfigurableJointMotion.Locked;
joint.angularZMotion = ConfigurableJointMotion.Locked;
var addTargetGO = new GameObject("Additional Pin Target");
addTargetGO.layer = script.muscle.target.gameObject.layer;
addTargetGO.transform.parent = script.muscle.target;
addTargetGO.transform.position = addGO.transform.position;
addTargetGO.transform.rotation = addGO.transform.rotation;
target = addTargetGO.transform;
}
private bool RemoveAdditionalPin()
{
if (script.muscle.additionalPin == null) return false;
//script.muscle.additionalPin.gameObject.hideFlags = HideFlags.None;
//script.muscle.additionalPinTarget.gameObject.hideFlags = HideFlags.None;
PuppetMasterInspector.DestroyImmediateSafe(script.muscle.additionalPin.gameObject);
PuppetMasterInspector.DestroyImmediateSafe(script.muscle.additionalPinTarget.gameObject);
var puppetMasterS = new SerializedObject(script.puppetMaster);
puppetMasterS.FindProperty("muscles").GetArrayElementAtIndex(script.muscle.index).FindPropertyRelative("additionalPin").objectReferenceValue = null;
puppetMasterS.FindProperty("muscles").GetArrayElementAtIndex(script.muscle.index).FindPropertyRelative("additionalPinTarget").objectReferenceValue = null;
puppetMasterS.ApplyModifiedProperties();
return true;
}
private static float GetHandleSize(Vector3 position)
{
float s = HandleUtility.GetHandleSize(position) * 0.1f;
return Mathf.Lerp(s, 0.025f, 0.2f);
}
void OnSceneGUI() {
DrawScene(script);
}
private static void CubeCapSafe(Vector3 position, Quaternion rotation, float size)
{
#if UNITY_5_6_OR_NEWER
Handles.CubeHandleCap(0, position, rotation, size, EventType.Repaint);
#else
Handles.CubeCap(0, position, rotation, size);
#endif
}
private static void SphereCapSafe(Vector3 position, Quaternion rotation, float size)
{
#if UNITY_5_6_OR_NEWER
Handles.SphereHandleCap(0, position, rotation, size, EventType.Repaint);
#else
Handles.SphereCap(0, position, rotation, size);
#endif
}
public static void DrawScene(PropMuscle script)
{
if (script == null) return;
if (Application.isPlaying) return;
GUIStyle sceneLabelStyle = new GUIStyle();
sceneLabelStyle.wordWrap = false;
sceneLabelStyle.normal.textColor = sceneColor;
Handles.color = sceneColor;
float size = GetHandleSize(script.transform.position);
if (Selection.activeGameObject == script.gameObject)
{
Handles.Label(script.transform.position + script.transform.forward * size * 2f, new GUIContent(script.transform.name), sceneLabelStyle);
} else
{
Handles.Label(script.transform.position + script.transform.forward * size * 2f, new GUIContent("Click to select Prop Muscle"), sceneLabelStyle);
}
if (Selection.activeGameObject == script.gameObject)
{
CubeCapSafe(script.transform.position, script.transform.rotation, size * 2f);
} else
{
if (DotButton(script.transform.position, script.transform.rotation, size, size))
{
Selection.activeGameObject = script.gameObject;
}
}
if (script.muscle.additionalPin != null)
{
Handles.DrawLine(script.transform.position, script.muscle.additionalPin.transform.position);
SphereCapSafe(script.muscle.additionalPin.transform.position, script.muscle.additionalPin.transform.rotation, size);
if (Selection.activeGameObject == script.gameObject)
{
Handles.Label(script.muscle.additionalPin.transform.position + script.transform.forward * size * 2f, new GUIContent("Additional Pin"), sceneLabelStyle);
}
}
Handles.color = Color.white;
}
public static bool DotButton(Vector3 position, Quaternion direction, float size, float pickSize)
{
#if UNITY_5_6_OR_NEWER
return Handles.Button(position, direction, size, pickSize, Handles.DotHandleCap);
#else
return Handles.Button(position, direction, size, pickSize, Handles.DotCap);
#endif
}
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 2d0583daa68217f49b271ee02c9374f5
timeCreated: 1550562021
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,21 @@
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
namespace RootMotion.Dynamics {
[CustomEditor(typeof(PuppetMasterHumanoidConfig))]
public class PuppetMasterHumanoidConfigInspector : Editor {
private PuppetMasterHumanoidConfig script { get { return target as PuppetMasterHumanoidConfig; } }
public override void OnInspectorGUI() {
foreach (PuppetMasterHumanoidConfig.HumanoidMuscle m in script.muscles) {
m.name = m.bone.ToString();
}
DrawDefaultInspector ();
}
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: f97a5dd098e6d624caf82f29ed6896d2
timeCreated: 1485252527
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,437 @@
using UnityEngine;
using UnityEditor;
using System.Collections;
using System;
namespace RootMotion.Dynamics
{
[CustomEditor(typeof(PuppetMaster))]
public class PuppetMasterInspector : Editor
{
private PuppetMaster script { get { return target as PuppetMaster; } }
private Transform animatedCharacter;
private bool isValid;
private int characterControllerLayer = 8;
private int ragdollLayer = 9;
private ConfigurableJoint addPropMuscleTo;
private MonoScript monoScript;
private Animator targetAnimator;
private SkinnedMeshRenderer[] skinnedMeshRenderers = new SkinnedMeshRenderer[0];
// Colors
private GUIStyle style = new GUIStyle();
private GUIStyle miniLabelStyle = new GUIStyle();
private static Color pro = new Color(0.5f, 0.7f, 0.3f, 1f);
private static Color free = new Color(0.2f, 0.3f, 0.1f, 1f);
#region Inspector
void OnEnable()
{
if (!Application.isPlaying)
{
monoScript = MonoScript.FromMonoBehaviour(script);
int currentExecutionOrder = MonoImporter.GetExecutionOrder(monoScript);
if (currentExecutionOrder != 10100) MonoImporter.SetExecutionOrder(monoScript, 10100);
// Fix negative collider sizes for ragdolls created before PuppetMaster 0.3
BoxCollider[] boxColliders = script.GetComponentsInChildren<BoxCollider>();
foreach (BoxCollider box in boxColliders)
{
box.size = new Vector3(Mathf.Abs(box.size.x), Mathf.Abs(box.size.y), Mathf.Abs(box.size.z));
}
CapsuleCollider[] capsuleColliders = script.GetComponentsInChildren<CapsuleCollider>();
foreach (CapsuleCollider capsule in capsuleColliders)
{
capsule.height = Mathf.Abs(capsule.height);
capsule.radius = Mathf.Abs(capsule.radius);
}
if (script.transform.parent != null)
{
targetAnimator = script.transform.parent.GetComponentInChildren<Animator>();
}
}
else
{
if (script.initiated) targetAnimator = script.targetAnimator;
}
if (script.transform.parent != null)
{
skinnedMeshRenderers = script.transform.parent.GetComponentsInChildren<SkinnedMeshRenderer>();
}
isValid = IsValid();
}
private bool IsValid()
{
if (script.muscles.Length > 0) return true;
ConfigurableJoint[] joints = script.gameObject.GetComponentsInChildren<ConfigurableJoint>();
if (joints == null || joints.Length == 0)
{
return false;
}
if (animatedCharacter == null) animatedCharacter = script.transform;
return true;
}
public override void OnInspectorGUI()
{
if (script == null) return;
serializedObject.Update();
if (script.muscles.Length > 0 && script.muscles[0].target != null && script.targetRoot == null) script.targetRoot = script.FindTargetRootRecursive(script.muscles[0].target);
style.wordWrap = true;
style.normal.textColor = EditorGUIUtility.isProSkin ? pro : free;
miniLabelStyle.wordWrap = true;
miniLabelStyle.fontSize = 10;
miniLabelStyle.normal.textColor = EditorStyles.miniLabel.normal.textColor;
if (!isValid)
{
EditorGUILayout.Space();
EditorGUILayout.LabelField(
"To set up PuppetMaster, add the component to a ragdoll character that is built with ConfigurableJoints. " +
"If your ragdoll uses other types of joints, you can easily convert them by selecting the character and clicking on GameObject/Convert To ConfigurableJoints."
, style);
EditorGUILayout.Space();
return;
}
if (!Application.isPlaying)
{
for (int i = 0; i < script.muscles.Length; i++)
{
script.muscles[i].index = i;
}
}
foreach (Muscle m in script.muscles)
{
if (m.joint == null)
{
m.name = "Missing Joint Reference!";
}
else if (m.target == null)
{
m.name = "Missing Target Reference!";
}
else m.name = m.joint.name;
}
if (script.muscles.Length == 0)
{
GUILayout.Space(5);
animatedCharacter = (Transform)EditorGUILayout.ObjectField(new GUIContent("Animated Target", "If it is assigned to the same GameObject, it will be duplicated and cleaned up of all the ragdoll components. It can also be an instance of the character or even another character as long as the positions of the bones match. The rotations of the bones don't need to be identical. That makes it possible to share ragdoll structures and is also most useful when the feet bones are not aligned to the ground (like Mixamo characters). In that case you can simply rotate the ragdoll's feet to align, keeping the target's feet where they are."), animatedCharacter, typeof(Transform), true);
GUILayout.Space(5);
characterControllerLayer = EditorGUILayout.IntField(new GUIContent("Character Controller Layer", "The layer to assign the character controller to. Collisions between this layer and the 'Ragdoll Layer' will be ignored, or else the ragdoll would collide with the character controller."), characterControllerLayer);
ragdollLayer = EditorGUILayout.IntField(new GUIContent("Ragdoll Layer", "The layer to assign the PuppetMaster and all it's muscles to. Collisions between this layer and the 'Character Controller Layer' will be ignored, or else the ragdoll would collide with the character controller."), ragdollLayer);
if (characterControllerLayer == ragdollLayer)
{
GUILayout.Space(5);
EditorGUILayout.LabelField(
"The 'Character Controller Layer' must not be the same as the 'Ragdoll Layer', your ragdoll bones would collide with the character controller."
, style);
EditorGUILayout.Space();
}
if (animatedCharacter != null && characterControllerLayer != ragdollLayer)
{
GUILayout.Space(5);
if (GUILayout.Button("Set Up PuppetMaster", GUILayout.MaxWidth(140)))
{
#if UNITY_2018_3_OR_NEWER
if (animatedCharacter == script.transform)
{
if (PrefabUtility.IsPartOfPrefabInstance(animatedCharacter.gameObject)) PrefabUtility.UnpackPrefabInstance(PrefabUtility.GetNearestPrefabInstanceRoot(animatedCharacter.gameObject), PrefabUnpackMode.Completely, InteractionMode.UserAction);
} else
{
if (PrefabUtility.IsPartOfPrefabInstance(script.gameObject)) PrefabUtility.UnpackPrefabInstance(PrefabUtility.GetNearestPrefabInstanceRoot(script.gameObject), PrefabUnpackMode.Completely, InteractionMode.UserAction);
}
#endif
script.SetUpTo(animatedCharacter, characterControllerLayer, ragdollLayer);
animatedCharacter = null;
}
EditorGUILayout.LabelField("Setting up PuppetMaster is not undoable. Make sure to make a backup duplicate of the character before you do that.", miniLabelStyle);
if (animatedCharacter == script.transform)
{
GUILayout.Space(5);
EditorGUILayout.BeginVertical("Box");
GUILayout.Label("NB! 'Animated Target' is set to the same GameObject as this. PuppetMaster will make a duplicate of this GameObject and break the prefab to remove ragdoll components. It is recommended to set up the ragdoll on a new model instance, add PuppetMater to that and assign the original character as it's 'Animated Target'.", miniLabelStyle);
EditorGUILayout.EndVertical();
}
}
GUILayout.Space(5);
}
else
{
// Fix muscle positions and rotations to their targets
if (!Application.isPlaying && script.targetRoot != null)
{
if (script.transform.parent == script.targetRoot.parent)
{
script.transform.localPosition = Vector3.zero;
script.transform.localRotation = Quaternion.identity;
script.targetRoot.localPosition = Vector3.zero;
script.targetRoot.localRotation = Quaternion.identity;
}
foreach (Muscle m in script.muscles)
{
if (m.joint != null && m.target != null && !m.isPropMuscle)
{
m.joint.transform.position = m.target.position;
var r = m.joint.GetComponent<Rigidbody>();
bool hasChild = false;
foreach (Muscle otherMuscle in script.muscles)
{
if (otherMuscle != m && otherMuscle.joint != null && otherMuscle.joint.connectedBody != null)
{
if (otherMuscle.joint.connectedBody == r)
{
hasChild = true;
break;
}
}
}
if (hasChild)
{
m.joint.transform.rotation = m.target.rotation;
}
}
}
}
if (!Application.isPlaying && script.humanoidConfig != null && script.targetRoot != null && script.targetAnimator != null && script.targetAnimator.isHuman)
{
script.humanoidConfig.ApplyTo(script);
GUILayout.Space(5);
EditorGUILayout.BeginVertical("Box");
GUILayout.Label("Properties of this PuppetMaster are locked to the Humanoid Config file.", miniLabelStyle);
EditorGUILayout.EndVertical();
GUILayout.Space(5);
}
script.muscleSpring = Mathf.Clamp(script.muscleSpring, 0f, script.muscleSpring);
script.muscleDamper = Mathf.Clamp(script.muscleDamper, 0f, script.muscleDamper);
DrawDefaultInspector();
GUILayout.Space(10);
// Prop Muscles
GUIStyle largeHeaderStyle = new GUIStyle(GUI.skin.label);
largeHeaderStyle.fontSize = 16;
largeHeaderStyle.fontStyle = FontStyle.Normal;
//largeHeaderStyle.alignment = TextAnchor.LowerLeft;
largeHeaderStyle.alignment = TextAnchor.MiddleLeft;
GUI.color = Color.grey * 0.7f;
EditorGUILayout.LabelField("Prop Muscles", largeHeaderStyle);
GUI.color = Color.white;
EditorGUILayout.BeginHorizontal("Box");
addPropMuscleTo = (ConfigurableJoint)EditorGUILayout.ObjectField(GUIContent.none, addPropMuscleTo, typeof(ConfigurableJoint), true);
if (GUILayout.Button("Add Prop Muscle"))
{
serializedObject.ApplyModifiedProperties();
AddPropMuscle(script, addPropMuscleTo, addPropMuscleTo.transform.position, addPropMuscleTo.transform.rotation, Vector3.forward * 0.5f);
serializedObject.Update();
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.LabelField("Prop Muscles are muscles that props (PuppetMasterProp) can be attached to. For example, to put a sword in the right hand, assign the right hand muscle above, click on 'Add Prop Muscle', then move the added muscle to where you would want the sword to be held. To pick up the sword, just assign it as 'Current Prop' in the PropMuscle component on the prop muscle.", miniLabelStyle);
GUILayout.Space(5);
}
bool animatorWarning = targetAnimator != null && targetAnimator.cullingMode != AnimatorCullingMode.AlwaysAnimate;
if (animatorWarning)
{
GUILayout.Space(5);
EditorGUILayout.BeginVertical("Box");
GUILayout.Label("If Animator 'Culling Mode' is not set to 'Always Animate', animation might pause and cause glitches when the ragdoll is out of SkinnedMeshRenderer.bounds.", miniLabelStyle);
EditorGUILayout.EndVertical();
}
bool rendererWarning = false;
foreach (SkinnedMeshRenderer s in skinnedMeshRenderers)
{
if (!s.updateWhenOffscreen)
{
rendererWarning = true;
break;
}
}
if (rendererWarning)
{
if (!animatorWarning) GUILayout.Space(5);
EditorGUILayout.BeginVertical("Box");
GUILayout.Label("One of the SkinnedMeshRenderers in the animated character hierarchy has 'Update When Offscreen' set to false. This might cause it to disappear from view when the ragdoll is out of the renderer's bounds.", miniLabelStyle);
EditorGUILayout.EndVertical();
}
serializedObject.ApplyModifiedProperties();
}
public static void DestroyImmediateSafe(GameObject go)
{
#if UNITY_2018_3_OR_NEWER
if (PrefabUtility.IsPartOfPrefabInstance(go)) PrefabUtility.UnpackPrefabInstance(PrefabUtility.GetNearestPrefabInstanceRoot(go), PrefabUnpackMode.Completely, InteractionMode.UserAction);
#endif
DestroyImmediate(go);
}
public static bool AddPropMuscle(PuppetMaster script, ConfigurableJoint addPropMuscleTo, Vector3 position, Quaternion rotation, Vector3 additionalPinOffset, Transform targetParent = null)
{
var serializedObject = new SerializedObject(script);
if (addPropMuscleTo != null)
{
bool isFlat = script.HierarchyIsFlat();
var addToMuscle = script.GetMuscle(addPropMuscleTo);
if (addToMuscle != null)
{
GameObject go = new GameObject("Prop Muscle " + addPropMuscleTo.name);
go.layer = addPropMuscleTo.gameObject.layer;
go.transform.parent = isFlat ? script.transform : addPropMuscleTo.transform;
go.transform.position = position;
go.transform.rotation = rotation;
var r = go.AddComponent<Rigidbody>();
GameObject target = new GameObject("Prop Muscle Target " + addPropMuscleTo.name);
target.gameObject.layer = addToMuscle.target.gameObject.layer;
target.transform.parent = targetParent == null ? addToMuscle.target : targetParent;
target.transform.position = go.transform.position;
target.transform.rotation = go.transform.rotation;
var joint = go.AddComponent<ConfigurableJoint>();
joint.connectedBody = addToMuscle.joint.gameObject.GetComponent<Rigidbody>();
joint.xMotion = ConfigurableJointMotion.Locked;
joint.yMotion = ConfigurableJointMotion.Locked;
joint.zMotion = ConfigurableJointMotion.Locked;
joint.angularXMotion = ConfigurableJointMotion.Locked;
joint.angularYMotion = ConfigurableJointMotion.Locked;
joint.angularZMotion = ConfigurableJointMotion.Locked;
r.interpolation = joint.connectedBody.interpolation;
int newLength = script.muscles.Length + 1;
int newMuscleIndex = newLength - 1;
SerializedProperty muscles = serializedObject.FindProperty("muscles");
muscles.InsertArrayElementAtIndex(newMuscleIndex);
muscles.GetArrayElementAtIndex(newMuscleIndex).FindPropertyRelative("index").intValue = newMuscleIndex;
muscles.GetArrayElementAtIndex(newMuscleIndex).FindPropertyRelative("joint").objectReferenceValue = joint;
muscles.GetArrayElementAtIndex(newMuscleIndex).FindPropertyRelative("target").objectReferenceValue = target.transform;
muscles.GetArrayElementAtIndex(newMuscleIndex).FindPropertyRelative("props").FindPropertyRelative("group").intValue = 8;
muscles.GetArrayElementAtIndex(newMuscleIndex).FindPropertyRelative("isPropMuscle").boolValue = true;
serializedObject.ApplyModifiedProperties();
var propMuscle = joint.gameObject.AddComponent<PropMuscle>();
var propMuscleS = new SerializedObject(propMuscle);
propMuscleS.FindProperty("puppetMaster").objectReferenceValue = script;
propMuscleS.FindProperty("additionalPinOffset").vector3Value = additionalPinOffset;
propMuscleS.ApplyModifiedProperties();
if (additionalPinOffset != Vector3.zero)
{
propMuscleS.Update();
ConfigurableJoint additionalJoint = null;
Transform additionalTarget = null;
PropMuscleInspector.AddAdditionalPinUnserialized(propMuscle, out additionalJoint, out additionalTarget);
muscles.GetArrayElementAtIndex(newMuscleIndex).FindPropertyRelative("additionalPin").objectReferenceValue = additionalJoint;
muscles.GetArrayElementAtIndex(newMuscleIndex).FindPropertyRelative("additionalPinTarget").objectReferenceValue = additionalTarget;
propMuscleS.ApplyModifiedProperties();
}
serializedObject.ApplyModifiedProperties();
// TODO Do not add if addPropMuscleTo already has a PropMuscle
return true;
}
else
{
Debug.LogError("Can't add Prop Muscle to a ConfigurableJoint that is not in the list of PuppetMaster.muscles.", script.transform);
return false;
}
}
else
{
Debug.LogError("Please assign the ConfigurableJoint of the muscle you wish to add the Prop Muscle to.", script.transform);
return false;
}
}
private bool IsRagdoll()
{
Rigidbody[] rigidbodies = (Rigidbody[])script.gameObject.GetComponentsInChildren<Rigidbody>();
foreach (Rigidbody r in rigidbodies)
{
if (r != script.GetComponent<Rigidbody>()) return true;
}
return false;
}
#endregion Inspector
#region Scene
void OnSceneGUI()
{
if (script == null) return;
if (Application.isPlaying) return;
foreach (Muscle m in script.muscles)
{
if (m.joint != null)
{
var propMuscle = m.joint.GetComponent<PropMuscle>();
if (propMuscle != null)
{
PropMuscleInspector.DrawScene(propMuscle);
}
}
}
Handles.color = Color.white;
}
#endregion Scene
}
}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: d63c5bd59fb5541eeb1098d1f4a6d01c
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
@@ -0,0 +1,37 @@
using UnityEngine;
using System.Collections;
using UnityEditor;
namespace RootMotion.Dynamics
{
[CustomEditor(typeof(PuppetMasterProp))]
public class PuppetMasterPropInspector : Editor
{
private PuppetMasterProp script { get { return target as PuppetMasterProp; } }
private GUIStyle style = new GUIStyle();
private GUIStyle miniLabelStyle = new GUIStyle();
private static Color pro = new Color(0.5f, 0.7f, 0.3f, 1f);
private static Color free = new Color(0.2f, 0.3f, 0.1f, 1f);
public override void OnInspectorGUI()
{
if (script == null) return;
serializedObject.Update();
style.wordWrap = true;
style.normal.textColor = EditorGUIUtility.isProSkin ? pro : free;
miniLabelStyle.wordWrap = true;
miniLabelStyle.fontSize = 10;
miniLabelStyle.normal.textColor = EditorStyles.miniLabel.normal.textColor;
DrawDefaultInspector();
script.muscleProps.group = Muscle.Group.Prop;
serializedObject.ApplyModifiedProperties();
}
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: a7f9c20921f4b1942b1f7b410dd66836
timeCreated: 1550561801
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,46 @@
using UnityEngine;
using UnityEditor;
namespace RootMotion.Dynamics {
[CustomPropertyDrawer (typeof (Weight))]
public class WeightDrawer : PropertyDrawer {
const int valueWidth = 30;
const int gap = 20;
const float min = 0;
const float max = 1;
public override void OnGUI (Rect pos, SerializedProperty prop, GUIContent label) {
SerializedProperty mode = prop.FindPropertyRelative("mode");
SerializedProperty floatValue = prop.FindPropertyRelative ("floatValue");
SerializedProperty curve = prop.FindPropertyRelative ("curve");
SerializedProperty tooltip = prop.FindPropertyRelative("tooltip");
label.tooltip = tooltip.stringValue;
Rect left = new Rect(pos.x, pos.y, pos.width - valueWidth - gap, pos.height);
Rect right = new Rect (pos.width - valueWidth, pos.y, valueWidth, pos.height);
Weight.Mode m = (Weight.Mode)mode.enumValueIndex;
if (m == Weight.Mode.Float) {
floatValue.floatValue = EditorGUI.FloatField(left, label, floatValue.floatValue);
} else {
// Draw curve
int indent = EditorGUI.indentLevel;
EditorGUI.PropertyField (left, curve, label);
EditorGUI.indentLevel = indent;
}
int i = EditorGUI.indentLevel;
EditorGUI.indentLevel = 0;
m = (Weight.Mode)EditorGUI.EnumPopup(right, GUIContent.none, ( Weight.Mode)mode.enumValueIndex, EditorStyles.miniBoldLabel);
mode.enumValueIndex = (int)m;
EditorGUI.indentLevel = i;
}
}
}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: f882d03cc62ed40c7b8febce6ef4a0de
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 98d02ab32f6fa4551b1983c76cea4586
folderAsset: yes
timeCreated: 1452250914
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,75 @@
using UnityEngine;
using UnityEditor;
using System.Collections;
using RootMotion.Dynamics;
namespace RootMotion.Demos {
[CustomEditor(typeof(CharacterMeleeDemo))]
public class CharacterMeleeDemoInspector : Editor {
private CharacterMeleeDemo script { get { return target as CharacterMeleeDemo; }}
private GameObject replace;
private static Color pro = new Color(0.7f, 0.9f, 0.5f, 1f);
private static Color free = new Color(0.4f, 0.5f, 0.3f, 1f);
public override void OnInspectorGUI() {
GUI.changed = false;
if (!Application.isPlaying) {
GUI.color = EditorGUIUtility.isProSkin? pro: free;
EditorGUILayout.BeginHorizontal();
replace = (GameObject)EditorGUILayout.ObjectField("Replace Character Model", replace, typeof(GameObject), true);
if (replace != null) {
if (GUILayout.Button("Replace")) {
Debug.Log("PropMuscle needs to be set up manually and assigned as 'Prop Muscle' in the CharacterMeleeDemo component on the character.");
/* TODO Update to PropMuscle
PropRoot propRoot = script.propRoot;
Vector3 localPosition = propRoot.transform.localPosition;
Quaternion localRotation = propRoot.transform.localRotation;
propRoot.transform.parent = null;
CharacterPuppetInspector.ReplacePuppetModel(script as CharacterThirdPerson, replace);
Animator animator = script.characterAnimation.GetComponent<Animator>();
PuppetMaster puppetMaster = script.transform.parent.GetComponentInChildren<PuppetMaster>();
propRoot.transform.parent = animator.GetBoneTransform(HumanBodyBones.RightHand);
propRoot.transform.localPosition = localPosition;
propRoot.transform.localRotation = localRotation;
propRoot.puppetMaster = puppetMaster;
propRoot.connectTo = GetRigidbody(puppetMaster, animator.GetBoneTransform(HumanBodyBones.RightLowerArm));
Debug.Log("You probably need to adjust the localPosition and localRotation of the Prop Root to match this character's hand.");
*/
UserControlAI[] userControls = (UserControlAI[])GameObject.FindObjectsOfType<UserControlAI>();
foreach (UserControlAI ai in userControls) {
if (ai.moveTarget == null) {
ai.moveTarget = script.transform.parent.GetComponentInChildren<PuppetMaster>().muscles[0].joint.transform;
}
}
}
}
EditorGUILayout.EndHorizontal();
GUI.color = Color.white;
}
DrawDefaultInspector();
if (GUI.changed) EditorUtility.SetDirty(script);
}
private Rigidbody GetRigidbody(PuppetMaster puppetMaster, Transform target) {
foreach (Muscle m in puppetMaster.muscles) {
if (m.target == target) return m.joint.GetComponent<Rigidbody>();
}
return null;
}
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 5c5c74fcc11b441abb014b8119cb9e5f
timeCreated: 1452255675
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,176 @@
using UnityEngine;
using UnityEditor;
using System.Collections;
using RootMotion.Dynamics;
namespace RootMotion.Demos {
[CustomEditor(typeof(CharacterPuppet))]
public class CharacterPuppetInspector : Editor {
private CharacterPuppet script { get { return target as CharacterPuppet; }}
private GameObject replace;
private static Color pro = new Color(0.7f, 0.9f, 0.5f, 1f);
private static Color free = new Color(0.4f, 0.5f, 0.3f, 1f);
public override void OnInspectorGUI() {
GUI.changed = false;
if (!Application.isPlaying) {
GUI.color = EditorGUIUtility.isProSkin? pro: free;
EditorGUILayout.BeginHorizontal();
replace = (GameObject)EditorGUILayout.ObjectField("Replace Character Model", replace, typeof(GameObject), true);
if (replace != null) {
if (GUILayout.Button("Replace")) {
ReplacePuppetModel(script as CharacterThirdPerson, replace);
replace = null;
}
}
GUI.color = Color.white;
EditorGUILayout.EndHorizontal();
}
DrawDefaultInspector();
if (GUI.changed) EditorUtility.SetDirty(script);
}
public static void ReplacePuppetModel(CharacterThirdPerson script, GameObject replace) {
// Drag your Humanoid character to the scene, parent it to the "Animation Controller" just where the Pilot is
GameObject find = GameObject.Find(replace.name);
bool isSceneObject = find != null && find == replace;
GameObject instance = isSceneObject? replace: (GameObject)GameObject.Instantiate(replace, script.transform.position, script.transform.rotation);
instance.transform.parent = script.characterAnimation.transform;
instance.name = replace.name;
instance.transform.position = script.transform.position;
instance.transform.rotation = script.transform.rotation;
Animator animator = instance.GetComponentInChildren<Animator>();
bool isAnimator = animator != null;
if (!isAnimator || !animator.isHuman) {
Debug.LogWarning("The demo character controller requires a Humanoid character.");
return;
}
SkinnedMeshRenderer[] skinnedMeshRenders = instance.GetComponentsInChildren<SkinnedMeshRenderer>();
foreach (SkinnedMeshRenderer s in skinnedMeshRenders) s.updateWhenOffscreen = true;
// Unparent "Character Controller" from the "ThirdPersonPuppet"
Transform oldRoot = script.transform.parent;
PuppetMaster oldPM = script.transform.parent.GetComponentInChildren<PuppetMaster>();
RigidbodyInterpolation oldInterpolation = oldPM.muscles[0].joint.GetComponent<Rigidbody>().interpolation;
BehaviourBase[] behaviours = script.transform.parent.GetComponentsInChildren<BehaviourBase>();
Camera camera = script.transform.parent.GetComponentInChildren<Camera>();
CameraController cameraController = null;
if (camera != null) cameraController = camera.gameObject.GetComponent<CameraController>();
LayerSetup layerSetup = oldPM.GetComponent<LayerSetup>();
script.transform.parent = null;
// Delete the "Pilot"
DestroyImmediate(script.characterAnimation.transform.GetChild(0).gameObject);
// Replace the Avatar in the Animator component of the "Animation Controller" gameobject.
Animator characterAnimator = script.characterAnimation.GetComponent<Animator>();
characterAnimator.avatar = animator.avatar;
// Add BipedRagdollCreator to the "Animation Controller", use it to create a ragdoll, delete the component when done
Joint joint = instance.GetComponentInChildren<Joint>();
bool isRagdoll = joint != null;
bool isConfigurable = isRagdoll && joint is ConfigurableJoint;
if (isRagdoll && !isConfigurable) {
JointConverter.ToConfigurable(instance);
}
if (!isRagdoll) {
BipedRagdollReferences r = BipedRagdollReferences.FromAvatar(animator);
BipedRagdollCreator.Options options = BipedRagdollCreator.AutodetectOptions(r);
// Edit options here if you need to
BipedRagdollCreator.Create(r, options);
}
// Delete the Animator from your character root (not the one on "Animation Controller")
DestroyImmediate(animator);
// Add PuppetMaster to the "Character Controller", click on Set Up PuppetMaster.
int cLayer = layerSetup != null? layerSetup.characterControllerLayer: script.gameObject.layer;
int rLayer = layerSetup != null? layerSetup.ragdollLayer: oldPM.muscles[0].joint.gameObject.layer;
PuppetMaster newPuppetMaster = PuppetMaster.SetUp(script.transform, cLayer, rLayer);
foreach (Muscle m in newPuppetMaster.muscles) {
m.joint.GetComponent<Rigidbody>().interpolation = oldInterpolation;
}
// Move the "Puppet" and "Fall" behaviours from the old rig to the new one (parent them to the "Behaviours").
Transform behaviourRoot = newPuppetMaster.transform.parent.Find("Behaviours");
Transform oldBehaviourRoot = behaviours.Length > 0? behaviours[0].transform.parent: FindChildNameContaining(oldRoot, "Behaviours");
foreach (BehaviourBase behaviour in behaviours) behaviour.transform.parent = behaviourRoot;
if (oldBehaviourRoot != null) DestroyImmediate(oldBehaviourRoot.gameObject);
// 9. Move the "Character Camera" to the new rig, replace the "Target" of the CharacterController component
if (camera != null) camera.transform.parent = newPuppetMaster.transform.parent;
if (cameraController != null) cameraController.target = newPuppetMaster.muscles[0].joint.transform;
// THIS IS NOT REQUIRED SINCE 0.3 Use the RagdollEditor (add it to the PuppetMaster) to multiply the mass of the ragdoll by 10
// 10. Copy the LayerSetup component from the old PuppetMaster to the new one if you have not set up the layers in the Layer Collision Matrix.
if (layerSetup != null) {
LayerSetup newLayerSetup = newPuppetMaster.gameObject.AddComponent<LayerSetup>();
if (newLayerSetup != null) {
newLayerSetup.characterController = layerSetup.characterController;
newLayerSetup.characterControllerLayer = layerSetup.characterControllerLayer;
newLayerSetup.ragdollLayer = layerSetup.ragdollLayer;
newLayerSetup.ignoreCollisionWithCharacterController = layerSetup.ignoreCollisionWithCharacterController;
}
}
// 11. Make sure the new PuppetMaster settings match with the old one, delete the old rig
newPuppetMaster.state = oldPM.state;
newPuppetMaster.stateSettings = oldPM.stateSettings;
newPuppetMaster.mode = oldPM.mode;
newPuppetMaster.blendTime = oldPM.blendTime;
newPuppetMaster.fixTargetTransforms = oldPM.fixTargetTransforms;
newPuppetMaster.solverIterationCount = oldPM.solverIterationCount;
newPuppetMaster.visualizeTargetPose = oldPM.visualizeTargetPose;
newPuppetMaster.mappingWeight = oldPM.mappingWeight;
newPuppetMaster.pinWeight = oldPM.pinWeight;
newPuppetMaster.muscleWeight = oldPM.muscleWeight;
newPuppetMaster.muscleSpring = oldPM.muscleSpring;
newPuppetMaster.muscleDamper = oldPM.muscleDamper;
newPuppetMaster.pinPow = oldPM.pinPow;
newPuppetMaster.pinDistanceFalloff = oldPM.pinDistanceFalloff;
newPuppetMaster.updateJointAnchors = oldPM.updateJointAnchors;
newPuppetMaster.supportTranslationAnimation = oldPM.supportTranslationAnimation;
newPuppetMaster.angularLimits = oldPM.angularLimits;
newPuppetMaster.internalCollisions = oldPM.internalCollisions;
// 12 Parent this CharacterPuppet to the new puppet root
script.transform.parent = newPuppetMaster.transform.parent;
// 13. Delete the old root
script.transform.parent.name = oldRoot.name;
for (int i = 0; i < oldRoot.childCount; i++) {
var child = oldRoot.GetChild(i);
if (child != oldPM.transform && child != behaviourRoot) {
child.parent = script.transform.parent;
}
}
DestroyImmediate(oldRoot.gameObject);
}
private static Transform FindChildNameContaining(Transform t, string name) {
for (int i = 0; i < t.childCount; i++) {
if (t.GetChild(i).name.Contains(name)) return t.GetChild(i);
}
return null;
}
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: d86142a0934834027a39b8a2e105c009
timeCreated: 1452250930
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: