Initial release of the Unity plugin.

PiperOrigin-RevId: 425947505
This commit is contained in:
Tom Erez
2022-02-02 20:17:13 +00:00
committed by Saran Tunyasuvunakool
parent 8ec3dd97a4
commit 6de9eafa13
298 changed files with 20617 additions and 2 deletions
+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: f5a5ea2338a298b5e94d5f5653c0b85b
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,26 @@
// Copyright 2019 DeepMind Technologies Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using UnityEditor;
using UnityEngine;
namespace Mujoco {
[CustomPropertyDrawer(typeof(AbsoluteValueAttribute))]
public class AbsoluteValuePropertyDrawer : PropertyDrawer {
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {
property.floatValue = Mathf.Abs(EditorGUI.FloatField(position, label, property.floatValue));
}
}
}
@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: ac61b66fbbd264beebb1df6cd423d122
timeCreated: 1538126279
licenseType: Pro
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
+199
View File
@@ -0,0 +1,199 @@
// Copyright 2019 DeepMind Technologies Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using UnityEditor;
using UnityEngine;
namespace Mujoco {
[CustomEditor(typeof(MjActuator))]
[CanEditMultipleObjects]
public class MjActuatorEditor : Editor {
private bool _showCustomParams = false;
private bool _showDebugValues = false;
private bool _showDynPrm = false;
private bool _showGainPrm = false;
private bool _showBiasValues = false;
// General actuator properties.
private SerializedProperty _dynType;
private SerializedProperty _gainType;
private SerializedProperty _biasType;
private SerializedProperty _dynPrm;
private SerializedProperty _gainPrm;
private SerializedProperty _biasPrm;
// Position actuator properties.
private SerializedProperty _kp;
// Velocity actuator properties.
private SerializedProperty _kv;
// Cylinder actuator properties.
private SerializedProperty _cylinderTimeConst;
private SerializedProperty _area;
private SerializedProperty _diameter;
private SerializedProperty _bias;
// Cylinder actuator properties.
private SerializedProperty _muscleTimeConst;
private SerializedProperty _range;
private SerializedProperty _force;
private SerializedProperty _scale;
private SerializedProperty _lmin;
private SerializedProperty _lmax;
private SerializedProperty _vmax;
private SerializedProperty _fpmax;
private SerializedProperty _fvmax;
public void OnEnable() {
_showCustomParams = false;
_showDebugValues = false;
_showDynPrm = false;
_showGainPrm = false;
_showBiasValues = false;
var customParams = serializedObject.FindProperty("CustomParams");
// General actuator properties.
_dynType = customParams.FindPropertyRelative("DynType");
_gainType = customParams.FindPropertyRelative("GainType");
_biasType = customParams.FindPropertyRelative("BiasType");
_dynPrm = customParams.FindPropertyRelative("DynPrm");
_gainPrm = customParams.FindPropertyRelative("GainPrm");
_biasPrm = customParams.FindPropertyRelative("BiasPrm");
// Position actuator properties.
_kp = customParams.FindPropertyRelative("Kp");
// Velocity actuator properties.
_kv = customParams.FindPropertyRelative("Kv");
// Cylinder actuator properties.
_cylinderTimeConst = customParams.FindPropertyRelative("CylinderTimeConst");
_area = customParams.FindPropertyRelative("Area");
_diameter = customParams.FindPropertyRelative("Diameter");
_bias = customParams.FindPropertyRelative("Bias");
// Cylinder actuator properties.
_muscleTimeConst = customParams.FindPropertyRelative("MuscleTimeConst");
_range = customParams.FindPropertyRelative("Range");
_force = customParams.FindPropertyRelative("Force");
_scale = customParams.FindPropertyRelative("Scale");
_lmin = customParams.FindPropertyRelative("LMin");
_lmax = customParams.FindPropertyRelative("LMax");
_vmax = customParams.FindPropertyRelative("VMax");
_fpmax = customParams.FindPropertyRelative("FpMax");
_fvmax = customParams.FindPropertyRelative("FvMax");
}
public override void OnInspectorGUI() {
serializedObject.Update();
foreach (var target in serializedObject.targetObjects) {
EditActuator(target as MjActuator);
}
serializedObject.ApplyModifiedProperties();
}
private void EditActuator(MjActuator actuator) {
DrawDefaultInspector();
_showCustomParams = EditorGUILayout.Foldout(_showCustomParams, "Custom Params");
if (_showCustomParams) {
EditCustomParams(actuator.Type, actuator.CustomParams);
}
_showDebugValues = EditorGUILayout.Foldout(_showDebugValues, "Debug");
if (_showDebugValues) {
using (new EditorGUI.DisabledScope(true)) {
EditorGUILayout.FloatField("Length", actuator.Length);
EditorGUILayout.FloatField("Velocity", actuator.Velocity);
EditorGUILayout.FloatField("Force", actuator.Force);
}
}
}
private void EditCustomParams(MjActuator.ActuatorType type,
MjActuator.CustomParameters parameters) {
switch (type) {
case MjActuator.ActuatorType.General: {
EditGeneralParams(parameters);
break;
}
case MjActuator.ActuatorType.Position: {
EditPositionParams(parameters);
break;
}
case MjActuator.ActuatorType.Velocity: {
EditVelocityParams(parameters);
break;
}
case MjActuator.ActuatorType.Cylinder: {
EditCylinderParams(parameters);
break;
}
case MjActuator.ActuatorType.Muscle: {
EditMuscleParams(parameters);
break;
}
}
}
private void EditGeneralParams(MjActuator.CustomParameters parameters) {
EditorGUILayout.PropertyField(_dynType);
EditorGUILayout.PropertyField(_gainType);
EditorGUILayout.PropertyField(_biasType);
_showDynPrm = EditorGUILayout.Foldout(_showDynPrm, "DynPrm");
if (_showDynPrm) {
for (var i = 0; i < parameters.DynPrm.Count; ++i) {
EditorGUILayout.PropertyField(_dynPrm.GetArrayElementAtIndex(i));
}
}
_showGainPrm = EditorGUILayout.Foldout(_showGainPrm, "GainPrm");
if (_showGainPrm) {
for (var i = 0; i < parameters.GainPrm.Count; ++i) {
EditorGUILayout.PropertyField(_gainPrm.GetArrayElementAtIndex(i));
}
}
_showBiasValues = EditorGUILayout.Foldout(_showBiasValues, "BiasPrm");
if (_showBiasValues) {
for (var i = 0; i < parameters.BiasPrm.Count; ++i) {
EditorGUILayout.PropertyField(_biasPrm.GetArrayElementAtIndex(i));
}
}
}
private void EditPositionParams(MjActuator.CustomParameters parameters) {
EditorGUILayout.PropertyField(_kp);
}
private void EditVelocityParams(MjActuator.CustomParameters parameters) {
EditorGUILayout.PropertyField(_kv);
}
private void EditCylinderParams(MjActuator.CustomParameters parameters) {
EditorGUILayout.PropertyField(_cylinderTimeConst);
EditorGUILayout.PropertyField(_area);
EditorGUILayout.PropertyField(_diameter);
_showBiasValues = EditorGUILayout.Foldout(_showBiasValues, "Bias");
if (_showBiasValues) {
for (var i = 0; i < parameters.Bias.Length; ++i) {
EditorGUILayout.PropertyField(_bias.GetArrayElementAtIndex(i));
}
}
}
private void EditMuscleParams(MjActuator.CustomParameters parameters) {
EditorGUILayout.PropertyField(_muscleTimeConst, new GUIContent("TimeConst"));
EditorGUILayout.PropertyField(_range);
EditorGUILayout.PropertyField(_force);
EditorGUILayout.PropertyField(_scale);
EditorGUILayout.PropertyField(_lmin);
EditorGUILayout.PropertyField(_lmax);
EditorGUILayout.PropertyField(_vmax);
EditorGUILayout.PropertyField(_fpmax);
EditorGUILayout.PropertyField(_fvmax);
}
}
}
@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 76f90e10df489475490b387a53dd88da
timeCreated: 1547050687
licenseType: Pro
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
+77
View File
@@ -0,0 +1,77 @@
// Copyright 2019 DeepMind Technologies Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using UnityEditor;
using UnityEngine;
namespace Mujoco {
[CustomEditor(typeof(MjGeom), true)]
[CanEditMultipleObjects]
public class MjGeomEditor : MjShapeComponentEditor {
public override void OnInspectorGUI() {
serializedObject.Update();
EditorGUILayout.PropertyField(serializedObject.FindProperty("Mass"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("Density"));
serializedObject.ApplyModifiedProperties();
base.OnInspectorGUI();
}
[MenuItem("CONTEXT/MjGeom/Add mesh renderer")]
private static void AddMeshComponents(MenuCommand menuCommand) {
var geom = menuCommand.context as MjGeom;
geom.gameObject.AddComponent<MjMeshFilter>();
geom.gameObject.AddComponent<MeshRenderer>().material = new Material(Shader.Find("Diffuse"));
}
[MenuItem("CONTEXT/MjGeom/Convert to free object")]
private static void ConvertToFreeObject(MenuCommand menuCommand) {
var geom = menuCommand.context as MjGeom;
if (geom.GetComponentInParent<MjBody>()) {
Debug.LogError("This geom already has a Body parent.", geom.GetComponentInParent<MjBody>());
return;
}
var parent = new GameObject(geom.gameObject.name + " Body").transform;
var root = geom.transform.root;
if (root != geom.transform) {
parent.parent = geom.transform.parent;
}
parent.gameObject.AddComponent<MjBody>();
var joint = new GameObject("Free Joint").AddComponent<MjFreeJoint>();
joint.transform.parent = parent;
geom.transform.parent = parent;
}
[MenuItem("CONTEXT/Collider/Add a matching MuJoCo geom")]
private static void AddMatchingGeom(MenuCommand menuCommand) {
var collider = menuCommand.context as Collider;
collider.enabled = false;
var geom = collider.gameObject.AddComponent<MjGeom>();
if (collider as BoxCollider) {
geom.ShapeType = MjShapeComponent.ShapeTypes.Box;
} else if (collider as SphereCollider) {
geom.ShapeType = MjShapeComponent.ShapeTypes.Sphere;
} else if (collider as CapsuleCollider) {
geom.ShapeType = MjShapeComponent.ShapeTypes.Capsule;
} else if (collider as MeshCollider) {
geom.ShapeType = MjShapeComponent.ShapeTypes.Mesh;
((MjMeshShape)geom.Shape).Mesh = ((MeshCollider)collider).sharedMesh;
} else {
Debug.LogError("Collider type not supported yet.", collider);
collider.enabled = true;
GameObject.DestroyImmediate(geom);
}
}
}
}
@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: d5409b149ad694715a57f4dc8bb7a857
timeCreated: 1552041114
licenseType: Pro
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
+58
View File
@@ -0,0 +1,58 @@
// Copyright 2019 DeepMind Technologies Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEditor.AnimatedValues;
using UnityEngine;
namespace Mujoco {
public static class MjHandles {
// Renders a visualization of an axis, anchored at the specified world space origin.
//
// Args:
// origin: World space coordinates of the anchoring point for the visualization.
// direction: Axis direction.
public static void Axis(Vector3 origin, Vector3 direction) {
var size = HandleUtility.GetHandleSize(origin) * 0.3f;
var axisEnd = origin + direction * size;
var capRotation = Quaternion.LookRotation(direction);
Handles.DrawLine(origin, axisEnd);
Handles.ConeHandleCap(0, axisEnd, capRotation, size, EventType.Repaint);
}
// Renders a visualization of linear (translational) limits, anchored at the specified world
// space origin.
//
// Args:
// origin: World space coordinates of the anchoring point for the visualization.
// lower: Distance from the origin below, where the limit expires.
// upper: Distance from the origin above, where the limit expires.
// axis: Axis along which the limit works.
public static void LinearLimits(Vector3 origin, float lower, float upper, Vector3 axis) {
if (upper > lower) {
var discRadius = HandleUtility.GetHandleSize(origin) * 0.7f;
var startPosition = origin + axis * lower;
var endPosition = origin + axis * upper;
Handles.DrawSolidDisc(startPosition, axis, discRadius);
Handles.DrawSolidDisc(endPosition, axis, discRadius);
Handles.DrawLine(origin, endPosition);
}
}
}
}
+13
View File
@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 1a810c29762134ebb9bbee3903172764
timeCreated: 1537794456
licenseType: Pro
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,41 @@
// Copyright 2019 DeepMind Technologies Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEditor.AnimatedValues;
using UnityEngine;
namespace Mujoco {
[CustomEditor(typeof(MjHingeJoint))]
public class MjHingeJointEditor : Editor {
private MjHingeJoint _joint;
protected virtual void OnEnable() {
_joint = (MjHingeJoint)target;
}
protected virtual void OnSceneGUI() {
DrawHandles(_joint);
}
public static void DrawHandles(MjHingeJoint joint) {
Handles.color = Color.yellow;
MjHandles.Axis(joint.transform.position, joint.RotationAxis);
}
}
}
@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: bdaa159fcf7064108aed2229bc39ac0d
timeCreated: 1537794793
licenseType: Pro
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
+176
View File
@@ -0,0 +1,176 @@
#if UNITY_EDITOR
using System;
using UnityEditor;
using UnityEngine;
namespace Mujoco {
// During play mode, in the scene view, with a MjBody component selected, holding down control
// and left mouse drag will apply a force on the body. Holding shift down will change the applied
// force direction between World XZ plane and Y[camera-up].
[CustomEditor(typeof(MjBody))]
public class MjMouseSpring : Editor {
private bool _lastShiftKeyState = false;
private Plane _mouseDragPlane;
private Vector3 _mouseDragCurrentPoint = Vector3.negativeInfinity;
private Color _translucentRed = new Color(1, 0, 0, 0.1f);
public void OnDisable() {
// If we're still the hot control at this stage, we need to release.
int uniqueID = GUIUtility.GetControlID(FocusType.Passive);
if (GUIUtility.hotControl == uniqueID) {
GUIUtility.hotControl = 0;
}
}
private void SetDragOriginAndDragPlane(Vector3 planeOrigin, Vector3 normal) {
normal[1] = 0;
normal = _lastShiftKeyState ? Vector3.up : normal;
_mouseDragPlane.SetNormalAndPosition(normal, planeOrigin);
}
private void UpdatePositionOnDragPlane(Vector3 mousePosition) {
float rayDist;
Ray ray = HandleUtility.GUIPointToWorldRay(mousePosition);
if (_mouseDragPlane.Raycast(ray, out rayDist)) {
_mouseDragCurrentPoint = ray.GetPoint(rayDist);
}
}
private void DrawMouseSpringGui(Vector3 bodyPosition, Vector3 direction, Camera renderCamera) {
// Update and draw the drag indicator.
var rot = Quaternion.FromToRotation(Vector3.up, direction);
// Backup defaults.
var backupColour = Handles.color;
// Update the drag plane indicator disc and outline...
var discRadius = (_mouseDragCurrentPoint - bodyPosition).magnitude;
Handles.color = Color.red;
Handles.DrawWireDisc(bodyPosition, _mouseDragPlane.normal, discRadius);
Handles.color = _translucentRed;
Handles.DrawSolidDisc(bodyPosition, _mouseDragPlane.normal, discRadius);
// ...and give it a phat poly line to show the drag anchor origin.
Handles.color = Color.white;
Handles.DrawAAPolyLine(6, new Vector3[] { bodyPosition, _mouseDragCurrentPoint });
// Restore defaults.
Handles.color = backupColour;
}
public unsafe void OnSceneGUI() {
if (!Application.isPlaying) {
return;
}
var currentEvent = UnityEngine.Event.current;
// Cache the hot control to determine whether we're currently capturing mouse input.
int uniqueID = GUIUtility.GetControlID(FocusType.Passive);
// Mouse spring is active if the control key is held down and the user is dragging the
// left mouse button, or if we're already in the process of capturing mouse input.
bool mouseSpringActive = GUIUtility.hotControl == uniqueID;
bool mouseSpringStarting = currentEvent.control && currentEvent.button == 0;
if (!mouseSpringStarting && !mouseSpringActive) {
return;
}
var sceneCamera = SceneView.currentDrawingSceneView?.camera;
if (sceneCamera == null) {
Debug.LogError("SceneView.currentDrawingSceneView is null");
return;
}
MjBody body = target as MjBody;
Vector3 bodyPosition =
body != null ? body.transform.position : Vector3.zero;
var scene = MjScene.Instance;
switch (currentEvent.type) {
case EventType.MouseDown:
if (EditorWindow.mouseOverWindow == UnityEditor.EditorWindow.GetWindow<SceneView>()) {
// The mouse was pressed in the scene view, so start capturing all mouse input until
// the mouse button's released.
GUIUtility.hotControl = uniqueID;
_lastShiftKeyState = false;
SetDragOriginAndDragPlane(bodyPosition, -sceneCamera.transform.forward);
currentEvent.Use();
}
return;
case EventType.MouseDrag:
if (mouseSpringActive) {
// We're currently capturing all mouse input, so consume the event.
GUIUtility.hotControl = uniqueID;
currentEvent.Use();
}
return;
case EventType.MouseUp:
if (mouseSpringActive) {
// We're still capturing all mouse input so consume the event, but we can release our
// control over capturing input now as the mouse button's been released.
GUIUtility.hotControl = 0;
currentEvent.Use();
// as opposed to unity's addforce, xfrc_applied is persistent
scene.Data->xfrc_applied[6*body.MujocoId + 0] = 0;
scene.Data->xfrc_applied[6*body.MujocoId + 1] = 0;
scene.Data->xfrc_applied[6*body.MujocoId + 2] = 0;
}
return;
case EventType.Repaint: {
if (mouseSpringActive) {
if (currentEvent.shift != _lastShiftKeyState) {
_lastShiftKeyState = currentEvent.shift;
SetDragOriginAndDragPlane(bodyPosition, -sceneCamera.transform.forward);
}
// Raycast towards the drag plane to update _mouseDragCurrentPoint.
UpdatePositionOnDragPlane(currentEvent.mousePosition);
Vector3 bodyVel = Vector3.one;
double[] mjBodyVel = new double[6];
fixed (double* res = mjBodyVel) {
MujocoLib.mj_objectVelocity(
scene.Model, scene.Data, (int)MujocoLib.mjtObj.mjOBJ_BODY, body.MujocoId, res, 0);
// linear velocity is in the last 3 entries
bodyVel = MjEngineTool.UnityVector3(res, 1);
}
float springStiffness = 100;
var settings = MjGlobalSettings.Instance;
if (settings) {
springStiffness = settings.MouseSpringStiffness;
}
Vector3 delta = _mouseDragCurrentPoint - bodyPosition;
float mass = 1.0f / (float)scene.Model->body_invweight0[2*body.MujocoId];
Vector3 unityForce = delta * springStiffness * mass;
unityForce -= bodyVel * Mathf.Sqrt(springStiffness) * mass;
Vector3 mjForce = MjEngineTool.MjVector3(unityForce);
scene.Data->xfrc_applied[6*body.MujocoId + 0] = mjForce.x;
scene.Data->xfrc_applied[6*body.MujocoId + 1] = mjForce.y;
scene.Data->xfrc_applied[6*body.MujocoId + 2] = mjForce.z;
// Draw and immediately force a repaint.
DrawMouseSpringGui(body.transform.position, delta, sceneCamera);
SceneView.RepaintAll();
}
return;
}
}
}
}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 6c4ae8cbdd0cac0a387364d88408d932
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,38 @@
// Copyright 2019 DeepMind Technologies Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace Mujoco {
[CustomEditor(typeof(MjShapeComponent), true)]
[CanEditMultipleObjects]
public class MjShapeComponentEditor : Editor {
public override void OnInspectorGUI() {
serializedObject.Update();
var shapeType = serializedObject.FindProperty("ShapeType");
EditorGUILayout.PropertyField(shapeType);
EditorGUILayout.PropertyField(
serializedObject.FindProperty($"{shapeType.enumDisplayNames[shapeType.enumValueIndex]}"),
includeChildren: true);
serializedObject.ApplyModifiedProperties();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 21af9fef28ac0899e982e791916b5fc5
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,48 @@
// Copyright 2019 DeepMind Technologies Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEditor.AnimatedValues;
using UnityEngine;
namespace Mujoco {
[CustomEditor(typeof(MjSlideJoint))]
public class MjSlideJointEditor : Editor {
private MjSlideJoint _joint;
protected virtual void OnEnable() {
_joint = (MjSlideJoint)target;
}
protected virtual void OnSceneGUI() {
DrawHandles(_joint);
}
// Draw the handles for the slide joint.
public static void DrawHandles(MjSlideJoint joint) {
// Draw the handles.
if (joint.Settings.Solver.Limited) {
Handles.color = Color.blue;
MjHandles.LinearLimits(joint.transform.position, joint.RangeLower, joint.RangeUpper,
joint.SlideAxis);
}
Handles.color = Color.yellow;
MjHandles.Axis(joint.transform.position, joint.SlideAxis);
}
}
}
@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: bf7c14a263938456e9393a8d0fce7b9f
timeCreated: 1538066332
licenseType: Pro
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 974c7b5fe753877ebaa54ec26e113e1c
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,32 @@
// Copyright 2019 DeepMind Technologies Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.IO;
using UnityEditor;
using UnityEngine;
namespace Mujoco {
// Mujoco scenes importer window.
public class MjImporterEditorWindow : EditorWindow {
[MenuItem("Assets/Import MuJoCo Scene")]
public static void Apply() {
string path = EditorUtility.OpenFilePanel("Select an MJCF model", "", "xml");
if (!string.IsNullOrEmpty(path)) {
var importer = new MjImporterWithAssets();
importer.ImportFile(path);
}
}
}
}
@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 85ddf6116132e4c128ed82ac6034ce4a
timeCreated: 1538581084
licenseType: Pro
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,287 @@
// Copyright 2019 DeepMind Technologies Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
using UnityEditor;
using UnityEngine;
namespace Mujoco {
// API for importing Mujoco XML files into Unity scenes.
public class MjImporterWithAssets : MjcfImporter {
private const string _semiTransparentMaterialName = "mujoco_semitransparent_template";
private string _sourceMeshesDir;
private string _targetMeshesDir;
private string _targetAssetDir;
private unsafe MujocoLib.mjModel_* _mjModel = null;
// Imports the scene from the specified file, which should be a well-formed MJCF document.
// The imported scene will be placed under a single node with the requested name assigned.
//
// Args:
// filePath: Path to XML file.
//
// Throws:
// Exception if the parsed XML is malformed or contains rough errors. If an exception is thrown,
// the entire imported scene will be automatically deleted.
// TODO(etom) - reconsider unencouraged pattern of validation through exception side-effects.
public unsafe GameObject ImportFile(string filePath) {
// If MuJoCo can't parse the mjcfString, we abort the entire process.
// MjEngineTool.LoadModelFromString throws an exception when MuJoCo fails to parse the provided
// mjcfString.
var name = Path.GetFileNameWithoutExtension(filePath) + $"{UnityEngine.Random.Range(0,999)}";
string newPath = Path.Combine(Application.temporaryCachePath, $"{name}.xml");
_mjModel = MjEngineTool.LoadModelFromFile(filePath);
MjEngineTool.SaveModelToFile(newPath, _mjModel);
Debug.Log($"Imported MJCF loaded, saved to {newPath}");
string mjcfString = File.ReadAllText(newPath);
GameObject root = null;
try {
root = ImportString(mjcfString, name, filePath);
} finally {
MujocoLib.mj_deleteModel(_mjModel);
}
return root;
}
public GameObject ImportString(
string mjcfString, string name = null, string filePath = null) {
var mjcfXml = new XmlDocument();
mjcfXml.LoadXml(mjcfString);
// Determine the folder where the meshes are stored.
ConfigureMeshPath(filePath, name, mjcfXml);
GameObject sceneRoot = null;
try {
sceneRoot = ImportXml(mjcfXml, name);
} catch (Exception) {
// We consider any error as critical, and end the import process immediately, cleaning up
// any assets created.
AssetDatabase.DeleteAsset(_targetAssetDir);
}
return sceneRoot;
}
protected override void ParseRoot(GameObject parentObject, XmlElement parentNode) {
// This makes no references, and should be parsed first.
var assetNode = parentNode.SelectSingleNode("asset") as XmlElement;
if (assetNode != null) {
ParseAssets(assetNode);
}
base.ParseRoot(parentObject, parentNode);
}
protected override void ParseGeom(GameObject parentObject, XmlElement child) {
var gameObject = CreateGameObjectWithUniqueName<MjGeom>(parentObject, child);
gameObject.AddComponent<MjMeshFilter>();
var renderer = gameObject.AddComponent<MeshRenderer>();
ResolveOrCreateMaterial(renderer, child);
}
private void ConfigureMeshPath(string path, string projectName, XmlDocument mjcf) {
// Crate the mesh target directory.
_targetMeshesDir = Path.Combine(
Application.dataPath, "Local", "MjImports", projectName, "Resources");
_targetAssetDir = Path.Combine("Assets", "Local", "MjImports", projectName, "Resources");
if (!Directory.Exists(_targetMeshesDir)) {
Directory.CreateDirectory(_targetMeshesDir);
}
if (string.IsNullOrEmpty(path)) { // we're loading a string
return;
}
_sourceMeshesDir = Path.GetDirectoryName(path);
var compilerNode = mjcf.SelectSingleNode("/mujoco/compiler") as XmlElement;
if (compilerNode != null) {
// Parse the location of meshes
var relativeMeshDir = compilerNode.GetStringAttribute("meshdir", defaultValue: string.Empty);
_sourceMeshesDir = Path.Combine(_sourceMeshesDir, relativeMeshDir);
}
Debug.Log(
$"Meshes locations: source = {_sourceMeshesDir}, target = {_targetMeshesDir}");
}
private void ParseAssets(XmlElement parentNode) {
foreach (var child in parentNode.SelectNodes("descendant::mesh").OfType<XmlElement>()) {
_modifiers.ApplyModifiersToElement(child);
ParseMesh(child);
}
foreach (var child in parentNode.SelectNodes("descendant::material").OfType<XmlElement>()) {
_modifiers.ApplyModifiersToElement(child);
ParseMaterial(child);
}
AssetDatabase.SaveAssets();
}
private void ImportMeshFromModel(int meshIndex) {
}
// Using mesh assets involves:
// (1) Copying the asset to a Resources folder, and rescaling it during that operation.
// (2) Allowing Unity to parse it using a registered asset importer (STLMeshImporter).
// (3) Loading that asset as a Mesh resource when the referring geom is parsed.
//
// We're also using a dedicated folder to deploy the meshes that are being imported, so that the
// user can find all meshes loaded by importing a specific model.
private void ParseMesh(XmlElement parentNode) {
if (parentNode.HasAttribute("vertex")) {
throw new NotImplementedException("XML with explicit mesh info not supported yet.");
}
var fileName = parentNode.GetStringAttribute("file");
// If we want to use the element name as the asset name, we must sanitize it:
var unsanitizedAssetReferenceName =
parentNode.GetStringAttribute("name", defaultValue: string.Empty);
var assetReferenceName = MjEngineTool.Sanitize(unsanitizedAssetReferenceName);
var sourceFilePath = Path.Combine(_sourceMeshesDir, fileName);
var targetFilePath = Path.Combine(_targetMeshesDir, assetReferenceName + ".stl");
if (File.Exists(targetFilePath)) {
File.Delete(targetFilePath);
}
var scale = MjEngineTool.UnityVector3(
parentNode.GetVector3Attribute("scale", defaultValue: Vector3.one));
CopyMeshAndRescale(sourceFilePath, targetFilePath, scale);
var assetPath = Path.Combine(_targetAssetDir, assetReferenceName + ".stl");
// This asset path should be available because the MuJoCo compiler guarantees element names
// are unique, but check for completeness (and in case sanitizing the name broke uniqueness):
if (AssetDatabase.LoadMainAssetAtPath(assetPath) != null) {
throw new Exception(
$"Trying to import mesh {unsanitizedAssetReferenceName} but {assetPath} already exists.");
}
AssetDatabase.ImportAsset(assetPath);
var copiedMesh = AssetDatabase.LoadMainAssetAtPath(assetPath) as Mesh;
if (copiedMesh == null) {
throw new Exception($"Mesh {assetPath} was not imported.");
}
copiedMesh.RecalculateNormals();
copiedMesh.RecalculateTangents();
copiedMesh.RecalculateBounds();
}
private void CopyMeshAndRescale(
string sourceFilePath, string targetFilePath, Vector3 scale) {
var originalMeshBytes = File.ReadAllBytes(sourceFilePath);
var mesh = StlMeshParser.ParseBinary(originalMeshBytes, scale);
var rescaledMeshBytes = StlMeshParser.SerializeBinary(mesh);
File.WriteAllBytes(targetFilePath, rescaledMeshBytes);
}
private void ParseMaterial(XmlElement parentNode) {
var rgba = parentNode.GetFloatArrayAttribute(
"rgba", defaultValue: new float[] {1.0f, 1.0f, 1.0f, 1.0f});
var emission = parentNode.GetFloatAttribute("emission", defaultValue: 0.0f);
var reflectance = parentNode.GetFloatAttribute("reflectance", defaultValue: 0.0f);
var specular = parentNode.GetFloatAttribute("specular", defaultValue: 0.5f);
var shininess = parentNode.GetFloatAttribute("shininess", defaultValue: 0.5f);
var unsanitizedName = parentNode.GetStringAttribute("name", defaultValue: string.Empty);
var name = MjEngineTool.Sanitize(unsanitizedName);
var albedo = new Color(rgba[0], rgba[1], rgba[2], rgba[3]);
// Mujoco uses a Blinn/Phong shading model with the addition of reflectance. Unfortunately, at
// the moment of writing this comment, Unity does not come with a compatible shader. The closest
// results can be achieved using the Standard shader that implements the Cook-Torrence shading
// model.
Material material;
if (rgba[3] < 1f) {
material = new Material(AssetDatabase.LoadMainAssetAtPath(
AssetDatabase.GUIDToAssetPath(
AssetDatabase.FindAssets(_semiTransparentMaterialName)[0])) as Material);
} else {
material = new Material(Shader.Find("Standard"));
}
material.SetColor("_Color", albedo);
material.SetFloat("_Metallic", reflectance);
// In order to convert the specular/shininess parameters into glossiness/roughness,
// we perform a coarse approximation.
// In Blinn/Phong model, Shininess corresponds to the width of the specular spot, while
// the Specularity corresponds to its strength (how visible it is). In order to approximate it
// with a single parameter Glossiness, we will assume that the largest value wins. The model
// will break at the extremes (Spec~=1 & Shin~=0, Spec~=0 & Shin~=1), however it should be
// representative for the intermediate values.
float glossiness = Math.Max(specular, shininess);
// We observe that any reflective material is automatically glossy, by the property of not
// having rough surface that would scatter the incoming light.
// Instead of modifying the Shininess parameter however, we're dirrectly modifying
// the glossiness by bringing the value closer to the upper boundary.
glossiness = (1.0f - reflectance) * glossiness + reflectance;
material.SetFloat("_Glossiness", glossiness);
// We choose to define a simple emission model that only emits light, without scaling
// the brightness of the defined color. If the user requires, they should tweak the material
// settings manually.
if (emission > 0.5f) {
material.EnableKeyword("_EMISSION");
material.SetColor("_EmissionColor", albedo);
}
var assetPath = Path.Combine(_targetAssetDir, name + ".mat");
if (AssetDatabase.LoadMainAssetAtPath(assetPath) != null) {
throw new Exception(
$"Trying to create material {unsanitizedName} but {assetPath} already exists.");
}
AssetDatabase.CreateAsset(material, assetPath);
}
// Loads a named material asset, or creates an ad-hoc material asset for the specific node.
private void ResolveOrCreateMaterial(MeshRenderer renderer, XmlElement parentNode) {
// When the asset was parsed and stored its name was sanitized, so we should load it using a
// sanitized name:
var materialName =
MjEngineTool.Sanitize(parentNode.GetStringAttribute("material", defaultValue: string.Empty));
Material material = null;
if (!string.IsNullOrEmpty(materialName)) {
var assetPath = Path.Combine(_targetAssetDir, materialName + ".mat");
material = (Material)AssetDatabase.LoadAssetAtPath(assetPath, typeof(Material));
} else {
// Nodes may contain inlined color definitions, which override the assigned material colors.
if (parentNode.HasAttribute("rgba")) {
// We need a bespoke copy of the material from the database for this particular node.
var rgba = parentNode.GetFloatArrayAttribute(
"rgba", defaultValue: new float[] {1.0f, 1.0f, 1.0f, 1.0f});
if (rgba[3] < 1f) {
material = new Material(
AssetDatabase.LoadMainAssetAtPath(
AssetDatabase.GUIDToAssetPath(
AssetDatabase.FindAssets(_semiTransparentMaterialName)[0])) as Material);
} else {
material = new Material(Shader.Find("Standard"));
}
material.color = new Color(rgba[0], rgba[1], rgba[2], rgba[3]);
// We use the geom's name, guaranteed to be unique, as the asset name.
// If geom is nameless, use a random number.
var name =
MjEngineTool.Sanitize(parentNode.GetStringAttribute(
"name", defaultValue: $"{UnityEngine.Random.Range(0, 1000000)}"));
var assetPath = Path.Combine(_targetAssetDir, name + ".mat");
if (AssetDatabase.LoadMainAssetAtPath(assetPath) != null) {
throw new Exception(
$"Creating a material asset for the geom {name}, but {assetPath} already exists.");
}
AssetDatabase.CreateAsset(material, assetPath);
AssetDatabase.SaveAssets();
material = AssetDatabase.LoadMainAssetAtPath(assetPath) as Material;
} else {
material = DefaultMujocoMaterial;
}
}
renderer.sharedMaterial = material;
}
}
}
@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 0115d33f9ea9249e78644b1fa5cd7765
timeCreated: 1538581083
licenseType: Pro
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
+36
View File
@@ -0,0 +1,36 @@
// Copyright 2019 DeepMind Technologies Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.IO;
using System.Linq;
using UnityEditor.AssetImporters;
using UnityEngine;
namespace Mujoco {
// Importer for STL mesh files.
[ScriptedImporter(version: 1, ext: "stl")]
public class StlMeshImporter : ScriptedImporter {
public override void OnImportAsset(AssetImportContext ctx) {
var assetName = Path.GetFileNameWithoutExtension(ctx.assetPath);
var modelContents = File.ReadAllBytes(ctx.assetPath);
var mesh = StlMeshParser.ParseBinary(modelContents, Vector3.one);
ctx.AddObjectToAsset(assetName, mesh);
ctx.SetMainObject(mesh);
}
}
}
@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 9060c43f3694e454c873753ea0cc2f49
timeCreated: 1550070047
licenseType: Pro
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
+127
View File
@@ -0,0 +1,127 @@
// Copyright 2019 DeepMind Technologies Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEngine;
namespace Mujoco {
public static class BinaryReaderExtensions {
public static Vector3 ReadVector3(this BinaryReader reader) {
var x = reader.ReadSingle();
var y = reader.ReadSingle();
var z = reader.ReadSingle();
return new Vector3(x, y, z);
}
}
public static class BinaryWriterExtensions {
public static void Write(this BinaryWriter writer, Vector3 val) {
writer.Write(val.x);
writer.Write(val.y);
writer.Write(val.z);
}
}
public class StlMeshParser {
private const int _headerLength = 80;
private const int _attributesSizeLength = 2;
private const int _verticesPerTriangle = 3;
private const int _unityLimitNumVerticesPerMesh = 65535;
private const string _asciiFileTypeId = "solid";
private static Vector3 ToXZY(Vector3 v) => new Vector3(v.x, v.z, v.y);
// The binary STL format is described here: https://en.wikipedia.org/wiki/STL_(file_format)
public static Mesh ParseBinary(byte[] stlFileContents, Vector3 scale) {
var fileTypeId = System.Text.Encoding.UTF8.GetString(
stlFileContents.Take(_asciiFileTypeId.Length).ToArray());
if (fileTypeId == _asciiFileTypeId) {
throw new IOException("Ascii STL file format is not supported.");
}
using (var stream = new MemoryStream(stlFileContents)) {
using (var reader = new BinaryReader(stream)) {
reader.ReadBytes(_headerLength);
var numTriangles = reader.ReadUInt32();
var numVertices = numTriangles * _verticesPerTriangle;
if (numVertices > _unityLimitNumVerticesPerMesh) {
throw new IndexOutOfRangeException(
"The mesh exceeds the number of vertices per mesh allowed by Unity. " +
$"({numVertices} > {_unityLimitNumVerticesPerMesh})");
}
var triangleIndices = new List<int>(capacity: (int)numVertices);
var vertices = new List<Vector3>(capacity: (int)numVertices);
var normals = new List<Vector3>(capacity: (int)numVertices);
for (var i = 0; i < numVertices; i += _verticesPerTriangle) {
var triangleNormal = ToXZY(reader.ReadVector3());
normals.AddRange(new[] { triangleNormal, triangleNormal, triangleNormal });
vertices.AddRange(new[] {
ToXZY(reader.ReadVector3()),
ToXZY(reader.ReadVector3()),
ToXZY(reader.ReadVector3()) });
triangleIndices.AddRange(new[] {i, i + 2, i + 1});
reader.ReadInt16(); // Read the unused attribute indices field.
}
var mesh = new Mesh();
mesh.vertices = vertices.ToArray();
mesh.normals = normals.ToArray();
mesh.triangles = triangleIndices.ToArray();
mesh.vertices = mesh.vertices.Select(
vertexPosition => Vector3.Scale(vertexPosition, scale)).ToArray();
mesh.RecalculateNormals();
mesh.RecalculateTangents();
mesh.RecalculateBounds();
return mesh;
}
}
}
public static byte[] SerializeBinary(Mesh mesh) {
using (var stream = new MemoryStream()) {
using (var writer = new BinaryWriter(stream)) {
// Write the header. We only want to write the id and then pad the rest with zeros, up to 80
// bytes.
writer.Write(_asciiFileTypeId);
writer.Write(new byte[_headerLength - _asciiFileTypeId.Length - 1]);
var numTriangles = mesh.triangles.Length / 3;
writer.Write((int)numTriangles);
for (var i = 0; i < mesh.triangles.Length; i += _verticesPerTriangle) {
// STL format uses face normals, while Unity Meshes use vertex normals. We need to convert
// one into another by calculating a mean of vertex normals.
var i1 = mesh.triangles[i];
var i2 = mesh.triangles[i + 1];
var i3 = mesh.triangles[i + 2];
var faceNormal = (mesh.normals[i1] + mesh.normals[i2] + mesh.normals[i3]).normalized;
writer.Write(ToXZY(faceNormal));
writer.Write(ToXZY(mesh.vertices[i1]));
writer.Write(ToXZY(mesh.vertices[i3]));
writer.Write(ToXZY(mesh.vertices[i2]));
writer.Write((short)0);
}
return stream.GetBuffer();
}
}
}
}
}
@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 0d443565163aa4ddea5d910f3517ecfb
timeCreated: 1550063597
licenseType: Pro
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
+16
View File
@@ -0,0 +1,16 @@
{
"name": "Mujoco.Editor",
"rootNamespace": "",
"references": [
"Mujoco"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": true,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}
+7
View File
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 7bdf927c2041ed42ba41bdbbf914db24
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant: