text
stringlengths
7
35.3M
id
stringlengths
11
185
metadata
dict
__index_level_0__
int64
0
2.14k
fileFormatVersion: 2 guid: c6fdbb551d80c435abe6fc911b1ea11f DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ml-agents/Project/Assets/ML-Agents/Examples/GridWorld/Scenes/GridWorld.unity.meta/0
{ "file_path": "ml-agents/Project/Assets/ML-Agents/Examples/GridWorld/Scenes/GridWorld.unity.meta", "repo_id": "ml-agents", "token_count": 64 }
1,913
fileFormatVersion: 2 guid: 3b3523d54e3214c6a90424bf3ee8c934 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ml-agents/Project/Assets/ML-Agents/Examples/Hallway/Demos.meta/0
{ "file_path": "ml-agents/Project/Assets/ML-Agents/Examples/Hallway/Demos.meta", "repo_id": "ml-agents", "token_count": 72 }
1,914
fileFormatVersion: 2 guid: 919e0fed2d0f4447daf1db942cc6ffd9 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ml-agents/Project/Assets/ML-Agents/Examples/Hallway/Scripts/HallwaySettings.cs.meta/0
{ "file_path": "ml-agents/Project/Assets/ML-Agents/Examples/Hallway/Scripts/HallwaySettings.cs.meta", "repo_id": "ml-agents", "token_count": 97 }
1,915
fileFormatVersion: 2 guid: aaa471bd5e2014848a66917476671aed PrefabImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ml-agents/Project/Assets/ML-Agents/Examples/Match3/Prefabs/Match3VisualObs.prefab.meta/0
{ "file_path": "ml-agents/Project/Assets/ML-Agents/Examples/Match3/Prefabs/Match3VisualObs.prefab.meta", "repo_id": "ml-agents", "token_count": 62 }
1,916
using Unity.MLAgents; using Unity.MLAgents.Actuators; using Unity.MLAgents.Integrations.Match3; namespace Unity.MLAgentsExamples { public class Match3ExampleActuatorComponent : Match3ActuatorComponent { /// <inheritdoc/> public override IActuator[] CreateActuators() { var board = GetComponent<Match3Board>(); var seed = RandomSeed == -1 ? gameObject.GetInstanceID() : RandomSeed + 1; return new IActuator[] { new Match3ExampleActuator(board, ForceHeuristic, ActuatorName, seed) }; } } }
ml-agents/Project/Assets/ML-Agents/Examples/Match3/Scripts/Match3ExampleActuatorComponent.cs/0
{ "file_path": "ml-agents/Project/Assets/ML-Agents/Examples/Match3/Scripts/Match3ExampleActuatorComponent.cs", "repo_id": "ml-agents", "token_count": 232 }
1,917
fileFormatVersion: 2 guid: 3d2b9d5547d934200a786212743850c4 folderAsset: yes timeCreated: 1514922259 licenseType: Free DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ml-agents/Project/Assets/ML-Agents/Examples/PushBlock/Prefabs.meta/0
{ "file_path": "ml-agents/Project/Assets/ML-Agents/Examples/PushBlock/Prefabs.meta", "repo_id": "ml-agents", "token_count": 84 }
1,918
%YAML 1.1 %TAG !u! tag:unity3d.com,2011: --- !u!1 &1058115561937900 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 4799209171944556} - component: {fileID: 33372756098612312} - component: {fileID: 23425474254155940} m_Layer: 0 m_Name: mouth m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!4 &4799209171944556 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1058115561937900} m_LocalRotation: {x: -0, y: 1, z: -0, w: 0} m_LocalPosition: {x: 0, y: -0.18299997, z: 0.50040054} m_LocalScale: {x: 0.27602, y: 0.042489994, z: 0.13891} m_Children: [] m_Father: {fileID: 4544987641442146} m_RootOrder: 3 m_LocalEulerAnglesHint: {x: 0, y: 180, z: 0} --- !u!33 &33372756098612312 MeshFilter: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1058115561937900} m_Mesh: {fileID: 10210, guid: 0000000000000000e000000000000000, type: 0} --- !u!23 &23425474254155940 MeshRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1058115561937900} m_Enabled: 1 m_CastShadows: 1 m_ReceiveShadows: 1 m_DynamicOccludee: 1 m_MotionVectors: 1 m_LightProbeUsage: 1 m_ReflectionProbeUsage: 1 m_RayTracingMode: 2 m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: - {fileID: 2100000, guid: f731be6866ce749fd8349e67ae81f76a, type: 2} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 m_StaticBatchRoot: {fileID: 0} m_ProbeAnchor: {fileID: 0} m_LightProbeVolumeOverride: {fileID: 0} m_ScaleInLightmap: 1 m_ReceiveGI: 1 m_PreserveUVs: 1 m_IgnoreNormalsForChartDetection: 0 m_ImportantGI: 0 m_StitchLightmapSeams: 0 m_SelectedEditorRenderState: 3 m_MinimumChartSize: 4 m_AutoUVMaxDistance: 0.5 m_AutoUVMaxAngle: 89 m_LightmapParameters: {fileID: 0} m_SortingLayerID: 0 m_SortingLayer: 0 m_SortingOrder: 0 --- !u!1 &1125452240183160 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 4006990431719496} m_Layer: 0 m_Name: PushBlockWithInputArea m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!4 &4006990431719496 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1125452240183160} m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: - {fileID: 4188187884171146} - {fileID: 4228459933126600} - {fileID: 4643236529171504} - {fileID: 4662886693952972} - {fileID: 4491958117158432} m_Father: {fileID: 0} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!1 &1257458296368784 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 4544987641442146} - component: {fileID: 33329158164785646} - component: {fileID: 23060698592861174} m_Layer: 0 m_Name: AgentCube_Blue m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!4 &4544987641442146 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1257458296368784} m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: - {fileID: 4693470752376230} - {fileID: 4510816898360128} - {fileID: 4885544221206768} - {fileID: 4799209171944556} - {fileID: 4744579300537096} m_Father: {fileID: 4188187884171146} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!33 &33329158164785646 MeshFilter: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1257458296368784} m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0} --- !u!23 &23060698592861174 MeshRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1257458296368784} m_Enabled: 1 m_CastShadows: 1 m_ReceiveShadows: 1 m_DynamicOccludee: 1 m_MotionVectors: 1 m_LightProbeUsage: 1 m_ReflectionProbeUsage: 1 m_RayTracingMode: 2 m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: - {fileID: 2100000, guid: c9fa44c2c3f8ce74ca39a3355ea42631, type: 2} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 m_StaticBatchRoot: {fileID: 0} m_ProbeAnchor: {fileID: 0} m_LightProbeVolumeOverride: {fileID: 0} m_ScaleInLightmap: 1 m_ReceiveGI: 1 m_PreserveUVs: 1 m_IgnoreNormalsForChartDetection: 0 m_ImportantGI: 0 m_StitchLightmapSeams: 0 m_SelectedEditorRenderState: 3 m_MinimumChartSize: 4 m_AutoUVMaxDistance: 0.5 m_AutoUVMaxAngle: 89 m_LightmapParameters: {fileID: 0} m_SortingLayerID: 0 m_SortingLayer: 0 m_SortingOrder: 0 --- !u!1 &1441513772919942 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 4228459933126600} - component: {fileID: 33257578884602618} - component: {fileID: 23824899148377476} - component: {fileID: 65797106708039188} m_Layer: 0 m_Name: Goal m_TagString: goal m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!4 &4228459933126600 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1441513772919942} m_LocalRotation: {x: 0, y: -0, z: -0, w: 1} m_LocalPosition: {x: -0, y: -0.03, z: -10.5} m_LocalScale: {x: 0.01, y: 0.01, z: 0.010748733} m_Children: [] m_Father: {fileID: 4006990431719496} m_RootOrder: 1 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!33 &33257578884602618 MeshFilter: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1441513772919942} m_Mesh: {fileID: 4300004, guid: c639386c12f5f7841892163a199dfacc, type: 3} --- !u!23 &23824899148377476 MeshRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1441513772919942} m_Enabled: 1 m_CastShadows: 1 m_ReceiveShadows: 1 m_DynamicOccludee: 1 m_MotionVectors: 1 m_LightProbeUsage: 1 m_ReflectionProbeUsage: 1 m_RayTracingMode: 2 m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: - {fileID: 2100000, guid: c67450f290f3e4897bc40276a619e78d, type: 2} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 m_StaticBatchRoot: {fileID: 0} m_ProbeAnchor: {fileID: 0} m_LightProbeVolumeOverride: {fileID: 0} m_ScaleInLightmap: 1 m_ReceiveGI: 1 m_PreserveUVs: 0 m_IgnoreNormalsForChartDetection: 0 m_ImportantGI: 0 m_StitchLightmapSeams: 0 m_SelectedEditorRenderState: 3 m_MinimumChartSize: 4 m_AutoUVMaxDistance: 0.5 m_AutoUVMaxAngle: 89 m_LightmapParameters: {fileID: 0} m_SortingLayerID: 0 m_SortingLayer: 0 m_SortingOrder: 0 --- !u!65 &65797106708039188 BoxCollider: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1441513772919942} m_Material: {fileID: 0} m_IsTrigger: 0 m_Enabled: 1 serializedVersion: 2 m_Size: {x: 2500, y: 300, z: 400} m_Center: {x: 0, y: 2.5, z: 0} --- !u!1 &1461267750064770 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 4510816898360128} - component: {fileID: 33894909717767508} - component: {fileID: 23501817194256018} m_Layer: 0 m_Name: eye m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!4 &4510816898360128 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1461267750064770} m_LocalRotation: {x: -0, y: 1, z: -0, w: 0} m_LocalPosition: {x: 0.29999995, y: 0.07399994, z: 0.50040054} m_LocalScale: {x: 0.29457998, y: 0.29457998, z: 0.29457998} m_Children: [] m_Father: {fileID: 4544987641442146} m_RootOrder: 1 m_LocalEulerAnglesHint: {x: 0, y: 180, z: 0} --- !u!33 &33894909717767508 MeshFilter: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1461267750064770} m_Mesh: {fileID: 10210, guid: 0000000000000000e000000000000000, type: 0} --- !u!23 &23501817194256018 MeshRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1461267750064770} m_Enabled: 1 m_CastShadows: 1 m_ReceiveShadows: 1 m_DynamicOccludee: 1 m_MotionVectors: 1 m_LightProbeUsage: 1 m_ReflectionProbeUsage: 1 m_RayTracingMode: 2 m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: - {fileID: 2100000, guid: f731be6866ce749fd8349e67ae81f76a, type: 2} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 m_StaticBatchRoot: {fileID: 0} m_ProbeAnchor: {fileID: 0} m_LightProbeVolumeOverride: {fileID: 0} m_ScaleInLightmap: 1 m_ReceiveGI: 1 m_PreserveUVs: 1 m_IgnoreNormalsForChartDetection: 0 m_ImportantGI: 0 m_StitchLightmapSeams: 0 m_SelectedEditorRenderState: 3 m_MinimumChartSize: 4 m_AutoUVMaxDistance: 0.5 m_AutoUVMaxAngle: 89 m_LightmapParameters: {fileID: 0} m_SortingLayerID: 0 m_SortingLayer: 0 m_SortingOrder: 0 --- !u!1 &1489716781518988 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 4188187884171146} - component: {fileID: 54817351390947638} - component: {fileID: 114306175693660464} - component: {fileID: 1929062229609328833} - component: {fileID: 65880096262939968} - component: {fileID: 114807072692257076} - component: {fileID: 114451319691753174} - component: {fileID: 8964598783836598940} - component: {fileID: 4081319787948195948} - component: {fileID: 572751784} - component: {fileID: 572751783} - component: {fileID: 6641003793403090299} m_Layer: 0 m_Name: Agent m_TagString: agent m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!4 &4188187884171146 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1489716781518988} m_LocalRotation: {x: 0, y: 1, z: 0, w: 0} m_LocalPosition: {x: 0, y: 1, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: - {fileID: 4544987641442146} m_Father: {fileID: 4006990431719496} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 180, z: 0} --- !u!54 &54817351390947638 Rigidbody: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1489716781518988} serializedVersion: 2 m_Mass: 10 m_Drag: 4 m_AngularDrag: 0.05 m_UseGravity: 1 m_IsKinematic: 0 m_Interpolate: 0 m_Constraints: 112 m_CollisionDetection: 0 --- !u!114 &114306175693660464 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1489716781518988} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 5d1c4e0b1822b495aa52bc52839ecb30, type: 3} m_Name: m_EditorClassIdentifier: m_BrainParameters: VectorObservationSize: 0 NumStackedVectorObservations: 2 m_ActionSpec: m_NumContinuousActions: 0 BranchSizes: VectorActionSize: VectorActionDescriptions: [] VectorActionSpaceType: 0 hasUpgradedBrainParametersWithActionSpec: 1 m_Model: {fileID: 5022602860645237092, guid: bee50ae7fd03e4e16a4ac45db4d96f6e, type: 3} m_InferenceDevice: 2 m_BehaviorType: 0 m_BehaviorName: PushBlock TeamId: 0 m_UseChildSensors: 1 m_UseChildActuators: 1 m_ObservableAttributeHandling: 0 --- !u!114 &1929062229609328833 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1489716781518988} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 925dd654260d9400ea7c46c3fccbc885, type: 3} m_Name: m_EditorClassIdentifier: agentParameters: maxStep: 0 hasUpgradedFromAgentParameters: 1 MaxStep: 5000 ground: {fileID: 1500989011945850} area: {fileID: 1125452240183160} areaBounds: m_Center: {x: 0, y: 0, z: 0} m_Extent: {x: 0, y: 0, z: 0} block: {fileID: 1831337770648600} goalDetect: {fileID: 0} --- !u!65 &65880096262939968 BoxCollider: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1489716781518988} m_Material: {fileID: 0} m_IsTrigger: 0 m_Enabled: 1 serializedVersion: 2 m_Size: {x: 1, y: 1, z: 1} m_Center: {x: 0, y: 0, z: 0} --- !u!114 &114807072692257076 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1489716781518988} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 6bb6b867a41448888c1cd4f99643ad71, type: 3} m_Name: m_EditorClassIdentifier: m_SensorName: RayPerceptionSensor m_DetectableTags: - block - goal - wall m_RaysPerDirection: 3 m_MaxRayDegrees: 90 m_SphereCastRadius: 0.5 m_RayLength: 12 m_RayLayerMask: serializedVersion: 2 m_Bits: 4294967291 m_ObservationStacks: 3 rayHitColor: {r: 1, g: 0, b: 0, a: 1} rayMissColor: {r: 1, g: 1, b: 1, a: 1} m_StartVerticalOffset: 0 m_EndVerticalOffset: 0 --- !u!114 &114451319691753174 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1489716781518988} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 6bb6b867a41448888c1cd4f99643ad71, type: 3} m_Name: m_EditorClassIdentifier: m_SensorName: OffsetRayPerceptionSensor m_DetectableTags: - block - goal - wall m_RaysPerDirection: 3 m_MaxRayDegrees: 90 m_SphereCastRadius: 0.5 m_RayLength: 12 m_RayLayerMask: serializedVersion: 2 m_Bits: 4294967291 m_ObservationStacks: 3 rayHitColor: {r: 1, g: 0, b: 0, a: 1} rayMissColor: {r: 1, g: 1, b: 1, a: 1} m_StartVerticalOffset: 1.5 m_EndVerticalOffset: 1.5 --- !u!114 &8964598783836598940 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1489716781518988} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 3a5c9d521e5ef4759a8246a07d52221e, type: 3} m_Name: m_EditorClassIdentifier: DecisionPeriod: 5 TakeActionsBetweenDecisions: 1 --- !u!114 &4081319787948195948 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1489716781518988} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 3a6da8f78a394c6ab027688eab81e04d, type: 3} m_Name: m_EditorClassIdentifier: debugCommandLineOverride: --- !u!114 &572751784 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1489716781518988} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 62899f850307741f2a39c98a8b639597, type: 3} m_Name: m_EditorClassIdentifier: m_Actions: {fileID: -944628639613478452, guid: fcfa5a3b2c4254b2baad1ae474fc4b93, type: 3} m_NotificationBehavior: 3 m_UIInputModule: {fileID: 0} m_DeviceLostEvent: m_PersistentCalls: m_Calls: [] m_DeviceRegainedEvent: m_PersistentCalls: m_Calls: [] m_ControlsChangedEvent: m_PersistentCalls: m_Calls: [] m_ActionEvents: [] m_NeverAutoSwitchControlSchemes: 0 m_DefaultControlScheme: m_DefaultActionMap: Movement m_SplitScreenIndex: -1 m_Camera: {fileID: 0} --- !u!114 &572751783 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1489716781518988} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 33005b124d7f841a191249baf2bacb2a, type: 3} m_Name: m_EditorClassIdentifier: m_ActionSpec: m_NumContinuousActions: 2 BranchSizes: 02000000 --- !u!114 &6641003793403090299 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1489716781518988} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: bb9a2d951ffa44f53ba04a31f2712f5f, type: 3} m_Name: m_EditorClassIdentifier: JumpTime: 0.5 --- !u!1 &1500989011945850 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 4643236529171504} - component: {fileID: 33737551691836984} - component: {fileID: 23549423015434358} - component: {fileID: 65513349759460256} m_Layer: 0 m_Name: Ground m_TagString: ground m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!4 &4643236529171504 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1500989011945850} m_LocalRotation: {x: 0, y: -0, z: -0, w: 1} m_LocalPosition: {x: -0, y: 0, z: -0.00000030517577} m_LocalScale: {x: 0.01, y: 0.01, z: 0.01} m_Children: [] m_Father: {fileID: 4006990431719496} m_RootOrder: 2 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!33 &33737551691836984 MeshFilter: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1500989011945850} m_Mesh: {fileID: 4300002, guid: c639386c12f5f7841892163a199dfacc, type: 3} --- !u!23 &23549423015434358 MeshRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1500989011945850} m_Enabled: 1 m_CastShadows: 1 m_ReceiveShadows: 1 m_DynamicOccludee: 1 m_MotionVectors: 1 m_LightProbeUsage: 1 m_ReflectionProbeUsage: 1 m_RayTracingMode: 2 m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: - {fileID: 2100000, guid: acba6bf2a290a496bb8989b42bf8698d, type: 2} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 m_StaticBatchRoot: {fileID: 0} m_ProbeAnchor: {fileID: 0} m_LightProbeVolumeOverride: {fileID: 0} m_ScaleInLightmap: 1 m_ReceiveGI: 1 m_PreserveUVs: 0 m_IgnoreNormalsForChartDetection: 0 m_ImportantGI: 0 m_StitchLightmapSeams: 0 m_SelectedEditorRenderState: 3 m_MinimumChartSize: 4 m_AutoUVMaxDistance: 0.5 m_AutoUVMaxAngle: 89 m_LightmapParameters: {fileID: 0} m_SortingLayerID: 0 m_SortingLayer: 0 m_SortingOrder: 0 --- !u!65 &65513349759460256 BoxCollider: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1500989011945850} m_Material: {fileID: 0} m_IsTrigger: 0 m_Enabled: 1 serializedVersion: 2 m_Size: {x: 2500, y: 100, z: 2500} m_Center: {x: 0, y: -50, z: 0} --- !u!1 &1587735394719530 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 4744579300537096} - component: {fileID: 33895795138265702} - component: {fileID: 23899848265046434} m_Layer: 0 m_Name: Headband m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!4 &4744579300537096 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1587735394719530} m_LocalRotation: {x: -0, y: -0, z: 0.016506119, w: 0.9998638} m_LocalPosition: {x: 0, y: 0.341, z: 0} m_LocalScale: {x: 1.0441425, y: 0.19278127, z: 1.0441422} m_Children: [] m_Father: {fileID: 4544987641442146} m_RootOrder: 4 m_LocalEulerAnglesHint: {x: 0, y: -179.99998, z: 1.8920001} --- !u!33 &33895795138265702 MeshFilter: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1587735394719530} m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0} --- !u!23 &23899848265046434 MeshRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1587735394719530} m_Enabled: 1 m_CastShadows: 1 m_ReceiveShadows: 1 m_DynamicOccludee: 1 m_MotionVectors: 1 m_LightProbeUsage: 1 m_ReflectionProbeUsage: 1 m_RayTracingMode: 2 m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: - {fileID: 2100000, guid: 04be259c590de46f69db4cbd1da877d5, type: 2} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 m_StaticBatchRoot: {fileID: 0} m_ProbeAnchor: {fileID: 0} m_LightProbeVolumeOverride: {fileID: 0} m_ScaleInLightmap: 1 m_ReceiveGI: 1 m_PreserveUVs: 1 m_IgnoreNormalsForChartDetection: 0 m_ImportantGI: 0 m_StitchLightmapSeams: 0 m_SelectedEditorRenderState: 3 m_MinimumChartSize: 4 m_AutoUVMaxDistance: 0.5 m_AutoUVMaxAngle: 89 m_LightmapParameters: {fileID: 0} m_SortingLayerID: 0 m_SortingLayer: 0 m_SortingOrder: 0 --- !u!1 &1724888327628444 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 4693470752376230} - component: {fileID: 20603941467042180} m_Layer: 0 m_Name: AgentCamera m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 0 --- !u!4 &4693470752376230 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1724888327628444} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0.15} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: [] m_Father: {fileID: 4544987641442146} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!20 &20603941467042180 Camera: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1724888327628444} m_Enabled: 1 serializedVersion: 2 m_ClearFlags: 2 m_BackGroundColor: {r: 0.46666667, g: 0.5647059, b: 0.60784316, a: 1} m_projectionMatrixMode: 1 m_GateFitMode: 2 m_FOVAxisMode: 0 m_SensorSize: {x: 36, y: 24} m_LensShift: {x: 0, y: 0} m_FocalLength: 50 m_NormalizedViewPortRect: serializedVersion: 2 x: 0 y: 0 width: 1 height: 1 near clip plane: 0.3 far clip plane: 1000 field of view: 60 orthographic: 0 orthographic size: 5 m_Depth: 0 m_CullingMask: serializedVersion: 2 m_Bits: 4294950911 m_RenderingPath: -1 m_TargetTexture: {fileID: 0} m_TargetDisplay: 0 m_TargetEye: 3 m_HDR: 1 m_AllowMSAA: 1 m_AllowDynamicResolution: 0 m_ForceIntoRT: 0 m_OcclusionCulling: 1 m_StereoConvergence: 10 m_StereoSeparation: 0.022 --- !u!1 &1831337770648600 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 4491958117158432} - component: {fileID: 33211910135534124} - component: {fileID: 65500237382738106} - component: {fileID: 23965303024756010} - component: {fileID: 54485094479975724} - component: {fileID: 4489253887773211256} m_Layer: 0 m_Name: Block m_TagString: block m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!4 &4491958117158432 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1831337770648600} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 2, y: 1, z: -1.43} m_LocalScale: {x: 2, y: 0.75, z: 2} m_Children: [] m_Father: {fileID: 4006990431719496} m_RootOrder: 4 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!33 &33211910135534124 MeshFilter: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1831337770648600} m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0} --- !u!65 &65500237382738106 BoxCollider: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1831337770648600} m_Material: {fileID: 0} m_IsTrigger: 0 m_Enabled: 1 serializedVersion: 2 m_Size: {x: 1, y: 1, z: 1} m_Center: {x: 0, y: 0, z: 0} --- !u!23 &23965303024756010 MeshRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1831337770648600} m_Enabled: 1 m_CastShadows: 1 m_ReceiveShadows: 1 m_DynamicOccludee: 1 m_MotionVectors: 1 m_LightProbeUsage: 1 m_ReflectionProbeUsage: 1 m_RayTracingMode: 2 m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: - {fileID: 2100000, guid: eaad04b0e0dec42229c9cb00a981d7ac, type: 2} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 m_StaticBatchRoot: {fileID: 0} m_ProbeAnchor: {fileID: 0} m_LightProbeVolumeOverride: {fileID: 0} m_ScaleInLightmap: 1 m_ReceiveGI: 1 m_PreserveUVs: 1 m_IgnoreNormalsForChartDetection: 0 m_ImportantGI: 0 m_StitchLightmapSeams: 0 m_SelectedEditorRenderState: 3 m_MinimumChartSize: 4 m_AutoUVMaxDistance: 0.5 m_AutoUVMaxAngle: 89 m_LightmapParameters: {fileID: 0} m_SortingLayerID: 0 m_SortingLayer: 0 m_SortingOrder: 0 --- !u!54 &54485094479975724 Rigidbody: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1831337770648600} serializedVersion: 2 m_Mass: 10 m_Drag: 0.5 m_AngularDrag: 0.05 m_UseGravity: 1 m_IsKinematic: 0 m_Interpolate: 0 m_Constraints: 112 m_CollisionDetection: 0 --- !u!114 &4489253887773211256 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1831337770648600} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: ec55820c897dd4f41904e8c43085f56b, type: 3} m_Name: m_EditorClassIdentifier: agent: {fileID: 0} --- !u!1 &1948183181472910 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 4662886693952972} - component: {fileID: 33923598962272346} - component: {fileID: 23386727129662884} - component: {fileID: 65537431973827738} - component: {fileID: 65603921567931242} - component: {fileID: 65701990377179520} - component: {fileID: 65220627410631168} m_Layer: 0 m_Name: WallsOuter m_TagString: wall m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!4 &4662886693952972 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1948183181472910} m_LocalRotation: {x: 0, y: -0, z: -0, w: 1} m_LocalPosition: {x: -0, y: 0, z: 0} m_LocalScale: {x: 0.01, y: 0.16, z: 0.01} m_Children: [] m_Father: {fileID: 4006990431719496} m_RootOrder: 3 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!33 &33923598962272346 MeshFilter: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1948183181472910} m_Mesh: {fileID: 4300000, guid: c639386c12f5f7841892163a199dfacc, type: 3} --- !u!23 &23386727129662884 MeshRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1948183181472910} m_Enabled: 0 m_CastShadows: 1 m_ReceiveShadows: 1 m_DynamicOccludee: 1 m_MotionVectors: 1 m_LightProbeUsage: 1 m_ReflectionProbeUsage: 1 m_RayTracingMode: 2 m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: - {fileID: 10306, guid: 0000000000000000f000000000000000, type: 0} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 m_StaticBatchRoot: {fileID: 0} m_ProbeAnchor: {fileID: 0} m_LightProbeVolumeOverride: {fileID: 0} m_ScaleInLightmap: 1 m_ReceiveGI: 1 m_PreserveUVs: 0 m_IgnoreNormalsForChartDetection: 0 m_ImportantGI: 0 m_StitchLightmapSeams: 0 m_SelectedEditorRenderState: 3 m_MinimumChartSize: 4 m_AutoUVMaxDistance: 0.5 m_AutoUVMaxAngle: 89 m_LightmapParameters: {fileID: 0} m_SortingLayerID: 0 m_SortingLayer: 0 m_SortingOrder: 0 --- !u!65 &65537431973827738 BoxCollider: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1948183181472910} m_Material: {fileID: 0} m_IsTrigger: 0 m_Enabled: 1 serializedVersion: 2 m_Size: {x: 50, y: 200, z: 2600} m_Center: {x: -1275, y: 50, z: 0} --- !u!65 &65603921567931242 BoxCollider: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1948183181472910} m_Material: {fileID: 0} m_IsTrigger: 0 m_Enabled: 1 serializedVersion: 2 m_Size: {x: 50, y: 200, z: 2600} m_Center: {x: 1275, y: 50, z: 0} --- !u!65 &65701990377179520 BoxCollider: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1948183181472910} m_Material: {fileID: 0} m_IsTrigger: 0 m_Enabled: 1 serializedVersion: 2 m_Size: {x: 2500, y: 200, z: 50} m_Center: {x: 0, y: 50, z: -1275} --- !u!65 &65220627410631168 BoxCollider: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1948183181472910} m_Material: {fileID: 0} m_IsTrigger: 0 m_Enabled: 1 serializedVersion: 2 m_Size: {x: 2500, y: 200, z: 50} m_Center: {x: 0, y: 50, z: 1275} --- !u!1 &1998092687759860 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 4885544221206768} - component: {fileID: 33708290946592760} - component: {fileID: 23666927211414522} m_Layer: 0 m_Name: eye m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!4 &4885544221206768 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1998092687759860} m_LocalRotation: {x: -0, y: 1, z: -0, w: 0} m_LocalPosition: {x: -0.29999995, y: 0.07399994, z: 0.50040054} m_LocalScale: {x: 0.29457998, y: 0.29457998, z: 0.29457998} m_Children: [] m_Father: {fileID: 4544987641442146} m_RootOrder: 2 m_LocalEulerAnglesHint: {x: 0, y: 180, z: 0} --- !u!33 &33708290946592760 MeshFilter: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1998092687759860} m_Mesh: {fileID: 10210, guid: 0000000000000000e000000000000000, type: 0} --- !u!23 &23666927211414522 MeshRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1998092687759860} m_Enabled: 1 m_CastShadows: 1 m_ReceiveShadows: 1 m_DynamicOccludee: 1 m_MotionVectors: 1 m_LightProbeUsage: 1 m_ReflectionProbeUsage: 1 m_RayTracingMode: 2 m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: - {fileID: 2100000, guid: f731be6866ce749fd8349e67ae81f76a, type: 2} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 m_StaticBatchRoot: {fileID: 0} m_ProbeAnchor: {fileID: 0} m_LightProbeVolumeOverride: {fileID: 0} m_ScaleInLightmap: 1 m_ReceiveGI: 1 m_PreserveUVs: 1 m_IgnoreNormalsForChartDetection: 0 m_ImportantGI: 0 m_StitchLightmapSeams: 0 m_SelectedEditorRenderState: 3 m_MinimumChartSize: 4 m_AutoUVMaxDistance: 0.5 m_AutoUVMaxAngle: 89 m_LightmapParameters: {fileID: 0} m_SortingLayerID: 0 m_SortingLayer: 0 m_SortingOrder: 0
ml-agents/Project/Assets/ML-Agents/Examples/PushBlockWithInput/Prefabs/PushBlockWithInputArea.prefab/0
{ "file_path": "ml-agents/Project/Assets/ML-Agents/Examples/PushBlockWithInput/Prefabs/PushBlockWithInputArea.prefab", "repo_id": "ml-agents", "token_count": 15480 }
1,919
using UnityEngine; public class PushBlockWithInputSettings : MonoBehaviour { /// <summary> /// The "walking speed" of the agents in the scene. /// </summary> public float agentRunSpeed; /// <summary> /// The agent rotation speed. /// Every agent will use this setting. /// </summary> public float agentRotationSpeed; public float agentJumpForce; public float agentJumpCoolDown; /// <summary> /// The spawn area margin multiplier. /// ex: .9 means 90% of spawn area will be used. /// .1 margin will be left (so players don't spawn off of the edge). /// The higher this value, the longer training time required. /// </summary> public float spawnAreaMarginMultiplier; /// <summary> /// When a goal is scored the ground will switch to this /// material for a few seconds. /// </summary> public Material goalScoredMaterial; /// <summary> /// When an agent fails, the ground will turn this material for a few seconds. /// </summary> public Material failMaterial; }
ml-agents/Project/Assets/ML-Agents/Examples/PushBlockWithInput/Scripts/PushBlockWithInputSettings.cs/0
{ "file_path": "ml-agents/Project/Assets/ML-Agents/Examples/PushBlockWithInput/Scripts/PushBlockWithInputSettings.cs", "repo_id": "ml-agents", "token_count": 334 }
1,920
// Upgrade NOTE: replaced 'mul(UNITY_MATRIX_MVP,*)' with 'UnityObjectToClipPos(*)' Shader "Custom/Outline and ScreenSpace texture" { Properties { [Header(Outline)] _OutlineVal ("Outline value", Range(0., 2.)) = 1. _OutlineCol ("Outline color", color) = (1., 1., 1., 1.) [Header(Texture)] _MainTex ("Texture", 2D) = "white" {} _Zoom ("Zoom", Range(0.5, 20)) = 1 _SpeedX ("Speed along X", Range(-1, 1)) = 0 _SpeedY ("Speed along Y", Range(-1, 1)) = 0 } SubShader { Tags { "Queue"="Geometry" "RenderType"="Opaque" } Pass { Cull Front CGPROGRAM #pragma vertex vert #pragma fragment frag #include "UnityCG.cginc" struct v2f { float4 pos : SV_POSITION; }; float _OutlineVal; v2f vert(appdata_base v) { v2f o; // Convert vertex to clip space o.pos = UnityObjectToClipPos(v.vertex); // Convert normal to view space (camera space) float3 normal = mul((float3x3) UNITY_MATRIX_IT_MV, v.normal); // Compute normal value in clip space normal.x *= UNITY_MATRIX_P[0][0]; normal.y *= UNITY_MATRIX_P[1][1]; // Scale the model depending the previous computed normal and outline value o.pos.xy += _OutlineVal * normal.xy; return o; } fixed4 _OutlineCol; fixed4 frag(v2f i) : SV_Target { return _OutlineCol; } ENDCG } Pass { CGPROGRAM #pragma vertex vert #pragma fragment frag #include "UnityCG.cginc" float4 vert(appdata_base v) : SV_POSITION { return UnityObjectToClipPos(v.vertex); } sampler2D _MainTex; float _Zoom; float _SpeedX; float _SpeedY; fixed4 frag(float4 i : VPOS) : SV_Target { // Screen space texture return tex2D(_MainTex, ((i.xy / _ScreenParams.xy) + float2(_Time.y * _SpeedX, _Time.y * _SpeedY)) / _Zoom); } ENDCG } } }
ml-agents/Project/Assets/ML-Agents/Examples/SharedAssets/Materials/ShaderOutline.shader/0
{ "file_path": "ml-agents/Project/Assets/ML-Agents/Examples/SharedAssets/Materials/ShaderOutline.shader", "repo_id": "ml-agents", "token_count": 839 }
1,921
fileFormatVersion: 2 guid: b3f44c5319ba14b88a7cc096cfd91979 NativeFormatImporter: externalObjects: {} mainObjectFileID: 100100000 userData: assetBundleName: assetBundleVariant:
ml-agents/Project/Assets/ML-Agents/Examples/SharedAssets/Prefabs/AgentCubeWithCamera_Purple.prefab.meta/0
{ "file_path": "ml-agents/Project/Assets/ML-Agents/Examples/SharedAssets/Prefabs/AgentCubeWithCamera_Purple.prefab.meta", "repo_id": "ml-agents", "token_count": 76 }
1,922
fileFormatVersion: 2 guid: 2c8b8cb388800475291391089d1a2351 NativeFormatImporter: externalObjects: {} mainObjectFileID: 100100000 userData: assetBundleName: assetBundleVariant:
ml-agents/Project/Assets/ML-Agents/Examples/SharedAssets/Prefabs/Logo-PlaneMesh-GRAY.prefab.meta/0
{ "file_path": "ml-agents/Project/Assets/ML-Agents/Examples/SharedAssets/Prefabs/Logo-PlaneMesh-GRAY.prefab.meta", "repo_id": "ml-agents", "token_count": 75 }
1,923
%YAML 1.1 %TAG !u! tag:unity3d.com,2011: --- !u!1001 &100100000 Prefab: m_ObjectHideFlags: 1 serializedVersion: 2 m_Modification: m_TransformParent: {fileID: 0} m_Modifications: [] m_RemovedComponents: [] m_ParentPrefab: {fileID: 0} m_RootGameObject: {fileID: 1147101126618602} m_IsPrefabParent: 1 --- !u!1 &1147101126618602 GameObject: m_ObjectHideFlags: 0 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} serializedVersion: 5 m_Component: - component: {fileID: 4134156155830030} - component: {fileID: 33781785803569660} - component: {fileID: 65535238649650828} - component: {fileID: 23435667802952786} m_Layer: 0 m_Name: Symbol_X m_TagString: symbol_X m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!1 &1800632560103032 GameObject: m_ObjectHideFlags: 0 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} serializedVersion: 5 m_Component: - component: {fileID: 4247497194682288} - component: {fileID: 33445901905875220} - component: {fileID: 23052055968543938} m_Layer: 0 m_Name: symbol_x m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!4 &4134156155830030 Transform: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1147101126618602} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 7, y: 2.45, z: 24.7} m_LocalScale: {x: 4.08117, y: 4.01236, z: 1.1449} m_Children: - {fileID: 4247497194682288} m_Father: {fileID: 0} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!4 &4247497194682288 Transform: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1800632560103032} m_LocalRotation: {x: -0, y: -0, z: 0.38268343, w: 0.92387956} m_LocalPosition: {x: 0, y: 0, z: -0.337} m_LocalScale: {x: 0.39643255, y: 0.39643255, z: 1.4011297} m_Children: [] m_Father: {fileID: 4134156155830030} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 45} --- !u!23 &23052055968543938 MeshRenderer: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1800632560103032} m_Enabled: 1 m_CastShadows: 1 m_ReceiveShadows: 1 m_DynamicOccludee: 1 m_MotionVectors: 1 m_LightProbeUsage: 1 m_ReflectionProbeUsage: 1 m_Materials: - {fileID: 2100000, guid: 69fefdd39d2b34b169e921910bed9c0d, type: 2} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 m_StaticBatchRoot: {fileID: 0} m_ProbeAnchor: {fileID: 0} m_LightProbeVolumeOverride: {fileID: 0} m_ScaleInLightmap: 1 m_PreserveUVs: 0 m_IgnoreNormalsForChartDetection: 0 m_ImportantGI: 0 m_StitchLightmapSeams: 0 m_SelectedEditorRenderState: 3 m_MinimumChartSize: 4 m_AutoUVMaxDistance: 0.5 m_AutoUVMaxAngle: 89 m_LightmapParameters: {fileID: 0} m_SortingLayerID: 0 m_SortingLayer: 0 m_SortingOrder: 0 --- !u!23 &23435667802952786 MeshRenderer: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1147101126618602} m_Enabled: 1 m_CastShadows: 1 m_ReceiveShadows: 1 m_DynamicOccludee: 1 m_MotionVectors: 1 m_LightProbeUsage: 1 m_ReflectionProbeUsage: 1 m_Materials: - {fileID: 2100000, guid: eaad04b0e0dec42229c9cb00a981d7ac, type: 2} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 m_StaticBatchRoot: {fileID: 0} m_ProbeAnchor: {fileID: 0} m_LightProbeVolumeOverride: {fileID: 0} m_ScaleInLightmap: 1 m_PreserveUVs: 1 m_IgnoreNormalsForChartDetection: 0 m_ImportantGI: 0 m_StitchLightmapSeams: 0 m_SelectedEditorRenderState: 3 m_MinimumChartSize: 4 m_AutoUVMaxDistance: 0.5 m_AutoUVMaxAngle: 89 m_LightmapParameters: {fileID: 0} m_SortingLayerID: 0 m_SortingLayer: 0 m_SortingOrder: 0 --- !u!33 &33445901905875220 MeshFilter: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1800632560103032} m_Mesh: {fileID: 4300000, guid: df826ba32791e458caefe83b4498ce35, type: 3} --- !u!33 &33781785803569660 MeshFilter: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1147101126618602} m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0} --- !u!65 &65535238649650828 BoxCollider: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1147101126618602} m_Material: {fileID: 0} m_IsTrigger: 0 m_Enabled: 1 serializedVersion: 2 m_Size: {x: 1, y: 1, z: 1} m_Center: {x: 0, y: 0, z: 0}
ml-agents/Project/Assets/ML-Agents/Examples/SharedAssets/Prefabs/Symbol_X.prefab/0
{ "file_path": "ml-agents/Project/Assets/ML-Agents/Examples/SharedAssets/Prefabs/Symbol_X.prefab", "repo_id": "ml-agents", "token_count": 2145 }
1,924
using UnityEngine; namespace Unity.MLAgentsExamples { public class DirectionIndicator : MonoBehaviour { public bool updatedByAgent; //should this be updated by the agent? If not, it will use local settings public Transform transformToFollow; //ex: hips or body public Transform targetToLookAt; //target in the scene the indicator will point to public float heightOffset; private float m_StartingYPos; void OnEnable() { m_StartingYPos = transform.position.y; } void Update() { if (updatedByAgent) return; transform.position = new Vector3(transformToFollow.position.x, m_StartingYPos + heightOffset, transformToFollow.position.z); Vector3 walkDir = targetToLookAt.position - transform.position; walkDir.y = 0; //flatten dir on the y transform.rotation = Quaternion.LookRotation(walkDir); } //Public method to allow an agent to directly update this component public void MatchOrientation(Transform t) { transform.position = new Vector3(t.position.x, m_StartingYPos + heightOffset, t.position.z); transform.rotation = t.rotation; } } }
ml-agents/Project/Assets/ML-Agents/Examples/SharedAssets/Scripts/DirectionIndicator.cs/0
{ "file_path": "ml-agents/Project/Assets/ML-Agents/Examples/SharedAssets/Scripts/DirectionIndicator.cs", "repo_id": "ml-agents", "token_count": 528 }
1,925
using UnityEngine; using Unity.MLAgents; namespace Unity.MLAgentsExamples { /// <summary> /// A helper class for the ML-Agents example scenes to override various /// global settings, and restore them afterwards. /// This can modify some Physics and time-stepping properties, so you /// shouldn't copy it into your project unless you know what you're doing. /// </summary> public class ProjectSettingsOverrides : MonoBehaviour { // Original values Vector3 m_OriginalGravity; float m_OriginalFixedDeltaTime; float m_OriginalMaximumDeltaTime; int m_OriginalSolverIterations; int m_OriginalSolverVelocityIterations; bool m_OriginalReuseCollisionCallbacks; [Tooltip("Increase or decrease the scene gravity. Use ~3x to make things less floaty")] public float gravityMultiplier = 1.0f; [Header("Advanced physics settings")] [Tooltip("The interval in seconds at which physics and other fixed frame rate updates (like MonoBehaviour's FixedUpdate) are performed.")] public float fixedDeltaTime = .02f; [Tooltip("The maximum time a frame can take. Physics and other fixed frame rate updates (like MonoBehaviour's FixedUpdate) will be performed only for this duration of time per frame.")] public float maximumDeltaTime = 1.0f / 3.0f; [Tooltip("Determines how accurately Rigidbody joints and collision contacts are resolved. (default 6). Must be positive.")] public int solverIterations = 6; [Tooltip("Affects how accurately the Rigidbody joints and collision contacts are resolved. (default 1). Must be positive.")] public int solverVelocityIterations = 1; [Tooltip("Determines whether the garbage collector should reuse only a single instance of a Collision type for all collision callbacks. Reduces Garbage.")] public bool reuseCollisionCallbacks = true; public void Awake() { // Save the original values m_OriginalGravity = Physics.gravity; m_OriginalFixedDeltaTime = Time.fixedDeltaTime; m_OriginalMaximumDeltaTime = Time.maximumDeltaTime; m_OriginalSolverIterations = Physics.defaultSolverIterations; m_OriginalSolverVelocityIterations = Physics.defaultSolverVelocityIterations; m_OriginalReuseCollisionCallbacks = Physics.reuseCollisionCallbacks; // Override Physics.gravity *= gravityMultiplier; Time.fixedDeltaTime = fixedDeltaTime; Time.maximumDeltaTime = maximumDeltaTime; Physics.defaultSolverIterations = solverIterations; Physics.defaultSolverVelocityIterations = solverVelocityIterations; Physics.reuseCollisionCallbacks = reuseCollisionCallbacks; // Make sure the Academy singleton is initialized first, since it will create the SideChannels. Academy.Instance.EnvironmentParameters.RegisterCallback("gravity", f => { Physics.gravity = new Vector3(0, -f, 0); }); } public void OnDestroy() { Physics.gravity = m_OriginalGravity; Time.fixedDeltaTime = m_OriginalFixedDeltaTime; Time.maximumDeltaTime = m_OriginalMaximumDeltaTime; Physics.defaultSolverIterations = m_OriginalSolverIterations; Physics.defaultSolverVelocityIterations = m_OriginalSolverVelocityIterations; Physics.reuseCollisionCallbacks = m_OriginalReuseCollisionCallbacks; } } }
ml-agents/Project/Assets/ML-Agents/Examples/SharedAssets/Scripts/ProjectSettingsOverrides.cs/0
{ "file_path": "ml-agents/Project/Assets/ML-Agents/Examples/SharedAssets/Scripts/ProjectSettingsOverrides.cs", "repo_id": "ml-agents", "token_count": 1260 }
1,926
fileFormatVersion: 2 guid: 4ed55169d81ee40a0a1f8be2420eba78 timeCreated: 1513650193 licenseType: Free NativeFormatImporter: externalObjects: {} mainObjectFileID: 13400000 userData: assetBundleName: assetBundleVariant:
ml-agents/Project/Assets/ML-Agents/Examples/Soccer/Materials/Physic_Materials/NoFriction.physicMaterial.meta/0
{ "file_path": "ml-agents/Project/Assets/ML-Agents/Examples/Soccer/Materials/Physic_Materials/NoFriction.physicMaterial.meta", "repo_id": "ml-agents", "token_count": 90 }
1,927
fileFormatVersion: 2 guid: 92c2f286041694279ba415db1e246842 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ml-agents/Project/Assets/ML-Agents/Examples/Walker/Materials.meta/0
{ "file_path": "ml-agents/Project/Assets/ML-Agents/Examples/Walker/Materials.meta", "repo_id": "ml-agents", "token_count": 67 }
1,928
using System; using UnityEngine; using Unity.MLAgents; using Unity.MLAgents.Actuators; using Unity.MLAgentsExamples; using Unity.MLAgents.Sensors; using BodyPart = Unity.MLAgentsExamples.BodyPart; using Random = UnityEngine.Random; public class WalkerAgent : Agent { [Header("Walk Speed")] [Range(0.1f, 10)] [SerializeField] //The walking speed to try and achieve private float m_TargetWalkingSpeed = 10; public float MTargetWalkingSpeed // property { get { return m_TargetWalkingSpeed; } set { m_TargetWalkingSpeed = Mathf.Clamp(value, .1f, m_maxWalkingSpeed); } } const float m_maxWalkingSpeed = 10; //The max walking speed //Should the agent sample a new goal velocity each episode? //If true, walkSpeed will be randomly set between zero and m_maxWalkingSpeed in OnEpisodeBegin() //If false, the goal velocity will be walkingSpeed public bool randomizeWalkSpeedEachEpisode; //The direction an agent will walk during training. private Vector3 m_WorldDirToWalk = Vector3.right; [Header("Target To Walk Towards")] public Transform target; //Target the agent will walk towards during training. [Header("Body Parts")] public Transform hips; public Transform chest; public Transform spine; public Transform head; public Transform thighL; public Transform shinL; public Transform footL; public Transform thighR; public Transform shinR; public Transform footR; public Transform armL; public Transform forearmL; public Transform handL; public Transform armR; public Transform forearmR; public Transform handR; //This will be used as a stabilized model space reference point for observations //Because ragdolls can move erratically during training, using a stabilized reference transform improves learning OrientationCubeController m_OrientationCube; //The indicator graphic gameobject that points towards the target DirectionIndicator m_DirectionIndicator; JointDriveController m_JdController; EnvironmentParameters m_ResetParams; public override void Initialize() { m_OrientationCube = GetComponentInChildren<OrientationCubeController>(); m_DirectionIndicator = GetComponentInChildren<DirectionIndicator>(); //Setup each body part m_JdController = GetComponent<JointDriveController>(); m_JdController.SetupBodyPart(hips); m_JdController.SetupBodyPart(chest); m_JdController.SetupBodyPart(spine); m_JdController.SetupBodyPart(head); m_JdController.SetupBodyPart(thighL); m_JdController.SetupBodyPart(shinL); m_JdController.SetupBodyPart(footL); m_JdController.SetupBodyPart(thighR); m_JdController.SetupBodyPart(shinR); m_JdController.SetupBodyPart(footR); m_JdController.SetupBodyPart(armL); m_JdController.SetupBodyPart(forearmL); m_JdController.SetupBodyPart(handL); m_JdController.SetupBodyPart(armR); m_JdController.SetupBodyPart(forearmR); m_JdController.SetupBodyPart(handR); m_ResetParams = Academy.Instance.EnvironmentParameters; } /// <summary> /// Loop over body parts and reset them to initial conditions. /// </summary> public override void OnEpisodeBegin() { //Reset all of the body parts foreach (var bodyPart in m_JdController.bodyPartsDict.Values) { bodyPart.Reset(bodyPart); } //Random start rotation to help generalize hips.rotation = Quaternion.Euler(0, Random.Range(0.0f, 360.0f), 0); UpdateOrientationObjects(); //Set our goal walking speed MTargetWalkingSpeed = randomizeWalkSpeedEachEpisode ? Random.Range(0.1f, m_maxWalkingSpeed) : MTargetWalkingSpeed; } /// <summary> /// Add relevant information on each body part to observations. /// </summary> public void CollectObservationBodyPart(BodyPart bp, VectorSensor sensor) { //GROUND CHECK sensor.AddObservation(bp.groundContact.touchingGround); // Is this bp touching the ground //Get velocities in the context of our orientation cube's space //Note: You can get these velocities in world space as well but it may not train as well. sensor.AddObservation(m_OrientationCube.transform.InverseTransformDirection(bp.rb.velocity)); sensor.AddObservation(m_OrientationCube.transform.InverseTransformDirection(bp.rb.angularVelocity)); //Get position relative to hips in the context of our orientation cube's space sensor.AddObservation(m_OrientationCube.transform.InverseTransformDirection(bp.rb.position - hips.position)); if (bp.rb.transform != hips && bp.rb.transform != handL && bp.rb.transform != handR) { sensor.AddObservation(bp.rb.transform.localRotation); sensor.AddObservation(bp.currentStrength / m_JdController.maxJointForceLimit); } } /// <summary> /// Loop over body parts to add them to observation. /// </summary> public override void CollectObservations(VectorSensor sensor) { var cubeForward = m_OrientationCube.transform.forward; //velocity we want to match var velGoal = cubeForward * MTargetWalkingSpeed; //ragdoll's avg vel var avgVel = GetAvgVelocity(); //current ragdoll velocity. normalized sensor.AddObservation(Vector3.Distance(velGoal, avgVel)); //avg body vel relative to cube sensor.AddObservation(m_OrientationCube.transform.InverseTransformDirection(avgVel)); //vel goal relative to cube sensor.AddObservation(m_OrientationCube.transform.InverseTransformDirection(velGoal)); //rotation deltas sensor.AddObservation(Quaternion.FromToRotation(hips.forward, cubeForward)); sensor.AddObservation(Quaternion.FromToRotation(head.forward, cubeForward)); //Position of target position relative to cube sensor.AddObservation(m_OrientationCube.transform.InverseTransformPoint(target.transform.position)); foreach (var bodyPart in m_JdController.bodyPartsList) { CollectObservationBodyPart(bodyPart, sensor); } } public override void OnActionReceived(ActionBuffers actionBuffers) { var bpDict = m_JdController.bodyPartsDict; var i = -1; var continuousActions = actionBuffers.ContinuousActions; bpDict[chest].SetJointTargetRotation(continuousActions[++i], continuousActions[++i], continuousActions[++i]); bpDict[spine].SetJointTargetRotation(continuousActions[++i], continuousActions[++i], continuousActions[++i]); bpDict[thighL].SetJointTargetRotation(continuousActions[++i], continuousActions[++i], 0); bpDict[thighR].SetJointTargetRotation(continuousActions[++i], continuousActions[++i], 0); bpDict[shinL].SetJointTargetRotation(continuousActions[++i], 0, 0); bpDict[shinR].SetJointTargetRotation(continuousActions[++i], 0, 0); bpDict[footR].SetJointTargetRotation(continuousActions[++i], continuousActions[++i], continuousActions[++i]); bpDict[footL].SetJointTargetRotation(continuousActions[++i], continuousActions[++i], continuousActions[++i]); bpDict[armL].SetJointTargetRotation(continuousActions[++i], continuousActions[++i], 0); bpDict[armR].SetJointTargetRotation(continuousActions[++i], continuousActions[++i], 0); bpDict[forearmL].SetJointTargetRotation(continuousActions[++i], 0, 0); bpDict[forearmR].SetJointTargetRotation(continuousActions[++i], 0, 0); bpDict[head].SetJointTargetRotation(continuousActions[++i], continuousActions[++i], 0); //update joint strength settings bpDict[chest].SetJointStrength(continuousActions[++i]); bpDict[spine].SetJointStrength(continuousActions[++i]); bpDict[head].SetJointStrength(continuousActions[++i]); bpDict[thighL].SetJointStrength(continuousActions[++i]); bpDict[shinL].SetJointStrength(continuousActions[++i]); bpDict[footL].SetJointStrength(continuousActions[++i]); bpDict[thighR].SetJointStrength(continuousActions[++i]); bpDict[shinR].SetJointStrength(continuousActions[++i]); bpDict[footR].SetJointStrength(continuousActions[++i]); bpDict[armL].SetJointStrength(continuousActions[++i]); bpDict[forearmL].SetJointStrength(continuousActions[++i]); bpDict[armR].SetJointStrength(continuousActions[++i]); bpDict[forearmR].SetJointStrength(continuousActions[++i]); } //Update OrientationCube and DirectionIndicator void UpdateOrientationObjects() { m_WorldDirToWalk = target.position - hips.position; m_OrientationCube.UpdateOrientation(hips, target); if (m_DirectionIndicator) { m_DirectionIndicator.MatchOrientation(m_OrientationCube.transform); } } void FixedUpdate() { UpdateOrientationObjects(); var cubeForward = m_OrientationCube.transform.forward; // Set reward for this step according to mixture of the following elements. // a. Match target speed //This reward will approach 1 if it matches perfectly and approach zero as it deviates var matchSpeedReward = GetMatchingVelocityReward(cubeForward * MTargetWalkingSpeed, GetAvgVelocity()); //Check for NaNs if (float.IsNaN(matchSpeedReward)) { throw new ArgumentException( "NaN in moveTowardsTargetReward.\n" + $" cubeForward: {cubeForward}\n" + $" hips.velocity: {m_JdController.bodyPartsDict[hips].rb.velocity}\n" + $" maximumWalkingSpeed: {m_maxWalkingSpeed}" ); } // b. Rotation alignment with target direction. //This reward will approach 1 if it faces the target direction perfectly and approach zero as it deviates var headForward = head.forward; headForward.y = 0; // var lookAtTargetReward = (Vector3.Dot(cubeForward, head.forward) + 1) * .5F; var lookAtTargetReward = (Vector3.Dot(cubeForward, headForward) + 1) * .5F; //Check for NaNs if (float.IsNaN(lookAtTargetReward)) { throw new ArgumentException( "NaN in lookAtTargetReward.\n" + $" cubeForward: {cubeForward}\n" + $" head.forward: {head.forward}" ); } AddReward(matchSpeedReward * lookAtTargetReward); } //Returns the average velocity of all of the body parts //Using the velocity of the hips only has shown to result in more erratic movement from the limbs, so... //...using the average helps prevent this erratic movement Vector3 GetAvgVelocity() { Vector3 velSum = Vector3.zero; //ALL RBS int numOfRb = 0; foreach (var item in m_JdController.bodyPartsList) { numOfRb++; velSum += item.rb.velocity; } var avgVel = velSum / numOfRb; return avgVel; } //normalized value of the difference in avg speed vs goal walking speed. public float GetMatchingVelocityReward(Vector3 velocityGoal, Vector3 actualVelocity) { //distance between our actual velocity and goal velocity var velDeltaMagnitude = Mathf.Clamp(Vector3.Distance(actualVelocity, velocityGoal), 0, MTargetWalkingSpeed); //return the value on a declining sigmoid shaped curve that decays from 1 to 0 //This reward will approach 1 if it matches perfectly and approach zero as it deviates return Mathf.Pow(1 - Mathf.Pow(velDeltaMagnitude / MTargetWalkingSpeed, 2), 2); } /// <summary> /// Agent touched the target /// </summary> public void TouchedTarget() { AddReward(1f); } }
ml-agents/Project/Assets/ML-Agents/Examples/Walker/Scripts/WalkerAgent.cs/0
{ "file_path": "ml-agents/Project/Assets/ML-Agents/Examples/Walker/Scripts/WalkerAgent.cs", "repo_id": "ml-agents", "token_count": 4621 }
1,929
fileFormatVersion: 2 guid: 54ab68247b13ffe42927e8859e0e57cc NativeFormatImporter: externalObjects: {} mainObjectFileID: 2100000 userData: assetBundleName: assetBundleVariant:
ml-agents/Project/Assets/ML-Agents/Examples/WallJump/Materials/WallJumpCourtSuccess.mat.meta/0
{ "file_path": "ml-agents/Project/Assets/ML-Agents/Examples/WallJump/Materials/WallJumpCourtSuccess.mat.meta", "repo_id": "ml-agents", "token_count": 72 }
1,930
%YAML 1.1 %TAG !u! tag:unity3d.com,2011: --- !u!850595691 &4890085278179872738 LightingSettings: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_Name: WallJumpSettings serializedVersion: 4 m_GIWorkflowMode: 0 m_EnableBakedLightmaps: 1 m_EnableRealtimeLightmaps: 1 m_RealtimeEnvironmentLighting: 1 m_BounceScale: 1 m_AlbedoBoost: 1 m_IndirectOutputScale: 1 m_UsingShadowmask: 1 m_BakeBackend: 0 m_LightmapMaxSize: 1024 m_BakeResolution: 40 m_Padding: 2 m_LightmapCompression: 3 m_AO: 0 m_AOMaxDistance: 1 m_CompAOExponent: 1 m_CompAOExponentDirect: 0 m_ExtractAO: 0 m_MixedBakeMode: 2 m_LightmapsBakeMode: 1 m_FilterMode: 1 m_LightmapParameters: {fileID: 15204, guid: 0000000000000000f000000000000000, type: 0} m_ExportTrainingData: 0 m_TrainingDataDestination: TrainingData m_RealtimeResolution: 2 m_ForceWhiteAlbedo: 0 m_ForceUpdates: 0 m_FinalGather: 0 m_FinalGatherRayCount: 256 m_FinalGatherFiltering: 1 m_PVRCulling: 1 m_PVRSampling: 1 m_PVRDirectSampleCount: 32 m_PVRSampleCount: 500 m_PVREnvironmentSampleCount: 500 m_PVREnvironmentReferencePointCount: 2048 m_LightProbeSampleCountMultiplier: 4 m_PVRBounces: 2 m_PVRMinBounces: 2 m_PVREnvironmentMIS: 0 m_PVRFilteringMode: 2 m_PVRDenoiserTypeDirect: 0 m_PVRDenoiserTypeIndirect: 0 m_PVRDenoiserTypeAO: 0 m_PVRFilterTypeDirect: 0 m_PVRFilterTypeIndirect: 0 m_PVRFilterTypeAO: 0 m_PVRFilteringGaussRadiusDirect: 1 m_PVRFilteringGaussRadiusIndirect: 5 m_PVRFilteringGaussRadiusAO: 2 m_PVRFilteringAtrousPositionSigmaDirect: 0.5 m_PVRFilteringAtrousPositionSigmaIndirect: 2 m_PVRFilteringAtrousPositionSigmaAO: 1 m_PVRTiledBaking: 0
ml-agents/Project/Assets/ML-Agents/Examples/WallJump/Scenes/WallJumpSettings.lighting/0
{ "file_path": "ml-agents/Project/Assets/ML-Agents/Examples/WallJump/Scenes/WallJumpSettings.lighting", "repo_id": "ml-agents", "token_count": 750 }
1,931
%YAML 1.1 %TAG !u! tag:unity3d.com,2011: --- !u!1 &3425944858556105217 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 4000013202901713542} - component: {fileID: 3824013808842067416} - component: {fileID: 3612783679526746640} m_Layer: 0 m_Name: MeshBodySeg3 m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!4 &4000013202901713542 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 3425944858556105217} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 0.49789357, y: 0.75, z: 0.49789354} m_Children: - {fileID: 7430253518057581880} m_Father: {fileID: 7430253517665647541} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 89.98, y: 0, z: 0} --- !u!33 &3824013808842067416 MeshFilter: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 3425944858556105217} m_Mesh: {fileID: 10208, guid: 0000000000000000e000000000000000, type: 0} --- !u!23 &3612783679526746640 MeshRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 3425944858556105217} m_Enabled: 1 m_CastShadows: 1 m_ReceiveShadows: 1 m_DynamicOccludee: 1 m_MotionVectors: 1 m_LightProbeUsage: 1 m_ReflectionProbeUsage: 1 m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: - {fileID: 2100000, guid: c9fa44c2c3f8ce74ca39a3355ea42631, type: 2} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 m_StaticBatchRoot: {fileID: 0} m_ProbeAnchor: {fileID: 0} m_LightProbeVolumeOverride: {fileID: 0} m_ScaleInLightmap: 1 m_PreserveUVs: 0 m_IgnoreNormalsForChartDetection: 0 m_ImportantGI: 0 m_StitchLightmapSeams: 0 m_SelectedEditorRenderState: 3 m_MinimumChartSize: 4 m_AutoUVMaxDistance: 0.5 m_AutoUVMaxAngle: 89 m_LightmapParameters: {fileID: 0} m_SortingLayerID: 0 m_SortingLayer: 0 m_SortingOrder: 0 --- !u!1 &4341398410231292401 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 3706743983009984222} - component: {fileID: 5451460609091845275} - component: {fileID: 3076491853972576545} - component: {fileID: 1758637205552806262} - component: {fileID: 5075903151365038534} - component: {fileID: 1896215321265182657} m_Layer: 0 m_Name: mouth m_TagString: agent m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!4 &3706743983009984222 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 4341398410231292401} m_LocalRotation: {x: 0.7071068, y: -0, z: -0, w: 0.7071068} m_LocalPosition: {x: 0, y: -0.16541958, z: 0.9368001} m_LocalScale: {x: 0.15541708, y: 0.03930019, z: 0.026193839} m_Children: [] m_Father: {fileID: 7430253517585478437} m_RootOrder: 2 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!33 &5451460609091845275 MeshFilter: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 4341398410231292401} m_Mesh: {fileID: 10207, guid: 0000000000000000e000000000000000, type: 0} --- !u!23 &3076491853972576545 MeshRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 4341398410231292401} m_Enabled: 1 m_CastShadows: 1 m_ReceiveShadows: 1 m_DynamicOccludee: 1 m_MotionVectors: 1 m_LightProbeUsage: 1 m_ReflectionProbeUsage: 1 m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: - {fileID: 2100000, guid: 69fefdd39d2b34b169e921910bed9c0d, type: 2} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 m_StaticBatchRoot: {fileID: 0} m_ProbeAnchor: {fileID: 0} m_LightProbeVolumeOverride: {fileID: 0} m_ScaleInLightmap: 1 m_PreserveUVs: 0 m_IgnoreNormalsForChartDetection: 0 m_ImportantGI: 0 m_StitchLightmapSeams: 0 m_SelectedEditorRenderState: 3 m_MinimumChartSize: 4 m_AutoUVMaxDistance: 0.5 m_AutoUVMaxAngle: 89 m_LightmapParameters: {fileID: 0} m_SortingLayerID: 0 m_SortingLayer: 0 m_SortingOrder: 0 --- !u!135 &1758637205552806262 SphereCollider: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 4341398410231292401} m_Material: {fileID: 0} m_IsTrigger: 0 m_Enabled: 1 serializedVersion: 2 m_Radius: 2 m_Center: {x: -0.13, y: 1.25, z: -5} --- !u!54 &5075903151365038534 Rigidbody: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 4341398410231292401} serializedVersion: 2 m_Mass: 1 m_Drag: 0 m_AngularDrag: 0.05 m_UseGravity: 1 m_IsKinematic: 0 m_Interpolate: 0 m_Constraints: 0 m_CollisionDetection: 3 --- !u!138 &1896215321265182657 FixedJoint: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 4341398410231292401} m_ConnectedBody: {fileID: 7430253517585478438} m_BreakForce: Infinity m_BreakTorque: Infinity m_EnableCollision: 0 m_EnablePreprocessing: 1 m_MassScale: 0.1 m_ConnectedMassScale: 1 --- !u!1 &5066808357271954180 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 7123748794063981559} - component: {fileID: 6091561061807415017} - component: {fileID: 138307165290057190} m_Layer: 0 m_Name: MeshBodySeg2 m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!4 &7123748794063981559 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 5066808357271954180} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 0.5606166, y: 0.75, z: 0.5606165} m_Children: - {fileID: 7430253518207655505} m_Father: {fileID: 7430253518623948737} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 89.98, y: 0, z: 0} --- !u!33 &6091561061807415017 MeshFilter: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 5066808357271954180} m_Mesh: {fileID: 10208, guid: 0000000000000000e000000000000000, type: 0} --- !u!23 &138307165290057190 MeshRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 5066808357271954180} m_Enabled: 1 m_CastShadows: 1 m_ReceiveShadows: 1 m_DynamicOccludee: 1 m_MotionVectors: 1 m_LightProbeUsage: 1 m_ReflectionProbeUsage: 1 m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: - {fileID: 2100000, guid: c9fa44c2c3f8ce74ca39a3355ea42631, type: 2} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 m_StaticBatchRoot: {fileID: 0} m_ProbeAnchor: {fileID: 0} m_LightProbeVolumeOverride: {fileID: 0} m_ScaleInLightmap: 1 m_PreserveUVs: 0 m_IgnoreNormalsForChartDetection: 0 m_ImportantGI: 0 m_StitchLightmapSeams: 0 m_SelectedEditorRenderState: 3 m_MinimumChartSize: 4 m_AutoUVMaxDistance: 0.5 m_AutoUVMaxAngle: 89 m_LightmapParameters: {fileID: 0} m_SortingLayerID: 0 m_SortingLayer: 0 m_SortingOrder: 0 --- !u!1 &7080128691884336933 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 8679239658813963324} - component: {fileID: 4173695739753575171} - component: {fileID: 599689188601990516} m_Layer: 0 m_Name: MeshBodySeg1 m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!4 &8679239658813963324 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7080128691884336933} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 0.6562462, y: 0.75, z: 0.6562462} m_Children: - {fileID: 7430253518678196321} m_Father: {fileID: 7430253518698367209} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 89.98, y: 0, z: 0} --- !u!33 &4173695739753575171 MeshFilter: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7080128691884336933} m_Mesh: {fileID: 10208, guid: 0000000000000000e000000000000000, type: 0} --- !u!23 &599689188601990516 MeshRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7080128691884336933} m_Enabled: 1 m_CastShadows: 1 m_ReceiveShadows: 1 m_DynamicOccludee: 1 m_MotionVectors: 1 m_LightProbeUsage: 1 m_ReflectionProbeUsage: 1 m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: - {fileID: 2100000, guid: c9fa44c2c3f8ce74ca39a3355ea42631, type: 2} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 m_StaticBatchRoot: {fileID: 0} m_ProbeAnchor: {fileID: 0} m_LightProbeVolumeOverride: {fileID: 0} m_ScaleInLightmap: 1 m_PreserveUVs: 0 m_IgnoreNormalsForChartDetection: 0 m_ImportantGI: 0 m_StitchLightmapSeams: 0 m_SelectedEditorRenderState: 3 m_MinimumChartSize: 4 m_AutoUVMaxDistance: 0.5 m_AutoUVMaxAngle: 89 m_LightmapParameters: {fileID: 0} m_SortingLayerID: 0 m_SortingLayer: 0 m_SortingOrder: 0 --- !u!1 &7430253517558768489 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 7430253517558768490} - component: {fileID: 7430253517558768484} - component: {fileID: 7430253517558768491} m_Layer: 0 m_Name: pupil m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!4 &7430253517558768490 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253517558768489} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0.46, y: 0, z: 0} m_LocalScale: {x: 0.116126545, y: 0.35806346, z: 0.35806346} m_Children: [] m_Father: {fileID: 7430253518344216410} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!33 &7430253517558768484 MeshFilter: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253517558768489} m_Mesh: {fileID: 10207, guid: 0000000000000000e000000000000000, type: 0} --- !u!23 &7430253517558768491 MeshRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253517558768489} m_Enabled: 1 m_CastShadows: 1 m_ReceiveShadows: 1 m_DynamicOccludee: 1 m_MotionVectors: 1 m_LightProbeUsage: 1 m_ReflectionProbeUsage: 1 m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: - {fileID: 2100000, guid: 69fefdd39d2b34b169e921910bed9c0d, type: 2} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 m_StaticBatchRoot: {fileID: 0} m_ProbeAnchor: {fileID: 0} m_LightProbeVolumeOverride: {fileID: 0} m_ScaleInLightmap: 1 m_PreserveUVs: 0 m_IgnoreNormalsForChartDetection: 0 m_ImportantGI: 0 m_StitchLightmapSeams: 0 m_SelectedEditorRenderState: 3 m_MinimumChartSize: 4 m_AutoUVMaxDistance: 0.5 m_AutoUVMaxAngle: 89 m_LightmapParameters: {fileID: 0} m_SortingLayerID: 0 m_SortingLayer: 0 m_SortingOrder: 0 --- !u!1 &7430253517585478436 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 7430253517585478437} - component: {fileID: 7430253517585478438} - component: {fileID: 7430253517585478432} - component: {fileID: 7430253517585478439} m_Layer: 0 m_Name: BodySeg0 m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!4 &7430253517585478437 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253517585478436} m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: - {fileID: 7430253518935506121} - {fileID: 7430253518344216410} - {fileID: 3706743983009984222} - {fileID: 3480290756406204138} - {fileID: 7430253518698367209} m_Father: {fileID: 7430253518223459951} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!54 &7430253517585478438 Rigidbody: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253517585478436} serializedVersion: 2 m_Mass: 10 m_Drag: 0 m_AngularDrag: 0.05 m_UseGravity: 1 m_IsKinematic: 0 m_Interpolate: 0 m_Constraints: 0 m_CollisionDetection: 3 --- !u!136 &7430253517585478432 CapsuleCollider: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253517585478436} m_Material: {fileID: 0} m_IsTrigger: 0 m_Enabled: 1 m_Radius: 0.37 m_Height: 2 m_Direction: 2 m_Center: {x: 0, y: 0, z: 0} --- !u!153 &7430253517585478439 ConfigurableJoint: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253517585478436} m_ConnectedBody: {fileID: 7430253518698367210} m_Anchor: {x: 0, y: 0, z: -0.8} m_Axis: {x: 1, y: 0, z: 0} m_AutoConfigureConnectedAnchor: 1 m_ConnectedAnchor: {x: 0, y: 0.5162998, z: 0.00029248} serializedVersion: 2 m_SecondaryAxis: {x: 0, y: 1, z: 0} m_XMotion: 0 m_YMotion: 0 m_ZMotion: 0 m_AngularXMotion: 1 m_AngularYMotion: 1 m_AngularZMotion: 0 m_LinearLimitSpring: spring: 0 damper: 0 m_LinearLimit: limit: 0 bounciness: 0 contactDistance: 0 m_AngularXLimitSpring: spring: 0 damper: 0 m_LowAngularXLimit: limit: -60 bounciness: 0 contactDistance: 0 m_HighAngularXLimit: limit: 60 bounciness: 0 contactDistance: 0 m_AngularYZLimitSpring: spring: 0 damper: 0 m_AngularYLimit: limit: 60 bounciness: 0 contactDistance: 0 m_AngularZLimit: limit: 0 bounciness: 0 contactDistance: 0 m_TargetPosition: {x: 0, y: 0, z: 0} m_TargetVelocity: {x: 0, y: 0, z: 0} m_XDrive: serializedVersion: 3 positionSpring: 0 positionDamper: 0 maximumForce: 3.4028233e+38 m_YDrive: serializedVersion: 3 positionSpring: 0 positionDamper: 0 maximumForce: 3.4028233e+38 m_ZDrive: serializedVersion: 3 positionSpring: 0 positionDamper: 0 maximumForce: 3.4028233e+38 m_TargetRotation: {x: 0, y: 0, z: 0, w: 1} m_TargetAngularVelocity: {x: 0, y: 0, z: 0} m_RotationDriveMode: 1 m_AngularXDrive: serializedVersion: 3 positionSpring: 0 positionDamper: 0 maximumForce: 3.4028233e+38 m_AngularYZDrive: serializedVersion: 3 positionSpring: 0 positionDamper: 0 maximumForce: 3.4028233e+38 m_SlerpDrive: serializedVersion: 3 positionSpring: 1 positionDamper: 1 maximumForce: 3.4028233e+38 m_ProjectionMode: 1 m_ProjectionDistance: 0.1 m_ProjectionAngle: 180 m_ConfiguredInWorldSpace: 0 m_SwapBodies: 0 m_BreakForce: Infinity m_BreakTorque: Infinity m_EnableCollision: 0 m_EnablePreprocessing: 1 m_MassScale: 1 m_ConnectedMassScale: 1 --- !u!1 &7430253517594625975 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 7430253517594625968} - component: {fileID: 7430253517594625970} - component: {fileID: 7430253517594625969} m_Layer: 0 m_Name: pupil m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!4 &7430253517594625968 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253517594625975} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0.46, y: 0, z: 0} m_LocalScale: {x: 0.116126545, y: 0.35806346, z: 0.35806346} m_Children: [] m_Father: {fileID: 7430253518935506121} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!33 &7430253517594625970 MeshFilter: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253517594625975} m_Mesh: {fileID: 10207, guid: 0000000000000000e000000000000000, type: 0} --- !u!23 &7430253517594625969 MeshRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253517594625975} m_Enabled: 1 m_CastShadows: 1 m_ReceiveShadows: 1 m_DynamicOccludee: 1 m_MotionVectors: 1 m_LightProbeUsage: 1 m_ReflectionProbeUsage: 1 m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: - {fileID: 2100000, guid: 69fefdd39d2b34b169e921910bed9c0d, type: 2} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 m_StaticBatchRoot: {fileID: 0} m_ProbeAnchor: {fileID: 0} m_LightProbeVolumeOverride: {fileID: 0} m_ScaleInLightmap: 1 m_PreserveUVs: 0 m_IgnoreNormalsForChartDetection: 0 m_ImportantGI: 0 m_StitchLightmapSeams: 0 m_SelectedEditorRenderState: 3 m_MinimumChartSize: 4 m_AutoUVMaxDistance: 0.5 m_AutoUVMaxAngle: 89 m_LightmapParameters: {fileID: 0} m_SortingLayerID: 0 m_SortingLayer: 0 m_SortingOrder: 0 --- !u!1 &7430253517665647540 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 7430253517665647541} - component: {fileID: 7430253517665647543} - component: {fileID: 7430253517665647542} m_Layer: 0 m_Name: BodySeg3 m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!4 &7430253517665647541 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253517665647540} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0, y: -1.1159996, z: -0.0004159212} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: - {fileID: 4000013202901713542} m_Father: {fileID: 7430253518623948737} m_RootOrder: 1 m_LocalEulerAnglesHint: {x: 89.98, y: 0, z: 0} --- !u!136 &7430253517665647543 CapsuleCollider: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253517665647540} m_Material: {fileID: 0} m_IsTrigger: 0 m_Enabled: 1 m_Radius: 0.26 m_Height: 1.46 m_Direction: 1 m_Center: {x: 0, y: 0, z: 0} --- !u!54 &7430253517665647542 Rigidbody: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253517665647540} serializedVersion: 2 m_Mass: 10 m_Drag: 0 m_AngularDrag: 0.05 m_UseGravity: 1 m_IsKinematic: 0 m_Interpolate: 0 m_Constraints: 0 m_CollisionDetection: 3 --- !u!1 &7430253518057581887 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 7430253518057581880} - component: {fileID: 7430253518057581882} - component: {fileID: 7430253518057581881} m_Layer: 0 m_Name: stripe m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!4 &7430253518057581880 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253518057581887} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0, y: 0.000012721227, z: -0.048762847} m_LocalScale: {x: 1.0226575, y: 0.14130552, z: 0.9652029} m_Children: [] m_Father: {fileID: 4000013202901713542} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 89.98, y: 0, z: 0} --- !u!33 &7430253518057581882 MeshFilter: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253518057581887} m_Mesh: {fileID: 10208, guid: 0000000000000000e000000000000000, type: 0} --- !u!23 &7430253518057581881 MeshRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253518057581887} m_Enabled: 1 m_CastShadows: 1 m_ReceiveShadows: 1 m_DynamicOccludee: 1 m_MotionVectors: 1 m_LightProbeUsage: 1 m_ReflectionProbeUsage: 1 m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: - {fileID: 2100000, guid: eaad04b0e0dec42229c9cb00a981d7ac, type: 2} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 m_StaticBatchRoot: {fileID: 0} m_ProbeAnchor: {fileID: 0} m_LightProbeVolumeOverride: {fileID: 0} m_ScaleInLightmap: 1 m_PreserveUVs: 0 m_IgnoreNormalsForChartDetection: 0 m_ImportantGI: 0 m_StitchLightmapSeams: 0 m_SelectedEditorRenderState: 3 m_MinimumChartSize: 4 m_AutoUVMaxDistance: 0.5 m_AutoUVMaxAngle: 89 m_LightmapParameters: {fileID: 0} m_SortingLayerID: 0 m_SortingLayer: 0 m_SortingOrder: 0 --- !u!1 &7430253518207655504 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 7430253518207655505} - component: {fileID: 7430253518207655507} - component: {fileID: 7430253518207655506} m_Layer: 0 m_Name: stripe m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!4 &7430253518207655505 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253518207655504} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0, y: 0.000012721227, z: -0.048762847} m_LocalScale: {x: 1.0226575, y: 0.14130552, z: 0.9652029} m_Children: [] m_Father: {fileID: 7123748794063981559} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 89.98, y: 0, z: 0} --- !u!33 &7430253518207655507 MeshFilter: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253518207655504} m_Mesh: {fileID: 10208, guid: 0000000000000000e000000000000000, type: 0} --- !u!23 &7430253518207655506 MeshRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253518207655504} m_Enabled: 1 m_CastShadows: 1 m_ReceiveShadows: 1 m_DynamicOccludee: 1 m_MotionVectors: 1 m_LightProbeUsage: 1 m_ReflectionProbeUsage: 1 m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: - {fileID: 2100000, guid: eaad04b0e0dec42229c9cb00a981d7ac, type: 2} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 m_StaticBatchRoot: {fileID: 0} m_ProbeAnchor: {fileID: 0} m_LightProbeVolumeOverride: {fileID: 0} m_ScaleInLightmap: 1 m_PreserveUVs: 0 m_IgnoreNormalsForChartDetection: 0 m_ImportantGI: 0 m_StitchLightmapSeams: 0 m_SelectedEditorRenderState: 3 m_MinimumChartSize: 4 m_AutoUVMaxDistance: 0.5 m_AutoUVMaxAngle: 89 m_LightmapParameters: {fileID: 0} m_SortingLayerID: 0 m_SortingLayer: 0 m_SortingOrder: 0 --- !u!1 &7430253518223459950 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 7430253518223459951} - component: {fileID: 7430253518223459941} - component: {fileID: 7430253518223459940} - component: {fileID: 7430253518223459947} - component: {fileID: 7430253518223459946} - component: {fileID: 7430253518223459945} m_Layer: 0 m_Name: Worm m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!4 &7430253518223459951 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253518223459950} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0, y: 1.65, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: - {fileID: 7430253517585478437} - {fileID: 2730837554089586253} - {fileID: 5623293504353442273} m_Father: {fileID: 0} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!114 &7430253518223459941 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253518223459950} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 5d1c4e0b1822b495aa52bc52839ecb30, type: 3} m_Name: m_EditorClassIdentifier: m_BrainParameters: VectorObservationSize: 64 NumStackedVectorObservations: 1 m_ActionSpec: m_NumContinuousActions: 9 BranchSizes: VectorActionSize: 09000000 VectorActionDescriptions: [] VectorActionSpaceType: 1 hasUpgradedBrainParametersWithActionSpec: 1 m_Model: {fileID: 11400000, guid: 117512193457f4b35994eedc14532276, type: 3} m_InferenceDevice: 2 m_BehaviorType: 0 m_BehaviorName: Worm TeamId: 0 m_UseChildSensors: 1 m_UseChildActuators: 1 m_ObservableAttributeHandling: 0 --- !u!114 &7430253518223459940 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253518223459950} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 292fce25fb4b541f4b007a7b92c5923c, type: 3} m_Name: m_EditorClassIdentifier: agentParameters: maxStep: 0 hasUpgradedFromAgentParameters: 1 MaxStep: 5000 TargetPrefab: {fileID: 3839136118347789758, guid: 46734abd0de454192b407379c6a4ab8d, type: 3} bodySegment0: {fileID: 7430253517585478437} bodySegment1: {fileID: 7430253518698367209} bodySegment2: {fileID: 7430253518623948737} bodySegment3: {fileID: 7430253517665647541} --- !u!114 &7430253518223459947 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253518223459950} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 1b29724baddfa457da6eeab446fa49ca, type: 3} m_Name: m_EditorClassIdentifier: maxJointSpring: 3000 jointDampen: 30 maxJointForceLimit: 10000 bodyPartsList: [] --- !u!114 &7430253518223459946 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253518223459950} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 3a5c9d521e5ef4759a8246a07d52221e, type: 3} m_Name: m_EditorClassIdentifier: DecisionPeriod: 5 TakeActionsBetweenDecisions: 0 --- !u!114 &7430253518223459945 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253518223459950} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 3a6da8f78a394c6ab027688eab81e04d, type: 3} m_Name: m_EditorClassIdentifier: debugCommandLineOverride: --- !u!1 &7430253518344216409 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 7430253518344216410} - component: {fileID: 7430253518344216407} - component: {fileID: 7430253518344216406} - component: {fileID: 7430253518344216405} - component: {fileID: 7430253518344216404} - component: {fileID: 7430253518344216411} m_Layer: 0 m_Name: eyeL m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!4 &7430253518344216410 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253518344216409} m_LocalRotation: {x: 0.119500756, y: 0.6809617, z: 0.7218742, w: -0.030138876} m_LocalPosition: {x: -0.26999986, y: 0.10099998, z: 0.598} m_LocalScale: {x: 0.41889992, y: 0.41889998, z: 0.41889998} m_Children: - {fileID: 7430253517558768490} m_Father: {fileID: 7430253517585478437} m_RootOrder: 1 m_LocalEulerAnglesHint: {x: -82.03001, y: 71.489006, z: 120.688} --- !u!33 &7430253518344216407 MeshFilter: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253518344216409} m_Mesh: {fileID: 10207, guid: 0000000000000000e000000000000000, type: 0} --- !u!23 &7430253518344216406 MeshRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253518344216409} m_Enabled: 1 m_CastShadows: 1 m_ReceiveShadows: 1 m_DynamicOccludee: 1 m_MotionVectors: 1 m_LightProbeUsage: 1 m_ReflectionProbeUsage: 1 m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: - {fileID: 2100000, guid: eaad04b0e0dec42229c9cb00a981d7ac, type: 2} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 m_StaticBatchRoot: {fileID: 0} m_ProbeAnchor: {fileID: 0} m_LightProbeVolumeOverride: {fileID: 0} m_ScaleInLightmap: 1 m_PreserveUVs: 0 m_IgnoreNormalsForChartDetection: 0 m_ImportantGI: 0 m_StitchLightmapSeams: 0 m_SelectedEditorRenderState: 3 m_MinimumChartSize: 4 m_AutoUVMaxDistance: 0.5 m_AutoUVMaxAngle: 89 m_LightmapParameters: {fileID: 0} m_SortingLayerID: 0 m_SortingLayer: 0 m_SortingOrder: 0 --- !u!54 &7430253518344216405 Rigidbody: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253518344216409} serializedVersion: 2 m_Mass: 1 m_Drag: 0 m_AngularDrag: 0.05 m_UseGravity: 1 m_IsKinematic: 0 m_Interpolate: 0 m_Constraints: 0 m_CollisionDetection: 0 --- !u!153 &7430253518344216404 ConfigurableJoint: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253518344216409} m_ConnectedBody: {fileID: 7430253517585478438} m_Anchor: {x: 0, y: 0, z: 0} m_Axis: {x: 1, y: 0, z: 0} m_AutoConfigureConnectedAnchor: 1 m_ConnectedAnchor: {x: -0.26999986, y: 0.10099995, z: 0.598} serializedVersion: 2 m_SecondaryAxis: {x: 0, y: 1, z: 0} m_XMotion: 0 m_YMotion: 0 m_ZMotion: 0 m_AngularXMotion: 2 m_AngularYMotion: 2 m_AngularZMotion: 2 m_LinearLimitSpring: spring: 0 damper: 0 m_LinearLimit: limit: 0 bounciness: 0 contactDistance: 0 m_AngularXLimitSpring: spring: 0 damper: 0 m_LowAngularXLimit: limit: 0 bounciness: 0 contactDistance: 0 m_HighAngularXLimit: limit: 0 bounciness: 0 contactDistance: 0 m_AngularYZLimitSpring: spring: 0 damper: 0 m_AngularYLimit: limit: 0 bounciness: 0 contactDistance: 0 m_AngularZLimit: limit: 0 bounciness: 0 contactDistance: 0 m_TargetPosition: {x: 0, y: 0, z: 0} m_TargetVelocity: {x: 0, y: 0, z: 0} m_XDrive: serializedVersion: 3 positionSpring: 0 positionDamper: 0 maximumForce: 3.4028233e+38 m_YDrive: serializedVersion: 3 positionSpring: 0 positionDamper: 0 maximumForce: 3.4028233e+38 m_ZDrive: serializedVersion: 3 positionSpring: 0 positionDamper: 0 maximumForce: 3.4028233e+38 m_TargetRotation: {x: 0, y: 0, z: 0, w: 1} m_TargetAngularVelocity: {x: 0, y: 0, z: 0} m_RotationDriveMode: 1 m_AngularXDrive: serializedVersion: 3 positionSpring: 0 positionDamper: 0 maximumForce: 3.4028233e+38 m_AngularYZDrive: serializedVersion: 3 positionSpring: 0 positionDamper: 0 maximumForce: 3.4028233e+38 m_SlerpDrive: serializedVersion: 3 positionSpring: 15 positionDamper: 0 maximumForce: 3.4028233e+38 m_ProjectionMode: 1 m_ProjectionDistance: 0.1 m_ProjectionAngle: 180 m_ConfiguredInWorldSpace: 0 m_SwapBodies: 0 m_BreakForce: Infinity m_BreakTorque: Infinity m_EnableCollision: 0 m_EnablePreprocessing: 0 m_MassScale: 1 m_ConnectedMassScale: 1 --- !u!135 &7430253518344216411 SphereCollider: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253518344216409} m_Material: {fileID: 0} m_IsTrigger: 0 m_Enabled: 1 serializedVersion: 2 m_Radius: 0.3 m_Center: {x: 0, y: 0.00000023841858, z: -0.0000038146973} --- !u!1 &7430253518623948736 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 7430253518623948737} - component: {fileID: 7430253518623948764} - component: {fileID: 7430253518623948739} - component: {fileID: 7430253518623948738} m_Layer: 0 m_Name: BodySeg2 m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!4 &7430253518623948737 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253518623948736} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0, y: -1.1247, z: -0.00031888485} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: - {fileID: 7123748794063981559} - {fileID: 7430253517665647541} m_Father: {fileID: 7430253518698367209} m_RootOrder: 1 m_LocalEulerAnglesHint: {x: 89.98, y: 0, z: 0} --- !u!136 &7430253518623948764 CapsuleCollider: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253518623948736} m_Material: {fileID: 0} m_IsTrigger: 0 m_Enabled: 1 m_Radius: 0.28 m_Height: 1.48 m_Direction: 1 m_Center: {x: 0, y: 0, z: 0} --- !u!54 &7430253518623948739 Rigidbody: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253518623948736} serializedVersion: 2 m_Mass: 10 m_Drag: 0 m_AngularDrag: 0.05 m_UseGravity: 1 m_IsKinematic: 0 m_Interpolate: 0 m_Constraints: 0 m_CollisionDetection: 3 --- !u!153 &7430253518623948738 ConfigurableJoint: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253518623948736} m_ConnectedBody: {fileID: 7430253517665647542} m_Anchor: {x: 0, y: -0.55, z: 0} m_Axis: {x: 1, y: 0, z: 0} m_AutoConfigureConnectedAnchor: 1 m_ConnectedAnchor: {x: 0, y: 0.5659995, z: 0.0004159212} serializedVersion: 2 m_SecondaryAxis: {x: 0, y: 0, z: -1} m_XMotion: 0 m_YMotion: 0 m_ZMotion: 0 m_AngularXMotion: 1 m_AngularYMotion: 1 m_AngularZMotion: 0 m_LinearLimitSpring: spring: 0 damper: 0 m_LinearLimit: limit: 0 bounciness: 0 contactDistance: 0 m_AngularXLimitSpring: spring: 0 damper: 0 m_LowAngularXLimit: limit: -60 bounciness: 0 contactDistance: 0 m_HighAngularXLimit: limit: 60 bounciness: 0 contactDistance: 0 m_AngularYZLimitSpring: spring: 0 damper: 0 m_AngularYLimit: limit: 60 bounciness: 0 contactDistance: 0 m_AngularZLimit: limit: 0 bounciness: 0 contactDistance: 0 m_TargetPosition: {x: 0, y: 0, z: 0} m_TargetVelocity: {x: 0, y: 0, z: 0} m_XDrive: serializedVersion: 3 positionSpring: 0 positionDamper: 0 maximumForce: 3.4028233e+38 m_YDrive: serializedVersion: 3 positionSpring: 0 positionDamper: 0 maximumForce: 3.4028233e+38 m_ZDrive: serializedVersion: 3 positionSpring: 0 positionDamper: 0 maximumForce: 3.4028233e+38 m_TargetRotation: {x: 0, y: 0, z: 0, w: 1} m_TargetAngularVelocity: {x: 0, y: 0, z: 0} m_RotationDriveMode: 1 m_AngularXDrive: serializedVersion: 3 positionSpring: 0 positionDamper: 0 maximumForce: 3.4028233e+38 m_AngularYZDrive: serializedVersion: 3 positionSpring: 0 positionDamper: 0 maximumForce: 3.4028233e+38 m_SlerpDrive: serializedVersion: 3 positionSpring: 1 positionDamper: 1 maximumForce: 3.4028233e+38 m_ProjectionMode: 1 m_ProjectionDistance: 0.1 m_ProjectionAngle: 180 m_ConfiguredInWorldSpace: 0 m_SwapBodies: 0 m_BreakForce: Infinity m_BreakTorque: Infinity m_EnableCollision: 0 m_EnablePreprocessing: 1 m_MassScale: 1 m_ConnectedMassScale: 1 --- !u!1 &7430253518678196320 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 7430253518678196321} - component: {fileID: 7430253518678196323} - component: {fileID: 7430253518678196322} m_Layer: 0 m_Name: stripe m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!4 &7430253518678196321 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253518678196320} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0, y: 0.000012721227, z: -0.048762847} m_LocalScale: {x: 1.0226575, y: 0.14130552, z: 0.9652029} m_Children: [] m_Father: {fileID: 8679239658813963324} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 89.98, y: 0, z: 0} --- !u!33 &7430253518678196323 MeshFilter: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253518678196320} m_Mesh: {fileID: 10208, guid: 0000000000000000e000000000000000, type: 0} --- !u!23 &7430253518678196322 MeshRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253518678196320} m_Enabled: 1 m_CastShadows: 1 m_ReceiveShadows: 1 m_DynamicOccludee: 1 m_MotionVectors: 1 m_LightProbeUsage: 1 m_ReflectionProbeUsage: 1 m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: - {fileID: 2100000, guid: eaad04b0e0dec42229c9cb00a981d7ac, type: 2} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 m_StaticBatchRoot: {fileID: 0} m_ProbeAnchor: {fileID: 0} m_LightProbeVolumeOverride: {fileID: 0} m_ScaleInLightmap: 1 m_PreserveUVs: 0 m_IgnoreNormalsForChartDetection: 0 m_ImportantGI: 0 m_StitchLightmapSeams: 0 m_SelectedEditorRenderState: 3 m_MinimumChartSize: 4 m_AutoUVMaxDistance: 0.5 m_AutoUVMaxAngle: 89 m_LightmapParameters: {fileID: 0} m_SortingLayerID: 0 m_SortingLayer: 0 m_SortingOrder: 0 --- !u!1 &7430253518692004125 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 7430253518692004126} - component: {fileID: 7430253518692004120} - component: {fileID: 7430253518692004127} m_Layer: 0 m_Name: headband m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!4 &7430253518692004126 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253518692004125} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0, y: 0.154, z: -0.002} m_LocalScale: {x: 1.066923, y: 0.17350084, z: 1.0669229} m_Children: [] m_Father: {fileID: 3480290756406204138} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!33 &7430253518692004120 MeshFilter: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253518692004125} m_Mesh: {fileID: 10208, guid: 0000000000000000e000000000000000, type: 0} --- !u!23 &7430253518692004127 MeshRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253518692004125} m_Enabled: 1 m_CastShadows: 1 m_ReceiveShadows: 1 m_DynamicOccludee: 1 m_MotionVectors: 1 m_LightProbeUsage: 1 m_ReflectionProbeUsage: 1 m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: - {fileID: 2100000, guid: 5c59bd36def9a4684be49a21cf201a2d, type: 2} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 m_StaticBatchRoot: {fileID: 0} m_ProbeAnchor: {fileID: 0} m_LightProbeVolumeOverride: {fileID: 0} m_ScaleInLightmap: 1 m_PreserveUVs: 0 m_IgnoreNormalsForChartDetection: 0 m_ImportantGI: 0 m_StitchLightmapSeams: 0 m_SelectedEditorRenderState: 3 m_MinimumChartSize: 4 m_AutoUVMaxDistance: 0.5 m_AutoUVMaxAngle: 89 m_LightmapParameters: {fileID: 0} m_SortingLayerID: 0 m_SortingLayer: 0 m_SortingOrder: 0 --- !u!1 &7430253518698367208 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 7430253518698367209} - component: {fileID: 7430253518698367204} - component: {fileID: 7430253518698367210} - component: {fileID: 7430253518698367211} m_Layer: 0 m_Name: BodySeg1 m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!4 &7430253518698367209 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253518698367208} m_LocalRotation: {x: 0.70697504, y: -0, z: -0, w: 0.7072385} m_LocalPosition: {x: 0, y: 0.0001001358, z: -1.3162999} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: - {fileID: 8679239658813963324} - {fileID: 7430253518623948737} m_Father: {fileID: 7430253517585478437} m_RootOrder: 4 m_LocalEulerAnglesHint: {x: 89.98, y: 0, z: 0} --- !u!136 &7430253518698367204 CapsuleCollider: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253518698367208} m_Material: {fileID: 0} m_IsTrigger: 0 m_Enabled: 1 m_Radius: 0.33 m_Height: 1.5 m_Direction: 1 m_Center: {x: 0, y: 0, z: 0} --- !u!54 &7430253518698367210 Rigidbody: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253518698367208} serializedVersion: 2 m_Mass: 10 m_Drag: 0 m_AngularDrag: 0.05 m_UseGravity: 1 m_IsKinematic: 0 m_Interpolate: 0 m_Constraints: 0 m_CollisionDetection: 3 --- !u!153 &7430253518698367211 ConfigurableJoint: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253518698367208} m_ConnectedBody: {fileID: 7430253518623948739} m_Anchor: {x: 0, y: -0.55, z: 0} m_Axis: {x: 1, y: 0, z: 0} m_AutoConfigureConnectedAnchor: 1 m_ConnectedAnchor: {x: 0, y: 0.5747, z: 0.00031888485} serializedVersion: 2 m_SecondaryAxis: {x: 0, y: 0, z: -1} m_XMotion: 0 m_YMotion: 0 m_ZMotion: 0 m_AngularXMotion: 1 m_AngularYMotion: 1 m_AngularZMotion: 0 m_LinearLimitSpring: spring: 0 damper: 0 m_LinearLimit: limit: 0 bounciness: 0 contactDistance: 0 m_AngularXLimitSpring: spring: 0 damper: 0 m_LowAngularXLimit: limit: -60 bounciness: 0 contactDistance: 0 m_HighAngularXLimit: limit: 60 bounciness: 0 contactDistance: 0 m_AngularYZLimitSpring: spring: 0 damper: 0 m_AngularYLimit: limit: 60 bounciness: 0 contactDistance: 0 m_AngularZLimit: limit: 0 bounciness: 0 contactDistance: 0 m_TargetPosition: {x: 0, y: 0, z: 0} m_TargetVelocity: {x: 0, y: 0, z: 0} m_XDrive: serializedVersion: 3 positionSpring: 0 positionDamper: 0 maximumForce: 3.4028233e+38 m_YDrive: serializedVersion: 3 positionSpring: 0 positionDamper: 0 maximumForce: 3.4028233e+38 m_ZDrive: serializedVersion: 3 positionSpring: 0 positionDamper: 0 maximumForce: 3.4028233e+38 m_TargetRotation: {x: 0, y: 0, z: 0, w: 1} m_TargetAngularVelocity: {x: 0, y: 0, z: 0} m_RotationDriveMode: 1 m_AngularXDrive: serializedVersion: 3 positionSpring: 0 positionDamper: 0 maximumForce: 3.4028233e+38 m_AngularYZDrive: serializedVersion: 3 positionSpring: 0 positionDamper: 0 maximumForce: 3.4028233e+38 m_SlerpDrive: serializedVersion: 3 positionSpring: 1 positionDamper: 1 maximumForce: 3.4028233e+38 m_ProjectionMode: 1 m_ProjectionDistance: 0.1 m_ProjectionAngle: 180 m_ConfiguredInWorldSpace: 0 m_SwapBodies: 0 m_BreakForce: Infinity m_BreakTorque: Infinity m_EnableCollision: 0 m_EnablePreprocessing: 1 m_MassScale: 1 m_ConnectedMassScale: 1 --- !u!1 &7430253518935506120 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 7430253518935506121} - component: {fileID: 7430253518935506118} - component: {fileID: 7430253518935506117} - component: {fileID: 7430253518935506116} - component: {fileID: 7430253518935506123} - component: {fileID: 7430253518935506122} m_Layer: 0 m_Name: eyeR m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!4 &7430253518935506121 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253518935506120} m_LocalRotation: {x: -0.23005107, y: -0.214901, z: 0.06767845, w: 0.9467385} m_LocalPosition: {x: 0.289, y: 0.040000036, z: 0.648} m_LocalScale: {x: 0.41890004, y: 0.41889998, z: 0.41889995} m_Children: - {fileID: 7430253517594625968} m_Father: {fileID: 7430253517585478437} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: -23.986002, y: -28.650002, z: 14.3880005} --- !u!33 &7430253518935506118 MeshFilter: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253518935506120} m_Mesh: {fileID: 10207, guid: 0000000000000000e000000000000000, type: 0} --- !u!23 &7430253518935506117 MeshRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253518935506120} m_Enabled: 1 m_CastShadows: 1 m_ReceiveShadows: 1 m_DynamicOccludee: 1 m_MotionVectors: 1 m_LightProbeUsage: 1 m_ReflectionProbeUsage: 1 m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: - {fileID: 2100000, guid: eaad04b0e0dec42229c9cb00a981d7ac, type: 2} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 m_StaticBatchRoot: {fileID: 0} m_ProbeAnchor: {fileID: 0} m_LightProbeVolumeOverride: {fileID: 0} m_ScaleInLightmap: 1 m_PreserveUVs: 0 m_IgnoreNormalsForChartDetection: 0 m_ImportantGI: 0 m_StitchLightmapSeams: 0 m_SelectedEditorRenderState: 3 m_MinimumChartSize: 4 m_AutoUVMaxDistance: 0.5 m_AutoUVMaxAngle: 89 m_LightmapParameters: {fileID: 0} m_SortingLayerID: 0 m_SortingLayer: 0 m_SortingOrder: 0 --- !u!54 &7430253518935506116 Rigidbody: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253518935506120} serializedVersion: 2 m_Mass: 1 m_Drag: 0 m_AngularDrag: 0.05 m_UseGravity: 1 m_IsKinematic: 0 m_Interpolate: 0 m_Constraints: 0 m_CollisionDetection: 0 --- !u!153 &7430253518935506123 ConfigurableJoint: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253518935506120} m_ConnectedBody: {fileID: 7430253517585478438} m_Anchor: {x: 0, y: 0, z: 0} m_Axis: {x: 1, y: 0, z: 0} m_AutoConfigureConnectedAnchor: 1 m_ConnectedAnchor: {x: 0.289, y: 0.04000008, z: 0.648} serializedVersion: 2 m_SecondaryAxis: {x: 0, y: 1, z: 0} m_XMotion: 0 m_YMotion: 0 m_ZMotion: 0 m_AngularXMotion: 2 m_AngularYMotion: 2 m_AngularZMotion: 2 m_LinearLimitSpring: spring: 0 damper: 0 m_LinearLimit: limit: 0 bounciness: 0 contactDistance: 0 m_AngularXLimitSpring: spring: 0 damper: 0 m_LowAngularXLimit: limit: 0 bounciness: 0 contactDistance: 0 m_HighAngularXLimit: limit: 0 bounciness: 0 contactDistance: 0 m_AngularYZLimitSpring: spring: 0 damper: 0 m_AngularYLimit: limit: 0 bounciness: 0 contactDistance: 0 m_AngularZLimit: limit: 0 bounciness: 0 contactDistance: 0 m_TargetPosition: {x: 0, y: 0, z: 0} m_TargetVelocity: {x: 0, y: 0, z: 0} m_XDrive: serializedVersion: 3 positionSpring: 0 positionDamper: 0 maximumForce: 3.4028233e+38 m_YDrive: serializedVersion: 3 positionSpring: 0 positionDamper: 0 maximumForce: 3.4028233e+38 m_ZDrive: serializedVersion: 3 positionSpring: 0 positionDamper: 0 maximumForce: 3.4028233e+38 m_TargetRotation: {x: 0, y: 0, z: 0, w: 1} m_TargetAngularVelocity: {x: 0, y: 0, z: 0} m_RotationDriveMode: 1 m_AngularXDrive: serializedVersion: 3 positionSpring: 0 positionDamper: 0 maximumForce: 3.4028233e+38 m_AngularYZDrive: serializedVersion: 3 positionSpring: 0 positionDamper: 0 maximumForce: 3.4028233e+38 m_SlerpDrive: serializedVersion: 3 positionSpring: 15 positionDamper: 0 maximumForce: 3.4028233e+38 m_ProjectionMode: 1 m_ProjectionDistance: 0.1 m_ProjectionAngle: 180 m_ConfiguredInWorldSpace: 0 m_SwapBodies: 0 m_BreakForce: Infinity m_BreakTorque: Infinity m_EnableCollision: 0 m_EnablePreprocessing: 0 m_MassScale: 1 m_ConnectedMassScale: 1 --- !u!135 &7430253518935506122 SphereCollider: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7430253518935506120} m_Material: {fileID: 0} m_IsTrigger: 0 m_Enabled: 1 serializedVersion: 2 m_Radius: 0.3 m_Center: {x: 0, y: 0.00000023841858, z: -0.0000038146973} --- !u!1 &7548890140503101028 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 3480290756406204138} - component: {fileID: 8992089658186223816} - component: {fileID: 6730372162678760495} m_Layer: 0 m_Name: MeshBodySeg0 m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!4 &3480290756406204138 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7548890140503101028} m_LocalRotation: {x: 0.7071068, y: -0, z: -0, w: 0.7071068} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 0.7351969, y: 1, z: 0.7351975} m_Children: - {fileID: 7430253518692004126} m_Father: {fileID: 7430253517585478437} m_RootOrder: 3 m_LocalEulerAnglesHint: {x: 90, y: 0, z: 0} --- !u!33 &8992089658186223816 MeshFilter: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7548890140503101028} m_Mesh: {fileID: 10208, guid: 0000000000000000e000000000000000, type: 0} --- !u!23 &6730372162678760495 MeshRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7548890140503101028} m_Enabled: 1 m_CastShadows: 1 m_ReceiveShadows: 1 m_DynamicOccludee: 1 m_MotionVectors: 1 m_LightProbeUsage: 1 m_ReflectionProbeUsage: 1 m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: - {fileID: 2100000, guid: c9fa44c2c3f8ce74ca39a3355ea42631, type: 2} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 m_StaticBatchRoot: {fileID: 0} m_ProbeAnchor: {fileID: 0} m_LightProbeVolumeOverride: {fileID: 0} m_ScaleInLightmap: 1 m_PreserveUVs: 0 m_IgnoreNormalsForChartDetection: 0 m_ImportantGI: 0 m_StitchLightmapSeams: 0 m_SelectedEditorRenderState: 3 m_MinimumChartSize: 4 m_AutoUVMaxDistance: 0.5 m_AutoUVMaxAngle: 89 m_LightmapParameters: {fileID: 0} m_SortingLayerID: 0 m_SortingLayer: 0 m_SortingOrder: 0 --- !u!1001 &7922346880768243569 PrefabInstance: m_ObjectHideFlags: 0 serializedVersion: 2 m_Modification: m_TransformParent: {fileID: 7430253518223459951} m_Modifications: - target: {fileID: 2591864625898824423, guid: 72f745913c5a34df5aaadd5c1f0024cb, type: 3} propertyPath: m_IsActive value: 0 objectReference: {fileID: 0} - target: {fileID: 2591864627249999504, guid: 72f745913c5a34df5aaadd5c1f0024cb, type: 3} propertyPath: m_LocalPosition.x value: 0 objectReference: {fileID: 0} - target: {fileID: 2591864627249999504, guid: 72f745913c5a34df5aaadd5c1f0024cb, type: 3} propertyPath: m_LocalPosition.y value: 0 objectReference: {fileID: 0} - target: {fileID: 2591864627249999504, guid: 72f745913c5a34df5aaadd5c1f0024cb, type: 3} propertyPath: m_LocalPosition.z value: 0 objectReference: {fileID: 0} - target: {fileID: 2591864627249999504, guid: 72f745913c5a34df5aaadd5c1f0024cb, type: 3} propertyPath: m_LocalRotation.x value: 0 objectReference: {fileID: 0} - target: {fileID: 2591864627249999504, guid: 72f745913c5a34df5aaadd5c1f0024cb, type: 3} propertyPath: m_LocalRotation.y value: 0 objectReference: {fileID: 0} - target: {fileID: 2591864627249999504, guid: 72f745913c5a34df5aaadd5c1f0024cb, type: 3} propertyPath: m_LocalRotation.z value: 0 objectReference: {fileID: 0} - target: {fileID: 2591864627249999504, guid: 72f745913c5a34df5aaadd5c1f0024cb, type: 3} propertyPath: m_LocalRotation.w value: 1 objectReference: {fileID: 0} - target: {fileID: 2591864627249999504, guid: 72f745913c5a34df5aaadd5c1f0024cb, type: 3} propertyPath: m_RootOrder value: 2 objectReference: {fileID: 0} - target: {fileID: 2591864627249999504, guid: 72f745913c5a34df5aaadd5c1f0024cb, type: 3} propertyPath: m_LocalEulerAnglesHint.x value: 0 objectReference: {fileID: 0} - target: {fileID: 2591864627249999504, guid: 72f745913c5a34df5aaadd5c1f0024cb, type: 3} propertyPath: m_LocalEulerAnglesHint.y value: 0 objectReference: {fileID: 0} - target: {fileID: 2591864627249999504, guid: 72f745913c5a34df5aaadd5c1f0024cb, type: 3} propertyPath: m_LocalEulerAnglesHint.z value: 0 objectReference: {fileID: 0} - target: {fileID: 2591864627249999519, guid: 72f745913c5a34df5aaadd5c1f0024cb, type: 3} propertyPath: m_Name value: OrientationCube objectReference: {fileID: 0} m_RemovedComponents: [] m_SourcePrefab: {fileID: 100100000, guid: 72f745913c5a34df5aaadd5c1f0024cb, type: 3} --- !u!4 &5623293504353442273 stripped Transform: m_CorrespondingSourceObject: {fileID: 2591864627249999504, guid: 72f745913c5a34df5aaadd5c1f0024cb, type: 3} m_PrefabInstance: {fileID: 7922346880768243569} m_PrefabAsset: {fileID: 0} --- !u!1001 &8181510401464370429 PrefabInstance: m_ObjectHideFlags: 0 serializedVersion: 2 m_Modification: m_TransformParent: {fileID: 7430253518223459951} m_Modifications: - target: {fileID: 2514443435243387629, guid: e568400ebedb3474fac505995f12ed4a, type: 3} propertyPath: m_Name value: DirectionIndicator objectReference: {fileID: 0} - target: {fileID: 6026464216722085689, guid: e568400ebedb3474fac505995f12ed4a, type: 3} propertyPath: transformToFollow value: objectReference: {fileID: 7430253517585478437} - target: {fileID: 6026464216722085689, guid: e568400ebedb3474fac505995f12ed4a, type: 3} propertyPath: targetToLookAt value: objectReference: {fileID: 0} - target: {fileID: 6026464216722085689, guid: e568400ebedb3474fac505995f12ed4a, type: 3} propertyPath: updatedByAgent value: 1 objectReference: {fileID: 0} - target: {fileID: 6084207059270429360, guid: e568400ebedb3474fac505995f12ed4a, type: 3} propertyPath: m_LocalPosition.x value: 0 objectReference: {fileID: 0} - target: {fileID: 6084207059270429360, guid: e568400ebedb3474fac505995f12ed4a, type: 3} propertyPath: m_LocalPosition.y value: -1.16 objectReference: {fileID: 0} - target: {fileID: 6084207059270429360, guid: e568400ebedb3474fac505995f12ed4a, type: 3} propertyPath: m_LocalPosition.z value: 0 objectReference: {fileID: 0} - target: {fileID: 6084207059270429360, guid: e568400ebedb3474fac505995f12ed4a, type: 3} propertyPath: m_LocalRotation.x value: -0 objectReference: {fileID: 0} - target: {fileID: 6084207059270429360, guid: e568400ebedb3474fac505995f12ed4a, type: 3} propertyPath: m_LocalRotation.y value: 0.7071068 objectReference: {fileID: 0} - target: {fileID: 6084207059270429360, guid: e568400ebedb3474fac505995f12ed4a, type: 3} propertyPath: m_LocalRotation.z value: -0 objectReference: {fileID: 0} - target: {fileID: 6084207059270429360, guid: e568400ebedb3474fac505995f12ed4a, type: 3} propertyPath: m_LocalRotation.w value: 0.7071068 objectReference: {fileID: 0} - target: {fileID: 6084207059270429360, guid: e568400ebedb3474fac505995f12ed4a, type: 3} propertyPath: m_RootOrder value: 1 objectReference: {fileID: 0} - target: {fileID: 6084207059270429360, guid: e568400ebedb3474fac505995f12ed4a, type: 3} propertyPath: m_LocalEulerAnglesHint.x value: 0 objectReference: {fileID: 0} - target: {fileID: 6084207059270429360, guid: e568400ebedb3474fac505995f12ed4a, type: 3} propertyPath: m_LocalEulerAnglesHint.y value: 0 objectReference: {fileID: 0} - target: {fileID: 6084207059270429360, guid: e568400ebedb3474fac505995f12ed4a, type: 3} propertyPath: m_LocalEulerAnglesHint.z value: 0 objectReference: {fileID: 0} - target: {fileID: 6084207059270429360, guid: e568400ebedb3474fac505995f12ed4a, type: 3} propertyPath: m_LocalScale.x value: 1.2098714 objectReference: {fileID: 0} - target: {fileID: 6084207059270429360, guid: e568400ebedb3474fac505995f12ed4a, type: 3} propertyPath: m_LocalScale.y value: 0.020184275 objectReference: {fileID: 0} - target: {fileID: 6084207059270429360, guid: e568400ebedb3474fac505995f12ed4a, type: 3} propertyPath: m_LocalScale.z value: 1.2098714 objectReference: {fileID: 0} m_RemovedComponents: [] m_SourcePrefab: {fileID: 100100000, guid: e568400ebedb3474fac505995f12ed4a, type: 3} --- !u!4 &2730837554089586253 stripped Transform: m_CorrespondingSourceObject: {fileID: 6084207059270429360, guid: e568400ebedb3474fac505995f12ed4a, type: 3} m_PrefabInstance: {fileID: 8181510401464370429} m_PrefabAsset: {fileID: 0}
ml-agents/Project/Assets/ML-Agents/Examples/Worm/Prefabs/Worm.prefab/0
{ "file_path": "ml-agents/Project/Assets/ML-Agents/Examples/Worm/Prefabs/Worm.prefab", "repo_id": "ml-agents", "token_count": 28154 }
1,932
%YAML 1.1 %TAG !u! tag:unity3d.com,2011: --- !u!29 &1 OcclusionCullingSettings: m_ObjectHideFlags: 0 serializedVersion: 2 m_OcclusionBakeSettings: smallestOccluder: 5 smallestHole: 0.25 backfaceThreshold: 100 m_SceneGUID: 00000000000000000000000000000000 m_OcclusionCullingData: {fileID: 0} --- !u!104 &2 RenderSettings: m_ObjectHideFlags: 0 serializedVersion: 9 m_Fog: 0 m_FogColor: {r: 0.5, g: 0.5, b: 0.5, a: 1} m_FogMode: 3 m_FogDensity: 0.01 m_LinearFogStart: 0 m_LinearFogEnd: 300 m_AmbientSkyColor: {r: 0.212, g: 0.227, b: 0.259, a: 1} m_AmbientEquatorColor: {r: 0.114, g: 0.125, b: 0.133, a: 1} m_AmbientGroundColor: {r: 0.047, g: 0.043, b: 0.035, a: 1} m_AmbientIntensity: 1 m_AmbientMode: 0 m_SubtractiveShadowColor: {r: 0.42, g: 0.478, b: 0.627, a: 1} m_SkyboxMaterial: {fileID: 10304, guid: 0000000000000000f000000000000000, type: 0} m_HaloStrength: 0.5 m_FlareStrength: 1 m_FlareFadeSpeed: 3 m_HaloTexture: {fileID: 0} m_SpotCookie: {fileID: 10001, guid: 0000000000000000e000000000000000, type: 0} m_DefaultReflectionMode: 0 m_DefaultReflectionResolution: 128 m_ReflectionBounces: 1 m_ReflectionIntensity: 1 m_CustomReflection: {fileID: 0} m_Sun: {fileID: 0} m_IndirectSpecularColor: {r: 0.3731193, g: 0.38073996, b: 0.3587269, a: 1} m_UseRadianceAmbientProbe: 0 --- !u!157 &3 LightmapSettings: m_ObjectHideFlags: 0 serializedVersion: 11 m_GIWorkflowMode: 0 m_GISettings: serializedVersion: 2 m_BounceScale: 1 m_IndirectOutputScale: 1 m_AlbedoBoost: 1 m_EnvironmentLightingMode: 0 m_EnableBakedLightmaps: 1 m_EnableRealtimeLightmaps: 1 m_LightmapEditorSettings: serializedVersion: 10 m_Resolution: 2 m_BakeResolution: 40 m_AtlasSize: 1024 m_AO: 0 m_AOMaxDistance: 1 m_CompAOExponent: 1 m_CompAOExponentDirect: 0 m_Padding: 2 m_LightmapParameters: {fileID: 0} m_LightmapsBakeMode: 1 m_TextureCompression: 1 m_FinalGather: 0 m_FinalGatherFiltering: 1 m_FinalGatherRayCount: 256 m_ReflectionCompression: 2 m_MixedBakeMode: 2 m_BakeBackend: 1 m_PVRSampling: 1 m_PVRDirectSampleCount: 32 m_PVRSampleCount: 500 m_PVRBounces: 2 m_PVRFilterTypeDirect: 0 m_PVRFilterTypeIndirect: 0 m_PVRFilterTypeAO: 0 m_PVRFilteringMode: 1 m_PVRCulling: 1 m_PVRFilteringGaussRadiusDirect: 1 m_PVRFilteringGaussRadiusIndirect: 5 m_PVRFilteringGaussRadiusAO: 2 m_PVRFilteringAtrousPositionSigmaDirect: 0.5 m_PVRFilteringAtrousPositionSigmaIndirect: 2 m_PVRFilteringAtrousPositionSigmaAO: 1 m_ShowResolutionOverlay: 1 m_LightingDataAsset: {fileID: 0} m_UseShadowmask: 1 --- !u!196 &4 NavMeshSettings: serializedVersion: 2 m_ObjectHideFlags: 0 m_BuildSettings: serializedVersion: 2 agentTypeID: 0 agentRadius: 0.5 agentHeight: 2 agentSlope: 45 agentClimb: 0.4 ledgeDropHeight: 0 maxJumpAcrossDistance: 0 minRegionArea: 2 manualCellSize: 0 cellSize: 0.16666667 manualTileSize: 0 tileSize: 256 accuratePlacement: 0 debug: m_Flags: 0 m_NavMeshData: {fileID: 0} --- !u!1 &293272827 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 293272831} - component: {fileID: 293272830} - component: {fileID: 293272829} - component: {fileID: 293272832} - component: {fileID: 293272828} m_Layer: 0 m_Name: UncompressedObsAgent m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!114 &293272828 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 293272827} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 8eda65155b8ff4d14a3b048dae0fb21c, type: 3} m_Name: m_EditorClassIdentifier: TestTexture: {fileID: 2800000, guid: eeba1f6a35c72450894cf4f4cb516004, type: 3} ObservationStacks: 4 CompressionType: 0 --- !u!114 &293272829 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 293272827} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 88b6042bc9a5d4aa58d931eae49442e5, type: 3} m_Name: m_EditorClassIdentifier: agentParameters: maxStep: 0 hasUpgradedFromAgentParameters: 1 MaxStep: 0 --- !u!114 &293272830 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 293272827} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 5d1c4e0b1822b495aa52bc52839ecb30, type: 3} m_Name: m_EditorClassIdentifier: m_BrainParameters: VectorObservationSize: 0 NumStackedVectorObservations: 1 VectorActionSize: 01000000 VectorActionDescriptions: [] VectorActionSpaceType: 0 m_Model: {fileID: 0} m_InferenceDevice: 0 m_BehaviorType: 0 m_BehaviorName: TestCompressedObs TeamId: 0 m_UseChildSensors: 1 m_UseChildActuators: 1 m_ObservableAttributeHandling: 0 --- !u!4 &293272831 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 293272827} m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: [] m_Father: {fileID: 0} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!114 &293272832 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 293272827} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 3a5c9d521e5ef4759a8246a07d52221e, type: 3} m_Name: m_EditorClassIdentifier: DecisionPeriod: 1 TakeActionsBetweenDecisions: 1 --- !u!1 &2059361216 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 2059361220} - component: {fileID: 2059361219} - component: {fileID: 2059361218} - component: {fileID: 2059361221} - component: {fileID: 2059361217} m_Layer: 0 m_Name: CompressedObsAgent m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!114 &2059361217 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 2059361216} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 8eda65155b8ff4d14a3b048dae0fb21c, type: 3} m_Name: m_EditorClassIdentifier: TestTexture: {fileID: 2800000, guid: eeba1f6a35c72450894cf4f4cb516004, type: 3} ObservationStacks: 4 CompressionType: 1 --- !u!114 &2059361218 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 2059361216} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 88b6042bc9a5d4aa58d931eae49442e5, type: 3} m_Name: m_EditorClassIdentifier: agentParameters: maxStep: 0 hasUpgradedFromAgentParameters: 1 MaxStep: 0 --- !u!114 &2059361219 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 2059361216} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 5d1c4e0b1822b495aa52bc52839ecb30, type: 3} m_Name: m_EditorClassIdentifier: m_BrainParameters: VectorObservationSize: 0 NumStackedVectorObservations: 1 VectorActionSize: 01000000 VectorActionDescriptions: [] VectorActionSpaceType: 0 m_Model: {fileID: 0} m_InferenceDevice: 0 m_BehaviorType: 0 m_BehaviorName: TestCompressedObs TeamId: 0 m_UseChildSensors: 1 m_UseChildActuators: 1 m_ObservableAttributeHandling: 0 --- !u!4 &2059361220 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 2059361216} m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: [] m_Father: {fileID: 0} m_RootOrder: 1 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!114 &2059361221 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 2059361216} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 3a5c9d521e5ef4759a8246a07d52221e, type: 3} m_Name: m_EditorClassIdentifier: DecisionPeriod: 1 TakeActionsBetweenDecisions: 1
ml-agents/Project/Assets/ML-Agents/TestScenes/TestCompressedTexture/TestTextureCompressed.unity/0
{ "file_path": "ml-agents/Project/Assets/ML-Agents/TestScenes/TestCompressedTexture/TestTextureCompressed.unity", "repo_id": "ml-agents", "token_count": 4037 }
1,933
%YAML 1.1 %TAG !u! tag:unity3d.com,2011: --- !u!1045 &1 EditorBuildSettings: m_ObjectHideFlags: 0 serializedVersion: 2 m_Scenes: [] m_configObjects: {}
ml-agents/Project/ProjectSettings/EditorBuildSettings.asset/0
{ "file_path": "ml-agents/Project/ProjectSettings/EditorBuildSettings.asset", "repo_id": "ml-agents", "token_count": 71 }
1,934
<jupyter_start><jupyter_text>ML-Agents Open a UnityEnvironment Setup<jupyter_code>#@title Install Rendering Dependencies { display-mode: "form" } #@markdown (You only need to run this code when using Colab's hosted runtime) import os from IPython.display import HTML, display def progress(value, max=100): return HTML(""" <progress value='{value}' max='{max}', style='width: 100%' > {value} </progress> """.format(value=value, max=max)) pro_bar = display(progress(0, 100), display_id=True) try: import google.colab INSTALL_XVFB = True except ImportError: INSTALL_XVFB = 'COLAB_ALWAYS_INSTALL_XVFB' in os.environ if INSTALL_XVFB: with open('frame-buffer', 'w') as writefile: writefile.write("""#taken from https://gist.github.com/jterrace/2911875 XVFB=/usr/bin/Xvfb XVFBARGS=":1 -screen 0 1024x768x24 -ac +extension GLX +render -noreset" PIDFILE=./frame-buffer.pid case "$1" in start) echo -n "Starting virtual X frame buffer: Xvfb" /sbin/start-stop-daemon --start --quiet --pidfile $PIDFILE --make-pidfile --background --exec $XVFB -- $XVFBARGS echo "." ;; stop) echo -n "Stopping virtual X frame buffer: Xvfb" /sbin/start-stop-daemon --stop --quiet --pidfile $PIDFILE rm $PIDFILE echo "." ;; restart) $0 stop $0 start ;; *) echo "Usage: /etc/init.d/xvfb {start|stop|restart}" exit 1 esac exit 0 """) !sudo apt-get update pro_bar.update(progress(10, 100)) !sudo DEBIAN_FRONTEND=noninteractive apt install -y daemon wget gdebi-core build-essential libfontenc1 libfreetype6 xorg-dev xorg pro_bar.update(progress(20, 100)) !wget http://security.ubuntu.com/ubuntu/pool/main/libx/libxfont/libxfont1_1.5.1-1ubuntu0.16.04.4_amd64.deb 2>&1 pro_bar.update(progress(30, 100)) !wget --output-document xvfb.deb http://security.ubuntu.com/ubuntu/pool/universe/x/xorg-server/xvfb_1.18.4-0ubuntu0.12_amd64.deb 2>&1 pro_bar.update(progress(40, 100)) !sudo dpkg -i libxfont1_1.5.1-1ubuntu0.16.04.4_amd64.deb 2>&1 pro_bar.update(progress(50, 100)) !sudo dpkg -i xvfb.deb 2>&1 pro_bar.update(progress(70, 100)) !rm libxfont1_1.5.1-1ubuntu0.16.04.4_amd64.deb pro_bar.update(progress(80, 100)) !rm xvfb.deb pro_bar.update(progress(90, 100)) !bash frame-buffer start os.environ["DISPLAY"] = ":1" pro_bar.update(progress(100, 100))<jupyter_output><empty_output><jupyter_text>Installing ml-agents<jupyter_code>try: import mlagents print("ml-agents already installed") except ImportError: !python -m pip install -q mlagents==1.0.0 print("Installed ml-agents")<jupyter_output>ml-agents already installed<jupyter_text>Run the Environment<jupyter_code>#@title Select Environment { display-mode: "form" } env_id = "GridWorld" #@param ['Basic', '3DBall', '3DBallHard', 'GridWorld', 'Hallway', 'VisualHallway', 'CrawlerDynamicTarget', 'CrawlerStaticTarget', 'Bouncer', 'SoccerTwos', 'PushBlock', 'VisualPushBlock', 'WallJump', 'Tennis', 'Reacher', 'Pyramids', 'VisualPyramids', 'Walker', 'FoodCollector', 'VisualFoodCollector', 'StrikersVsGoalie', 'WormStaticTarget', 'WormDynamicTarget']<jupyter_output><empty_output><jupyter_text>Start Environment from the registry<jupyter_code># ----------------- # This code is used to close an env that might not have been closed before try: env.close() except: pass # ----------------- from mlagents_envs.registry import default_registry env = default_registry[env_id].make()<jupyter_output>[UnityMemory] Configuration Parameters - Can be set up in boot.config "memorysetup-bucket-allocator-granularity=16" "memorysetup-bucket-allocator-bucket-count=8" "memorysetup-bucket-allocator-block-size=4194304" "memorysetup-bucket-allocator-block-count=1" "memorysetup-main-allocator-block-size=16777216" "memorysetup-thread-allocator-block-size=16777216" "memorysetup-gfx-main-allocator-block-size=16777216" "memorysetup-gfx-thread-allocator-block-size=16777216" "memorysetup-cache-allocator-block-size=4194304" "memorysetup-typetree-allocator-block-size=2097152" "memorysetup-profiler-bucket-allocator-granularity=16" "memorysetup-profiler-bucket-allocator-bucket-count=8" "memorysetup-profiler-bucket-allocator-block-size=4194304" "memorysetup-profiler-bucket-allocator-block-count=1" "memorysetup-profiler-allocator-block-size=16777216" "memorysetup-profiler-editor-allocator-block-size=1048576" "memorysetup-temp-allocator-siz[...]<jupyter_text>Reset the environmentTo reset the environment, simply call `env.reset()`. This method takes no argument and returns nothing but will send a signal to the simulation to reset.<jupyter_code>env.reset()<jupyter_output><empty_output><jupyter_text>Behavior Specs Get the Behavior Specs from the Environment<jupyter_code># We will only consider the first Behavior behavior_name = list(env.behavior_specs)[0] print(f"Name of the behavior : {behavior_name}") spec = env.behavior_specs[behavior_name]<jupyter_output>Name of the behavior : GridWorld?team=0<jupyter_text>Get the Observation Space from the Behavior Specs<jupyter_code># Examine the number of observations per Agent print("Number of observations : ", len(spec.observation_specs)) # Is there a visual observation ? # Visual observation have 3 dimensions: Height, Width and number of channels vis_obs = any(len(spec.shape) == 3 for spec in spec.observation_specs) print("Is there a visual observation ?", vis_obs)<jupyter_output>Number of observations : 2 Is there a visual observation ? True<jupyter_text>Get the Action Space from the Behavior Specs<jupyter_code># Is the Action continuous or multi-discrete ? if spec.action_spec.continuous_size > 0: print(f"There are {spec.action_spec.continuous_size} continuous actions") if spec.action_spec.is_discrete(): print(f"There are {spec.action_spec.discrete_size} discrete actions") # How many actions are possible ? #print(f"There are {spec.action_size} action(s)") # For discrete actions only : How many different options does each action has ? if spec.action_spec.discrete_size > 0: for action, branch_size in enumerate(spec.action_spec.discrete_branches): print(f"Action number {action} has {branch_size} different options")<jupyter_output>There are 1 discrete actions Action number 0 has 5 different options<jupyter_text>Stepping the environment Get the steps from the EnvironmentYou can do this with the `env.get_steps(behavior_name)` method. If there are multiple behaviors in the Environment, you can call this method with each of the behavior's names._Note_ This will not move the simulation forward.<jupyter_code>decision_steps, terminal_steps = env.get_steps(behavior_name)<jupyter_output><empty_output><jupyter_text>Set actions for each behaviorYou can set the actions for the Agents of a Behavior by calling `env.set_actions()` you will need to specify the behavior name and pass a tensor of dimension 2. The first dimension of the action must be equal to the number of Agents that requested a decision during the step.<jupyter_code>env.set_actions(behavior_name, spec.action_spec.empty_action(len(decision_steps)))<jupyter_output><empty_output><jupyter_text>Move the simulation forwardCall `env.step()` to move the simulation forward. The simulation will progress until an Agent requestes a decision or terminates.<jupyter_code>env.step()<jupyter_output><empty_output><jupyter_text>Observations Show the observations for one of the Agents`DecisionSteps.obs` is a tuple containing all of the observations for all of the Agents with the provided Behavior name.Each value in the tuple is an observation tensor containing the observation data for all of the agents.<jupyter_code>import matplotlib.pyplot as plt import numpy as np %matplotlib inline for index, obs_spec in enumerate(spec.observation_specs): if len(obs_spec.shape) == 3: print("Here is the first visual observation") plt.imshow(np.moveaxis(decision_steps.obs[index][0, :, :, :], 0, -1)) plt.show() for index, obs_spec in enumerate(spec.observation_specs): if len(obs_spec.shape) == 1: print("First vector observations : ", decision_steps.obs[index][0,:])<jupyter_output>Here is the first visual observation<jupyter_text>Run the Environment for a few episodes<jupyter_code>for episode in range(3): env.reset() decision_steps, terminal_steps = env.get_steps(behavior_name) tracked_agent = -1 # -1 indicates not yet tracking done = False # For the tracked_agent episode_rewards = 0 # For the tracked_agent while not done: # Track the first agent we see if not tracking # Note : len(decision_steps) = [number of agents that requested a decision] if tracked_agent == -1 and len(decision_steps) >= 1: tracked_agent = decision_steps.agent_id[0] # Generate an action for all agents action = spec.action_spec.random_action(len(decision_steps)) # Set the actions env.set_actions(behavior_name, action) # Move the simulation forward env.step() # Get the new simulation results decision_steps, terminal_steps = env.get_steps(behavior_name) if tracked_agent in decision_steps: # The agent requested a decision episode_rewards += decision_steps[tracked_agent].reward if tracked_agent in terminal_steps: # The agent terminated its episode episode_rewards += terminal_steps[tracked_agent].reward done = True print(f"Total rewards for episode {episode} is {episode_rewards}")<jupyter_output>Total rewards for episode 0 is -1.1499999966472387 Total rewards for episode 1 is -1.5599999874830246 Total rewards for episode 2 is -1.049999998882413<jupyter_text>Close the Environment to free the port it is using<jupyter_code>env.close() print("Closed environment")<jupyter_output>Closed environment
ml-agents/colab/Colab_UnityEnvironment_1_Run.ipynb/0
{ "file_path": "ml-agents/colab/Colab_UnityEnvironment_1_Run.ipynb", "repo_id": "ml-agents", "token_count": 3403 }
1,935
namespace Unity.MLAgents.Extensions.Editor { }
ml-agents/com.unity.ml-agents.extensions/Editor/EditorExample.cs/0
{ "file_path": "ml-agents/com.unity.ml-agents.extensions/Editor/EditorExample.cs", "repo_id": "ml-agents", "token_count": 17 }
1,936
using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("Unity.ML-Agents.Extensions.EditorTests")] [assembly: InternalsVisibleTo("Unity.ML-Agents.Extensions.Editor")] [assembly: InternalsVisibleTo("Unity.ML-Agents.Extensions.Tests")]
ml-agents/com.unity.ml-agents.extensions/Runtime/AssemblyInfo.cs/0
{ "file_path": "ml-agents/com.unity.ml-agents.extensions/Runtime/AssemblyInfo.cs", "repo_id": "ml-agents", "token_count": 83 }
1,937
#if MLA_INPUT_SYSTEM using UnityEngine.InputSystem; namespace Unity.MLAgents.Extensions.Input { /// <summary> /// Implement this interface if you are listening to C# events from the generated C# class from the /// <see cref="InputActionAsset"/>. This interface works with the <see cref="InputActuatorComponent"/> in order /// to allow ML-Agents to simulate input actions based on the instance of the <see cref="InputActionAsset"/> /// used to listen to events. If you implement this interface the <see cref="InputActuatorComponent"/> will use /// what is returned from <see cref="GetInputActionAsset"/> as the asset to base it's simulated input for. /// Otherwise, the <see cref="InputActuatorComponent"/> will look for the <see cref="PlayerInput"/> component /// and use the asset from there. If you have multiple components handling PlayerInput on the same GameObject /// they will need to share the same instance of the <see cref="InputActionAsset"/> in order to get the simulated /// input. /// </summary> public interface IInputActionAssetProvider { /// <summary> /// Returns the <see cref="InputActionAsset"/> instance being from the generated C# class of the /// <see cref="InputActionAsset"/> in order to correctly fire events when simulating input from ML-Agents. /// </summary> /// <returns>The instance of the <see cref="InputActionAsset"/> you are listening for events on.</returns> (InputActionAsset, IInputActionCollection2) GetInputActionAsset(); } } #endif // MLA_INPUT_SYSTEM
ml-agents/com.unity.ml-agents.extensions/Runtime/Input/IInputActionAssetProvider.cs/0
{ "file_path": "ml-agents/com.unity.ml-agents.extensions/Runtime/Input/IInputActionAssetProvider.cs", "repo_id": "ml-agents", "token_count": 475 }
1,938
fileFormatVersion: 2 guid: 11fe037a02b4a483cb9342c3454232cd MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ml-agents/com.unity.ml-agents.extensions/Runtime/Sensors/ArticulationBodyPoseExtractor.cs.meta/0
{ "file_path": "ml-agents/com.unity.ml-agents.extensions/Runtime/Sensors/ArticulationBodyPoseExtractor.cs.meta", "repo_id": "ml-agents", "token_count": 93 }
1,939
fileFormatVersion: 2 guid: 867cab4a07f244518bae3e6fdda14416 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ml-agents/com.unity.ml-agents.extensions/Runtime/Sensors/RigidBodyPoseExtractor.cs.meta/0
{ "file_path": "ml-agents/com.unity.ml-agents.extensions/Runtime/Sensors/RigidBodyPoseExtractor.cs.meta", "repo_id": "ml-agents", "token_count": 96 }
1,940
#if MLA_INPUT_TESTS using NUnit.Framework; using Unity.MLAgents.Actuators; using Unity.MLAgents.Extensions.Input; using UnityEngine.InputSystem; namespace Unity.MLAgents.Extensions.Tests.Runtime.Input { public class IntegerInputActionAdaptorTests : InputTestFixture { IntegerInputActionAdaptor m_Adaptor; InputDevice m_Device; InputControl<int> m_Control; InputAction m_Action; public override void Setup() { base.Setup(); const string kLayout = @" { ""name"" : ""TestDevice"", ""extend"" : ""HID"", ""controls"" : [ { ""name"" : ""button"", ""layout"" : ""integer"" } ] }"; InputSystem.RegisterLayout(kLayout); m_Device = InputSystem.AddDevice("TestDevice"); m_Control = (InputControl<int>)m_Device["button"]; m_Action = new InputAction("action", InputActionType.Value, "/TestDevice/button", null, null, "int"); m_Action.Enable(); m_Adaptor = new IntegerInputActionAdaptor(); } public override void TearDown() { base.TearDown(); m_Adaptor = null; } [Test] public void TestGenerateActionSpec() { var actionSpec = m_Adaptor.GetActionSpecForInputAction(new InputAction()); Assert.IsTrue(actionSpec.NumDiscreteActions == 1); Assert.IsTrue(actionSpec.SumOfDiscreteBranchSizes == 2); } [Test] public void TestQueueEvent() { var actionBuffers = new ActionBuffers(ActionSegment<float>.Empty, new ActionSegment<int>(new[] { 1 })); var context = new InputActuatorEventContext(1, m_Device); using (context.GetEventForFrame(out var eventPtr)) { m_Adaptor.WriteToInputEventForAction(eventPtr, m_Action, m_Control, new ActionSpec(), actionBuffers); } InputSystem.Update(); var val = m_Action.ReadValue<int>(); Assert.IsTrue(val == 1); } [Test] public void TestWriteToHeuristic() { var actionBuffers = new ActionBuffers(ActionSegment<float>.Empty, new ActionSegment<int>(new[] { 1 })); var context = new InputActuatorEventContext(1, m_Device); using (context.GetEventForFrame(out var eventPtr)) { m_Adaptor.WriteToInputEventForAction(eventPtr, m_Action, m_Control, new ActionSpec(), actionBuffers); } InputSystem.Update(); var buffer = new ActionBuffers(ActionSegment<float>.Empty, new ActionSegment<int>(new int[1])); m_Adaptor.WriteToHeuristic(m_Action, buffer); Assert.IsTrue(buffer.DiscreteActions[0] == 1); } } } #endif // MLA_INPUT_TESTS
ml-agents/com.unity.ml-agents.extensions/Tests/Runtime/Input/Adaptors/IntegerInputActionAdaptorTests.cs/0
{ "file_path": "ml-agents/com.unity.ml-agents.extensions/Tests/Runtime/Input/Adaptors/IntegerInputActionAdaptorTests.cs", "repo_id": "ml-agents", "token_count": 1402 }
1,941
fileFormatVersion: 2 guid: a12a065df9b6f44d0b9a8e85d08d1cef TextScriptImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ml-agents/com.unity.ml-agents.extensions/package.json.meta/0
{ "file_path": "ml-agents/com.unity.ml-agents.extensions/package.json.meta", "repo_id": "ml-agents", "token_count": 71 }
1,942
using UnityEngine; using UnityEditor; using Unity.MLAgents.Policies; namespace Unity.MLAgents.Editor { /// <summary> /// PropertyDrawer for BrainParameters. Defines how BrainParameters are displayed in the /// Inspector. /// </summary> [CustomPropertyDrawer(typeof(BrainParameters))] internal class BrainParametersDrawer : PropertyDrawer { // The height of a line in the Unity Inspectors const float k_LineHeight = 17f; const int k_VecObsNumLine = 3; const string k_ActionSpecName = "m_ActionSpec"; const string k_ContinuousActionSizeName = "m_NumContinuousActions"; const string k_DiscreteBranchSizeName = "BranchSizes"; const string k_ActionDescriptionPropName = "VectorActionDescriptions"; const string k_VecObsPropName = "VectorObservationSize"; const string k_NumVecObsPropName = "NumStackedVectorObservations"; /// <inheritdoc /> public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { return GetHeightDrawVectorObservation() + GetHeightDrawVectorAction(property); } /// <inheritdoc /> public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { var indent = EditorGUI.indentLevel; EditorGUI.indentLevel = 0; position.height = k_LineHeight; EditorGUI.BeginProperty(position, label, property); EditorGUI.indentLevel++; // Vector Observations DrawVectorObservation(position, property); position.y += GetHeightDrawVectorObservation(); // Vector Action DrawVectorAction(position, property); position.y += GetHeightDrawVectorAction(property); EditorGUI.EndProperty(); EditorGUI.indentLevel = indent; } /// <summary> /// Draws the Vector Observations for the Brain Parameters /// </summary> /// <param name="position">Rectangle on the screen to use for the property GUI.</param> /// <param name="property">The SerializedProperty of the BrainParameters /// to make the custom GUI for.</param> static void DrawVectorObservation(Rect position, SerializedProperty property) { EditorGUI.LabelField(position, "Vector Observation"); position.y += k_LineHeight; EditorGUI.indentLevel++; EditorGUI.PropertyField(position, property.FindPropertyRelative(k_VecObsPropName), new GUIContent("Space Size", "Length of state " + "vector for brain (In Continuous state space)." + "Or number of possible values (in Discrete state space).")); position.y += k_LineHeight; EditorGUI.PropertyField(position, property.FindPropertyRelative(k_NumVecObsPropName), new GUIContent("Stacked Vectors", "Number of states that will be stacked before " + "being fed to the neural network.")); position.y += k_LineHeight; EditorGUI.indentLevel--; } /// <summary> /// The Height required to draw the Vector Observations paramaters /// </summary> /// <returns>The height of the drawer of the Vector Observations </returns> static float GetHeightDrawVectorObservation() { return k_VecObsNumLine * k_LineHeight; } /// <summary> /// Draws the Vector Actions parameters for the Brain Parameters /// </summary> /// <param name="position">Rectangle on the screen to use for the property GUI.</param> /// <param name="property">The SerializedProperty of the BrainParameters /// to make the custom GUI for.</param> static void DrawVectorAction(Rect position, SerializedProperty property) { EditorGUI.LabelField(position, "Actions"); position.y += k_LineHeight; EditorGUI.indentLevel++; var actionSpecProperty = property.FindPropertyRelative(k_ActionSpecName); DrawContinuousVectorAction(position, actionSpecProperty); position.y += k_LineHeight; DrawDiscreteVectorAction(position, actionSpecProperty); } /// <summary> /// Draws the Continuous Vector Actions parameters for the Brain Parameters /// </summary> /// <param name="position">Rectangle on the screen to use for the property GUI.</param> /// <param name="property">The SerializedProperty of the BrainParameters /// to make the custom GUI for.</param> static void DrawContinuousVectorAction(Rect position, SerializedProperty property) { var continuousActionSize = property.FindPropertyRelative(k_ContinuousActionSizeName); EditorGUI.PropertyField( position, continuousActionSize, new GUIContent("Continuous Actions", "Number of continuous actions.")); } /// <summary> /// Draws the Discrete Vector Actions parameters for the Brain Parameters /// </summary> /// <param name="position">Rectangle on the screen to use for the property GUI.</param> /// <param name="property">The SerializedProperty of the BrainParameters /// to make the custom GUI for.</param> static void DrawDiscreteVectorAction(Rect position, SerializedProperty property) { var branchSizes = property.FindPropertyRelative(k_DiscreteBranchSizeName); var newSize = EditorGUI.IntField( position, "Discrete Branches", branchSizes.arraySize); // This check is here due to: // https://fogbugz.unity3d.com/f/cases/1246524/ // If this case has been resolved, please remove this if condition. if (newSize != branchSizes.arraySize) { branchSizes.arraySize = newSize; } position.y += k_LineHeight; position.x += 20; position.width -= 20; for (var branchIndex = 0; branchIndex < branchSizes.arraySize; branchIndex++) { var branchActionSize = branchSizes.GetArrayElementAtIndex(branchIndex); EditorGUI.PropertyField( position, branchActionSize, new GUIContent("Branch " + branchIndex + " Size", "Number of possible actions for the branch number " + branchIndex + ".")); position.y += k_LineHeight; } } /// <summary> /// The Height required to draw the Vector Action parameters. /// </summary> /// <returns>The height of the drawer of the Vector Action.</returns> static float GetHeightDrawVectorAction(SerializedProperty property) { var actionSpecProperty = property.FindPropertyRelative(k_ActionSpecName); var numActionLines = 3 + actionSpecProperty.FindPropertyRelative(k_DiscreteBranchSizeName).arraySize; return numActionLines * k_LineHeight; } } }
ml-agents/com.unity.ml-agents/Editor/BrainParametersDrawer.cs/0
{ "file_path": "ml-agents/com.unity.ml-agents/Editor/BrainParametersDrawer.cs", "repo_id": "ml-agents", "token_count": 3042 }
1,943
fileFormatVersion: 2 guid: b20b0226063034686a6cf92ade284285 NativeFormatImporter: externalObjects: {} mainObjectFileID: 0 userData: assetBundleName: assetBundleVariant:
ml-agents/com.unity.ml-agents/Editor/UnityColors.colors.meta/0
{ "file_path": "ml-agents/com.unity.ml-agents/Editor/UnityColors.colors.meta", "repo_id": "ml-agents", "token_count": 69 }
1,944
fileFormatVersion: 2 guid: 9502ce7e38c5947dba996570732b6e9f PluginImporter: externalObjects: {} serializedVersion: 2 iconMap: {} executionOrder: {} defineConstraints: [] isPreloaded: 0 isOverridable: 0 isExplicitlyReferenced: 1 validateReferences: 1 platformData: - first: Any: second: enabled: 1 settings: {} - first: Editor: Editor second: enabled: 0 settings: DefaultValueInitialized: true - first: Windows Store Apps: WindowsStoreApps second: enabled: 0 settings: CPU: AnyCPU userData: assetBundleName: assetBundleVariant:
ml-agents/com.unity.ml-agents/Plugins/ProtoBuffer/System.Interactive.Async.dll.meta/0
{ "file_path": "ml-agents/com.unity.ml-agents/Plugins/ProtoBuffer/System.Interactive.Async.dll.meta", "repo_id": "ml-agents", "token_count": 270 }
1,945
using System; using System.Linq; using UnityEngine; namespace Unity.MLAgents.Actuators { /// <summary> /// Defines the structure of the actions to be used by the Actuator system. /// </summary> [Serializable] public struct ActionSpec { [SerializeField] int m_NumContinuousActions; /// <summary> /// An array of branch sizes for discrete actions. /// /// For an IActuator that uses discrete actions, the number of /// branches is the Length of the Array and each index contains the branch size. /// The cumulative sum of the total number of discrete actions can be retrieved /// by the <see cref="SumOfDiscreteBranchSizes"/> property. /// /// For an IActuator with a Continuous it will be null. /// </summary> public int[] BranchSizes; /// <summary> /// The number of continuous actions that an Agent can take. /// </summary> public int NumContinuousActions { get { return m_NumContinuousActions; } set { m_NumContinuousActions = value; } } /// <summary> /// The number of branches for discrete actions that an Agent can take. /// </summary> public int NumDiscreteActions { get { return BranchSizes == null ? 0 : BranchSizes.Length; } } /// <summary> /// Get the total number of Discrete Actions that can be taken by calculating the Sum /// of all of the Discrete Action branch sizes. /// </summary> public int SumOfDiscreteBranchSizes { get { return BranchSizes == null ? 0 : BranchSizes.Sum(); } } /// <summary> /// Creates a Continuous <see cref="ActionSpec"/> with the number of actions available. /// </summary> /// <param name="numActions">The number of continuous actions available.</param> /// <returns>An Continuous ActionSpec initialized with the number of actions available.</returns> public static ActionSpec MakeContinuous(int numActions) { var actuatorSpace = new ActionSpec(numActions, null); return actuatorSpace; } /// <summary> /// Creates a Discrete <see cref="ActionSpec"/> with the array of branch sizes that /// represents the action space. /// </summary> /// <param name="branchSizes">The array of branch sizes for the discrete actions. Each index /// contains the number of actions available for that branch.</param> /// <returns>An Discrete ActionSpec initialized with the array of branch sizes.</returns> public static ActionSpec MakeDiscrete(params int[] branchSizes) { var actuatorSpace = new ActionSpec(0, branchSizes); return actuatorSpace; } /// <summary> /// Create an ActionSpec initialized with the specified action sizes. /// </summary> /// <param name="numContinuousActions">The number of continuous actions available.</param> /// <param name="discreteBranchSizes">The array of branch sizes for the discrete actions. Each index /// contains the number of actions available for that branch.</param> public ActionSpec(int numContinuousActions = 0, int[] discreteBranchSizes = null) { m_NumContinuousActions = numContinuousActions; BranchSizes = discreteBranchSizes ?? Array.Empty<int>(); } /// <summary> /// Check that the ActionSpec uses either all continuous or all discrete actions. /// This is only used when connecting to old versions of the trainer that don't support this. /// </summary> /// <exception cref="UnityAgentsException"></exception> internal void CheckAllContinuousOrDiscrete() { if (NumContinuousActions > 0 && NumDiscreteActions > 0) { throw new UnityAgentsException( "Action spaces with both continuous and discrete actions are not supported by the trainer. " + "ActionSpecs must be all continuous or all discrete." ); } } /// <summary> /// Combines a list of actions specs and allocates a new array of branch sizes if needed. /// </summary> /// <param name="specs">The list of action specs to combine.</param> /// <returns>An ActionSpec which represents the aggregate of the ActionSpecs passed in.</returns> public static ActionSpec Combine(params ActionSpec[] specs) { var numContinuous = 0; var numDiscrete = 0; for (var i = 0; i < specs.Length; i++) { var spec = specs[i]; numContinuous += spec.NumContinuousActions; numDiscrete += spec.NumDiscreteActions; } if (numDiscrete <= 0) { return MakeContinuous(numContinuous); } var branchSizes = new int[numDiscrete]; var offset = 0; for (var i = 0; i < specs.Length; i++) { var spec = specs[i]; if (spec.BranchSizes.Length == 0) { continue; } var branchSizesLength = spec.BranchSizes.Length; Array.Copy(spec.BranchSizes, 0, branchSizes, offset, branchSizesLength); offset += branchSizesLength; } return new ActionSpec(numContinuous, branchSizes); } } }
ml-agents/com.unity.ml-agents/Runtime/Actuators/ActionSpec.cs/0
{ "file_path": "ml-agents/com.unity.ml-agents/Runtime/Actuators/ActionSpec.cs", "repo_id": "ml-agents", "token_count": 2334 }
1,946
namespace Unity.MLAgents.Actuators { /// <summary> /// Interface that allows objects to fill out an <see cref="ActionBuffers"/> data structure for controlling /// behavior of Agents or Actuators. /// </summary> public interface IHeuristicProvider { /// <summary> /// Method called on objects which are expected to fill out the <see cref="ActionBuffers"/> data structure. /// Object that implement this interface should be careful to be consistent in the placement of their actions /// in the <see cref="ActionBuffers"/> data structure. /// </summary> /// <param name="actionBuffersOut">The <see cref="ActionBuffers"/> data structure to be filled by the /// object implementing this interface.</param> void Heuristic(in ActionBuffers actionBuffersOut); } }
ml-agents/com.unity.ml-agents/Runtime/Actuators/IHeuristicProvider.cs/0
{ "file_path": "ml-agents/com.unity.ml-agents/Runtime/Actuators/IHeuristicProvider.cs", "repo_id": "ml-agents", "token_count": 268 }
1,947
using System; using Unity.Mathematics; using UnityEngine; namespace Unity.MLAgents.Areas { /// <summary> /// The Training Ares Replicator allows for a training area object group to be replicated dynamically during runtime. /// </summary> [DefaultExecutionOrder(-5)] public class TrainingAreaReplicator : MonoBehaviour { /// <summary> /// The base training area to be replicated. /// </summary> public GameObject baseArea; /// <summary> /// The number of training areas to replicate. /// </summary> public int numAreas = 1; /// <summary> /// The separation between each training area. /// </summary> public float separation = 10f; /// <summary> /// Whether to replicate in the editor or in a build only. Default = true /// </summary> public bool buildOnly = true; int3 m_GridSize = new(1, 1, 1); int m_AreaCount; string m_TrainingAreaName; /// <summary> /// The size of the computed grid to pack the training areas into. /// </summary> public int3 GridSize => m_GridSize; /// <summary> /// The name of the training area. /// </summary> public string TrainingAreaName => m_TrainingAreaName; /// <summary> /// Called before the simulation begins to computed the grid size for distributing /// the replicated training areas and set the area name. /// </summary> public void Awake() { // Computes the Grid Size on Awake ComputeGridSize(); // Sets the TrainingArea name to the name of the base area. m_TrainingAreaName = baseArea.name; } /// <summary> /// Called after Awake and before the simulation begins and adds the training areas before /// the Academy begins. /// </summary> public void OnEnable() { // Adds the training as replicas during OnEnable to ensure they are added before the Academy begins its work. if (buildOnly) { #if UNITY_STANDALONE && !UNITY_EDITOR AddEnvironments(); #endif return; } AddEnvironments(); } /// <summary> /// Computes the Grid Size for replicating the training area. /// </summary> void ComputeGridSize() { // check if running inference, if so, use the num areas set through the component, // otherwise, pull it from the academy if (Academy.Instance.Communicator != null) numAreas = Academy.Instance.NumAreas; var rootNumAreas = Mathf.Pow(numAreas, 1.0f / 3.0f); m_GridSize.x = Mathf.CeilToInt(rootNumAreas); m_GridSize.y = Mathf.CeilToInt(rootNumAreas); var zSize = Mathf.CeilToInt((float)numAreas / (m_GridSize.x * m_GridSize.y)); m_GridSize.z = zSize == 0 ? 1 : zSize; } /// <summary> /// Adds replicas of the training area to the scene. /// </summary> /// <exception cref="UnityAgentsException"></exception> void AddEnvironments() { if (numAreas > m_GridSize.x * m_GridSize.y * m_GridSize.z) { throw new UnityAgentsException("The number of training areas that you have specified exceeds the size of the grid."); } for (int z = 0; z < m_GridSize.z; z++) { for (int y = 0; y < m_GridSize.y; y++) { for (int x = 0; x < m_GridSize.x; x++) { if (m_AreaCount == 0) { // Skip this first area since it already exists. m_AreaCount = 1; } else if (m_AreaCount < numAreas) { m_AreaCount++; var area = Instantiate(baseArea, new Vector3(x * separation, y * separation, z * separation), Quaternion.identity); area.name = m_TrainingAreaName; } } } } } } }
ml-agents/com.unity.ml-agents/Runtime/Areas/TrainingAreaReplicator.cs/0
{ "file_path": "ml-agents/com.unity.ml-agents/Runtime/Areas/TrainingAreaReplicator.cs", "repo_id": "ml-agents", "token_count": 2080 }
1,948
fileFormatVersion: 2 guid: 0622d88401ec464d9d2cf2fb03ce17b5 timeCreated: 1579215785
ml-agents/com.unity.ml-agents/Runtime/Constants.cs.meta/0
{ "file_path": "ml-agents/com.unity.ml-agents/Runtime/Constants.cs.meta", "repo_id": "ml-agents", "token_count": 39 }
1,949
fileFormatVersion: 2 guid: 418327e202c7464bb6649d025df1b539 timeCreated: 1569444731
ml-agents/com.unity.ml-agents/Runtime/Grpc.meta/0
{ "file_path": "ml-agents/com.unity.ml-agents/Runtime/Grpc.meta", "repo_id": "ml-agents", "token_count": 39 }
1,950
// <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: mlagents_envs/communicator_objects/custom_reset_parameters.proto // </auto-generated> #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Unity.MLAgents.CommunicatorObjects { /// <summary>Holder for reflection information generated from mlagents_envs/communicator_objects/custom_reset_parameters.proto</summary> internal static partial class CustomResetParametersReflection { #region Descriptor /// <summary>File descriptor for mlagents_envs/communicator_objects/custom_reset_parameters.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static CustomResetParametersReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CkBtbGFnZW50c19lbnZzL2NvbW11bmljYXRvcl9vYmplY3RzL2N1c3RvbV9y", "ZXNldF9wYXJhbWV0ZXJzLnByb3RvEhRjb21tdW5pY2F0b3Jfb2JqZWN0cyIc", "ChpDdXN0b21SZXNldFBhcmFtZXRlcnNQcm90b0IlqgIiVW5pdHkuTUxBZ2Vu", "dHMuQ29tbXVuaWNhdG9yT2JqZWN0c2IGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Unity.MLAgents.CommunicatorObjects.CustomResetParametersProto), global::Unity.MLAgents.CommunicatorObjects.CustomResetParametersProto.Parser, null, null, null, null) })); } #endregion } #region Messages internal sealed partial class CustomResetParametersProto : pb::IMessage<CustomResetParametersProto> { private static readonly pb::MessageParser<CustomResetParametersProto> _parser = new pb::MessageParser<CustomResetParametersProto>(() => new CustomResetParametersProto()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<CustomResetParametersProto> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Unity.MLAgents.CommunicatorObjects.CustomResetParametersReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CustomResetParametersProto() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CustomResetParametersProto(CustomResetParametersProto other) : this() { _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CustomResetParametersProto Clone() { return new CustomResetParametersProto(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as CustomResetParametersProto); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(CustomResetParametersProto other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (_unknownFields != null) { _unknownFields.WriteTo(output); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(CustomResetParametersProto other) { if (other == null) { return; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; } } } } #endregion } #endregion Designer generated code
ml-agents/com.unity.ml-agents/Runtime/Grpc/CommunicatorObjects/CustomResetParameters.cs/0
{ "file_path": "ml-agents/com.unity.ml-agents/Runtime/Grpc/CommunicatorObjects/CustomResetParameters.cs", "repo_id": "ml-agents", "token_count": 2059 }
1,951
// <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: mlagents_envs/communicator_objects/unity_message.proto // </auto-generated> #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Unity.MLAgents.CommunicatorObjects { /// <summary>Holder for reflection information generated from mlagents_envs/communicator_objects/unity_message.proto</summary> internal static partial class UnityMessageReflection { #region Descriptor /// <summary>File descriptor for mlagents_envs/communicator_objects/unity_message.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static UnityMessageReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CjZtbGFnZW50c19lbnZzL2NvbW11bmljYXRvcl9vYmplY3RzL3VuaXR5X21l", "c3NhZ2UucHJvdG8SFGNvbW11bmljYXRvcl9vYmplY3RzGjVtbGFnZW50c19l", "bnZzL2NvbW11bmljYXRvcl9vYmplY3RzL3VuaXR5X291dHB1dC5wcm90bxo0", "bWxhZ2VudHNfZW52cy9jb21tdW5pY2F0b3Jfb2JqZWN0cy91bml0eV9pbnB1", "dC5wcm90bxovbWxhZ2VudHNfZW52cy9jb21tdW5pY2F0b3Jfb2JqZWN0cy9o", "ZWFkZXIucHJvdG8iwAEKEVVuaXR5TWVzc2FnZVByb3RvEjEKBmhlYWRlchgB", "IAEoCzIhLmNvbW11bmljYXRvcl9vYmplY3RzLkhlYWRlclByb3RvEjwKDHVu", "aXR5X291dHB1dBgCIAEoCzImLmNvbW11bmljYXRvcl9vYmplY3RzLlVuaXR5", "T3V0cHV0UHJvdG8SOgoLdW5pdHlfaW5wdXQYAyABKAsyJS5jb21tdW5pY2F0", "b3Jfb2JqZWN0cy5Vbml0eUlucHV0UHJvdG9CJaoCIlVuaXR5Lk1MQWdlbnRz", "LkNvbW11bmljYXRvck9iamVjdHNiBnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Unity.MLAgents.CommunicatorObjects.UnityOutputReflection.Descriptor, global::Unity.MLAgents.CommunicatorObjects.UnityInputReflection.Descriptor, global::Unity.MLAgents.CommunicatorObjects.HeaderReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Unity.MLAgents.CommunicatorObjects.UnityMessageProto), global::Unity.MLAgents.CommunicatorObjects.UnityMessageProto.Parser, new[]{ "Header", "UnityOutput", "UnityInput" }, null, null, null) })); } #endregion } #region Messages internal sealed partial class UnityMessageProto : pb::IMessage<UnityMessageProto> { private static readonly pb::MessageParser<UnityMessageProto> _parser = new pb::MessageParser<UnityMessageProto>(() => new UnityMessageProto()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<UnityMessageProto> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Unity.MLAgents.CommunicatorObjects.UnityMessageReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UnityMessageProto() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UnityMessageProto(UnityMessageProto other) : this() { Header = other.header_ != null ? other.Header.Clone() : null; UnityOutput = other.unityOutput_ != null ? other.UnityOutput.Clone() : null; UnityInput = other.unityInput_ != null ? other.UnityInput.Clone() : null; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UnityMessageProto Clone() { return new UnityMessageProto(this); } /// <summary>Field number for the "header" field.</summary> public const int HeaderFieldNumber = 1; private global::Unity.MLAgents.CommunicatorObjects.HeaderProto header_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Unity.MLAgents.CommunicatorObjects.HeaderProto Header { get { return header_; } set { header_ = value; } } /// <summary>Field number for the "unity_output" field.</summary> public const int UnityOutputFieldNumber = 2; private global::Unity.MLAgents.CommunicatorObjects.UnityOutputProto unityOutput_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Unity.MLAgents.CommunicatorObjects.UnityOutputProto UnityOutput { get { return unityOutput_; } set { unityOutput_ = value; } } /// <summary>Field number for the "unity_input" field.</summary> public const int UnityInputFieldNumber = 3; private global::Unity.MLAgents.CommunicatorObjects.UnityInputProto unityInput_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Unity.MLAgents.CommunicatorObjects.UnityInputProto UnityInput { get { return unityInput_; } set { unityInput_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as UnityMessageProto); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(UnityMessageProto other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(Header, other.Header)) return false; if (!object.Equals(UnityOutput, other.UnityOutput)) return false; if (!object.Equals(UnityInput, other.UnityInput)) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (header_ != null) hash ^= Header.GetHashCode(); if (unityOutput_ != null) hash ^= UnityOutput.GetHashCode(); if (unityInput_ != null) hash ^= UnityInput.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (header_ != null) { output.WriteRawTag(10); output.WriteMessage(Header); } if (unityOutput_ != null) { output.WriteRawTag(18); output.WriteMessage(UnityOutput); } if (unityInput_ != null) { output.WriteRawTag(26); output.WriteMessage(UnityInput); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (header_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Header); } if (unityOutput_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(UnityOutput); } if (unityInput_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(UnityInput); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(UnityMessageProto other) { if (other == null) { return; } if (other.header_ != null) { if (header_ == null) { header_ = new global::Unity.MLAgents.CommunicatorObjects.HeaderProto(); } Header.MergeFrom(other.Header); } if (other.unityOutput_ != null) { if (unityOutput_ == null) { unityOutput_ = new global::Unity.MLAgents.CommunicatorObjects.UnityOutputProto(); } UnityOutput.MergeFrom(other.UnityOutput); } if (other.unityInput_ != null) { if (unityInput_ == null) { unityInput_ = new global::Unity.MLAgents.CommunicatorObjects.UnityInputProto(); } UnityInput.MergeFrom(other.UnityInput); } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { if (header_ == null) { header_ = new global::Unity.MLAgents.CommunicatorObjects.HeaderProto(); } input.ReadMessage(header_); break; } case 18: { if (unityOutput_ == null) { unityOutput_ = new global::Unity.MLAgents.CommunicatorObjects.UnityOutputProto(); } input.ReadMessage(unityOutput_); break; } case 26: { if (unityInput_ == null) { unityInput_ = new global::Unity.MLAgents.CommunicatorObjects.UnityInputProto(); } input.ReadMessage(unityInput_); break; } } } } } #endregion } #endregion Designer generated code
ml-agents/com.unity.ml-agents/Runtime/Grpc/CommunicatorObjects/UnityMessage.cs/0
{ "file_path": "ml-agents/com.unity.ml-agents/Runtime/Grpc/CommunicatorObjects/UnityMessage.cs", "repo_id": "ml-agents", "token_count": 4200 }
1,952
{ "name": "Unity.ML-Agents.CommunicatorObjects", "rootNamespace": "", "references": [], "includePlatforms": [], "excludePlatforms": [], "allowUnsafeCode": false, "overrideReferences": false, "precompiledReferences": [ "System.IO.Abstractions.dll", "Google.Protobuf.dll", "Grpc.Core.dll" ], "autoReferenced": true, "defineConstraints": [], "versionDefines": [], "noEngineReferences": false }
ml-agents/com.unity.ml-agents/Runtime/Grpc/Unity.ML-Agents.CommunicatorObjects.asmdef/0
{ "file_path": "ml-agents/com.unity.ml-agents/Runtime/Grpc/Unity.ML-Agents.CommunicatorObjects.asmdef", "repo_id": "ml-agents", "token_count": 203 }
1,953
fileFormatVersion: 2 guid: 6f1b600613ec4960b40f8b4b8bc1f713 timeCreated: 1680984637
ml-agents/com.unity.ml-agents/Runtime/Inference/SymbolicTensorShapeExtensions.cs.meta/0
{ "file_path": "ml-agents/com.unity.ml-agents/Runtime/Inference/SymbolicTensorShapeExtensions.cs.meta", "repo_id": "ml-agents", "token_count": 39 }
1,954
using System; using System.Collections.Generic; namespace Unity.MLAgents { /// <summary> /// An array-like object that stores up to four elements. /// This is a value type that does not allocate any additional memory. /// </summary> /// <remarks> /// This does not implement any interfaces such as IList, in order to avoid any accidental boxing allocations. /// </remarks> /// <typeparam name="T"></typeparam> public struct InplaceArray<T> : IEquatable<InplaceArray<T>> where T : struct { private const int k_MaxLength = 4; private readonly int m_Length; private T m_Elem0; private T m_Elem1; private T m_Elem2; private T m_Elem3; /// <summary> /// Create a length-1 array. /// </summary> /// <param name="elem0"></param> public InplaceArray(T elem0) { m_Length = 1; m_Elem0 = elem0; m_Elem1 = new T(); m_Elem2 = new T(); m_Elem3 = new T(); } /// <summary> /// Create a length-2 array. /// </summary> /// <param name="elem0"></param> /// <param name="elem1"></param> public InplaceArray(T elem0, T elem1) { m_Length = 2; m_Elem0 = elem0; m_Elem1 = elem1; m_Elem2 = new T(); m_Elem3 = new T(); } /// <summary> /// Create a length-3 array. /// </summary> /// <param name="elem0"></param> /// <param name="elem1"></param> /// <param name="elem2"></param> public InplaceArray(T elem0, T elem1, T elem2) { m_Length = 3; m_Elem0 = elem0; m_Elem1 = elem1; m_Elem2 = elem2; m_Elem3 = new T(); } /// <summary> /// Create a length-3 array. /// </summary> /// <param name="elem0"></param> /// <param name="elem1"></param> /// <param name="elem2"></param> /// <param name="elem3"></param> public InplaceArray(T elem0, T elem1, T elem2, T elem3) { m_Length = 4; m_Elem0 = elem0; m_Elem1 = elem1; m_Elem2 = elem2; m_Elem3 = elem3; } /// <summary> /// Construct an InplaceArray from an IList (e.g. Array or List). /// The source must be non-empty and have at most 4 elements. /// </summary> /// <param name="elems"></param> /// <returns></returns> /// <exception cref="ArgumentOutOfRangeException"></exception> public static InplaceArray<T> FromList(IList<T> elems) { switch (elems.Count) { case 1: return new InplaceArray<T>(elems[0]); case 2: return new InplaceArray<T>(elems[0], elems[1]); case 3: return new InplaceArray<T>(elems[0], elems[1], elems[2]); case 4: return new InplaceArray<T>(elems[0], elems[1], elems[2], elems[3]); default: throw new ArgumentOutOfRangeException(); } } /// <summary> /// Per-element access. /// </summary> /// <param name="index"></param> /// <exception cref="IndexOutOfRangeException"></exception> public T this[int index] { get { if (index >= Length) { throw new IndexOutOfRangeException(); } switch (index) { case 0: return m_Elem0; case 1: return m_Elem1; case 2: return m_Elem2; case 3: return m_Elem3; default: throw new IndexOutOfRangeException(); } } set { if (index >= Length) { throw new IndexOutOfRangeException(); } switch (index) { case 0: m_Elem0 = value; break; case 1: m_Elem1 = value; break; case 2: m_Elem2 = value; break; case 3: m_Elem3 = value; break; default: throw new IndexOutOfRangeException(); } } } /// <summary> /// The length of the array. /// </summary> public int Length { get => m_Length; } /// <summary> /// Returns a string representation of the array's elements. /// </summary> /// <returns></returns> /// <exception cref="IndexOutOfRangeException"></exception> public override string ToString() { switch (m_Length) { case 1: return $"[{m_Elem0}]"; case 2: return $"[{m_Elem0}, {m_Elem1}]"; case 3: return $"[{m_Elem0}, {m_Elem1}, {m_Elem2}]"; case 4: return $"[{m_Elem0}, {m_Elem1}, {m_Elem2}, {m_Elem3}]"; default: throw new IndexOutOfRangeException(); } } /// <summary> /// Check that the arrays have the same length and have all equal values. /// </summary> /// <param name="lhs"></param> /// <param name="rhs"></param> /// <returns>Whether the arrays are equivalent.</returns> public static bool operator ==(InplaceArray<T> lhs, InplaceArray<T> rhs) { return lhs.Equals(rhs); } /// <summary> /// Check that the arrays are not equivalent. /// </summary> /// <param name="lhs"></param> /// <param name="rhs"></param> /// <returns>Whether the arrays are not equivalent</returns> public static bool operator !=(InplaceArray<T> lhs, InplaceArray<T> rhs) => !lhs.Equals(rhs); /// <summary> /// Check that the arrays are equivalent. /// </summary> /// <param name="other"></param> /// <returns>Whether the arrays are not equivalent</returns> public override bool Equals(object other) => other is InplaceArray<T> other1 && this.Equals(other1); /// <summary> /// Check that the arrays are equivalent. /// </summary> /// <param name="other"></param> /// <returns>Whether the arrays are not equivalent</returns> public bool Equals(InplaceArray<T> other) { // See https://montemagno.com/optimizing-c-struct-equality-with-iequatable/ var thisTuple = (m_Elem0, m_Elem1, m_Elem2, m_Elem3, Length); var otherTuple = (other.m_Elem0, other.m_Elem1, other.m_Elem2, other.m_Elem3, other.Length); return thisTuple.Equals(otherTuple); } /// <summary> /// Get a hashcode for the array. /// </summary> /// <returns></returns> public override int GetHashCode() { return (m_Elem0, m_Elem1, m_Elem2, m_Elem3, Length).GetHashCode(); } } }
ml-agents/com.unity.ml-agents/Runtime/InplaceArray.cs/0
{ "file_path": "ml-agents/com.unity.ml-agents/Runtime/InplaceArray.cs", "repo_id": "ml-agents", "token_count": 4220 }
1,955
using UnityEngine; using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("Unity.ML-Agents.DevTests.Editor")] namespace Unity.MLAgents { internal class MLAgentsSettings : ScriptableObject { [SerializeField] private bool m_ConnectTrainer = true; [SerializeField] private int m_EditorPort = 5004; public bool ConnectTrainer { get { return m_ConnectTrainer; } set { m_ConnectTrainer = value; OnChange(); } } public int EditorPort { get { return m_EditorPort; } set { m_EditorPort = value; OnChange(); } } internal void OnChange() { if (MLAgentsSettingsManager.Settings == this) MLAgentsSettingsManager.ApplySettings(); } } }
ml-agents/com.unity.ml-agents/Runtime/MLAgentsSettings.cs/0
{ "file_path": "ml-agents/com.unity.ml-agents/Runtime/MLAgentsSettings.cs", "repo_id": "ml-agents", "token_count": 485 }
1,956
using System; using UnityEngine; using UnityEngine.Rendering; namespace Unity.MLAgents.Sensors { /// <summary> /// A sensor that wraps a Camera object to generate visual observations for an agent. /// </summary> public class CameraSensor : ISensor, IBuiltInSensor, IDisposable { Camera m_Camera; int m_Width; int m_Height; bool m_Grayscale; string m_Name; private ObservationSpec m_ObservationSpec; SensorCompressionType m_CompressionType; Texture2D m_Texture; /// <summary> /// The Camera used for rendering the sensor observations. /// </summary> public Camera Camera { get { return m_Camera; } set { m_Camera = value; } } /// <summary> /// The compression type used by the sensor. /// </summary> public SensorCompressionType CompressionType { get { return m_CompressionType; } set { m_CompressionType = value; } } /// <summary> /// Creates and returns the camera sensor. /// </summary> /// <param name="camera">Camera object to capture images from.</param> /// <param name="width">The width of the generated visual observation.</param> /// <param name="height">The height of the generated visual observation.</param> /// <param name="grayscale">Whether to convert the generated image to grayscale or keep color.</param> /// <param name="name">The name of the camera sensor.</param> /// <param name="compression">The compression to apply to the generated image.</param> /// <param name="observationType">The type of observation.</param> public CameraSensor( Camera camera, int width, int height, bool grayscale, string name, SensorCompressionType compression, ObservationType observationType = ObservationType.Default) { m_Camera = camera; m_Width = width; m_Height = height; m_Grayscale = grayscale; m_Name = name; var channels = grayscale ? 1 : 3; m_ObservationSpec = ObservationSpec.Visual(channels, height, width, observationType); m_CompressionType = compression; m_Texture = new Texture2D(width, height, TextureFormat.RGB24, false); } /// <summary> /// Accessor for the name of the sensor. /// </summary> /// <returns>Sensor name.</returns> public string GetName() { return m_Name; } /// <summary> /// Returns a description of the observations that will be generated by the sensor. /// The shape will be 1 x h x w for grayscale and 3 x h x w for color. /// The dimensions have translational equivariance along width and height, /// and no property along the channels dimension. /// </summary> /// <returns></returns> public ObservationSpec GetObservationSpec() { return m_ObservationSpec; } /// <summary> /// Generates a compressed image. This can be valuable in speeding-up training. /// </summary> /// <returns>Compressed image.</returns> public byte[] GetCompressedObservation() { using (TimerStack.Instance.Scoped("CameraSensor.GetCompressedObservation")) { // TODO support more types here, e.g. JPG var compressed = m_Texture.EncodeToPNG(); return compressed; } } /// <summary> /// Writes out the generated, uncompressed image to the provided <see cref="ObservationWriter"/>. /// </summary> /// <param name="writer">Where the observation is written to.</param> /// <returns></returns> public int Write(ObservationWriter writer) { using (TimerStack.Instance.Scoped("CameraSensor.WriteToTensor")) { var numWritten = writer.WriteTexture(m_Texture, m_Grayscale); return numWritten; } } /// <inheritdoc/> public void Update() { ObservationToTexture(m_Camera, m_Texture, m_Width, m_Height); } /// <inheritdoc/> public void Reset() { } /// <inheritdoc/> public CompressionSpec GetCompressionSpec() { return new CompressionSpec(m_CompressionType); } /// <summary> /// Renders a Camera instance to a 2D texture at the corresponding resolution. /// </summary> /// <param name="obsCamera">Camera.</param> /// <param name="texture2D">Texture2D to render to.</param> /// <param name="width">Width of resulting 2D texture.</param> /// <param name="height">Height of resulting 2D texture.</param> public static void ObservationToTexture(Camera obsCamera, Texture2D texture2D, int width, int height) { if (SystemInfo.graphicsDeviceType == GraphicsDeviceType.Null) { Debug.LogError("GraphicsDeviceType is Null. This will likely crash when trying to render."); } var oldRec = obsCamera.rect; obsCamera.rect = new Rect(0f, 0f, 1f, 1f); var depth = 24; var format = RenderTextureFormat.Default; var readWrite = RenderTextureReadWrite.Default; var tempRt = RenderTexture.GetTemporary(width, height, depth, format, readWrite); var prevActiveRt = RenderTexture.active; var prevCameraRt = obsCamera.targetTexture; // render to offscreen texture (readonly from CPU side) RenderTexture.active = tempRt; obsCamera.targetTexture = tempRt; obsCamera.Render(); texture2D.ReadPixels(new Rect(0, 0, texture2D.width, texture2D.height), 0, 0); obsCamera.targetTexture = prevCameraRt; obsCamera.rect = oldRec; RenderTexture.active = prevActiveRt; RenderTexture.ReleaseTemporary(tempRt); } /// <inheritdoc/> public BuiltInSensorType GetBuiltInSensorType() { return BuiltInSensorType.CameraSensor; } /// <summary> /// Clean up the owned Texture2D. /// </summary> public void Dispose() { if (!ReferenceEquals(null, m_Texture)) { Utilities.DestroyTexture(m_Texture); m_Texture = null; } } } }
ml-agents/com.unity.ml-agents/Runtime/Sensors/CameraSensor.cs/0
{ "file_path": "ml-agents/com.unity.ml-agents/Runtime/Sensors/CameraSensor.cs", "repo_id": "ml-agents", "token_count": 2868 }
1,957
namespace Unity.MLAgents.Sensors { /// <summary> /// A description of the observations that an ISensor produces. /// This includes the size of the observation, the properties of each dimension, and how the observation /// should be used for training. /// </summary> public struct ObservationSpec { internal readonly InplaceArray<int> m_Shape; /// <summary> /// The size of the observations that will be generated. /// For example, a sensor that observes the velocity of a rigid body (in 3D) would use [3]. /// A sensor that returns an RGB image would use [Height, Width, 3]. /// </summary> public InplaceArray<int> Shape { get => m_Shape; } internal readonly InplaceArray<DimensionProperty> m_DimensionProperties; /// <summary> /// The properties of each dimensions of the observation. /// The length of the array must be equal to the rank of the observation tensor. /// </summary> /// <remarks> /// It is generally recommended to use default values provided by helper functions, /// as not all combinations of DimensionProperty may be supported by the trainer. /// </remarks> public InplaceArray<DimensionProperty> DimensionProperties { get => m_DimensionProperties; } internal ObservationType m_ObservationType; /// <summary> /// The type of the observation, e.g. whether they are generic or /// help determine the goal for the Agent. /// </summary> public ObservationType ObservationType { get => m_ObservationType; } /// <summary> /// The number of dimensions of the observation. /// </summary> public int Rank { get { return Shape.Length; } } /// <summary> /// Construct an ObservationSpec for 1-D observations of the requested length. /// </summary> /// <param name="length"></param> /// <param name="obsType"></param> /// <returns></returns> public static ObservationSpec Vector(int length, ObservationType obsType = ObservationType.Default) { return new ObservationSpec( new InplaceArray<int>(length), new InplaceArray<DimensionProperty>(DimensionProperty.None), obsType ); } /// <summary> /// Construct an ObservationSpec for variable-length observations. /// </summary> /// <param name="obsSize"></param> /// <param name="maxNumObs"></param> /// <returns></returns> public static ObservationSpec VariableLength(int obsSize, int maxNumObs) { var dimProps = new InplaceArray<DimensionProperty>( DimensionProperty.VariableSize, DimensionProperty.None ); return new ObservationSpec( new InplaceArray<int>(obsSize, maxNumObs), dimProps ); } /// <summary> /// Construct an ObservationSpec for visual-like observations, e.g. observations /// with a height, width, and possible multiple channels. /// </summary> /// <param name="height"></param> /// <param name="width"></param> /// <param name="channels"></param> /// <param name="obsType"></param> /// <returns></returns> public static ObservationSpec Visual(int channels, int height, int width, ObservationType obsType = ObservationType.Default) { var dimProps = new InplaceArray<DimensionProperty>( DimensionProperty.None, DimensionProperty.TranslationalEquivariance, DimensionProperty.TranslationalEquivariance ); return new ObservationSpec( new InplaceArray<int>(channels, height, width), dimProps, obsType ); } /// <summary> /// Create a general ObservationSpec from the shape, dimension properties, and observation type. /// </summary> /// <remarks> /// Note that not all combinations of DimensionProperty may be supported by the trainer. /// shape and dimensionProperties must have the same size. /// </remarks> /// <param name="shape"></param> /// <param name="dimensionProperties"></param> /// <param name="observationType"></param> /// <exception cref="UnityAgentsException"></exception> public ObservationSpec( InplaceArray<int> shape, InplaceArray<DimensionProperty> dimensionProperties, ObservationType observationType = ObservationType.Default ) { if (shape.Length != dimensionProperties.Length) { throw new UnityAgentsException("shape and dimensionProperties must have the same length."); } m_Shape = shape; m_DimensionProperties = dimensionProperties; m_ObservationType = observationType; } } }
ml-agents/com.unity.ml-agents/Runtime/Sensors/ObservationSpec.cs/0
{ "file_path": "ml-agents/com.unity.ml-agents/Runtime/Sensors/ObservationSpec.cs", "repo_id": "ml-agents", "token_count": 2149 }
1,958
fileFormatVersion: 2 guid: be795c90750a6420d93f569b69ddc1ba MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ml-agents/com.unity.ml-agents/Runtime/Sensors/Reflection/BoolReflectionSensor.cs.meta/0
{ "file_path": "ml-agents/com.unity.ml-agents/Runtime/Sensors/Reflection/BoolReflectionSensor.cs.meta", "repo_id": "ml-agents", "token_count": 95 }
1,959
fileFormatVersion: 2 guid: e756976ec2a0943cfbc0f97a6550a85b MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ml-agents/com.unity.ml-agents/Runtime/Sensors/Reflection/Vector3ReflectionSensor.cs.meta/0
{ "file_path": "ml-agents/com.unity.ml-agents/Runtime/Sensors/Reflection/Vector3ReflectionSensor.cs.meta", "repo_id": "ml-agents", "token_count": 95 }
1,960
fileFormatVersion: 2 guid: 38b7cc1f5819445aa85e9a9b054552dc MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ml-agents/com.unity.ml-agents/Runtime/Sensors/VectorSensorComponent.cs.meta/0
{ "file_path": "ml-agents/com.unity.ml-agents/Runtime/Sensors/VectorSensorComponent.cs.meta", "repo_id": "ml-agents", "token_count": 95 }
1,961
using System; using System.Collections.Generic; using UnityEngine; using System.IO; namespace Unity.MLAgents.SideChannels { /// <summary> /// Collection of static utilities for managing the registering/unregistering of /// <see cref="SideChannels"/> and the sending/receiving of messages for all the channels. /// </summary> public static class SideChannelManager { static Dictionary<Guid, SideChannel> s_RegisteredChannels = new Dictionary<Guid, SideChannel>(); struct CachedSideChannelMessage { public Guid ChannelId; public byte[] Message; } static readonly Queue<CachedSideChannelMessage> s_CachedMessages = new Queue<CachedSideChannelMessage>(); /// <summary> /// Register a side channel to begin sending and receiving messages. This method is /// available for environments that have custom side channels. All built-in side /// channels within the ML-Agents Toolkit are managed internally and do not need to /// be explicitly registered/unregistered. A side channel may only be registered once. /// </summary> /// <param name="sideChannel">The side channel to register.</param> public static void RegisterSideChannel(SideChannel sideChannel) { var channelId = sideChannel.ChannelId; if (s_RegisteredChannels.ContainsKey(channelId)) { throw new UnityAgentsException( $"A side channel with id {channelId} is already registered. " + "You cannot register multiple side channels of the same id."); } // Process any messages that we've already received for this channel ID. var numMessages = s_CachedMessages.Count; for (var i = 0; i < numMessages; i++) { var cachedMessage = s_CachedMessages.Dequeue(); if (channelId == cachedMessage.ChannelId) { sideChannel.ProcessMessage(cachedMessage.Message); } else { s_CachedMessages.Enqueue(cachedMessage); } } s_RegisteredChannels.Add(channelId, sideChannel); } /// <summary> /// Unregister a side channel to stop sending and receiving messages. This method is /// available for environments that have custom side channels. All built-in side /// channels within the ML-Agents Toolkit are managed internally and do not need to /// be explicitly registered/unregistered. Unregistering a side channel that has already /// been unregistered (or never registered in the first place) has no negative side effects. /// Note that unregistering a side channel may not stop the Python side /// from sending messages, but it does mean that sent messages with not result in a call /// to <see cref="SideChannel.OnMessageReceived(IncomingMessage)"/>. Furthermore, /// those messages will not be buffered and will, in essence, be lost. /// </summary> /// <param name="sideChannel">The side channel to unregister.</param> public static void UnregisterSideChannel(SideChannel sideChannel) { if (s_RegisteredChannels.ContainsKey(sideChannel.ChannelId)) { s_RegisteredChannels.Remove(sideChannel.ChannelId); } } /// <summary> /// Unregisters all the side channels from the communicator. /// </summary> internal static void UnregisterAllSideChannels() { s_RegisteredChannels = new Dictionary<Guid, SideChannel>(); } /// <summary> /// Returns the SideChannel of Type T if there is one registered, or null if it doesn't. /// If there are multiple SideChannels of the same type registered, the returned instance is arbitrary. /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> internal static T GetSideChannel<T>() where T : SideChannel { foreach (var sc in s_RegisteredChannels.Values) { if (sc.GetType() == typeof(T)) { return (T)sc; } } return null; } /// <summary> /// Grabs the messages that the registered side channels will send to Python at the current step /// into a singe byte array. /// </summary> /// <returns></returns> internal static byte[] GetSideChannelMessage() { return GetSideChannelMessage(s_RegisteredChannels); } /// <summary> /// Grabs the messages that the registered side channels will send to Python at the current step /// into a singe byte array. /// </summary> /// <param name="sideChannels"> A dictionary of channel type to channel.</param> /// <returns></returns> internal static byte[] GetSideChannelMessage(Dictionary<Guid, SideChannel> sideChannels) { if (!HasOutgoingMessages(sideChannels)) { // Early out so that we don't create the MemoryStream or BinaryWriter. // This is the most common case. return Array.Empty<byte>(); } using (var memStream = new MemoryStream()) { using (var binaryWriter = new BinaryWriter(memStream)) { foreach (var sideChannel in sideChannels.Values) { var messageList = sideChannel.MessageQueue; foreach (var message in messageList) { binaryWriter.Write(sideChannel.ChannelId.ToByteArray()); binaryWriter.Write(message.Length); binaryWriter.Write(message); } sideChannel.MessageQueue.Clear(); } return memStream.ToArray(); } } } /// <summary> /// Check whether any of the sidechannels have queued messages. /// </summary> /// <param name="sideChannels"></param> /// <returns></returns> static bool HasOutgoingMessages(Dictionary<Guid, SideChannel> sideChannels) { foreach (var sideChannel in sideChannels.Values) { var messageList = sideChannel.MessageQueue; if (messageList.Count > 0) { return true; } } return false; } /// <summary> /// Separates the data received from Python into individual messages for each registered side channel. /// </summary> /// <param name="dataReceived">The byte array of data received from Python.</param> internal static void ProcessSideChannelData(byte[] dataReceived) { ProcessSideChannelData(s_RegisteredChannels, dataReceived); } /// <summary> /// Separates the data received from Python into individual messages for each registered side channel. /// </summary> /// <param name="sideChannels">A dictionary of channel type to channel.</param> /// <param name="dataReceived">The byte array of data received from Python.</param> internal static void ProcessSideChannelData(Dictionary<Guid, SideChannel> sideChannels, byte[] dataReceived) { while (s_CachedMessages.Count != 0) { var cachedMessage = s_CachedMessages.Dequeue(); if (sideChannels.ContainsKey(cachedMessage.ChannelId)) { sideChannels[cachedMessage.ChannelId].ProcessMessage(cachedMessage.Message); } else { Debug.Log(string.Format( "Unknown side channel data received. Channel Id is " + ": {0}", cachedMessage.ChannelId)); } } if (dataReceived.Length == 0) { return; } using (var memStream = new MemoryStream(dataReceived)) { using (var binaryReader = new BinaryReader(memStream)) { while (memStream.Position < memStream.Length) { Guid channelId = Guid.Empty; byte[] message = null; try { channelId = new Guid(binaryReader.ReadBytes(16)); var messageLength = binaryReader.ReadInt32(); message = binaryReader.ReadBytes(messageLength); } catch (Exception ex) { throw new UnityAgentsException( "There was a problem reading a message in a SideChannel. Please make sure the " + "version of MLAgents in Unity is compatible with the Python version. Original error : " + ex.Message); } if (sideChannels.ContainsKey(channelId)) { sideChannels[channelId].ProcessMessage(message); } else { // Don't recognize this ID, but cache it in case the SideChannel that can handle // it is registered before the next call to ProcessSideChannelData. s_CachedMessages.Enqueue(new CachedSideChannelMessage { ChannelId = channelId, Message = message }); } } } } } } }
ml-agents/com.unity.ml-agents/Runtime/SideChannels/SideChannelManager.cs/0
{ "file_path": "ml-agents/com.unity.ml-agents/Runtime/SideChannels/SideChannelManager.cs", "repo_id": "ml-agents", "token_count": 4867 }
1,962
using System; using System.Diagnostics; using UnityEngine; namespace Unity.MLAgents { internal static class Utilities { /// <summary> /// Calculates the cumulative sum of an integer array. The result array will be one element /// larger than the input array since it has a padded 0 at the beginning. /// If the input is [a, b, c], the result will be [0, a, a+b, a+b+c] /// </summary> /// <param name="input"> /// Input array whose elements will be cumulatively added /// </param> /// <returns> The cumulative sum of the input array.</returns> internal static int[] CumSum(int[] input) { var runningSum = 0; var result = new int[input.Length + 1]; for (var actionIndex = 0; actionIndex < input.Length; actionIndex++) { runningSum += input[actionIndex]; result[actionIndex + 1] = runningSum; } return result; } /// <summary> /// Safely destroy a texture. This has to be used differently in unit tests. /// </summary> /// <param name="texture"></param> internal static void DestroyTexture(Texture2D texture) { if (Application.isEditor) { // Edit Mode tests complain if we use Destroy() UnityEngine.Object.DestroyImmediate(texture); } else { UnityEngine.Object.Destroy(texture); } } [Conditional("DEBUG")] internal static void DebugCheckNanAndInfinity(float value, string valueCategory, string caller) { if (float.IsNaN(value)) { throw new ArgumentException($"NaN {valueCategory} passed to {caller}."); } if (float.IsInfinity(value)) { throw new ArgumentException($"Inifinity {valueCategory} passed to {caller}."); } } } }
ml-agents/com.unity.ml-agents/Runtime/Utilities.cs/0
{ "file_path": "ml-agents/com.unity.ml-agents/Runtime/Utilities.cs", "repo_id": "ml-agents", "token_count": 928 }
1,963
fileFormatVersion: 2 guid: 99d76ec04c944b75bc6b85abfff4ac4e timeCreated: 1613680505
ml-agents/com.unity.ml-agents/Tests/Editor/Actuators/ActionSpecTests.cs.meta/0
{ "file_path": "ml-agents/com.unity.ml-agents/Tests/Editor/Actuators/ActionSpecTests.cs.meta", "repo_id": "ml-agents", "token_count": 40 }
1,964
fileFormatVersion: 2 guid: be419f7ed5c24b24a6f2636d3b107535 timeCreated: 1537915674
ml-agents/com.unity.ml-agents/Tests/Editor/Inference/EditModeTestInternalBrainTensorApplier.cs.meta/0
{ "file_path": "ml-agents/com.unity.ml-agents/Tests/Editor/Inference/EditModeTestInternalBrainTensorApplier.cs.meta", "repo_id": "ml-agents", "token_count": 41 }
1,965
fileFormatVersion: 2 guid: 2edf24df24ac426085cb31a94d063683 timeCreated: 1603392289
ml-agents/com.unity.ml-agents/Tests/Editor/Integrations/Match3/Match3ActuatorTests.cs.meta/0
{ "file_path": "ml-agents/com.unity.ml-agents/Tests/Editor/Integrations/Match3/Match3ActuatorTests.cs.meta", "repo_id": "ml-agents", "token_count": 38 }
1,966
fileFormatVersion: 2 guid: f5aa894d83ebc411581c8475cd2f9ae0 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ml-agents/com.unity.ml-agents/Tests/Editor/PublicAPI.meta/0
{ "file_path": "ml-agents/com.unity.ml-agents/Tests/Editor/PublicAPI.meta", "repo_id": "ml-agents", "token_count": 70 }
1,967
fileFormatVersion: 2 guid: 71aa620295f74ca5875e8e4782f08768 timeCreated: 1610760906
ml-agents/com.unity.ml-agents/Tests/Editor/SideChannels/EngineConfigurationChannelTests.cs.meta/0
{ "file_path": "ml-agents/com.unity.ml-agents/Tests/Editor/SideChannels/EngineConfigurationChannelTests.cs.meta", "repo_id": "ml-agents", "token_count": 37 }
1,968
using NUnit.Framework; namespace Unity.MLAgents.Tests { public class UtilitiesTests { [Test] public void TestCumSum() { var output = Utilities.CumSum(new[] { 1, 2, 3, 10 }); CollectionAssert.AreEqual(output, new[] { 0, 1, 3, 6, 16 }); output = Utilities.CumSum(new int[0]); CollectionAssert.AreEqual(output, new[] { 0 }); output = Utilities.CumSum(new[] { 100 }); CollectionAssert.AreEqual(output, new[] { 0, 100 }); output = Utilities.CumSum(new[] { -1, 10 }); CollectionAssert.AreEqual(output, new[] { 0, -1, 9 }); } } }
ml-agents/com.unity.ml-agents/Tests/Editor/UtilitiesTests.cs/0
{ "file_path": "ml-agents/com.unity.ml-agents/Tests/Editor/UtilitiesTests.cs", "repo_id": "ml-agents", "token_count": 320 }
1,969
using NUnit.Framework; using Unity.MLAgents.Sensors; namespace Unity.MLAgents.Tests { public class Float2DSensor : ISensor { public int Width { get; } public int Height { get; } string m_Name; private ObservationSpec m_ObservationSpec; public float[,] floatData; public Float2DSensor(int width, int height, string name) { Width = width; Height = height; m_Name = name; m_ObservationSpec = ObservationSpec.Visual(1, height, width); floatData = new float[Height, Width]; } public Float2DSensor(float[,] floatData, string name) { this.floatData = floatData; Height = floatData.GetLength(0); Width = floatData.GetLength(1); m_Name = name; m_ObservationSpec = ObservationSpec.Visual(1, Height, Width); } public string GetName() { return m_Name; } public ObservationSpec GetObservationSpec() { return m_ObservationSpec; } public byte[] GetCompressedObservation() { return null; } public int Write(ObservationWriter writer) { using (TimerStack.Instance.Scoped("Float2DSensor.Write")) { for (var h = 0; h < Height; h++) { for (var w = 0; w < Width; w++) { writer[0, h, w] = floatData[h, w]; } } var numWritten = Height * Width; return numWritten; } } public void Update() { } public void Reset() { } public CompressionSpec GetCompressionSpec() { return CompressionSpec.Default(); } } public class FloatVisualSensorTests { [Test] public void TestFloat2DSensorWrite() { var sensor = new Float2DSensor(3, 4, "floatsensor"); for (var h = 0; h < 4; h++) { for (var w = 0; w < 3; w++) { sensor.floatData[h, w] = 3 * h + w; } } var output = new float[12]; var writer = new ObservationWriter(); writer.SetTarget(output, sensor.GetObservationSpec(), 0); sensor.Write(writer); for (var i = 0; i < 9; i++) { Assert.AreEqual(i, output[i]); } } [Test] public void TestFloat2DSensorExternalData() { var data = new float[4, 3]; var sensor = new Float2DSensor(data, "floatsensor"); Assert.AreEqual(sensor.Height, 4); Assert.AreEqual(sensor.Width, 3); } } }
ml-agents/com.unity.ml-agents/Tests/Runtime/Sensor/FloatVisualSensorTests.cs/0
{ "file_path": "ml-agents/com.unity.ml-agents/Tests/Runtime/Sensor/FloatVisualSensorTests.cs", "repo_id": "ml-agents", "token_count": 1541 }
1,970
using System.Collections.Generic; using System.Text.RegularExpressions; using NUnit.Framework; using UnityEngine; using UnityEngine.TestTools; using Unity.MLAgents.Sensors; namespace Unity.MLAgents.Tests { public class DummySensor : ISensor { string m_Name = "DummySensor"; ObservationSpec m_ObservationSpec; public DummySensor(int dim1) { m_ObservationSpec = ObservationSpec.Vector(dim1); } public DummySensor(int dim1, int dim2) { m_ObservationSpec = ObservationSpec.VariableLength(dim1, dim2); } public DummySensor(int dim1, int dim2, int dim3) { m_ObservationSpec = ObservationSpec.Visual(dim1, dim2, dim3); } public string GetName() { return m_Name; } public ObservationSpec GetObservationSpec() { return m_ObservationSpec; } public byte[] GetCompressedObservation() { return null; } public int Write(ObservationWriter writer) { return this.ObservationSize(); } public void Update() { } public void Reset() { } public CompressionSpec GetCompressionSpec() { return CompressionSpec.Default(); } } public class SensorShapeValidatorTests { [Test] public void TestShapesAgree() { var validator = new SensorShapeValidator(); var sensorList1 = new List<ISensor>() { new DummySensor(1), new DummySensor(2, 3), new DummySensor(4, 5, 6) }; validator.ValidateSensors(sensorList1); var sensorList2 = new List<ISensor>() { new DummySensor(1), new DummySensor(2, 3), new DummySensor(4, 5, 6) }; validator.ValidateSensors(sensorList2); } [Test] public void TestNumSensorMismatch() { var validator = new SensorShapeValidator(); var sensorList1 = new List<ISensor>() { new DummySensor(1), new DummySensor(2, 3), new DummySensor(4, 5, 6) }; validator.ValidateSensors(sensorList1); var sensorList2 = new List<ISensor>() { new DummySensor(1), new DummySensor(2, 3), }; LogAssert.Expect(LogType.Assert, "Number of Sensors must match. 3 != 2"); validator.ValidateSensors(sensorList2); // Add the sensors in the other order validator = new SensorShapeValidator(); validator.ValidateSensors(sensorList2); LogAssert.Expect(LogType.Assert, "Number of Sensors must match. 2 != 3"); validator.ValidateSensors(sensorList1); } [Test] public void TestDimensionMismatch() { var validator = new SensorShapeValidator(); var sensorList1 = new List<ISensor>() { new DummySensor(1), new DummySensor(2, 3), new DummySensor(4, 5, 6) }; validator.ValidateSensors(sensorList1); var sensorList2 = new List<ISensor>() { new DummySensor(1), new DummySensor(2, 3), new DummySensor(4, 5) }; LogAssert.Expect(LogType.Assert, new Regex("Sensor shapes must match.*")); validator.ValidateSensors(sensorList2); // Add the sensors in the other order validator = new SensorShapeValidator(); validator.ValidateSensors(sensorList2); LogAssert.Expect(LogType.Assert, new Regex("Sensor shapes must match.*")); validator.ValidateSensors(sensorList1); } [Test] public void TestSizeMismatch() { var validator = new SensorShapeValidator(); var sensorList1 = new List<ISensor>() { new DummySensor(1), new DummySensor(2, 3), new DummySensor(4, 5, 6) }; validator.ValidateSensors(sensorList1); var sensorList2 = new List<ISensor>() { new DummySensor(1), new DummySensor(2, 3), new DummySensor(4, 5, 7) }; LogAssert.Expect(LogType.Assert, new Regex("Sensor shapes must match.*")); validator.ValidateSensors(sensorList2); // Add the sensors in the other order validator = new SensorShapeValidator(); validator.ValidateSensors(sensorList2); LogAssert.Expect(LogType.Assert, new Regex("Sensor shapes must match.*")); validator.ValidateSensors(sensorList1); } [Test] public void TestEverythingMismatch() { var validator = new SensorShapeValidator(); var sensorList1 = new List<ISensor>() { new DummySensor(1), new DummySensor(2, 3), new DummySensor(4, 5, 6) }; validator.ValidateSensors(sensorList1); var sensorList2 = new List<ISensor>() { new DummySensor(1), new DummySensor(9) }; LogAssert.Expect(LogType.Assert, "Number of Sensors must match. 3 != 2"); LogAssert.Expect(LogType.Assert, new Regex("Sensor shapes must match.*")); validator.ValidateSensors(sensorList2); // Add the sensors in the other order validator = new SensorShapeValidator(); validator.ValidateSensors(sensorList2); LogAssert.Expect(LogType.Assert, "Number of Sensors must match. 2 != 3"); LogAssert.Expect(LogType.Assert, new Regex("Sensor shapes must match.*")); validator.ValidateSensors(sensorList1); } } }
ml-agents/com.unity.ml-agents/Tests/Runtime/Sensor/SensorShapeValidatorTests.cs/0
{ "file_path": "ml-agents/com.unity.ml-agents/Tests/Runtime/Sensor/SensorShapeValidatorTests.cs", "repo_id": "ml-agents", "token_count": 2480 }
1,971
fileFormatVersion: 2 guid: e4c1564ff83a4d51855e5b5b461f6a59 timeCreated: 1616137685
ml-agents/com.unity.ml-agents/Tests/Runtime/Utils.meta/0
{ "file_path": "ml-agents/com.unity.ml-agents/Tests/Runtime/Utils.meta", "repo_id": "ml-agents", "token_count": 42 }
1,972
behaviors: Pyramids: trainer_type: ppo time_horizon: 128 max_steps: 1.0e7 hyperparameters: batch_size: 128 beta: 0.01 buffer_size: 2048 epsilon: 0.2 lambd: 0.95 learning_rate: 0.0003 num_epoch: 3 network_settings: num_layers: 2 normalize: false hidden_units: 512 reward_signals: extrinsic: strength: 1.0 gamma: 0.99 curiosity: strength: 0.02 gamma: 0.99 network_settings: hidden_units: 256 gail: strength: 0.01 gamma: 0.99 demo_path: Project/Assets/ML-Agents/Examples/Pyramids/Demos/ExpertPyramid.demo behavioral_cloning: demo_path: Project/Assets/ML-Agents/Examples/Pyramids/Demos/ExpertPyramid.demo strength: 0.5 steps: 150000
ml-agents/config/imitation/Pyramids.yaml/0
{ "file_path": "ml-agents/config/imitation/Pyramids.yaml", "repo_id": "ml-agents", "token_count": 419 }
1,973
behaviors: Pyramids: trainer_type: ppo hyperparameters: batch_size: 128 buffer_size: 2048 learning_rate: 0.0003 beta: 0.01 epsilon: 0.2 lambd: 0.95 num_epoch: 3 learning_rate_schedule: linear network_settings: normalize: false hidden_units: 512 num_layers: 2 vis_encode_type: simple reward_signals: extrinsic: gamma: 0.99 strength: 1.0 rnd: gamma: 0.99 strength: 0.01 network_settings: hidden_units: 64 num_layers: 3 learning_rate: 0.0001 keep_checkpoints: 5 max_steps: 3000000 time_horizon: 128 summary_freq: 30000
ml-agents/config/ppo/PyramidsRND.yaml/0
{ "file_path": "ml-agents/config/ppo/PyramidsRND.yaml", "repo_id": "ml-agents", "token_count": 360 }
1,974
behaviors: Pyramids: trainer_type: sac hyperparameters: learning_rate: 0.0003 learning_rate_schedule: constant batch_size: 128 buffer_size: 2000000 buffer_init_steps: 1000 tau: 0.01 steps_per_update: 10.0 save_replay_buffer: false init_entcoef: 0.01 reward_signal_steps_per_update: 10.0 network_settings: normalize: false hidden_units: 512 num_layers: 3 vis_encode_type: simple reward_signals: extrinsic: gamma: 0.995 strength: 2.0 gail: gamma: 0.99 strength: 0.01 learning_rate: 0.0003 use_actions: true use_vail: false demo_path: Project/Assets/ML-Agents/Examples/Pyramids/Demos/ExpertPyramid.demo keep_checkpoints: 5 max_steps: 3000000 time_horizon: 128 summary_freq: 30000
ml-agents/config/sac/Pyramids.yaml/0
{ "file_path": "ml-agents/config/sac/Pyramids.yaml", "repo_id": "ml-agents", "token_count": 423 }
1,975
# The Hugging Face Integration The [Hugging Face Hub 🤗](https://huggingface.co/models?pipeline_tag=reinforcement-learning) is a central place **where anyone can share and download models**. It allows you to: - **Host** your trained models. - **Download** trained models from the community. - Visualize your agents **playing directly on your browser**. You can see the list of ml-agents models [here](https://huggingface.co/models?library=ml-agents). We wrote a **complete tutorial to learn to train your first agent using ML-Agents and publish it to the Hub**: - A short tutorial where you [teach **Huggy the Dog to fetch the stick** and then play with him directly in your browser](https://huggingface.co/learn/deep-rl-course/unitbonus1/introduction) - A [more in-depth tutorial](https://huggingface.co/learn/deep-rl-course/unit5/introduction) ## Download a model from the Hub You can simply download a model from the Hub using `mlagents-load-from-hf`. You need to define two parameters: - `--repo-id`: the name of the Hugging Face repo you want to download. - `--local-dir`: the path to download the model. For instance, I want to load the model with model-id "ThomasSimonini/MLAgents-Pyramids" and put it in the downloads directory: ```sh mlagents-load-from-hf --repo-id="ThomasSimonini/MLAgents-Pyramids" --local-dir="./downloads" ``` ## Upload a model to the Hub You can simply upload a model to the Hub using `mlagents-push-to-hf` You need to define four parameters: - `--run-id`: the name of the training run id. - `--local-dir`: where the model was saved - `--repo-id`: the name of the Hugging Face repo you want to create or update. It’s always <your huggingface username>/<the repo name> If the repo does not exist it will be created automatically - `--commit-message`: since HF repos are git repositories you need to give a commit message. For instance, I want to upload my model trained with run-id "SnowballTarget1" to the repo-id: ThomasSimonini/ppo-SnowballTarget: ```sh mlagents-push-to-hf --run-id="SnowballTarget1" --local-dir="./results/SnowballTarget1" --repo-id="ThomasSimonini/ppo-SnowballTarget" --commit-message="First Push" ``` ## Visualize an agent playing You can watch your agent playing directly in your browser (if the environment is from the [ML-Agents official environments](Learning-Environment-Examples.md)) - Step 1: Go to https://huggingface.co/unity and select the environment demo. - Step 2: Find your model_id in the list. - Step 3: Select your .nn /.onnx file. - Step 4: Click on Watch the agent play
ml-agents/docs/Hugging-Face-Integration.md/0
{ "file_path": "ml-agents/docs/Hugging-Face-Integration.md", "repo_id": "ml-agents", "token_count": 770 }
1,976
# Upgrading # Migrating <!--- TODO: update ml-agents-env package version before release ---> ## Migrating to the ml-agents-envs 0.30.0 package - Python 3.10.12 is now the minimum version of python supported due to [python3.6 EOL](https://endoflife.date/python). Please update your python installation to 3.10.12 or higher. - The `gym-unity` package has been refactored into the `ml-agents-envs` package. Please update your imports accordingly. - Example: - Before ```python from gym_unity.unity_gym_env import UnityToGymWrapper ``` - After: ```python from mlagents_envs.envs.unity_gym_env import UnityToGymWrapper ``` ## Migrating the package to version 3.x - The official version of Unity ML-Agents supports is now 2023.2. If you run into issues, please consider deleting your project's Library folder and reopening your project. ## Migrating the package to version 2.x - The official version of Unity ML-Agents supports is now 2022.3 LTS. If you run into issues, please consider deleting your project's Library folder and reopening your project. - If you used any of the APIs that were deprecated before version 2.0, you need to use their replacement. These deprecated APIs have been removed. See the migration steps bellow for specific API replacements. ### Deprecated methods removed | **Deprecated API** | **Suggested Replacement** | |:-------:|:------:| | `IActuator ActuatorComponent.CreateActuator()` | `IActuator[] ActuatorComponent.CreateActuators()` | | `IActionReceiver.PackActions(in float[] destination)` | none | | `Agent.CollectDiscreteActionMasks(DiscreteActionMasker actionMasker)` | `Agent.WriteDiscreteActionMask(IDiscreteActionMask actionMask)` | | `Agent.Heuristic(float[] actionsOut)` | `Agent.Heuristic(in ActionBuffers actionsOut)` | | `Agent.OnActionReceived(float[] vectorAction)` | `Agent.OnActionReceived(ActionBuffers actions)` | | `Agent.GetAction()` | `Agent.GetStoredActionBuffers()` | | `BrainParameters.SpaceType`, `VectorActionSize`, `VectorActionSpaceType`, and `NumActions` | `BrainParameters.ActionSpec` | | `ObservationWriter.AddRange(IEnumerable<float> data, int writeOffset = 0)` | `ObservationWriter. AddList(IList<float> data, int writeOffset = 0` | | `SensorComponent.IsVisual()` and `IsVector()` | none | | `VectorSensor.AddObservation(IEnumerable<float> observation)` | `VectorSensor.AddObservation(IList<float> observation)` | | `SideChannelsManager` | `SideChannelManager` | ### IDiscreteActionMask changes - The interface for disabling specific discrete actions has changed. `IDiscreteActionMask.WriteMask()` was removed, and replaced with `SetActionEnabled()`. Instead of returning an IEnumerable with indices to disable, you can now call `SetActionEnabled` for each index to disable (or enable). As an example, if you overrode `Agent.WriteDiscreteActionMask()` with something that looked like: ```csharp public override void WriteDiscreteActionMask(IDiscreteActionMask actionMask) { var branch = 2; var actionsToDisable = new[] {1, 3}; actionMask.WriteMask(branch, actionsToDisable); } ``` the equivalent code would now be ```csharp public override void WriteDiscreteActionMask(IDiscreteActionMask actionMask) { var branch = 2; actionMask.SetActionEnabled(branch, 1, false); actionMask.SetActionEnabled(branch, 3, false); } ``` ### IActuator changes - The `IActuator` interface now implements `IHeuristicProvider`. Please add the corresponding `Heuristic(in ActionBuffers)` method to your custom Actuator classes. ### ISensor and SensorComponent changes - The `ISensor.GetObservationShape()` method and `ITypedSensor` and `IDimensionPropertiesSensor` interfaces were removed, and `GetObservationSpec()` was added. You can use `ObservationSpec.Vector()` or `ObservationSpec.Visual()` to generate `ObservationSpec`s that are equivalent to the previous shape. For example, if your old ISensor looked like: ```csharp public override int[] GetObservationShape() { return new[] { m_Height, m_Width, m_NumChannels }; } ``` the equivalent code would now be ```csharp public override ObservationSpec GetObservationSpec() { return ObservationSpec.Visual(m_Height, m_Width, m_NumChannels); } ``` - The `ISensor.GetCompressionType()` method and `ISparseChannelSensor` interface was removed, and `GetCompressionSpec()` was added. You can use `CompressionSpec.Default()` or `CompressionSpec.Compressed()` to generate `CompressionSpec`s that are equivalent to the previous values. For example, if your old ISensor looked like: ```csharp public virtual SensorCompressionType GetCompressionType() { return SensorCompressionType.None; } ``` the equivalent code would now be ```csharp public CompressionSpec GetCompressionSpec() { return CompressionSpec.Default(); } ``` - The abstract method `SensorComponent.GetObservationShape()` was removed. - The abstract method `SensorComponent.CreateSensor()` was replaced with `CreateSensors()`, which returns an `ISensor[]`. ### Match3 integration changes The Match-3 integration utilities were moved from `com.unity.ml-agents.extensions` to `com.unity.ml-agents`. The `AbstractBoard` interface was changed: * `AbstractBoard` no longer contains `Rows`, `Columns`, `NumCellTypes`, and `NumSpecialTypes` fields. * `public abstract BoardSize GetMaxBoardSize()` was added as an abstract method. `BoardSize` is a new struct that contains `Rows`, `Columns`, `NumCellTypes`, and `NumSpecialTypes` fields, with the same meanings as the old `AbstractBoard` fields. * `public virtual BoardSize GetCurrentBoardSize()` is an optional method; by default it returns `GetMaxBoardSize()`. If you wish to use a single behavior to work with multiple board sizes, override `GetCurrentBoardSize()` to return the current `BoardSize`. The values returned by `GetCurrentBoardSize()` must be less than or equal to the corresponding values from `GetMaxBoardSize()`. ### GridSensor changes The sensor configuration has changed: * The sensor implementation has been refactored and existing GridSensor created from extension package will not work in newer version. Some errors might show up when loading the old sensor in the scene. You'll need to remove the old sensor and create a new GridSensor. * These parameters names have changed but still refer to the same concept in the sensor: `GridNumSide` -> `GridSize`, `RotateToAgent` -> `RotateWithAgent`, `ObserveMask` -> `ColliderMask`, `DetectableObjects` -> `DetectableTags` * `DepthType` (`ChanelBase`/`ChannelHot`) option and `ChannelDepth` are removed. Now the default is one-hot encoding for detected tag. If you were using original GridSensor without overriding any method, switching to new GridSensor will produce similar effect for training although the actual observations will be slightly different. For creating your GridSensor implementation with custom data: * To create custom GridSensor, derive from `GridSensorBase` instead of `GridSensor`. Besides overriding `GetObjectData()`, you will also need to consider override `GetCellObservationSize()`, `IsDataNormalized()` and `GetProcessCollidersMethod()` according to the data you collect. Also you'll need to override `GridSensorComponent.GetGridSensors()` and return your custom GridSensor. * The input argument `tagIndex` in `GetObjectData()` has changed from 1-indexed to 0-indexed and the data type changed from `float` to `int`. The index of first detectable tag will be 0 instead of 1. `normalizedDistance` was removed from input. * The observation data should be written to the input `dataBuffer` instead of creating and returning a new array. * Removed the constraint of all data required to be normalized. You should specify it in `IsDataNormalized()`. Sensors with non-normalized data cannot use PNG compression type. * The sensor will not further encode the data received from `GetObjectData()` anymore. The values received from `GetObjectData()` will be the observation sent to the trainer. ### LSTM models from previous releases no longer supported The way that Sentis processes LSTM (recurrent neural networks) has changed. As a result, models trained with previous versions of ML-Agents will not be usable at inference if they were trained with a `memory` setting in the `.yaml` config file. If you want to use a model that has a recurrent neural network in this release of ML-Agents, you need to train the model using the python trainer from this release. ## Migrating to Release 13 ### Implementing IHeuristic in your IActuator implementations - If you have any custom actuators, you can now implement the `IHeuristicProvider` interface to have your actuator handle the generation of actions when an Agent is running in heuristic mode. - `VectorSensor.AddObservation(IEnumerable<float>)` is deprecated. Use `VectorSensor.AddObservation(IList<float>)` instead. - `ObservationWriter.AddRange()` is deprecated. Use `ObservationWriter.AddList()` instead. - `ActuatorComponent.CreateActuator()` is deprecated. Please use override `ActuatorComponent.CreateActuators` instead. Since `ActuatorComponent.CreateActuator()` is abstract, you will still need to override it in your class until it is removed. It is only ever called if you don't override `ActuatorComponent.CreateActuators`. You can suppress the warnings by surrounding the method with the following pragma: ```c# #pragma warning disable 672 public IActuator CreateActuator() { ... } #pragma warning restore 672 ``` # Migrating ## Migrating to Release 11 ### Agent virtual method deprecation - `Agent.CollectDiscreteActionMasks()` was deprecated and should be replaced with `Agent.WriteDiscreteActionMask()` - `Agent.Heuristic(float[])` was deprecated and should be replaced with `Agent.Heuristic(ActionBuffers)`. - `Agent.OnActionReceived(float[])` was deprecated and should be replaced with `Agent.OnActionReceived(ActionBuffers)`. - `Agent.GetAction()` was deprecated and should be replaced with `Agent.GetStoredActionBuffers()`. The default implementation of these will continue to call the deprecated versions where appropriate. However, the deprecated versions may not be compatible with continuous and discrete actions on the same Agent. ### BrainParameters field and method deprecation - `BrainParameters.VectorActionSize` was deprecated; you can now set `BrainParameters.ActionSpec.NumContinuousActions` or `BrainParameters.ActionSpec.BranchSizes` instead. - `BrainParameters.VectorActionSpaceType` was deprecated, since both continuous and discrete actions can now be used. - `BrainParameters.NumActions()` was deprecated. Use `BrainParameters.ActionSpec.NumContinuousActions` and `BrainParameters.ActionSpec.NumDiscreteActions` instead. ## Migrating from Release 7 to latest ### Important changes - Some trainer files were moved. If you were using the `TrainerFactory` class, it was moved to the `trainers/trainer` folder. - The `components` folder containing `bc` and `reward_signals` code was moved to the `trainers/tf` folder ### Steps to Migrate - Replace calls to `from mlagents.trainers.trainer_util import TrainerFactory` to `from mlagents.trainers.trainer import TrainerFactory` - Replace calls to `from mlagents.trainers.trainer_util import handle_existing_directories` to `from mlagents.trainers.directory_utils import validate_existing_directories` - Replace `mlagents.trainers.components` with `mlagents.trainers.tf.components` in your import statements. ## Migrating from Release 3 to Release 7 ### Important changes - The Parameter Randomization feature has been merged with the Curriculum feature. It is now possible to specify a sampler in the lesson of a Curriculum. Curriculum has been refactored and is now specified at the level of the parameter, not the behavior. More information [here](https://github.com/Unity-Technologies/ml-agents/blob/release_21_docs/docs/Training-ML-Agents.md).(#4160) ### Steps to Migrate - The configuration format for curriculum and parameter randomization has changed. To upgrade your configuration files, an upgrade script has been provided. Run `python -m mlagents.trainers.upgrade_config -h` to see the script usage. Note that you will have had to upgrade to/install the current version of ML-Agents before running the script. To update manually: - If your config file used a `parameter_randomization` section, rename that section to `environment_parameters` - If your config file used a `curriculum` section, you will need to rewrite your curriculum with this [format](Training-ML-Agents.md#curriculum). ## Migrating from Release 1 to Release 3 ### Important changes - Training artifacts (trained models, summaries) are now found under `results/` instead of `summaries/` and `models/`. - Trainer configuration, curriculum configuration, and parameter randomization configuration have all been moved to a single YAML file. (#3791) - Trainer configuration format has changed, and using a "default" behavior name has been deprecated. (#3936) - `max_step` in the `TerminalStep` and `TerminalSteps` objects was renamed `interrupted`. - On the UnityEnvironment API, `get_behavior_names()` and `get_behavior_specs()` methods were combined into the property `behavior_specs` that contains a mapping from behavior names to behavior spec. - `use_visual` and `allow_multiple_visual_obs` in the `UnityToGymWrapper` constructor were replaced by `allow_multiple_obs` which allows one or more visual observations and vector observations to be used simultaneously. - `--save-freq` has been removed from the CLI and is now configurable in the trainer configuration file. - `--lesson` has been removed from the CLI. Lessons will resume when using `--resume`. To start at a different lesson, modify your Curriculum configuration. ### Steps to Migrate - To upgrade your configuration files, an upgrade script has been provided. Run `python -m mlagents.trainers.upgrade_config -h` to see the script usage. Note that you will have had to upgrade to/install the current version of ML-Agents before running the script. To do it manually, copy your `<BehaviorName>` sections from `trainer_config.yaml` into a separate trainer configuration file, under a `behaviors` section. The `default` section is no longer needed. This new file should be specific to your environment, and not contain configurations for multiple environments (unless they have the same Behavior Names). - You will need to reformat your trainer settings as per the [example](Training-ML-Agents.md). - If your training uses [curriculum](Training-ML-Agents.md#curriculum-learning), move those configurations under a `curriculum` section. - If your training uses [parameter randomization](Training-ML-Agents.md#environment-parameter-randomization), move the contents of the sampler config to `parameter_randomization` in the main trainer configuration. - If you are using `UnityEnvironment` directly, replace `max_step` with `interrupted` in the `TerminalStep` and `TerminalSteps` objects. - Replace usage of `get_behavior_names()` and `get_behavior_specs()` in UnityEnvironment with `behavior_specs`. - If you use the `UnityToGymWrapper`, remove `use_visual` and `allow_multiple_visual_obs` from the constructor and add `allow_multiple_obs = True` if the environment contains either both visual and vector observations or multiple visual observations. - If you were setting `--save-freq` in the CLI, add a `checkpoint_interval` value in your trainer configuration, and set it equal to `save-freq * n_agents_in_scene`. ## Migrating from 0.15 to Release 1 ### Important changes - The `MLAgents` C# namespace was renamed to `Unity.MLAgents`, and other nested namespaces were similarly renamed (#3843). - The `--load` and `--train` command-line flags have been deprecated and replaced with `--resume` and `--inference`. - Running with the same `--run-id` twice will now throw an error. - The `play_against_current_self_ratio` self-play trainer hyperparameter has been renamed to `play_against_latest_model_ratio` - Removed the multi-agent gym option from the gym wrapper. For multi-agent scenarios, use the [Low Level Python API](Python-LLAPI.md). - The low level Python API has changed. You can look at the document [Low Level Python API documentation](Python-LLAPI.md) for more information. If you use `mlagents-learn` for training, this should be a transparent change. - The obsolete `Agent` methods `GiveModel`, `Done`, `InitializeAgent`, `AgentAction` and `AgentReset` have been removed. - The signature of `Agent.Heuristic()` was changed to take a `float[]` as a parameter, instead of returning the array. This was done to prevent a common source of error where users would return arrays of the wrong size. - The SideChannel API has changed (#3833, #3660) : - Introduced the `SideChannelManager` to register, unregister and access side channels. - `EnvironmentParameters` replaces the default `FloatProperties`. You can access the `EnvironmentParameters` with `Academy.Instance.EnvironmentParameters` on C#. If you were previously creating a `UnityEnvironment` in python and passing it a `FloatPropertiesChannel`, create an `EnvironmentParametersChannel` instead. - `SideChannel.OnMessageReceived` is now a protected method (was public) - SideChannel IncomingMessages methods now take an optional default argument, which is used when trying to read more data than the message contains. - Added a feature to allow sending stats from C# environments to TensorBoard (and other python StatsWriters). To do this from your code, use `Academy.Instance.StatsRecorder.Add(key, value)`(#3660) - `num_updates` and `train_interval` for SAC have been replaced with `steps_per_update`. - The `UnityEnv` class from the `gym-unity` package was renamed `UnityToGymWrapper` and no longer creates the `UnityEnvironment`. Instead, the `UnityEnvironment` must be passed as input to the constructor of `UnityToGymWrapper` - Public fields and properties on several classes were renamed to follow Unity's C# style conventions. All public fields and properties now use "PascalCase" instead of "camelCase"; for example, `Agent.maxStep` was renamed to `Agent.MaxStep`. For a full list of changes, see the pull request. (#3828) - `WriteAdapter` was renamed to `ObservationWriter`. (#3834) ### Steps to Migrate - In C# code, replace `using MLAgents` with `using Unity.MLAgents`. Replace other nested namespaces such as `using MLAgents.Sensors` with `using Unity.MLAgents.Sensors` - Replace the `--load` flag with `--resume` when calling `mlagents-learn`, and don't use the `--train` flag as training will happen by default. To run without training, use `--inference`. - To force-overwrite files from a pre-existing run, add the `--force` command-line flag. - The Jupyter notebooks have been removed from the repository. - If your Agent class overrides `Heuristic()`, change the signature to `public override void Heuristic(float[] actionsOut)` and assign values to `actionsOut` instead of returning an array. - If you used `SideChannels` you must: - Replace `Academy.FloatProperties` with `Academy.Instance.EnvironmentParameters`. - `Academy.RegisterSideChannel` and `Academy.UnregisterSideChannel` were removed. Use `SideChannelManager.RegisterSideChannel` and `SideChannelManager.UnregisterSideChannel` instead. - Set `steps_per_update` to be around equal to the number of agents in your environment, times `num_updates` and divided by `train_interval`. - Replace `UnityEnv` with `UnityToGymWrapper` in your code. The constructor no longer takes a file name as input but a fully constructed `UnityEnvironment` instead. - Update uses of "camelCase" fields and properties to "PascalCase". ## Migrating from 0.14 to 0.15 ### Important changes - The `Agent.CollectObservations()` virtual method now takes as input a `VectorSensor` sensor as argument. The `Agent.AddVectorObs()` methods were removed. - The `SetMask` was renamed to `SetMask` method must now be called on the `DiscreteActionMasker` argument of the `CollectDiscreteActionMasks` virtual method. - We consolidated our API for `DiscreteActionMasker`. `SetMask` takes two arguments : the branch index and the list of masked actions for that branch. - The `Monitor` class has been moved to the Examples Project. (It was prone to errors during testing) - The `MLAgents.Sensors` namespace has been introduced. All sensors classes are part of the `MLAgents.Sensors` namespace. - The `MLAgents.SideChannels` namespace has been introduced. All side channel classes are part of the `MLAgents.SideChannels` namespace. - The interface for `RayPerceptionSensor.PerceiveStatic()` was changed to take an input class and write to an output class, and the method was renamed to `Perceive()`. - The `SetMask` method must now be called on the `DiscreteActionMasker` argument of the `CollectDiscreteActionMasks` method. - The method `GetStepCount()` on the Agent class has been replaced with the property getter `StepCount` - The `--multi-gpu` option has been removed temporarily. - `AgentInfo.actionMasks` has been renamed to `AgentInfo.discreteActionMasks`. - `BrainParameters` and `SpaceType` have been removed from the public API - `BehaviorParameters` have been removed from the public API. - `DecisionRequester` has been made internal (you can still use the DecisionRequesterComponent from the inspector). `RepeatAction` was renamed `TakeActionsBetweenDecisions` for clarity. - The following methods in the `Agent` class have been renamed. The original method names will be removed in a later release: - `InitializeAgent()` was renamed to `Initialize()` - `AgentAction()` was renamed to `OnActionReceived()` - `AgentReset()` was renamed to `OnEpisodeBegin()` - `Done()` was renamed to `EndEpisode()` - `GiveModel()` was renamed to `SetModel()` - The `IFloatProperties` interface has been removed. - The interface for SideChannels was changed: - In C#, `OnMessageReceived` now takes a `IncomingMessage` argument, and `QueueMessageToSend` takes an `OutgoingMessage` argument. - In python, `on_message_received` now takes a `IncomingMessage` argument, and `queue_message_to_send` takes an `OutgoingMessage` argument. - Automatic stepping for Academy is now controlled from the AutomaticSteppingEnabled property. ### Steps to Migrate - Add the `using MLAgents.Sensors;` in addition to `using MLAgents;` on top of your Agent's script. - Replace your Agent's implementation of `CollectObservations()` with `CollectObservations(VectorSensor sensor)`. In addition, replace all calls to `AddVectorObs()` with `sensor.AddObservation()` or `sensor.AddOneHotObservation()` on the `VectorSensor` passed as argument. - Replace your calls to `SetActionMask` on your Agent to `DiscreteActionMasker.SetActionMask` in `CollectDiscreteActionMasks`. - If you call `RayPerceptionSensor.PerceiveStatic()` manually, add your inputs to a `RayPerceptionInput`. To get the previous float array output, iterate through `RayPerceptionOutput.rayOutputs` and call `RayPerceptionOutput.RayOutput.ToFloatArray()`. - Replace all calls to `Agent.GetStepCount()` with `Agent.StepCount` - We strongly recommend replacing the following methods with their new equivalent as they will be removed in a later release: - `InitializeAgent()` to `Initialize()` - `AgentAction()` to `OnActionReceived()` - `AgentReset()` to `OnEpisodeBegin()` - `Done()` to `EndEpisode()` - `GiveModel()` to `SetModel()` - Replace `IFloatProperties` variables with `FloatPropertiesChannel` variables. - If you implemented custom `SideChannels`, update the signatures of your methods, and add your data to the `OutgoingMessage` or read it from the `IncomingMessage`. - Replace calls to Academy.EnableAutomaticStepping()/DisableAutomaticStepping() with Academy.AutomaticSteppingEnabled = true/false. ## Migrating from 0.13 to 0.14 ### Important changes - The `UnitySDK` folder has been split into a Unity Package (`com.unity.ml-agents`) and an examples project (`Project`). Please follow the [Installation Guide](Installation.md) to get up and running with this new repo structure. - Several changes were made to how agents are reset and marked as done: - Calling `Done()` on the Agent will now reset it immediately and call the `AgentReset` virtual method. (This is to simplify the previous logic in which the Agent had to wait for the next `EnvironmentStep` to reset) - The "Reset on Done" setting in AgentParameters was removed; this is now effectively always true. `AgentOnDone` virtual method on the Agent has been removed. - The `Decision Period` and `On Demand decision` checkbox have been removed from the Agent. On demand decision is now the default (calling `RequestDecision` on the Agent manually.) - The Academy class was changed to a singleton, and its virtual methods were removed. - Trainer steps are now counted per-Agent, not per-environment as in previous versions. For instance, if you have 10 Agents in the scene, 20 environment steps now corresponds to 200 steps as printed in the terminal and in Tensorboard. - Curriculum config files are now YAML formatted and all curricula for a training run are combined into a single file. - The `--num-runs` command-line option has been removed from `mlagents-learn`. - Several fields on the Agent were removed or made private in order to simplify the interface. - The `agentParameters` field of the Agent has been removed. (Contained only `maxStep` information) - `maxStep` is now a public field on the Agent. (Was moved from `agentParameters`) - The `Info` field of the Agent has been made private. (Was only used internally and not meant to be modified outside of the Agent) - The `GetReward()` method on the Agent has been removed. (It was being confused with `GetCumulativeReward()`) - The `AgentAction` struct no longer contains a `value` field. (Value estimates were not set during inference) - The `GetValueEstimate()` method on the Agent has been removed. - The `UpdateValueAction()` method on the Agent has been removed. - The deprecated `RayPerception3D` and `RayPerception2D` classes were removed, and the `legacyHitFractionBehavior` argument was removed from `RayPerceptionSensor.PerceiveStatic()`. - RayPerceptionSensor was inconsistent in how it handle scale on the Agent's transform. It now scales the ray length and sphere size for casting as the transform's scale changes. ### Steps to Migrate - Follow the instructions on how to install the `com.unity.ml-agents` package into your project in the [Installation Guide](Installation.md). - If your Agent implemented `AgentOnDone` and did not have the checkbox `Reset On Done` checked in the inspector, you must call the code that was in `AgentOnDone` manually. - If you give your Agent a reward or penalty at the end of an episode (e.g. for reaching a goal or falling off of a platform), make sure you call `AddReward()` or `SetReward()` _before_ calling `Done()`. Previously, the order didn't matter. - If you were not using `On Demand Decision` for your Agent, you **must** add a `DecisionRequester` component to your Agent GameObject and set its `Decision Period` field to the old `Decision Period` of the Agent. - If you have a class that inherits from Academy: - If the class didn't override any of the virtual methods and didn't store any additional data, you can just remove the old script from the scene. - If the class had additional data, create a new MonoBehaviour and store the data in the new MonoBehaviour instead. - If the class overrode the virtual methods, create a new MonoBehaviour and move the logic to it: - Move the InitializeAcademy code to MonoBehaviour.Awake - Move the AcademyStep code to MonoBehaviour.FixedUpdate - Move the OnDestroy code to MonoBehaviour.OnDestroy. - Move the AcademyReset code to a new method and add it to the Academy.OnEnvironmentReset action. - Multiply `max_steps` and `summary_freq` in your `trainer_config.yaml` by the number of Agents in the scene. - Combine curriculum configs into a single file. See [the WallJump curricula](https://github.com/Unity-Technologies/ml-agents/blob/0.14.1/config/curricula/wall_jump.yaml) for an example of the new curriculum config format. A tool like https://www.json2yaml.com may be useful to help with the conversion. - If you have a model trained which uses RayPerceptionSensor and has non-1.0 scale in the Agent's transform, it must be retrained. ## Migrating from ML-Agents Toolkit v0.12.0 to v0.13.0 ### Important changes - The low level Python API has changed. You can look at the document [Low Level Python API documentation](Python-LLAPI.md) for more information. This should only affect you if you're writing a custom trainer; if you use `mlagents-learn` for training, this should be a transparent change. - `reset()` on the Low-Level Python API no longer takes a `train_mode` argument. To modify the performance/speed of the engine, you must use an `EngineConfigurationChannel` - `reset()` on the Low-Level Python API no longer takes a `config` argument. `UnityEnvironment` no longer has a `reset_parameters` field. To modify float properties in the environment, you must use a `FloatPropertiesChannel`. For more information, refer to the [Low Level Python API documentation](Python-LLAPI.md) - `CustomResetParameters` are now removed. - The Academy no longer has a `Training Configuration` nor `Inference Configuration` field in the inspector. To modify the configuration from the Low-Level Python API, use an `EngineConfigurationChannel`. To modify it during training, use the new command line arguments `--width`, `--height`, `--quality-level`, `--time-scale` and `--target-frame-rate` in `mlagents-learn`. - The Academy no longer has a `Default Reset Parameters` field in the inspector. The Academy class no longer has a `ResetParameters`. To access shared float properties with Python, use the new `FloatProperties` field on the Academy. - Offline Behavioral Cloning has been removed. To learn from demonstrations, use the GAIL and Behavioral Cloning features with either PPO or SAC. - `mlagents.envs` was renamed to `mlagents_envs`. The previous repo layout depended on [PEP420](https://www.python.org/dev/peps/pep-0420/), which caused problems with some of our tooling such as mypy and pylint. - The official version of Unity ML-Agents supports is now 2022.3 LTS. If you run into issues, please consider deleting your library folder and reopening your projects. You will need to install the Sentis package into your project in order to ML-Agents to compile correctly. ### Steps to Migrate - If you had a custom `Training Configuration` in the Academy inspector, you will need to pass your custom configuration at every training run using the new command line arguments `--width`, `--height`, `--quality-level`, `--time-scale` and `--target-frame-rate`. - If you were using `--slow` in `mlagents-learn`, you will need to pass your old `Inference Configuration` of the Academy inspector with the new command line arguments `--width`, `--height`, `--quality-level`, `--time-scale` and `--target-frame-rate` instead. - Any imports from `mlagents.envs` should be replaced with `mlagents_envs`. ## Migrating from ML-Agents Toolkit v0.11.0 to v0.12.0 ### Important Changes - Text actions and observations, and custom action and observation protos have been removed. - RayPerception3D and RayPerception2D are marked deprecated, and will be removed in a future release. They can be replaced by RayPerceptionSensorComponent3D and RayPerceptionSensorComponent2D. - The `Use Heuristic` checkbox in Behavior Parameters has been replaced with a `Behavior Type` dropdown menu. This has the following options: - `Default` corresponds to the previous unchecked behavior, meaning that Agents will train if they connect to a python trainer, otherwise they will perform inference. - `Heuristic Only` means the Agent will always use the `Heuristic()` method. This corresponds to having "Use Heuristic" selected in 0.11.0. - `Inference Only` means the Agent will always perform inference. - ML-Agents was upgraded to use Sentis 1.2.0-exp.2 and is installed via the package manager. ### Steps to Migrate - We [fixed a bug](https://github.com/Unity-Technologies/ml-agents/pull/2823) in `RayPerception3d.Perceive()` that was causing the `endOffset` to be used incorrectly. However this may produce different behavior from previous versions if you use a non-zero `startOffset`. To reproduce the old behavior, you should increase the value of `endOffset` by `startOffset`. You can verify your raycasts are performing as expected in scene view using the debug rays. - If you use RayPerception3D, replace it with RayPerceptionSensorComponent3D (and similarly for 2D). The settings, such as ray angles and detectable tags, are configured on the component now. RayPerception3D would contribute `(# of rays) * (# of tags + 2)` to the State Size in Behavior Parameters, but this is no longer necessary, so you should reduce the State Size by this amount. Making this change will require retraining your model, since the observations that RayPerceptionSensorComponent3D produces are different from the old behavior. - If you see messages such as `The type or namespace 'Sentis' could not be found` or `The type or namespace 'Google' could not be found`, you will need to [install the Sentis preview package](Installation.md#package-installation). ## Migrating from ML-Agents Toolkit v0.10 to v0.11.0 ### Important Changes - The definition of the gRPC service has changed. - The online BC training feature has been removed. - The BroadcastHub has been deprecated. If there is a training Python process, all LearningBrains in the scene will automatically be trained. If there is no Python process, inference will be used. - The Brain ScriptableObjects have been deprecated. The Brain Parameters are now on the Agent and are referred to as Behavior Parameters. Make sure the Behavior Parameters is attached to the Agent GameObject. - To use a heuristic behavior, implement the `Heuristic()` method in the Agent class and check the `use heuristic` checkbox in the Behavior Parameters. - Several changes were made to the setup for visual observations (i.e. using Cameras or RenderTextures): - Camera resolutions are no longer stored in the Brain Parameters. - AgentParameters no longer stores lists of Cameras and RenderTextures - To add visual observations to an Agent, you must now attach a CameraSensorComponent or RenderTextureComponent to the agent. The corresponding Camera or RenderTexture can be added to these in the editor, and the resolution and color/grayscale is configured on the component itself. #### Steps to Migrate - In order to be able to train, make sure both your ML-Agents Python package and UnitySDK code come from the v0.11 release. Training will not work, for example, if you update the ML-Agents Python package, and only update the API Version in UnitySDK. - If your Agents used visual observations, you must add a CameraSensorComponent corresponding to each old Camera in the Agent's camera list (and similarly for RenderTextures). - Since Brain ScriptableObjects have been removed, you will need to delete all the Brain ScriptableObjects from your `Assets` folder. Then, add a `Behavior Parameters` component to each `Agent` GameObject. You will then need to complete the fields on the new `Behavior Parameters` component with the BrainParameters of the old Brain. ## Migrating from ML-Agents Toolkit v0.9 to v0.10 ### Important Changes - We have updated the C# code in our repository to be in line with Unity Coding Conventions. This has changed the name of some public facing classes and enums. - The example environments have been updated. If you were using these environments to benchmark your training, please note that the resulting rewards may be slightly different in v0.10. #### Steps to Migrate - `UnitySDK/Assets/ML-Agents/Scripts/Communicator.cs` and its class `Communicator` have been renamed to `UnitySDK/Assets/ML-Agents/Scripts/ICommunicator.cs` and `ICommunicator` respectively. - The `SpaceType` Enums `discrete`, and `continuous` have been renamed to `Discrete` and `Continuous`. - We have removed the `Done` call as well as the capacity to set `Max Steps` on the Academy. Therefore an AcademyReset will never be triggered from C# (only from Python). If you want to reset the simulation after a fixed number of steps, or when an event in the simulation occurs, we recommend looking at our multi-agent example environments (such as FoodCollector). In our examples, groups of Agents can be reset through an "Area" that can reset groups of Agents. - The import for `mlagents.envs.UnityEnvironment` was removed. If you are using the Python API, change `from mlagents_envs import UnityEnvironment` to `from mlagents_envs.environment import UnityEnvironment`. ## Migrating from ML-Agents Toolkit v0.8 to v0.9 ### Important Changes - We have changed the way reward signals (including Curiosity) are defined in the `trainer_config.yaml`. - When using multiple environments, every "step" is recorded in TensorBoard. - The steps in the command line console corresponds to a single step of a single environment. Previously, each step corresponded to one step for all environments (i.e., `num_envs` steps). #### Steps to Migrate - If you were overriding any of these following parameters in your config file, remove them from the top-level config and follow the steps below: - `gamma`: Define a new `extrinsic` reward signal and set it's `gamma` to your new gamma. - `use_curiosity`, `curiosity_strength`, `curiosity_enc_size`: Define a `curiosity` reward signal and set its `strength` to `curiosity_strength`, and `encoding_size` to `curiosity_enc_size`. Give it the same `gamma` as your `extrinsic` signal to mimic previous behavior. - TensorBoards generated when running multiple environments in v0.8 are not comparable to those generated in v0.9 in terms of step count. Multiply your v0.8 step count by `num_envs` for an approximate comparison. You may need to change `max_steps` in your config as appropriate as well. ## Migrating from ML-Agents Toolkit v0.7 to v0.8 ### Important Changes - We have split the Python packages into two separate packages `ml-agents` and `ml-agents-envs`. - `--worker-id` option of `learn.py` has been removed, use `--base-port` instead if you'd like to run multiple instances of `learn.py`. #### Steps to Migrate - If you are installing via PyPI, there is no change. - If you intend to make modifications to `ml-agents` or `ml-agents-envs` please check the Installing for Development in the [Installation documentation](Installation.md). ## Migrating from ML-Agents Toolkit v0.6 to v0.7 ### Important Changes - We no longer support TFS and are now using the [Sentis](Sentis.md) #### Steps to Migrate - Make sure to remove the `ENABLE_TENSORFLOW` flag in your Unity Project settings ## Migrating from ML-Agents Toolkit v0.5 to v0.6 ### Important Changes - Brains are now Scriptable Objects instead of MonoBehaviors. - You can no longer modify the type of a Brain. If you want to switch between `PlayerBrain` and `LearningBrain` for multiple agents, you will need to assign a new Brain to each agent separately. **Note:** You can pass the same Brain to multiple agents in a scene by leveraging Unity's prefab system or look for all the agents in a scene using the search bar of the `Hierarchy` window with the word `Agent`. - We replaced the **Internal** and **External** Brain with **Learning Brain**. When you need to train a model, you need to drag it into the `Broadcast Hub` inside the `Academy` and check the `Control` checkbox. - We removed the `Broadcast` checkbox of the Brain, to use the broadcast functionality, you need to drag the Brain into the `Broadcast Hub`. - When training multiple Brains at the same time, each model is now stored into a separate model file rather than in the same file under different graph scopes. - The **Learning Brain** graph scope, placeholder names, output names and custom placeholders can no longer be modified. #### Steps to Migrate - To update a scene from v0.5 to v0.6, you must: - Remove the `Brain` GameObjects in the scene. (Delete all of the Brain GameObjects under Academy in the scene.) - Create new `Brain` Scriptable Objects using `Assets -> Create -> ML-Agents` for each type of the Brain you plan to use, and put the created files under a folder called Brains within your project. - Edit their `Brain Parameters` to be the same as the parameters used in the `Brain` GameObjects. - Agents have a `Brain` field in the Inspector, you need to drag the appropriate Brain ScriptableObject in it. - The Academy has a `Broadcast Hub` field in the inspector, which is list of brains used in the scene. To train or control your Brain from the `mlagents-learn` Python script, you need to drag the relevant `LearningBrain` ScriptableObjects used in your scene into entries into this list. ## Migrating from ML-Agents Toolkit v0.4 to v0.5 ### Important - The Unity project `unity-environment` has been renamed `UnitySDK`. - The `python` folder has been renamed to `ml-agents`. It now contains two packages, `mlagents.env` and `mlagents.trainers`. `mlagents.env` can be used to interact directly with a Unity environment, while `mlagents.trainers` contains the classes for training agents. - The supported Unity version has changed from `2017.1 or later` to `2017.4 or later`. 2017.4 is an LTS (Long Term Support) version that helps us maintain good quality and support. Earlier versions of Unity might still work, but you may encounter an [error](FAQ.md#instance-of-corebraininternal-couldnt-be-created) listed here. ### Unity API - Discrete Actions now use [branches](https://arxiv.org/abs/1711.08946). You can now specify concurrent discrete actions. You will need to update the Brain Parameters in the Brain Inspector in all your environments that use discrete actions. Refer to the [discrete action documentation](Learning-Environment-Design-Agents.md#discrete-action-space) for more information. ### Python API - In order to run a training session, you can now use the command `mlagents-learn` instead of `python3 learn.py` after installing the `mlagents` packages. This change is documented [here](Training-ML-Agents.md#training-with-mlagents-learn). For example, if we previously ran ```sh python3 learn.py 3DBall --train ``` from the `python` subdirectory (which is changed to `ml-agents` subdirectory in v0.5), we now run ```sh mlagents-learn config/trainer_config.yaml --env=3DBall --train ``` from the root directory where we installed the ML-Agents Toolkit. - It is now required to specify the path to the yaml trainer configuration file when running `mlagents-learn`. For an example trainer configuration file, see [trainer_config.yaml](https://github.com/Unity-Technologies/ml-agents/blob/0.5.0a/config/trainer_config.yaml). An example of passing a trainer configuration to `mlagents-learn` is shown above. - The environment name is now passed through the `--env` option. - Curriculum learning has been changed. In summary: - Curriculum files for the same environment must now be placed into a folder. Each curriculum file should be named after the Brain whose curriculum it specifies. - `min_lesson_length` now specifies the minimum number of episodes in a lesson and affects reward thresholding. - It is no longer necessary to specify the `Max Steps` of the Academy to use curriculum learning. ## Migrating from ML-Agents Toolkit v0.3 to v0.4 ### Unity API - `using MLAgents;` needs to be added in all of the C# scripts that use ML-Agents. ### Python API - We've changed some of the Python packages dependencies in requirement.txt file. Make sure to run `pip3 install -e .` within your `ml-agents/python` folder to update your Python packages. ## Migrating from ML-Agents Toolkit v0.2 to v0.3 There are a large number of new features and improvements in the ML-Agents toolkit v0.3 which change both the training process and Unity API in ways which will cause incompatibilities with environments made using older versions. This page is designed to highlight those changes for users familiar with v0.1 or v0.2 in order to ensure a smooth transition. ### Important - The ML-Agents Toolkit is no longer compatible with Python 2. ### Python Training - The training script `ppo.py` and `PPO.ipynb` Python notebook have been replaced with a single `learn.py` script as the launching point for training with ML-Agents. For more information on using `learn.py`, see [here](Training-ML-Agents.md#training-with-mlagents-learn). - Hyperparameters for training Brains are now stored in the `trainer_config.yaml` file. For more information on using this file, see [here](Training-ML-Agents.md#training-configurations). ### Unity API - Modifications to an Agent's rewards must now be done using either `AddReward()` or `SetReward()`. - Setting an Agent to done now requires the use of the `Done()` method. - `CollectStates()` has been replaced by `CollectObservations()`, which now no longer returns a list of floats. - To collect observations, call `AddVectorObs()` within `CollectObservations()`. Note that you can call `AddVectorObs()` with floats, integers, lists and arrays of floats, Vector3 and Quaternions. - `AgentStep()` has been replaced by `AgentAction()`. - `WaitTime()` has been removed. - The `Frame Skip` field of the Academy is replaced by the Agent's `Decision Frequency` field, enabling the Agent to make decisions at different frequencies. - The names of the inputs in the Internal Brain have been changed. You must replace `state` with `vector_observation` and `observation` with `visual_observation`. In addition, you must remove the `epsilon` placeholder. ### Semantics In order to more closely align with the terminology used in the Reinforcement Learning field, and to be more descriptive, we have changed the names of some of the concepts used in ML-Agents. The changes are highlighted in the table below. | Old - v0.2 and earlier | New - v0.3 and later | | ---------------------- | -------------------- | | State | Vector Observation | | Observation | Visual Observation | | Action | Vector Action | | N/A | Text Observation | | N/A | Text Action |
ml-agents/docs/Migrating.md/0
{ "file_path": "ml-agents/docs/Migrating.md", "repo_id": "ml-agents", "token_count": 12908 }
1,977
# Customizing Training via Plugins ML-Agents provides support for running your own python implementations of specific interfaces during the training process. These interfaces are currently fairly limited, but will be expanded in the future. **Note:** Plugin interfaces should currently be considered "in beta", and they may change in future releases. ## How to Write Your Own Plugin [This video](https://www.youtube.com/watch?v=fY3Y_xPKWNA) explains the basics of how to create a plugin system using setuptools, and is the same approach that ML-Agents' plugin system is based on. The `ml-agents-plugin-examples` directory contains a reference implementation of each plugin interface, so it's a good starting point. ### setup.py If you don't already have a `setup.py` file for your python code, you'll need to add one. `ml-agents-plugin-examples` has a [minimal example](../ml-agents-plugin-examples/setup.py) of this. In the call to `setup()`, you'll need to add to the `entry_points` dictionary for each plugin interface that you implement. The form of this is `{entry point name}={plugin module}:{plugin function}`. For example, in `ml-agents-plugin-examples`: ```python entry_points={ ML_AGENTS_STATS_WRITER: [ "example=mlagents_plugin_examples.example_stats_writer:get_example_stats_writer" ] } ``` * `ML_AGENTS_STATS_WRITER` (which is a string constant, `mlagents.stats_writer`) is the name of the plugin interface. This must be one of the provided interfaces ([see below](#plugin-interfaces)). * `example` is the plugin implementation name. This can be anything. * `mlagents_plugin_examples.example_stats_writer` is the plugin module. This points to the module where the plugin registration function is defined. * `get_example_stats_writer` is the plugin registration function. This is called when running `mlagents-learn`. The arguments and expected return type for this are different for each plugin interface. ### Local Installation Once you've defined `entry_points` in your `setup.py`, you will need to run ``` pip install -e [path to your plugin code] ``` in the same python virtual environment that you have `mlagents` installed. ## Plugin Interfaces ### StatsWriter The StatsWriter class receives various information from the training process, such as the average Agent reward in each summary period. By default, we log this information to the console and write it to [TensorBoard](Using-Tensorboard.md). #### Interface The `StatsWriter.write_stats()` method must be implemented in any derived classes. It takes a "category" parameter, which typically is the behavior name of the Agents being trained, and a dictionary of `StatSummary` values with string keys. Additionally, `StatsWriter.on_add_stat()` may be extended to register a callback handler for each stat emission. #### Registration The `StatsWriter` registration function takes a `RunOptions` argument and returns a list of `StatsWriter`s. An example implementation is provided in [`mlagents_plugin_examples`](../ml-agents-plugin-examples/mlagents_plugin_examples/example_stats_writer.py)
ml-agents/docs/Training-Plugins.md/0
{ "file_path": "ml-agents/docs/Training-Plugins.md", "repo_id": "ml-agents", "token_count": 818 }
1,978
<img src="docs/images/unity-wide.png" align="middle" width="3000"/> # Unity ML-Agents 工具包(Beta) v0.3.1 **注意:** 本文档为v0.3版本文档的部分翻译版,目前并不会随着英文版文档更新而更新。若要查看更新更全的英文版文档,请查看[这里](https://github.com/Unity-Technologies/ml-agents)。 **Unity Machine Learning Agents** (ML-Agents) 是一款开源的 Unity 插件, 使得我们得以在游戏环境和模拟环境中训练智能 agent。您可以使用 reinforcement learning(强化学习)、imitation learning(模仿学习)、neuroevolution(神经进化)或其他机器学习方法, 通过简单易用的 Python API进行控制,对 Agent 进行训练。我们还提供最先进算法的实现方式(基于 TensorFlow),让游戏开发者和业余爱好者能够轻松地 训练用于 2D、3D 和 VR/AR 游戏的智能 agent。 这些经过训练的 agent 可用于多种目的, 包括控制 NPC 行为(采用各种设置, 例如多个 agent 和对抗)、对游戏内部版本进行自动化测试、以及评估不同游戏设计决策的预发布版本。ML-Agents 对于游戏开发者和 AI 研究人员双方 都有利,因为它提供了一个集中的平台, 使得我们得以在 Unity 的丰富环境中测试 AI 的最新进展, 并使结果为更多的研究者和游戏开发者所用。 ## 功能 * 用于控制 Unity 环境的 Python API * 10 多个示例 Unity 环境 * 支持多种环境配置方案和训练方案 * 使用 deep reinforcement learning(深度强化学习)技术训练带记忆的Agent * 可轻松定义的 Curriculum Learning(课程学习)方案 * 通过广播 Agent 行为实现监督学习 * 内置 Imitation Learning(模仿学习)支持 * 通过按需决策功能实现灵活的 Agent 控制 * 在环境中可查看神经网络的输出 * 通过 Docker 实现简化设置(测试功能) ## 文档和参考 **除了安装和使用说明外,如需更多信息, 请参阅我们的[文档主页](docs/Readme.md)。**如果您使用的 是 v0.3 之前的 ML-Agents 版本,强烈建议您参考 我们的[关于迁移到 v0.3 的指南](/docs/Migrating.md)。 我们还发布了一系列与 ML-Agents 相关的博客文章: - reinforcement learning(强化学习)概念概述 ([多臂强盗](https://blogs.unity3d.com/2017/06/26/unity-ai-themed-blog-entries/) 和 [Q-learning](https://blogs.unity3d.com/2017/08/22/unity-ai-reinforcement-learning-with-q-learning/)) - [在实际游戏中使用机器学习 Agent:初学者指南](https://blogs.unity3d.com/2017/12/11/using-machine-learning-agents-in-a-real-game-a-beginners-guide/) - [文章](https://blogs.unity3d.com/2018/02/28/introducing-the-winners-of-the-first-ml-agents-challenge/)公布我们 [第一个 ML-Agents 挑战](https://connect.unity.com/challenges/ml-agents-1)的获胜者 - [文章](https://blogs.unity3d.com/2018/01/23/designing-safer-cities-through-simulations/) 概述如何利用 Unity 作为模拟器来设计更安全的城市。 除了我们自己的文档外,这里还有一些额外的相关文章: - [Unity AI - Unity 3D 人工智能](https://www.youtube.com/watch?v=bqsfkGbBU6k) - [游戏开发者学习机器学习](https://mikecann.co.uk/machine-learning/a-game-developer-learns-machine-learning-intent/) - [在 Intel 体系结构上单独研究 Unity Technologies ML-Agents](https://software.intel.com/en-us/articles/explore-unity-technologies-ml-agents-exclusively-on-intel-architecture) ## 社区和反馈 ML-Agents 是一个开源项目,我们鼓励并欢迎大家贡献自己的力量。 如果您想做出贡献,请务必查看我们的 [贡献准则](/com.unity.ml-agents/CONTRIBUTING.md)和 [行为准则](/CODE_OF_CONDUCT.md)。 您可以通过 Unity Connect 和 GitHub 与我们以及更广泛的社区进行交流: * 加入我们的 [Unity 机器学习频道](https://connect.unity.com/messages/c/035fba4f88400000) 与使用 ML-Agents 的其他人以及对机器学习充满热情的 Unity 开发者 交流。我们使用该频道来展示关于 ML-Agents (在更广泛的范围内,还包括游戏中的机器学习)的最新动态。 * 如果您在使用 ML-Agents 时遇到任何问题,请 [提交问题](https://github.com/Unity-Technologies/ml-agents/issues)并 确保提供尽可能多的详细信息。 对于任何其他问题或反馈,请直接与 ML-Agents 团队联系, 电子邮件地址为 [email protected]。 ## 许可证 [Apache 许可证 2.0](LICENSE)
ml-agents/localized_docs/zh-CN/README.md/0
{ "file_path": "ml-agents/localized_docs/zh-CN/README.md", "repo_id": "ml-agents", "token_count": 2696 }
1,979
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: mlagents_envs/communicator_objects/agent_info_action_pair.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database from google.protobuf import descriptor_pb2 # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from mlagents_envs.communicator_objects import agent_info_pb2 as mlagents__envs_dot_communicator__objects_dot_agent__info__pb2 from mlagents_envs.communicator_objects import agent_action_pb2 as mlagents__envs_dot_communicator__objects_dot_agent__action__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='mlagents_envs/communicator_objects/agent_info_action_pair.proto', package='communicator_objects', syntax='proto3', serialized_pb=_b('\n?mlagents_envs/communicator_objects/agent_info_action_pair.proto\x12\x14\x63ommunicator_objects\x1a\x33mlagents_envs/communicator_objects/agent_info.proto\x1a\x35mlagents_envs/communicator_objects/agent_action.proto\"\x91\x01\n\x18\x41gentInfoActionPairProto\x12\x38\n\nagent_info\x18\x01 \x01(\x0b\x32$.communicator_objects.AgentInfoProto\x12;\n\x0b\x61\x63tion_info\x18\x02 \x01(\x0b\x32&.communicator_objects.AgentActionProtoB%\xaa\x02\"Unity.MLAgents.CommunicatorObjectsb\x06proto3') , dependencies=[mlagents__envs_dot_communicator__objects_dot_agent__info__pb2.DESCRIPTOR,mlagents__envs_dot_communicator__objects_dot_agent__action__pb2.DESCRIPTOR,]) _AGENTINFOACTIONPAIRPROTO = _descriptor.Descriptor( name='AgentInfoActionPairProto', full_name='communicator_objects.AgentInfoActionPairProto', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='agent_info', full_name='communicator_objects.AgentInfoActionPairProto.agent_info', index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='action_info', full_name='communicator_objects.AgentInfoActionPairProto.action_info', index=1, number=2, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=198, serialized_end=343, ) _AGENTINFOACTIONPAIRPROTO.fields_by_name['agent_info'].message_type = mlagents__envs_dot_communicator__objects_dot_agent__info__pb2._AGENTINFOPROTO _AGENTINFOACTIONPAIRPROTO.fields_by_name['action_info'].message_type = mlagents__envs_dot_communicator__objects_dot_agent__action__pb2._AGENTACTIONPROTO DESCRIPTOR.message_types_by_name['AgentInfoActionPairProto'] = _AGENTINFOACTIONPAIRPROTO _sym_db.RegisterFileDescriptor(DESCRIPTOR) AgentInfoActionPairProto = _reflection.GeneratedProtocolMessageType('AgentInfoActionPairProto', (_message.Message,), dict( DESCRIPTOR = _AGENTINFOACTIONPAIRPROTO, __module__ = 'mlagents_envs.communicator_objects.agent_info_action_pair_pb2' # @@protoc_insertion_point(class_scope:communicator_objects.AgentInfoActionPairProto) )) _sym_db.RegisterMessage(AgentInfoActionPairProto) DESCRIPTOR.has_options = True DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\252\002\"Unity.MLAgents.CommunicatorObjects')) # @@protoc_insertion_point(module_scope)
ml-agents/ml-agents-envs/mlagents_envs/communicator_objects/agent_info_action_pair_pb2.py/0
{ "file_path": "ml-agents/ml-agents-envs/mlagents_envs/communicator_objects/agent_info_action_pair_pb2.py", "repo_id": "ml-agents", "token_count": 1443 }
1,980
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: mlagents_envs/communicator_objects/header.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database from google.protobuf import descriptor_pb2 # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor.FileDescriptor( name='mlagents_envs/communicator_objects/header.proto', package='communicator_objects', syntax='proto3', serialized_pb=_b('\n/mlagents_envs/communicator_objects/header.proto\x12\x14\x63ommunicator_objects\".\n\x0bHeaderProto\x12\x0e\n\x06status\x18\x01 \x01(\x05\x12\x0f\n\x07message\x18\x02 \x01(\tB%\xaa\x02\"Unity.MLAgents.CommunicatorObjectsb\x06proto3') ) _HEADERPROTO = _descriptor.Descriptor( name='HeaderProto', full_name='communicator_objects.HeaderProto', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='status', full_name='communicator_objects.HeaderProto.status', index=0, number=1, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='message', full_name='communicator_objects.HeaderProto.message', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=73, serialized_end=119, ) DESCRIPTOR.message_types_by_name['HeaderProto'] = _HEADERPROTO _sym_db.RegisterFileDescriptor(DESCRIPTOR) HeaderProto = _reflection.GeneratedProtocolMessageType('HeaderProto', (_message.Message,), dict( DESCRIPTOR = _HEADERPROTO, __module__ = 'mlagents_envs.communicator_objects.header_pb2' # @@protoc_insertion_point(class_scope:communicator_objects.HeaderProto) )) _sym_db.RegisterMessage(HeaderProto) DESCRIPTOR.has_options = True DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\252\002\"Unity.MLAgents.CommunicatorObjects')) # @@protoc_insertion_point(module_scope)
ml-agents/ml-agents-envs/mlagents_envs/communicator_objects/header_pb2.py/0
{ "file_path": "ml-agents/ml-agents-envs/mlagents_envs/communicator_objects/header_pb2.py", "repo_id": "ml-agents", "token_count": 1029 }
1,981
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: mlagents_envs/communicator_objects/unity_rl_initialization_output.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database from google.protobuf import descriptor_pb2 # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from mlagents_envs.communicator_objects import capabilities_pb2 as mlagents__envs_dot_communicator__objects_dot_capabilities__pb2 from mlagents_envs.communicator_objects import brain_parameters_pb2 as mlagents__envs_dot_communicator__objects_dot_brain__parameters__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='mlagents_envs/communicator_objects/unity_rl_initialization_output.proto', package='communicator_objects', syntax='proto3', serialized_pb=_b('\nGmlagents_envs/communicator_objects/unity_rl_initialization_output.proto\x12\x14\x63ommunicator_objects\x1a\x35mlagents_envs/communicator_objects/capabilities.proto\x1a\x39mlagents_envs/communicator_objects/brain_parameters.proto\"\x8c\x02\n UnityRLInitializationOutputProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x1d\n\x15\x63ommunication_version\x18\x02 \x01(\t\x12\x10\n\x08log_path\x18\x03 \x01(\t\x12\x44\n\x10\x62rain_parameters\x18\x05 \x03(\x0b\x32*.communicator_objects.BrainParametersProto\x12\x17\n\x0fpackage_version\x18\x07 \x01(\t\x12\x44\n\x0c\x63\x61pabilities\x18\x08 \x01(\x0b\x32..communicator_objects.UnityRLCapabilitiesProtoJ\x04\x08\x06\x10\x07\x42%\xaa\x02\"Unity.MLAgents.CommunicatorObjectsb\x06proto3') , dependencies=[mlagents__envs_dot_communicator__objects_dot_capabilities__pb2.DESCRIPTOR,mlagents__envs_dot_communicator__objects_dot_brain__parameters__pb2.DESCRIPTOR,]) _UNITYRLINITIALIZATIONOUTPUTPROTO = _descriptor.Descriptor( name='UnityRLInitializationOutputProto', full_name='communicator_objects.UnityRLInitializationOutputProto', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='name', full_name='communicator_objects.UnityRLInitializationOutputProto.name', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='communication_version', full_name='communicator_objects.UnityRLInitializationOutputProto.communication_version', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='log_path', full_name='communicator_objects.UnityRLInitializationOutputProto.log_path', index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='brain_parameters', full_name='communicator_objects.UnityRLInitializationOutputProto.brain_parameters', index=3, number=5, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='package_version', full_name='communicator_objects.UnityRLInitializationOutputProto.package_version', index=4, number=7, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='capabilities', full_name='communicator_objects.UnityRLInitializationOutputProto.capabilities', index=5, number=8, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=212, serialized_end=480, ) _UNITYRLINITIALIZATIONOUTPUTPROTO.fields_by_name['brain_parameters'].message_type = mlagents__envs_dot_communicator__objects_dot_brain__parameters__pb2._BRAINPARAMETERSPROTO _UNITYRLINITIALIZATIONOUTPUTPROTO.fields_by_name['capabilities'].message_type = mlagents__envs_dot_communicator__objects_dot_capabilities__pb2._UNITYRLCAPABILITIESPROTO DESCRIPTOR.message_types_by_name['UnityRLInitializationOutputProto'] = _UNITYRLINITIALIZATIONOUTPUTPROTO _sym_db.RegisterFileDescriptor(DESCRIPTOR) UnityRLInitializationOutputProto = _reflection.GeneratedProtocolMessageType('UnityRLInitializationOutputProto', (_message.Message,), dict( DESCRIPTOR = _UNITYRLINITIALIZATIONOUTPUTPROTO, __module__ = 'mlagents_envs.communicator_objects.unity_rl_initialization_output_pb2' # @@protoc_insertion_point(class_scope:communicator_objects.UnityRLInitializationOutputProto) )) _sym_db.RegisterMessage(UnityRLInitializationOutputProto) DESCRIPTOR.has_options = True DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\252\002\"Unity.MLAgents.CommunicatorObjects')) # @@protoc_insertion_point(module_scope)
ml-agents/ml-agents-envs/mlagents_envs/communicator_objects/unity_rl_initialization_output_pb2.py/0
{ "file_path": "ml-agents/ml-agents-envs/mlagents_envs/communicator_objects/unity_rl_initialization_output_pb2.py", "repo_id": "ml-agents", "token_count": 2256 }
1,982
from typing import Optional, Dict, Any, Tuple from gym import error from mlagents_envs.base_env import BaseEnv from pettingzoo import ParallelEnv from mlagents_envs.envs.unity_pettingzoo_base_env import UnityPettingzooBaseEnv class UnityParallelEnv(UnityPettingzooBaseEnv, ParallelEnv): """ Unity Parallel (PettingZoo) environment wrapper. """ def __init__(self, env: BaseEnv, seed: Optional[int] = None): """ Initializes a Unity Parallel environment wrapper. :param env: The UnityEnvironment that is being wrapped. :param seed: The seed for the action spaces of the agents. """ super().__init__(env, seed) def reset(self) -> Dict[str, Any]: """ Resets the environment. """ super().reset() return self._observations def step(self, actions: Dict[str, Any]) -> Tuple: self._assert_loaded() if len(self._live_agents) <= 0 and actions: raise error.Error( "You must reset the environment before you can perform a step." ) # Process actions for current_agent, action in actions.items(): self._process_action(current_agent, action) # Reset reward for k in self._rewards.keys(): self._rewards[k] = 0 # Step environment self._step() # Agent cleanup and sorting self._cleanup_agents() self._live_agents.sort() # unnecessary, only for passing API test return self._observations, self._rewards, self._dones, self._infos
ml-agents/ml-agents-envs/mlagents_envs/envs/unity_parallel_env.py/0
{ "file_path": "ml-agents/ml-agents-envs/mlagents_envs/envs/unity_parallel_env.py", "repo_id": "ml-agents", "token_count": 641 }
1,983
from mlagents_envs.side_channel import SideChannel, IncomingMessage, OutgoingMessage import uuid from typing import Dict, Optional, List class FloatPropertiesChannel(SideChannel): """ This is the SideChannel for float properties shared with Unity. You can modify the float properties of an environment with the commands set_property, get_property and list_properties. """ def __init__(self, channel_id: uuid.UUID = None) -> None: self._float_properties: Dict[str, float] = {} if channel_id is None: channel_id = uuid.UUID("60ccf7d0-4f7e-11ea-b238-784f4387d1f7") super().__init__(channel_id) def on_message_received(self, msg: IncomingMessage) -> None: """ Is called by the environment to the side channel. Can be called multiple times per step if multiple messages are meant for that SideChannel. """ k = msg.read_string() v = msg.read_float32() self._float_properties[k] = v def set_property(self, key: str, value: float) -> None: """ Sets a property in the Unity Environment. :param key: The string identifier of the property. :param value: The float value of the property. """ self._float_properties[key] = value msg = OutgoingMessage() msg.write_string(key) msg.write_float32(value) super().queue_message_to_send(msg) def get_property(self, key: str) -> Optional[float]: """ Gets a property in the Unity Environment. If the property was not found, will return None. :param key: The string identifier of the property. :return: The float value of the property or None. """ return self._float_properties.get(key) def list_properties(self) -> List[str]: """ Returns a list of all the string identifiers of the properties currently present in the Unity Environment. """ return list(self._float_properties.keys()) def get_property_dict_copy(self) -> Dict[str, float]: """ Returns a copy of the float properties. :return: """ return dict(self._float_properties)
ml-agents/ml-agents-envs/mlagents_envs/side_channel/float_properties_channel.py/0
{ "file_path": "ml-agents/ml-agents-envs/mlagents_envs/side_channel/float_properties_channel.py", "repo_id": "ml-agents", "token_count": 860 }
1,984
import os from pathlib import Path import pytest from mlagents_envs.registry import default_registry, UnityEnvRegistry from mlagents_envs.registry.remote_registry_entry import RemoteRegistryEntry BASIC_ID = "Basic" def create_registry(tmp_dir: str) -> UnityEnvRegistry: reg = UnityEnvRegistry() entry = RemoteRegistryEntry( BASIC_ID, 0.0, "Description", "https://storage.googleapis.com/mlagents-test-environments/1.0.0/linux/Basic.zip", "https://storage.googleapis.com/mlagents-test-environments/1.0.0/darwin/Basic.zip", "https://storage.googleapis.com/mlagents-test-environments/1.0.0/windows/Basic.zip", tmp_dir=tmp_dir, ) reg.register(entry) return reg @pytest.mark.parametrize("n_ports", [2]) def test_basic_in_registry(base_port: int, tmp_path: Path) -> None: assert BASIC_ID in default_registry os.environ["TERM"] = "xterm" registry = create_registry(str(tmp_path)) for worker_id in range(2): assert BASIC_ID in registry env = registry[BASIC_ID].make( base_port=base_port, worker_id=worker_id, no_graphics=True ) env.reset() env.step() assert len(env.behavior_specs) == 1 env.close()
ml-agents/ml-agents-envs/tests/test_registry.py/0
{ "file_path": "ml-agents/ml-agents-envs/tests/test_registry.py", "repo_id": "ml-agents", "token_count": 545 }
1,985
from typing import Dict, cast import attr from mlagents.torch_utils import torch, default_device from mlagents.trainers.buffer import AgentBuffer, BufferKey, RewardSignalUtil from mlagents_envs.timers import timed from mlagents.trainers.policy.torch_policy import TorchPolicy from mlagents.trainers.optimizer.torch_optimizer import TorchOptimizer from mlagents.trainers.settings import ( TrainerSettings, OnPolicyHyperparamSettings, ScheduleType, ) from mlagents.trainers.torch_entities.networks import ValueNetwork from mlagents.trainers.torch_entities.agent_action import AgentAction from mlagents.trainers.torch_entities.utils import ModelUtils from mlagents.trainers.trajectory import ObsUtil from mlagents.trainers.exception import TrainerConfigError @attr.s(auto_attribs=True) class A2CSettings(OnPolicyHyperparamSettings): beta: float = 5.0e-3 lambd: float = 0.95 num_epoch: int = attr.ib(default=1) # A2C does just one pass shared_critic: bool = False @num_epoch.validator def _check_num_epoch_one(self, attribute, value): if value != 1: raise TrainerConfigError("A2C requires num_epoch = 1") learning_rate_schedule: ScheduleType = ScheduleType.LINEAR beta_schedule: ScheduleType = ScheduleType.LINEAR class A2COptimizer(TorchOptimizer): def __init__(self, policy: TorchPolicy, trainer_settings: TrainerSettings): """ Takes a Policy and a Dict of trainer parameters and creates an Optimizer around the policy. The A2C optimizer has a value estimator and a loss function. :param policy: A TorchPolicy object that will be updated by this A2C Optimizer. :param trainer_params: Trainer parameters dictionary that specifies the properties of the trainer. """ # Create the graph here to give more granular control of the TF graph to the Optimizer. super().__init__(policy, trainer_settings) self.hyperparameters: A2CSettings = cast( A2CSettings, trainer_settings.hyperparameters ) params = list(self.policy.actor.parameters()) if self.hyperparameters.shared_critic: self._critic = policy.actor else: self._critic = ValueNetwork( list(self.reward_signals.keys()), policy.behavior_spec.observation_specs, network_settings=trainer_settings.network_settings, ) self._critic.to(default_device()) params += list(self._critic.parameters()) self.decay_learning_rate = ModelUtils.DecayedValue( self.hyperparameters.learning_rate_schedule, self.hyperparameters.learning_rate, 1e-10, self.trainer_settings.max_steps, ) self.decay_beta = ModelUtils.DecayedValue( self.hyperparameters.beta_schedule, self.hyperparameters.beta, 1e-10, self.trainer_settings.max_steps, ) self.optimizer = torch.optim.Adam( params, lr=self.trainer_settings.hyperparameters.learning_rate ) self.stats_name_to_update_name = { "Losses/Value Loss": "value_loss", "Losses/Policy Loss": "policy_loss", } self.stream_names = list(self.reward_signals.keys()) @property def critic(self): return self._critic @timed def update(self, batch: AgentBuffer, num_sequences: int) -> Dict[str, float]: """ Performs update on model. :param batch: Batch of experiences. :param num_sequences: Number of sequences to process. :return: Results of update. """ # Get decayed parameters decay_lr = self.decay_learning_rate.get_value(self.policy.get_current_step()) decay_bet = self.decay_beta.get_value(self.policy.get_current_step()) returns = {} for name in self.reward_signals: returns[name] = ModelUtils.list_to_tensor( batch[RewardSignalUtil.returns_key(name)] ) n_obs = len(self.policy.behavior_spec.observation_specs) current_obs = ObsUtil.from_buffer(batch, n_obs) # Convert to tensors current_obs = [ModelUtils.list_to_tensor(obs) for obs in current_obs] act_masks = ModelUtils.list_to_tensor(batch[BufferKey.ACTION_MASK]) actions = AgentAction.from_buffer(batch) memories = [ ModelUtils.list_to_tensor(batch[BufferKey.MEMORY][i]) for i in range(0, len(batch[BufferKey.MEMORY]), self.policy.sequence_length) ] if len(memories) > 0: memories = torch.stack(memories).unsqueeze(0) # Get value memories value_memories = [ ModelUtils.list_to_tensor(batch[BufferKey.CRITIC_MEMORY][i]) for i in range( 0, len(batch[BufferKey.CRITIC_MEMORY]), self.policy.sequence_length ) ] if len(value_memories) > 0: value_memories = torch.stack(value_memories).unsqueeze(0) run_out = self.policy.actor.get_stats( current_obs, masks=act_masks, actions=actions, memories=memories, sequence_length=self.policy.sequence_length, ) log_probs = run_out["log_probs"] entropy = run_out["entropy"] values, _ = self.critic.critic_pass( current_obs, memories=value_memories, sequence_length=self.policy.sequence_length, ) log_probs = log_probs.flatten() value_loss_per_head = [] for name, head in values.items(): returns_tensor = returns[name] be = (returns_tensor - head) ** 2 value_loss_per_head.append(be) value_loss = torch.mean(torch.stack(value_loss_per_head)) advantages = ModelUtils.list_to_tensor(batch[BufferKey.ADVANTAGES]) policy_loss = -1 * torch.mean(torch.sum(log_probs, dim=1) * advantages) loss = policy_loss + 0.5 * value_loss - decay_bet * torch.mean(entropy) # Set optimizer learning rate ModelUtils.update_learning_rate(self.optimizer, decay_lr) self.optimizer.zero_grad() loss.backward() self.optimizer.step() update_stats = { # NOTE: abs() is not technically correct, but matches the behavior in TensorFlow. # TODO: After PyTorch is default, change to something more correct. "Losses/Policy Loss": torch.abs(policy_loss).item(), "Losses/Value Loss": value_loss.item(), "Policy/Learning Rate": decay_lr, "Policy/Beta": decay_bet, } return update_stats def get_modules(self): modules = { "Optimizer:value_optimizer": self.optimizer, "Optimizer:critic": self._critic, } for reward_provider in self.reward_signals.values(): modules.update(reward_provider.get_modules()) return modules
ml-agents/ml-agents-trainer-plugin/mlagents_trainer_plugin/a2c/a2c_optimizer.py/0
{ "file_path": "ml-agents/ml-agents-trainer-plugin/mlagents_trainer_plugin/a2c/a2c_optimizer.py", "repo_id": "ml-agents", "token_count": 3079 }
1,986
# Version of the library that will be used to upload to pypi __version__ = "1.1.0.dev0" # Git tag that will be checked to determine whether to trigger upload to pypi __release_tag__ = None
ml-agents/ml-agents/mlagents/trainers/__init__.py/0
{ "file_path": "ml-agents/ml-agents/mlagents/trainers/__init__.py", "repo_id": "ml-agents", "token_count": 58 }
1,987
# # Unity ML-Agents Toolkit import abc from typing import Any, Tuple, List class BaseModelSaver(abc.ABC): """This class is the base class for the ModelSaver""" def __init__(self): pass @abc.abstractmethod def register(self, module: Any) -> None: """ Register the modules to the ModelSaver. The ModelSaver will store the module and include it in the saved files when saving checkpoint/exporting graph. :param module: the module to be registered """ pass def _register_policy(self, policy): """ Helper function for registering policy to the ModelSaver. :param policy: the policy to be registered """ pass def _register_optimizer(self, optimizer): """ Helper function for registering optimizer to the ModelSaver. :param optimizer: the optimizer to be registered """ pass @abc.abstractmethod def save_checkpoint(self, behavior_name: str, step: int) -> Tuple[str, List[str]]: """ Checkpoints the policy on disk. :param checkpoint_path: filepath to write the checkpoint :param behavior_name: Behavior name of bevavior to be trained :return: A Tuple of the path to the exported file, as well as a List of any auxillary files that were returned. For instance, an exported file would be Model.onnx, and the auxillary files would be [Model.pt] for PyTorch """ pass @abc.abstractmethod def export(self, output_filepath: str, behavior_name: str) -> None: """ Saves the serialized model, given a path and behavior name. This method will save the policy graph to the given filepath. The path should be provided without an extension as multiple serialized model formats may be generated as a result. :param output_filepath: path (without suffix) for the model file(s) :param behavior_name: Behavior name of behavior to be trained. """ pass @abc.abstractmethod def initialize_or_load(self, policy): """ Initialize/Load registered modules by default. If given input argument policy, do with the input policy instead. This argument is mainly for the initialization of the ghost trainer's fixed policy. :param policy (optional): if given, perform the initializing/loading on this input policy. Otherwise, do with the registered policy """ pass
ml-agents/ml-agents/mlagents/trainers/model_saver/model_saver.py/0
{ "file_path": "ml-agents/ml-agents/mlagents/trainers/model_saver/model_saver.py", "repo_id": "ml-agents", "token_count": 952 }
1,988
import yaml import pytest from mlagents.trainers.upgrade_config import convert_behaviors, remove_nones, convert from mlagents.trainers.settings import RewardSignalType from mlagents.trainers.ppo.trainer import PPOSettings, TRAINER_NAME as PPO_TRAINER_NAME from mlagents.trainers.sac.trainer import SACSettings, TRAINER_NAME as SAC_TRAINER_NAME BRAIN_NAME = "testbehavior" # Check one per category BATCH_SIZE = 256 HIDDEN_UNITS = 32 SUMMARY_FREQ = 500 PPO_CONFIG = f""" default: trainer: ppo batch_size: 1024 beta: 5.0e-3 buffer_size: 10240 epsilon: 0.2 hidden_units: 128 lambd: 0.95 learning_rate: 3.0e-4 learning_rate_schedule: linear beta_schedule: constant epsilon_schedule: linear max_steps: 5.0e5 memory_size: 256 normalize: false num_epoch: 3 num_layers: 2 time_horizon: 64 sequence_length: 64 summary_freq: 10000 use_recurrent: false vis_encode_type: simple reward_signals: extrinsic: strength: 1.0 gamma: 0.99 {BRAIN_NAME}: trainer: ppo batch_size: {BATCH_SIZE} beta: 5.0e-3 buffer_size: 64 epsilon: 0.2 hidden_units: {HIDDEN_UNITS} lambd: 0.95 learning_rate: 5.0e-3 max_steps: 2500 memory_size: 256 normalize: false num_epoch: 3 num_layers: 2 time_horizon: 64 sequence_length: 64 summary_freq: {SUMMARY_FREQ} use_recurrent: false reward_signals: curiosity: strength: 1.0 gamma: 0.99 encoding_size: 128 """ SAC_CONFIG = f""" default: trainer: sac batch_size: 128 buffer_size: 50000 buffer_init_steps: 0 hidden_units: 128 init_entcoef: 1.0 learning_rate: 3.0e-4 learning_rate_schedule: constant max_steps: 5.0e5 memory_size: 256 normalize: false num_update: 1 train_interval: 1 num_layers: 2 time_horizon: 64 sequence_length: 64 summary_freq: 10000 tau: 0.005 use_recurrent: false vis_encode_type: simple reward_signals: extrinsic: strength: 1.0 gamma: 0.99 {BRAIN_NAME}: trainer: sac batch_size: {BATCH_SIZE} buffer_size: 64 buffer_init_steps: 100 hidden_units: {HIDDEN_UNITS} init_entcoef: 0.01 learning_rate: 3.0e-4 max_steps: 1000 memory_size: 256 normalize: false num_update: 1 train_interval: 1 num_layers: 1 time_horizon: 64 sequence_length: 64 summary_freq: {SUMMARY_FREQ} tau: 0.005 use_recurrent: false curiosity_enc_size: 128 demo_path: None vis_encode_type: simple reward_signals: curiosity: strength: 1.0 gamma: 0.99 encoding_size: 128 """ CURRICULUM = """ BigWallJump: measure: progress thresholds: [0.1, 0.3, 0.5] min_lesson_length: 200 signal_smoothing: true parameters: big_wall_min_height: [0.0, 4.0, 6.0, 8.0] big_wall_max_height: [4.0, 7.0, 8.0, 8.0] SmallWallJump: measure: progress thresholds: [0.1, 0.3, 0.5] min_lesson_length: 100 signal_smoothing: true parameters: small_wall_height: [1.5, 2.0, 2.5, 4.0] """ RANDOMIZATION = """ resampling-interval: 5000 mass: sampler-type: uniform min_value: 0.5 max_value: 10 gravity: sampler-type: uniform min_value: 7 max_value: 12 scale: sampler-type: uniform min_value: 0.75 max_value: 3 """ @pytest.mark.parametrize("use_recurrent", [True, False]) @pytest.mark.parametrize("trainer_type", [PPO_TRAINER_NAME, SAC_TRAINER_NAME]) def test_convert_behaviors(trainer_type, use_recurrent): if trainer_type == PPO_TRAINER_NAME: trainer_config = PPO_CONFIG trainer_settings_type = PPOSettings else: trainer_config = SAC_CONFIG trainer_settings_type = SACSettings old_config = yaml.safe_load(trainer_config) old_config[BRAIN_NAME]["use_recurrent"] = use_recurrent new_config = convert_behaviors(old_config) # Test that the new config can be converted to TrainerSettings w/o exceptions trainer_settings = new_config[BRAIN_NAME] # Test that the trainer_settings contains the settings for BRAIN_NAME and # the defaults where specified assert trainer_settings.trainer_type == trainer_type assert isinstance(trainer_settings.hyperparameters, trainer_settings_type) assert trainer_settings.hyperparameters.batch_size == BATCH_SIZE assert trainer_settings.network_settings.hidden_units == HIDDEN_UNITS assert RewardSignalType.CURIOSITY in trainer_settings.reward_signals def test_convert(): old_behaviors = yaml.safe_load(PPO_CONFIG) old_curriculum = yaml.safe_load(CURRICULUM) old_sampler = yaml.safe_load(RANDOMIZATION) config = convert(old_behaviors, old_curriculum, old_sampler) assert BRAIN_NAME in config["behaviors"] assert "big_wall_min_height" in config["environment_parameters"] curriculum = config["environment_parameters"]["big_wall_min_height"]["curriculum"] assert len(curriculum) == 4 for i, expected_value in enumerate([0.0, 4.0, 6.0, 8.0]): assert curriculum[i][f"Lesson{i}"]["value"] == expected_value for i, threshold in enumerate([0.1, 0.3, 0.5]): criteria = curriculum[i][f"Lesson{i}"]["completion_criteria"] assert criteria["threshold"] == threshold assert criteria["behavior"] == "BigWallJump" assert criteria["signal_smoothing"] assert criteria["min_lesson_length"] == 200 assert criteria["measure"] == "progress" assert "gravity" in config["environment_parameters"] gravity = config["environment_parameters"]["gravity"] assert gravity["sampler_type"] == "uniform" assert gravity["sampler_parameters"]["min_value"] == 7 assert gravity["sampler_parameters"]["max_value"] == 12 def test_remove_nones(): dict_with_nones = {"hello": {"hello2": 2, "hello3": None}, "hello4": None} dict_without_nones = {"hello": {"hello2": 2}} output = remove_nones(dict_with_nones) assert output == dict_without_nones
ml-agents/ml-agents/mlagents/trainers/tests/test_config_conversion.py/0
{ "file_path": "ml-agents/ml-agents/mlagents/trainers/tests/test_config_conversion.py", "repo_id": "ml-agents", "token_count": 3036 }
1,989
import yaml from mlagents.trainers.settings import RunOptions from mlagents.trainers.training_analytics_side_channel import ( TrainingAnalyticsSideChannel, ) test_curriculum_config_yaml = """ environment_parameters: param_1: curriculum: - name: Lesson1 completion_criteria: measure: reward behavior: fake_behavior threshold: 30 min_lesson_length: 100 require_reset: true value: 1 - name: Lesson2 completion_criteria: measure: reward behavior: fake_behavior threshold: 60 min_lesson_length: 100 require_reset: false value: 2 - name: Lesson3 value: sampler_type: uniform sampler_parameters: min_value: 1 max_value: 3 """ def test_sanitize_run_options(): run_options = RunOptions.from_dict(yaml.safe_load(test_curriculum_config_yaml)) sanitized = TrainingAnalyticsSideChannel._sanitize_run_options(run_options) assert "param_1" not in sanitized["environment_parameters"] assert "fake_behavior" not in sanitized["environment_parameters"] assert ( TrainingAnalyticsSideChannel._hash("param_1") in sanitized["environment_parameters"] ) level1 = TrainingAnalyticsSideChannel._hash("param_1") assert sanitized["environment_parameters"][level1]["curriculum"][0][ "completion_criteria" ]["behavior"] == TrainingAnalyticsSideChannel._hash("fake_behavior")
ml-agents/ml-agents/mlagents/trainers/tests/test_training_analytics_side_channel.py/0
{ "file_path": "ml-agents/ml-agents/mlagents/trainers/tests/test_training_analytics_side_channel.py", "repo_id": "ml-agents", "token_count": 751 }
1,990
import pytest import numpy as np from mlagents.trainers.ghost.trainer import GhostTrainer from mlagents.trainers.ghost.controller import GhostController from mlagents.trainers.behavior_id_utils import BehaviorIdentifiers from mlagents.trainers.ppo.trainer import PPOTrainer from mlagents.trainers.agent_processor import AgentManagerQueue from mlagents.trainers.buffer import BufferKey, RewardSignalUtil from mlagents.trainers.tests import mock_brain as mb from mlagents.trainers.tests.mock_brain import copy_buffer_fields from mlagents.trainers.tests.test_trajectory import make_fake_trajectory from mlagents.trainers.settings import TrainerSettings, SelfPlaySettings from mlagents.trainers.tests.dummy_config import create_observation_specs_with_shapes @pytest.fixture def dummy_config(): return TrainerSettings(self_play=SelfPlaySettings()) VECTOR_ACTION_SPACE = 1 VECTOR_OBS_SPACE = 8 DISCRETE_ACTION_SPACE = [3, 3, 3, 2] BUFFER_INIT_SAMPLES = 10241 NUM_AGENTS = 12 @pytest.mark.parametrize("use_discrete", [True, False]) def test_load_and_set(dummy_config, use_discrete): mock_specs = mb.setup_test_behavior_specs( use_discrete, False, vector_action_space=DISCRETE_ACTION_SPACE if use_discrete else VECTOR_ACTION_SPACE, vector_obs_space=VECTOR_OBS_SPACE, ) trainer_params = dummy_config trainer = PPOTrainer("test", 0, trainer_params, True, False, 0, "0") trainer.seed = 1 policy = trainer.create_policy("test", mock_specs) trainer.seed = 20 # otherwise graphs are the same to_load_policy = trainer.create_policy("test", mock_specs) weights = policy.get_weights() load_weights = to_load_policy.get_weights() try: for w, lw in zip(weights, load_weights): np.testing.assert_array_equal(w, lw) except AssertionError: pass to_load_policy.load_weights(weights) load_weights = to_load_policy.get_weights() for w, lw in zip(weights, load_weights): np.testing.assert_array_equal(w, lw) def test_resume(dummy_config, tmp_path): mock_specs = mb.setup_test_behavior_specs( True, False, vector_action_space=[2], vector_obs_space=1 ) behavior_id_team0 = "test_brain?team=0" behavior_id_team1 = "test_brain?team=1" brain_name = BehaviorIdentifiers.from_name_behavior_id(behavior_id_team0).brain_name tmp_path = tmp_path.as_posix() ppo_trainer = PPOTrainer(brain_name, 0, dummy_config, True, False, 0, tmp_path) controller = GhostController(100) trainer = GhostTrainer( ppo_trainer, brain_name, controller, 0, dummy_config, True, tmp_path ) parsed_behavior_id0 = BehaviorIdentifiers.from_name_behavior_id(behavior_id_team0) policy = trainer.create_policy(parsed_behavior_id0, mock_specs) trainer.add_policy(parsed_behavior_id0, policy) parsed_behavior_id1 = BehaviorIdentifiers.from_name_behavior_id(behavior_id_team1) policy = trainer.create_policy(parsed_behavior_id1, mock_specs) trainer.add_policy(parsed_behavior_id1, policy) trainer.save_model() # Make a new trainer, check that the policies are the same ppo_trainer2 = PPOTrainer(brain_name, 0, dummy_config, True, True, 0, tmp_path) trainer2 = GhostTrainer( ppo_trainer2, brain_name, controller, 0, dummy_config, True, tmp_path ) policy = trainer2.create_policy(parsed_behavior_id0, mock_specs) trainer2.add_policy(parsed_behavior_id0, policy) policy = trainer2.create_policy(parsed_behavior_id1, mock_specs) trainer2.add_policy(parsed_behavior_id1, policy) trainer1_policy = trainer.get_policy(parsed_behavior_id1.behavior_id) trainer2_policy = trainer2.get_policy(parsed_behavior_id1.behavior_id) weights = trainer1_policy.get_weights() weights2 = trainer2_policy.get_weights() for w, lw in zip(weights, weights2): np.testing.assert_array_equal(w, lw) def test_process_trajectory(dummy_config): mock_specs = mb.setup_test_behavior_specs( True, False, vector_action_space=[2], vector_obs_space=1 ) behavior_id_team0 = "test_brain?team=0" behavior_id_team1 = "test_brain?team=1" brain_name = BehaviorIdentifiers.from_name_behavior_id(behavior_id_team0).brain_name ppo_trainer = PPOTrainer(brain_name, 0, dummy_config, True, False, 0, "0") controller = GhostController(100) trainer = GhostTrainer( ppo_trainer, brain_name, controller, 0, dummy_config, True, "0" ) # first policy encountered becomes policy trained by wrapped PPO parsed_behavior_id0 = BehaviorIdentifiers.from_name_behavior_id(behavior_id_team0) policy = trainer.create_policy(parsed_behavior_id0, mock_specs) trainer.add_policy(parsed_behavior_id0, policy) trajectory_queue0 = AgentManagerQueue(behavior_id_team0) trainer.subscribe_trajectory_queue(trajectory_queue0) # Ghost trainer should ignore this queue because off policy parsed_behavior_id1 = BehaviorIdentifiers.from_name_behavior_id(behavior_id_team1) policy = trainer.create_policy(parsed_behavior_id1, mock_specs) trainer.add_policy(parsed_behavior_id1, policy) trajectory_queue1 = AgentManagerQueue(behavior_id_team1) trainer.subscribe_trajectory_queue(trajectory_queue1) time_horizon = 15 trajectory = make_fake_trajectory( length=time_horizon, max_step_complete=True, observation_specs=create_observation_specs_with_shapes([(1,)]), action_spec=mock_specs.action_spec, ) trajectory_queue0.put(trajectory) trainer.advance() # Check that trainer put trajectory in update buffer assert trainer.trainer.update_buffer.num_experiences == 15 trajectory_queue1.put(trajectory) trainer.advance() # Check that ghost trainer ignored off policy queue assert trainer.trainer.update_buffer.num_experiences == 15 # Check that it emptied the queue assert trajectory_queue1.empty() def test_publish_queue(dummy_config): mock_specs = mb.setup_test_behavior_specs( True, False, vector_action_space=[1], vector_obs_space=8 ) behavior_id_team0 = "test_brain?team=0" behavior_id_team1 = "test_brain?team=1" parsed_behavior_id0 = BehaviorIdentifiers.from_name_behavior_id(behavior_id_team0) brain_name = parsed_behavior_id0.brain_name ppo_trainer = PPOTrainer(brain_name, 0, dummy_config, True, False, 0, "0") controller = GhostController(100) trainer = GhostTrainer( ppo_trainer, brain_name, controller, 0, dummy_config, True, "0" ) # First policy encountered becomes policy trained by wrapped PPO # This queue should remain empty after swap snapshot policy = trainer.create_policy(parsed_behavior_id0, mock_specs) trainer.add_policy(parsed_behavior_id0, policy) policy_queue0 = AgentManagerQueue(behavior_id_team0) trainer.publish_policy_queue(policy_queue0) # Ghost trainer should use this queue for ghost policy swap parsed_behavior_id1 = BehaviorIdentifiers.from_name_behavior_id(behavior_id_team1) policy = trainer.create_policy(parsed_behavior_id1, mock_specs) trainer.add_policy(parsed_behavior_id1, policy) policy_queue1 = AgentManagerQueue(behavior_id_team1) trainer.publish_policy_queue(policy_queue1) # check ghost trainer swap pushes to ghost queue and not trainer assert policy_queue0.empty() and policy_queue1.empty() trainer._swap_snapshots() assert policy_queue0.empty() and not policy_queue1.empty() # clear policy_queue1.get_nowait() buffer = mb.simulate_rollout(BUFFER_INIT_SAMPLES, mock_specs) # Mock out reward signal eval copy_buffer_fields( buffer, src_key=BufferKey.ENVIRONMENT_REWARDS, dst_keys=[ BufferKey.ADVANTAGES, RewardSignalUtil.rewards_key("extrinsic"), RewardSignalUtil.returns_key("extrinsic"), RewardSignalUtil.value_estimates_key("extrinsic"), RewardSignalUtil.rewards_key("curiosity"), RewardSignalUtil.returns_key("curiosity"), RewardSignalUtil.value_estimates_key("curiosity"), ], ) trainer.trainer.update_buffer = buffer # when ghost trainer advance and wrapped trainer buffers full # the wrapped trainer pushes updated policy to correct queue assert policy_queue0.empty() and policy_queue1.empty() trainer.advance() assert not policy_queue0.empty() and policy_queue1.empty() if __name__ == "__main__": pytest.main()
ml-agents/ml-agents/mlagents/trainers/tests/torch_entities/test_ghost.py/0
{ "file_path": "ml-agents/ml-agents/mlagents/trainers/tests/torch_entities/test_ghost.py", "repo_id": "ml-agents", "token_count": 3236 }
1,991
from mlagents.torch_utils import torch from typing import List import math from mlagents.trainers.torch_entities.layers import ( linear_layer, Swish, Initialization, LayerNorm, ) class ConditionalEncoder(torch.nn.Module): def __init__( self, input_size: int, goal_size: int, hidden_size: int, num_layers: int, num_conditional_layers: int, kernel_init: Initialization = Initialization.KaimingHeNormal, kernel_gain: float = 1.0, ): """ ConditionalEncoder module. A fully connected network of which some of the weights are generated by a goal conditioning. Uses the HyperNetwork module to generate the weights of the network. Only the weights of the last "num_conditional_layers" layers will be generated by HyperNetworks, the others will use regular parameters. :param input_size: The size of the input of the encoder :param goal_size: The size of the goal tensor that will condition the encoder :param hidden_size: The number of hidden units in the encoder :param num_layers: The total number of layers of the encoder (both regular and generated by HyperNetwork) :param num_conditional_layers: The number of layers generated with hypernetworks :param kernel_init: The Initialization to use for the weights of the layer :param kernel_gain: The multiplier for the weights of the kernel. """ super().__init__() layers: List[torch.nn.Module] = [] prev_size = input_size for i in range(num_layers): if num_layers - i <= num_conditional_layers: # This means layer i is a conditional layer since the conditional # leyers are the last num_conditional_layers layers.append( HyperNetwork(prev_size, hidden_size, goal_size, hidden_size, 2) ) else: layers.append( linear_layer( prev_size, hidden_size, kernel_init=kernel_init, kernel_gain=kernel_gain, ) ) layers.append(Swish()) prev_size = hidden_size self.layers = torch.nn.ModuleList(layers) def forward( self, input_tensor: torch.Tensor, goal_tensor: torch.Tensor ) -> torch.Tensor: # type: ignore activation = input_tensor for layer in self.layers: if isinstance(layer, HyperNetwork): activation = layer(activation, goal_tensor) else: activation = layer(activation) return activation class HyperNetwork(torch.nn.Module): def __init__( self, input_size, output_size, hyper_input_size, layer_size, num_layers ): """ Hyper Network module. This module will use the hyper_input tensor to generate the weights of the main network. The main network is a single fully connected layer. :param input_size: The size of the input of the main network :param output_size: The size of the output of the main network :param hyper_input_size: The size of the input of the hypernetwork that will generate the main network. :param layer_size: The number of hidden units in the layers of the hypernetwork :param num_layers: The number of layers of the hypernetwork """ super().__init__() self.input_size = input_size self.output_size = output_size layer_in_size = hyper_input_size layers = [] for _ in range(num_layers): layers.append( linear_layer( layer_in_size, layer_size, kernel_init=Initialization.KaimingHeNormal, kernel_gain=1.0, bias_init=Initialization.Zero, ) ) layers.append(Swish()) layer_in_size = layer_size flat_output = linear_layer( layer_size, input_size * output_size, kernel_init=Initialization.KaimingHeNormal, kernel_gain=0.1, bias_init=Initialization.Zero, ) # Re-initializing the weights of the last layer of the hypernetwork bound = math.sqrt(1 / (layer_size * self.input_size)) flat_output.weight.data.uniform_(-bound, bound) self.hypernet = torch.nn.Sequential(*layers, LayerNorm(), flat_output) # The hypernetwork will not generate the bias of the main network layer self.bias = torch.nn.Parameter(torch.zeros(output_size)) def forward(self, input_activation, hyper_input): output_weights = self.hypernet(hyper_input) output_weights = output_weights.view(-1, self.input_size, self.output_size) result = ( torch.bmm(input_activation.unsqueeze(1), output_weights).squeeze(1) + self.bias ) return result
ml-agents/ml-agents/mlagents/trainers/torch_entities/conditioning.py/0
{ "file_path": "ml-agents/ml-agents/mlagents/trainers/torch_entities/conditioning.py", "repo_id": "ml-agents", "token_count": 2272 }
1,992
import copy import json import hmac import hashlib import sys from typing import Optional, Dict import mlagents_envs import mlagents.trainers from mlagents import torch_utils from mlagents.trainers.settings import RewardSignalType from mlagents_envs.exception import UnityCommunicationException from mlagents_envs.side_channel import ( IncomingMessage, OutgoingMessage, DefaultTrainingAnalyticsSideChannel, ) from mlagents_envs.communicator_objects.training_analytics_pb2 import ( TrainingEnvironmentInitialized, TrainingBehaviorInitialized, ) from google.protobuf.any_pb2 import Any from mlagents.trainers.settings import TrainerSettings, RunOptions class TrainingAnalyticsSideChannel(DefaultTrainingAnalyticsSideChannel): """ Side channel that sends information about the training to the Unity environment so it can be logged. """ __vendorKey: str = "unity.ml-agents" def __init__(self) -> None: # >>> uuid.uuid5(uuid.NAMESPACE_URL, "com.unity.ml-agents/TrainingAnalyticsSideChannel") # UUID('b664a4a9-d86f-5a5f-95cb-e8353a7e8356') # Use the same uuid as the parent side channel super().__init__() self.run_options: Optional[RunOptions] = None @classmethod def _hash(cls, data: str) -> str: res = hmac.new( cls.__vendorKey.encode("utf-8"), data.encode("utf-8"), hashlib.sha256 ).hexdigest() return res def on_message_received(self, msg: IncomingMessage) -> None: raise UnityCommunicationException( "The TrainingAnalyticsSideChannel received a message from Unity, " "this should not have happened." ) @classmethod def _sanitize_run_options(cls, config: RunOptions) -> Dict[str, Any]: res = copy.deepcopy(config.as_dict()) # Filter potentially PII behavior names if "behaviors" in res and res["behaviors"]: res["behaviors"] = {cls._hash(k): v for (k, v) in res["behaviors"].items()} for (k, v) in res["behaviors"].items(): if "init_path" in v and v["init_path"] is not None: hashed_path = cls._hash(v["init_path"]) res["behaviors"][k]["init_path"] = hashed_path if "demo_path" in v and v["demo_path"] is not None: hashed_path = cls._hash(v["demo_path"]) res["behaviors"][k]["demo_path"] = hashed_path # Filter potentially PII curriculum and behavior names from Checkpoint Settings if "environment_parameters" in res and res["environment_parameters"]: res["environment_parameters"] = { cls._hash(k): v for (k, v) in res["environment_parameters"].items() } for (curriculumName, curriculum) in res["environment_parameters"].items(): updated_lessons = [] for lesson in curriculum["curriculum"]: new_lesson = copy.deepcopy(lesson) if "name" in lesson: new_lesson["name"] = cls._hash(lesson["name"]) if ( "completion_criteria" in lesson and lesson["completion_criteria"] is not None ): new_lesson["completion_criteria"]["behavior"] = cls._hash( new_lesson["completion_criteria"]["behavior"] ) updated_lessons.append(new_lesson) res["environment_parameters"][curriculumName][ "curriculum" ] = updated_lessons # Filter potentially PII filenames from Checkpoint Settings if "checkpoint_settings" in res and res["checkpoint_settings"] is not None: if ( "initialize_from" in res["checkpoint_settings"] and res["checkpoint_settings"]["initialize_from"] is not None ): res["checkpoint_settings"]["initialize_from"] = cls._hash( res["checkpoint_settings"]["initialize_from"] ) if ( "results_dir" in res["checkpoint_settings"] and res["checkpoint_settings"]["results_dir"] is not None ): res["checkpoint_settings"]["results_dir"] = hash( res["checkpoint_settings"]["results_dir"] ) return res def environment_initialized(self, run_options: RunOptions) -> None: self.run_options = run_options # Tuple of (major, minor, patch) vi = sys.version_info env_params = run_options.environment_parameters sanitized_run_options = self._sanitize_run_options(run_options) msg = TrainingEnvironmentInitialized( python_version=f"{vi[0]}.{vi[1]}.{vi[2]}", mlagents_version=mlagents.trainers.__version__, mlagents_envs_version=mlagents_envs.__version__, torch_version=torch_utils.torch.__version__, torch_device_type=torch_utils.default_device().type, num_envs=run_options.env_settings.num_envs, num_environment_parameters=len(env_params) if env_params else 0, run_options=json.dumps(sanitized_run_options), ) any_message = Any() any_message.Pack(msg) env_init_msg = OutgoingMessage() env_init_msg.set_raw_bytes(any_message.SerializeToString()) super().queue_message_to_send(env_init_msg) @classmethod def _sanitize_trainer_settings(cls, config: TrainerSettings) -> Dict[str, Any]: config_dict = copy.deepcopy(config.as_dict()) if "init_path" in config_dict and config_dict["init_path"] is not None: hashed_path = cls._hash(config_dict["init_path"]) config_dict["init_path"] = hashed_path if "demo_path" in config_dict and config_dict["demo_path"] is not None: hashed_path = cls._hash(config_dict["demo_path"]) config_dict["demo_path"] = hashed_path return config_dict def training_started(self, behavior_name: str, config: TrainerSettings) -> None: raw_config = self._sanitize_trainer_settings(config) msg = TrainingBehaviorInitialized( behavior_name=self._hash(behavior_name), trainer_type=config.trainer_type, extrinsic_reward_enabled=( RewardSignalType.EXTRINSIC in config.reward_signals ), gail_reward_enabled=(RewardSignalType.GAIL in config.reward_signals), curiosity_reward_enabled=( RewardSignalType.CURIOSITY in config.reward_signals ), rnd_reward_enabled=(RewardSignalType.RND in config.reward_signals), behavioral_cloning_enabled=config.behavioral_cloning is not None, recurrent_enabled=config.network_settings.memory is not None, visual_encoder=config.network_settings.vis_encode_type.value, num_network_layers=config.network_settings.num_layers, num_network_hidden_units=config.network_settings.hidden_units, trainer_threaded=config.threaded, self_play_enabled=config.self_play is not None, curriculum_enabled=self._behavior_uses_curriculum(behavior_name), config=json.dumps(raw_config), ) any_message = Any() any_message.Pack(msg) training_start_msg = OutgoingMessage() training_start_msg.set_raw_bytes(any_message.SerializeToString()) super().queue_message_to_send(training_start_msg) def _behavior_uses_curriculum(self, behavior_name: str) -> bool: if not self.run_options or not self.run_options.environment_parameters: return False for param_settings in self.run_options.environment_parameters.values(): for lesson in param_settings.curriculum: cc = lesson.completion_criteria if cc and cc.behavior == behavior_name: return True return False
ml-agents/ml-agents/mlagents/trainers/training_analytics_side_channel.py/0
{ "file_path": "ml-agents/ml-agents/mlagents/trainers/training_analytics_side_channel.py", "repo_id": "ml-agents", "token_count": 3655 }
1,993
import argparse from .yamato_utils import init_venv def main(): parser = argparse.ArgumentParser() parser.add_argument("--mlagents-version", default=None) parser.add_argument("--extra-packages", default=None) args = parser.parse_args() extra_packages = [] if args.extra_packages is not None: extra_packages = args.extra_packages.split(",") init_venv( mlagents_python_version=args.mlagents_version, extra_packages=extra_packages ) if __name__ == "__main__": main()
ml-agents/ml-agents/tests/yamato/setup_venv.py/0
{ "file_path": "ml-agents/ml-agents/tests/yamato/setup_venv.py", "repo_id": "ml-agents", "token_count": 193 }
1,994
syntax = "proto3"; option csharp_namespace = "Unity.MLAgents.CommunicatorObjects"; package communicator_objects; message HeaderProto { int32 status = 1; string message = 2; }
ml-agents/protobuf-definitions/proto/mlagents_envs/communicator_objects/header.proto/0
{ "file_path": "ml-agents/protobuf-definitions/proto/mlagents_envs/communicator_objects/header.proto", "repo_id": "ml-agents", "token_count": 61 }
1,995
fileFormatVersion: 2 guid: 079ea0ed741ff194a80cce029630b5ac folderAsset: yes DefaultImporter: userData: assetBundleName: assetBundleVariant:
xLua/Assets/Plugins/Android/libs/x86.meta/0
{ "file_path": "xLua/Assets/Plugins/Android/libs/x86.meta", "repo_id": "xLua", "token_count": 62 }
1,996
fileFormatVersion: 2 guid: 92f9773841d5ffd44b794b9b584a5c05 timeCreated: 1504062948 licenseType: Pro PluginImporter: serializedVersion: 2 iconMap: {} executionOrder: {} isPreloaded: 0 isOverridable: 0 platformData: data: first: Any: second: enabled: 0 settings: {} data: first: Editor: Editor second: enabled: 0 settings: DefaultValueInitialized: true data: first: Facebook: WebGL second: enabled: 1 settings: {} data: first: WebGL: WebGL second: enabled: 1 settings: {} userData: assetBundleName: assetBundleVariant:
xLua/Assets/Plugins/WebGL/xlua_webgl.cpp.meta/0
{ "file_path": "xLua/Assets/Plugins/WebGL/xlua_webgl.cpp.meta", "repo_id": "xLua", "token_count": 348 }
1,997
fileFormatVersion: 2 guid: afd3fcbd8a9d48945b874adff2c0aa6d folderAsset: yes DefaultImporter: userData:
xLua/Assets/XLua/Examples/02_U3DScripting.meta/0
{ "file_path": "xLua/Assets/XLua/Examples/02_U3DScripting.meta", "repo_id": "xLua", "token_count": 48 }
1,998
fileFormatVersion: 2 guid: 554d570d8b369434ba8a099ebafee542 timeCreated: 1478591886 licenseType: Pro DefaultImporter: userData: assetBundleName: assetBundleVariant:
xLua/Assets/XLua/Examples/04_LuaObjectOrented/InvokeLua.unity.meta/0
{ "file_path": "xLua/Assets/XLua/Examples/04_LuaObjectOrented/InvokeLua.unity.meta", "repo_id": "xLua", "token_count": 72 }
1,999
using System; using UnityEditor; using UnityEngine; using CSObjectWrapEditor; using XLua; namespace XLuaTest { public static class BuildFromCLI { /// <summary> /// 此方法通过Unity菜单调用。 /// </summary> [MenuItem("XLua/Examples/13_BuildFromCLI")] public static void BuildFromUnityMenu() { var outputDir = Application.dataPath.Substring(0, Application.dataPath.Length - "/Assets".Length) + "/output"; var packageName = "xLuaGame.exe"; build(outputDir, packageName); } /// <summary> /// 此方法通过命令行调用。 /// </summary> public static void Build() { var outputDir = Application.dataPath.Substring(0, Application.dataPath.Length - "/Assets".Length) + "/output"; var packageName = "xLuaGame.exe"; build(outputDir, packageName); } private static void build(string outputDir, string packageName) { Debug.Log("构建开始:输出目录 " + outputDir); DelegateBridge.Gen_Flag = true; Generator.ClearAll(); Generator.GenAll(); var levels = new string[0]; var locationPathName = string.Format("{0}/{1}", outputDir, packageName); var target = BuildTarget.StandaloneWindows64; var options = BuildOptions.None; BuildPipeline.BuildPlayer(levels, locationPathName, target, options); Debug.Log("构建完成"); } } }
xLua/Assets/XLua/Examples/13_BuildFromCLI/Editor/BuildFromCLI.cs/0
{ "file_path": "xLua/Assets/XLua/Examples/13_BuildFromCLI/Editor/BuildFromCLI.cs", "repo_id": "xLua", "token_count": 728 }
2,000
fileFormatVersion: 2 guid: 5fa8c6bd6daed854c98654418f48a830 timeCreated: 1482482561 licenseType: Pro MonoImporter: serializedVersion: 2 defaultReferences: - Template: {fileID: 4900000, guid: 384feb229d259f549bbbac9e910b782b, type: 3} executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
xLua/Assets/XLua/Src/Editor/LinkXmlGen/LinkXmlGen.cs.meta/0
{ "file_path": "xLua/Assets/XLua/Src/Editor/LinkXmlGen/LinkXmlGen.cs.meta", "repo_id": "xLua", "token_count": 136 }
2,001
/* * Tencent is pleased to support the open source community by making xLua available. * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at * http://opensource.org/licenses/MIT * 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; namespace XLua { public enum GenFlag { No = 0, [Obsolete("use GCOptimizeAttribute instead")] GCOptimize = 1 } //如果你要生成Lua调用CSharp的代码,加这个标签 public class LuaCallCSharpAttribute : Attribute { GenFlag flag; public GenFlag Flag { get { return flag; } } public LuaCallCSharpAttribute(GenFlag flag = GenFlag.No) { this.flag = flag; } } //生成CSharp调用Lua,加这标签 //[AttributeUsage(AttributeTargets.Delegate | AttributeTargets.Interface)] public class CSharpCallLuaAttribute : Attribute { } //如果某属性、方法不需要生成,加这个标签 public class BlackListAttribute : Attribute { } [Flags] public enum OptimizeFlag { Default = 0, PackAsTable = 1 } //如果想对struct生成免GC代码,加这个标签 public class GCOptimizeAttribute : Attribute { OptimizeFlag flag; public OptimizeFlag Flag { get { return flag; } } public GCOptimizeAttribute(OptimizeFlag flag = OptimizeFlag.Default) { this.flag = flag; } } //如果想在反射下使用,加这个标签 public class ReflectionUseAttribute : Attribute { } //只能标注Dictionary<Type, List<string>>的field或者property public class DoNotGenAttribute : Attribute { } public class AdditionalPropertiesAttribute : Attribute { } [Flags] public enum HotfixFlag { Stateless = 0, [Obsolete("use xlua.util.state instead!", true)] Stateful = 1, ValueTypeBoxing = 2, IgnoreProperty = 4, IgnoreNotPublic = 8, Inline = 16, IntKey = 32, AdaptByDelegate = 64, IgnoreCompilerGenerated = 128, NoBaseProxy = 256, } public class HotfixAttribute : Attribute { HotfixFlag flag; public HotfixFlag Flag { get { return flag; } } public HotfixAttribute(HotfixFlag e = HotfixFlag.Stateless) { flag = e; } } [AttributeUsage(AttributeTargets.Delegate)] internal class HotfixDelegateAttribute : Attribute { } #if !XLUA_GENERAL public static class SysGenConfig { [GCOptimize] static List<Type> GCOptimize { get { return new List<Type>() { typeof(UnityEngine.Vector2), typeof(UnityEngine.Vector3), typeof(UnityEngine.Vector4), typeof(UnityEngine.Color), typeof(UnityEngine.Quaternion), typeof(UnityEngine.Ray), typeof(UnityEngine.Bounds), typeof(UnityEngine.Ray2D), }; } } [AdditionalProperties] static Dictionary<Type, List<string>> AdditionalProperties { get { return new Dictionary<Type, List<string>>() { { typeof(UnityEngine.Ray), new List<string>() { "origin", "direction" } }, { typeof(UnityEngine.Ray2D), new List<string>() { "origin", "direction" } }, { typeof(UnityEngine.Bounds), new List<string>() { "center", "extents" } }, }; } } } #endif }
xLua/Assets/XLua/Src/GenAttributes.cs/0
{ "file_path": "xLua/Assets/XLua/Src/GenAttributes.cs", "repo_id": "xLua", "token_count": 2122 }
2,002
/* * Tencent is pleased to support the open source community by making xLua available. * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at * http://opensource.org/licenses/MIT * 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. */ #if USE_UNI_LUA using LuaAPI = UniLua.Lua; using RealStatePtr = UniLua.ILuaState; using LuaCSFunction = UniLua.CSharpFunctionDelegate; #else using LuaAPI = XLua.LuaDLL.Lua; using RealStatePtr = System.IntPtr; using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; #endif using System; using System.Collections.Generic; using System.Text; using System.Collections; namespace XLua { public partial class LuaTable : LuaBase { public LuaTable(int reference, LuaEnv luaenv) : base(reference, luaenv) { } // no boxing version get public void Get<TKey, TValue>(TKey key, out TValue value) { #if THREAD_SAFE || HOTFIX_ENABLE lock (luaEnv.luaEnvLock) { #endif var L = luaEnv.L; var translator = luaEnv.translator; int oldTop = LuaAPI.lua_gettop(L); LuaAPI.lua_getref(L, luaReference); translator.PushByType(L, key); if (0 != LuaAPI.xlua_pgettable(L, -2)) { string err = LuaAPI.lua_tostring(L, -1); LuaAPI.lua_settop(L, oldTop); throw new Exception("get field [" + key + "] error:" + err); } LuaTypes lua_type = LuaAPI.lua_type(L, -1); Type type_of_value = typeof(TValue); if (lua_type == LuaTypes.LUA_TNIL && type_of_value.IsValueType()) { throw new InvalidCastException("can not assign nil to " + type_of_value.GetFriendlyName()); } try { translator.Get(L, -1, out value); } catch (Exception e) { throw e; } finally { LuaAPI.lua_settop(L, oldTop); } #if THREAD_SAFE || HOTFIX_ENABLE } #endif } // no boxing version get public bool ContainsKey<TKey>(TKey key) { #if THREAD_SAFE || HOTFIX_ENABLE lock (luaEnv.luaEnvLock) { #endif var L = luaEnv.L; var translator = luaEnv.translator; int oldTop = LuaAPI.lua_gettop(L); LuaAPI.lua_getref(L, luaReference); translator.PushByType(L, key); if (0 != LuaAPI.xlua_pgettable(L, -2)) { string err = LuaAPI.lua_tostring(L, -1); LuaAPI.lua_settop(L, oldTop); throw new Exception("get field [" + key + "] error:" + err); } bool ret = LuaAPI.lua_type(L, -1) != LuaTypes.LUA_TNIL; LuaAPI.lua_settop(L, oldTop); return ret; #if THREAD_SAFE || HOTFIX_ENABLE } #endif } //no boxing version set public void Set<TKey, TValue>(TKey key, TValue value) { #if THREAD_SAFE || HOTFIX_ENABLE lock (luaEnv.luaEnvLock) { #endif var L = luaEnv.L; int oldTop = LuaAPI.lua_gettop(L); var translator = luaEnv.translator; LuaAPI.lua_getref(L, luaReference); translator.PushByType(L, key); translator.PushByType(L, value); if (0 != LuaAPI.xlua_psettable(L, -3)) { luaEnv.ThrowExceptionFromError(oldTop); } LuaAPI.lua_settop(L, oldTop); #if THREAD_SAFE || HOTFIX_ENABLE } #endif } public T GetInPath<T>(string path) { #if THREAD_SAFE || HOTFIX_ENABLE lock (luaEnv.luaEnvLock) { #endif var L = luaEnv.L; var translator = luaEnv.translator; int oldTop = LuaAPI.lua_gettop(L); LuaAPI.lua_getref(L, luaReference); if (0 != LuaAPI.xlua_pgettable_bypath(L, -1, path)) { luaEnv.ThrowExceptionFromError(oldTop); } LuaTypes lua_type = LuaAPI.lua_type(L, -1); if (lua_type == LuaTypes.LUA_TNIL && typeof(T).IsValueType()) { throw new InvalidCastException("can not assign nil to " + typeof(T).GetFriendlyName()); } T value; try { translator.Get(L, -1, out value); } catch (Exception e) { throw e; } finally { LuaAPI.lua_settop(L, oldTop); } return value; #if THREAD_SAFE || HOTFIX_ENABLE } #endif } public void SetInPath<T>(string path, T val) { #if THREAD_SAFE || HOTFIX_ENABLE lock (luaEnv.luaEnvLock) { #endif var L = luaEnv.L; int oldTop = LuaAPI.lua_gettop(L); LuaAPI.lua_getref(L, luaReference); luaEnv.translator.PushByType(L, val); if (0 != LuaAPI.xlua_psettable_bypath(L, -2, path)) { luaEnv.ThrowExceptionFromError(oldTop); } LuaAPI.lua_settop(L, oldTop); #if THREAD_SAFE || HOTFIX_ENABLE } #endif } [Obsolete("use no boxing version: GetInPath/SetInPath Get/Set instead!")] public object this[string field] { get { return GetInPath<object>(field); } set { SetInPath(field, value); } } [Obsolete("use no boxing version: GetInPath/SetInPath Get/Set instead!")] public object this[object field] { get { return Get<object>(field); } set { Set(field, value); } } public void ForEach<TKey, TValue>(Action<TKey, TValue> action) { #if THREAD_SAFE || HOTFIX_ENABLE lock (luaEnv.luaEnvLock) { #endif var L = luaEnv.L; var translator = luaEnv.translator; int oldTop = LuaAPI.lua_gettop(L); try { LuaAPI.lua_getref(L, luaReference); LuaAPI.lua_pushnil(L); while (LuaAPI.lua_next(L, -2) != 0) { if (translator.Assignable<TKey>(L, -2)) { TKey key; TValue val; translator.Get(L, -2, out key); translator.Get(L, -1, out val); action(key, val); } LuaAPI.lua_pop(L, 1); } } finally { LuaAPI.lua_settop(L, oldTop); } #if THREAD_SAFE || HOTFIX_ENABLE } #endif } public int Length { get { #if THREAD_SAFE || HOTFIX_ENABLE lock (luaEnv.luaEnvLock) { #endif var L = luaEnv.L; int oldTop = LuaAPI.lua_gettop(L); LuaAPI.lua_getref(L, luaReference); var len = (int)LuaAPI.xlua_objlen(L, -1); LuaAPI.lua_settop(L, oldTop); return len; #if THREAD_SAFE || HOTFIX_ENABLE } #endif } } #if THREAD_SAFE || HOTFIX_ENABLE [Obsolete("not thread safe!", true)] #endif public IEnumerable GetKeys() { var L = luaEnv.L; var translator = luaEnv.translator; int oldTop = LuaAPI.lua_gettop(L); LuaAPI.lua_getref(L, luaReference); LuaAPI.lua_pushnil(L); while (LuaAPI.lua_next(L, -2) != 0) { yield return translator.GetObject(L, -2); LuaAPI.lua_pop(L, 1); } LuaAPI.lua_settop(L, oldTop); } #if THREAD_SAFE || HOTFIX_ENABLE [Obsolete("not thread safe!", true)] #endif public IEnumerable<T> GetKeys<T>() { var L = luaEnv.L; var translator = luaEnv.translator; int oldTop = LuaAPI.lua_gettop(L); LuaAPI.lua_getref(L, luaReference); LuaAPI.lua_pushnil(L); while (LuaAPI.lua_next(L, -2) != 0) { if (translator.Assignable<T>(L, -2)) { T v; translator.Get(L, -2, out v); yield return v; } LuaAPI.lua_pop(L, 1); } LuaAPI.lua_settop(L, oldTop); } [Obsolete("use no boxing version: Get<TKey, TValue> !")] public T Get<T>(object key) { T ret; Get(key, out ret); return ret; } public TValue Get<TKey, TValue>(TKey key) { TValue ret; Get(key, out ret); return ret; } public TValue Get<TValue>(string key) { TValue ret; Get(key, out ret); return ret; } public void SetMetaTable(LuaTable metaTable) { #if THREAD_SAFE || HOTFIX_ENABLE lock (luaEnv.luaEnvLock) { #endif push(luaEnv.L); metaTable.push(luaEnv.L); LuaAPI.lua_setmetatable(luaEnv.L, -2); LuaAPI.lua_pop(luaEnv.L, 1); #if THREAD_SAFE || HOTFIX_ENABLE } #endif } public T Cast<T>() { var L = luaEnv.L; var translator = luaEnv.translator; #if THREAD_SAFE || HOTFIX_ENABLE lock (luaEnv.luaEnvLock) { #endif push(L); T ret = (T)translator.GetObject(L, -1, typeof(T)); LuaAPI.lua_pop(luaEnv.L, 1); return ret; #if THREAD_SAFE || HOTFIX_ENABLE } #endif } internal override void push(RealStatePtr L) { LuaAPI.lua_getref(L, luaReference); } public override string ToString() { return "table :" + luaReference; } } }
xLua/Assets/XLua/Src/LuaTable.cs/0
{ "file_path": "xLua/Assets/XLua/Src/LuaTable.cs", "repo_id": "xLua", "token_count": 6594 }
2,003
/* * Tencent is pleased to support the open source community by making xLua available. * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at * http://opensource.org/licenses/MIT * 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. */ #if USE_UNI_LUA using LuaAPI = UniLua.Lua; using RealStatePtr = UniLua.ILuaState; using LuaCSFunction = UniLua.CSharpFunctionDelegate; #else using LuaAPI = XLua.LuaDLL.Lua; using RealStatePtr = System.IntPtr; using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; #endif namespace XLua { using System; using System.IO; using System.Reflection; public partial class StaticLuaCallbacks { internal LuaCSFunction GcMeta, ToStringMeta, EnumAndMeta, EnumOrMeta; internal LuaCSFunction StaticCSFunctionWraper, FixCSFunctionWraper; internal LuaCSFunction DelegateCtor; public StaticLuaCallbacks() { GcMeta = new LuaCSFunction(StaticLuaCallbacks.LuaGC); ToStringMeta = new LuaCSFunction(StaticLuaCallbacks.ToString); EnumAndMeta = new LuaCSFunction(EnumAnd); EnumOrMeta = new LuaCSFunction(EnumOr); StaticCSFunctionWraper = new LuaCSFunction(StaticLuaCallbacks.StaticCSFunction); FixCSFunctionWraper = new LuaCSFunction(StaticLuaCallbacks.FixCSFunction); DelegateCtor = new LuaCSFunction(DelegateConstructor); } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int EnumAnd(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); object left = translator.FastGetCSObj(L, 1); object right = translator.FastGetCSObj(L, 2); Type typeOfLeft = left.GetType(); if (!typeOfLeft.IsEnum() || typeOfLeft != right.GetType()) { return LuaAPI.luaL_error(L, "invalid argument for Enum BitwiseAnd"); } translator.PushAny(L, Enum.ToObject(typeOfLeft, Convert.ToInt64(left) & Convert.ToInt64(right))); return 1; } catch (Exception e) { return LuaAPI.luaL_error(L, "c# exception in Enum BitwiseAnd:" + e); } } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int EnumOr(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); object left = translator.FastGetCSObj(L, 1); object right = translator.FastGetCSObj(L, 2); Type typeOfLeft = left.GetType(); if (!typeOfLeft.IsEnum() || typeOfLeft != right.GetType()) { return LuaAPI.luaL_error(L, "invalid argument for Enum BitwiseOr"); } translator.PushAny(L, Enum.ToObject(typeOfLeft, Convert.ToInt64(left) | Convert.ToInt64(right))); return 1; } catch (Exception e) { return LuaAPI.luaL_error(L, "c# exception in Enum BitwiseOr:" + e); } } [MonoPInvokeCallback(typeof(LuaCSFunction))] static int StaticCSFunction(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); LuaCSFunction func = (LuaCSFunction)translator.FastGetCSObj(L, LuaAPI.xlua_upvalueindex(1)); return func(L); } catch (Exception e) { return LuaAPI.luaL_error(L, "c# exception in StaticCSFunction:" + e); } } [MonoPInvokeCallback(typeof(LuaCSFunction))] static int FixCSFunction(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); int idx = LuaAPI.xlua_tointeger(L, LuaAPI.xlua_upvalueindex(1)); LuaCSFunction func = (LuaCSFunction)translator.GetFixCSFunction(idx); return func(L); } catch (Exception e) { return LuaAPI.luaL_error(L, "c# exception in FixCSFunction:" + e); } } #if GEN_CODE_MINIMIZE [MonoPInvokeCallback(typeof(LuaDLL.CSharpWrapperCaller))] internal static int CSharpWrapperCallerImpl(RealStatePtr L, int funcidx, int top) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); return translator.CallCSharpWrapper(L, funcidx, top); } catch (Exception e) { return LuaAPI.luaL_error(L, "c# exception:" + e); } } #endif #if GEN_CODE_MINIMIZE public static int DelegateCall(RealStatePtr L, int top) #else [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int DelegateCall(RealStatePtr L) #endif { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); object objDelegate = translator.FastGetCSObj(L, 1); if (objDelegate == null || !(objDelegate is Delegate)) { return LuaAPI.luaL_error(L, "trying to invoke a value that is not delegate nor callable"); } return translator.methodWrapsCache.GetDelegateWrap(objDelegate.GetType())(L); } catch (Exception e) { return LuaAPI.luaL_error(L, "c# exception in DelegateCall:" + e); } } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int LuaGC(RealStatePtr L) { try { int udata = LuaAPI.xlua_tocsobj_safe(L, 1); if (udata != -1) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); if ( translator != null ) { translator.collectObject(udata); } } return 0; } catch (Exception e) { return LuaAPI.luaL_error(L, "c# exception in LuaGC:" + e); } } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int ToString(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); object obj = translator.FastGetCSObj(L, 1); translator.PushAny(L, obj != null ? (obj.ToString() + ": " + obj.GetHashCode()) : "<invalid c# object>"); return 1; } catch (Exception e) { return LuaAPI.luaL_error(L, "c# exception in ToString:" + e); } } #if GEN_CODE_MINIMIZE public static int DelegateCombine(RealStatePtr L, int top) #else [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int DelegateCombine(RealStatePtr L) #endif { try { var translator = ObjectTranslatorPool.Instance.Find(L); Type type = translator.FastGetCSObj(L, LuaAPI.lua_type(L, 1) == LuaTypes.LUA_TUSERDATA ? 1 : 2).GetType(); Delegate d1 = translator.GetObject(L, 1, type) as Delegate; Delegate d2 = translator.GetObject(L, 2, type) as Delegate; if (d1 == null || d2 == null) { return LuaAPI.luaL_error(L, "one parameter must be a delegate, other one must be delegate or function"); } translator.PushAny(L, Delegate.Combine(d1, d2)); return 1; } catch (Exception e) { return LuaAPI.luaL_error(L, "c# exception in DelegateCombine:" + e); } } #if GEN_CODE_MINIMIZE public static int DelegateRemove(RealStatePtr L, int top) #else [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int DelegateRemove(RealStatePtr L) #endif { try { var translator = ObjectTranslatorPool.Instance.Find(L); Delegate d1 = translator.FastGetCSObj(L, 1) as Delegate; if (d1 == null) { return LuaAPI.luaL_error(L, "#1 parameter must be a delegate"); } Delegate d2 = translator.GetObject(L, 2, d1.GetType()) as Delegate; if (d2 == null) { return LuaAPI.luaL_error(L, "#2 parameter must be a delegate or a function "); } translator.PushAny(L, Delegate.Remove(d1, d2)); return 1; } catch (Exception e) { return LuaAPI.luaL_error(L, "c# exception in DelegateRemove:" + e); } } static bool tryPrimitiveArrayGet(Type type, RealStatePtr L, object obj, int index) { bool ok = true; if (type == typeof(int[])) { int[] array = obj as int[]; LuaAPI.xlua_pushinteger(L, array[index]); } else if (type == typeof(float[])) { float[] array = obj as float[]; LuaAPI.lua_pushnumber(L, array[index]); } else if (type == typeof(double[])) { double[] array = obj as double[]; LuaAPI.lua_pushnumber(L, array[index]); } else if (type == typeof(bool[])) { bool[] array = obj as bool[]; LuaAPI.lua_pushboolean(L, array[index]); } else if (type == typeof(long[])) { long[] array = obj as long[]; LuaAPI.lua_pushint64(L, array[index]); } else if (type == typeof(ulong[])) { ulong[] array = obj as ulong[]; LuaAPI.lua_pushuint64(L, array[index]); } else if (type == typeof(sbyte[])) { sbyte[] array = obj as sbyte[]; LuaAPI.xlua_pushinteger(L, array[index]); } else if (type == typeof(short[])) { short[] array = obj as short[]; LuaAPI.xlua_pushinteger(L, array[index]); } else if (type == typeof(ushort[])) { ushort[] array = obj as ushort[]; LuaAPI.xlua_pushinteger(L, array[index]); } else if (type == typeof(char[])) { char[] array = obj as char[]; LuaAPI.xlua_pushinteger(L, array[index]); } else if (type == typeof(uint[])) { uint[] array = obj as uint[]; LuaAPI.xlua_pushuint(L, array[index]); } else if (type == typeof(IntPtr[])) { IntPtr[] array = obj as IntPtr[]; LuaAPI.lua_pushlightuserdata(L, array[index]); } else if (type == typeof(decimal[])) { decimal[] array = obj as decimal[]; ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); translator.PushDecimal(L, array[index]); } else if (type == typeof(string[])) { string[] array = obj as string[]; LuaAPI.lua_pushstring(L, array[index]); } else { ok = false; } return ok; } #if GEN_CODE_MINIMIZE public static int ArrayIndexer(RealStatePtr L, int top) #else [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int ArrayIndexer(RealStatePtr L) #endif { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); System.Array array = (System.Array)translator.FastGetCSObj(L, 1); if (array == null) { return LuaAPI.luaL_error(L, "#1 parameter is not a array!"); } int i = LuaAPI.xlua_tointeger(L, 2); if (i >= array.Length) { return LuaAPI.luaL_error(L, "index out of range! i =" + i + ", array.Length=" + array.Length); } Type type = array.GetType(); if (tryPrimitiveArrayGet(type, L, array, i)) { return 1; } if (InternalGlobals.genTryArrayGetPtr != null) { try { if (InternalGlobals.genTryArrayGetPtr(type, L, translator, array, i)) { return 1; } } catch (Exception e) { return LuaAPI.luaL_error(L, "c# exception:" + e.Message + ",stack:" + e.StackTrace); } } object ret = array.GetValue(i); translator.PushAny(L, ret); return 1; } catch (Exception e) { return LuaAPI.luaL_error(L, "c# exception in ArrayIndexer:" + e); } } public static bool TryPrimitiveArraySet(Type type, RealStatePtr L, object obj, int array_idx, int obj_idx) { bool ok = true; LuaTypes lua_type = LuaAPI.lua_type(L, obj_idx); if (type == typeof(int[]) && lua_type == LuaTypes.LUA_TNUMBER) { int[] array = obj as int[]; array[array_idx] = LuaAPI.xlua_tointeger(L, obj_idx); } else if (type == typeof(float[]) && lua_type == LuaTypes.LUA_TNUMBER) { float[] array = obj as float[]; array[array_idx] = (float)LuaAPI.lua_tonumber(L, obj_idx); } else if (type == typeof(double[]) && lua_type == LuaTypes.LUA_TNUMBER) { double[] array = obj as double[]; array[array_idx] = LuaAPI.lua_tonumber(L, obj_idx); ; } else if (type == typeof(bool[]) && lua_type == LuaTypes.LUA_TBOOLEAN) { bool[] array = obj as bool[]; array[array_idx] = LuaAPI.lua_toboolean(L, obj_idx); } else if (type == typeof(long[]) && LuaAPI.lua_isint64(L, obj_idx)) { long[] array = obj as long[]; array[array_idx] = LuaAPI.lua_toint64(L, obj_idx); } else if (type == typeof(ulong[]) && LuaAPI.lua_isuint64(L, obj_idx)) { ulong[] array = obj as ulong[]; array[array_idx] = LuaAPI.lua_touint64(L, obj_idx); } else if (type == typeof(sbyte[]) && lua_type == LuaTypes.LUA_TNUMBER) { sbyte[] array = obj as sbyte[]; array[array_idx] = (sbyte)LuaAPI.xlua_tointeger(L, obj_idx); } else if (type == typeof(short[]) && lua_type == LuaTypes.LUA_TNUMBER) { short[] array = obj as short[]; array[array_idx] = (short)LuaAPI.xlua_tointeger(L, obj_idx); } else if (type == typeof(ushort[]) && lua_type == LuaTypes.LUA_TNUMBER) { ushort[] array = obj as ushort[]; array[array_idx] = (ushort)LuaAPI.xlua_tointeger(L, obj_idx); } else if (type == typeof(char[]) && lua_type == LuaTypes.LUA_TNUMBER) { char[] array = obj as char[]; array[array_idx] = (char)LuaAPI.xlua_tointeger(L, obj_idx); } else if (type == typeof(uint[]) && lua_type == LuaTypes.LUA_TNUMBER) { uint[] array = obj as uint[]; array[array_idx] = LuaAPI.xlua_touint(L, obj_idx); } else if (type == typeof(IntPtr[]) && lua_type == LuaTypes.LUA_TLIGHTUSERDATA) { IntPtr[] array = obj as IntPtr[]; array[array_idx] = LuaAPI.lua_touserdata(L, obj_idx); } else if (type == typeof(decimal[])) { decimal[] array = obj as decimal[]; if (lua_type == LuaTypes.LUA_TNUMBER) { array[array_idx] = (decimal)LuaAPI.lua_tonumber(L, obj_idx); } if (lua_type == LuaTypes.LUA_TUSERDATA) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); if (translator.IsDecimal(L, obj_idx)) { translator.Get(L, obj_idx, out array[array_idx]); } else { ok = false; } } else { ok = false; } } else if (type == typeof(string[]) && lua_type == LuaTypes.LUA_TSTRING) { string[] array = obj as string[]; array[array_idx] = LuaAPI.lua_tostring(L, obj_idx); } else { ok = false; } return ok; } #if GEN_CODE_MINIMIZE public static int ArrayNewIndexer(RealStatePtr L, int top) #else [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int ArrayNewIndexer(RealStatePtr L) #endif { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); System.Array array = (System.Array)translator.FastGetCSObj(L, 1); if (array == null) { return LuaAPI.luaL_error(L, "#1 parameter is not a array!"); } int i = LuaAPI.xlua_tointeger(L, 2); if (i >= array.Length) { return LuaAPI.luaL_error(L, "index out of range! i =" + i + ", array.Length=" + array.Length); } Type type = array.GetType(); if (TryPrimitiveArraySet(type, L, array, i, 3)) { return 0; } if (InternalGlobals.genTryArraySetPtr != null) { try { if (InternalGlobals.genTryArraySetPtr(type, L, translator, array, i, 3)) { return 0; } } catch (Exception e) { return LuaAPI.luaL_error(L, "c# exception:" + e.Message + ",stack:" + e.StackTrace); } } object val = translator.GetObject(L, 3, type.GetElementType()); array.SetValue(val, i); return 0; } catch (Exception e) { return LuaAPI.luaL_error(L, "c# exception in ArrayNewIndexer:" + e); } } #if GEN_CODE_MINIMIZE public static int ArrayLength(RealStatePtr L, int top) #else [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int ArrayLength(RealStatePtr L) #endif { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); System.Array array = (System.Array)translator.FastGetCSObj(L, 1); LuaAPI.xlua_pushinteger(L, array.Length); return 1; } catch (System.Exception e) { return LuaAPI.luaL_error(L, "c# exception in ArrayLength:" + e); } } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int MetaFuncIndex(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Type type = translator.FastGetCSObj(L, 2) as Type; if (type == null) { return LuaAPI.luaL_error(L, "#2 param need a System.Type!"); } //UnityEngine.Debug.Log("============================load type by __index:" + type); //translator.TryDelayWrapLoader(L, type); translator.GetTypeId(L, type); LuaAPI.lua_pushvalue(L, 2); LuaAPI.lua_rawget(L, 1); return 1; } catch (System.Exception e) { return LuaAPI.luaL_error(L, "c# exception in MetaFuncIndex:" + e); } } [MonoPInvokeCallback(typeof(LuaCSFunction))] internal static int Panic(RealStatePtr L) { string reason = String.Format("unprotected error in call to Lua API ({0})", LuaAPI.lua_tostring(L, -1)); throw new LuaException(reason); } #if !XLUA_GENERAL [MonoPInvokeCallback(typeof(LuaCSFunction))] internal static int Print(RealStatePtr L) { try { int n = LuaAPI.lua_gettop(L); string s = String.Empty; if (0 != LuaAPI.xlua_getglobal(L, "tostring")) { return LuaAPI.luaL_error(L, "can not get tostring in print:"); } for (int i = 1; i <= n; i++) { LuaAPI.lua_pushvalue(L, -1); /* function to be called */ LuaAPI.lua_pushvalue(L, i); /* value to print */ if (0 != LuaAPI.lua_pcall(L, 1, 1, 0)) { return LuaAPI.lua_error(L); } s += LuaAPI.lua_tostring(L, -1); if (i != n) s += "\t"; LuaAPI.lua_pop(L, 1); /* pop result */ } UnityEngine.Debug.Log("LUA: " + s); return 0; } catch (System.Exception e) { return LuaAPI.luaL_error(L, "c# exception in print:" + e); } } #endif #if (!UNITY_SWITCH && !UNITY_WEBGL) || UNITY_EDITOR [MonoPInvokeCallback(typeof(LuaCSFunction))] internal static int LoadSocketCore(RealStatePtr L) { return LuaAPI.luaopen_socket_core(L); } #endif [MonoPInvokeCallback(typeof(LuaCSFunction))] internal static int LoadCS(RealStatePtr L) { LuaAPI.xlua_pushasciistring(L, LuaEnv.CSHARP_NAMESPACE); LuaAPI.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX); return 1; } [MonoPInvokeCallback(typeof(LuaCSFunction))] internal static int LoadBuiltinLib(RealStatePtr L) { try { string builtin_lib = LuaAPI.lua_tostring(L, 1); LuaEnv self = ObjectTranslatorPool.Instance.Find(L).luaEnv; LuaCSFunction initer; if (self.buildin_initer.TryGetValue(builtin_lib, out initer)) { LuaAPI.lua_pushstdcallcfunction(L, initer); } else { LuaAPI.lua_pushstring(L, string.Format( "\n\tno such builtin lib '{0}'", builtin_lib)); } return 1; } catch (System.Exception e) { return LuaAPI.luaL_error(L, "c# exception in LoadBuiltinLib:" + e); } } #if !XLUA_GENERAL [MonoPInvokeCallback(typeof(LuaCSFunction))] internal static int LoadFromResource(RealStatePtr L) { try { string filename = LuaAPI.lua_tostring(L, 1).Replace('.', '/') + ".lua"; // Load with Unity3D resources UnityEngine.TextAsset file = (UnityEngine.TextAsset)UnityEngine.Resources.Load(filename); if (file == null) { LuaAPI.lua_pushstring(L, string.Format( "\n\tno such resource '{0}'", filename)); } else { if (LuaAPI.xluaL_loadbuffer(L, file.bytes, file.bytes.Length, "@" + filename) != 0) { return LuaAPI.luaL_error(L, String.Format("error loading module {0} from resource, {1}", LuaAPI.lua_tostring(L, 1), LuaAPI.lua_tostring(L, -1))); } } return 1; } catch (System.Exception e) { return LuaAPI.luaL_error(L, "c# exception in LoadFromResource:" + e); } } [MonoPInvokeCallback(typeof(LuaCSFunction))] internal static int LoadFromStreamingAssetsPath(RealStatePtr L) { try { string filename = LuaAPI.lua_tostring(L, 1).Replace('.', '/') + ".lua"; var filepath = UnityEngine.Application.streamingAssetsPath + "/" + filename; #if UNITY_ANDROID && !UNITY_EDITOR UnityEngine.WWW www = new UnityEngine.WWW(filepath); while (true) { if (www.isDone || !string.IsNullOrEmpty(www.error)) { System.Threading.Thread.Sleep(50); //�Ƚ�hacker������ if (!string.IsNullOrEmpty(www.error)) { LuaAPI.lua_pushstring(L, string.Format( "\n\tno such file '{0}' in streamingAssetsPath!", filename)); } else { UnityEngine.Debug.LogWarning("load lua file from StreamingAssets is obsolete, filename:" + filename); if (LuaAPI.xluaL_loadbuffer(L, www.bytes, www.bytes.Length , "@" + filename) != 0) { return LuaAPI.luaL_error(L, String.Format("error loading module {0} from streamingAssetsPath, {1}", LuaAPI.lua_tostring(L, 1), LuaAPI.lua_tostring(L, -1))); } } break; } } #else if (File.Exists(filepath)) { // string text = File.ReadAllText(filepath); var bytes = File.ReadAllBytes(filepath); UnityEngine.Debug.LogWarning("load lua file from StreamingAssets is obsolete, filename:" + filename); if (LuaAPI.xluaL_loadbuffer(L, bytes, bytes.Length, "@" + filename) != 0) { return LuaAPI.luaL_error(L, String.Format("error loading module {0} from streamingAssetsPath, {1}", LuaAPI.lua_tostring(L, 1), LuaAPI.lua_tostring(L, -1))); } } else { LuaAPI.lua_pushstring(L, string.Format( "\n\tno such file '{0}' in streamingAssetsPath!", filename)); } #endif return 1; } catch (System.Exception e) { return LuaAPI.luaL_error(L, "c# exception in LoadFromStreamingAssetsPath:" + e); } } #endif [MonoPInvokeCallback(typeof(LuaCSFunction))] internal static int LoadFromCustomLoaders(RealStatePtr L) { try { string filename = LuaAPI.lua_tostring(L, 1); LuaEnv self = ObjectTranslatorPool.Instance.Find(L).luaEnv; foreach (var loader in self.customLoaders) { string real_file_path = filename; byte[] bytes = loader(ref real_file_path); if (bytes != null) { if (LuaAPI.xluaL_loadbuffer(L, bytes, bytes.Length, "@" + real_file_path) != 0) { return LuaAPI.luaL_error(L, String.Format("error loading module {0} from CustomLoader, {1}", LuaAPI.lua_tostring(L, 1), LuaAPI.lua_tostring(L, -1))); } return 1; } } LuaAPI.lua_pushstring(L, string.Format( "\n\tno such file '{0}' in CustomLoaders!", filename)); return 1; } catch (System.Exception e) { return LuaAPI.luaL_error(L, "c# exception in LoadFromCustomLoaders:" + e); } } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int LoadAssembly(RealStatePtr L) { #if UNITY_WSA && !UNITY_EDITOR return LuaAPI.luaL_error(L, "xlua.load_assembly no support in uwp!"); #else try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); string assemblyName = LuaAPI.lua_tostring(L, 1); Assembly assembly = null; try { assembly = Assembly.Load(assemblyName); } catch (BadImageFormatException) { // The assemblyName was invalid. It is most likely a path. } if (assembly == null) { assembly = Assembly.Load(AssemblyName.GetAssemblyName(assemblyName)); } if (assembly != null && !translator.assemblies.Contains(assembly)) { translator.assemblies.Add(assembly); } return 0; } catch (System.Exception e) { return LuaAPI.luaL_error(L, "c# exception in xlua.load_assembly:" + e); } #endif } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int ImportType(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); string className = LuaAPI.lua_tostring(L, 1); Type type = translator.FindType(className); if (type != null) { if (translator.GetTypeId(L, type) >= 0) { LuaAPI.lua_pushboolean(L, true); } else { return LuaAPI.luaL_error(L, "can not load type " + type); } } else { LuaAPI.lua_pushnil(L); } return 1; } catch (System.Exception e) { return LuaAPI.luaL_error(L, "c# exception in xlua.import_type:" + e); } } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int ImportGenericType(RealStatePtr L) { try { int top = LuaAPI.lua_gettop(L); if (top < 2) return LuaAPI.luaL_error(L, "import generic type need at lease 2 arguments"); ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); string className = LuaAPI.lua_tostring(L, 1); if (className.EndsWith("<>")) className = className.Substring(0, className.Length - 2); Type genericDef = translator.FindType(className + "`" + (top - 1)); if (genericDef == null || !genericDef.IsGenericTypeDefinition()) { LuaAPI.lua_pushnil(L); } else { Type[] typeArguments = new Type[top - 1]; for(int i = 2; i <= top; i++) { typeArguments[i - 2] = getType(L, translator, i); if (typeArguments[i - 2] == null) { return LuaAPI.luaL_error(L, "param need a type"); } } Type genericInc = genericDef.MakeGenericType(typeArguments); translator.GetTypeId(L, genericInc); translator.PushAny(L, genericInc); } return 1; } catch (System.Exception e) { return LuaAPI.luaL_error(L, "c# exception in xlua.import_type:" + e); } } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int Cast(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Type type; translator.Get(L, 2, out type); if (type == null) { return LuaAPI.luaL_error(L, "#2 param[" + LuaAPI.lua_tostring(L, 2) + "]is not valid type indicator"); } LuaAPI.luaL_getmetatable(L, type.FullName); if (LuaAPI.lua_isnil(L, -1)) { return LuaAPI.luaL_error(L, "no gen code for " + LuaAPI.lua_tostring(L, 2)); } LuaAPI.lua_setmetatable(L, 1); return 0; } catch (System.Exception e) { return LuaAPI.luaL_error(L, "c# exception in xlua.cast:" + e); } } static Type getType(RealStatePtr L, ObjectTranslator translator, int idx) { if (LuaAPI.lua_type(L, idx) == LuaTypes.LUA_TTABLE) { LuaTable tbl; translator.Get(L, idx, out tbl); return tbl.Get<Type>("UnderlyingSystemType"); } else if (LuaAPI.lua_type(L, idx) == LuaTypes.LUA_TSTRING) { string className = LuaAPI.lua_tostring(L, idx); return translator.FindType(className); } else if (translator.GetObject(L, idx) is Type) { return translator.GetObject(L, idx) as Type; } else { return null; } } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int XLuaAccess(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Type type = getType(L, translator, 1); object obj = null; if (type == null && LuaAPI.lua_type(L, 1) == LuaTypes.LUA_TUSERDATA) { obj = translator.SafeGetCSObj(L, 1); if (obj == null) { return LuaAPI.luaL_error(L, "xlua.access, #1 parameter must a type/c# object/string"); } type = obj.GetType(); } if (type == null) { return LuaAPI.luaL_error(L, "xlua.access, can not find c# type"); } string fieldName = LuaAPI.lua_tostring(L, 2); BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static; if (LuaAPI.lua_gettop(L) > 2) // set { var field = type.GetField(fieldName, bindingFlags); if (field != null) { field.SetValue(obj, translator.GetObject(L, 3, field.FieldType)); return 0; } var prop = type.GetProperty(fieldName, bindingFlags); if (prop != null) { prop.SetValue(obj, translator.GetObject(L, 3, prop.PropertyType), null); return 0; } } else { var field = type.GetField(fieldName, bindingFlags); if (field != null) { translator.PushAny(L, field.GetValue(obj)); return 1; } var prop = type.GetProperty(fieldName, bindingFlags); if (prop != null) { translator.PushAny(L, prop.GetValue(obj, null)); return 1; } } return LuaAPI.luaL_error(L, "xlua.access, no field " + fieldName); } catch (Exception e) { return LuaAPI.luaL_error(L, "c# exception in xlua.access: " + e); } } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int XLuaPrivateAccessible(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Type type = getType(L, translator, 1); ; if (type == null) { return LuaAPI.luaL_error(L, "xlua.private_accessible, can not find c# type"); } while(type != null) { translator.PrivateAccessible(L, type); type = type.BaseType(); } return 0; } catch (Exception e) { return LuaAPI.luaL_error(L, "c# exception in xlua.private_accessible: " + e); } } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int XLuaMetatableOperation(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Type type = getType(L, translator, 1); if (type == null) { return LuaAPI.luaL_error(L, "xlua.metatable_operation, can not find c# type"); } bool is_first = false; int type_id = translator.getTypeId(L, type, out is_first); var param_num = LuaAPI.lua_gettop(L); if (param_num == 1) //get { LuaAPI.xlua_rawgeti(L, LuaIndexes.LUA_REGISTRYINDEX, type_id); return 1; } else if (param_num == 2) //set { if (LuaAPI.lua_type(L, 2) != LuaTypes.LUA_TTABLE) { return LuaAPI.luaL_error(L, "argument #2 must be a table"); } LuaAPI.lua_pushnumber(L, type_id); LuaAPI.xlua_rawseti(L, 2, 1); LuaAPI.xlua_rawseti(L, LuaIndexes.LUA_REGISTRYINDEX, type_id); return 0; } else { return LuaAPI.luaL_error(L, "invalid argument num for xlua.metatable_operation: " + param_num); } } catch (Exception e) { return LuaAPI.luaL_error(L, "c# exception in xlua.metatable_operation: " + e); } } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int DelegateConstructor(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Type type = getType(L, translator, 1); if (type == null || !typeof(Delegate).IsAssignableFrom(type)) { return LuaAPI.luaL_error(L, "delegate constructor: #1 argument must be a Delegate's type"); } translator.PushAny(L, translator.GetObject(L, 2, type)); return 1; } catch (Exception e) { return LuaAPI.luaL_error(L, "c# exception in delegate constructor: " + e); } } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int ToFunction(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); MethodBase m; translator.Get(L, 1, out m); if (m == null) { return LuaAPI.luaL_error(L, "ToFunction: #1 argument must be a MethodBase"); } translator.PushFixCSFunction(L, new LuaCSFunction(translator.methodWrapsCache._GenMethodWrap(m.DeclaringType, m.Name, new MethodBase[] { m }).Call)); return 1; } catch (Exception e) { return LuaAPI.luaL_error(L, "c# exception in ToFunction: " + e); } } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int GenericMethodWraper(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); MethodInfo genericMethod; translator.Get(L, LuaAPI.xlua_upvalueindex(1), out genericMethod); int n = LuaAPI.lua_gettop(L); Type[] typeArguments = new Type[n]; for(int i = 0; i < n; i++) { Type type = getType(L, translator, i + 1); if (type == null) { return LuaAPI.luaL_error(L, "param #" + (i + 1) + " is not a type"); } typeArguments[i] = type; } var method = genericMethod.MakeGenericMethod(typeArguments); translator.PushFixCSFunction(L, new LuaCSFunction(translator.methodWrapsCache._GenMethodWrap(method.DeclaringType, method.Name, new MethodBase[] { method }).Call)); return 1; } catch (Exception e) { return LuaAPI.luaL_error(L, "c# exception in GenericMethodWraper: " + e); } } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int GetGenericMethod(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Type type = getType(L, translator, 1); if (type == null) { return LuaAPI.luaL_error(L, "xlua.get_generic_method, can not find c# type"); } string methodName = LuaAPI.lua_tostring(L, 2); if (string.IsNullOrEmpty(methodName)) { return LuaAPI.luaL_error(L, "xlua.get_generic_method, #2 param need a string"); } System.Collections.Generic.List<MethodInfo> matchMethods = new System.Collections.Generic.List<MethodInfo>(); var allMethods = type.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance); for(int i = 0; i < allMethods.Length; i++) { var method = allMethods[i]; if (method.Name == methodName && method.IsGenericMethodDefinition) { matchMethods.Add(method); } } int methodIdx = 0; if (matchMethods.Count == 0) { LuaAPI.lua_pushnil(L); } else { if (LuaAPI.lua_isinteger(L, 3)) { methodIdx = LuaAPI.xlua_tointeger(L, 3); } translator.PushAny(L, matchMethods[methodIdx]); LuaAPI.lua_pushstdcallcfunction(L, GenericMethodWraper, 1); } } catch (Exception e) { return LuaAPI.luaL_error(L, "c# exception in xlua.get_generic_method: " + e); } return 1; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int ReleaseCsObject(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); translator.ReleaseCSObj(L, 1); return 0; } catch (Exception e) { return LuaAPI.luaL_error(L, "c# exception in ReleaseCsObject: " + e); } } } }
xLua/Assets/XLua/Src/StaticLuaCallbacks.cs/0
{ "file_path": "xLua/Assets/XLua/Src/StaticLuaCallbacks.cs", "repo_id": "xLua", "token_count": 26159 }
2,004
using System; using System.Linq; using System.Collections.Generic; using System.IO; using System.Reflection; namespace XLua { public class XLuaHotfixInject { public static void Useage() { Console.WriteLine("XLuaHotfixInject assmbly_path id_map_file_path [cfg_assmbly2_path] [search_path1, search_path2 ...]"); } public static void Main(string[] args) { if (args.Length < 2) { Useage(); return; } try { var injectAssmblyPath = Path.GetFullPath(args[0]); var xluaAssmblyPath = Path.GetFullPath(args[1]); string cfg_append = null; if (args.Length > 3) { cfg_append = Path.GetFullPath(args[3]); if (!cfg_append.EndsWith(".data")) { cfg_append = null; } } AppDomain currentDomain = AppDomain.CurrentDomain; List<string> search_paths = args.Skip(cfg_append == null ? 3 : 4).ToList(); currentDomain.AssemblyResolve += new ResolveEventHandler((object sender, ResolveEventArgs rea) => { foreach (var search_path in search_paths) { string assemblyPath = Path.Combine(search_path, new AssemblyName(rea.Name).Name + ".dll"); if (File.Exists(assemblyPath)) { return Assembly.Load(File.ReadAllBytes(assemblyPath)); } } return null; }); var assembly = Assembly.Load(File.ReadAllBytes(injectAssmblyPath)); var hotfixCfg = new Dictionary<string, int>(); HotfixConfig.GetConfig(hotfixCfg, assembly.GetTypes()); if (cfg_append != null) { using (BinaryReader reader = new BinaryReader(File.Open(cfg_append, FileMode.Open))) { int count = reader.ReadInt32(); for(int i = 0; i < count; i++) { string k = reader.ReadString(); int v = reader.ReadInt32(); if (!hotfixCfg.ContainsKey(k)) { hotfixCfg.Add(k, v); } } } } Hotfix.HotfixInject(injectAssmblyPath, xluaAssmblyPath, args.Skip(cfg_append == null ? 3 : 3), args[2], hotfixCfg); } catch(Exception e) { Console.WriteLine("Exception in hotfix inject: " + e); } } } }
xLua/General/Src/XLuaHotfixInject.cs/0
{ "file_path": "xLua/General/Src/XLuaHotfixInject.cs", "repo_id": "xLua", "token_count": 1732 }
2,005
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProjectGuid>{F433BFDC-6095-9CEA-E902-E39C5563D3A9}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>XLuaUnitTestGenCode</RootNamespace> <AssemblyName>XLuaUnitTestGenCode</AssemblyName> <TargetFrameworkVersion>v4.0</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PlatformTarget>AnyCPU</PlatformTarget> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>..\Bin\</OutputPath> <BaseIntermediateOutputPath>obj\Any CPU\Debug\XLuaUnitTestGenCode\</BaseIntermediateOutputPath> <IntermediateOutputPath>$(BaseIntermediateOutputPath)</IntermediateOutputPath> <DefineConstants>_DEBUG;DEBUG;TRACE;;XLUA_GENERAL</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <PlatformTarget>AnyCPU</PlatformTarget> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>..\Bin\</OutputPath> <BaseIntermediateOutputPath>obj\Any CPU\Release\XLuaUnitTestGenCode\</BaseIntermediateOutputPath> <IntermediateOutputPath>$(BaseIntermediateOutputPath)</IntermediateOutputPath> <DefineConstants>;XLUA_GENERAL</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="System" /> <Reference Include="System.Core" /> </ItemGroup> <ItemGroup> <Compile Include="..\..\Assets\XLua\Src\CodeEmit.cs"> <Link>Assets\XLua\Src\CodeEmit.cs</Link> </Compile> <Compile Include="..\..\Assets\XLua\Src\CopyByValue.cs"> <Link>Assets\XLua\Src\CopyByValue.cs</Link> </Compile> <Compile Include="..\..\Assets\XLua\Src\DelegateBridge.cs"> <Link>Assets\XLua\Src\DelegateBridge.cs</Link> </Compile> <Compile Include="..\..\Assets\XLua\Src\GenAttributes.cs"> <Link>Assets\XLua\Src\GenAttributes.cs</Link> </Compile> <Compile Include="..\..\Assets\XLua\Src\GenericDelegateBridge.cs"> <Link>Assets\XLua\Src\GenericDelegateBridge.cs</Link> </Compile> <Compile Include="..\..\Assets\XLua\Src\InternalGlobals.cs"> <Link>Assets\XLua\Src\InternalGlobals.cs</Link> </Compile> <Compile Include="..\..\Assets\XLua\Src\LuaBase.cs"> <Link>Assets\XLua\Src\LuaBase.cs</Link> </Compile> <Compile Include="..\..\Assets\XLua\Src\LuaDLL.cs"> <Link>Assets\XLua\Src\LuaDLL.cs</Link> </Compile> <Compile Include="..\..\Assets\XLua\Src\LuaEnv.cs"> <Link>Assets\XLua\Src\LuaEnv.cs</Link> </Compile> <Compile Include="..\..\Assets\XLua\Src\LuaException.cs"> <Link>Assets\XLua\Src\LuaException.cs</Link> </Compile> <Compile Include="..\..\Assets\XLua\Src\LuaFunction.cs"> <Link>Assets\XLua\Src\LuaFunction.cs</Link> </Compile> <Compile Include="..\..\Assets\XLua\Src\LuaTable.cs"> <Link>Assets\XLua\Src\LuaTable.cs</Link> </Compile> <Compile Include="..\..\Assets\XLua\Src\MethodWarpsCache.cs"> <Link>Assets\XLua\Src\MethodWarpsCache.cs</Link> </Compile> <Compile Include="..\..\Assets\XLua\Src\ObjectCasters.cs"> <Link>Assets\XLua\Src\ObjectCasters.cs</Link> </Compile> <Compile Include="..\..\Assets\XLua\Src\ObjectPool.cs"> <Link>Assets\XLua\Src\ObjectPool.cs</Link> </Compile> <Compile Include="..\..\Assets\XLua\Src\ObjectTranslator.cs"> <Link>Assets\XLua\Src\ObjectTranslator.cs</Link> </Compile> <Compile Include="..\..\Assets\XLua\Src\ObjectTranslatorPool.cs"> <Link>Assets\XLua\Src\ObjectTranslatorPool.cs</Link> </Compile> <Compile Include="..\..\Assets\XLua\Src\RawObject.cs"> <Link>Assets\XLua\Src\RawObject.cs</Link> </Compile> <Compile Include="..\..\Assets\XLua\Src\SignatureLoader.cs"> <Link>Assets\XLua\Src\SignatureLoader.cs</Link> </Compile> <Compile Include="..\..\Assets\XLua\Src\StaticLuaCallbacks.cs"> <Link>Assets\XLua\Src\StaticLuaCallbacks.cs</Link> </Compile> <Compile Include="..\..\Assets\XLua\Src\TemplateEngine\TemplateEngine.cs"> <Link>Assets\XLua\Src\TemplateEngine\TemplateEngine.cs</Link> </Compile> <Compile Include="..\..\Assets\XLua\Src\TypeExtensions.cs"> <Link>Assets\XLua\Src\TypeExtensions.cs</Link> </Compile> <Compile Include="..\..\Assets\XLua\Src\Utils.cs"> <Link>Assets\XLua\Src\Utils.cs</Link> </Compile> <Compile Include="..\..\Test\UnitTest\xLuaTest\CSharpCallLua\CSObjectForTestCSCallLua.cs"> <Link>Test\UnitTest\xLuaTest\CSharpCallLua\CSObjectForTestCSCallLua.cs</Link> </Compile> <Compile Include="..\..\Test\UnitTest\xLuaTest\CSharpCallLua\TCForTestCSCallLua.cs"> <Link>Test\UnitTest\xLuaTest\CSharpCallLua\TCForTestCSCallLua.cs</Link> </Compile> <Compile Include="..\..\Test\UnitTest\xLuaTest\CSharpCallLua\TestCSCallLua.cs"> <Link>Test\UnitTest\xLuaTest\CSharpCallLua\TestCSCallLua.cs</Link> </Compile> <Compile Include="..\..\Test\UnitTest\xLuaTest\LuaCallCS\CSObjectForLuaCallCS.cs"> <Link>Test\UnitTest\xLuaTest\LuaCallCS\CSObjectForLuaCallCS.cs</Link> </Compile> <Compile Include="..\..\Test\UnitTest\xLuaTest\LuaTestCommon.cs"> <Link>Test\UnitTest\xLuaTest\LuaTestCommon.cs</Link> </Compile> <Compile Include="..\..\Test\UnitTest\xLuaTest\LuaTestObj.cs"> <Link>Test\UnitTest\xLuaTest\LuaTestObj.cs</Link> </Compile> <Compile Include="..\..\Test\UnitTest\xLuaTest\LuaTestObjReflect.cs"> <Link>Test\UnitTest\xLuaTest\LuaTestObjReflect.cs</Link> </Compile> <Compile Include="..\..\Test\UnitTest\xLuaTest\Main.cs"> <Link>Test\UnitTest\xLuaTest\Main.cs</Link> </Compile> <Compile Include="..\Gen2\AClassWrap.cs"> <Link>Gen2\AClassWrap.cs</Link> </Compile> <Compile Include="..\Gen2\CClassWrap.cs"> <Link>Gen2\CClassWrap.cs</Link> </Compile> <Compile Include="..\Gen2\DelegatesGensBridge.cs"> <Link>Gen2\DelegatesGensBridge.cs</Link> </Compile> <Compile Include="..\Gen2\EmployeeTemplateWrap.cs"> <Link>Gen2\EmployeeTemplateWrap.cs</Link> </Compile> <Compile Include="..\Gen2\EmployeestructWrap.cs"> <Link>Gen2\EmployeestructWrap.cs</Link> </Compile> <Compile Include="..\Gen2\EnumWrap.cs"> <Link>Gen2\EnumWrap.cs</Link> </Compile> <Compile Include="..\Gen2\Gen2FloatStructWrap.cs"> <Link>Gen2\Gen2FloatStructWrap.cs</Link> </Compile> <Compile Include="..\Gen2\Gen3FloatStructWrap.cs"> <Link>Gen2\Gen3FloatStructWrap.cs</Link> </Compile> <Compile Include="..\Gen2\Gen4FloatStructWrap.cs"> <Link>Gen2\Gen4FloatStructWrap.cs</Link> </Compile> <Compile Include="..\Gen2\Gen5FloatStructWrap.cs"> <Link>Gen2\Gen5FloatStructWrap.cs</Link> </Compile> <Compile Include="..\Gen2\Gen6FloatStructWrap.cs"> <Link>Gen2\Gen6FloatStructWrap.cs</Link> </Compile> <Compile Include="..\Gen2\GenCodeBaseClassWrap.cs"> <Link>Gen2\GenCodeBaseClassWrap.cs</Link> </Compile> <Compile Include="..\Gen2\GenCodeDrivedClassWrap.cs"> <Link>Gen2\GenCodeDrivedClassWrap.cs</Link> </Compile> <Compile Include="..\Gen2\GenCodeStructWrap.cs"> <Link>Gen2\GenCodeStructWrap.cs</Link> </Compile> <Compile Include="..\Gen2\HasConstructStructWrap.cs"> <Link>Gen2\HasConstructStructWrap.cs</Link> </Compile> <Compile Include="..\Gen2\IGenCodeTestWrap.cs"> <Link>Gen2\IGenCodeTestWrap.cs</Link> </Compile> <Compile Include="..\Gen2\ITestLuaClassWrap.cs"> <Link>Gen2\ITestLuaClassWrap.cs</Link> </Compile> <Compile Include="..\Gen2\LongStaticWrap.cs"> <Link>Gen2\LongStaticWrap.cs</Link> </Compile> <Compile Include="..\Gen2\LuaTestCommonWrap.cs"> <Link>Gen2\LuaTestCommonWrap.cs</Link> </Compile> <Compile Include="..\Gen2\LuaTestObjWrap.cs"> <Link>Gen2\LuaTestObjWrap.cs</Link> </Compile> <Compile Include="..\Gen2\ManagerWrap.cs"> <Link>Gen2\ManagerWrap.cs</Link> </Compile> <Compile Include="..\Gen2\NoContClassWrap.cs"> <Link>Gen2\NoContClassWrap.cs</Link> </Compile> <Compile Include="..\Gen2\PackUnpack.cs"> <Link>Gen2\PackUnpack.cs</Link> </Compile> <Compile Include="..\Gen2\ReferTestClassWrap.cs"> <Link>Gen2\ReferTestClassWrap.cs</Link> </Compile> <Compile Include="..\Gen2\StaticPusherStructAWrap.cs"> <Link>Gen2\StaticPusherStructAWrap.cs</Link> </Compile> <Compile Include="..\Gen2\StaticPusherStructAllWrap.cs"> <Link>Gen2\StaticPusherStructAllWrap.cs</Link> </Compile> <Compile Include="..\Gen2\StaticPusherStructBWrap.cs"> <Link>Gen2\StaticPusherStructBWrap.cs</Link> </Compile> <Compile Include="..\Gen2\TCForTestCSCallLuaWrap.cs"> <Link>Gen2\TCForTestCSCallLuaWrap.cs</Link> </Compile> <Compile Include="..\Gen2\TableAutoTransComplexClassWrap.cs"> <Link>Gen2\TableAutoTransComplexClassWrap.cs</Link> </Compile> <Compile Include="..\Gen2\TableAutoTransComplexStructWrap.cs"> <Link>Gen2\TableAutoTransComplexStructWrap.cs</Link> </Compile> <Compile Include="..\Gen2\TableAutoTransSimpleClassWrap.cs"> <Link>Gen2\TableAutoTransSimpleClassWrap.cs</Link> </Compile> <Compile Include="..\Gen2\TableAutoTransSimpleStructWrap.cs"> <Link>Gen2\TableAutoTransSimpleStructWrap.cs</Link> </Compile> <Compile Include="..\Gen2\TestCastClassWrap.cs"> <Link>Gen2\TestCastClassWrap.cs</Link> </Compile> <Compile Include="..\Gen2\TestChineseStringWrap.cs"> <Link>Gen2\TestChineseStringWrap.cs</Link> </Compile> <Compile Include="..\Gen2\TestExtensionMethod_TestExtensionMethodFOrClassWrap.cs"> <Link>Gen2\TestExtensionMethod_TestExtensionMethodFOrClassWrap.cs</Link> </Compile> <Compile Include="..\Gen2\TestExtensionMethod_TestExtensionMethodForStructWrap.cs"> <Link>Gen2\TestExtensionMethod_TestExtensionMethodForStructWrap.cs</Link> </Compile> <Compile Include="..\Gen2\TestGenFloatStructClassWrap.cs"> <Link>Gen2\TestGenFloatStructClassWrap.cs</Link> </Compile> <Compile Include="..\Gen2\TestStructWrap.cs"> <Link>Gen2\TestStructWrap.cs</Link> </Compile> <Compile Include="..\Gen2\TestTableAutoTransClassWrap.cs"> <Link>Gen2\TestTableAutoTransClassWrap.cs</Link> </Compile> <Compile Include="..\Gen2\WrapPusher.cs"> <Link>Gen2\WrapPusher.cs</Link> </Compile> <Compile Include="..\Gen2\XLuaGenAutoRegister.cs"> <Link>Gen2\XLuaGenAutoRegister.cs</Link> </Compile> <Compile Include="..\Gen2\tableValue1InfEqualBridge.cs"> <Link>Gen2\tableValue1InfEqualBridge.cs</Link> </Compile> <Compile Include="..\Gen2\tableValue1InfLessBridge.cs"> <Link>Gen2\tableValue1InfLessBridge.cs</Link> </Compile> <Compile Include="..\Gen2\tableValue1InfMoreBridge.cs"> <Link>Gen2\tableValue1InfMoreBridge.cs</Link> </Compile> <Compile Include="..\Gen2\tableValue1InfTypeDiffBridge.cs"> <Link>Gen2\tableValue1InfTypeDiffBridge.cs</Link> </Compile> <Compile Include="..\Gen2\tableValue2InfBridge.cs"> <Link>Gen2\tableValue2InfBridge.cs</Link> </Compile> <Compile Include="..\Gen2\tableVarIncludeInfBridge.cs"> <Link>Gen2\tableVarIncludeInfBridge.cs</Link> </Compile> <Compile Include="..\Gen2\testLuaCallCS_ChildCalssWrap.cs"> <Link>Gen2\testLuaCallCS_ChildCalssWrap.cs</Link> </Compile> <Compile Include="..\Gen2\testLuaCallCS_MultiContClassWrap.cs"> <Link>Gen2\testLuaCallCS_MultiContClassWrap.cs</Link> </Compile> <Compile Include="..\Gen2\testLuaCallCS_OneParamContClassWrap.cs"> <Link>Gen2\testLuaCallCS_OneParamContClassWrap.cs</Link> </Compile> <Compile Include="..\Gen2\testLuaCallCS_OverClassAWrap.cs"> <Link>Gen2\testLuaCallCS_OverClassAWrap.cs</Link> </Compile> <Compile Include="..\Gen2\testLuaCallCS_OverClassBWrap.cs"> <Link>Gen2\testLuaCallCS_OverClassBWrap.cs</Link> </Compile> <Compile Include="..\Gen2\testLuaCallCS_OverClassCDeriveNGAWrap.cs"> <Link>Gen2\testLuaCallCS_OverClassCDeriveNGAWrap.cs</Link> </Compile> <Compile Include="..\Gen2\testLuaCallCS_OverClassCWrap.cs"> <Link>Gen2\testLuaCallCS_OverClassCWrap.cs</Link> </Compile> <Compile Include="..\Gen2\testLuaCallCS_StaticTestClassWrap.cs"> <Link>Gen2\testLuaCallCS_StaticTestClassWrap.cs</Link> </Compile> <Compile Include="..\Gen2\testLuaCallCS_TwoParamsContClassWrap.cs"> <Link>Gen2\testLuaCallCS_TwoParamsContClassWrap.cs</Link> </Compile> <Compile Include="..\Gen2\testLuaCallCS_abstractFatherClassWrap.cs"> <Link>Gen2\testLuaCallCS_abstractFatherClassWrap.cs</Link> </Compile> <Compile Include="..\Src\XLuaUnitTest.cs"> <Link>Src\XLuaUnitTest.cs</Link> </Compile> </ItemGroup> <ItemGroup> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project>
xLua/General/vs2013/XLuaUnitTestGenCode.csproj/0
{ "file_path": "xLua/General/vs2013/XLuaUnitTestGenCode.csproj", "repo_id": "xLua", "token_count": 6091 }
2,006
fileFormatVersion: 2 guid: 1f134b58b34a7854ea895e518b4ffb9c timeCreated: 1483528414 licenseType: Pro DefaultImporter: userData: assetBundleName: assetBundleVariant:
xLua/Test/UnitTest/StreamingAssets/csCallLua.lua.meta/0
{ "file_path": "xLua/Test/UnitTest/StreamingAssets/csCallLua.lua.meta", "repo_id": "xLua", "token_count": 72 }
2,007
require("luaCallCs") require("luaCallCsReflect") require("csCallLua") require("genCode") --require("luaTdrTest") function islua53() return not not math.type end -- for test case CMyTestEnv = TestEnvironment:new() function CMyTestEnv:new(oo) local o = oo or {} setmetatable(o, self) self.__index = self return o end function CMyTestEnv.SetUp(self) print("CMyTestEnv.SetUp") end function CMyTestEnv.TearDown(self) print("CMyTestEnv.TearDown") end co = coroutine.create(function() local resultPath = CS.LuaTestCommon.resultPath local tInitPara = { --ltest_filter = "CMyTestCaseLuaCallCS.*:CMyTestCase3.*", ltest_list_tests = resultPath.."ltest_case_list_co.txt", ltest_list_falied = resultPath.."ltest_case_failed_co.txt", } InitLTest(tInitPara) AddLTestSuite(CMyTestCaseLuaCallCS:new(), "CMyTestCaseLuaCallCS", "Case") AddLTestSuite(CMyTestCaseLuaCallCSReflect:new(), "CMyTestCaseLuaCallCSReflect", "Case") --AddLTestSuite(CMyTestCaseGenCode:new(), "CMyTestCaseGenCode", "Case") AddLTestSuite(CMyTestCaseCSCallLua:new(), "CMyTestCaseCSCallLua", "test") --AddLTestSuite(CMyTestCaseLuaTdr:new(), "CMyTestCaseLuaTdr", "Case") RunAllTests(CMyTestEnv:new()) local t = GetRunStatInfo() --print(t.iFailedNum) coroutine.yield() end) function main() print(coroutine.resume(co)); local resultPath = CS.LuaTestCommon.resultPath local tInitPara = { --ltest_filter = "CMyTestCaseLuaCallCS.*:CMyTestCase3.*", ltest_list_tests = resultPath.."ltest_case_list.txt", ltest_list_falied = resultPath.."ltest_case_failed.txt", } InitLTest(tInitPara) AddLTestSuite(CMyTestCaseLuaCallCS:new(), "CMyTestCaseLuaCallCS", "Case") AddLTestSuite(CMyTestCaseLuaCallCSReflect:new(), "CMyTestCaseLuaCallCSReflect", "Case") --AddLTestSuite(CMyTestCaseGenCode:new(), "CMyTestCaseGenCode", "Case") AddLTestSuite(CMyTestCaseCSCallLua:new(), "CMyTestCaseCSCallLua", "test") --AddLTestSuite(CMyTestCaseLuaTdr:new(), "CMyTestCaseLuaTdr", "Case") RunAllTests(CMyTestEnv:new()) print('--------------------------------------------------------') local t = GetRunStatInfo() --print(t.iFailedNum) end main() local ret = islua53() print("islua53") print(tostring(ret))
xLua/Test/UnitTest/StreamingAssets/main.lua/0
{ "file_path": "xLua/Test/UnitTest/StreamingAssets/main.lua", "repo_id": "xLua", "token_count": 882 }
2,008
fileFormatVersion: 2 guid: 04eee5a18722aca49bfb2fb28416ede1 folderAsset: yes timeCreated: 1483527547 licenseType: Pro DefaultImporter: userData: assetBundleName: assetBundleVariant:
xLua/Test/UnitTest/xLuaTest/CSharpCallLua/Resources.meta/0
{ "file_path": "xLua/Test/UnitTest/xLuaTest/CSharpCallLua/Resources.meta", "repo_id": "xLua", "token_count": 73 }
2,009
fileFormatVersion: 2 guid: cba25057ebcf1d54c9ad49fde9b6e62d timeCreated: 1483527551 licenseType: Pro MonoImporter: serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
xLua/Test/UnitTest/xLuaTest/CSharpCallLua/TestCSCallLua.cs.meta/0
{ "file_path": "xLua/Test/UnitTest/xLuaTest/CSharpCallLua/TestCSCallLua.cs.meta", "repo_id": "xLua", "token_count": 102 }
2,010
fileFormatVersion: 2 guid: 568886381954c3b408d0b9ace77f3af3 timeCreated: 1483527551 licenseType: Pro TextScriptImporter: userData: assetBundleName: assetBundleVariant:
xLua/Test/UnitTest/xLuaTest/Resources/non_tlv_net_msg_type.xml.meta/0
{ "file_path": "xLua/Test/UnitTest/xLuaTest/Resources/non_tlv_net_msg_type.xml.meta", "repo_id": "xLua", "token_count": 72 }
2,011
/* ** $Id: luac.c,v 1.75 2015/03/12 01:58:27 lhf Exp $ ** Lua compiler (saves bytecodes to files; also lists bytecodes) ** See Copyright Notice in lua.h */ #define luac_c #define LUA_CORE #include "lprefix.h" #include <ctype.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "lua.h" #include "lauxlib.h" #include "lobject.h" #include "lstate.h" #include "lundump.h" static void PrintFunction(const Proto* f, int full); #define luaU_print PrintFunction #define PROGNAME "luac" /* default program name */ #define OUTPUT PROGNAME ".out" /* default output file */ static int listing=0; /* list bytecodes? */ static int dumping=1; /* dump bytecodes? */ static int stripping=0; /* strip debug information? */ static char Output[]={ OUTPUT }; /* default output file name */ static const char* output=Output; /* actual output file name */ static const char* progname=PROGNAME; /* actual program name */ static void fatal(const char* message) { fprintf(stderr,"%s: %s\n",progname,message); exit(EXIT_FAILURE); } static void cannot(const char* what) { fprintf(stderr,"%s: cannot %s %s: %s\n",progname,what,output,strerror(errno)); exit(EXIT_FAILURE); } static void usage(const char* message) { if (*message=='-') fprintf(stderr,"%s: unrecognized option '%s'\n",progname,message); else fprintf(stderr,"%s: %s\n",progname,message); fprintf(stderr, "usage: %s [options] [filenames]\n" "Available options are:\n" " -l list (use -l -l for full listing)\n" " -o name output to file 'name' (default is \"%s\")\n" " -p parse only\n" " -s strip debug information\n" " -v show version information\n" " -- stop handling options\n" " - stop handling options and process stdin\n" ,progname,Output); exit(EXIT_FAILURE); } #define IS(s) (strcmp(argv[i],s)==0) static int doargs(int argc, char* argv[]) { int i; int version=0; if (argv[0]!=NULL && *argv[0]!=0) progname=argv[0]; for (i=1; i<argc; i++) { if (*argv[i]!='-') /* end of options; keep it */ break; else if (IS("--")) /* end of options; skip it */ { ++i; if (version) ++version; break; } else if (IS("-")) /* end of options; use stdin */ break; else if (IS("-l")) /* list */ ++listing; else if (IS("-o")) /* output file */ { output=argv[++i]; if (output==NULL || *output==0 || (*output=='-' && output[1]!=0)) usage("'-o' needs argument"); if (IS("-")) output=NULL; } else if (IS("-p")) /* parse only */ dumping=0; else if (IS("-s")) /* strip debug information */ stripping=1; else if (IS("-v")) /* show version */ ++version; else /* unknown option */ usage(argv[i]); } if (i==argc && (listing || !dumping)) { dumping=0; argv[--i]=Output; } if (version) { printf("%s\n",LUA_COPYRIGHT); if (version==argc-1) exit(EXIT_SUCCESS); } return i; } #define FUNCTION "(function()end)();" static const char* reader(lua_State *L, void *ud, size_t *size) { UNUSED(L); if ((*(int*)ud)--) { *size=sizeof(FUNCTION)-1; return FUNCTION; } else { *size=0; return NULL; } } #define toproto(L,i) getproto(L->top+(i)) static const Proto* combine(lua_State* L, int n) { if (n==1) return toproto(L,-1); else { Proto* f; int i=n; if (lua_load(L,reader,&i,"=(" PROGNAME ")",NULL)!=LUA_OK) fatal(lua_tostring(L,-1)); f=toproto(L,-1); for (i=0; i<n; i++) { f->p[i]=toproto(L,i-n-1); if (f->p[i]->sizeupvalues>0) f->p[i]->upvalues[0].instack=0; } f->sizelineinfo=0; return f; } } static int writer(lua_State* L, const void* p, size_t size, void* u) { UNUSED(L); return (fwrite(p,size,1,(FILE*)u)!=1) && (size!=0); } static int pmain(lua_State* L) { int argc=(int)lua_tointeger(L,1); char** argv=(char**)lua_touserdata(L,2); const Proto* f; int i; if (!lua_checkstack(L,argc)) fatal("too many input files"); for (i=0; i<argc; i++) { const char* filename=IS("-") ? NULL : argv[i]; if (luaL_loadfile(L,filename)!=LUA_OK) fatal(lua_tostring(L,-1)); } f=combine(L,argc); if (listing) luaU_print(f,listing>1); if (dumping) { FILE* D= (output==NULL) ? stdout : fopen(output,"wb"); if (D==NULL) cannot("open"); lua_lock(L); luaU_dump(L,f,writer,D,stripping); lua_unlock(L); if (ferror(D)) cannot("write"); if (fclose(D)) cannot("close"); } return 0; } int main(int argc, char* argv[]) { lua_State* L; int i=doargs(argc,argv); argc-=i; argv+=i; if (argc<=0) usage("no input files given"); L=luaL_newstate(); if (L==NULL) fatal("cannot create state: not enough memory"); lua_pushcfunction(L,&pmain); lua_pushinteger(L,argc); lua_pushlightuserdata(L,argv); if (lua_pcall(L,2,0,0)!=LUA_OK) fatal(lua_tostring(L,-1)); lua_close(L); return EXIT_SUCCESS; } /* ** $Id: luac.c,v 1.75 2015/03/12 01:58:27 lhf Exp $ ** print bytecodes ** See Copyright Notice in lua.h */ #include <ctype.h> #include <stdio.h> #define luac_c #define LUA_CORE #include "ldebug.h" #include "lobject.h" #include "lopcodes.h" #define VOID(p) ((const void*)(p)) static void PrintString(const TString* ts) { const char* s=getstr(ts); size_t i,n=tsslen(ts); printf("%c",'"'); for (i=0; i<n; i++) { int c=(int)(unsigned char)s[i]; switch (c) { case '"': printf("\\\""); break; case '\\': printf("\\\\"); break; case '\a': printf("\\a"); break; case '\b': printf("\\b"); break; case '\f': printf("\\f"); break; case '\n': printf("\\n"); break; case '\r': printf("\\r"); break; case '\t': printf("\\t"); break; case '\v': printf("\\v"); break; default: if (isprint(c)) printf("%c",c); else printf("\\%03d",c); } } printf("%c",'"'); } static void PrintConstant(const Proto* f, int i) { const TValue* o=&f->k[i]; switch (ttype(o)) { case LUA_TNIL: printf("nil"); break; case LUA_TBOOLEAN: printf(bvalue(o) ? "true" : "false"); break; case LUA_TNUMFLT: { char buff[100]; sprintf(buff,LUA_NUMBER_FMT,fltvalue(o)); printf("%s",buff); if (buff[strspn(buff,"-0123456789")]=='\0') printf(".0"); break; } case LUA_TNUMINT: printf(LUA_INTEGER_FMT,ivalue(o)); break; case LUA_TSHRSTR: case LUA_TLNGSTR: PrintString(tsvalue(o)); break; default: /* cannot happen */ printf("? type=%d",ttype(o)); break; } } #define UPVALNAME(x) ((f->upvalues[x].name) ? getstr(f->upvalues[x].name) : "-") #define MYK(x) (-1-(x)) static void PrintCode(const Proto* f) { const Instruction* code=f->code; int pc,n=f->sizecode; for (pc=0; pc<n; pc++) { Instruction i=code[pc]; OpCode o=GET_OPCODE(i); int a=GETARG_A(i); int b=GETARG_B(i); int c=GETARG_C(i); int ax=GETARG_Ax(i); int bx=GETARG_Bx(i); int sbx=GETARG_sBx(i); int line=getfuncline(f,pc); printf("\t%d\t",pc+1); if (line>0) printf("[%d]\t",line); else printf("[-]\t"); printf("%-9s\t",luaP_opnames[o]); switch (getOpMode(o)) { case iABC: printf("%d",a); if (getBMode(o)!=OpArgN) printf(" %d",ISK(b) ? (MYK(INDEXK(b))) : b); if (getCMode(o)!=OpArgN) printf(" %d",ISK(c) ? (MYK(INDEXK(c))) : c); break; case iABx: printf("%d",a); if (getBMode(o)==OpArgK) printf(" %d",MYK(bx)); if (getBMode(o)==OpArgU) printf(" %d",bx); break; case iAsBx: printf("%d %d",a,sbx); break; case iAx: printf("%d",MYK(ax)); break; } switch (o) { case OP_LOADK: printf("\t; "); PrintConstant(f,bx); break; case OP_GETUPVAL: case OP_SETUPVAL: printf("\t; %s",UPVALNAME(b)); break; case OP_GETTABUP: printf("\t; %s",UPVALNAME(b)); if (ISK(c)) { printf(" "); PrintConstant(f,INDEXK(c)); } break; case OP_SETTABUP: printf("\t; %s",UPVALNAME(a)); if (ISK(b)) { printf(" "); PrintConstant(f,INDEXK(b)); } if (ISK(c)) { printf(" "); PrintConstant(f,INDEXK(c)); } break; case OP_GETTABLE: case OP_SELF: if (ISK(c)) { printf("\t; "); PrintConstant(f,INDEXK(c)); } break; case OP_SETTABLE: case OP_ADD: case OP_SUB: case OP_MUL: case OP_POW: case OP_DIV: case OP_IDIV: case OP_BAND: case OP_BOR: case OP_BXOR: case OP_SHL: case OP_SHR: case OP_EQ: case OP_LT: case OP_LE: if (ISK(b) || ISK(c)) { printf("\t; "); if (ISK(b)) PrintConstant(f,INDEXK(b)); else printf("-"); printf(" "); if (ISK(c)) PrintConstant(f,INDEXK(c)); else printf("-"); } break; case OP_JMP: case OP_FORLOOP: case OP_FORPREP: case OP_TFORLOOP: printf("\t; to %d",sbx+pc+2); break; case OP_CLOSURE: printf("\t; %p",VOID(f->p[bx])); break; case OP_SETLIST: if (c==0) printf("\t; %d",(int)code[++pc]); else printf("\t; %d",c); break; case OP_EXTRAARG: printf("\t; "); PrintConstant(f,ax); break; default: break; } printf("\n"); } } #define SS(x) ((x==1)?"":"s") #define S(x) (int)(x),SS(x) static void PrintHeader(const Proto* f) { const char* s=f->source ? getstr(f->source) : "=?"; if (*s=='@' || *s=='=') s++; else if (*s==LUA_SIGNATURE[0]) s="(bstring)"; else s="(string)"; printf("\n%s <%s:%d,%d> (%d instruction%s at %p)\n", (f->linedefined==0)?"main":"function",s, f->linedefined,f->lastlinedefined, S(f->sizecode),VOID(f)); printf("%d%s param%s, %d slot%s, %d upvalue%s, ", (int)(f->numparams),f->is_vararg?"+":"",SS(f->numparams), S(f->maxstacksize),S(f->sizeupvalues)); printf("%d local%s, %d constant%s, %d function%s\n", S(f->sizelocvars),S(f->sizek),S(f->sizep)); } static void PrintDebug(const Proto* f) { int i,n; n=f->sizek; printf("constants (%d) for %p:\n",n,VOID(f)); for (i=0; i<n; i++) { printf("\t%d\t",i+1); PrintConstant(f,i); printf("\n"); } n=f->sizelocvars; printf("locals (%d) for %p:\n",n,VOID(f)); for (i=0; i<n; i++) { printf("\t%d\t%s\t%d\t%d\n", i,getstr(f->locvars[i].varname),f->locvars[i].startpc+1,f->locvars[i].endpc+1); } n=f->sizeupvalues; printf("upvalues (%d) for %p:\n",n,VOID(f)); for (i=0; i<n; i++) { printf("\t%d\t%s\t%d\t%d\n", i,UPVALNAME(i),f->upvalues[i].instack,f->upvalues[i].idx); } } static void PrintFunction(const Proto* f, int full) { int i,n=f->sizep; PrintHeader(f); PrintCode(f); if (full) PrintDebug(f); for (i=0; i<n; i++) PrintFunction(f->p[i],full); }
xLua/WebGLPlugins/luac.c/0
{ "file_path": "xLua/WebGLPlugins/luac.c", "repo_id": "xLua", "token_count": 4811 }
2,012