Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- Completed/.gitattributes +2 -0
- Completed/.gitignore +3 -0
- Completed/GridRobot.csproj +11 -0
- Completed/GridRobot.sln +19 -0
- Completed/addons/godot_rl_agents/controller/ai_controller_2d.gd +127 -0
- Completed/addons/godot_rl_agents/controller/ai_controller_3d.gd +128 -0
- Completed/addons/godot_rl_agents/godot_rl_agents.gd +16 -0
- Completed/addons/godot_rl_agents/icon.png +3 -0
- Completed/addons/godot_rl_agents/onnx/csharp/ONNXInference.cs +109 -0
- Completed/addons/godot_rl_agents/onnx/csharp/SessionConfigurator.cs +131 -0
- Completed/addons/godot_rl_agents/onnx/csharp/docs/ONNXInference.xml +31 -0
- Completed/addons/godot_rl_agents/onnx/csharp/docs/SessionConfigurator.xml +29 -0
- Completed/addons/godot_rl_agents/onnx/wrapper/ONNX_wrapper.gd +51 -0
- Completed/addons/godot_rl_agents/plugin.cfg +7 -0
- Completed/addons/godot_rl_agents/sensors/sensors_2d/ExampleRaycastSensor2D.tscn +48 -0
- Completed/addons/godot_rl_agents/sensors/sensors_2d/GridSensor2D.gd +235 -0
- Completed/addons/godot_rl_agents/sensors/sensors_2d/ISensor2D.gd +25 -0
- Completed/addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.gd +118 -0
- Completed/addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.tscn +7 -0
- Completed/addons/godot_rl_agents/sensors/sensors_3d/ExampleRaycastSensor3D.tscn +6 -0
- Completed/addons/godot_rl_agents/sensors/sensors_3d/GridSensor3D.gd +258 -0
- Completed/addons/godot_rl_agents/sensors/sensors_3d/ISensor3D.gd +25 -0
- Completed/addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.gd +63 -0
- Completed/addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.tscn +35 -0
- Completed/addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd +185 -0
- Completed/addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.tscn +27 -0
- Completed/addons/godot_rl_agents/sync.gd +587 -0
- Completed/assets/car.glb +0 -0
- Completed/assets/goal_tile.glb +0 -0
- Completed/assets/orange_tile.glb +0 -0
- Completed/assets/road_tile.glb +0 -0
- Completed/assets/robot.glb +0 -0
- Completed/assets/tree_tile.glb +0 -0
- Completed/icon.svg +1 -0
- Completed/license.md +5 -0
- Completed/model.onnx +3 -0
- Completed/project.godot +55 -0
- Completed/scenes/car.tscn +10 -0
- Completed/scenes/game_scene.tscn +28 -0
- Completed/scenes/onnx_inference_scene.tscn +35 -0
- Completed/scenes/robot.tscn +207 -0
- Completed/scenes/tile.tscn +18 -0
- Completed/scenes/training_scene.tscn +42 -0
- Completed/scripts/car.gd +18 -0
- Completed/scripts/car_manager.gd +48 -0
- Completed/scripts/grid_map.gd +122 -0
- Completed/scripts/robot.gd +111 -0
- Completed/scripts/robot_ai_controller.gd +121 -0
- Completed/scripts/tile.gd +30 -0
- README.md +25 -0
Completed/.gitattributes
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
# Normalize EOL for all files that Git considers text files.
|
2 |
+
* text=auto eol=lf
|
Completed/.gitignore
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
# Godot 4+ specific ignores
|
2 |
+
.godot/
|
3 |
+
android/
|
Completed/GridRobot.csproj
ADDED
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<Project Sdk="Godot.NET.Sdk/4.3.0-beta.3">
|
2 |
+
<PropertyGroup>
|
3 |
+
<TargetFramework>net6.0</TargetFramework>
|
4 |
+
<TargetFramework Condition=" '$(GodotTargetPlatform)' == 'android' ">net7.0</TargetFramework>
|
5 |
+
<TargetFramework Condition=" '$(GodotTargetPlatform)' == 'ios' ">net8.0</TargetFramework>
|
6 |
+
<EnableDynamicLoading>true</EnableDynamicLoading>
|
7 |
+
</PropertyGroup>
|
8 |
+
<ItemGroup>
|
9 |
+
<PackageReference Include="Microsoft.ML.OnnxRuntime" Version="1.15.1" />
|
10 |
+
</ItemGroup>
|
11 |
+
</Project>
|
Completed/GridRobot.sln
ADDED
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Microsoft Visual Studio Solution File, Format Version 12.00
|
2 |
+
# Visual Studio 2012
|
3 |
+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GridRobot", "GridRobot.csproj", "{A5E8FC07-E73E-476D-93D5-2EA7814E2E23}"
|
4 |
+
EndProject
|
5 |
+
Global
|
6 |
+
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
7 |
+
Debug|Any CPU = Debug|Any CPU
|
8 |
+
ExportDebug|Any CPU = ExportDebug|Any CPU
|
9 |
+
ExportRelease|Any CPU = ExportRelease|Any CPU
|
10 |
+
EndGlobalSection
|
11 |
+
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
12 |
+
{A5E8FC07-E73E-476D-93D5-2EA7814E2E23}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
13 |
+
{A5E8FC07-E73E-476D-93D5-2EA7814E2E23}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
14 |
+
{A5E8FC07-E73E-476D-93D5-2EA7814E2E23}.ExportDebug|Any CPU.ActiveCfg = ExportDebug|Any CPU
|
15 |
+
{A5E8FC07-E73E-476D-93D5-2EA7814E2E23}.ExportDebug|Any CPU.Build.0 = ExportDebug|Any CPU
|
16 |
+
{A5E8FC07-E73E-476D-93D5-2EA7814E2E23}.ExportRelease|Any CPU.ActiveCfg = ExportRelease|Any CPU
|
17 |
+
{A5E8FC07-E73E-476D-93D5-2EA7814E2E23}.ExportRelease|Any CPU.Build.0 = ExportRelease|Any CPU
|
18 |
+
EndGlobalSection
|
19 |
+
EndGlobal
|
Completed/addons/godot_rl_agents/controller/ai_controller_2d.gd
ADDED
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
extends Node2D
|
2 |
+
class_name AIController2D
|
3 |
+
|
4 |
+
enum ControlModes {
|
5 |
+
INHERIT_FROM_SYNC, ## Inherit setting from sync node
|
6 |
+
HUMAN, ## Test the environment manually
|
7 |
+
TRAINING, ## Train a model
|
8 |
+
ONNX_INFERENCE, ## Load a pretrained model using an .onnx file
|
9 |
+
RECORD_EXPERT_DEMOS ## Record observations and actions for expert demonstrations
|
10 |
+
}
|
11 |
+
@export var control_mode: ControlModes = ControlModes.INHERIT_FROM_SYNC
|
12 |
+
## The path to a trained .onnx model file to use for inference (overrides the path set in sync node).
|
13 |
+
@export var onnx_model_path := ""
|
14 |
+
## Once the number of steps has passed, the flag 'needs_reset' will be set to 'true' for this instance.
|
15 |
+
@export var reset_after := 1000
|
16 |
+
|
17 |
+
@export_group("Record expert demos mode options")
|
18 |
+
## Path where the demos will be saved. The file can later be used for imitation learning.
|
19 |
+
@export var expert_demo_save_path: String
|
20 |
+
## The action that erases the last recorded episode from the currently recorded data.
|
21 |
+
@export var remove_last_episode_key: InputEvent
|
22 |
+
## Action will be repeated for n frames. Will introduce control lag if larger than 1.
|
23 |
+
## Can be used to ensure that action_repeat on inference and training matches
|
24 |
+
## the recorded demonstrations.
|
25 |
+
@export var action_repeat: int = 1
|
26 |
+
|
27 |
+
@export_group("Multi-policy mode options")
|
28 |
+
## Allows you to set certain agents to use different policies.
|
29 |
+
## Changing has no effect with default SB3 training. Works with Rllib example.
|
30 |
+
## Tutorial: https://github.com/edbeeching/godot_rl_agents/blob/main/docs/TRAINING_MULTIPLE_POLICIES.md
|
31 |
+
@export var policy_name: String = "shared_policy"
|
32 |
+
|
33 |
+
var onnx_model: ONNXModel
|
34 |
+
|
35 |
+
var heuristic := "human"
|
36 |
+
var done := false
|
37 |
+
var reward := 0.0
|
38 |
+
var n_steps := 0
|
39 |
+
var needs_reset := false
|
40 |
+
|
41 |
+
var _player: Node2D
|
42 |
+
|
43 |
+
|
44 |
+
func _ready():
|
45 |
+
add_to_group("AGENT")
|
46 |
+
|
47 |
+
|
48 |
+
func init(player: Node2D):
|
49 |
+
_player = player
|
50 |
+
|
51 |
+
|
52 |
+
#-- Methods that need implementing using the "extend script" option in Godot --#
|
53 |
+
func get_obs() -> Dictionary:
|
54 |
+
assert(false, "the get_obs method is not implemented when extending from ai_controller")
|
55 |
+
return {"obs": []}
|
56 |
+
|
57 |
+
|
58 |
+
func get_reward() -> float:
|
59 |
+
assert(false, "the get_reward method is not implemented when extending from ai_controller")
|
60 |
+
return 0.0
|
61 |
+
|
62 |
+
|
63 |
+
func get_action_space() -> Dictionary:
|
64 |
+
assert(
|
65 |
+
false,
|
66 |
+
"the get get_action_space method is not implemented when extending from ai_controller"
|
67 |
+
)
|
68 |
+
return {
|
69 |
+
"example_actions_continous": {"size": 2, "action_type": "continuous"},
|
70 |
+
"example_actions_discrete": {"size": 2, "action_type": "discrete"},
|
71 |
+
}
|
72 |
+
|
73 |
+
|
74 |
+
func set_action(action) -> void:
|
75 |
+
assert(false, "the set_action method is not implemented when extending from ai_controller")
|
76 |
+
|
77 |
+
|
78 |
+
#-----------------------------------------------------------------------------#
|
79 |
+
|
80 |
+
|
81 |
+
#-- Methods that sometimes need implementing using the "extend script" option in Godot --#
|
82 |
+
# Only needed if you are recording expert demos with this AIController
|
83 |
+
func get_action() -> Array:
|
84 |
+
assert(false, "the get_action method is not implemented in extended AIController but demo_recorder is used")
|
85 |
+
return []
|
86 |
+
|
87 |
+
# -----------------------------------------------------------------------------#
|
88 |
+
|
89 |
+
func _physics_process(delta):
|
90 |
+
n_steps += 1
|
91 |
+
if n_steps > reset_after:
|
92 |
+
needs_reset = true
|
93 |
+
|
94 |
+
|
95 |
+
func get_obs_space():
|
96 |
+
# may need overriding if the obs space is complex
|
97 |
+
var obs = get_obs()
|
98 |
+
return {
|
99 |
+
"obs": {"size": [len(obs["obs"])], "space": "box"},
|
100 |
+
}
|
101 |
+
|
102 |
+
|
103 |
+
func reset():
|
104 |
+
n_steps = 0
|
105 |
+
needs_reset = false
|
106 |
+
|
107 |
+
|
108 |
+
func reset_if_done():
|
109 |
+
if done:
|
110 |
+
reset()
|
111 |
+
|
112 |
+
|
113 |
+
func set_heuristic(h):
|
114 |
+
# sets the heuristic from "human" or "model" nothing to change here
|
115 |
+
heuristic = h
|
116 |
+
|
117 |
+
|
118 |
+
func get_done():
|
119 |
+
return done
|
120 |
+
|
121 |
+
|
122 |
+
func set_done_false():
|
123 |
+
done = false
|
124 |
+
|
125 |
+
|
126 |
+
func zero_reward():
|
127 |
+
reward = 0.0
|
Completed/addons/godot_rl_agents/controller/ai_controller_3d.gd
ADDED
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
extends Node3D
|
2 |
+
class_name AIController3D
|
3 |
+
|
4 |
+
enum ControlModes {
|
5 |
+
INHERIT_FROM_SYNC, ## Inherit setting from sync node
|
6 |
+
HUMAN, ## Test the environment manually
|
7 |
+
TRAINING, ## Train a model
|
8 |
+
ONNX_INFERENCE, ## Load a pretrained model using an .onnx file
|
9 |
+
RECORD_EXPERT_DEMOS ## Record observations and actions for expert demonstrations
|
10 |
+
}
|
11 |
+
@export var control_mode: ControlModes = ControlModes.INHERIT_FROM_SYNC
|
12 |
+
## The path to a trained .onnx model file to use for inference (overrides the path set in sync node).
|
13 |
+
@export var onnx_model_path := ""
|
14 |
+
## Once the number of steps has passed, the flag 'needs_reset' will be set to 'true' for this instance.
|
15 |
+
@export var reset_after := 1000
|
16 |
+
|
17 |
+
@export_group("Record expert demos mode options")
|
18 |
+
## Path where the demos will be saved. The file can later be used for imitation learning.
|
19 |
+
@export var expert_demo_save_path: String
|
20 |
+
## The action that erases the last recorded episode from the currently recorded data.
|
21 |
+
@export var remove_last_episode_key: InputEvent
|
22 |
+
## Action will be repeated for n frames. Will introduce control lag if larger than 1.
|
23 |
+
## Can be used to ensure that action_repeat on inference and training matches
|
24 |
+
## the recorded demonstrations.
|
25 |
+
@export var action_repeat: int = 1
|
26 |
+
|
27 |
+
@export_group("Multi-policy mode options")
|
28 |
+
## Allows you to set certain agents to use different policies.
|
29 |
+
## Changing has no effect with default SB3 training. Works with Rllib example.
|
30 |
+
## Tutorial: https://github.com/edbeeching/godot_rl_agents/blob/main/docs/TRAINING_MULTIPLE_POLICIES.md
|
31 |
+
@export var policy_name: String = "shared_policy"
|
32 |
+
|
33 |
+
var onnx_model: ONNXModel
|
34 |
+
|
35 |
+
var heuristic := "human"
|
36 |
+
var done := false
|
37 |
+
var reward := 0.0
|
38 |
+
var n_steps := 0
|
39 |
+
var needs_reset := false
|
40 |
+
|
41 |
+
var _player: Node3D
|
42 |
+
|
43 |
+
|
44 |
+
func _ready():
|
45 |
+
add_to_group("AGENT")
|
46 |
+
|
47 |
+
|
48 |
+
func init(player: Node3D):
|
49 |
+
_player = player
|
50 |
+
|
51 |
+
|
52 |
+
#-- Methods that need implementing using the "extend script" option in Godot --#
|
53 |
+
func get_obs() -> Dictionary:
|
54 |
+
assert(false, "the get_obs method is not implemented when extending from ai_controller")
|
55 |
+
return {"obs": []}
|
56 |
+
|
57 |
+
|
58 |
+
func get_reward() -> float:
|
59 |
+
assert(false, "the get_reward method is not implemented when extending from ai_controller")
|
60 |
+
return 0.0
|
61 |
+
|
62 |
+
|
63 |
+
func get_action_space() -> Dictionary:
|
64 |
+
assert(
|
65 |
+
false,
|
66 |
+
"the get_action_space method is not implemented when extending from ai_controller"
|
67 |
+
)
|
68 |
+
return {
|
69 |
+
"example_actions_continous": {"size": 2, "action_type": "continuous"},
|
70 |
+
"example_actions_discrete": {"size": 2, "action_type": "discrete"},
|
71 |
+
}
|
72 |
+
|
73 |
+
|
74 |
+
func set_action(action) -> void:
|
75 |
+
assert(false, "the set_action method is not implemented when extending from ai_controller")
|
76 |
+
|
77 |
+
|
78 |
+
#-----------------------------------------------------------------------------#
|
79 |
+
|
80 |
+
|
81 |
+
#-- Methods that sometimes need implementing using the "extend script" option in Godot --#
|
82 |
+
# Only needed if you are recording expert demos with this AIController
|
83 |
+
func get_action() -> Array:
|
84 |
+
assert(false, "the get_action method is not implemented in extended AIController but demo_recorder is used")
|
85 |
+
return []
|
86 |
+
|
87 |
+
# -----------------------------------------------------------------------------#
|
88 |
+
|
89 |
+
|
90 |
+
func _physics_process(delta):
|
91 |
+
n_steps += 1
|
92 |
+
if n_steps > reset_after:
|
93 |
+
needs_reset = true
|
94 |
+
|
95 |
+
|
96 |
+
func get_obs_space():
|
97 |
+
# may need overriding if the obs space is complex
|
98 |
+
var obs = get_obs()
|
99 |
+
return {
|
100 |
+
"obs": {"size": [len(obs["obs"])], "space": "box"},
|
101 |
+
}
|
102 |
+
|
103 |
+
|
104 |
+
func reset():
|
105 |
+
n_steps = 0
|
106 |
+
needs_reset = false
|
107 |
+
|
108 |
+
|
109 |
+
func reset_if_done():
|
110 |
+
if done:
|
111 |
+
reset()
|
112 |
+
|
113 |
+
|
114 |
+
func set_heuristic(h):
|
115 |
+
# sets the heuristic from "human" or "model" nothing to change here
|
116 |
+
heuristic = h
|
117 |
+
|
118 |
+
|
119 |
+
func get_done():
|
120 |
+
return done
|
121 |
+
|
122 |
+
|
123 |
+
func set_done_false():
|
124 |
+
done = false
|
125 |
+
|
126 |
+
|
127 |
+
func zero_reward():
|
128 |
+
reward = 0.0
|
Completed/addons/godot_rl_agents/godot_rl_agents.gd
ADDED
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
@tool
|
2 |
+
extends EditorPlugin
|
3 |
+
|
4 |
+
|
5 |
+
func _enter_tree():
|
6 |
+
# Initialization of the plugin goes here.
|
7 |
+
# Add the new type with a name, a parent type, a script and an icon.
|
8 |
+
add_custom_type("Sync", "Node", preload("sync.gd"), preload("icon.png"))
|
9 |
+
#add_custom_type("RaycastSensor2D2", "Node", preload("raycast_sensor_2d.gd"), preload("icon.png"))
|
10 |
+
|
11 |
+
|
12 |
+
func _exit_tree():
|
13 |
+
# Clean-up of the plugin goes here.
|
14 |
+
# Always remember to remove it from the engine when deactivated.
|
15 |
+
remove_custom_type("Sync")
|
16 |
+
#remove_custom_type("RaycastSensor2D2")
|
Completed/addons/godot_rl_agents/icon.png
ADDED
Git LFS Details
|
Completed/addons/godot_rl_agents/onnx/csharp/ONNXInference.cs
ADDED
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
using Godot;
|
2 |
+
using Microsoft.ML.OnnxRuntime;
|
3 |
+
using Microsoft.ML.OnnxRuntime.Tensors;
|
4 |
+
using System.Collections.Generic;
|
5 |
+
using System.Linq;
|
6 |
+
|
7 |
+
namespace GodotONNX
|
8 |
+
{
|
9 |
+
/// <include file='docs/ONNXInference.xml' path='docs/members[@name="ONNXInference"]/ONNXInference/*'/>
|
10 |
+
public partial class ONNXInference : GodotObject
|
11 |
+
{
|
12 |
+
|
13 |
+
private InferenceSession session;
|
14 |
+
/// <summary>
|
15 |
+
/// Path to the ONNX model. Use Initialize to change it.
|
16 |
+
/// </summary>
|
17 |
+
private string modelPath;
|
18 |
+
private int batchSize;
|
19 |
+
|
20 |
+
private SessionOptions SessionOpt;
|
21 |
+
|
22 |
+
/// <summary>
|
23 |
+
/// init function
|
24 |
+
/// </summary>
|
25 |
+
/// <param name="Path"></param>
|
26 |
+
/// <param name="BatchSize"></param>
|
27 |
+
/// <returns>Returns the output size of the model</returns>
|
28 |
+
public int Initialize(string Path, int BatchSize)
|
29 |
+
{
|
30 |
+
modelPath = Path;
|
31 |
+
batchSize = BatchSize;
|
32 |
+
SessionOpt = SessionConfigurator.MakeConfiguredSessionOptions();
|
33 |
+
session = LoadModel(modelPath);
|
34 |
+
return session.OutputMetadata["output"].Dimensions[1];
|
35 |
+
}
|
36 |
+
|
37 |
+
|
38 |
+
/// <include file='docs/ONNXInference.xml' path='docs/members[@name="ONNXInference"]/Run/*'/>
|
39 |
+
public Godot.Collections.Dictionary<string, Godot.Collections.Array<float>> RunInference(Godot.Collections.Array<float> obs, int state_ins)
|
40 |
+
{
|
41 |
+
//Current model: Any (Godot Rl Agents)
|
42 |
+
//Expects a tensor of shape [batch_size, input_size] type float named obs and a tensor of shape [batch_size] type float named state_ins
|
43 |
+
|
44 |
+
//Fill the input tensors
|
45 |
+
// create span from inputSize
|
46 |
+
var span = new float[obs.Count]; //There's probably a better way to do this
|
47 |
+
for (int i = 0; i < obs.Count; i++)
|
48 |
+
{
|
49 |
+
span[i] = obs[i];
|
50 |
+
}
|
51 |
+
|
52 |
+
IReadOnlyCollection<NamedOnnxValue> inputs = new List<NamedOnnxValue>
|
53 |
+
{
|
54 |
+
NamedOnnxValue.CreateFromTensor("obs", new DenseTensor<float>(span, new int[] { batchSize, obs.Count })),
|
55 |
+
NamedOnnxValue.CreateFromTensor("state_ins", new DenseTensor<float>(new float[] { state_ins }, new int[] { batchSize }))
|
56 |
+
};
|
57 |
+
IReadOnlyCollection<string> outputNames = new List<string> { "output", "state_outs" }; //ONNX is sensible to these names, as well as the input names
|
58 |
+
|
59 |
+
IDisposableReadOnlyCollection<DisposableNamedOnnxValue> results;
|
60 |
+
//We do not use "using" here so we get a better exception explaination later
|
61 |
+
try
|
62 |
+
{
|
63 |
+
results = session.Run(inputs, outputNames);
|
64 |
+
}
|
65 |
+
catch (OnnxRuntimeException e)
|
66 |
+
{
|
67 |
+
//This error usually means that the model is not compatible with the input, beacause of the input shape (size)
|
68 |
+
GD.Print("Error at inference: ", e);
|
69 |
+
return null;
|
70 |
+
}
|
71 |
+
//Can't convert IEnumerable<float> to Variant, so we have to convert it to an array or something
|
72 |
+
Godot.Collections.Dictionary<string, Godot.Collections.Array<float>> output = new Godot.Collections.Dictionary<string, Godot.Collections.Array<float>>();
|
73 |
+
DisposableNamedOnnxValue output1 = results.First();
|
74 |
+
DisposableNamedOnnxValue output2 = results.Last();
|
75 |
+
Godot.Collections.Array<float> output1Array = new Godot.Collections.Array<float>();
|
76 |
+
Godot.Collections.Array<float> output2Array = new Godot.Collections.Array<float>();
|
77 |
+
|
78 |
+
foreach (float f in output1.AsEnumerable<float>())
|
79 |
+
{
|
80 |
+
output1Array.Add(f);
|
81 |
+
}
|
82 |
+
|
83 |
+
foreach (float f in output2.AsEnumerable<float>())
|
84 |
+
{
|
85 |
+
output2Array.Add(f);
|
86 |
+
}
|
87 |
+
|
88 |
+
output.Add(output1.Name, output1Array);
|
89 |
+
output.Add(output2.Name, output2Array);
|
90 |
+
|
91 |
+
//Output is a dictionary of arrays, ex: { "output" : [0.1, 0.2, 0.3, 0.4, ...], "state_outs" : [0.5, ...]}
|
92 |
+
results.Dispose();
|
93 |
+
return output;
|
94 |
+
}
|
95 |
+
/// <include file='docs/ONNXInference.xml' path='docs/members[@name="ONNXInference"]/Load/*'/>
|
96 |
+
public InferenceSession LoadModel(string Path)
|
97 |
+
{
|
98 |
+
using Godot.FileAccess file = FileAccess.Open(Path, Godot.FileAccess.ModeFlags.Read);
|
99 |
+
byte[] model = file.GetBuffer((int)file.GetLength());
|
100 |
+
//file.Close(); file.Dispose(); //Close the file, then dispose the reference.
|
101 |
+
return new InferenceSession(model, SessionOpt); //Load the model
|
102 |
+
}
|
103 |
+
public void FreeDisposables()
|
104 |
+
{
|
105 |
+
session.Dispose();
|
106 |
+
SessionOpt.Dispose();
|
107 |
+
}
|
108 |
+
}
|
109 |
+
}
|
Completed/addons/godot_rl_agents/onnx/csharp/SessionConfigurator.cs
ADDED
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
using Godot;
|
2 |
+
using Microsoft.ML.OnnxRuntime;
|
3 |
+
|
4 |
+
namespace GodotONNX
|
5 |
+
{
|
6 |
+
/// <include file='docs/SessionConfigurator.xml' path='docs/members[@name="SessionConfigurator"]/SessionConfigurator/*'/>
|
7 |
+
|
8 |
+
public static class SessionConfigurator
|
9 |
+
{
|
10 |
+
public enum ComputeName
|
11 |
+
{
|
12 |
+
CUDA,
|
13 |
+
ROCm,
|
14 |
+
DirectML,
|
15 |
+
CoreML,
|
16 |
+
CPU
|
17 |
+
}
|
18 |
+
|
19 |
+
/// <include file='docs/SessionConfigurator.xml' path='docs/members[@name="SessionConfigurator"]/GetSessionOptions/*'/>
|
20 |
+
public static SessionOptions MakeConfiguredSessionOptions()
|
21 |
+
{
|
22 |
+
SessionOptions sessionOptions = new();
|
23 |
+
SetOptions(sessionOptions);
|
24 |
+
return sessionOptions;
|
25 |
+
}
|
26 |
+
|
27 |
+
private static void SetOptions(SessionOptions sessionOptions)
|
28 |
+
{
|
29 |
+
sessionOptions.LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_WARNING;
|
30 |
+
ApplySystemSpecificOptions(sessionOptions);
|
31 |
+
}
|
32 |
+
|
33 |
+
/// <include file='docs/SessionConfigurator.xml' path='docs/members[@name="SessionConfigurator"]/SystemCheck/*'/>
|
34 |
+
static public void ApplySystemSpecificOptions(SessionOptions sessionOptions)
|
35 |
+
{
|
36 |
+
//Most code for this function is verbose only, the only reason it exists is to track
|
37 |
+
//implementation progress of the different compute APIs.
|
38 |
+
|
39 |
+
//December 2022: CUDA is not working.
|
40 |
+
|
41 |
+
string OSName = OS.GetName(); //Get OS Name
|
42 |
+
|
43 |
+
//ComputeName ComputeAPI = ComputeCheck(); //Get Compute API
|
44 |
+
// //TODO: Get CPU architecture
|
45 |
+
|
46 |
+
//Linux can use OpenVINO (C#) on x64 and ROCm on x86 (GDNative/C++)
|
47 |
+
//Windows can use OpenVINO (C#) on x64
|
48 |
+
//TODO: try TensorRT instead of CUDA
|
49 |
+
//TODO: Use OpenVINO for Intel Graphics
|
50 |
+
|
51 |
+
// Temporarily using CPU on all platforms to avoid errors detected with DML
|
52 |
+
ComputeName ComputeAPI = ComputeName.CPU;
|
53 |
+
|
54 |
+
//match OS and Compute API
|
55 |
+
GD.Print($"OS: {OSName} Compute API: {ComputeAPI}");
|
56 |
+
|
57 |
+
// CPU is set by default without appending necessary
|
58 |
+
// sessionOptions.AppendExecutionProvider_CPU(0);
|
59 |
+
|
60 |
+
/*
|
61 |
+
switch (OSName)
|
62 |
+
{
|
63 |
+
case "Windows": //Can use CUDA, DirectML
|
64 |
+
if (ComputeAPI is ComputeName.CUDA)
|
65 |
+
{
|
66 |
+
//CUDA
|
67 |
+
//sessionOptions.AppendExecutionProvider_CUDA(0);
|
68 |
+
//sessionOptions.AppendExecutionProvider_DML(0);
|
69 |
+
}
|
70 |
+
else if (ComputeAPI is ComputeName.DirectML)
|
71 |
+
{
|
72 |
+
//DirectML
|
73 |
+
//sessionOptions.AppendExecutionProvider_DML(0);
|
74 |
+
}
|
75 |
+
break;
|
76 |
+
case "X11": //Can use CUDA, ROCm
|
77 |
+
if (ComputeAPI is ComputeName.CUDA)
|
78 |
+
{
|
79 |
+
//CUDA
|
80 |
+
//sessionOptions.AppendExecutionProvider_CUDA(0);
|
81 |
+
}
|
82 |
+
if (ComputeAPI is ComputeName.ROCm)
|
83 |
+
{
|
84 |
+
//ROCm, only works on x86
|
85 |
+
//Research indicates that this has to be compiled as a GDNative plugin
|
86 |
+
//GD.Print("ROCm not supported yet, using CPU.");
|
87 |
+
//sessionOptions.AppendExecutionProvider_CPU(0);
|
88 |
+
}
|
89 |
+
break;
|
90 |
+
case "macOS": //Can use CoreML
|
91 |
+
if (ComputeAPI is ComputeName.CoreML)
|
92 |
+
{ //CoreML
|
93 |
+
//TODO: Needs testing
|
94 |
+
//sessionOptions.AppendExecutionProvider_CoreML(0);
|
95 |
+
//CoreML on ARM64, out of the box, on x64 needs .tar file from GitHub
|
96 |
+
}
|
97 |
+
break;
|
98 |
+
default:
|
99 |
+
GD.Print("OS not Supported.");
|
100 |
+
break;
|
101 |
+
}
|
102 |
+
*/
|
103 |
+
}
|
104 |
+
|
105 |
+
|
106 |
+
/// <include file='docs/SessionConfigurator.xml' path='docs/members[@name="SessionConfigurator"]/ComputeCheck/*'/>
|
107 |
+
public static ComputeName ComputeCheck()
|
108 |
+
{
|
109 |
+
string adapterName = Godot.RenderingServer.GetVideoAdapterName();
|
110 |
+
//string adapterVendor = Godot.RenderingServer.GetVideoAdapterVendor();
|
111 |
+
adapterName = adapterName.ToUpper(new System.Globalization.CultureInfo(""));
|
112 |
+
//TODO: GPU vendors for MacOS, what do they even use these days?
|
113 |
+
|
114 |
+
if (adapterName.Contains("INTEL"))
|
115 |
+
{
|
116 |
+
return ComputeName.DirectML;
|
117 |
+
}
|
118 |
+
if (adapterName.Contains("AMD") || adapterName.Contains("RADEON"))
|
119 |
+
{
|
120 |
+
return ComputeName.DirectML;
|
121 |
+
}
|
122 |
+
if (adapterName.Contains("NVIDIA"))
|
123 |
+
{
|
124 |
+
return ComputeName.CUDA;
|
125 |
+
}
|
126 |
+
|
127 |
+
GD.Print("Graphics Card not recognized."); //Should use CPU
|
128 |
+
return ComputeName.CPU;
|
129 |
+
}
|
130 |
+
}
|
131 |
+
}
|
Completed/addons/godot_rl_agents/onnx/csharp/docs/ONNXInference.xml
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<docs>
|
2 |
+
<members name="ONNXInference">
|
3 |
+
<ONNXInference>
|
4 |
+
<summary>
|
5 |
+
The main <c>ONNXInference</c> Class that handles the inference process.
|
6 |
+
</summary>
|
7 |
+
</ONNXInference>
|
8 |
+
<Initialize>
|
9 |
+
<summary>
|
10 |
+
Starts the inference process.
|
11 |
+
</summary>
|
12 |
+
<param name="Path">Path to the ONNX model, expects a path inside resources.</param>
|
13 |
+
<param name="BatchSize">How many observations will the model recieve.</param>
|
14 |
+
</Initialize>
|
15 |
+
<Run>
|
16 |
+
<summary>
|
17 |
+
Runs the given input through the model and returns the output.
|
18 |
+
</summary>
|
19 |
+
<param name="obs">Dictionary containing all observations.</param>
|
20 |
+
<param name="state_ins">How many different agents are creating these observations.</param>
|
21 |
+
<returns>A Dictionary of arrays, containing instructions based on the observations.</returns>
|
22 |
+
</Run>
|
23 |
+
<Load>
|
24 |
+
<summary>
|
25 |
+
Loads the given model into the inference process, using the best Execution provider available.
|
26 |
+
</summary>
|
27 |
+
<param name="Path">Path to the ONNX model, expects a path inside resources.</param>
|
28 |
+
<returns>InferenceSession ready to run.</returns>
|
29 |
+
</Load>
|
30 |
+
</members>
|
31 |
+
</docs>
|
Completed/addons/godot_rl_agents/onnx/csharp/docs/SessionConfigurator.xml
ADDED
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<docs>
|
2 |
+
<members name="SessionConfigurator">
|
3 |
+
<SessionConfigurator>
|
4 |
+
<summary>
|
5 |
+
The main <c>SessionConfigurator</c> Class that handles the execution options and providers for the inference process.
|
6 |
+
</summary>
|
7 |
+
</SessionConfigurator>
|
8 |
+
<GetSessionOptions>
|
9 |
+
<summary>
|
10 |
+
Creates a SessionOptions with all available execution providers.
|
11 |
+
</summary>
|
12 |
+
<returns>SessionOptions with all available execution providers.</returns>
|
13 |
+
</GetSessionOptions>
|
14 |
+
<SystemCheck>
|
15 |
+
<summary>
|
16 |
+
Appends any execution provider available in the current system.
|
17 |
+
</summary>
|
18 |
+
<remarks>
|
19 |
+
This function is mainly verbose for tracking implementation progress of different compute APIs.
|
20 |
+
</remarks>
|
21 |
+
</SystemCheck>
|
22 |
+
<ComputeCheck>
|
23 |
+
<summary>
|
24 |
+
Checks for available GPUs.
|
25 |
+
</summary>
|
26 |
+
<returns>An integer identifier for each compute platform.</returns>
|
27 |
+
</ComputeCheck>
|
28 |
+
</members>
|
29 |
+
</docs>
|
Completed/addons/godot_rl_agents/onnx/wrapper/ONNX_wrapper.gd
ADDED
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
extends Resource
|
2 |
+
class_name ONNXModel
|
3 |
+
var inferencer_script = load("res://addons/godot_rl_agents/onnx/csharp/ONNXInference.cs")
|
4 |
+
|
5 |
+
var inferencer = null
|
6 |
+
|
7 |
+
## How many action values the model outputs
|
8 |
+
var action_output_size: int
|
9 |
+
|
10 |
+
## Used to differentiate models
|
11 |
+
## that only output continuous action mean (e.g. sb3, cleanrl export)
|
12 |
+
## versus models that output mean and logstd (e.g. rllib export)
|
13 |
+
var action_means_only: bool
|
14 |
+
|
15 |
+
## Whether action_means_value has been set already for this model
|
16 |
+
var action_means_only_set: bool
|
17 |
+
|
18 |
+
# Must provide the path to the model and the batch size
|
19 |
+
func _init(model_path, batch_size):
|
20 |
+
inferencer = inferencer_script.new()
|
21 |
+
action_output_size = inferencer.Initialize(model_path, batch_size)
|
22 |
+
|
23 |
+
# This function is the one that will be called from the game,
|
24 |
+
# requires the observation as an array and the state_ins as an int
|
25 |
+
# returns an Array containing the action the model takes.
|
26 |
+
func run_inference(obs: Array, state_ins: int) -> Dictionary:
|
27 |
+
if inferencer == null:
|
28 |
+
printerr("Inferencer not initialized")
|
29 |
+
return {}
|
30 |
+
return inferencer.RunInference(obs, state_ins)
|
31 |
+
|
32 |
+
|
33 |
+
func _notification(what):
|
34 |
+
if what == NOTIFICATION_PREDELETE:
|
35 |
+
inferencer.FreeDisposables()
|
36 |
+
inferencer.free()
|
37 |
+
|
38 |
+
# Check whether agent uses a continuous actions model with only action means or not
|
39 |
+
func set_action_means_only(agent_action_space):
|
40 |
+
action_means_only_set = true
|
41 |
+
var continuous_only: bool = true
|
42 |
+
var continuous_actions: int
|
43 |
+
for action in agent_action_space:
|
44 |
+
if not agent_action_space[action]["action_type"] == "continuous":
|
45 |
+
continuous_only = false
|
46 |
+
break
|
47 |
+
else:
|
48 |
+
continuous_actions += agent_action_space[action]["size"]
|
49 |
+
if continuous_only:
|
50 |
+
if continuous_actions == action_output_size:
|
51 |
+
action_means_only = true
|
Completed/addons/godot_rl_agents/plugin.cfg
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[plugin]
|
2 |
+
|
3 |
+
name="GodotRLAgents"
|
4 |
+
description="Custom nodes for the godot rl agents toolkit "
|
5 |
+
author="Edward Beeching"
|
6 |
+
version="0.1"
|
7 |
+
script="godot_rl_agents.gd"
|
Completed/addons/godot_rl_agents/sensors/sensors_2d/ExampleRaycastSensor2D.tscn
ADDED
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[gd_scene load_steps=5 format=3 uid="uid://ddeq7mn1ealyc"]
|
2 |
+
|
3 |
+
[ext_resource type="Script" path="res://addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.gd" id="1"]
|
4 |
+
|
5 |
+
[sub_resource type="GDScript" id="2"]
|
6 |
+
script/source = "extends Node2D
|
7 |
+
|
8 |
+
|
9 |
+
|
10 |
+
func _physics_process(delta: float) -> void:
|
11 |
+
print(\"step start\")
|
12 |
+
|
13 |
+
"
|
14 |
+
|
15 |
+
[sub_resource type="GDScript" id="1"]
|
16 |
+
script/source = "extends RayCast2D
|
17 |
+
|
18 |
+
var steps = 1
|
19 |
+
|
20 |
+
func _physics_process(delta: float) -> void:
|
21 |
+
print(\"processing raycast\")
|
22 |
+
steps += 1
|
23 |
+
if steps % 2:
|
24 |
+
force_raycast_update()
|
25 |
+
|
26 |
+
print(is_colliding())
|
27 |
+
"
|
28 |
+
|
29 |
+
[sub_resource type="CircleShape2D" id="3"]
|
30 |
+
|
31 |
+
[node name="ExampleRaycastSensor2D" type="Node2D"]
|
32 |
+
script = SubResource("2")
|
33 |
+
|
34 |
+
[node name="ExampleAgent" type="Node2D" parent="."]
|
35 |
+
position = Vector2(573, 314)
|
36 |
+
rotation = 0.286234
|
37 |
+
|
38 |
+
[node name="RaycastSensor2D" type="Node2D" parent="ExampleAgent"]
|
39 |
+
script = ExtResource("1")
|
40 |
+
|
41 |
+
[node name="TestRayCast2D" type="RayCast2D" parent="."]
|
42 |
+
script = SubResource("1")
|
43 |
+
|
44 |
+
[node name="StaticBody2D" type="StaticBody2D" parent="."]
|
45 |
+
position = Vector2(1, 52)
|
46 |
+
|
47 |
+
[node name="CollisionShape2D" type="CollisionShape2D" parent="StaticBody2D"]
|
48 |
+
shape = SubResource("3")
|
Completed/addons/godot_rl_agents/sensors/sensors_2d/GridSensor2D.gd
ADDED
@@ -0,0 +1,235 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
@tool
|
2 |
+
extends ISensor2D
|
3 |
+
class_name GridSensor2D
|
4 |
+
|
5 |
+
@export var debug_view := false:
|
6 |
+
get:
|
7 |
+
return debug_view
|
8 |
+
set(value):
|
9 |
+
debug_view = value
|
10 |
+
_update()
|
11 |
+
|
12 |
+
@export_flags_2d_physics var detection_mask := 0:
|
13 |
+
get:
|
14 |
+
return detection_mask
|
15 |
+
set(value):
|
16 |
+
detection_mask = value
|
17 |
+
_update()
|
18 |
+
|
19 |
+
@export var collide_with_areas := false:
|
20 |
+
get:
|
21 |
+
return collide_with_areas
|
22 |
+
set(value):
|
23 |
+
collide_with_areas = value
|
24 |
+
_update()
|
25 |
+
|
26 |
+
@export var collide_with_bodies := true:
|
27 |
+
get:
|
28 |
+
return collide_with_bodies
|
29 |
+
set(value):
|
30 |
+
collide_with_bodies = value
|
31 |
+
_update()
|
32 |
+
|
33 |
+
@export_range(1, 200, 0.1) var cell_width := 20.0:
|
34 |
+
get:
|
35 |
+
return cell_width
|
36 |
+
set(value):
|
37 |
+
cell_width = value
|
38 |
+
_update()
|
39 |
+
|
40 |
+
@export_range(1, 200, 0.1) var cell_height := 20.0:
|
41 |
+
get:
|
42 |
+
return cell_height
|
43 |
+
set(value):
|
44 |
+
cell_height = value
|
45 |
+
_update()
|
46 |
+
|
47 |
+
@export_range(1, 21, 2, "or_greater") var grid_size_x := 3:
|
48 |
+
get:
|
49 |
+
return grid_size_x
|
50 |
+
set(value):
|
51 |
+
grid_size_x = value
|
52 |
+
_update()
|
53 |
+
|
54 |
+
@export_range(1, 21, 2, "or_greater") var grid_size_y := 3:
|
55 |
+
get:
|
56 |
+
return grid_size_y
|
57 |
+
set(value):
|
58 |
+
grid_size_y = value
|
59 |
+
_update()
|
60 |
+
|
61 |
+
var _obs_buffer: PackedFloat64Array
|
62 |
+
var _rectangle_shape: RectangleShape2D
|
63 |
+
var _collision_mapping: Dictionary
|
64 |
+
var _n_layers_per_cell: int
|
65 |
+
|
66 |
+
var _highlighted_cell_color: Color
|
67 |
+
var _standard_cell_color: Color
|
68 |
+
|
69 |
+
|
70 |
+
func get_observation():
|
71 |
+
return _obs_buffer
|
72 |
+
|
73 |
+
|
74 |
+
func _update():
|
75 |
+
if Engine.is_editor_hint():
|
76 |
+
if is_node_ready():
|
77 |
+
_spawn_nodes()
|
78 |
+
|
79 |
+
|
80 |
+
func _ready() -> void:
|
81 |
+
_set_colors()
|
82 |
+
|
83 |
+
if Engine.is_editor_hint():
|
84 |
+
if get_child_count() == 0:
|
85 |
+
_spawn_nodes()
|
86 |
+
else:
|
87 |
+
_spawn_nodes()
|
88 |
+
|
89 |
+
|
90 |
+
func _set_colors() -> void:
|
91 |
+
_standard_cell_color = Color(100.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0)
|
92 |
+
_highlighted_cell_color = Color(255.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0)
|
93 |
+
|
94 |
+
|
95 |
+
func _get_collision_mapping() -> Dictionary:
|
96 |
+
# defines which layer is mapped to which cell obs index
|
97 |
+
var total_bits = 0
|
98 |
+
var collision_mapping = {}
|
99 |
+
for i in 32:
|
100 |
+
var bit_mask = 2 ** i
|
101 |
+
if (detection_mask & bit_mask) > 0:
|
102 |
+
collision_mapping[i] = total_bits
|
103 |
+
total_bits += 1
|
104 |
+
|
105 |
+
return collision_mapping
|
106 |
+
|
107 |
+
|
108 |
+
func _spawn_nodes():
|
109 |
+
for cell in get_children():
|
110 |
+
cell.name = "_%s" % cell.name # Otherwise naming below will fail
|
111 |
+
cell.queue_free()
|
112 |
+
|
113 |
+
_collision_mapping = _get_collision_mapping()
|
114 |
+
#prints("collision_mapping", _collision_mapping, len(_collision_mapping))
|
115 |
+
# allocate memory for the observations
|
116 |
+
_n_layers_per_cell = len(_collision_mapping)
|
117 |
+
_obs_buffer = PackedFloat64Array()
|
118 |
+
_obs_buffer.resize(grid_size_x * grid_size_y * _n_layers_per_cell)
|
119 |
+
_obs_buffer.fill(0)
|
120 |
+
#prints(len(_obs_buffer), _obs_buffer )
|
121 |
+
|
122 |
+
_rectangle_shape = RectangleShape2D.new()
|
123 |
+
_rectangle_shape.set_size(Vector2(cell_width, cell_height))
|
124 |
+
|
125 |
+
var shift := Vector2(
|
126 |
+
-(grid_size_x / 2) * cell_width,
|
127 |
+
-(grid_size_y / 2) * cell_height,
|
128 |
+
)
|
129 |
+
|
130 |
+
for i in grid_size_x:
|
131 |
+
for j in grid_size_y:
|
132 |
+
var cell_position = Vector2(i * cell_width, j * cell_height) + shift
|
133 |
+
_create_cell(i, j, cell_position)
|
134 |
+
|
135 |
+
|
136 |
+
func _create_cell(i: int, j: int, position: Vector2):
|
137 |
+
var cell := Area2D.new()
|
138 |
+
cell.position = position
|
139 |
+
cell.name = "GridCell %s %s" % [i, j]
|
140 |
+
cell.modulate = _standard_cell_color
|
141 |
+
|
142 |
+
if collide_with_areas:
|
143 |
+
cell.area_entered.connect(_on_cell_area_entered.bind(i, j))
|
144 |
+
cell.area_exited.connect(_on_cell_area_exited.bind(i, j))
|
145 |
+
|
146 |
+
if collide_with_bodies:
|
147 |
+
cell.body_entered.connect(_on_cell_body_entered.bind(i, j))
|
148 |
+
cell.body_exited.connect(_on_cell_body_exited.bind(i, j))
|
149 |
+
|
150 |
+
cell.collision_layer = 0
|
151 |
+
cell.collision_mask = detection_mask
|
152 |
+
cell.monitorable = true
|
153 |
+
add_child(cell)
|
154 |
+
cell.set_owner(get_tree().edited_scene_root)
|
155 |
+
|
156 |
+
var col_shape := CollisionShape2D.new()
|
157 |
+
col_shape.shape = _rectangle_shape
|
158 |
+
col_shape.name = "CollisionShape2D"
|
159 |
+
cell.add_child(col_shape)
|
160 |
+
col_shape.set_owner(get_tree().edited_scene_root)
|
161 |
+
|
162 |
+
if debug_view:
|
163 |
+
var quad = MeshInstance2D.new()
|
164 |
+
quad.name = "MeshInstance2D"
|
165 |
+
var quad_mesh = QuadMesh.new()
|
166 |
+
|
167 |
+
quad_mesh.set_size(Vector2(cell_width, cell_height))
|
168 |
+
|
169 |
+
quad.mesh = quad_mesh
|
170 |
+
cell.add_child(quad)
|
171 |
+
quad.set_owner(get_tree().edited_scene_root)
|
172 |
+
|
173 |
+
|
174 |
+
func _update_obs(cell_i: int, cell_j: int, collision_layer: int, entered: bool):
|
175 |
+
for key in _collision_mapping:
|
176 |
+
var bit_mask = 2 ** key
|
177 |
+
if (collision_layer & bit_mask) > 0:
|
178 |
+
var collison_map_index = _collision_mapping[key]
|
179 |
+
|
180 |
+
var obs_index = (
|
181 |
+
(cell_i * grid_size_x * _n_layers_per_cell)
|
182 |
+
+ (cell_j * _n_layers_per_cell)
|
183 |
+
+ collison_map_index
|
184 |
+
)
|
185 |
+
#prints(obs_index, cell_i, cell_j)
|
186 |
+
if entered:
|
187 |
+
_obs_buffer[obs_index] += 1
|
188 |
+
else:
|
189 |
+
_obs_buffer[obs_index] -= 1
|
190 |
+
|
191 |
+
|
192 |
+
func _toggle_cell(cell_i: int, cell_j: int):
|
193 |
+
var cell = get_node_or_null("GridCell %s %s" % [cell_i, cell_j])
|
194 |
+
|
195 |
+
if cell == null:
|
196 |
+
print("cell not found, returning")
|
197 |
+
|
198 |
+
var n_hits = 0
|
199 |
+
var start_index = (cell_i * grid_size_x * _n_layers_per_cell) + (cell_j * _n_layers_per_cell)
|
200 |
+
for i in _n_layers_per_cell:
|
201 |
+
n_hits += _obs_buffer[start_index + i]
|
202 |
+
|
203 |
+
if n_hits > 0:
|
204 |
+
cell.modulate = _highlighted_cell_color
|
205 |
+
else:
|
206 |
+
cell.modulate = _standard_cell_color
|
207 |
+
|
208 |
+
|
209 |
+
func _on_cell_area_entered(area: Area2D, cell_i: int, cell_j: int):
|
210 |
+
#prints("_on_cell_area_entered", cell_i, cell_j)
|
211 |
+
_update_obs(cell_i, cell_j, area.collision_layer, true)
|
212 |
+
if debug_view:
|
213 |
+
_toggle_cell(cell_i, cell_j)
|
214 |
+
#print(_obs_buffer)
|
215 |
+
|
216 |
+
|
217 |
+
func _on_cell_area_exited(area: Area2D, cell_i: int, cell_j: int):
|
218 |
+
#prints("_on_cell_area_exited", cell_i, cell_j)
|
219 |
+
_update_obs(cell_i, cell_j, area.collision_layer, false)
|
220 |
+
if debug_view:
|
221 |
+
_toggle_cell(cell_i, cell_j)
|
222 |
+
|
223 |
+
|
224 |
+
func _on_cell_body_entered(body: Node2D, cell_i: int, cell_j: int):
|
225 |
+
#prints("_on_cell_body_entered", cell_i, cell_j)
|
226 |
+
_update_obs(cell_i, cell_j, body.collision_layer, true)
|
227 |
+
if debug_view:
|
228 |
+
_toggle_cell(cell_i, cell_j)
|
229 |
+
|
230 |
+
|
231 |
+
func _on_cell_body_exited(body: Node2D, cell_i: int, cell_j: int):
|
232 |
+
#prints("_on_cell_body_exited", cell_i, cell_j)
|
233 |
+
_update_obs(cell_i, cell_j, body.collision_layer, false)
|
234 |
+
if debug_view:
|
235 |
+
_toggle_cell(cell_i, cell_j)
|
Completed/addons/godot_rl_agents/sensors/sensors_2d/ISensor2D.gd
ADDED
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
extends Node2D
|
2 |
+
class_name ISensor2D
|
3 |
+
|
4 |
+
var _obs: Array = []
|
5 |
+
var _active := false
|
6 |
+
|
7 |
+
|
8 |
+
func get_observation():
|
9 |
+
pass
|
10 |
+
|
11 |
+
|
12 |
+
func activate():
|
13 |
+
_active = true
|
14 |
+
|
15 |
+
|
16 |
+
func deactivate():
|
17 |
+
_active = false
|
18 |
+
|
19 |
+
|
20 |
+
func _update_observation():
|
21 |
+
pass
|
22 |
+
|
23 |
+
|
24 |
+
func reset():
|
25 |
+
pass
|
Completed/addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.gd
ADDED
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
@tool
|
2 |
+
extends ISensor2D
|
3 |
+
class_name RaycastSensor2D
|
4 |
+
|
5 |
+
@export_flags_2d_physics var collision_mask := 1:
|
6 |
+
get:
|
7 |
+
return collision_mask
|
8 |
+
set(value):
|
9 |
+
collision_mask = value
|
10 |
+
_update()
|
11 |
+
|
12 |
+
@export var collide_with_areas := false:
|
13 |
+
get:
|
14 |
+
return collide_with_areas
|
15 |
+
set(value):
|
16 |
+
collide_with_areas = value
|
17 |
+
_update()
|
18 |
+
|
19 |
+
@export var collide_with_bodies := true:
|
20 |
+
get:
|
21 |
+
return collide_with_bodies
|
22 |
+
set(value):
|
23 |
+
collide_with_bodies = value
|
24 |
+
_update()
|
25 |
+
|
26 |
+
@export var n_rays := 16.0:
|
27 |
+
get:
|
28 |
+
return n_rays
|
29 |
+
set(value):
|
30 |
+
n_rays = value
|
31 |
+
_update()
|
32 |
+
|
33 |
+
@export_range(5, 3000, 5.0) var ray_length := 200:
|
34 |
+
get:
|
35 |
+
return ray_length
|
36 |
+
set(value):
|
37 |
+
ray_length = value
|
38 |
+
_update()
|
39 |
+
@export_range(5, 360, 5.0) var cone_width := 360.0:
|
40 |
+
get:
|
41 |
+
return cone_width
|
42 |
+
set(value):
|
43 |
+
cone_width = value
|
44 |
+
_update()
|
45 |
+
|
46 |
+
@export var debug_draw := true:
|
47 |
+
get:
|
48 |
+
return debug_draw
|
49 |
+
set(value):
|
50 |
+
debug_draw = value
|
51 |
+
_update()
|
52 |
+
|
53 |
+
var _angles = []
|
54 |
+
var rays := []
|
55 |
+
|
56 |
+
|
57 |
+
func _update():
|
58 |
+
if Engine.is_editor_hint():
|
59 |
+
if debug_draw:
|
60 |
+
_spawn_nodes()
|
61 |
+
else:
|
62 |
+
for ray in get_children():
|
63 |
+
if ray is RayCast2D:
|
64 |
+
remove_child(ray)
|
65 |
+
|
66 |
+
|
67 |
+
func _ready() -> void:
|
68 |
+
_spawn_nodes()
|
69 |
+
|
70 |
+
|
71 |
+
func _spawn_nodes():
|
72 |
+
for ray in rays:
|
73 |
+
ray.queue_free()
|
74 |
+
rays = []
|
75 |
+
|
76 |
+
_angles = []
|
77 |
+
var step = cone_width / (n_rays)
|
78 |
+
var start = step / 2 - cone_width / 2
|
79 |
+
|
80 |
+
for i in n_rays:
|
81 |
+
var angle = start + i * step
|
82 |
+
var ray = RayCast2D.new()
|
83 |
+
ray.set_target_position(
|
84 |
+
Vector2(ray_length * cos(deg_to_rad(angle)), ray_length * sin(deg_to_rad(angle)))
|
85 |
+
)
|
86 |
+
ray.set_name("node_" + str(i))
|
87 |
+
ray.enabled = false
|
88 |
+
ray.collide_with_areas = collide_with_areas
|
89 |
+
ray.collide_with_bodies = collide_with_bodies
|
90 |
+
ray.collision_mask = collision_mask
|
91 |
+
add_child(ray)
|
92 |
+
rays.append(ray)
|
93 |
+
|
94 |
+
_angles.append(start + i * step)
|
95 |
+
|
96 |
+
|
97 |
+
func get_observation() -> Array:
|
98 |
+
return self.calculate_raycasts()
|
99 |
+
|
100 |
+
|
101 |
+
func calculate_raycasts() -> Array:
|
102 |
+
var result = []
|
103 |
+
for ray in rays:
|
104 |
+
ray.enabled = true
|
105 |
+
ray.force_raycast_update()
|
106 |
+
var distance = _get_raycast_distance(ray)
|
107 |
+
result.append(distance)
|
108 |
+
ray.enabled = false
|
109 |
+
return result
|
110 |
+
|
111 |
+
|
112 |
+
func _get_raycast_distance(ray: RayCast2D) -> float:
|
113 |
+
if !ray.is_colliding():
|
114 |
+
return 0.0
|
115 |
+
|
116 |
+
var distance = (global_position - ray.get_collision_point()).length()
|
117 |
+
distance = clamp(distance, 0.0, ray_length)
|
118 |
+
return (ray_length - distance) / ray_length
|
Completed/addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.tscn
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[gd_scene load_steps=2 format=3 uid="uid://drvfihk5esgmv"]
|
2 |
+
|
3 |
+
[ext_resource type="Script" path="res://addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.gd" id="1"]
|
4 |
+
|
5 |
+
[node name="RaycastSensor2D" type="Node2D"]
|
6 |
+
script = ExtResource("1")
|
7 |
+
n_rays = 17.0
|
Completed/addons/godot_rl_agents/sensors/sensors_3d/ExampleRaycastSensor3D.tscn
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[gd_scene format=3 uid="uid://biu787qh4woik"]
|
2 |
+
|
3 |
+
[node name="ExampleRaycastSensor3D" type="Node3D"]
|
4 |
+
|
5 |
+
[node name="Camera3D" type="Camera3D" parent="."]
|
6 |
+
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0.804183, 0, 2.70146)
|
Completed/addons/godot_rl_agents/sensors/sensors_3d/GridSensor3D.gd
ADDED
@@ -0,0 +1,258 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
@tool
|
2 |
+
extends ISensor3D
|
3 |
+
class_name GridSensor3D
|
4 |
+
|
5 |
+
@export var debug_view := false:
|
6 |
+
get:
|
7 |
+
return debug_view
|
8 |
+
set(value):
|
9 |
+
debug_view = value
|
10 |
+
_update()
|
11 |
+
|
12 |
+
@export_flags_3d_physics var detection_mask := 0:
|
13 |
+
get:
|
14 |
+
return detection_mask
|
15 |
+
set(value):
|
16 |
+
detection_mask = value
|
17 |
+
_update()
|
18 |
+
|
19 |
+
@export var collide_with_areas := false:
|
20 |
+
get:
|
21 |
+
return collide_with_areas
|
22 |
+
set(value):
|
23 |
+
collide_with_areas = value
|
24 |
+
_update()
|
25 |
+
|
26 |
+
@export var collide_with_bodies := false:
|
27 |
+
# NOTE! The sensor will not detect StaticBody3D, add an area to static bodies to detect them
|
28 |
+
get:
|
29 |
+
return collide_with_bodies
|
30 |
+
set(value):
|
31 |
+
collide_with_bodies = value
|
32 |
+
_update()
|
33 |
+
|
34 |
+
@export_range(0.1, 2, 0.1) var cell_width := 1.0:
|
35 |
+
get:
|
36 |
+
return cell_width
|
37 |
+
set(value):
|
38 |
+
cell_width = value
|
39 |
+
_update()
|
40 |
+
|
41 |
+
@export_range(0.1, 2, 0.1) var cell_height := 1.0:
|
42 |
+
get:
|
43 |
+
return cell_height
|
44 |
+
set(value):
|
45 |
+
cell_height = value
|
46 |
+
_update()
|
47 |
+
|
48 |
+
@export_range(1, 21, 2, "or_greater") var grid_size_x := 3:
|
49 |
+
get:
|
50 |
+
return grid_size_x
|
51 |
+
set(value):
|
52 |
+
grid_size_x = value
|
53 |
+
_update()
|
54 |
+
|
55 |
+
@export_range(1, 21, 2, "or_greater") var grid_size_z := 3:
|
56 |
+
get:
|
57 |
+
return grid_size_z
|
58 |
+
set(value):
|
59 |
+
grid_size_z = value
|
60 |
+
_update()
|
61 |
+
|
62 |
+
var _obs_buffer: PackedFloat64Array
|
63 |
+
var _box_shape: BoxShape3D
|
64 |
+
var _collision_mapping: Dictionary
|
65 |
+
var _n_layers_per_cell: int
|
66 |
+
|
67 |
+
var _highlighted_box_material: StandardMaterial3D
|
68 |
+
var _standard_box_material: StandardMaterial3D
|
69 |
+
|
70 |
+
|
71 |
+
func get_observation():
|
72 |
+
return _obs_buffer
|
73 |
+
|
74 |
+
|
75 |
+
func reset():
|
76 |
+
_obs_buffer.fill(0)
|
77 |
+
|
78 |
+
|
79 |
+
func _update():
|
80 |
+
if Engine.is_editor_hint():
|
81 |
+
if is_node_ready():
|
82 |
+
_spawn_nodes()
|
83 |
+
|
84 |
+
|
85 |
+
func _ready() -> void:
|
86 |
+
_make_materials()
|
87 |
+
|
88 |
+
if Engine.is_editor_hint():
|
89 |
+
if get_child_count() == 0:
|
90 |
+
_spawn_nodes()
|
91 |
+
else:
|
92 |
+
_spawn_nodes()
|
93 |
+
|
94 |
+
|
95 |
+
func _make_materials() -> void:
|
96 |
+
if _highlighted_box_material != null and _standard_box_material != null:
|
97 |
+
return
|
98 |
+
|
99 |
+
_standard_box_material = StandardMaterial3D.new()
|
100 |
+
_standard_box_material.set_transparency(1) # ALPHA
|
101 |
+
_standard_box_material.albedo_color = Color(
|
102 |
+
100.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0
|
103 |
+
)
|
104 |
+
|
105 |
+
_highlighted_box_material = StandardMaterial3D.new()
|
106 |
+
_highlighted_box_material.set_transparency(1) # ALPHA
|
107 |
+
_highlighted_box_material.albedo_color = Color(
|
108 |
+
255.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0
|
109 |
+
)
|
110 |
+
|
111 |
+
|
112 |
+
func _get_collision_mapping() -> Dictionary:
|
113 |
+
# defines which layer is mapped to which cell obs index
|
114 |
+
var total_bits = 0
|
115 |
+
var collision_mapping = {}
|
116 |
+
for i in 32:
|
117 |
+
var bit_mask = 2 ** i
|
118 |
+
if (detection_mask & bit_mask) > 0:
|
119 |
+
collision_mapping[i] = total_bits
|
120 |
+
total_bits += 1
|
121 |
+
|
122 |
+
return collision_mapping
|
123 |
+
|
124 |
+
|
125 |
+
func _spawn_nodes():
|
126 |
+
for cell in get_children():
|
127 |
+
cell.name = "_%s" % cell.name # Otherwise naming below will fail
|
128 |
+
cell.queue_free()
|
129 |
+
|
130 |
+
_collision_mapping = _get_collision_mapping()
|
131 |
+
#prints("collision_mapping", _collision_mapping, len(_collision_mapping))
|
132 |
+
# allocate memory for the observations
|
133 |
+
_n_layers_per_cell = len(_collision_mapping)
|
134 |
+
_obs_buffer = PackedFloat64Array()
|
135 |
+
_obs_buffer.resize(grid_size_x * grid_size_z * _n_layers_per_cell)
|
136 |
+
_obs_buffer.fill(0)
|
137 |
+
#prints(len(_obs_buffer), _obs_buffer )
|
138 |
+
|
139 |
+
_box_shape = BoxShape3D.new()
|
140 |
+
_box_shape.set_size(Vector3(cell_width, cell_height, cell_width))
|
141 |
+
|
142 |
+
var shift := Vector3(
|
143 |
+
-(grid_size_x / 2) * cell_width,
|
144 |
+
0,
|
145 |
+
-(grid_size_z / 2) * cell_width,
|
146 |
+
)
|
147 |
+
|
148 |
+
for i in grid_size_x:
|
149 |
+
for j in grid_size_z:
|
150 |
+
var cell_position = Vector3(i * cell_width, 0.0, j * cell_width) + shift
|
151 |
+
_create_cell(i, j, cell_position)
|
152 |
+
|
153 |
+
|
154 |
+
func _create_cell(i: int, j: int, position: Vector3):
|
155 |
+
var cell := Area3D.new()
|
156 |
+
cell.position = position
|
157 |
+
cell.name = "GridCell %s %s" % [i, j]
|
158 |
+
|
159 |
+
if collide_with_areas:
|
160 |
+
cell.area_entered.connect(_on_cell_area_entered.bind(i, j))
|
161 |
+
cell.area_exited.connect(_on_cell_area_exited.bind(i, j))
|
162 |
+
|
163 |
+
if collide_with_bodies:
|
164 |
+
cell.body_entered.connect(_on_cell_body_entered.bind(i, j))
|
165 |
+
cell.body_exited.connect(_on_cell_body_exited.bind(i, j))
|
166 |
+
|
167 |
+
# cell.body_shape_entered.connect(_on_cell_body_shape_entered.bind(i, j))
|
168 |
+
# cell.body_shape_exited.connect(_on_cell_body_shape_exited.bind(i, j))
|
169 |
+
|
170 |
+
cell.collision_layer = 0
|
171 |
+
cell.collision_mask = detection_mask
|
172 |
+
cell.monitorable = true
|
173 |
+
cell.input_ray_pickable = false
|
174 |
+
add_child(cell)
|
175 |
+
cell.set_owner(get_tree().edited_scene_root)
|
176 |
+
|
177 |
+
var col_shape := CollisionShape3D.new()
|
178 |
+
col_shape.shape = _box_shape
|
179 |
+
col_shape.name = "CollisionShape3D"
|
180 |
+
cell.add_child(col_shape)
|
181 |
+
col_shape.set_owner(get_tree().edited_scene_root)
|
182 |
+
|
183 |
+
if debug_view:
|
184 |
+
var box = MeshInstance3D.new()
|
185 |
+
box.name = "MeshInstance3D"
|
186 |
+
var box_mesh = BoxMesh.new()
|
187 |
+
|
188 |
+
box_mesh.set_size(Vector3(cell_width, cell_height, cell_width))
|
189 |
+
box_mesh.material = _standard_box_material
|
190 |
+
|
191 |
+
box.mesh = box_mesh
|
192 |
+
cell.add_child(box)
|
193 |
+
box.set_owner(get_tree().edited_scene_root)
|
194 |
+
|
195 |
+
|
196 |
+
func _update_obs(cell_i: int, cell_j: int, collision_layer: int, entered: bool):
|
197 |
+
for key in _collision_mapping:
|
198 |
+
var bit_mask = 2 ** key
|
199 |
+
if (collision_layer & bit_mask) > 0:
|
200 |
+
var collison_map_index = _collision_mapping[key]
|
201 |
+
|
202 |
+
var obs_index = (
|
203 |
+
(cell_i * grid_size_z * _n_layers_per_cell)
|
204 |
+
+ (cell_j * _n_layers_per_cell)
|
205 |
+
+ collison_map_index
|
206 |
+
)
|
207 |
+
#prints(obs_index, cell_i, cell_j)
|
208 |
+
if entered:
|
209 |
+
_obs_buffer[obs_index] += 1
|
210 |
+
else:
|
211 |
+
_obs_buffer[obs_index] -= 1
|
212 |
+
|
213 |
+
|
214 |
+
func _toggle_cell(cell_i: int, cell_j: int):
|
215 |
+
var cell = get_node_or_null("GridCell %s %s" % [cell_i, cell_j])
|
216 |
+
|
217 |
+
if cell == null:
|
218 |
+
print("cell not found, returning")
|
219 |
+
|
220 |
+
var n_hits = 0
|
221 |
+
var start_index = (cell_i * grid_size_z * _n_layers_per_cell) + (cell_j * _n_layers_per_cell)
|
222 |
+
for i in _n_layers_per_cell:
|
223 |
+
n_hits += _obs_buffer[start_index + i]
|
224 |
+
|
225 |
+
var cell_mesh = cell.get_node_or_null("MeshInstance3D")
|
226 |
+
if n_hits > 0:
|
227 |
+
cell_mesh.mesh.material = _highlighted_box_material
|
228 |
+
else:
|
229 |
+
cell_mesh.mesh.material = _standard_box_material
|
230 |
+
|
231 |
+
|
232 |
+
func _on_cell_area_entered(area: Area3D, cell_i: int, cell_j: int):
|
233 |
+
#prints("_on_cell_area_entered", cell_i, cell_j)
|
234 |
+
_update_obs(cell_i, cell_j, area.collision_layer, true)
|
235 |
+
if debug_view:
|
236 |
+
_toggle_cell(cell_i, cell_j)
|
237 |
+
#print(_obs_buffer)
|
238 |
+
|
239 |
+
|
240 |
+
func _on_cell_area_exited(area: Area3D, cell_i: int, cell_j: int):
|
241 |
+
#prints("_on_cell_area_exited", cell_i, cell_j)
|
242 |
+
_update_obs(cell_i, cell_j, area.collision_layer, false)
|
243 |
+
if debug_view:
|
244 |
+
_toggle_cell(cell_i, cell_j)
|
245 |
+
|
246 |
+
|
247 |
+
func _on_cell_body_entered(body: Node3D, cell_i: int, cell_j: int):
|
248 |
+
#prints("_on_cell_body_entered", cell_i, cell_j)
|
249 |
+
_update_obs(cell_i, cell_j, body.collision_layer, true)
|
250 |
+
if debug_view:
|
251 |
+
_toggle_cell(cell_i, cell_j)
|
252 |
+
|
253 |
+
|
254 |
+
func _on_cell_body_exited(body: Node3D, cell_i: int, cell_j: int):
|
255 |
+
#prints("_on_cell_body_exited", cell_i, cell_j)
|
256 |
+
_update_obs(cell_i, cell_j, body.collision_layer, false)
|
257 |
+
if debug_view:
|
258 |
+
_toggle_cell(cell_i, cell_j)
|
Completed/addons/godot_rl_agents/sensors/sensors_3d/ISensor3D.gd
ADDED
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
extends Node3D
|
2 |
+
class_name ISensor3D
|
3 |
+
|
4 |
+
var _obs: Array = []
|
5 |
+
var _active := false
|
6 |
+
|
7 |
+
|
8 |
+
func get_observation():
|
9 |
+
pass
|
10 |
+
|
11 |
+
|
12 |
+
func activate():
|
13 |
+
_active = true
|
14 |
+
|
15 |
+
|
16 |
+
func deactivate():
|
17 |
+
_active = false
|
18 |
+
|
19 |
+
|
20 |
+
func _update_observation():
|
21 |
+
pass
|
22 |
+
|
23 |
+
|
24 |
+
func reset():
|
25 |
+
pass
|
Completed/addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.gd
ADDED
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
extends Node3D
|
2 |
+
class_name RGBCameraSensor3D
|
3 |
+
var camera_pixels = null
|
4 |
+
|
5 |
+
@onready var camera_texture := $Control/CameraTexture as Sprite2D
|
6 |
+
@onready var processed_texture := $Control/ProcessedTexture as Sprite2D
|
7 |
+
@onready var sub_viewport := $SubViewport as SubViewport
|
8 |
+
@onready var displayed_image: ImageTexture
|
9 |
+
|
10 |
+
@export var render_image_resolution := Vector2(36, 36)
|
11 |
+
## Display size does not affect rendered or sent image resolution.
|
12 |
+
## Scale is relative to either render image or downscale image resolution
|
13 |
+
## depending on which mode is set.
|
14 |
+
@export var displayed_image_scale_factor := Vector2(8, 8)
|
15 |
+
|
16 |
+
@export_group("Downscale image options")
|
17 |
+
## Enable to downscale the rendered image before sending the obs.
|
18 |
+
@export var downscale_image: bool = false
|
19 |
+
## If downscale_image is true, will display the downscaled image instead of rendered image.
|
20 |
+
@export var display_downscaled_image: bool = true
|
21 |
+
## This is the resolution of the image that will be sent after downscaling
|
22 |
+
@export var resized_image_resolution := Vector2(36, 36)
|
23 |
+
|
24 |
+
|
25 |
+
func _ready():
|
26 |
+
sub_viewport.size = render_image_resolution
|
27 |
+
camera_texture.scale = displayed_image_scale_factor
|
28 |
+
|
29 |
+
if downscale_image and display_downscaled_image:
|
30 |
+
camera_texture.visible = false
|
31 |
+
processed_texture.scale = displayed_image_scale_factor
|
32 |
+
else:
|
33 |
+
processed_texture.visible = false
|
34 |
+
|
35 |
+
|
36 |
+
func get_camera_pixel_encoding():
|
37 |
+
var image := camera_texture.get_texture().get_image() as Image
|
38 |
+
|
39 |
+
if downscale_image:
|
40 |
+
image.resize(
|
41 |
+
resized_image_resolution.x, resized_image_resolution.y, Image.INTERPOLATE_NEAREST
|
42 |
+
)
|
43 |
+
if display_downscaled_image:
|
44 |
+
if not processed_texture.texture:
|
45 |
+
displayed_image = ImageTexture.create_from_image(image)
|
46 |
+
processed_texture.texture = displayed_image
|
47 |
+
else:
|
48 |
+
displayed_image.update(image)
|
49 |
+
|
50 |
+
return image.get_data().hex_encode()
|
51 |
+
|
52 |
+
|
53 |
+
func get_camera_shape() -> Array:
|
54 |
+
var size = resized_image_resolution if downscale_image else render_image_resolution
|
55 |
+
|
56 |
+
assert(
|
57 |
+
size.x >= 36 and size.y >= 36,
|
58 |
+
"Camera sensor sent image resolution must be 36x36 or larger."
|
59 |
+
)
|
60 |
+
if sub_viewport.transparent_bg:
|
61 |
+
return [4, size.y, size.x]
|
62 |
+
else:
|
63 |
+
return [3, size.y, size.x]
|
Completed/addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.tscn
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[gd_scene load_steps=3 format=3 uid="uid://baaywi3arsl2m"]
|
2 |
+
|
3 |
+
[ext_resource type="Script" path="res://addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.gd" id="1"]
|
4 |
+
|
5 |
+
[sub_resource type="ViewportTexture" id="ViewportTexture_y72s3"]
|
6 |
+
viewport_path = NodePath("SubViewport")
|
7 |
+
|
8 |
+
[node name="RGBCameraSensor3D" type="Node3D"]
|
9 |
+
script = ExtResource("1")
|
10 |
+
|
11 |
+
[node name="RemoteTransform" type="RemoteTransform3D" parent="."]
|
12 |
+
remote_path = NodePath("../SubViewport/Camera")
|
13 |
+
|
14 |
+
[node name="SubViewport" type="SubViewport" parent="."]
|
15 |
+
size = Vector2i(36, 36)
|
16 |
+
render_target_update_mode = 3
|
17 |
+
|
18 |
+
[node name="Camera" type="Camera3D" parent="SubViewport"]
|
19 |
+
near = 0.5
|
20 |
+
|
21 |
+
[node name="Control" type="Control" parent="."]
|
22 |
+
layout_mode = 3
|
23 |
+
anchors_preset = 15
|
24 |
+
anchor_right = 1.0
|
25 |
+
anchor_bottom = 1.0
|
26 |
+
grow_horizontal = 2
|
27 |
+
grow_vertical = 2
|
28 |
+
metadata/_edit_use_anchors_ = true
|
29 |
+
|
30 |
+
[node name="CameraTexture" type="Sprite2D" parent="Control"]
|
31 |
+
texture = SubResource("ViewportTexture_y72s3")
|
32 |
+
centered = false
|
33 |
+
|
34 |
+
[node name="ProcessedTexture" type="Sprite2D" parent="Control"]
|
35 |
+
centered = false
|
Completed/addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd
ADDED
@@ -0,0 +1,185 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
@tool
|
2 |
+
extends ISensor3D
|
3 |
+
class_name RayCastSensor3D
|
4 |
+
@export_flags_3d_physics var collision_mask = 1:
|
5 |
+
get:
|
6 |
+
return collision_mask
|
7 |
+
set(value):
|
8 |
+
collision_mask = value
|
9 |
+
_update()
|
10 |
+
@export_flags_3d_physics var boolean_class_mask = 1:
|
11 |
+
get:
|
12 |
+
return boolean_class_mask
|
13 |
+
set(value):
|
14 |
+
boolean_class_mask = value
|
15 |
+
_update()
|
16 |
+
|
17 |
+
@export var n_rays_width := 6.0:
|
18 |
+
get:
|
19 |
+
return n_rays_width
|
20 |
+
set(value):
|
21 |
+
n_rays_width = value
|
22 |
+
_update()
|
23 |
+
|
24 |
+
@export var n_rays_height := 6.0:
|
25 |
+
get:
|
26 |
+
return n_rays_height
|
27 |
+
set(value):
|
28 |
+
n_rays_height = value
|
29 |
+
_update()
|
30 |
+
|
31 |
+
@export var ray_length := 10.0:
|
32 |
+
get:
|
33 |
+
return ray_length
|
34 |
+
set(value):
|
35 |
+
ray_length = value
|
36 |
+
_update()
|
37 |
+
|
38 |
+
@export var cone_width := 60.0:
|
39 |
+
get:
|
40 |
+
return cone_width
|
41 |
+
set(value):
|
42 |
+
cone_width = value
|
43 |
+
_update()
|
44 |
+
|
45 |
+
@export var cone_height := 60.0:
|
46 |
+
get:
|
47 |
+
return cone_height
|
48 |
+
set(value):
|
49 |
+
cone_height = value
|
50 |
+
_update()
|
51 |
+
|
52 |
+
@export var collide_with_areas := false:
|
53 |
+
get:
|
54 |
+
return collide_with_areas
|
55 |
+
set(value):
|
56 |
+
collide_with_areas = value
|
57 |
+
_update()
|
58 |
+
|
59 |
+
@export var collide_with_bodies := true:
|
60 |
+
get:
|
61 |
+
return collide_with_bodies
|
62 |
+
set(value):
|
63 |
+
collide_with_bodies = value
|
64 |
+
_update()
|
65 |
+
|
66 |
+
@export var class_sensor := false
|
67 |
+
|
68 |
+
var rays := []
|
69 |
+
var geo = null
|
70 |
+
|
71 |
+
|
72 |
+
func _update():
|
73 |
+
if Engine.is_editor_hint():
|
74 |
+
if is_node_ready():
|
75 |
+
_spawn_nodes()
|
76 |
+
|
77 |
+
|
78 |
+
func _ready() -> void:
|
79 |
+
if Engine.is_editor_hint():
|
80 |
+
if get_child_count() == 0:
|
81 |
+
_spawn_nodes()
|
82 |
+
else:
|
83 |
+
_spawn_nodes()
|
84 |
+
|
85 |
+
|
86 |
+
func _spawn_nodes():
|
87 |
+
print("spawning nodes")
|
88 |
+
for ray in get_children():
|
89 |
+
ray.queue_free()
|
90 |
+
if geo:
|
91 |
+
geo.clear()
|
92 |
+
#$Lines.remove_points()
|
93 |
+
rays = []
|
94 |
+
|
95 |
+
var horizontal_step = cone_width / (n_rays_width)
|
96 |
+
var vertical_step = cone_height / (n_rays_height)
|
97 |
+
|
98 |
+
var horizontal_start = horizontal_step / 2 - cone_width / 2
|
99 |
+
var vertical_start = vertical_step / 2 - cone_height / 2
|
100 |
+
|
101 |
+
var points = []
|
102 |
+
|
103 |
+
for i in n_rays_width:
|
104 |
+
for j in n_rays_height:
|
105 |
+
var angle_w = horizontal_start + i * horizontal_step
|
106 |
+
var angle_h = vertical_start + j * vertical_step
|
107 |
+
#angle_h = 0.0
|
108 |
+
var ray = RayCast3D.new()
|
109 |
+
var cast_to = to_spherical_coords(ray_length, angle_w, angle_h)
|
110 |
+
ray.set_target_position(cast_to)
|
111 |
+
|
112 |
+
points.append(cast_to)
|
113 |
+
|
114 |
+
ray.set_name("node_" + str(i) + " " + str(j))
|
115 |
+
ray.enabled = false
|
116 |
+
ray.collide_with_bodies = collide_with_bodies
|
117 |
+
ray.collide_with_areas = collide_with_areas
|
118 |
+
ray.collision_mask = collision_mask
|
119 |
+
add_child(ray)
|
120 |
+
ray.set_owner(get_tree().edited_scene_root)
|
121 |
+
rays.append(ray)
|
122 |
+
ray.force_raycast_update()
|
123 |
+
|
124 |
+
|
125 |
+
# if Engine.editor_hint:
|
126 |
+
# _create_debug_lines(points)
|
127 |
+
|
128 |
+
|
129 |
+
func _create_debug_lines(points):
|
130 |
+
if not geo:
|
131 |
+
geo = ImmediateMesh.new()
|
132 |
+
add_child(geo)
|
133 |
+
|
134 |
+
geo.clear()
|
135 |
+
geo.begin(Mesh.PRIMITIVE_LINES)
|
136 |
+
for point in points:
|
137 |
+
geo.set_color(Color.AQUA)
|
138 |
+
geo.add_vertex(Vector3.ZERO)
|
139 |
+
geo.add_vertex(point)
|
140 |
+
geo.end()
|
141 |
+
|
142 |
+
|
143 |
+
func display():
|
144 |
+
if geo:
|
145 |
+
geo.display()
|
146 |
+
|
147 |
+
|
148 |
+
func to_spherical_coords(r, inc, azimuth) -> Vector3:
|
149 |
+
return Vector3(
|
150 |
+
r * sin(deg_to_rad(inc)) * cos(deg_to_rad(azimuth)),
|
151 |
+
r * sin(deg_to_rad(azimuth)),
|
152 |
+
r * cos(deg_to_rad(inc)) * cos(deg_to_rad(azimuth))
|
153 |
+
)
|
154 |
+
|
155 |
+
|
156 |
+
func get_observation() -> Array:
|
157 |
+
return self.calculate_raycasts()
|
158 |
+
|
159 |
+
|
160 |
+
func calculate_raycasts() -> Array:
|
161 |
+
var result = []
|
162 |
+
for ray in rays:
|
163 |
+
ray.set_enabled(true)
|
164 |
+
ray.force_raycast_update()
|
165 |
+
var distance = _get_raycast_distance(ray)
|
166 |
+
|
167 |
+
result.append(distance)
|
168 |
+
if class_sensor:
|
169 |
+
var hit_class: float = 0
|
170 |
+
if ray.get_collider():
|
171 |
+
var hit_collision_layer = ray.get_collider().collision_layer
|
172 |
+
hit_collision_layer = hit_collision_layer & collision_mask
|
173 |
+
hit_class = (hit_collision_layer & boolean_class_mask) > 0
|
174 |
+
result.append(float(hit_class))
|
175 |
+
ray.set_enabled(false)
|
176 |
+
return result
|
177 |
+
|
178 |
+
|
179 |
+
func _get_raycast_distance(ray: RayCast3D) -> float:
|
180 |
+
if !ray.is_colliding():
|
181 |
+
return 0.0
|
182 |
+
|
183 |
+
var distance = (global_transform.origin - ray.get_collision_point()).length()
|
184 |
+
distance = clamp(distance, 0.0, ray_length)
|
185 |
+
return (ray_length - distance) / ray_length
|
Completed/addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.tscn
ADDED
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[gd_scene load_steps=2 format=3 uid="uid://b803cbh1fmy66"]
|
2 |
+
|
3 |
+
[ext_resource type="Script" path="res://addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd" id="1"]
|
4 |
+
|
5 |
+
[node name="RaycastSensor3D" type="Node3D"]
|
6 |
+
script = ExtResource("1")
|
7 |
+
n_rays_width = 4.0
|
8 |
+
n_rays_height = 2.0
|
9 |
+
ray_length = 11.0
|
10 |
+
|
11 |
+
[node name="node_1 0" type="RayCast3D" parent="."]
|
12 |
+
target_position = Vector3(-1.38686, -2.84701, 10.5343)
|
13 |
+
|
14 |
+
[node name="node_1 1" type="RayCast3D" parent="."]
|
15 |
+
target_position = Vector3(-1.38686, 2.84701, 10.5343)
|
16 |
+
|
17 |
+
[node name="node_2 0" type="RayCast3D" parent="."]
|
18 |
+
target_position = Vector3(1.38686, -2.84701, 10.5343)
|
19 |
+
|
20 |
+
[node name="node_2 1" type="RayCast3D" parent="."]
|
21 |
+
target_position = Vector3(1.38686, 2.84701, 10.5343)
|
22 |
+
|
23 |
+
[node name="node_3 0" type="RayCast3D" parent="."]
|
24 |
+
target_position = Vector3(4.06608, -2.84701, 9.81639)
|
25 |
+
|
26 |
+
[node name="node_3 1" type="RayCast3D" parent="."]
|
27 |
+
target_position = Vector3(4.06608, 2.84701, 9.81639)
|
Completed/addons/godot_rl_agents/sync.gd
ADDED
@@ -0,0 +1,587 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
extends Node
|
2 |
+
class_name Sync
|
3 |
+
|
4 |
+
# --fixed-fps 2000 --disable-render-loop
|
5 |
+
|
6 |
+
enum ControlModes {
|
7 |
+
HUMAN, ## Test the environment manually
|
8 |
+
TRAINING, ## Train a model
|
9 |
+
ONNX_INFERENCE ## Load a pretrained model using an .onnx file
|
10 |
+
}
|
11 |
+
@export var control_mode: ControlModes = ControlModes.TRAINING
|
12 |
+
## Action will be repeated for n frames (Godot physics steps).
|
13 |
+
@export_range(1, 10, 1, "or_greater") var action_repeat := 8
|
14 |
+
## Speeds up the physics in the environment to enable faster training.
|
15 |
+
@export_range(0, 10, 0.01, "or_greater") var speed_up := 1.0
|
16 |
+
## The path to a trained .onnx model file to use for inference (only needed for the 'Onnx Inference' control mode).
|
17 |
+
@export var onnx_model_path := ""
|
18 |
+
|
19 |
+
# Onnx model stored for each requested path
|
20 |
+
var onnx_models: Dictionary
|
21 |
+
|
22 |
+
@onready var start_time = Time.get_ticks_msec()
|
23 |
+
|
24 |
+
const MAJOR_VERSION := "0"
|
25 |
+
const MINOR_VERSION := "7"
|
26 |
+
const DEFAULT_PORT := "11008"
|
27 |
+
const DEFAULT_SEED := "1"
|
28 |
+
var stream: StreamPeerTCP = null
|
29 |
+
var connected = false
|
30 |
+
var message_center
|
31 |
+
var should_connect = true
|
32 |
+
|
33 |
+
var all_agents: Array
|
34 |
+
var agents_training: Array
|
35 |
+
## Policy name of each agent, for use with multi-policy multi-agent RL cases
|
36 |
+
var agents_training_policy_names: Array[String] = ["shared_policy"]
|
37 |
+
var agents_inference: Array
|
38 |
+
var agents_heuristic: Array
|
39 |
+
|
40 |
+
## For recording expert demos
|
41 |
+
var agent_demo_record: Node
|
42 |
+
## File path for writing recorded trajectories
|
43 |
+
var expert_demo_save_path: String
|
44 |
+
## Stores recorded trajectories
|
45 |
+
var demo_trajectories: Array
|
46 |
+
## A trajectory includes obs: Array, acts: Array, terminal (set in Python env instead)
|
47 |
+
var current_demo_trajectory: Array
|
48 |
+
|
49 |
+
var need_to_send_obs = false
|
50 |
+
var args = null
|
51 |
+
var initialized = false
|
52 |
+
var just_reset = false
|
53 |
+
var onnx_model = null
|
54 |
+
var n_action_steps = 0
|
55 |
+
|
56 |
+
var _action_space_training: Array[Dictionary] = []
|
57 |
+
var _action_space_inference: Array[Dictionary] = []
|
58 |
+
var _obs_space_training: Array[Dictionary] = []
|
59 |
+
|
60 |
+
# Called when the node enters the scene tree for the first time.
|
61 |
+
func _ready():
|
62 |
+
await get_parent().ready
|
63 |
+
get_tree().set_pause(true)
|
64 |
+
_initialize()
|
65 |
+
#await get_tree().create_timer(1.0).timeout
|
66 |
+
get_tree().set_pause(false)
|
67 |
+
|
68 |
+
|
69 |
+
func _initialize():
|
70 |
+
_get_agents()
|
71 |
+
args = _get_args()
|
72 |
+
Engine.physics_ticks_per_second = _get_speedup() * 60 # Replace with function body.
|
73 |
+
Engine.time_scale = _get_speedup() * 1.0
|
74 |
+
prints(
|
75 |
+
"physics ticks",
|
76 |
+
Engine.physics_ticks_per_second,
|
77 |
+
Engine.time_scale,
|
78 |
+
_get_speedup(),
|
79 |
+
speed_up
|
80 |
+
)
|
81 |
+
|
82 |
+
_set_heuristic("human", all_agents)
|
83 |
+
|
84 |
+
_initialize_training_agents()
|
85 |
+
_initialize_inference_agents()
|
86 |
+
_initialize_demo_recording()
|
87 |
+
|
88 |
+
_set_seed()
|
89 |
+
_set_action_repeat()
|
90 |
+
initialized = true
|
91 |
+
|
92 |
+
|
93 |
+
func _initialize_training_agents():
|
94 |
+
if agents_training.size() > 0:
|
95 |
+
_obs_space_training.resize(agents_training.size())
|
96 |
+
_action_space_training.resize(agents_training.size())
|
97 |
+
for agent_idx in range(0, agents_training.size()):
|
98 |
+
_obs_space_training[agent_idx] = agents_training[agent_idx].get_obs_space()
|
99 |
+
_action_space_training[agent_idx] = agents_training[agent_idx].get_action_space()
|
100 |
+
connected = connect_to_server()
|
101 |
+
if connected:
|
102 |
+
_set_heuristic("model", agents_training)
|
103 |
+
_handshake()
|
104 |
+
_send_env_info()
|
105 |
+
else:
|
106 |
+
push_warning(
|
107 |
+
"Couldn't connect to Python server, using human controls instead. ",
|
108 |
+
"Did you start the training server using e.g. `gdrl` from the console?"
|
109 |
+
)
|
110 |
+
|
111 |
+
|
112 |
+
func _initialize_inference_agents():
|
113 |
+
if agents_inference.size() > 0:
|
114 |
+
if control_mode == ControlModes.ONNX_INFERENCE:
|
115 |
+
assert(
|
116 |
+
FileAccess.file_exists(onnx_model_path),
|
117 |
+
"Onnx Model Path set on Sync node does not exist: %s" % onnx_model_path
|
118 |
+
)
|
119 |
+
onnx_models[onnx_model_path] = ONNXModel.new(onnx_model_path, 1)
|
120 |
+
|
121 |
+
for agent in agents_inference:
|
122 |
+
var action_space = agent.get_action_space()
|
123 |
+
_action_space_inference.append(action_space)
|
124 |
+
|
125 |
+
var agent_onnx_model: ONNXModel
|
126 |
+
if agent.onnx_model_path.is_empty():
|
127 |
+
assert(
|
128 |
+
onnx_models.has(onnx_model_path),
|
129 |
+
(
|
130 |
+
"Node %s has no onnx model path set " % agent.get_path()
|
131 |
+
+ "and sync node's control mode is not set to OnnxInference. "
|
132 |
+
+ "Either add the path to the AIController, "
|
133 |
+
+ "or if you want to use the path set on sync node instead, "
|
134 |
+
+ "set control mode to OnnxInference."
|
135 |
+
)
|
136 |
+
)
|
137 |
+
prints(
|
138 |
+
"Info: AIController %s" % agent.get_path(),
|
139 |
+
"has no onnx model path set.",
|
140 |
+
"Using path set on the sync node instead."
|
141 |
+
)
|
142 |
+
agent_onnx_model = onnx_models[onnx_model_path]
|
143 |
+
else:
|
144 |
+
if not onnx_models.has(agent.onnx_model_path):
|
145 |
+
assert(
|
146 |
+
FileAccess.file_exists(agent.onnx_model_path),
|
147 |
+
(
|
148 |
+
"Onnx Model Path set on %s node does not exist: %s"
|
149 |
+
% [agent.get_path(), agent.onnx_model_path]
|
150 |
+
)
|
151 |
+
)
|
152 |
+
onnx_models[agent.onnx_model_path] = ONNXModel.new(agent.onnx_model_path, 1)
|
153 |
+
agent_onnx_model = onnx_models[agent.onnx_model_path]
|
154 |
+
|
155 |
+
agent.onnx_model = agent_onnx_model
|
156 |
+
if not agent_onnx_model.action_means_only_set:
|
157 |
+
agent_onnx_model.set_action_means_only(action_space)
|
158 |
+
|
159 |
+
_set_heuristic("model", agents_inference)
|
160 |
+
|
161 |
+
|
162 |
+
func _initialize_demo_recording():
|
163 |
+
if agent_demo_record:
|
164 |
+
expert_demo_save_path = agent_demo_record.expert_demo_save_path
|
165 |
+
assert(
|
166 |
+
not expert_demo_save_path.is_empty(),
|
167 |
+
"Expert demo save path set in %s is empty." % agent_demo_record.get_path()
|
168 |
+
)
|
169 |
+
|
170 |
+
InputMap.add_action("RemoveLastDemoEpisode")
|
171 |
+
InputMap.action_add_event(
|
172 |
+
"RemoveLastDemoEpisode", agent_demo_record.remove_last_episode_key
|
173 |
+
)
|
174 |
+
current_demo_trajectory.resize(2)
|
175 |
+
current_demo_trajectory[0] = []
|
176 |
+
current_demo_trajectory[1] = []
|
177 |
+
agent_demo_record.heuristic = "demo_record"
|
178 |
+
|
179 |
+
|
180 |
+
func _physics_process(_delta):
|
181 |
+
# two modes, human control, agent control
|
182 |
+
# pause tree, send obs, get actions, set actions, unpause tree
|
183 |
+
|
184 |
+
_demo_record_process()
|
185 |
+
|
186 |
+
if n_action_steps % action_repeat != 0:
|
187 |
+
n_action_steps += 1
|
188 |
+
return
|
189 |
+
|
190 |
+
n_action_steps += 1
|
191 |
+
|
192 |
+
_training_process()
|
193 |
+
_inference_process()
|
194 |
+
_heuristic_process()
|
195 |
+
|
196 |
+
|
197 |
+
func _training_process():
|
198 |
+
if connected:
|
199 |
+
get_tree().set_pause(true)
|
200 |
+
|
201 |
+
if just_reset:
|
202 |
+
just_reset = false
|
203 |
+
var obs = _get_obs_from_agents(agents_training)
|
204 |
+
|
205 |
+
var reply = {"type": "reset", "obs": obs}
|
206 |
+
_send_dict_as_json_message(reply)
|
207 |
+
# this should go straight to getting the action and setting it checked the agent, no need to perform one phyics tick
|
208 |
+
get_tree().set_pause(false)
|
209 |
+
return
|
210 |
+
|
211 |
+
if need_to_send_obs:
|
212 |
+
need_to_send_obs = false
|
213 |
+
var reward = _get_reward_from_agents()
|
214 |
+
var done = _get_done_from_agents()
|
215 |
+
#_reset_agents_if_done() # this ensures the new observation is from the next env instance : NEEDS REFACTOR
|
216 |
+
|
217 |
+
var obs = _get_obs_from_agents(agents_training)
|
218 |
+
|
219 |
+
var reply = {"type": "step", "obs": obs, "reward": reward, "done": done}
|
220 |
+
_send_dict_as_json_message(reply)
|
221 |
+
|
222 |
+
var handled = handle_message()
|
223 |
+
|
224 |
+
|
225 |
+
func _inference_process():
|
226 |
+
if agents_inference.size() > 0:
|
227 |
+
var obs: Array = _get_obs_from_agents(agents_inference)
|
228 |
+
var actions = []
|
229 |
+
|
230 |
+
for agent_id in range(0, agents_inference.size()):
|
231 |
+
var model: ONNXModel = agents_inference[agent_id].onnx_model
|
232 |
+
var action = model.run_inference(
|
233 |
+
obs[agent_id]["obs"], 1.0
|
234 |
+
)
|
235 |
+
var action_dict = _extract_action_dict(
|
236 |
+
action["output"], _action_space_inference[agent_id], model.action_means_only
|
237 |
+
)
|
238 |
+
actions.append(action_dict)
|
239 |
+
|
240 |
+
_set_agent_actions(actions, agents_inference)
|
241 |
+
_reset_agents_if_done(agents_inference)
|
242 |
+
get_tree().set_pause(false)
|
243 |
+
|
244 |
+
|
245 |
+
func _demo_record_process():
|
246 |
+
if not agent_demo_record:
|
247 |
+
return
|
248 |
+
|
249 |
+
if Input.is_action_just_pressed("RemoveLastDemoEpisode"):
|
250 |
+
print("[Sync script][Demo recorder] Removing last recorded episode.")
|
251 |
+
demo_trajectories.remove_at(demo_trajectories.size() - 1)
|
252 |
+
print("Remaining episode count: %d" % demo_trajectories.size())
|
253 |
+
|
254 |
+
if n_action_steps % agent_demo_record.action_repeat != 0:
|
255 |
+
return
|
256 |
+
|
257 |
+
var obs_dict: Dictionary = agent_demo_record.get_obs()
|
258 |
+
|
259 |
+
# Get the current obs from the agent
|
260 |
+
assert(
|
261 |
+
obs_dict.has("obs"),
|
262 |
+
"Demo recorder needs an 'obs' key in get_obs() returned dictionary to record obs from."
|
263 |
+
)
|
264 |
+
current_demo_trajectory[0].append(obs_dict.obs)
|
265 |
+
|
266 |
+
# Get the action applied for the current obs from the agent
|
267 |
+
agent_demo_record.set_action()
|
268 |
+
var acts = agent_demo_record.get_action()
|
269 |
+
|
270 |
+
var terminal = agent_demo_record.get_done()
|
271 |
+
# Record actions only for non-terminal states
|
272 |
+
if terminal:
|
273 |
+
agent_demo_record.set_done_false()
|
274 |
+
else:
|
275 |
+
current_demo_trajectory[1].append(acts)
|
276 |
+
|
277 |
+
if terminal:
|
278 |
+
#current_demo_trajectory[2].append(true)
|
279 |
+
demo_trajectories.append(current_demo_trajectory.duplicate(true))
|
280 |
+
print("[Sync script][Demo recorder] Recorded episode count: %d" % demo_trajectories.size())
|
281 |
+
current_demo_trajectory[0].clear()
|
282 |
+
current_demo_trajectory[1].clear()
|
283 |
+
|
284 |
+
|
285 |
+
func _heuristic_process():
|
286 |
+
for agent in agents_heuristic:
|
287 |
+
_reset_agents_if_done(agents_heuristic)
|
288 |
+
|
289 |
+
|
290 |
+
func _extract_action_dict(action_array: Array, action_space: Dictionary, action_means_only: bool):
|
291 |
+
var index = 0
|
292 |
+
var result = {}
|
293 |
+
for key in action_space.keys():
|
294 |
+
var size = action_space[key]["size"]
|
295 |
+
var action_type = action_space[key]["action_type"]
|
296 |
+
if action_type == "discrete":
|
297 |
+
var largest_logit: float # Value of the largest logit for this action in the actions array
|
298 |
+
var largest_logit_idx: int # Index of the largest logit for this action in the actions array
|
299 |
+
for logit_idx in range(0, size):
|
300 |
+
var logit_value = action_array[index + logit_idx]
|
301 |
+
if logit_value > largest_logit:
|
302 |
+
largest_logit = logit_value
|
303 |
+
largest_logit_idx = logit_idx
|
304 |
+
result[key] = largest_logit_idx # Index of the largest logit is the discrete action value
|
305 |
+
index += size
|
306 |
+
elif action_type == "continuous":
|
307 |
+
# For continous actions, we only take the action mean values
|
308 |
+
result[key] = clamp_array(action_array.slice(index, index + size), -1.0, 1.0)
|
309 |
+
if action_means_only:
|
310 |
+
index += size # model only outputs action means, so we move index by size
|
311 |
+
else:
|
312 |
+
index += size * 2 # model outputs logstd after action mean, we skip the logstd part
|
313 |
+
|
314 |
+
else:
|
315 |
+
assert(false, 'Only "discrete" and "continuous" action types supported. Found: %s action type set.' % action_type)
|
316 |
+
|
317 |
+
|
318 |
+
return result
|
319 |
+
|
320 |
+
|
321 |
+
## For AIControllers that inherit mode from sync, sets the correct mode.
|
322 |
+
func _set_agent_mode(agent: Node):
|
323 |
+
var agent_inherits_mode: bool = agent.control_mode == agent.ControlModes.INHERIT_FROM_SYNC
|
324 |
+
|
325 |
+
if agent_inherits_mode:
|
326 |
+
match control_mode:
|
327 |
+
ControlModes.HUMAN:
|
328 |
+
agent.control_mode = agent.ControlModes.HUMAN
|
329 |
+
ControlModes.TRAINING:
|
330 |
+
agent.control_mode = agent.ControlModes.TRAINING
|
331 |
+
ControlModes.ONNX_INFERENCE:
|
332 |
+
agent.control_mode = agent.ControlModes.ONNX_INFERENCE
|
333 |
+
|
334 |
+
|
335 |
+
func _get_agents():
|
336 |
+
all_agents = get_tree().get_nodes_in_group("AGENT")
|
337 |
+
for agent in all_agents:
|
338 |
+
_set_agent_mode(agent)
|
339 |
+
|
340 |
+
if agent.control_mode == agent.ControlModes.TRAINING:
|
341 |
+
agents_training.append(agent)
|
342 |
+
elif agent.control_mode == agent.ControlModes.ONNX_INFERENCE:
|
343 |
+
agents_inference.append(agent)
|
344 |
+
elif agent.control_mode == agent.ControlModes.HUMAN:
|
345 |
+
agents_heuristic.append(agent)
|
346 |
+
elif agent.control_mode == agent.ControlModes.RECORD_EXPERT_DEMOS:
|
347 |
+
assert(
|
348 |
+
not agent_demo_record,
|
349 |
+
"Currently only a single AIController can be used for recording expert demos."
|
350 |
+
)
|
351 |
+
agent_demo_record = agent
|
352 |
+
|
353 |
+
var training_agent_count = agents_training.size()
|
354 |
+
agents_training_policy_names.resize(training_agent_count)
|
355 |
+
for i in range(0, training_agent_count):
|
356 |
+
agents_training_policy_names[i] = agents_training[i].policy_name
|
357 |
+
|
358 |
+
|
359 |
+
func _set_heuristic(heuristic, agents: Array):
|
360 |
+
for agent in agents:
|
361 |
+
agent.set_heuristic(heuristic)
|
362 |
+
|
363 |
+
|
364 |
+
func _handshake():
|
365 |
+
print("performing handshake")
|
366 |
+
|
367 |
+
var json_dict = _get_dict_json_message()
|
368 |
+
assert(json_dict["type"] == "handshake")
|
369 |
+
var major_version = json_dict["major_version"]
|
370 |
+
var minor_version = json_dict["minor_version"]
|
371 |
+
if major_version != MAJOR_VERSION:
|
372 |
+
print("WARNING: major verison mismatch ", major_version, " ", MAJOR_VERSION)
|
373 |
+
if minor_version != MINOR_VERSION:
|
374 |
+
print("WARNING: minor verison mismatch ", minor_version, " ", MINOR_VERSION)
|
375 |
+
|
376 |
+
print("handshake complete")
|
377 |
+
|
378 |
+
|
379 |
+
func _get_dict_json_message():
|
380 |
+
# returns a dictionary from of the most recent message
|
381 |
+
# this is not waiting
|
382 |
+
while stream.get_available_bytes() == 0:
|
383 |
+
stream.poll()
|
384 |
+
if stream.get_status() != 2:
|
385 |
+
print("server disconnected status, closing")
|
386 |
+
get_tree().quit()
|
387 |
+
return null
|
388 |
+
|
389 |
+
OS.delay_usec(10)
|
390 |
+
|
391 |
+
var message = stream.get_string()
|
392 |
+
var json_data = JSON.parse_string(message)
|
393 |
+
|
394 |
+
return json_data
|
395 |
+
|
396 |
+
|
397 |
+
func _send_dict_as_json_message(dict):
|
398 |
+
stream.put_string(JSON.stringify(dict, "", false))
|
399 |
+
|
400 |
+
|
401 |
+
func _send_env_info():
|
402 |
+
var json_dict = _get_dict_json_message()
|
403 |
+
assert(json_dict["type"] == "env_info")
|
404 |
+
|
405 |
+
var message = {
|
406 |
+
"type": "env_info",
|
407 |
+
"observation_space": _obs_space_training,
|
408 |
+
"action_space": _action_space_training,
|
409 |
+
"n_agents": len(agents_training),
|
410 |
+
"agent_policy_names": agents_training_policy_names
|
411 |
+
}
|
412 |
+
_send_dict_as_json_message(message)
|
413 |
+
|
414 |
+
|
415 |
+
func connect_to_server():
|
416 |
+
print("Waiting for one second to allow server to start")
|
417 |
+
OS.delay_msec(1000)
|
418 |
+
print("trying to connect to server")
|
419 |
+
stream = StreamPeerTCP.new()
|
420 |
+
|
421 |
+
# "localhost" was not working on windows VM, had to use the IP
|
422 |
+
var ip = "127.0.0.1"
|
423 |
+
var port = _get_port()
|
424 |
+
var connect = stream.connect_to_host(ip, port)
|
425 |
+
stream.set_no_delay(true) # TODO check if this improves performance or not
|
426 |
+
stream.poll()
|
427 |
+
# Fetch the status until it is either connected (2) or failed to connect (3)
|
428 |
+
while stream.get_status() < 2:
|
429 |
+
stream.poll()
|
430 |
+
return stream.get_status() == 2
|
431 |
+
|
432 |
+
|
433 |
+
func _get_args():
|
434 |
+
print("getting command line arguments")
|
435 |
+
var arguments = {}
|
436 |
+
for argument in OS.get_cmdline_args():
|
437 |
+
print(argument)
|
438 |
+
if argument.find("=") > -1:
|
439 |
+
var key_value = argument.split("=")
|
440 |
+
arguments[key_value[0].lstrip("--")] = key_value[1]
|
441 |
+
else:
|
442 |
+
# Options without an argument will be present in the dictionary,
|
443 |
+
# with the value set to an empty string.
|
444 |
+
arguments[argument.lstrip("--")] = ""
|
445 |
+
|
446 |
+
return arguments
|
447 |
+
|
448 |
+
|
449 |
+
func _get_speedup():
|
450 |
+
print(args)
|
451 |
+
return args.get("speedup", str(speed_up)).to_float()
|
452 |
+
|
453 |
+
|
454 |
+
func _get_port():
|
455 |
+
return args.get("port", DEFAULT_PORT).to_int()
|
456 |
+
|
457 |
+
|
458 |
+
func _set_seed():
|
459 |
+
var _seed = args.get("env_seed", DEFAULT_SEED).to_int()
|
460 |
+
seed(_seed)
|
461 |
+
|
462 |
+
|
463 |
+
func _set_action_repeat():
|
464 |
+
action_repeat = args.get("action_repeat", str(action_repeat)).to_int()
|
465 |
+
|
466 |
+
|
467 |
+
func disconnect_from_server():
|
468 |
+
stream.disconnect_from_host()
|
469 |
+
|
470 |
+
|
471 |
+
func handle_message() -> bool:
|
472 |
+
# get json message: reset, step, close
|
473 |
+
var message = _get_dict_json_message()
|
474 |
+
if message["type"] == "close":
|
475 |
+
print("received close message, closing game")
|
476 |
+
get_tree().quit()
|
477 |
+
get_tree().set_pause(false)
|
478 |
+
return true
|
479 |
+
|
480 |
+
if message["type"] == "reset":
|
481 |
+
print("resetting all agents")
|
482 |
+
_reset_agents()
|
483 |
+
just_reset = true
|
484 |
+
get_tree().set_pause(false)
|
485 |
+
#print("resetting forcing draw")
|
486 |
+
# RenderingServer.force_draw()
|
487 |
+
# var obs = _get_obs_from_agents()
|
488 |
+
# print("obs ", obs)
|
489 |
+
# var reply = {
|
490 |
+
# "type": "reset",
|
491 |
+
# "obs": obs
|
492 |
+
# }
|
493 |
+
# _send_dict_as_json_message(reply)
|
494 |
+
return true
|
495 |
+
|
496 |
+
if message["type"] == "call":
|
497 |
+
var method = message["method"]
|
498 |
+
var returns = _call_method_on_agents(method)
|
499 |
+
var reply = {"type": "call", "returns": returns}
|
500 |
+
print("calling method from Python")
|
501 |
+
_send_dict_as_json_message(reply)
|
502 |
+
return handle_message()
|
503 |
+
|
504 |
+
if message["type"] == "action":
|
505 |
+
var action = message["action"]
|
506 |
+
_set_agent_actions(action, agents_training)
|
507 |
+
need_to_send_obs = true
|
508 |
+
get_tree().set_pause(false)
|
509 |
+
return true
|
510 |
+
|
511 |
+
print("message was not handled")
|
512 |
+
return false
|
513 |
+
|
514 |
+
|
515 |
+
func _call_method_on_agents(method):
|
516 |
+
var returns = []
|
517 |
+
for agent in all_agents:
|
518 |
+
returns.append(agent.call(method))
|
519 |
+
|
520 |
+
return returns
|
521 |
+
|
522 |
+
|
523 |
+
func _reset_agents_if_done(agents = all_agents):
|
524 |
+
for agent in agents:
|
525 |
+
if agent.get_done():
|
526 |
+
agent.set_done_false()
|
527 |
+
|
528 |
+
|
529 |
+
func _reset_agents(agents = all_agents):
|
530 |
+
for agent in agents:
|
531 |
+
agent.needs_reset = true
|
532 |
+
#agent.reset()
|
533 |
+
|
534 |
+
|
535 |
+
func _get_obs_from_agents(agents: Array = all_agents):
|
536 |
+
var obs = []
|
537 |
+
for agent in agents:
|
538 |
+
obs.append(agent.get_obs())
|
539 |
+
return obs
|
540 |
+
|
541 |
+
|
542 |
+
func _get_reward_from_agents(agents: Array = agents_training):
|
543 |
+
var rewards = []
|
544 |
+
for agent in agents:
|
545 |
+
rewards.append(agent.get_reward())
|
546 |
+
agent.zero_reward()
|
547 |
+
return rewards
|
548 |
+
|
549 |
+
|
550 |
+
func _get_done_from_agents(agents: Array = agents_training):
|
551 |
+
var dones = []
|
552 |
+
for agent in agents:
|
553 |
+
var done = agent.get_done()
|
554 |
+
if done:
|
555 |
+
agent.set_done_false()
|
556 |
+
dones.append(done)
|
557 |
+
return dones
|
558 |
+
|
559 |
+
|
560 |
+
func _set_agent_actions(actions, agents: Array = all_agents):
|
561 |
+
for i in range(len(actions)):
|
562 |
+
agents[i].set_action(actions[i])
|
563 |
+
|
564 |
+
|
565 |
+
func clamp_array(arr: Array, min: float, max: float):
|
566 |
+
var output: Array = []
|
567 |
+
for a in arr:
|
568 |
+
output.append(clamp(a, min, max))
|
569 |
+
return output
|
570 |
+
|
571 |
+
|
572 |
+
## Save recorded export demos on window exit (Close game window instead of "Stop" button in Godot Editor)
|
573 |
+
func _notification(what):
|
574 |
+
if demo_trajectories.size() == 0 or expert_demo_save_path.is_empty():
|
575 |
+
return
|
576 |
+
|
577 |
+
if what == NOTIFICATION_PREDELETE:
|
578 |
+
var json_string = JSON.stringify(demo_trajectories, "", false)
|
579 |
+
var file = FileAccess.open(expert_demo_save_path, FileAccess.WRITE)
|
580 |
+
|
581 |
+
if not file:
|
582 |
+
var error: Error = FileAccess.get_open_error()
|
583 |
+
assert(not error, "There was an error opening the file: %d" % error)
|
584 |
+
|
585 |
+
file.store_line(json_string)
|
586 |
+
var error = file.get_error()
|
587 |
+
assert(not error, "There was an error after trying to write to the file: %d" % error)
|
Completed/assets/car.glb
ADDED
Binary file (87.4 kB). View file
|
|
Completed/assets/goal_tile.glb
ADDED
Binary file (49.3 kB). View file
|
|
Completed/assets/orange_tile.glb
ADDED
Binary file (3.39 kB). View file
|
|
Completed/assets/road_tile.glb
ADDED
Binary file (3.48 kB). View file
|
|
Completed/assets/robot.glb
ADDED
Binary file (135 kB). View file
|
|
Completed/assets/tree_tile.glb
ADDED
Binary file (14.9 kB). View file
|
|
Completed/icon.svg
ADDED
Completed/license.md
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
CrossTheRoad Environment made by Ivan Dodic (https://github.com/Ivan-267)
|
2 |
+
|
3 |
+
The following license is only for the graphical assets in the folder "assets", specifically .glb files:
|
4 |
+
Author: Ivan Dodic (https://github.com/Ivan-267),
|
5 |
+
License: https://creativecommons.org/licenses/by/4.0/
|
Completed/model.onnx
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:d6d2345651e25fb09773faa5fc1ee47f74e27de57b52b8dbc3a818bb9b6b76c3
|
3 |
+
size 39900
|
Completed/project.godot
ADDED
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
; Engine configuration file.
|
2 |
+
; It's best edited using the editor UI and not directly,
|
3 |
+
; since the parameters that go here are not all obvious.
|
4 |
+
;
|
5 |
+
; Format:
|
6 |
+
; [section] ; section goes between []
|
7 |
+
; param=value ; assign values to parameters
|
8 |
+
|
9 |
+
config_version=5
|
10 |
+
|
11 |
+
[application]
|
12 |
+
|
13 |
+
config/name="CrossTheRoadEnv"
|
14 |
+
run/main_scene="res://scenes/training_scene.tscn"
|
15 |
+
config/features=PackedStringArray("4.3", "C#", "Forward Plus")
|
16 |
+
config/icon="res://icon.svg"
|
17 |
+
|
18 |
+
[dotnet]
|
19 |
+
|
20 |
+
project/assembly_name="GridRobot"
|
21 |
+
|
22 |
+
[editor_plugins]
|
23 |
+
|
24 |
+
enabled=PackedStringArray("res://addons/godot_rl_agents/plugin.cfg")
|
25 |
+
|
26 |
+
[input]
|
27 |
+
|
28 |
+
move_left={
|
29 |
+
"deadzone": 0.5,
|
30 |
+
"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":65,"key_label":0,"unicode":97,"location":0,"echo":false,"script":null)
|
31 |
+
, Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":4194319,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null)
|
32 |
+
]
|
33 |
+
}
|
34 |
+
move_right={
|
35 |
+
"deadzone": 0.5,
|
36 |
+
"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":68,"key_label":0,"unicode":100,"location":0,"echo":false,"script":null)
|
37 |
+
, Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":4194321,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null)
|
38 |
+
]
|
39 |
+
}
|
40 |
+
move_up={
|
41 |
+
"deadzone": 0.5,
|
42 |
+
"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":87,"key_label":0,"unicode":119,"location":0,"echo":false,"script":null)
|
43 |
+
, Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":4194320,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null)
|
44 |
+
]
|
45 |
+
}
|
46 |
+
move_down={
|
47 |
+
"deadzone": 0.5,
|
48 |
+
"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":83,"key_label":0,"unicode":115,"location":0,"echo":false,"script":null)
|
49 |
+
, Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":4194322,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null)
|
50 |
+
]
|
51 |
+
}
|
52 |
+
|
53 |
+
[rendering]
|
54 |
+
|
55 |
+
anti_aliasing/name="CrossTheRoad"
|
Completed/scenes/car.tscn
ADDED
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[gd_scene load_steps=3 format=3 uid="uid://bhk60xl5s8pmm"]
|
2 |
+
|
3 |
+
[ext_resource type="Script" path="res://scripts/car.gd" id="1_psb6d"]
|
4 |
+
[ext_resource type="PackedScene" uid="uid://b2n1vy10th4qo" path="res://assets/car.glb" id="2_fqh82"]
|
5 |
+
|
6 |
+
[node name="Car" type="Node3D"]
|
7 |
+
transform = Transform3D(-4.37114e-08, 0, 1, 0, 1, 0, -1, 0, -4.37114e-08, 0, 0.75, 0)
|
8 |
+
script = ExtResource("1_psb6d")
|
9 |
+
|
10 |
+
[node name="car" parent="." instance=ExtResource("2_fqh82")]
|
Completed/scenes/game_scene.tscn
ADDED
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[gd_scene load_steps=6 format=3 uid="uid://dn2auvcty4aoe"]
|
2 |
+
|
3 |
+
[ext_resource type="PackedScene" uid="uid://bsuw6dqwq2e3v" path="res://scenes/robot.tscn" id="1_2k47m"]
|
4 |
+
[ext_resource type="PackedScene" uid="uid://crui8soua8lj2" path="res://scenes/tile.tscn" id="2_ltmsi"]
|
5 |
+
[ext_resource type="Script" path="res://scripts/car_manager.gd" id="4_jfcfq"]
|
6 |
+
[ext_resource type="Script" path="res://scripts/grid_map.gd" id="4_lrlqi"]
|
7 |
+
[ext_resource type="PackedScene" uid="uid://bhk60xl5s8pmm" path="res://scenes/car.tscn" id="4_nsbp8"]
|
8 |
+
|
9 |
+
[node name="GameScene" type="Node3D"]
|
10 |
+
|
11 |
+
[node name="Camera3D" type="Camera3D" parent="."]
|
12 |
+
transform = Transform3D(1, 0, 0, 0, 0.615661, 0.788011, 0, -0.788011, 0.615661, 5, 10, 15.95)
|
13 |
+
size = 12.748
|
14 |
+
|
15 |
+
[node name="Map" type="Node3D" parent="."]
|
16 |
+
script = ExtResource("4_lrlqi")
|
17 |
+
tile = ExtResource("2_ltmsi")
|
18 |
+
|
19 |
+
[node name="Tiles" type="Node3D" parent="Map"]
|
20 |
+
|
21 |
+
[node name="Cars" type="Node3D" parent="." node_paths=PackedStringArray("map")]
|
22 |
+
script = ExtResource("4_jfcfq")
|
23 |
+
map = NodePath("../Map")
|
24 |
+
car_scene = ExtResource("4_nsbp8")
|
25 |
+
|
26 |
+
[node name="Robot" parent="." node_paths=PackedStringArray("map", "car_manager") instance=ExtResource("1_2k47m")]
|
27 |
+
map = NodePath("../Map")
|
28 |
+
car_manager = NodePath("../Cars")
|
Completed/scenes/onnx_inference_scene.tscn
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[gd_scene load_steps=6 format=3 uid="uid://qnxlq4cwno4t"]
|
2 |
+
|
3 |
+
[ext_resource type="PackedScene" uid="uid://dn2auvcty4aoe" path="res://scenes/game_scene.tscn" id="1_0y8h2"]
|
4 |
+
[ext_resource type="Script" path="res://addons/godot_rl_agents/sync.gd" id="2_5kbv3"]
|
5 |
+
|
6 |
+
[sub_resource type="ProceduralSkyMaterial" id="ProceduralSkyMaterial_bdk3k"]
|
7 |
+
sky_horizon_color = Color(0.64625, 0.65575, 0.67075, 1)
|
8 |
+
ground_horizon_color = Color(0.64625, 0.65575, 0.67075, 1)
|
9 |
+
|
10 |
+
[sub_resource type="Sky" id="Sky_uw47m"]
|
11 |
+
sky_material = SubResource("ProceduralSkyMaterial_bdk3k")
|
12 |
+
|
13 |
+
[sub_resource type="Environment" id="Environment_iamhl"]
|
14 |
+
background_mode = 2
|
15 |
+
sky = SubResource("Sky_uw47m")
|
16 |
+
tonemap_mode = 2
|
17 |
+
glow_enabled = true
|
18 |
+
|
19 |
+
[node name="OnnxInferenceScene" type="Node3D"]
|
20 |
+
|
21 |
+
[node name="GameScene" parent="." instance=ExtResource("1_0y8h2")]
|
22 |
+
|
23 |
+
[node name="Sync" type="Node" parent="."]
|
24 |
+
script = ExtResource("2_5kbv3")
|
25 |
+
control_mode = 2
|
26 |
+
action_repeat = 1
|
27 |
+
speed_up = 0.1
|
28 |
+
onnx_model_path = "model.onnx"
|
29 |
+
|
30 |
+
[node name="WorldEnvironment" type="WorldEnvironment" parent="."]
|
31 |
+
environment = SubResource("Environment_iamhl")
|
32 |
+
|
33 |
+
[node name="DirectionalLight3D" type="DirectionalLight3D" parent="."]
|
34 |
+
transform = Transform3D(-0.866025, -0.433013, 0.25, 0, 0.5, 0.866025, -0.5, 0.75, -0.433013, 0, 0, 0)
|
35 |
+
shadow_enabled = true
|
Completed/scenes/robot.tscn
ADDED
@@ -0,0 +1,207 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[gd_scene load_steps=8 format=3 uid="uid://bsuw6dqwq2e3v"]
|
2 |
+
|
3 |
+
[ext_resource type="PackedScene" uid="uid://bb2je1c8jc1qr" path="res://assets/robot.glb" id="1_n7jto"]
|
4 |
+
[ext_resource type="Script" path="res://scripts/robot.gd" id="1_vywkg"]
|
5 |
+
[ext_resource type="Script" path="res://scripts/robot_ai_controller.gd" id="5_sx7mj"]
|
6 |
+
|
7 |
+
[sub_resource type="Animation" id="Animation_2kfmf"]
|
8 |
+
length = 0.001
|
9 |
+
tracks/0/type = "value"
|
10 |
+
tracks/0/imported = false
|
11 |
+
tracks/0/enabled = true
|
12 |
+
tracks/0/path = NodePath("Robot/Arm:rotation")
|
13 |
+
tracks/0/interp = 1
|
14 |
+
tracks/0/loop_wrap = true
|
15 |
+
tracks/0/keys = {
|
16 |
+
"times": PackedFloat32Array(0),
|
17 |
+
"transitions": PackedFloat32Array(1),
|
18 |
+
"update": 0,
|
19 |
+
"values": [Vector3(0, 0, 0)]
|
20 |
+
}
|
21 |
+
tracks/1/type = "value"
|
22 |
+
tracks/1/imported = false
|
23 |
+
tracks/1/enabled = true
|
24 |
+
tracks/1/path = NodePath("Robot/Arm_001:rotation")
|
25 |
+
tracks/1/interp = 1
|
26 |
+
tracks/1/loop_wrap = true
|
27 |
+
tracks/1/keys = {
|
28 |
+
"times": PackedFloat32Array(0),
|
29 |
+
"transitions": PackedFloat32Array(1),
|
30 |
+
"update": 0,
|
31 |
+
"values": [Vector3(0, 0, 0)]
|
32 |
+
}
|
33 |
+
tracks/2/type = "value"
|
34 |
+
tracks/2/imported = false
|
35 |
+
tracks/2/enabled = true
|
36 |
+
tracks/2/path = NodePath("Robot/Torso:position")
|
37 |
+
tracks/2/interp = 1
|
38 |
+
tracks/2/loop_wrap = true
|
39 |
+
tracks/2/keys = {
|
40 |
+
"times": PackedFloat32Array(0),
|
41 |
+
"transitions": PackedFloat32Array(1),
|
42 |
+
"update": 0,
|
43 |
+
"values": [Vector3(0, 0, 0)]
|
44 |
+
}
|
45 |
+
tracks/3/type = "value"
|
46 |
+
tracks/3/imported = false
|
47 |
+
tracks/3/enabled = true
|
48 |
+
tracks/3/path = NodePath("Robot/Head:position")
|
49 |
+
tracks/3/interp = 1
|
50 |
+
tracks/3/loop_wrap = true
|
51 |
+
tracks/3/keys = {
|
52 |
+
"times": PackedFloat32Array(0),
|
53 |
+
"transitions": PackedFloat32Array(1),
|
54 |
+
"update": 0,
|
55 |
+
"values": [Vector3(0, 0, 0)]
|
56 |
+
}
|
57 |
+
tracks/4/type = "value"
|
58 |
+
tracks/4/imported = false
|
59 |
+
tracks/4/enabled = true
|
60 |
+
tracks/4/path = NodePath("Robot/Head:rotation")
|
61 |
+
tracks/4/interp = 1
|
62 |
+
tracks/4/loop_wrap = true
|
63 |
+
tracks/4/keys = {
|
64 |
+
"times": PackedFloat32Array(0),
|
65 |
+
"transitions": PackedFloat32Array(1),
|
66 |
+
"update": 0,
|
67 |
+
"values": [Vector3(0, 0, 0)]
|
68 |
+
}
|
69 |
+
|
70 |
+
[sub_resource type="Animation" id="Animation_ly00x"]
|
71 |
+
resource_name = "idle"
|
72 |
+
length = 4.0
|
73 |
+
loop_mode = 1
|
74 |
+
tracks/0/type = "value"
|
75 |
+
tracks/0/imported = false
|
76 |
+
tracks/0/enabled = true
|
77 |
+
tracks/0/path = NodePath("Robot/Arm:rotation")
|
78 |
+
tracks/0/interp = 2
|
79 |
+
tracks/0/loop_wrap = true
|
80 |
+
tracks/0/keys = {
|
81 |
+
"times": PackedFloat32Array(0, 2),
|
82 |
+
"transitions": PackedFloat32Array(1, 1),
|
83 |
+
"update": 0,
|
84 |
+
"values": [Vector3(0, 0, 0), Vector3(0.349066, 0, 0.0610865)]
|
85 |
+
}
|
86 |
+
tracks/1/type = "value"
|
87 |
+
tracks/1/imported = false
|
88 |
+
tracks/1/enabled = true
|
89 |
+
tracks/1/path = NodePath("Robot/Arm_001:rotation")
|
90 |
+
tracks/1/interp = 2
|
91 |
+
tracks/1/loop_wrap = true
|
92 |
+
tracks/1/keys = {
|
93 |
+
"times": PackedFloat32Array(0, 2),
|
94 |
+
"transitions": PackedFloat32Array(1, 1),
|
95 |
+
"update": 0,
|
96 |
+
"values": [Vector3(0, 0, 0), Vector3(-0.349066, 0, -0.148353)]
|
97 |
+
}
|
98 |
+
tracks/2/type = "value"
|
99 |
+
tracks/2/imported = false
|
100 |
+
tracks/2/enabled = true
|
101 |
+
tracks/2/path = NodePath("Robot/Head:rotation")
|
102 |
+
tracks/2/interp = 2
|
103 |
+
tracks/2/loop_wrap = true
|
104 |
+
tracks/2/keys = {
|
105 |
+
"times": PackedFloat32Array(0, 1, 2, 3),
|
106 |
+
"transitions": PackedFloat32Array(1, 1, 1, 1),
|
107 |
+
"update": 0,
|
108 |
+
"values": [Vector3(0, 0, 0), Vector3(0, 0.162316, 0.0488692), Vector3(0, 0, 0), Vector3(0.139626, -0.178024, 0.0226893)]
|
109 |
+
}
|
110 |
+
|
111 |
+
[sub_resource type="Animation" id="Animation_6jb0l"]
|
112 |
+
resource_name = "idle"
|
113 |
+
loop_mode = 1
|
114 |
+
tracks/0/type = "value"
|
115 |
+
tracks/0/imported = false
|
116 |
+
tracks/0/enabled = true
|
117 |
+
tracks/0/path = NodePath("Robot/Arm:rotation")
|
118 |
+
tracks/0/interp = 2
|
119 |
+
tracks/0/loop_wrap = true
|
120 |
+
tracks/0/keys = {
|
121 |
+
"times": PackedFloat32Array(0, 0.5),
|
122 |
+
"transitions": PackedFloat32Array(1, 1),
|
123 |
+
"update": 0,
|
124 |
+
"values": [Vector3(0, 0, 0), Vector3(0, -0.174533, 0)]
|
125 |
+
}
|
126 |
+
tracks/1/type = "value"
|
127 |
+
tracks/1/imported = false
|
128 |
+
tracks/1/enabled = true
|
129 |
+
tracks/1/path = NodePath("Robot/Arm_001:rotation")
|
130 |
+
tracks/1/interp = 2
|
131 |
+
tracks/1/loop_wrap = true
|
132 |
+
tracks/1/keys = {
|
133 |
+
"times": PackedFloat32Array(0, 0.5),
|
134 |
+
"transitions": PackedFloat32Array(1, 1),
|
135 |
+
"update": 0,
|
136 |
+
"values": [Vector3(0, 0, 0), Vector3(0, 0.174533, 0)]
|
137 |
+
}
|
138 |
+
tracks/2/type = "value"
|
139 |
+
tracks/2/imported = false
|
140 |
+
tracks/2/enabled = true
|
141 |
+
tracks/2/path = NodePath("Robot/Torso:position")
|
142 |
+
tracks/2/interp = 2
|
143 |
+
tracks/2/loop_wrap = true
|
144 |
+
tracks/2/keys = {
|
145 |
+
"times": PackedFloat32Array(0, 0.25, 0.5),
|
146 |
+
"transitions": PackedFloat32Array(1, 1, 1),
|
147 |
+
"update": 0,
|
148 |
+
"values": [Vector3(0, 0, 0), Vector3(0, -0.01, 0), Vector3(0, 0, 0)]
|
149 |
+
}
|
150 |
+
tracks/3/type = "value"
|
151 |
+
tracks/3/imported = false
|
152 |
+
tracks/3/enabled = true
|
153 |
+
tracks/3/path = NodePath("Robot/Head:position")
|
154 |
+
tracks/3/interp = 1
|
155 |
+
tracks/3/loop_wrap = true
|
156 |
+
tracks/3/keys = {
|
157 |
+
"times": PackedFloat32Array(0, 0.5),
|
158 |
+
"transitions": PackedFloat32Array(1, 1),
|
159 |
+
"update": 0,
|
160 |
+
"values": [Vector3(0, 0, 0), Vector3(0, -0.02, 0)]
|
161 |
+
}
|
162 |
+
tracks/4/type = "value"
|
163 |
+
tracks/4/imported = false
|
164 |
+
tracks/4/enabled = true
|
165 |
+
tracks/4/path = NodePath("Robot/Head:rotation")
|
166 |
+
tracks/4/interp = 1
|
167 |
+
tracks/4/loop_wrap = true
|
168 |
+
tracks/4/keys = {
|
169 |
+
"times": PackedFloat32Array(0, 0.25, 0.5),
|
170 |
+
"transitions": PackedFloat32Array(1, 1, 1),
|
171 |
+
"update": 0,
|
172 |
+
"values": [Vector3(0, 0, 0), Vector3(-0.0349066, 0, 0), Vector3(0, 0, 0)]
|
173 |
+
}
|
174 |
+
|
175 |
+
[sub_resource type="AnimationLibrary" id="AnimationLibrary_g7kmm"]
|
176 |
+
_data = {
|
177 |
+
"RESET": SubResource("Animation_2kfmf"),
|
178 |
+
"idle": SubResource("Animation_ly00x"),
|
179 |
+
"walking": SubResource("Animation_6jb0l")
|
180 |
+
}
|
181 |
+
|
182 |
+
[node name="Robot" type="Node3D" groups=["resetable"]]
|
183 |
+
script = ExtResource("1_vywkg")
|
184 |
+
print_game_status_enabled = true
|
185 |
+
metadata/_edit_lock_ = true
|
186 |
+
|
187 |
+
[node name="AIController3D" type="Node3D" parent="."]
|
188 |
+
script = ExtResource("5_sx7mj")
|
189 |
+
reset_after = 40
|
190 |
+
|
191 |
+
[node name="robot" parent="." instance=ExtResource("1_n7jto")]
|
192 |
+
transform = Transform3D(2, 0, 0, 0, 2, 0, 0, 0, 2, 0, -0.1, 0)
|
193 |
+
|
194 |
+
[node name="Robot" parent="robot" index="0"]
|
195 |
+
transform = Transform3D(-4.37114e-08, 0, 1, 0, 1, 0, -1, 0, -4.37114e-08, 0, 0, 0)
|
196 |
+
|
197 |
+
[node name="Arm_001" parent="robot/Robot" index="1"]
|
198 |
+
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0.00394951, 0, -0.18)
|
199 |
+
|
200 |
+
[node name="AnimationPlayer" type="AnimationPlayer" parent="robot"]
|
201 |
+
libraries = {
|
202 |
+
"": SubResource("AnimationLibrary_g7kmm")
|
203 |
+
}
|
204 |
+
autoplay = "idle"
|
205 |
+
speed_scale = 16.0
|
206 |
+
|
207 |
+
[editable path="robot"]
|
Completed/scenes/tile.tscn
ADDED
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[gd_scene load_steps=6 format=3 uid="uid://crui8soua8lj2"]
|
2 |
+
|
3 |
+
[ext_resource type="Script" path="res://scripts/tile.gd" id="1_xode2"]
|
4 |
+
[ext_resource type="PackedScene" uid="uid://bfb0o41scdp70" path="res://assets/road_tile.glb" id="2_c5l1q"]
|
5 |
+
[ext_resource type="PackedScene" uid="uid://bn7tu2v2dgfuc" path="res://assets/orange_tile.glb" id="3_rlmbm"]
|
6 |
+
[ext_resource type="PackedScene" uid="uid://dtq61doicjsbq" path="res://assets/tree_tile.glb" id="4_p4mpm"]
|
7 |
+
[ext_resource type="PackedScene" uid="uid://6wdk5i0xsijn" path="res://assets/goal_tile.glb" id="5_p4gbw"]
|
8 |
+
|
9 |
+
[node name="Tile" type="Node3D"]
|
10 |
+
script = ExtResource("1_xode2")
|
11 |
+
|
12 |
+
[node name="orange_tile" parent="." instance=ExtResource("3_rlmbm")]
|
13 |
+
|
14 |
+
[node name="road_tile" parent="." instance=ExtResource("2_c5l1q")]
|
15 |
+
|
16 |
+
[node name="tree_tile" parent="." instance=ExtResource("4_p4mpm")]
|
17 |
+
|
18 |
+
[node name="goal_tile" parent="." instance=ExtResource("5_p4gbw")]
|
Completed/scenes/training_scene.tscn
ADDED
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[gd_scene load_steps=6 format=3 uid="uid://cl152s178wgm5"]
|
2 |
+
|
3 |
+
[ext_resource type="PackedScene" uid="uid://dn2auvcty4aoe" path="res://scenes/game_scene.tscn" id="1_ft0b8"]
|
4 |
+
[ext_resource type="Script" path="res://addons/godot_rl_agents/sync.gd" id="2_sk0r2"]
|
5 |
+
|
6 |
+
[sub_resource type="ProceduralSkyMaterial" id="ProceduralSkyMaterial_bdk3k"]
|
7 |
+
sky_horizon_color = Color(0.64625, 0.65575, 0.67075, 1)
|
8 |
+
ground_horizon_color = Color(0.64625, 0.65575, 0.67075, 1)
|
9 |
+
|
10 |
+
[sub_resource type="Sky" id="Sky_uw47m"]
|
11 |
+
sky_material = SubResource("ProceduralSkyMaterial_bdk3k")
|
12 |
+
|
13 |
+
[sub_resource type="Environment" id="Environment_iamhl"]
|
14 |
+
background_mode = 2
|
15 |
+
sky = SubResource("Sky_uw47m")
|
16 |
+
tonemap_mode = 2
|
17 |
+
glow_enabled = true
|
18 |
+
|
19 |
+
[node name="TrainingScene" type="Node3D"]
|
20 |
+
|
21 |
+
[node name="GameScene" parent="." instance=ExtResource("1_ft0b8")]
|
22 |
+
|
23 |
+
[node name="GameScene2" parent="." instance=ExtResource("1_ft0b8")]
|
24 |
+
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -30, 0, 0)
|
25 |
+
|
26 |
+
[node name="GameScene3" parent="." instance=ExtResource("1_ft0b8")]
|
27 |
+
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 30, 0, 0)
|
28 |
+
|
29 |
+
[node name="GameScene4" parent="." instance=ExtResource("1_ft0b8")]
|
30 |
+
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, -400)
|
31 |
+
|
32 |
+
[node name="Sync" type="Node" parent="."]
|
33 |
+
script = ExtResource("2_sk0r2")
|
34 |
+
action_repeat = 1
|
35 |
+
speed_up = 8.0
|
36 |
+
|
37 |
+
[node name="WorldEnvironment" type="WorldEnvironment" parent="."]
|
38 |
+
environment = SubResource("Environment_iamhl")
|
39 |
+
|
40 |
+
[node name="DirectionalLight3D" type="DirectionalLight3D" parent="."]
|
41 |
+
transform = Transform3D(-0.866025, -0.433013, 0.25, 0, 0.5, 0.866025, -0.5, 0.75, -0.433013, 0, 0, 0)
|
42 |
+
shadow_enabled = true
|
Completed/scripts/car.gd
ADDED
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
extends Node3D
|
2 |
+
class_name Car
|
3 |
+
|
4 |
+
## Car, moves along x axis,
|
5 |
+
## and changes direction once left or right edge is reached
|
6 |
+
|
7 |
+
#region Initialized by car manager
|
8 |
+
var step_size: int
|
9 |
+
var left_edge_x: int
|
10 |
+
var right_edge_x: int
|
11 |
+
var current_direction: int = 1
|
12 |
+
#endregion
|
13 |
+
|
14 |
+
func _physics_process(_delta: float) -> void:
|
15 |
+
if not (position.x > left_edge_x and position.x < right_edge_x):
|
16 |
+
current_direction = -current_direction
|
17 |
+
rotation.y = current_direction / 2.0 * PI
|
18 |
+
position.x += step_size * current_direction
|
Completed/scripts/car_manager.gd
ADDED
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
extends Node3D
|
2 |
+
class_name CarManager
|
3 |
+
|
4 |
+
@export var map: Map
|
5 |
+
@export var car_scene: PackedScene
|
6 |
+
|
7 |
+
var car_left_edge_x: int
|
8 |
+
var car_right_edge_x: int
|
9 |
+
|
10 |
+
@onready var cars: Array[Node] = get_children()
|
11 |
+
|
12 |
+
# Called when the node enters the scene tree for the first time.
|
13 |
+
func _ready() -> void:
|
14 |
+
for road_row_idx in map.road_rows.size():
|
15 |
+
create_car()
|
16 |
+
reset()
|
17 |
+
|
18 |
+
|
19 |
+
func create_car():
|
20 |
+
var new_car = car_scene.instantiate()
|
21 |
+
add_child(new_car)
|
22 |
+
cars.append(new_car)
|
23 |
+
|
24 |
+
|
25 |
+
func reset():
|
26 |
+
# If there are more cars than the current map layout road rows, remove
|
27 |
+
# the extra cars
|
28 |
+
while cars.size() > map.road_rows.size():
|
29 |
+
cars[cars.size() - 1].queue_free()
|
30 |
+
cars.remove_at(cars.size() - 1)
|
31 |
+
|
32 |
+
# If there are less cars than the current map layout road rows,
|
33 |
+
# add more cars
|
34 |
+
while cars.size() < map.road_rows.size():
|
35 |
+
create_car()
|
36 |
+
|
37 |
+
# Set car edge positions (at which they turn), position and other properties
|
38 |
+
for car_id in cars.size():
|
39 |
+
var car = cars[car_id]
|
40 |
+
car.left_edge_x = 0
|
41 |
+
car.right_edge_x = (map.grid_size_x - 1) * map.tile_size
|
42 |
+
car.step_size = map.tile_size
|
43 |
+
|
44 |
+
car.position.x = range(car.left_edge_x + 2, car.right_edge_x - 2, 2).pick_random()
|
45 |
+
car.position.y = map.tile_size / 2 + 0.75 # 0.75 is to make the bottom of the car be at road height
|
46 |
+
car.position.z = map.road_rows[car_id] * 2
|
47 |
+
|
48 |
+
car.current_direction = 1 if randi_range(0, 1) == 0 else -1
|
Completed/scripts/grid_map.gd
ADDED
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
extends Node3D
|
2 |
+
class_name Map
|
3 |
+
|
4 |
+
@export var tile: PackedScene
|
5 |
+
|
6 |
+
# Grid positions
|
7 |
+
var instantiated_tiles: Dictionary
|
8 |
+
var tile_positions: Array[Vector3i]
|
9 |
+
|
10 |
+
var player_start_position: Vector3i
|
11 |
+
var goal_position: Vector3i
|
12 |
+
|
13 |
+
## Size of each tile, adjust manually if using larger or smaller tiles
|
14 |
+
var tile_size: int = 2
|
15 |
+
|
16 |
+
## Determines the width of the grid, tested with 6
|
17 |
+
## may need adjustments for the AIController obs as it captures
|
18 |
+
## 6 cells from the left and right of the player
|
19 |
+
var grid_size_x = 6
|
20 |
+
|
21 |
+
## Number of rows in the grid
|
22 |
+
var grid_size_z = 0
|
23 |
+
|
24 |
+
var road_rows: Array[int]
|
25 |
+
|
26 |
+
var tiles_instantiated: bool = false
|
27 |
+
|
28 |
+
## Removes all tile nodes on first launch (if any are added in the editor)
|
29 |
+
## and on subsequent calls, it hides all tiles
|
30 |
+
func remove_all_tiles():
|
31 |
+
for tile in $Tiles.get_children():
|
32 |
+
if not tiles_instantiated:
|
33 |
+
tile.queue_free()
|
34 |
+
else:
|
35 |
+
tile.hide_all()
|
36 |
+
|
37 |
+
tile_positions.clear()
|
38 |
+
road_rows.clear()
|
39 |
+
grid_size_z = 0
|
40 |
+
|
41 |
+
## Adds a tile to the grid, takes a scene containing the tile and grid position
|
42 |
+
func create_tile(tile_name: Tile.TileNames, grid_position: Vector3i):
|
43 |
+
if instantiated_tiles.has(grid_position):
|
44 |
+
instantiated_tiles[grid_position].set_tile(tile_name)
|
45 |
+
tile_positions.append(grid_position)
|
46 |
+
return
|
47 |
+
|
48 |
+
var new_tile = tile.instantiate() as Tile
|
49 |
+
new_tile.position = grid_position * tile_size
|
50 |
+
$Tiles.add_child(new_tile)
|
51 |
+
instantiated_tiles[grid_position] = new_tile
|
52 |
+
new_tile.set_tile(tile_name)
|
53 |
+
tile_positions.append(grid_position)
|
54 |
+
|
55 |
+
func _ready():
|
56 |
+
set_cells()
|
57 |
+
|
58 |
+
## You can set the layout by adjusting each row with set_row_cells()
|
59 |
+
## Note: Changing size after initial start is not supported
|
60 |
+
## you can change the order or rows or how many of the second tiles to add
|
61 |
+
## as long as the total size (number of rows, width) remains the same
|
62 |
+
|
63 |
+
func set_cells():
|
64 |
+
remove_all_tiles()
|
65 |
+
|
66 |
+
add_row(Tile.TileNames.orange, Tile.TileNames.goal, 1)
|
67 |
+
add_row(Tile.TileNames.orange)
|
68 |
+
add_row(Tile.TileNames.orange, Tile.TileNames.tree, 2)
|
69 |
+
add_row(Tile.TileNames.road)
|
70 |
+
add_row(Tile.TileNames.orange, Tile.TileNames.tree, 2)
|
71 |
+
add_row(Tile.TileNames.orange)
|
72 |
+
add_row(Tile.TileNames.orange)
|
73 |
+
|
74 |
+
set_player_position_to_last_row()
|
75 |
+
|
76 |
+
tiles_instantiated = true
|
77 |
+
|
78 |
+
func reset():
|
79 |
+
if not is_node_ready():
|
80 |
+
await ready
|
81 |
+
set_cells()
|
82 |
+
|
83 |
+
func get_tile(grid_pos: Vector3i):
|
84 |
+
if not grid_pos in tile_positions:
|
85 |
+
return null
|
86 |
+
return instantiated_tiles[grid_pos]
|
87 |
+
|
88 |
+
|
89 |
+
func get_grid_position(global_pos: Vector3i):
|
90 |
+
var grid_pos = Vector3i(to_local(global_pos) / 2.0)
|
91 |
+
return grid_pos
|
92 |
+
|
93 |
+
func set_row_tiles(row: int, tile: Tile.TileNames, second_tile: Tile.TileNames = Tile.TileNames.orange, second_tile_count: int = 0):
|
94 |
+
var first_tile_columns: Array = range(grid_size_x)
|
95 |
+
|
96 |
+
if second_tile_count:
|
97 |
+
for i in second_tile_count:
|
98 |
+
first_tile_columns.remove_at(randi_range(0, first_tile_columns.size() - 1))
|
99 |
+
|
100 |
+
for column in range(grid_size_x):
|
101 |
+
var tile_to_create: Tile.TileNames
|
102 |
+
if column in first_tile_columns:
|
103 |
+
tile_to_create = tile
|
104 |
+
else:
|
105 |
+
tile_to_create = second_tile
|
106 |
+
var tile_grid_coords := Vector3i(column, 0, row)
|
107 |
+
create_tile(tile_to_create, tile_grid_coords)
|
108 |
+
if tile_to_create == Tile.TileNames.goal:
|
109 |
+
goal_position = tile_grid_coords
|
110 |
+
|
111 |
+
if tile == Tile.TileNames.road:
|
112 |
+
road_rows.append(row)
|
113 |
+
|
114 |
+
func add_row(tile: Tile.TileNames, second_tile: Tile.TileNames = Tile.TileNames.orange, second_tile_count: int = 0):
|
115 |
+
set_row_tiles(grid_size_z, tile, second_tile, second_tile_count)
|
116 |
+
grid_size_z += 1
|
117 |
+
|
118 |
+
func set_player_position_to_grid_row(row: int):
|
119 |
+
player_start_position = to_global(Vector3i(range(0, grid_size_x - 1, 2).pick_random(), 0, row * tile_size))
|
120 |
+
|
121 |
+
func set_player_position_to_last_row():
|
122 |
+
set_player_position_to_grid_row(grid_size_z - 1)
|
Completed/scripts/robot.gd
ADDED
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
extends Node3D
|
2 |
+
class_name Player
|
3 |
+
|
4 |
+
## Whether to print the game success/failed messsages to console
|
5 |
+
@export var print_game_status_enabled: bool
|
6 |
+
|
7 |
+
## How far the robot can move per step
|
8 |
+
@export var movement_step := 2.0
|
9 |
+
|
10 |
+
@export var map: Map
|
11 |
+
@export var car_manager: CarManager
|
12 |
+
|
13 |
+
@onready var _ai_controller := $AIController3D
|
14 |
+
@onready var visual_robot: Node3D = $robot
|
15 |
+
|
16 |
+
var last_dist_to_goal
|
17 |
+
|
18 |
+
#region Set by AIController
|
19 |
+
var requested_movement: Vector3
|
20 |
+
#endregion
|
21 |
+
|
22 |
+
|
23 |
+
func _ready():
|
24 |
+
reset()
|
25 |
+
|
26 |
+
|
27 |
+
func _physics_process(delta):
|
28 |
+
# Set to true by the sync node when reset is requested from Python (starting training, evaluation, etc.)
|
29 |
+
if _ai_controller.needs_reset:
|
30 |
+
game_over()
|
31 |
+
_process_movement(delta)
|
32 |
+
|
33 |
+
|
34 |
+
func _process_movement(_delta):
|
35 |
+
for car in car_manager.cars:
|
36 |
+
if get_grid_position() == map.get_grid_position(car.global_position):
|
37 |
+
# If a car has moved to the current player position, end episode
|
38 |
+
game_over(0)
|
39 |
+
print_game_status("Failed, hit car while standing")
|
40 |
+
|
41 |
+
if requested_movement:
|
42 |
+
# Move the robot to the requested position
|
43 |
+
global_position += (requested_movement * movement_step)
|
44 |
+
# Update the visual rotation of the robot to look toward the direction of last requested movement
|
45 |
+
visual_robot.global_rotation_degrees.y = rad_to_deg(atan2(-requested_movement.x, -requested_movement.z))
|
46 |
+
|
47 |
+
var grid_position: Vector3i = get_grid_position()
|
48 |
+
var tile: Tile = map.get_tile(grid_position)
|
49 |
+
|
50 |
+
if not tile:
|
51 |
+
# Push the robot back if there's no tile to move to (out of map boundary)
|
52 |
+
global_position -= (requested_movement * movement_step)
|
53 |
+
elif tile.id == tile.TileNames.tree:
|
54 |
+
# Push the robot back if it has moved to a tree tile
|
55 |
+
global_position -= (requested_movement * movement_step)
|
56 |
+
elif tile.id == tile.TileNames.goal:
|
57 |
+
# If a goal tile is reached, end episode with reward +1
|
58 |
+
game_over(1)
|
59 |
+
print_game_status("Success, reached goal")
|
60 |
+
else:
|
61 |
+
for car in car_manager.cars:
|
62 |
+
if get_grid_position() == map.get_grid_position(car.global_position):
|
63 |
+
# If the robot moved to a car's current position, end episode
|
64 |
+
game_over(0)
|
65 |
+
print_game_status("Failed, hit car while walking")
|
66 |
+
|
67 |
+
# After processing the move, zero the movement for the next step
|
68 |
+
# (only in case of human control)
|
69 |
+
if _ai_controller.control_mode == AIController3D.ControlModes.HUMAN:
|
70 |
+
requested_movement = Vector3.ZERO
|
71 |
+
|
72 |
+
reward_approaching_goal()
|
73 |
+
|
74 |
+
|
75 |
+
## Adds a positive reward if the robot approaches the goal
|
76 |
+
func reward_approaching_goal():
|
77 |
+
var grid_pos: Vector3i = get_grid_position()
|
78 |
+
var dist_to_goal = grid_pos.distance_to(map.goal_position)
|
79 |
+
if last_dist_to_goal == null: last_dist_to_goal = dist_to_goal
|
80 |
+
|
81 |
+
if dist_to_goal < last_dist_to_goal:
|
82 |
+
_ai_controller.reward += (last_dist_to_goal - dist_to_goal) / 10.0
|
83 |
+
last_dist_to_goal = dist_to_goal
|
84 |
+
|
85 |
+
|
86 |
+
func get_grid_position() -> Vector3i:
|
87 |
+
return map.get_grid_position(global_position)
|
88 |
+
|
89 |
+
|
90 |
+
func game_over(reward = 0.0):
|
91 |
+
_ai_controller.done = true
|
92 |
+
_ai_controller.reward += reward
|
93 |
+
_ai_controller.reset()
|
94 |
+
reset()
|
95 |
+
|
96 |
+
|
97 |
+
func reset():
|
98 |
+
last_dist_to_goal = null
|
99 |
+
# Order of resetting is important:
|
100 |
+
# We reset the map first, which sets a new player start position
|
101 |
+
# and the road segments (needed to know where to spawn the cars)
|
102 |
+
map.reset()
|
103 |
+
# after that, we can set the player position
|
104 |
+
global_position = Vector3(map.player_start_position) + Vector3.UP * 1.5
|
105 |
+
# and also reset or create (on first start) the cars
|
106 |
+
car_manager.reset()
|
107 |
+
|
108 |
+
|
109 |
+
func print_game_status(message: String):
|
110 |
+
if print_game_status_enabled:
|
111 |
+
print(message)
|
Completed/scripts/robot_ai_controller.gd
ADDED
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
extends AIController3D
|
2 |
+
class_name RobotAIController
|
3 |
+
|
4 |
+
@onready var player := get_parent() as Player
|
5 |
+
|
6 |
+
|
7 |
+
func get_obs() -> Dictionary:
|
8 |
+
var observations := Array()
|
9 |
+
var player_pos = player.get_grid_position()
|
10 |
+
|
11 |
+
# Determines how many grid cells the AI can observe
|
12 |
+
# e.g. front refers to "up" looking from above,
|
13 |
+
# and does not rotate with the robot, same with others.
|
14 |
+
# Set to observe all cells from two rows in front of player,
|
15 |
+
# 0 behind
|
16 |
+
var visible_rows_in_front_of_player: int = 2
|
17 |
+
var visible_rows_behind_the_player: int = 0
|
18 |
+
|
19 |
+
# Set to observe the entire width of the grid on both sides
|
20 |
+
# so it will always see all cells up to 2 rows in front.
|
21 |
+
var visible_columns_left_of_player: int = player.map.grid_size_x
|
22 |
+
var visible_columns_right_of_player: int = player.map.grid_size_x
|
23 |
+
|
24 |
+
# For tiles near player we provide [direction, id] (e.g: [-1, 0])
|
25 |
+
# direction is -1 or 1 for cars, 0 for static tiles
|
26 |
+
# if a car is in a tile, we override the id of tile underneath
|
27 |
+
|
28 |
+
# Car ID is the ID of the last tile + 1
|
29 |
+
var car_id = Tile.TileNames.size()
|
30 |
+
|
31 |
+
# If there is no tile placed at the grid coord, we use -1 as id
|
32 |
+
var no_tile_id: int = -1
|
33 |
+
|
34 |
+
# Note: We don't need to include the player position directly in obs
|
35 |
+
# as we are always including data for cells "around" the player,
|
36 |
+
# so the player location relative to those cells is implicitly included
|
37 |
+
|
38 |
+
for z in range(
|
39 |
+
player_pos.z - visible_rows_in_front_of_player,
|
40 |
+
player_pos.z + visible_rows_behind_the_player + 1
|
41 |
+
):
|
42 |
+
for x in range(
|
43 |
+
player_pos.x - visible_columns_left_of_player,
|
44 |
+
player_pos.x + visible_columns_right_of_player + 1
|
45 |
+
):
|
46 |
+
var grid_pos := Vector3i(x, 0, z)
|
47 |
+
var tile: Tile = player.map.get_tile(grid_pos)
|
48 |
+
|
49 |
+
if not tile:
|
50 |
+
observations.append_array([0, no_tile_id])
|
51 |
+
else:
|
52 |
+
var is_car: bool
|
53 |
+
for car in player.car_manager.cars:
|
54 |
+
if grid_pos == player.map.get_grid_position(car.global_position):
|
55 |
+
is_car = true
|
56 |
+
observations.append(car.current_direction)
|
57 |
+
if is_car:
|
58 |
+
observations.append(car_id)
|
59 |
+
else:
|
60 |
+
observations.append_array([0, tile.id])
|
61 |
+
|
62 |
+
return {"obs": observations}
|
63 |
+
|
64 |
+
|
65 |
+
func get_reward() -> float:
|
66 |
+
return reward
|
67 |
+
|
68 |
+
|
69 |
+
func _process(_delta: float) -> void:
|
70 |
+
# In case of human control, we get the user input
|
71 |
+
if control_mode == ControlModes.HUMAN:
|
72 |
+
get_user_input()
|
73 |
+
|
74 |
+
|
75 |
+
func _physics_process(_delta: float) -> void:
|
76 |
+
# Reset on timeout, this is implemented in parent class to set needs_reset to true,
|
77 |
+
# we are re-implementing here to call player.game_over() that handles the game reset.
|
78 |
+
n_steps += 1
|
79 |
+
if n_steps > reset_after:
|
80 |
+
player.game_over(0)
|
81 |
+
player.print_game_status("Episode timed out.")
|
82 |
+
|
83 |
+
|
84 |
+
## Defines the actions for the AI agent
|
85 |
+
func get_action_space() -> Dictionary:
|
86 |
+
return {
|
87 |
+
"movement": {"size": 5, "action_type": "discrete"},
|
88 |
+
}
|
89 |
+
|
90 |
+
|
91 |
+
## Applies AI control actions to the robot
|
92 |
+
func set_action(action = null) -> void:
|
93 |
+
# We have specified discrete action type with size 5,
|
94 |
+
# which means there are 5 possible values that the agent can output
|
95 |
+
# for each step, i.e. one of: 0, 1, 2, 3, 4,
|
96 |
+
# we use those to allow the agent to move in 4 directions,
|
97 |
+
# + there is a 'no movement' action.
|
98 |
+
# First convert to int to use match as action value is of float type.
|
99 |
+
match int(action.movement):
|
100 |
+
0:
|
101 |
+
player.requested_movement = Vector3.LEFT
|
102 |
+
1:
|
103 |
+
player.requested_movement = Vector3.RIGHT
|
104 |
+
2:
|
105 |
+
player.requested_movement = Vector3.FORWARD
|
106 |
+
3:
|
107 |
+
player.requested_movement = Vector3.BACK
|
108 |
+
4:
|
109 |
+
player.requested_movement = Vector3.ZERO
|
110 |
+
|
111 |
+
|
112 |
+
## Applies user input actions to the robot
|
113 |
+
func get_user_input() -> void:
|
114 |
+
if Input.is_action_just_pressed("move_up"):
|
115 |
+
player.requested_movement = Vector3.FORWARD
|
116 |
+
elif Input.is_action_just_pressed("move_right"):
|
117 |
+
player.requested_movement = Vector3.RIGHT
|
118 |
+
elif Input.is_action_just_pressed("move_down"):
|
119 |
+
player.requested_movement = Vector3.BACK
|
120 |
+
elif Input.is_action_just_pressed("move_left"):
|
121 |
+
player.requested_movement = Vector3.LEFT
|
Completed/scripts/tile.gd
ADDED
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
extends Node3D
|
2 |
+
class_name Tile
|
3 |
+
|
4 |
+
## Tile class it allows setting the visible tile design by
|
5 |
+
## hiding the nodes with not currently used tile designs.
|
6 |
+
## (Intended to be used with tile.tscn)
|
7 |
+
|
8 |
+
## Tile names, must be in the same order as child nodes
|
9 |
+
enum TileNames {
|
10 |
+
orange,
|
11 |
+
road,
|
12 |
+
tree,
|
13 |
+
goal
|
14 |
+
}
|
15 |
+
|
16 |
+
## ID of the current set tile
|
17 |
+
var id: int
|
18 |
+
|
19 |
+
@onready var tiles: Array = get_children()
|
20 |
+
|
21 |
+
## Sets the specified tile mesh to be visible, and hides others
|
22 |
+
func set_tile(tile_name: TileNames):
|
23 |
+
hide_all()
|
24 |
+
id = int(tile_name)
|
25 |
+
tiles[id].visible = true
|
26 |
+
|
27 |
+
## Hides all tiles
|
28 |
+
func hide_all():
|
29 |
+
for tile in tiles:
|
30 |
+
tile.visible = false
|
README.md
ADDED
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
library_name: godot-rl
|
3 |
+
tags:
|
4 |
+
- deep-reinforcement-learning
|
5 |
+
- reinforcement-learning
|
6 |
+
- godot-rl
|
7 |
+
- environments
|
8 |
+
- video-games
|
9 |
+
---
|
10 |
+
|
11 |
+
A RL environment called CrossTheRoad for the Godot Game Engine.
|
12 |
+
|
13 |
+
This environment was created with: https://github.com/edbeeching/godot_rl_agents
|
14 |
+
|
15 |
+
|
16 |
+
## Downloading the environment
|
17 |
+
|
18 |
+
After installing Godot RL Agents, download the environment with:
|
19 |
+
|
20 |
+
```
|
21 |
+
gdrl.env_from_hub -r jtatman/godot_rl_CrossTheRoad
|
22 |
+
```
|
23 |
+
|
24 |
+
|
25 |
+
|