diff --git a/README.md b/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..1e8a7e4d5b0e9b8fbc95c3733f199e2eaa1f4f29
--- /dev/null
+++ b/README.md
@@ -0,0 +1,25 @@
+---
+library_name: godot-rl
+tags:
+- deep-reinforcement-learning
+- reinforcement-learning
+- godot-rl
+- environments
+- video-games
+---
+
+A RL environment called TestExamples for the Godot Game Engine.
+
+This environment was created with: https://github.com/edbeeching/godot_rl_agents
+
+
+## Downloading the environment
+
+After installing Godot RL Agents, download the environment with:
+
+```
+gdrl.env_from_hub -r jtatman/godot_rl_TestExamples
+```
+
+
+
diff --git a/SimpleReachGoal/CSharp/.gitattributes b/SimpleReachGoal/CSharp/.gitattributes
new file mode 100644
index 0000000000000000000000000000000000000000..8ad74f78d9c9b9b8f3d68772c6d5aa0cb3fe47e9
--- /dev/null
+++ b/SimpleReachGoal/CSharp/.gitattributes
@@ -0,0 +1,2 @@
+# Normalize EOL for all files that Git considers text files.
+* text=auto eol=lf
diff --git a/SimpleReachGoal/CSharp/.gitignore b/SimpleReachGoal/CSharp/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..7de8ea58b7054d16d554ddea743ca5255256b122
--- /dev/null
+++ b/SimpleReachGoal/CSharp/.gitignore
@@ -0,0 +1,3 @@
+# Godot 4+ specific ignores
+.godot/
+android/
diff --git a/SimpleReachGoal/CSharp/SimpleReachGoal.csproj b/SimpleReachGoal/CSharp/SimpleReachGoal.csproj
new file mode 100644
index 0000000000000000000000000000000000000000..9e0f6e5f28fa39bd53a520b4df2afde5651b4452
--- /dev/null
+++ b/SimpleReachGoal/CSharp/SimpleReachGoal.csproj
@@ -0,0 +1,11 @@
+
+
+ net6.0
+ net7.0
+ net8.0
+ true
+
+
+
+
+
\ No newline at end of file
diff --git a/SimpleReachGoal/CSharp/SimpleReachGoal.onnx b/SimpleReachGoal/CSharp/SimpleReachGoal.onnx
new file mode 100644
index 0000000000000000000000000000000000000000..49cab68f41ae98ae9730c0ef9f98876deecbcd06
--- /dev/null
+++ b/SimpleReachGoal/CSharp/SimpleReachGoal.onnx
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:80cdcca6356a62cf997e3f18777c799ca930b53236f4fb2e911edec5c6c78838
+size 40656
diff --git a/SimpleReachGoal/CSharp/SimpleReachGoal.sln b/SimpleReachGoal/CSharp/SimpleReachGoal.sln
new file mode 100644
index 0000000000000000000000000000000000000000..cac7cbea2c4eb2fff6dba72881672fb52ef40f35
--- /dev/null
+++ b/SimpleReachGoal/CSharp/SimpleReachGoal.sln
@@ -0,0 +1,19 @@
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio 2012
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SimpleReachGoal", "SimpleReachGoal.csproj", "{8B1C40FD-E462-48E5-B273-A0E360A0580B}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|Any CPU = Debug|Any CPU
+ ExportDebug|Any CPU = ExportDebug|Any CPU
+ ExportRelease|Any CPU = ExportRelease|Any CPU
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {8B1C40FD-E462-48E5-B273-A0E360A0580B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {8B1C40FD-E462-48E5-B273-A0E360A0580B}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {8B1C40FD-E462-48E5-B273-A0E360A0580B}.ExportDebug|Any CPU.ActiveCfg = ExportDebug|Any CPU
+ {8B1C40FD-E462-48E5-B273-A0E360A0580B}.ExportDebug|Any CPU.Build.0 = ExportDebug|Any CPU
+ {8B1C40FD-E462-48E5-B273-A0E360A0580B}.ExportRelease|Any CPU.ActiveCfg = ExportRelease|Any CPU
+ {8B1C40FD-E462-48E5-B273-A0E360A0580B}.ExportRelease|Any CPU.Build.0 = ExportRelease|Any CPU
+ EndGlobalSection
+EndGlobal
diff --git a/SimpleReachGoal/CSharp/addons/godot_rl_agents/controller/ai_controller_2d.gd b/SimpleReachGoal/CSharp/addons/godot_rl_agents/controller/ai_controller_2d.gd
new file mode 100644
index 0000000000000000000000000000000000000000..fb2365649bc6a900453f5ba262af82bd59fa5a6c
--- /dev/null
+++ b/SimpleReachGoal/CSharp/addons/godot_rl_agents/controller/ai_controller_2d.gd
@@ -0,0 +1,118 @@
+extends Node2D
+class_name AIController2D
+
+enum ControlModes { INHERIT_FROM_SYNC, HUMAN, TRAINING, ONNX_INFERENCE, RECORD_EXPERT_DEMOS }
+@export var control_mode: ControlModes = ControlModes.INHERIT_FROM_SYNC
+@export var onnx_model_path := ""
+@export var reset_after := 1000
+
+@export_group("Record expert demos mode options")
+## Path where the demos will be saved. The file can later be used for imitation learning.
+@export var expert_demo_save_path: String
+## The action that erases the last recorded episode from the currently recorded data.
+@export var remove_last_episode_key: InputEvent
+## Action will be repeated for n frames. Will introduce control lag if larger than 1.
+## Can be used to ensure that action_repeat on inference and training matches
+## the recorded demonstrations.
+@export var action_repeat: int = 1
+
+var onnx_model: ONNXModel
+
+var heuristic := "human"
+var done := false
+var reward := 0.0
+var n_steps := 0
+var needs_reset := false
+
+var _player: Node2D
+
+
+func _ready():
+ add_to_group("AGENT")
+
+
+func init(player: Node2D):
+ _player = player
+
+
+#-- Methods that need implementing using the "extend script" option in Godot --#
+func get_obs() -> Dictionary:
+ assert(false, "the get_obs method is not implemented when extending from ai_controller")
+ return {"obs": []}
+
+
+func get_reward() -> float:
+ assert(false, "the get_reward method is not implemented when extending from ai_controller")
+ return 0.0
+
+
+func get_action_space() -> Dictionary:
+ assert(
+ false,
+ "the get get_action_space method is not implemented when extending from ai_controller"
+ )
+ return {
+ "example_actions_continous": {"size": 2, "action_type": "continuous"},
+ "example_actions_discrete": {"size": 2, "action_type": "discrete"},
+ }
+
+
+func set_action(action) -> void:
+ assert(false, "the set_action method is not implemented when extending from ai_controller")
+
+
+#-----------------------------------------------------------------------------#
+
+
+#-- Methods that sometimes need implementing using the "extend script" option in Godot --#
+# Only needed if you are recording expert demos with this AIController
+func get_action() -> Array:
+ assert(
+ false,
+ "the get_action method is not implemented in extended AIController but demo_recorder is used"
+ )
+ return []
+
+
+# -----------------------------------------------------------------------------#
+
+
+func _physics_process(delta):
+ n_steps += 1
+ if n_steps > reset_after:
+ needs_reset = true
+
+
+func get_obs_space():
+ # may need overriding if the obs space is complex
+ var obs = get_obs()
+ return {
+ "obs": {"size": [len(obs["obs"])], "space": "box"},
+ }
+
+
+func reset():
+ n_steps = 0
+ needs_reset = false
+
+
+func reset_if_done():
+ if done:
+ reset()
+
+
+func set_heuristic(h):
+ # sets the heuristic from "human" or "model" nothing to change here
+ heuristic = h
+
+
+func get_done():
+ return done
+
+
+func set_done_false():
+ done = false
+
+
+func zero_reward():
+ reward = 0.0
diff --git a/SimpleReachGoal/CSharp/addons/godot_rl_agents/controller/ai_controller_3d.gd b/SimpleReachGoal/CSharp/addons/godot_rl_agents/controller/ai_controller_3d.gd
new file mode 100644
index 0000000000000000000000000000000000000000..a5b4ee61ac838c03d6e22283f17adce0e6b4bbfa
--- /dev/null
+++ b/SimpleReachGoal/CSharp/addons/godot_rl_agents/controller/ai_controller_3d.gd
@@ -0,0 +1,117 @@
+extends Node3D
+class_name AIController3D
+
+enum ControlModes { INHERIT_FROM_SYNC, HUMAN, TRAINING, ONNX_INFERENCE, RECORD_EXPERT_DEMOS }
+@export var control_mode: ControlModes = ControlModes.INHERIT_FROM_SYNC
+@export var onnx_model_path := ""
+@export var reset_after := 1000
+
+@export_group("Record expert demos mode options")
+## Path where the demos will be saved. The file can later be used for imitation learning.
+@export var expert_demo_save_path: String
+## The action that erases the last recorded episode from the currently recorded data.
+@export var remove_last_episode_key: InputEvent
+## Action will be repeated for n frames. Will introduce control lag if larger than 1.
+## Can be used to ensure that action_repeat on inference and training matches
+## the recorded demonstrations.
+@export var action_repeat: int = 1
+
+var onnx_model: ONNXModel
+
+var heuristic := "human"
+var done := false
+var reward := 0.0
+var n_steps := 0
+var needs_reset := false
+
+var _player: Node3D
+
+
+func _ready():
+ add_to_group("AGENT")
+
+
+func init(player: Node3D):
+ _player = player
+
+
+#-- Methods that need implementing using the "extend script" option in Godot --#
+func get_obs() -> Dictionary:
+ assert(false, "the get_obs method is not implemented when extending from ai_controller")
+ return {"obs": []}
+
+
+func get_reward() -> float:
+ assert(false, "the get_reward method is not implemented when extending from ai_controller")
+ return 0.0
+
+
+func get_action_space() -> Dictionary:
+ assert(
+ false, "the get_action_space method is not implemented when extending from ai_controller"
+ )
+ return {
+ "example_actions_continous": {"size": 2, "action_type": "continuous"},
+ "example_actions_discrete": {"size": 2, "action_type": "discrete"},
+ }
+
+
+func set_action(action) -> void:
+ assert(false, "the set_action method is not implemented when extending from ai_controller")
+
+
+#-----------------------------------------------------------------------------#
+
+
+#-- Methods that sometimes need implementing using the "extend script" option in Godot --#
+# Only needed if you are recording expert demos with this AIController
+func get_action() -> Array:
+ assert(
+ false,
+ "the get_action method is not implemented in extended AIController but demo_recorder is used"
+ )
+ return []
+
+
+# -----------------------------------------------------------------------------#
+
+
+func _physics_process(delta):
+ n_steps += 1
+ if n_steps > reset_after:
+ needs_reset = true
+
+
+func get_obs_space():
+ # may need overriding if the obs space is complex
+ var obs = get_obs()
+ return {
+ "obs": {"size": [len(obs["obs"])], "space": "box"},
+ }
+
+
+func reset():
+ n_steps = 0
+ needs_reset = false
+
+
+func reset_if_done():
+ if done:
+ reset()
+
+
+func set_heuristic(h):
+ # sets the heuristic from "human" or "model" nothing to change here
+ heuristic = h
+
+
+func get_done():
+ return done
+
+
+func set_done_false():
+ done = false
+
+
+func zero_reward():
+ reward = 0.0
diff --git a/SimpleReachGoal/CSharp/addons/godot_rl_agents/godot_rl_agents.gd b/SimpleReachGoal/CSharp/addons/godot_rl_agents/godot_rl_agents.gd
new file mode 100644
index 0000000000000000000000000000000000000000..e4fe13693a598c808aca1b64051d1c0c70783296
--- /dev/null
+++ b/SimpleReachGoal/CSharp/addons/godot_rl_agents/godot_rl_agents.gd
@@ -0,0 +1,16 @@
+@tool
+extends EditorPlugin
+
+
+func _enter_tree():
+ # Initialization of the plugin goes here.
+ # Add the new type with a name, a parent type, a script and an icon.
+ add_custom_type("Sync", "Node", preload("sync.gd"), preload("icon.png"))
+ #add_custom_type("RaycastSensor2D2", "Node", preload("raycast_sensor_2d.gd"), preload("icon.png"))
+
+
+func _exit_tree():
+ # Clean-up of the plugin goes here.
+ # Always remember to remove it from the engine when deactivated.
+ remove_custom_type("Sync")
+ #remove_custom_type("RaycastSensor2D2")
diff --git a/SimpleReachGoal/CSharp/addons/godot_rl_agents/icon.png b/SimpleReachGoal/CSharp/addons/godot_rl_agents/icon.png
new file mode 100644
index 0000000000000000000000000000000000000000..ccb4ca000e3e1cf659fe367ab5bff67c1eb3467d
--- /dev/null
+++ b/SimpleReachGoal/CSharp/addons/godot_rl_agents/icon.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:e3a8bc372d3313ce1ede4e7554472e37b322178b9488bfb709e296585abd3c44
+size 198
diff --git a/SimpleReachGoal/CSharp/addons/godot_rl_agents/onnx/csharp/ONNXInference.cs b/SimpleReachGoal/CSharp/addons/godot_rl_agents/onnx/csharp/ONNXInference.cs
new file mode 100644
index 0000000000000000000000000000000000000000..d2c6364a90eeac1ec8c6633d01029bffd352958e
--- /dev/null
+++ b/SimpleReachGoal/CSharp/addons/godot_rl_agents/onnx/csharp/ONNXInference.cs
@@ -0,0 +1,103 @@
+using Godot;
+using Microsoft.ML.OnnxRuntime;
+using Microsoft.ML.OnnxRuntime.Tensors;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace GodotONNX
+{
+ ///
+ public partial class ONNXInference : GodotObject
+ {
+
+ private InferenceSession session;
+ ///
+ /// Path to the ONNX model. Use Initialize to change it.
+ ///
+ private string modelPath;
+ private int batchSize;
+
+ private SessionOptions SessionOpt;
+
+ //init function
+ ///
+ public void Initialize(string Path, int BatchSize)
+ {
+ modelPath = Path;
+ batchSize = BatchSize;
+ SessionOpt = SessionConfigurator.MakeConfiguredSessionOptions();
+ session = LoadModel(modelPath);
+
+ }
+ ///
+ public Godot.Collections.Dictionary> RunInference(Godot.Collections.Array obs, int state_ins)
+ {
+ //Current model: Any (Godot Rl Agents)
+ //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
+
+ //Fill the input tensors
+ // create span from inputSize
+ var span = new float[obs.Count]; //There's probably a better way to do this
+ for (int i = 0; i < obs.Count; i++)
+ {
+ span[i] = obs[i];
+ }
+
+ IReadOnlyCollection inputs = new List
+ {
+ NamedOnnxValue.CreateFromTensor("obs", new DenseTensor(span, new int[] { batchSize, obs.Count })),
+ NamedOnnxValue.CreateFromTensor("state_ins", new DenseTensor(new float[] { state_ins }, new int[] { batchSize }))
+ };
+ IReadOnlyCollection outputNames = new List { "output", "state_outs" }; //ONNX is sensible to these names, as well as the input names
+
+ IDisposableReadOnlyCollection results;
+ //We do not use "using" here so we get a better exception explaination later
+ try
+ {
+ results = session.Run(inputs, outputNames);
+ }
+ catch (OnnxRuntimeException e)
+ {
+ //This error usually means that the model is not compatible with the input, beacause of the input shape (size)
+ GD.Print("Error at inference: ", e);
+ return null;
+ }
+ //Can't convert IEnumerable to Variant, so we have to convert it to an array or something
+ Godot.Collections.Dictionary> output = new Godot.Collections.Dictionary>();
+ DisposableNamedOnnxValue output1 = results.First();
+ DisposableNamedOnnxValue output2 = results.Last();
+ Godot.Collections.Array output1Array = new Godot.Collections.Array();
+ Godot.Collections.Array output2Array = new Godot.Collections.Array();
+
+ foreach (float f in output1.AsEnumerable())
+ {
+ output1Array.Add(f);
+ }
+
+ foreach (float f in output2.AsEnumerable())
+ {
+ output2Array.Add(f);
+ }
+
+ output.Add(output1.Name, output1Array);
+ output.Add(output2.Name, output2Array);
+
+ //Output is a dictionary of arrays, ex: { "output" : [0.1, 0.2, 0.3, 0.4, ...], "state_outs" : [0.5, ...]}
+ results.Dispose();
+ return output;
+ }
+ ///
+ public InferenceSession LoadModel(string Path)
+ {
+ using Godot.FileAccess file = FileAccess.Open(Path, Godot.FileAccess.ModeFlags.Read);
+ byte[] model = file.GetBuffer((int)file.GetLength());
+ //file.Close(); file.Dispose(); //Close the file, then dispose the reference.
+ return new InferenceSession(model, SessionOpt); //Load the model
+ }
+ public void FreeDisposables()
+ {
+ session.Dispose();
+ SessionOpt.Dispose();
+ }
+ }
+}
diff --git a/SimpleReachGoal/CSharp/addons/godot_rl_agents/onnx/csharp/SessionConfigurator.cs b/SimpleReachGoal/CSharp/addons/godot_rl_agents/onnx/csharp/SessionConfigurator.cs
new file mode 100644
index 0000000000000000000000000000000000000000..3f77d784b8e875e6884e097b8a9a87d888f252cf
--- /dev/null
+++ b/SimpleReachGoal/CSharp/addons/godot_rl_agents/onnx/csharp/SessionConfigurator.cs
@@ -0,0 +1,131 @@
+using Godot;
+using Microsoft.ML.OnnxRuntime;
+
+namespace GodotONNX
+{
+ ///
+
+ public static class SessionConfigurator
+ {
+ public enum ComputeName
+ {
+ CUDA,
+ ROCm,
+ DirectML,
+ CoreML,
+ CPU
+ }
+
+ ///
+ public static SessionOptions MakeConfiguredSessionOptions()
+ {
+ SessionOptions sessionOptions = new();
+ SetOptions(sessionOptions);
+ return sessionOptions;
+ }
+
+ private static void SetOptions(SessionOptions sessionOptions)
+ {
+ sessionOptions.LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_WARNING;
+ ApplySystemSpecificOptions(sessionOptions);
+ }
+
+ ///
+ static public void ApplySystemSpecificOptions(SessionOptions sessionOptions)
+ {
+ //Most code for this function is verbose only, the only reason it exists is to track
+ //implementation progress of the different compute APIs.
+
+ //December 2022: CUDA is not working.
+
+ string OSName = OS.GetName(); //Get OS Name
+
+ //ComputeName ComputeAPI = ComputeCheck(); //Get Compute API
+ // //TODO: Get CPU architecture
+
+ //Linux can use OpenVINO (C#) on x64 and ROCm on x86 (GDNative/C++)
+ //Windows can use OpenVINO (C#) on x64
+ //TODO: try TensorRT instead of CUDA
+ //TODO: Use OpenVINO for Intel Graphics
+
+ // Temporarily using CPU on all platforms to avoid errors detected with DML
+ ComputeName ComputeAPI = ComputeName.CPU;
+
+ //match OS and Compute API
+ GD.Print($"OS: {OSName} Compute API: {ComputeAPI}");
+
+ // CPU is set by default without appending necessary
+ // sessionOptions.AppendExecutionProvider_CPU(0);
+
+ /*
+ switch (OSName)
+ {
+ case "Windows": //Can use CUDA, DirectML
+ if (ComputeAPI is ComputeName.CUDA)
+ {
+ //CUDA
+ //sessionOptions.AppendExecutionProvider_CUDA(0);
+ //sessionOptions.AppendExecutionProvider_DML(0);
+ }
+ else if (ComputeAPI is ComputeName.DirectML)
+ {
+ //DirectML
+ //sessionOptions.AppendExecutionProvider_DML(0);
+ }
+ break;
+ case "X11": //Can use CUDA, ROCm
+ if (ComputeAPI is ComputeName.CUDA)
+ {
+ //CUDA
+ //sessionOptions.AppendExecutionProvider_CUDA(0);
+ }
+ if (ComputeAPI is ComputeName.ROCm)
+ {
+ //ROCm, only works on x86
+ //Research indicates that this has to be compiled as a GDNative plugin
+ //GD.Print("ROCm not supported yet, using CPU.");
+ //sessionOptions.AppendExecutionProvider_CPU(0);
+ }
+ break;
+ case "macOS": //Can use CoreML
+ if (ComputeAPI is ComputeName.CoreML)
+ { //CoreML
+ //TODO: Needs testing
+ //sessionOptions.AppendExecutionProvider_CoreML(0);
+ //CoreML on ARM64, out of the box, on x64 needs .tar file from GitHub
+ }
+ break;
+ default:
+ GD.Print("OS not Supported.");
+ break;
+ }
+ */
+ }
+
+
+ ///
+ public static ComputeName ComputeCheck()
+ {
+ string adapterName = Godot.RenderingServer.GetVideoAdapterName();
+ //string adapterVendor = Godot.RenderingServer.GetVideoAdapterVendor();
+ adapterName = adapterName.ToUpper(new System.Globalization.CultureInfo(""));
+ //TODO: GPU vendors for MacOS, what do they even use these days?
+
+ if (adapterName.Contains("INTEL"))
+ {
+ return ComputeName.DirectML;
+ }
+ if (adapterName.Contains("AMD") || adapterName.Contains("RADEON"))
+ {
+ return ComputeName.DirectML;
+ }
+ if (adapterName.Contains("NVIDIA"))
+ {
+ return ComputeName.CUDA;
+ }
+
+ GD.Print("Graphics Card not recognized."); //Should use CPU
+ return ComputeName.CPU;
+ }
+ }
+}
diff --git a/SimpleReachGoal/CSharp/addons/godot_rl_agents/onnx/csharp/docs/ONNXInference.xml b/SimpleReachGoal/CSharp/addons/godot_rl_agents/onnx/csharp/docs/ONNXInference.xml
new file mode 100644
index 0000000000000000000000000000000000000000..91b07d607dc89f11e957e13758d8c0ee4fb72be8
--- /dev/null
+++ b/SimpleReachGoal/CSharp/addons/godot_rl_agents/onnx/csharp/docs/ONNXInference.xml
@@ -0,0 +1,31 @@
+
+
+
+
+ The main ONNXInference Class that handles the inference process.
+
+
+
+
+ Starts the inference process.
+
+ Path to the ONNX model, expects a path inside resources.
+ How many observations will the model recieve.
+
+
+
+ Runs the given input through the model and returns the output.
+
+ Dictionary containing all observations.
+ How many different agents are creating these observations.
+ A Dictionary of arrays, containing instructions based on the observations.
+
+
+
+ Loads the given model into the inference process, using the best Execution provider available.
+
+ Path to the ONNX model, expects a path inside resources.
+ InferenceSession ready to run.
+
+
+
\ No newline at end of file
diff --git a/SimpleReachGoal/CSharp/addons/godot_rl_agents/onnx/csharp/docs/SessionConfigurator.xml b/SimpleReachGoal/CSharp/addons/godot_rl_agents/onnx/csharp/docs/SessionConfigurator.xml
new file mode 100644
index 0000000000000000000000000000000000000000..f160c02f0d4cab92e10f799b6f4c5a71d4d6c0f2
--- /dev/null
+++ b/SimpleReachGoal/CSharp/addons/godot_rl_agents/onnx/csharp/docs/SessionConfigurator.xml
@@ -0,0 +1,29 @@
+
+
+
+
+ The main SessionConfigurator Class that handles the execution options and providers for the inference process.
+
+
+
+
+ Creates a SessionOptions with all available execution providers.
+
+ SessionOptions with all available execution providers.
+
+
+
+ Appends any execution provider available in the current system.
+
+
+ This function is mainly verbose for tracking implementation progress of different compute APIs.
+
+
+
+
+ Checks for available GPUs.
+
+ An integer identifier for each compute platform.
+
+
+
\ No newline at end of file
diff --git a/SimpleReachGoal/CSharp/addons/godot_rl_agents/onnx/wrapper/ONNX_wrapper.gd b/SimpleReachGoal/CSharp/addons/godot_rl_agents/onnx/wrapper/ONNX_wrapper.gd
new file mode 100644
index 0000000000000000000000000000000000000000..d573582b995a2b8fe05553f7cf58fb2e3b58d482
--- /dev/null
+++ b/SimpleReachGoal/CSharp/addons/godot_rl_agents/onnx/wrapper/ONNX_wrapper.gd
@@ -0,0 +1,27 @@
+extends Resource
+class_name ONNXModel
+var inferencer_script = load("res://addons/godot_rl_agents/onnx/csharp/ONNXInference.cs")
+
+var inferencer = null
+
+
+# Must provide the path to the model and the batch size
+func _init(model_path, batch_size):
+ inferencer = inferencer_script.new()
+ inferencer.Initialize(model_path, batch_size)
+
+
+# This function is the one that will be called from the game,
+# requires the observation as an array and the state_ins as an int
+# returns an Array containing the action the model takes.
+func run_inference(obs: Array, state_ins: int) -> Dictionary:
+ if inferencer == null:
+ printerr("Inferencer not initialized")
+ return {}
+ return inferencer.RunInference(obs, state_ins)
+
+
+func _notification(what):
+ if what == NOTIFICATION_PREDELETE:
+ inferencer.FreeDisposables()
+ inferencer.free()
diff --git a/SimpleReachGoal/CSharp/addons/godot_rl_agents/plugin.cfg b/SimpleReachGoal/CSharp/addons/godot_rl_agents/plugin.cfg
new file mode 100644
index 0000000000000000000000000000000000000000..b1bc988c80e3fe68e6d4279691fd5892e5ef323d
--- /dev/null
+++ b/SimpleReachGoal/CSharp/addons/godot_rl_agents/plugin.cfg
@@ -0,0 +1,7 @@
+[plugin]
+
+name="GodotRLAgents"
+description="Custom nodes for the godot rl agents toolkit "
+author="Edward Beeching"
+version="0.1"
+script="godot_rl_agents.gd"
diff --git a/SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_2d/ExampleRaycastSensor2D.tscn b/SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_2d/ExampleRaycastSensor2D.tscn
new file mode 100644
index 0000000000000000000000000000000000000000..5edb6c7fc9da56e625d57185bdbafdbcc3fc67c5
--- /dev/null
+++ b/SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_2d/ExampleRaycastSensor2D.tscn
@@ -0,0 +1,48 @@
+[gd_scene load_steps=5 format=3 uid="uid://ddeq7mn1ealyc"]
+
+[ext_resource type="Script" path="res://addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.gd" id="1"]
+
+[sub_resource type="GDScript" id="2"]
+script/source = "extends Node2D
+
+
+
+func _physics_process(delta: float) -> void:
+ print(\"step start\")
+
+"
+
+[sub_resource type="GDScript" id="1"]
+script/source = "extends RayCast2D
+
+var steps = 1
+
+func _physics_process(delta: float) -> void:
+ print(\"processing raycast\")
+ steps += 1
+ if steps % 2:
+ force_raycast_update()
+
+ print(is_colliding())
+"
+
+[sub_resource type="CircleShape2D" id="3"]
+
+[node name="ExampleRaycastSensor2D" type="Node2D"]
+script = SubResource("2")
+
+[node name="ExampleAgent" type="Node2D" parent="."]
+position = Vector2(573, 314)
+rotation = 0.286234
+
+[node name="RaycastSensor2D" type="Node2D" parent="ExampleAgent"]
+script = ExtResource("1")
+
+[node name="TestRayCast2D" type="RayCast2D" parent="."]
+script = SubResource("1")
+
+[node name="StaticBody2D" type="StaticBody2D" parent="."]
+position = Vector2(1, 52)
+
+[node name="CollisionShape2D" type="CollisionShape2D" parent="StaticBody2D"]
+shape = SubResource("3")
diff --git a/SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_2d/GridSensor2D.gd b/SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_2d/GridSensor2D.gd
new file mode 100644
index 0000000000000000000000000000000000000000..da170ba93919a8f28510ea8fc1ab876fe5876d34
--- /dev/null
+++ b/SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_2d/GridSensor2D.gd
@@ -0,0 +1,235 @@
+@tool
+extends ISensor2D
+class_name GridSensor2D
+
+@export var debug_view := false:
+ get:
+ return debug_view
+ set(value):
+ debug_view = value
+ _update()
+
+@export_flags_2d_physics var detection_mask := 0:
+ get:
+ return detection_mask
+ set(value):
+ detection_mask = value
+ _update()
+
+@export var collide_with_areas := false:
+ get:
+ return collide_with_areas
+ set(value):
+ collide_with_areas = value
+ _update()
+
+@export var collide_with_bodies := true:
+ get:
+ return collide_with_bodies
+ set(value):
+ collide_with_bodies = value
+ _update()
+
+@export_range(1, 200, 0.1) var cell_width := 20.0:
+ get:
+ return cell_width
+ set(value):
+ cell_width = value
+ _update()
+
+@export_range(1, 200, 0.1) var cell_height := 20.0:
+ get:
+ return cell_height
+ set(value):
+ cell_height = value
+ _update()
+
+@export_range(1, 21, 2, "or_greater") var grid_size_x := 3:
+ get:
+ return grid_size_x
+ set(value):
+ grid_size_x = value
+ _update()
+
+@export_range(1, 21, 2, "or_greater") var grid_size_y := 3:
+ get:
+ return grid_size_y
+ set(value):
+ grid_size_y = value
+ _update()
+
+var _obs_buffer: PackedFloat64Array
+var _rectangle_shape: RectangleShape2D
+var _collision_mapping: Dictionary
+var _n_layers_per_cell: int
+
+var _highlighted_cell_color: Color
+var _standard_cell_color: Color
+
+
+func get_observation():
+ return _obs_buffer
+
+
+func _update():
+ if Engine.is_editor_hint():
+ if is_node_ready():
+ _spawn_nodes()
+
+
+func _ready() -> void:
+ _set_colors()
+
+ if Engine.is_editor_hint():
+ if get_child_count() == 0:
+ _spawn_nodes()
+ else:
+ _spawn_nodes()
+
+
+func _set_colors() -> void:
+ _standard_cell_color = Color(100.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0)
+ _highlighted_cell_color = Color(255.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0)
+
+
+func _get_collision_mapping() -> Dictionary:
+ # defines which layer is mapped to which cell obs index
+ var total_bits = 0
+ var collision_mapping = {}
+ for i in 32:
+ var bit_mask = 2 ** i
+ if (detection_mask & bit_mask) > 0:
+ collision_mapping[i] = total_bits
+ total_bits += 1
+
+ return collision_mapping
+
+
+func _spawn_nodes():
+ for cell in get_children():
+ cell.name = "_%s" % cell.name # Otherwise naming below will fail
+ cell.queue_free()
+
+ _collision_mapping = _get_collision_mapping()
+ #prints("collision_mapping", _collision_mapping, len(_collision_mapping))
+ # allocate memory for the observations
+ _n_layers_per_cell = len(_collision_mapping)
+ _obs_buffer = PackedFloat64Array()
+ _obs_buffer.resize(grid_size_x * grid_size_y * _n_layers_per_cell)
+ _obs_buffer.fill(0)
+ #prints(len(_obs_buffer), _obs_buffer )
+
+ _rectangle_shape = RectangleShape2D.new()
+ _rectangle_shape.set_size(Vector2(cell_width, cell_height))
+
+ var shift := Vector2(
+ -(grid_size_x / 2) * cell_width,
+ -(grid_size_y / 2) * cell_height,
+ )
+
+ for i in grid_size_x:
+ for j in grid_size_y:
+ var cell_position = Vector2(i * cell_width, j * cell_height) + shift
+ _create_cell(i, j, cell_position)
+
+
+func _create_cell(i: int, j: int, position: Vector2):
+ var cell := Area2D.new()
+ cell.position = position
+ cell.name = "GridCell %s %s" % [i, j]
+ cell.modulate = _standard_cell_color
+
+ if collide_with_areas:
+ cell.area_entered.connect(_on_cell_area_entered.bind(i, j))
+ cell.area_exited.connect(_on_cell_area_exited.bind(i, j))
+
+ if collide_with_bodies:
+ cell.body_entered.connect(_on_cell_body_entered.bind(i, j))
+ cell.body_exited.connect(_on_cell_body_exited.bind(i, j))
+
+ cell.collision_layer = 0
+ cell.collision_mask = detection_mask
+ cell.monitorable = true
+ add_child(cell)
+ cell.set_owner(get_tree().edited_scene_root)
+
+ var col_shape := CollisionShape2D.new()
+ col_shape.shape = _rectangle_shape
+ col_shape.name = "CollisionShape2D"
+ cell.add_child(col_shape)
+ col_shape.set_owner(get_tree().edited_scene_root)
+
+ if debug_view:
+ var quad = MeshInstance2D.new()
+ quad.name = "MeshInstance2D"
+ var quad_mesh = QuadMesh.new()
+
+ quad_mesh.set_size(Vector2(cell_width, cell_height))
+
+ quad.mesh = quad_mesh
+ cell.add_child(quad)
+ quad.set_owner(get_tree().edited_scene_root)
+
+
+func _update_obs(cell_i: int, cell_j: int, collision_layer: int, entered: bool):
+ for key in _collision_mapping:
+ var bit_mask = 2 ** key
+ if (collision_layer & bit_mask) > 0:
+ var collison_map_index = _collision_mapping[key]
+
+ var obs_index = (
+ (cell_i * grid_size_x * _n_layers_per_cell)
+ + (cell_j * _n_layers_per_cell)
+ + collison_map_index
+ )
+ #prints(obs_index, cell_i, cell_j)
+ if entered:
+ _obs_buffer[obs_index] += 1
+ else:
+ _obs_buffer[obs_index] -= 1
+
+
+func _toggle_cell(cell_i: int, cell_j: int):
+ var cell = get_node_or_null("GridCell %s %s" % [cell_i, cell_j])
+
+ if cell == null:
+ print("cell not found, returning")
+
+ var n_hits = 0
+ var start_index = (cell_i * grid_size_x * _n_layers_per_cell) + (cell_j * _n_layers_per_cell)
+ for i in _n_layers_per_cell:
+ n_hits += _obs_buffer[start_index + i]
+
+ if n_hits > 0:
+ cell.modulate = _highlighted_cell_color
+ else:
+ cell.modulate = _standard_cell_color
+
+
+func _on_cell_area_entered(area: Area2D, cell_i: int, cell_j: int):
+ #prints("_on_cell_area_entered", cell_i, cell_j)
+ _update_obs(cell_i, cell_j, area.collision_layer, true)
+ if debug_view:
+ _toggle_cell(cell_i, cell_j)
+ #print(_obs_buffer)
+
+
+func _on_cell_area_exited(area: Area2D, cell_i: int, cell_j: int):
+ #prints("_on_cell_area_exited", cell_i, cell_j)
+ _update_obs(cell_i, cell_j, area.collision_layer, false)
+ if debug_view:
+ _toggle_cell(cell_i, cell_j)
+
+
+func _on_cell_body_entered(body: Node2D, cell_i: int, cell_j: int):
+ #prints("_on_cell_body_entered", cell_i, cell_j)
+ _update_obs(cell_i, cell_j, body.collision_layer, true)
+ if debug_view:
+ _toggle_cell(cell_i, cell_j)
+
+
+func _on_cell_body_exited(body: Node2D, cell_i: int, cell_j: int):
+ #prints("_on_cell_body_exited", cell_i, cell_j)
+ _update_obs(cell_i, cell_j, body.collision_layer, false)
+ if debug_view:
+ _toggle_cell(cell_i, cell_j)
diff --git a/SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_2d/ISensor2D.gd b/SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_2d/ISensor2D.gd
new file mode 100644
index 0000000000000000000000000000000000000000..67669a1d71a3e37d780b396633951d7d1ac79edb
--- /dev/null
+++ b/SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_2d/ISensor2D.gd
@@ -0,0 +1,25 @@
+extends Node2D
+class_name ISensor2D
+
+var _obs: Array = []
+var _active := false
+
+
+func get_observation():
+ pass
+
+
+func activate():
+ _active = true
+
+
+func deactivate():
+ _active = false
+
+
+func _update_observation():
+ pass
+
+
+func reset():
+ pass
diff --git a/SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.gd b/SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.gd
new file mode 100644
index 0000000000000000000000000000000000000000..9bb54ede90a6f6ffd5e65d89bf1bd561bc0832ed
--- /dev/null
+++ b/SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.gd
@@ -0,0 +1,118 @@
+@tool
+extends ISensor2D
+class_name RaycastSensor2D
+
+@export_flags_2d_physics var collision_mask := 1:
+ get:
+ return collision_mask
+ set(value):
+ collision_mask = value
+ _update()
+
+@export var collide_with_areas := false:
+ get:
+ return collide_with_areas
+ set(value):
+ collide_with_areas = value
+ _update()
+
+@export var collide_with_bodies := true:
+ get:
+ return collide_with_bodies
+ set(value):
+ collide_with_bodies = value
+ _update()
+
+@export var n_rays := 16.0:
+ get:
+ return n_rays
+ set(value):
+ n_rays = value
+ _update()
+
+@export_range(5, 3000, 5.0) var ray_length := 200:
+ get:
+ return ray_length
+ set(value):
+ ray_length = value
+ _update()
+@export_range(5, 360, 5.0) var cone_width := 360.0:
+ get:
+ return cone_width
+ set(value):
+ cone_width = value
+ _update()
+
+@export var debug_draw := true:
+ get:
+ return debug_draw
+ set(value):
+ debug_draw = value
+ _update()
+
+var _angles = []
+var rays := []
+
+
+func _update():
+ if Engine.is_editor_hint():
+ if debug_draw:
+ _spawn_nodes()
+ else:
+ for ray in get_children():
+ if ray is RayCast2D:
+ remove_child(ray)
+
+
+func _ready() -> void:
+ _spawn_nodes()
+
+
+func _spawn_nodes():
+ for ray in rays:
+ ray.queue_free()
+ rays = []
+
+ _angles = []
+ var step = cone_width / (n_rays)
+ var start = step / 2 - cone_width / 2
+
+ for i in n_rays:
+ var angle = start + i * step
+ var ray = RayCast2D.new()
+ ray.set_target_position(
+ Vector2(ray_length * cos(deg_to_rad(angle)), ray_length * sin(deg_to_rad(angle)))
+ )
+ ray.set_name("node_" + str(i))
+ ray.enabled = false
+ ray.collide_with_areas = collide_with_areas
+ ray.collide_with_bodies = collide_with_bodies
+ ray.collision_mask = collision_mask
+ add_child(ray)
+ rays.append(ray)
+
+ _angles.append(start + i * step)
+
+
+func get_observation() -> Array:
+ return self.calculate_raycasts()
+
+
+func calculate_raycasts() -> Array:
+ var result = []
+ for ray in rays:
+ ray.enabled = true
+ ray.force_raycast_update()
+ var distance = _get_raycast_distance(ray)
+ result.append(distance)
+ ray.enabled = false
+ return result
+
+
+func _get_raycast_distance(ray: RayCast2D) -> float:
+ if !ray.is_colliding():
+ return 0.0
+
+ var distance = (global_position - ray.get_collision_point()).length()
+ distance = clamp(distance, 0.0, ray_length)
+ return (ray_length - distance) / ray_length
diff --git a/SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.tscn b/SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.tscn
new file mode 100644
index 0000000000000000000000000000000000000000..5ca402c08305efedbfc6afd0a1893a0ca2e11cfd
--- /dev/null
+++ b/SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.tscn
@@ -0,0 +1,7 @@
+[gd_scene load_steps=2 format=3 uid="uid://drvfihk5esgmv"]
+
+[ext_resource type="Script" path="res://addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.gd" id="1"]
+
+[node name="RaycastSensor2D" type="Node2D"]
+script = ExtResource("1")
+n_rays = 17.0
diff --git a/SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_3d/ExampleRaycastSensor3D.tscn b/SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_3d/ExampleRaycastSensor3D.tscn
new file mode 100644
index 0000000000000000000000000000000000000000..a8057c7619cbb835709d2704074b0d5ebfa00a0c
--- /dev/null
+++ b/SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_3d/ExampleRaycastSensor3D.tscn
@@ -0,0 +1,6 @@
+[gd_scene format=3 uid="uid://biu787qh4woik"]
+
+[node name="ExampleRaycastSensor3D" type="Node3D"]
+
+[node name="Camera3D" type="Camera3D" parent="."]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0.804183, 0, 2.70146)
diff --git a/SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_3d/GridSensor3D.gd b/SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_3d/GridSensor3D.gd
new file mode 100644
index 0000000000000000000000000000000000000000..03593cc04d74ce0d0f16a4518e59b9309a09a5a7
--- /dev/null
+++ b/SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_3d/GridSensor3D.gd
@@ -0,0 +1,258 @@
+@tool
+extends ISensor3D
+class_name GridSensor3D
+
+@export var debug_view := false:
+ get:
+ return debug_view
+ set(value):
+ debug_view = value
+ _update()
+
+@export_flags_3d_physics var detection_mask := 0:
+ get:
+ return detection_mask
+ set(value):
+ detection_mask = value
+ _update()
+
+@export var collide_with_areas := false:
+ get:
+ return collide_with_areas
+ set(value):
+ collide_with_areas = value
+ _update()
+
+@export var collide_with_bodies := false:
+ # NOTE! The sensor will not detect StaticBody3D, add an area to static bodies to detect them
+ get:
+ return collide_with_bodies
+ set(value):
+ collide_with_bodies = value
+ _update()
+
+@export_range(0.1, 2, 0.1) var cell_width := 1.0:
+ get:
+ return cell_width
+ set(value):
+ cell_width = value
+ _update()
+
+@export_range(0.1, 2, 0.1) var cell_height := 1.0:
+ get:
+ return cell_height
+ set(value):
+ cell_height = value
+ _update()
+
+@export_range(1, 21, 2, "or_greater") var grid_size_x := 3:
+ get:
+ return grid_size_x
+ set(value):
+ grid_size_x = value
+ _update()
+
+@export_range(1, 21, 2, "or_greater") var grid_size_z := 3:
+ get:
+ return grid_size_z
+ set(value):
+ grid_size_z = value
+ _update()
+
+var _obs_buffer: PackedFloat64Array
+var _box_shape: BoxShape3D
+var _collision_mapping: Dictionary
+var _n_layers_per_cell: int
+
+var _highlighted_box_material: StandardMaterial3D
+var _standard_box_material: StandardMaterial3D
+
+
+func get_observation():
+ return _obs_buffer
+
+
+func reset():
+ _obs_buffer.fill(0)
+
+
+func _update():
+ if Engine.is_editor_hint():
+ if is_node_ready():
+ _spawn_nodes()
+
+
+func _ready() -> void:
+ _make_materials()
+
+ if Engine.is_editor_hint():
+ if get_child_count() == 0:
+ _spawn_nodes()
+ else:
+ _spawn_nodes()
+
+
+func _make_materials() -> void:
+ if _highlighted_box_material != null and _standard_box_material != null:
+ return
+
+ _standard_box_material = StandardMaterial3D.new()
+ _standard_box_material.set_transparency(1) # ALPHA
+ _standard_box_material.albedo_color = Color(
+ 100.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0
+ )
+
+ _highlighted_box_material = StandardMaterial3D.new()
+ _highlighted_box_material.set_transparency(1) # ALPHA
+ _highlighted_box_material.albedo_color = Color(
+ 255.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0
+ )
+
+
+func _get_collision_mapping() -> Dictionary:
+ # defines which layer is mapped to which cell obs index
+ var total_bits = 0
+ var collision_mapping = {}
+ for i in 32:
+ var bit_mask = 2 ** i
+ if (detection_mask & bit_mask) > 0:
+ collision_mapping[i] = total_bits
+ total_bits += 1
+
+ return collision_mapping
+
+
+func _spawn_nodes():
+ for cell in get_children():
+ cell.name = "_%s" % cell.name # Otherwise naming below will fail
+ cell.queue_free()
+
+ _collision_mapping = _get_collision_mapping()
+ #prints("collision_mapping", _collision_mapping, len(_collision_mapping))
+ # allocate memory for the observations
+ _n_layers_per_cell = len(_collision_mapping)
+ _obs_buffer = PackedFloat64Array()
+ _obs_buffer.resize(grid_size_x * grid_size_z * _n_layers_per_cell)
+ _obs_buffer.fill(0)
+ #prints(len(_obs_buffer), _obs_buffer )
+
+ _box_shape = BoxShape3D.new()
+ _box_shape.set_size(Vector3(cell_width, cell_height, cell_width))
+
+ var shift := Vector3(
+ -(grid_size_x / 2) * cell_width,
+ 0,
+ -(grid_size_z / 2) * cell_width,
+ )
+
+ for i in grid_size_x:
+ for j in grid_size_z:
+ var cell_position = Vector3(i * cell_width, 0.0, j * cell_width) + shift
+ _create_cell(i, j, cell_position)
+
+
+func _create_cell(i: int, j: int, position: Vector3):
+ var cell := Area3D.new()
+ cell.position = position
+ cell.name = "GridCell %s %s" % [i, j]
+
+ if collide_with_areas:
+ cell.area_entered.connect(_on_cell_area_entered.bind(i, j))
+ cell.area_exited.connect(_on_cell_area_exited.bind(i, j))
+
+ if collide_with_bodies:
+ cell.body_entered.connect(_on_cell_body_entered.bind(i, j))
+ cell.body_exited.connect(_on_cell_body_exited.bind(i, j))
+
+# cell.body_shape_entered.connect(_on_cell_body_shape_entered.bind(i, j))
+# cell.body_shape_exited.connect(_on_cell_body_shape_exited.bind(i, j))
+
+ cell.collision_layer = 0
+ cell.collision_mask = detection_mask
+ cell.monitorable = true
+ cell.input_ray_pickable = false
+ add_child(cell)
+ cell.set_owner(get_tree().edited_scene_root)
+
+ var col_shape := CollisionShape3D.new()
+ col_shape.shape = _box_shape
+ col_shape.name = "CollisionShape3D"
+ cell.add_child(col_shape)
+ col_shape.set_owner(get_tree().edited_scene_root)
+
+ if debug_view:
+ var box = MeshInstance3D.new()
+ box.name = "MeshInstance3D"
+ var box_mesh = BoxMesh.new()
+
+ box_mesh.set_size(Vector3(cell_width, cell_height, cell_width))
+ box_mesh.material = _standard_box_material
+
+ box.mesh = box_mesh
+ cell.add_child(box)
+ box.set_owner(get_tree().edited_scene_root)
+
+
+func _update_obs(cell_i: int, cell_j: int, collision_layer: int, entered: bool):
+ for key in _collision_mapping:
+ var bit_mask = 2 ** key
+ if (collision_layer & bit_mask) > 0:
+ var collison_map_index = _collision_mapping[key]
+
+ var obs_index = (
+ (cell_i * grid_size_x * _n_layers_per_cell)
+ + (cell_j * _n_layers_per_cell)
+ + collison_map_index
+ )
+ #prints(obs_index, cell_i, cell_j)
+ if entered:
+ _obs_buffer[obs_index] += 1
+ else:
+ _obs_buffer[obs_index] -= 1
+
+
+func _toggle_cell(cell_i: int, cell_j: int):
+ var cell = get_node_or_null("GridCell %s %s" % [cell_i, cell_j])
+
+ if cell == null:
+ print("cell not found, returning")
+
+ var n_hits = 0
+ var start_index = (cell_i * grid_size_x * _n_layers_per_cell) + (cell_j * _n_layers_per_cell)
+ for i in _n_layers_per_cell:
+ n_hits += _obs_buffer[start_index + i]
+
+ var cell_mesh = cell.get_node_or_null("MeshInstance3D")
+ if n_hits > 0:
+ cell_mesh.mesh.material = _highlighted_box_material
+ else:
+ cell_mesh.mesh.material = _standard_box_material
+
+
+func _on_cell_area_entered(area: Area3D, cell_i: int, cell_j: int):
+ #prints("_on_cell_area_entered", cell_i, cell_j)
+ _update_obs(cell_i, cell_j, area.collision_layer, true)
+ if debug_view:
+ _toggle_cell(cell_i, cell_j)
+ #print(_obs_buffer)
+
+
+func _on_cell_area_exited(area: Area3D, cell_i: int, cell_j: int):
+ #prints("_on_cell_area_exited", cell_i, cell_j)
+ _update_obs(cell_i, cell_j, area.collision_layer, false)
+ if debug_view:
+ _toggle_cell(cell_i, cell_j)
+
+
+func _on_cell_body_entered(body: Node3D, cell_i: int, cell_j: int):
+ #prints("_on_cell_body_entered", cell_i, cell_j)
+ _update_obs(cell_i, cell_j, body.collision_layer, true)
+ if debug_view:
+ _toggle_cell(cell_i, cell_j)
+
+
+func _on_cell_body_exited(body: Node3D, cell_i: int, cell_j: int):
+ #prints("_on_cell_body_exited", cell_i, cell_j)
+ _update_obs(cell_i, cell_j, body.collision_layer, false)
+ if debug_view:
+ _toggle_cell(cell_i, cell_j)
diff --git a/SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_3d/ISensor3D.gd b/SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_3d/ISensor3D.gd
new file mode 100644
index 0000000000000000000000000000000000000000..aca3c2db480c5f61058d565ae4652916af4c51ad
--- /dev/null
+++ b/SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_3d/ISensor3D.gd
@@ -0,0 +1,25 @@
+extends Node3D
+class_name ISensor3D
+
+var _obs: Array = []
+var _active := false
+
+
+func get_observation():
+ pass
+
+
+func activate():
+ _active = true
+
+
+func deactivate():
+ _active = false
+
+
+func _update_observation():
+ pass
+
+
+func reset():
+ pass
diff --git a/SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.gd b/SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.gd
new file mode 100644
index 0000000000000000000000000000000000000000..1037e970c3dccd26c6b987533115d12fca790549
--- /dev/null
+++ b/SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.gd
@@ -0,0 +1,21 @@
+extends Node3D
+class_name RGBCameraSensor3D
+var camera_pixels = null
+
+@onready var camera_texture := $Control/TextureRect/CameraTexture as Sprite2D
+@onready var sub_viewport := $SubViewport as SubViewport
+
+
+func get_camera_pixel_encoding():
+ return camera_texture.get_texture().get_image().get_data().hex_encode()
+
+
+func get_camera_shape() -> Array:
+ assert(
+ sub_viewport.size.x >= 36 and sub_viewport.size.y >= 36,
+ "SubViewport size must be 36x36 or larger."
+ )
+ if sub_viewport.transparent_bg:
+ return [4, sub_viewport.size.y, sub_viewport.size.x]
+ else:
+ return [3, sub_viewport.size.y, sub_viewport.size.x]
diff --git a/SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.tscn b/SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.tscn
new file mode 100644
index 0000000000000000000000000000000000000000..052b5577db16ab7d25f5f473a539b3099f400db8
--- /dev/null
+++ b/SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.tscn
@@ -0,0 +1,41 @@
+[gd_scene load_steps=3 format=3 uid="uid://baaywi3arsl2m"]
+
+[ext_resource type="Script" path="res://addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.gd" id="1"]
+
+[sub_resource type="ViewportTexture" id="1"]
+viewport_path = NodePath("SubViewport")
+
+[node name="RGBCameraSensor3D" type="Node3D"]
+script = ExtResource("1")
+
+[node name="RemoteTransform3D" type="RemoteTransform3D" parent="."]
+remote_path = NodePath("../SubViewport/Camera3D")
+
+[node name="SubViewport" type="SubViewport" parent="."]
+size = Vector2i(32, 32)
+render_target_update_mode = 3
+
+[node name="Camera3D" type="Camera3D" parent="SubViewport"]
+near = 0.5
+
+[node name="Control" type="Control" parent="."]
+layout_mode = 3
+anchors_preset = 15
+anchor_right = 1.0
+anchor_bottom = 1.0
+grow_horizontal = 2
+grow_vertical = 2
+
+[node name="TextureRect" type="ColorRect" parent="Control"]
+layout_mode = 0
+offset_left = 1096.0
+offset_top = 534.0
+offset_right = 1114.0
+offset_bottom = 552.0
+scale = Vector2(10, 10)
+color = Color(0.00784314, 0.00784314, 0.00784314, 1)
+
+[node name="CameraTexture" type="Sprite2D" parent="Control/TextureRect"]
+texture = SubResource("1")
+offset = Vector2(9, 9)
+flip_v = true
diff --git a/SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd b/SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd
new file mode 100644
index 0000000000000000000000000000000000000000..1357529f9232c3323316212cc84042bde1afb6f2
--- /dev/null
+++ b/SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd
@@ -0,0 +1,185 @@
+@tool
+extends ISensor3D
+class_name RayCastSensor3D
+@export_flags_3d_physics var collision_mask = 1:
+ get:
+ return collision_mask
+ set(value):
+ collision_mask = value
+ _update()
+@export_flags_3d_physics var boolean_class_mask = 1:
+ get:
+ return boolean_class_mask
+ set(value):
+ boolean_class_mask = value
+ _update()
+
+@export var n_rays_width := 6.0:
+ get:
+ return n_rays_width
+ set(value):
+ n_rays_width = value
+ _update()
+
+@export var n_rays_height := 6.0:
+ get:
+ return n_rays_height
+ set(value):
+ n_rays_height = value
+ _update()
+
+@export var ray_length := 10.0:
+ get:
+ return ray_length
+ set(value):
+ ray_length = value
+ _update()
+
+@export var cone_width := 60.0:
+ get:
+ return cone_width
+ set(value):
+ cone_width = value
+ _update()
+
+@export var cone_height := 60.0:
+ get:
+ return cone_height
+ set(value):
+ cone_height = value
+ _update()
+
+@export var collide_with_areas := false:
+ get:
+ return collide_with_areas
+ set(value):
+ collide_with_areas = value
+ _update()
+
+@export var collide_with_bodies := true:
+ get:
+ return collide_with_bodies
+ set(value):
+ collide_with_bodies = value
+ _update()
+
+@export var class_sensor := false
+
+var rays := []
+var geo = null
+
+
+func _update():
+ if Engine.is_editor_hint():
+ if is_node_ready():
+ _spawn_nodes()
+
+
+func _ready() -> void:
+ if Engine.is_editor_hint():
+ if get_child_count() == 0:
+ _spawn_nodes()
+ else:
+ _spawn_nodes()
+
+
+func _spawn_nodes():
+ print("spawning nodes")
+ for ray in get_children():
+ ray.queue_free()
+ if geo:
+ geo.clear()
+ #$Lines.remove_points()
+ rays = []
+
+ var horizontal_step = cone_width / (n_rays_width)
+ var vertical_step = cone_height / (n_rays_height)
+
+ var horizontal_start = horizontal_step / 2 - cone_width / 2
+ var vertical_start = vertical_step / 2 - cone_height / 2
+
+ var points = []
+
+ for i in n_rays_width:
+ for j in n_rays_height:
+ var angle_w = horizontal_start + i * horizontal_step
+ var angle_h = vertical_start + j * vertical_step
+ #angle_h = 0.0
+ var ray = RayCast3D.new()
+ var cast_to = to_spherical_coords(ray_length, angle_w, angle_h)
+ ray.set_target_position(cast_to)
+
+ points.append(cast_to)
+
+ ray.set_name("node_" + str(i) + " " + str(j))
+ ray.enabled = true
+ ray.collide_with_bodies = collide_with_bodies
+ ray.collide_with_areas = collide_with_areas
+ ray.collision_mask = collision_mask
+ add_child(ray)
+ ray.set_owner(get_tree().edited_scene_root)
+ rays.append(ray)
+ ray.force_raycast_update()
+
+
+# if Engine.editor_hint:
+# _create_debug_lines(points)
+
+
+func _create_debug_lines(points):
+ if not geo:
+ geo = ImmediateMesh.new()
+ add_child(geo)
+
+ geo.clear()
+ geo.begin(Mesh.PRIMITIVE_LINES)
+ for point in points:
+ geo.set_color(Color.AQUA)
+ geo.add_vertex(Vector3.ZERO)
+ geo.add_vertex(point)
+ geo.end()
+
+
+func display():
+ if geo:
+ geo.display()
+
+
+func to_spherical_coords(r, inc, azimuth) -> Vector3:
+ return Vector3(
+ r * sin(deg_to_rad(inc)) * cos(deg_to_rad(azimuth)),
+ r * sin(deg_to_rad(azimuth)),
+ r * cos(deg_to_rad(inc)) * cos(deg_to_rad(azimuth))
+ )
+
+
+func get_observation() -> Array:
+ return self.calculate_raycasts()
+
+
+func calculate_raycasts() -> Array:
+ var result = []
+ for ray in rays:
+ ray.set_enabled(true)
+ ray.force_raycast_update()
+ var distance = _get_raycast_distance(ray)
+
+ result.append(distance)
+ if class_sensor:
+ var hit_class: float = 0
+ if ray.get_collider():
+ var hit_collision_layer = ray.get_collider().collision_layer
+ hit_collision_layer = hit_collision_layer & collision_mask
+ hit_class = (hit_collision_layer & boolean_class_mask) > 0
+ result.append(float(hit_class))
+ ray.set_enabled(false)
+ return result
+
+
+func _get_raycast_distance(ray: RayCast3D) -> float:
+ if !ray.is_colliding():
+ return 0.0
+
+ var distance = (global_transform.origin - ray.get_collision_point()).length()
+ distance = clamp(distance, 0.0, ray_length)
+ return (ray_length - distance) / ray_length
diff --git a/SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.tscn b/SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.tscn
new file mode 100644
index 0000000000000000000000000000000000000000..35f9796596b2fb79bfcfe31e3d3a9637d9008e55
--- /dev/null
+++ b/SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.tscn
@@ -0,0 +1,27 @@
+[gd_scene load_steps=2 format=3 uid="uid://b803cbh1fmy66"]
+
+[ext_resource type="Script" path="res://addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd" id="1"]
+
+[node name="RaycastSensor3D" type="Node3D"]
+script = ExtResource("1")
+n_rays_width = 4.0
+n_rays_height = 2.0
+ray_length = 11.0
+
+[node name="node_1 0" type="RayCast3D" parent="."]
+target_position = Vector3(-1.38686, -2.84701, 10.5343)
+
+[node name="node_1 1" type="RayCast3D" parent="."]
+target_position = Vector3(-1.38686, 2.84701, 10.5343)
+
+[node name="node_2 0" type="RayCast3D" parent="."]
+target_position = Vector3(1.38686, -2.84701, 10.5343)
+
+[node name="node_2 1" type="RayCast3D" parent="."]
+target_position = Vector3(1.38686, 2.84701, 10.5343)
+
+[node name="node_3 0" type="RayCast3D" parent="."]
+target_position = Vector3(4.06608, -2.84701, 9.81639)
+
+[node name="node_3 1" type="RayCast3D" parent="."]
+target_position = Vector3(4.06608, 2.84701, 9.81639)
diff --git a/SimpleReachGoal/CSharp/addons/godot_rl_agents/sync.gd b/SimpleReachGoal/CSharp/addons/godot_rl_agents/sync.gd
new file mode 100644
index 0000000000000000000000000000000000000000..340ec2041bed6488e931f504025bdc54cc828d90
--- /dev/null
+++ b/SimpleReachGoal/CSharp/addons/godot_rl_agents/sync.gd
@@ -0,0 +1,548 @@
+extends Node
+
+# --fixed-fps 2000 --disable-render-loop
+
+enum ControlModes { HUMAN, TRAINING, ONNX_INFERENCE }
+@export var control_mode: ControlModes = ControlModes.TRAINING
+@export_range(1, 10, 1, "or_greater") var action_repeat := 8
+@export_range(0, 10, 0.1, "or_greater") var speed_up := 1.0
+@export var onnx_model_path := ""
+
+# Onnx model stored for each requested path
+var onnx_models: Dictionary
+
+@onready var start_time = Time.get_ticks_msec()
+
+const MAJOR_VERSION := "0"
+const MINOR_VERSION := "7"
+const DEFAULT_PORT := "11008"
+const DEFAULT_SEED := "1"
+var stream: StreamPeerTCP = null
+var connected = false
+var message_center
+var should_connect = true
+
+var all_agents: Array
+var agents_training: Array
+var agents_inference: Array
+var agents_heuristic: Array
+
+## For recording expert demos
+var agent_demo_record: Node
+## File path for writing recorded trajectories
+var expert_demo_save_path: String
+## Stores recorded trajectories
+var demo_trajectories: Array
+## A trajectory includes obs: Array, acts: Array, terminal (set in Python env instead)
+var current_demo_trajectory: Array
+
+var need_to_send_obs = false
+var args = null
+var initialized = false
+var just_reset = false
+var onnx_model = null
+var n_action_steps = 0
+
+var _action_space: Dictionary
+var _action_space_inference: Array[Dictionary] = []
+var _obs_space: Dictionary
+
+
+# Called when the node enters the scene tree for the first time.
+func _ready():
+ await get_tree().root.ready
+ get_tree().set_pause(true)
+ _initialize()
+ await get_tree().create_timer(1.0).timeout
+ get_tree().set_pause(false)
+
+
+func _initialize():
+ _get_agents()
+ args = _get_args()
+ Engine.physics_ticks_per_second = _get_speedup() * 60 # Replace with function body.
+ Engine.time_scale = _get_speedup() * 1.0
+ prints(
+ "physics ticks",
+ Engine.physics_ticks_per_second,
+ Engine.time_scale,
+ _get_speedup(),
+ speed_up
+ )
+
+ _set_heuristic("human", all_agents)
+
+ _initialize_training_agents()
+ _initialize_inference_agents()
+ _initialize_demo_recording()
+
+ _set_seed()
+ _set_action_repeat()
+ initialized = true
+
+
+func _initialize_training_agents():
+ if agents_training.size() > 0:
+ _obs_space = agents_training[0].get_obs_space()
+ _action_space = agents_training[0].get_action_space()
+ connected = connect_to_server()
+ if connected:
+ _set_heuristic("model", agents_training)
+ _handshake()
+ _send_env_info()
+ else:
+ push_warning(
+ "Couldn't connect to Python server, using human controls instead. ",
+ "Did you start the training server using e.g. `gdrl` from the console?"
+ )
+
+
+func _initialize_inference_agents():
+ if agents_inference.size() > 0:
+ if control_mode == ControlModes.ONNX_INFERENCE:
+ assert(
+ FileAccess.file_exists(onnx_model_path),
+ "Onnx Model Path set on Sync node does not exist: %s" % onnx_model_path
+ )
+ onnx_models[onnx_model_path] = ONNXModel.new(onnx_model_path, 1)
+
+ for agent in agents_inference:
+ _action_space_inference.append(agent.get_action_space())
+
+ var agent_onnx_model: ONNXModel
+ if agent.onnx_model_path.is_empty():
+ assert(
+ onnx_models.has(onnx_model_path),
+ (
+ "Node %s has no onnx model path set " % agent.get_path()
+ + "and sync node's control mode is not set to OnnxInference. "
+ + "Either add the path to the AIController, "
+ + "or if you want to use the path set on sync node instead, "
+ + "set control mode to OnnxInference."
+ )
+ )
+ prints(
+ "Info: AIController %s" % agent.get_path(),
+ "has no onnx model path set.",
+ "Using path set on the sync node instead."
+ )
+ agent_onnx_model = onnx_models[onnx_model_path]
+ else:
+ if not onnx_models.has(agent.onnx_model_path):
+ assert(
+ FileAccess.file_exists(agent.onnx_model_path),
+ (
+ "Onnx Model Path set on %s node does not exist: %s"
+ % [agent.get_path(), agent.onnx_model_path]
+ )
+ )
+ onnx_models[agent.onnx_model_path] = ONNXModel.new(agent.onnx_model_path, 1)
+ agent_onnx_model = onnx_models[agent.onnx_model_path]
+
+ agent.onnx_model = agent_onnx_model
+ _set_heuristic("model", agents_inference)
+
+
+func _initialize_demo_recording():
+ if agent_demo_record:
+ expert_demo_save_path = agent_demo_record.expert_demo_save_path
+ assert(
+ not expert_demo_save_path.is_empty(),
+ "Expert demo save path set in %s is empty." % agent_demo_record.get_path()
+ )
+
+ InputMap.add_action("RemoveLastDemoEpisode")
+ InputMap.action_add_event(
+ "RemoveLastDemoEpisode", agent_demo_record.remove_last_episode_key
+ )
+ current_demo_trajectory.resize(2)
+ current_demo_trajectory[0] = []
+ current_demo_trajectory[1] = []
+ agent_demo_record.heuristic = "demo_record"
+
+
+func _physics_process(_delta):
+ # two modes, human control, agent control
+ # pause tree, send obs, get actions, set actions, unpause tree
+
+ _demo_record_process()
+
+ if n_action_steps % action_repeat != 0:
+ n_action_steps += 1
+ return
+
+ n_action_steps += 1
+
+ _training_process()
+ _inference_process()
+ _heuristic_process()
+
+
+func _training_process():
+ if connected:
+ get_tree().set_pause(true)
+
+ if just_reset:
+ just_reset = false
+ var obs = _get_obs_from_agents(agents_training)
+
+ var reply = {"type": "reset", "obs": obs}
+ _send_dict_as_json_message(reply)
+ # this should go straight to getting the action and setting it checked the agent, no need to perform one phyics tick
+ get_tree().set_pause(false)
+ return
+
+ if need_to_send_obs:
+ need_to_send_obs = false
+ var reward = _get_reward_from_agents()
+ var done = _get_done_from_agents()
+ #_reset_agents_if_done() # this ensures the new observation is from the next env instance : NEEDS REFACTOR
+
+ var obs = _get_obs_from_agents(agents_training)
+
+ var reply = {"type": "step", "obs": obs, "reward": reward, "done": done}
+ _send_dict_as_json_message(reply)
+
+ var handled = handle_message()
+
+
+func _inference_process():
+ if agents_inference.size() > 0:
+ var obs: Array = _get_obs_from_agents(agents_inference)
+ var actions = []
+
+ for agent_id in range(0, agents_inference.size()):
+ var action = agents_inference[agent_id].onnx_model.run_inference(
+ obs[agent_id]["obs"], 1.0
+ )
+ action["output"] = clamp_array(action["output"], -1.0, 1.0)
+ var action_dict = _extract_action_dict(
+ action["output"], _action_space_inference[agent_id]
+ )
+ actions.append(action_dict)
+
+ _set_agent_actions(actions, agents_inference)
+ _reset_agents_if_done(agents_inference)
+ get_tree().set_pause(false)
+
+
+func _demo_record_process():
+ if not agent_demo_record:
+ return
+
+ if Input.is_action_just_pressed("RemoveLastDemoEpisode"):
+ print("[Sync script][Demo recorder] Removing last recorded episode.")
+ demo_trajectories.remove_at(demo_trajectories.size() - 1)
+ print("Remaining episode count: %d" % demo_trajectories.size())
+
+ if n_action_steps % agent_demo_record.action_repeat != 0:
+ return
+
+ var obs_dict: Dictionary = agent_demo_record.get_obs()
+
+ # Get the current obs from the agent
+ assert(
+ obs_dict.has("obs"),
+ "Demo recorder needs an 'obs' key in get_obs() returned dictionary to record obs from."
+ )
+ current_demo_trajectory[0].append(obs_dict.obs)
+
+ # Get the action applied for the current obs from the agent
+ agent_demo_record.set_action()
+ var acts = agent_demo_record.get_action()
+
+ var terminal = agent_demo_record.get_done()
+ # Record actions only for non-terminal states
+ if terminal:
+ agent_demo_record.set_done_false()
+ else:
+ current_demo_trajectory[1].append(acts)
+
+ if terminal:
+ #current_demo_trajectory[2].append(true)
+ demo_trajectories.append(current_demo_trajectory.duplicate(true))
+ print("[Sync script][Demo recorder] Recorded episode count: %d" % demo_trajectories.size())
+ current_demo_trajectory[0].clear()
+ current_demo_trajectory[1].clear()
+
+
+func _heuristic_process():
+ for agent in agents_heuristic:
+ _reset_agents_if_done(agents_heuristic)
+
+
+func _extract_action_dict(action_array: Array, action_space: Dictionary):
+ var index = 0
+ var result = {}
+ for key in action_space.keys():
+ var size = action_space[key]["size"]
+ if action_space[key]["action_type"] == "discrete":
+ result[key] = round(action_array[index])
+ else:
+ result[key] = action_array.slice(index, index + size)
+ index += size
+
+ return result
+
+
+## For AIControllers that inherit mode from sync, sets the correct mode.
+func _set_agent_mode(agent: Node):
+ var agent_inherits_mode: bool = agent.control_mode == agent.ControlModes.INHERIT_FROM_SYNC
+
+ if agent_inherits_mode:
+ match control_mode:
+ ControlModes.HUMAN:
+ agent.control_mode = agent.ControlModes.HUMAN
+ ControlModes.TRAINING:
+ agent.control_mode = agent.ControlModes.TRAINING
+ ControlModes.ONNX_INFERENCE:
+ agent.control_mode = agent.ControlModes.ONNX_INFERENCE
+
+
+func _get_agents():
+ all_agents = get_tree().get_nodes_in_group("AGENT")
+ for agent in all_agents:
+ _set_agent_mode(agent)
+
+ if agent.control_mode == agent.ControlModes.TRAINING:
+ agents_training.append(agent)
+ elif agent.control_mode == agent.ControlModes.ONNX_INFERENCE:
+ agents_inference.append(agent)
+ elif agent.control_mode == agent.ControlModes.HUMAN:
+ agents_heuristic.append(agent)
+ elif agent.control_mode == agent.ControlModes.RECORD_EXPERT_DEMOS:
+ assert(
+ not agent_demo_record,
+ "Currently only a single AIController can be used for recording expert demos."
+ )
+ agent_demo_record = agent
+
+
+func _set_heuristic(heuristic, agents: Array):
+ for agent in agents:
+ agent.set_heuristic(heuristic)
+
+
+func _handshake():
+ print("performing handshake")
+
+ var json_dict = _get_dict_json_message()
+ assert(json_dict["type"] == "handshake")
+ var major_version = json_dict["major_version"]
+ var minor_version = json_dict["minor_version"]
+ if major_version != MAJOR_VERSION:
+ print("WARNING: major verison mismatch ", major_version, " ", MAJOR_VERSION)
+ if minor_version != MINOR_VERSION:
+ print("WARNING: minor verison mismatch ", minor_version, " ", MINOR_VERSION)
+
+ print("handshake complete")
+
+
+func _get_dict_json_message():
+ # returns a dictionary from of the most recent message
+ # this is not waiting
+ while stream.get_available_bytes() == 0:
+ stream.poll()
+ if stream.get_status() != 2:
+ print("server disconnected status, closing")
+ get_tree().quit()
+ return null
+
+ OS.delay_usec(10)
+
+ var message = stream.get_string()
+ var json_data = JSON.parse_string(message)
+
+ return json_data
+
+
+func _send_dict_as_json_message(dict):
+ stream.put_string(JSON.stringify(dict, "", false))
+
+
+func _send_env_info():
+ var json_dict = _get_dict_json_message()
+ assert(json_dict["type"] == "env_info")
+
+ var message = {
+ "type": "env_info",
+ "observation_space": _obs_space,
+ "action_space": _action_space,
+ "n_agents": len(agents_training)
+ }
+ _send_dict_as_json_message(message)
+
+
+func connect_to_server():
+ print("Waiting for one second to allow server to start")
+ OS.delay_msec(1000)
+ print("trying to connect to server")
+ stream = StreamPeerTCP.new()
+
+ # "localhost" was not working on windows VM, had to use the IP
+ var ip = "127.0.0.1"
+ var port = _get_port()
+ var connect = stream.connect_to_host(ip, port)
+ stream.set_no_delay(true) # TODO check if this improves performance or not
+ stream.poll()
+ # Fetch the status until it is either connected (2) or failed to connect (3)
+ while stream.get_status() < 2:
+ stream.poll()
+ return stream.get_status() == 2
+
+
+func _get_args():
+ print("getting command line arguments")
+ var arguments = {}
+ for argument in OS.get_cmdline_args():
+ print(argument)
+ if argument.find("=") > -1:
+ var key_value = argument.split("=")
+ arguments[key_value[0].lstrip("--")] = key_value[1]
+ else:
+ # Options without an argument will be present in the dictionary,
+ # with the value set to an empty string.
+ arguments[argument.lstrip("--")] = ""
+
+ return arguments
+
+
+func _get_speedup():
+ print(args)
+ return args.get("speedup", str(speed_up)).to_float()
+
+
+func _get_port():
+ return args.get("port", DEFAULT_PORT).to_int()
+
+
+func _set_seed():
+ var _seed = args.get("env_seed", DEFAULT_SEED).to_int()
+ seed(_seed)
+
+
+func _set_action_repeat():
+ action_repeat = args.get("action_repeat", str(action_repeat)).to_int()
+
+
+func disconnect_from_server():
+ stream.disconnect_from_host()
+
+
+func handle_message() -> bool:
+ # get json message: reset, step, close
+ var message = _get_dict_json_message()
+ if message["type"] == "close":
+ print("received close message, closing game")
+ get_tree().quit()
+ get_tree().set_pause(false)
+ return true
+
+ if message["type"] == "reset":
+ print("resetting all agents")
+ _reset_agents()
+ just_reset = true
+ get_tree().set_pause(false)
+ #print("resetting forcing draw")
+# RenderingServer.force_draw()
+# var obs = _get_obs_from_agents()
+# print("obs ", obs)
+# var reply = {
+# "type": "reset",
+# "obs": obs
+# }
+# _send_dict_as_json_message(reply)
+ return true
+
+ if message["type"] == "call":
+ var method = message["method"]
+ var returns = _call_method_on_agents(method)
+ var reply = {"type": "call", "returns": returns}
+ print("calling method from Python")
+ _send_dict_as_json_message(reply)
+ return handle_message()
+
+ if message["type"] == "action":
+ var action = message["action"]
+ _set_agent_actions(action, agents_training)
+ need_to_send_obs = true
+ get_tree().set_pause(false)
+ return true
+
+ print("message was not handled")
+ return false
+
+
+func _call_method_on_agents(method):
+ var returns = []
+ for agent in all_agents:
+ returns.append(agent.call(method))
+
+ return returns
+
+
+func _reset_agents_if_done(agents = all_agents):
+ for agent in agents:
+ if agent.get_done():
+ agent.set_done_false()
+
+
+func _reset_agents(agents = all_agents):
+ for agent in agents:
+ agent.needs_reset = true
+ #agent.reset()
+
+
+func _get_obs_from_agents(agents: Array = all_agents):
+ var obs = []
+ for agent in agents:
+ obs.append(agent.get_obs())
+ return obs
+
+
+func _get_reward_from_agents(agents: Array = agents_training):
+ var rewards = []
+ for agent in agents:
+ rewards.append(agent.get_reward())
+ agent.zero_reward()
+ return rewards
+
+
+func _get_done_from_agents(agents: Array = agents_training):
+ var dones = []
+ for agent in agents:
+ var done = agent.get_done()
+ if done:
+ agent.set_done_false()
+ dones.append(done)
+ return dones
+
+
+func _set_agent_actions(actions, agents: Array = all_agents):
+ for i in range(len(actions)):
+ agents[i].set_action(actions[i])
+
+
+func clamp_array(arr: Array, min: float, max: float):
+ var output: Array = []
+ for a in arr:
+ output.append(clamp(a, min, max))
+ return output
+
+
+## Save recorded export demos on window exit (Close game window instead of "Stop" button in Godot Editor)
+func _notification(what):
+ if demo_trajectories.size() == 0 or expert_demo_save_path.is_empty():
+ return
+
+ if what == NOTIFICATION_PREDELETE:
+ var json_string = JSON.stringify(demo_trajectories, "", false)
+ var file = FileAccess.open(expert_demo_save_path, FileAccess.WRITE)
+
+ if not file:
+ var error: Error = FileAccess.get_open_error()
+ assert(not error, "There was an error opening the file: %d" % error)
+
+ file.store_line(json_string)
+ var error = file.get_error()
+ assert(not error, "There was an error after trying to write to the file: %d" % error)
diff --git a/SimpleReachGoal/CSharp/icon.svg b/SimpleReachGoal/CSharp/icon.svg
new file mode 100644
index 0000000000000000000000000000000000000000..b370ceb72740b9a759fe11b364f0d4de27df42f8
--- /dev/null
+++ b/SimpleReachGoal/CSharp/icon.svg
@@ -0,0 +1 @@
+
diff --git a/SimpleReachGoal/CSharp/project.godot b/SimpleReachGoal/CSharp/project.godot
new file mode 100644
index 0000000000000000000000000000000000000000..a901e02ac6ff78da5143df2b6c934baa8e8b4b64
--- /dev/null
+++ b/SimpleReachGoal/CSharp/project.godot
@@ -0,0 +1,24 @@
+; Engine configuration file.
+; It's best edited using the editor UI and not directly,
+; since the parameters that go here are not all obvious.
+;
+; Format:
+; [section] ; section goes between []
+; param=value ; assign values to parameters
+
+config_version=5
+
+[application]
+
+config/name="SimpleReachGoal"
+run/main_scene="res://scenes/training_scene/training_scene.tscn"
+config/features=PackedStringArray("4.3", "C#", "Forward Plus")
+config/icon="res://icon.svg"
+
+[dotnet]
+
+project/assembly_name="SimpleReachGoal"
+
+[editor_plugins]
+
+enabled=PackedStringArray("res://addons/godot_rl_agents/plugin.cfg")
diff --git a/SimpleReachGoal/CSharp/scenes/game_scene/AreaPositionRandomizer.cs b/SimpleReachGoal/CSharp/scenes/game_scene/AreaPositionRandomizer.cs
new file mode 100644
index 0000000000000000000000000000000000000000..1d7ee4345e803f404988a501265be8c39921fa47
--- /dev/null
+++ b/SimpleReachGoal/CSharp/scenes/game_scene/AreaPositionRandomizer.cs
@@ -0,0 +1,31 @@
+using Godot;
+using System.Collections.Generic;
+
+public partial class AreaPositionRandomizer : Node3D
+{
+ private Area3D area;
+ private readonly List areaSpawnPoints = new();
+
+ // Called when the node enters the scene tree for the first time.
+ public override void _Ready()
+ {
+ foreach (Node node in GetChildren())
+ {
+ if (node is Area3D areaNode)
+ {
+ area = areaNode;
+ }
+ else if (node is MeshInstance3D mesh)
+ {
+ areaSpawnPoints.Add(mesh);
+ mesh.Visible = false;
+ }
+ }
+ }
+
+ public void Reset()
+ {
+ Vector3 newAreaPosition = areaSpawnPoints[GD.RandRange(0, areaSpawnPoints.Count - 1)].GlobalPosition;
+ area.GlobalPosition = newAreaPosition;
+ }
+}
diff --git a/SimpleReachGoal/CSharp/scenes/game_scene/GameSceneManager.cs b/SimpleReachGoal/CSharp/scenes/game_scene/GameSceneManager.cs
new file mode 100644
index 0000000000000000000000000000000000000000..fd6c5aedf833bbb3644d747d07a1d2127ea7176b
--- /dev/null
+++ b/SimpleReachGoal/CSharp/scenes/game_scene/GameSceneManager.cs
@@ -0,0 +1,24 @@
+using Godot;
+
+public partial class GameSceneManager : Node3D
+{
+ [Export]
+ public AreaPositionRandomizer GoalManager { get; set; }
+ [Export]
+ public AreaPositionRandomizer ObstacleManager { get; set; }
+ [Export]
+ public Player Player { get; set; }
+
+ // Called when the node enters the scene tree for the first time.
+ public override void _Ready()
+ {
+ Reset();
+ }
+
+ public void Reset()
+ {
+ GoalManager.Reset();
+ ObstacleManager.Reset();
+ Player.Reset();
+ }
+}
diff --git a/SimpleReachGoal/CSharp/scenes/game_scene/game_scene.tscn b/SimpleReachGoal/CSharp/scenes/game_scene/game_scene.tscn
new file mode 100644
index 0000000000000000000000000000000000000000..861af28960442de0aebe9b54251c0ec77e632a6e
--- /dev/null
+++ b/SimpleReachGoal/CSharp/scenes/game_scene/game_scene.tscn
@@ -0,0 +1,190 @@
+[gd_scene load_steps=13 format=3 uid="uid://qofctg4fc0c2"]
+
+[ext_resource type="Script" path="res://scenes/game_scene/GameSceneManager.cs" id="1_cplta"]
+[ext_resource type="Script" path="res://scenes/game_scene/AreaPositionRandomizer.cs" id="2_x2fdq"]
+[ext_resource type="PackedScene" uid="uid://fhnd4o88w5p4" path="res://scenes/player/player.tscn" id="3_j13wo"]
+
+[sub_resource type="StandardMaterial3D" id="StandardMaterial3D_g301e"]
+transparency = 1
+albedo_color = Color(0, 1, 0.166667, 0.756863)
+
+[sub_resource type="BoxMesh" id="BoxMesh_wnjao"]
+
+[sub_resource type="BoxShape3D" id="BoxShape3D_mblpq"]
+
+[sub_resource type="StandardMaterial3D" id="StandardMaterial3D_irk0a"]
+transparency = 1
+albedo_color = Color(0, 1, 0.166667, 0.313726)
+
+[sub_resource type="StandardMaterial3D" id="StandardMaterial3D_t0cxi"]
+transparency = 1
+albedo_color = Color(1, 0, 0, 0.756863)
+
+[sub_resource type="StandardMaterial3D" id="StandardMaterial3D_qu1jy"]
+transparency = 1
+albedo_color = Color(1, 0, 0, 0.313726)
+
+[sub_resource type="StandardMaterial3D" id="StandardMaterial3D_1ahva"]
+albedo_color = Color(0.8, 0.8, 0.8, 1)
+
+[sub_resource type="BoxMesh" id="BoxMesh_eh8qq"]
+material = SubResource("StandardMaterial3D_1ahva")
+size = Vector3(10, 0.1, 10)
+
+[sub_resource type="BoxShape3D" id="BoxShape3D_wmgsa"]
+size = Vector3(10, 1, 10)
+
+[node name="GameScene" type="Node3D" node_paths=PackedStringArray("GoalManager", "ObstacleManager", "Player")]
+script = ExtResource("1_cplta")
+GoalManager = NodePath("GoalManager")
+ObstacleManager = NodePath("ObstacleManager")
+Player = NodePath("Player")
+
+[node name="GoalManager" type="Node3D" parent="."]
+script = ExtResource("2_x2fdq")
+
+[node name="Goal" type="Area3D" parent="GoalManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 4, 0.5, -4)
+collision_layer = 2
+monitorable = false
+
+[node name="MeshInstance3D" type="MeshInstance3D" parent="GoalManager/Goal"]
+material_override = SubResource("StandardMaterial3D_g301e")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="CollisionShape3D" type="CollisionShape3D" parent="GoalManager/Goal"]
+shape = SubResource("BoxShape3D_mblpq")
+
+[node name="SpawnPosition" type="MeshInstance3D" parent="GoalManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 4, 0.5, 4)
+material_override = SubResource("StandardMaterial3D_irk0a")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition2" type="MeshInstance3D" parent="GoalManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -4, 0.5, 4)
+material_override = SubResource("StandardMaterial3D_irk0a")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition3" type="MeshInstance3D" parent="GoalManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -4, 0.5, -4)
+material_override = SubResource("StandardMaterial3D_irk0a")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition4" type="MeshInstance3D" parent="GoalManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 4, 0.5, -4)
+material_override = SubResource("StandardMaterial3D_irk0a")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="ObstacleManager" type="Node3D" parent="."]
+script = ExtResource("2_x2fdq")
+
+[node name="Obstacle" type="Area3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 2, 0.5, -2)
+collision_layer = 4
+monitorable = false
+
+[node name="MeshInstance3D" type="MeshInstance3D" parent="ObstacleManager/Obstacle"]
+material_override = SubResource("StandardMaterial3D_t0cxi")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="CollisionShape3D" type="CollisionShape3D" parent="ObstacleManager/Obstacle"]
+shape = SubResource("BoxShape3D_mblpq")
+
+[node name="SpawnPosition" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0.5, -2)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition2" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0.5, 2)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition3" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 2, 0.5, 0)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition4" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -2, 0.5, 0)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition5" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -2, 0.5, -1)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition6" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -2, 0.5, -2)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition7" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -1, 0.5, -2)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition8" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0.5, -2)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition9" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 2, 0.5, -2)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition10" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 2, 0.5, -1)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition11" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 2, 0.5, 1)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition12" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 2, 0.5, 2)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition13" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0.5, 2)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition14" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -1, 0.5, 2)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition15" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -2, 0.5, 2)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition16" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -2, 0.5, 1)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="Ground" type="StaticBody3D" parent="."]
+
+[node name="MeshInstance3D" type="MeshInstance3D" parent="Ground"]
+mesh = SubResource("BoxMesh_eh8qq")
+skeleton = NodePath("../..")
+
+[node name="CollisionShape3D" type="CollisionShape3D" parent="Ground"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, -0.45, 0)
+shape = SubResource("BoxShape3D_wmgsa")
+
+[node name="Player" parent="." node_paths=PackedStringArray("GameSceneManager", "Goal", "Obstacle", "AIController") instance=ExtResource("3_j13wo")]
+GameSceneManager = NodePath("..")
+Goal = NodePath("../GoalManager/Goal")
+Obstacle = NodePath("../ObstacleManager/Obstacle")
+AIController = NodePath("AIController3D")
+
+[connection signal="body_entered" from="GoalManager/Goal" to="Player" method="OnGoalBodyEntered"]
+[connection signal="body_entered" from="ObstacleManager/Obstacle" to="Player" method="OnObstacleBodyEntered"]
diff --git a/SimpleReachGoal/CSharp/scenes/player/Player.cs b/SimpleReachGoal/CSharp/scenes/player/Player.cs
new file mode 100644
index 0000000000000000000000000000000000000000..ef11ac4e13d24ab8eb60b006010920b655c15aa1
--- /dev/null
+++ b/SimpleReachGoal/CSharp/scenes/player/Player.cs
@@ -0,0 +1,92 @@
+using Godot;
+
+public partial class Player : CharacterBody3D
+{
+ [Export]
+ public GameSceneManager GameSceneManager { get; set; }
+ [Export]
+ public Area3D Goal { get; set; }
+ [Export]
+ public Area3D Obstacle { get; set; }
+ [Export]
+ public Node3D AIController { get; set; }
+ [Export]
+ public float Speed { get => speed; set => speed = value; }
+ public Vector2 RequestedMovement { get; set; }
+
+ private float speed = 5f;
+ private Transform3D initialTransform;
+
+ public override void _Ready()
+ {
+ initialTransform = Transform;
+ }
+
+ public override void _PhysicsProcess(double delta)
+ {
+ if (!IsOnFloor())
+ {
+ Velocity += GetGravity() * (float)delta;
+ }
+
+ // If controlled by human, takes the keyboard arrows as input
+ // otherwise, requested_movement will be set by the AIController based on RL agent's output actions
+ if ((string)AIController.Get("heuristic") == "human")
+ {
+ RequestedMovement = Input.GetVector("ui_left", "ui_right", "ui_up", "ui_down");
+ }
+
+ RequestedMovement = RequestedMovement.LimitLength(1f) * Speed;
+
+ Velocity = new(RequestedMovement.X, Velocity.Y, RequestedMovement.Y);
+
+ // We only move when the episode is not marked as done
+ // to prevent repeating a possibly wrong action from the previous episode.
+ // This is related to the sync node Action Repeat functionality,
+ // we don't get a new action for every physics step. This check may
+ // not be required for every env, and is not used in all examples.
+ if (!(bool)AIController.Get("done"))
+ {
+ MoveAndSlide();
+ }
+
+ ResetOnPlayerFalling();
+
+ }
+
+ // Resets the game if the player has fallen down
+ private void ResetOnPlayerFalling()
+ {
+ if (GlobalPosition.Y < -1.0)
+ {
+ GameOver(-1.0);
+ }
+ }
+
+ // Ends the game, setting an optional reward
+ private void GameOver(double reward)
+ {
+ double currentReward = (double)AIController.Get("reward");
+ AIController.Set("reward", currentReward + reward);
+ GameSceneManager.Reset();
+ }
+
+ // Resets the player and AIController
+ public void Reset()
+ {
+ AIController.Call("end_episode");
+ Transform = initialTransform;
+ }
+
+ // When the goal is entered, we restart the game with a positive reward
+ public void OnGoalBodyEntered(Node3D body)
+ {
+ GameOver(1.0);
+ }
+
+ // When the obstacle is entered, we restart the game with a negative reward
+ public void OnObstacleBodyEntered(Node3D body)
+ {
+ GameOver(-1.0);
+ }
+}
diff --git a/SimpleReachGoal/CSharp/scenes/player/player.tscn b/SimpleReachGoal/CSharp/scenes/player/player.tscn
new file mode 100644
index 0000000000000000000000000000000000000000..ababd60fcc5438a4235acc730493273631a50bb4
--- /dev/null
+++ b/SimpleReachGoal/CSharp/scenes/player/player.tscn
@@ -0,0 +1,497 @@
+[gd_scene load_steps=7 format=3 uid="uid://fhnd4o88w5p4"]
+
+[ext_resource type="Script" path="res://scenes/player/Player.cs" id="1_73fx5"]
+[ext_resource type="Script" path="res://scenes/player/player_ai_controller.gd" id="2_suigr"]
+[ext_resource type="Script" path="res://addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd" id="3_qsyok"]
+
+[sub_resource type="StandardMaterial3D" id="StandardMaterial3D_owc64"]
+albedo_color = Color(0.929563, 0.63943, 7.70092e-07, 1)
+
+[sub_resource type="CapsuleMesh" id="CapsuleMesh_jc5om"]
+material = SubResource("StandardMaterial3D_owc64")
+radius = 0.25
+height = 1.0
+
+[sub_resource type="CapsuleShape3D" id="CapsuleShape3D_2gph3"]
+radius = 0.25
+height = 1.0
+
+[node name="Player" type="CharacterBody3D"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0.5, 0)
+script = ExtResource("1_73fx5")
+
+[node name="MeshInstance3D" type="MeshInstance3D" parent="."]
+mesh = SubResource("CapsuleMesh_jc5om")
+skeleton = NodePath("../..")
+
+[node name="CollisionShape3D" type="CollisionShape3D" parent="."]
+shape = SubResource("CapsuleShape3D_2gph3")
+
+[node name="AIController3D" type="Node3D" parent="." node_paths=PackedStringArray("player", "raycast_sensors")]
+script = ExtResource("2_suigr")
+player = NodePath("..")
+raycast_sensors = [NodePath("GoalRaycastSensor"), NodePath("ObstacleRaycastSensor"), NodePath("GroundRaycastSensor")]
+
+[node name="GoalRaycastSensor" type="Node3D" parent="AIController3D"]
+script = ExtResource("3_qsyok")
+collision_mask = 2
+boolean_class_mask = 0
+n_rays_width = 32.0
+n_rays_height = 1.0
+cone_width = 360.0
+cone_height = 0.0
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_0 0" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-0.980171, 0, -9.95185)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_1 0" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-2.90285, 0, -9.5694)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_2 0" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-4.71397, 0, -8.81921)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_3 0" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-6.34393, 0, -7.7301)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_4 0" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-7.7301, 0, -6.34393)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_5 0" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-8.81921, 0, -4.71397)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57424" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-9.5694, 0, -2.90285)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57425" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-9.95185, 0, -0.980171)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57426" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-9.95185, 0, 0.980171)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57427" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-9.5694, 0, 2.90285)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57428" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-8.81921, 0, 4.71397)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57429" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-7.7301, 0, 6.34393)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_12 0" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-6.34393, 0, 7.7301)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_13 0" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-4.71397, 0, 8.81921)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_14 0" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-2.90285, 0, 9.5694)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_15 0" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-0.980171, 0, 9.95185)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57430" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(0.980171, 0, 9.95185)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57431" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(2.90285, 0, 9.5694)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57432" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(4.71397, 0, 8.81921)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57433" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(6.34393, 0, 7.7301)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57434" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(7.7301, 0, 6.34393)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57435" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(8.81921, 0, 4.71397)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57436" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(9.5694, 0, 2.90285)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57437" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(9.95185, 0, 0.980171)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57438" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(9.95185, 0, -0.980171)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57439" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(9.5694, 0, -2.90285)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57440" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(8.81921, 0, -4.71397)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57441" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(7.7301, 0, -6.34393)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57442" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(6.34393, 0, -7.7301)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57443" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(4.71397, 0, -8.81921)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57444" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(2.90285, 0, -9.5694)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57445" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(0.980171, 0, -9.95185)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="ObstacleRaycastSensor" type="Node3D" parent="AIController3D"]
+script = ExtResource("3_qsyok")
+collision_mask = 4
+boolean_class_mask = 0
+n_rays_width = 32.0
+n_rays_height = 1.0
+cone_width = 360.0
+cone_height = 0.0
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_0 0" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-0.980171, 0, -9.95185)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_1 0" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-2.90285, 0, -9.5694)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_2 0" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-4.71397, 0, -8.81921)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_3 0" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-6.34393, 0, -7.7301)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_4 0" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-7.7301, 0, -6.34393)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_5 0" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-8.81921, 0, -4.71397)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56972" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-9.5694, 0, -2.90285)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56973" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-9.95185, 0, -0.980171)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56974" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-9.95185, 0, 0.980171)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56975" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-9.5694, 0, 2.90285)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56976" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-8.81921, 0, 4.71397)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56977" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-7.7301, 0, 6.34393)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_12 0" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-6.34393, 0, 7.7301)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_13 0" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-4.71397, 0, 8.81921)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_14 0" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-2.90285, 0, 9.5694)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_15 0" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-0.980171, 0, 9.95185)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56978" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(0.980171, 0, 9.95185)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56979" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(2.90285, 0, 9.5694)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56980" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(4.71397, 0, 8.81921)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56981" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(6.34393, 0, 7.7301)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56982" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(7.7301, 0, 6.34393)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56983" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(8.81921, 0, 4.71397)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56984" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(9.5694, 0, 2.90285)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56985" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(9.95185, 0, 0.980171)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56986" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(9.95185, 0, -0.980171)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56987" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(9.5694, 0, -2.90285)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56988" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(8.81921, 0, -4.71397)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56989" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(7.7301, 0, -6.34393)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56990" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(6.34393, 0, -7.7301)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56991" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(4.71397, 0, -8.81921)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56992" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(2.90285, 0, -9.5694)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56993" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(0.980171, 0, -9.95185)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="GroundRaycastSensor" type="Node3D" parent="AIController3D"]
+transform = Transform3D(1, 0, 0, 0, -4.37114e-08, -1, 0, 1, -4.37114e-08, 0, 0, 0)
+script = ExtResource("3_qsyok")
+boolean_class_mask = 0
+n_rays_width = 4.0
+n_rays_height = 4.0
+ray_length = 2.0
+cone_width = 90.0
+cone_height = 90.0
+
+[node name="node_0 0" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(-0.92388, -1.11114, 1.38268)
+
+[node name="@RayCast3D@24718" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(-1.08979, -0.390181, 1.63099)
+
+[node name="@RayCast3D@24719" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(-1.08979, 0.390181, 1.63099)
+
+[node name="@RayCast3D@24720" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(-0.92388, 1.11114, 1.38268)
+
+[node name="node_1 0" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(-0.324423, -1.11114, 1.63099)
+
+[node name="@RayCast3D@24721" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(-0.382683, -0.390181, 1.92388)
+
+[node name="@RayCast3D@24722" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(-0.382683, 0.390181, 1.92388)
+
+[node name="@RayCast3D@24723" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(-0.324423, 1.11114, 1.63099)
+
+[node name="@RayCast3D@24724" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(0.324423, -1.11114, 1.63099)
+
+[node name="@RayCast3D@24725" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(0.382683, -0.390181, 1.92388)
+
+[node name="@RayCast3D@24726" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(0.382683, 0.390181, 1.92388)
+
+[node name="@RayCast3D@24727" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(0.324423, 1.11114, 1.63099)
+
+[node name="@RayCast3D@24728" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(0.92388, -1.11114, 1.38268)
+
+[node name="@RayCast3D@24729" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(1.08979, -0.390181, 1.63099)
+
+[node name="@RayCast3D@24730" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(1.08979, 0.390181, 1.63099)
+
+[node name="@RayCast3D@24731" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(0.92388, 1.11114, 1.38268)
diff --git a/SimpleReachGoal/CSharp/scenes/player/player_ai_controller.gd b/SimpleReachGoal/CSharp/scenes/player/player_ai_controller.gd
new file mode 100644
index 0000000000000000000000000000000000000000..93024737db1decc49891e35732c36a996e42c4a2
--- /dev/null
+++ b/SimpleReachGoal/CSharp/scenes/player/player_ai_controller.gd
@@ -0,0 +1,48 @@
+extends AIController3D
+class_name PlayerAIController
+
+@export var player: Node3D
+@export var raycast_sensors: Array[RayCastSensor3D]
+
+
+func _physics_process(delta):
+ n_steps += 1
+
+ if n_steps > reset_after:
+ player.GameSceneManager.Reset()
+
+
+func end_episode():
+ done = true
+ reset()
+
+
+func get_obs() -> Dictionary:
+ var obs: PackedFloat32Array = []
+ for sensor in raycast_sensors:
+ obs.append_array(sensor.get_observation())
+
+ var level_size: float = 10
+ var relative_goal_position: Vector3 = player.to_local(player.Goal.global_position)
+ var relative_obstacle_position: Vector3 = player.to_local(player.Obstacle.global_position)
+ obs.append_array(
+ [
+ relative_goal_position.x / level_size,
+ relative_goal_position.z / level_size,
+ relative_obstacle_position.x / level_size,
+ relative_obstacle_position.z / level_size
+ ]
+ )
+ return {"obs": obs}
+
+
+func get_reward() -> float:
+ return reward
+
+
+func get_action_space() -> Dictionary:
+ return {"move_action": {"size": 2, "action_type": "continuous"}}
+
+
+func set_action(action) -> void:
+ player.RequestedMovement = Vector2(action.move_action[0], action.move_action[1])
diff --git a/SimpleReachGoal/CSharp/scenes/training_scene/training_scene.tscn b/SimpleReachGoal/CSharp/scenes/training_scene/training_scene.tscn
new file mode 100644
index 0000000000000000000000000000000000000000..41d665aa97aaa334d32039cbefe6b4e0d63b3a3d
--- /dev/null
+++ b/SimpleReachGoal/CSharp/scenes/training_scene/training_scene.tscn
@@ -0,0 +1,83 @@
+[gd_scene load_steps=6 format=3 uid="uid://b12majbajmkqq"]
+
+[ext_resource type="PackedScene" uid="uid://qofctg4fc0c2" path="res://scenes/game_scene/game_scene.tscn" id="1_pdcwe"]
+[ext_resource type="Script" path="res://addons/godot_rl_agents/sync.gd" id="2_7kqnq"]
+
+[sub_resource type="ProceduralSkyMaterial" id="ProceduralSkyMaterial_kbbm2"]
+sky_horizon_color = Color(0.64625, 0.65575, 0.67075, 1)
+ground_horizon_color = Color(0.64625, 0.65575, 0.67075, 1)
+
+[sub_resource type="Sky" id="Sky_lpkw7"]
+sky_material = SubResource("ProceduralSkyMaterial_kbbm2")
+
+[sub_resource type="Environment" id="Environment_3ytk2"]
+background_mode = 2
+sky = SubResource("Sky_lpkw7")
+tonemap_mode = 2
+glow_enabled = true
+
+[node name="TrainingScene" type="Node3D"]
+
+[node name="WorldEnvironment" type="WorldEnvironment" parent="."]
+environment = SubResource("Environment_3ytk2")
+
+[node name="DirectionalLight3D" type="DirectionalLight3D" parent="."]
+transform = Transform3D(-0.866024, -0.433016, 0.250001, 0, 0.499998, 0.866026, -0.500003, 0.749999, -0.43301, 0, 0, 0)
+shadow_enabled = true
+
+[node name="GameScene" parent="." node_paths=PackedStringArray("GoalManager", "ObstacleManager", "Player") instance=ExtResource("1_pdcwe")]
+GoalManager = NodePath("GoalManager")
+ObstacleManager = NodePath("ObstacleManager")
+Player = NodePath("Player")
+
+[node name="GameScene2" parent="." node_paths=PackedStringArray("GoalManager", "ObstacleManager", "Player") instance=ExtResource("1_pdcwe")]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 100, 0, 0)
+GoalManager = NodePath("GoalManager")
+ObstacleManager = NodePath("ObstacleManager")
+Player = NodePath("Player")
+
+[node name="GameScene3" parent="." node_paths=PackedStringArray("GoalManager", "ObstacleManager", "Player") instance=ExtResource("1_pdcwe")]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 200, 0, 0)
+GoalManager = NodePath("GoalManager")
+ObstacleManager = NodePath("ObstacleManager")
+Player = NodePath("Player")
+
+[node name="GameScene4" parent="." node_paths=PackedStringArray("GoalManager", "ObstacleManager", "Player") instance=ExtResource("1_pdcwe")]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 300, 0, 0)
+GoalManager = NodePath("GoalManager")
+ObstacleManager = NodePath("ObstacleManager")
+Player = NodePath("Player")
+
+[node name="GameScene5" parent="." node_paths=PackedStringArray("GoalManager", "ObstacleManager", "Player") instance=ExtResource("1_pdcwe")]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 100)
+GoalManager = NodePath("GoalManager")
+ObstacleManager = NodePath("ObstacleManager")
+Player = NodePath("Player")
+
+[node name="GameScene6" parent="." node_paths=PackedStringArray("GoalManager", "ObstacleManager", "Player") instance=ExtResource("1_pdcwe")]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 100, 0, 100)
+GoalManager = NodePath("GoalManager")
+ObstacleManager = NodePath("ObstacleManager")
+Player = NodePath("Player")
+
+[node name="GameScene7" parent="." node_paths=PackedStringArray("GoalManager", "ObstacleManager", "Player") instance=ExtResource("1_pdcwe")]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 200, 0, 100)
+GoalManager = NodePath("GoalManager")
+ObstacleManager = NodePath("ObstacleManager")
+Player = NodePath("Player")
+
+[node name="GameScene8" parent="." node_paths=PackedStringArray("GoalManager", "ObstacleManager", "Player") instance=ExtResource("1_pdcwe")]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 300, 0, 100)
+GoalManager = NodePath("GoalManager")
+ObstacleManager = NodePath("ObstacleManager")
+Player = NodePath("Player")
+
+[node name="Camera3D" type="Camera3D" parent="."]
+transform = Transform3D(1, 0, 0, 0, 0.803856, 0.594823, 0, -0.594823, 0.803856, 0, 9.562, 11.843)
+fov = 51.7
+
+[node name="Sync" type="Node" parent="."]
+script = ExtResource("2_7kqnq")
+control_mode = 2
+speed_up = 8.0
+onnx_model_path = "SimpleReachGoal.onnx"
diff --git a/SimpleReachGoal/CSharpAll/.gitattributes b/SimpleReachGoal/CSharpAll/.gitattributes
new file mode 100644
index 0000000000000000000000000000000000000000..8ad74f78d9c9b9b8f3d68772c6d5aa0cb3fe47e9
--- /dev/null
+++ b/SimpleReachGoal/CSharpAll/.gitattributes
@@ -0,0 +1,2 @@
+# Normalize EOL for all files that Git considers text files.
+* text=auto eol=lf
diff --git a/SimpleReachGoal/CSharpAll/.gitignore b/SimpleReachGoal/CSharpAll/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..7de8ea58b7054d16d554ddea743ca5255256b122
--- /dev/null
+++ b/SimpleReachGoal/CSharpAll/.gitignore
@@ -0,0 +1,3 @@
+# Godot 4+ specific ignores
+.godot/
+android/
diff --git a/SimpleReachGoal/CSharpAll/SimpleReachGoal.csproj b/SimpleReachGoal/CSharpAll/SimpleReachGoal.csproj
new file mode 100644
index 0000000000000000000000000000000000000000..9e0f6e5f28fa39bd53a520b4df2afde5651b4452
--- /dev/null
+++ b/SimpleReachGoal/CSharpAll/SimpleReachGoal.csproj
@@ -0,0 +1,11 @@
+
+
+ net6.0
+ net7.0
+ net8.0
+ true
+
+
+
+
+
\ No newline at end of file
diff --git a/SimpleReachGoal/CSharpAll/SimpleReachGoal.onnx b/SimpleReachGoal/CSharpAll/SimpleReachGoal.onnx
new file mode 100644
index 0000000000000000000000000000000000000000..49cab68f41ae98ae9730c0ef9f98876deecbcd06
--- /dev/null
+++ b/SimpleReachGoal/CSharpAll/SimpleReachGoal.onnx
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:80cdcca6356a62cf997e3f18777c799ca930b53236f4fb2e911edec5c6c78838
+size 40656
diff --git a/SimpleReachGoal/CSharpAll/SimpleReachGoal.sln b/SimpleReachGoal/CSharpAll/SimpleReachGoal.sln
new file mode 100644
index 0000000000000000000000000000000000000000..cac7cbea2c4eb2fff6dba72881672fb52ef40f35
--- /dev/null
+++ b/SimpleReachGoal/CSharpAll/SimpleReachGoal.sln
@@ -0,0 +1,19 @@
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio 2012
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SimpleReachGoal", "SimpleReachGoal.csproj", "{8B1C40FD-E462-48E5-B273-A0E360A0580B}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|Any CPU = Debug|Any CPU
+ ExportDebug|Any CPU = ExportDebug|Any CPU
+ ExportRelease|Any CPU = ExportRelease|Any CPU
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {8B1C40FD-E462-48E5-B273-A0E360A0580B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {8B1C40FD-E462-48E5-B273-A0E360A0580B}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {8B1C40FD-E462-48E5-B273-A0E360A0580B}.ExportDebug|Any CPU.ActiveCfg = ExportDebug|Any CPU
+ {8B1C40FD-E462-48E5-B273-A0E360A0580B}.ExportDebug|Any CPU.Build.0 = ExportDebug|Any CPU
+ {8B1C40FD-E462-48E5-B273-A0E360A0580B}.ExportRelease|Any CPU.ActiveCfg = ExportRelease|Any CPU
+ {8B1C40FD-E462-48E5-B273-A0E360A0580B}.ExportRelease|Any CPU.Build.0 = ExportRelease|Any CPU
+ EndGlobalSection
+EndGlobal
diff --git a/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/controller/ai_controller_2d.gd b/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/controller/ai_controller_2d.gd
new file mode 100644
index 0000000000000000000000000000000000000000..fb2365649bc6a900453f5ba262af82bd59fa5a6c
--- /dev/null
+++ b/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/controller/ai_controller_2d.gd
@@ -0,0 +1,118 @@
+extends Node2D
+class_name AIController2D
+
+enum ControlModes { INHERIT_FROM_SYNC, HUMAN, TRAINING, ONNX_INFERENCE, RECORD_EXPERT_DEMOS }
+@export var control_mode: ControlModes = ControlModes.INHERIT_FROM_SYNC
+@export var onnx_model_path := ""
+@export var reset_after := 1000
+
+@export_group("Record expert demos mode options")
+## Path where the demos will be saved. The file can later be used for imitation learning.
+@export var expert_demo_save_path: String
+## The action that erases the last recorded episode from the currently recorded data.
+@export var remove_last_episode_key: InputEvent
+## Action will be repeated for n frames. Will introduce control lag if larger than 1.
+## Can be used to ensure that action_repeat on inference and training matches
+## the recorded demonstrations.
+@export var action_repeat: int = 1
+
+var onnx_model: ONNXModel
+
+var heuristic := "human"
+var done := false
+var reward := 0.0
+var n_steps := 0
+var needs_reset := false
+
+var _player: Node2D
+
+
+func _ready():
+ add_to_group("AGENT")
+
+
+func init(player: Node2D):
+ _player = player
+
+
+#-- Methods that need implementing using the "extend script" option in Godot --#
+func get_obs() -> Dictionary:
+ assert(false, "the get_obs method is not implemented when extending from ai_controller")
+ return {"obs": []}
+
+
+func get_reward() -> float:
+ assert(false, "the get_reward method is not implemented when extending from ai_controller")
+ return 0.0
+
+
+func get_action_space() -> Dictionary:
+ assert(
+ false,
+ "the get get_action_space method is not implemented when extending from ai_controller"
+ )
+ return {
+ "example_actions_continous": {"size": 2, "action_type": "continuous"},
+ "example_actions_discrete": {"size": 2, "action_type": "discrete"},
+ }
+
+
+func set_action(action) -> void:
+ assert(false, "the set_action method is not implemented when extending from ai_controller")
+
+
+#-----------------------------------------------------------------------------#
+
+
+#-- Methods that sometimes need implementing using the "extend script" option in Godot --#
+# Only needed if you are recording expert demos with this AIController
+func get_action() -> Array:
+ assert(
+ false,
+ "the get_action method is not implemented in extended AIController but demo_recorder is used"
+ )
+ return []
+
+
+# -----------------------------------------------------------------------------#
+
+
+func _physics_process(delta):
+ n_steps += 1
+ if n_steps > reset_after:
+ needs_reset = true
+
+
+func get_obs_space():
+ # may need overriding if the obs space is complex
+ var obs = get_obs()
+ return {
+ "obs": {"size": [len(obs["obs"])], "space": "box"},
+ }
+
+
+func reset():
+ n_steps = 0
+ needs_reset = false
+
+
+func reset_if_done():
+ if done:
+ reset()
+
+
+func set_heuristic(h):
+ # sets the heuristic from "human" or "model" nothing to change here
+ heuristic = h
+
+
+func get_done():
+ return done
+
+
+func set_done_false():
+ done = false
+
+
+func zero_reward():
+ reward = 0.0
diff --git a/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/controller/ai_controller_3d.gd b/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/controller/ai_controller_3d.gd
new file mode 100644
index 0000000000000000000000000000000000000000..a5b4ee61ac838c03d6e22283f17adce0e6b4bbfa
--- /dev/null
+++ b/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/controller/ai_controller_3d.gd
@@ -0,0 +1,117 @@
+extends Node3D
+class_name AIController3D
+
+enum ControlModes { INHERIT_FROM_SYNC, HUMAN, TRAINING, ONNX_INFERENCE, RECORD_EXPERT_DEMOS }
+@export var control_mode: ControlModes = ControlModes.INHERIT_FROM_SYNC
+@export var onnx_model_path := ""
+@export var reset_after := 1000
+
+@export_group("Record expert demos mode options")
+## Path where the demos will be saved. The file can later be used for imitation learning.
+@export var expert_demo_save_path: String
+## The action that erases the last recorded episode from the currently recorded data.
+@export var remove_last_episode_key: InputEvent
+## Action will be repeated for n frames. Will introduce control lag if larger than 1.
+## Can be used to ensure that action_repeat on inference and training matches
+## the recorded demonstrations.
+@export var action_repeat: int = 1
+
+var onnx_model: ONNXModel
+
+var heuristic := "human"
+var done := false
+var reward := 0.0
+var n_steps := 0
+var needs_reset := false
+
+var _player: Node3D
+
+
+func _ready():
+ add_to_group("AGENT")
+
+
+func init(player: Node3D):
+ _player = player
+
+
+#-- Methods that need implementing using the "extend script" option in Godot --#
+func get_obs() -> Dictionary:
+ assert(false, "the get_obs method is not implemented when extending from ai_controller")
+ return {"obs": []}
+
+
+func get_reward() -> float:
+ assert(false, "the get_reward method is not implemented when extending from ai_controller")
+ return 0.0
+
+
+func get_action_space() -> Dictionary:
+ assert(
+ false, "the get_action_space method is not implemented when extending from ai_controller"
+ )
+ return {
+ "example_actions_continous": {"size": 2, "action_type": "continuous"},
+ "example_actions_discrete": {"size": 2, "action_type": "discrete"},
+ }
+
+
+func set_action(action) -> void:
+ assert(false, "the set_action method is not implemented when extending from ai_controller")
+
+
+#-----------------------------------------------------------------------------#
+
+
+#-- Methods that sometimes need implementing using the "extend script" option in Godot --#
+# Only needed if you are recording expert demos with this AIController
+func get_action() -> Array:
+ assert(
+ false,
+ "the get_action method is not implemented in extended AIController but demo_recorder is used"
+ )
+ return []
+
+
+# -----------------------------------------------------------------------------#
+
+
+func _physics_process(delta):
+ n_steps += 1
+ if n_steps > reset_after:
+ needs_reset = true
+
+
+func get_obs_space():
+ # may need overriding if the obs space is complex
+ var obs = get_obs()
+ return {
+ "obs": {"size": [len(obs["obs"])], "space": "box"},
+ }
+
+
+func reset():
+ n_steps = 0
+ needs_reset = false
+
+
+func reset_if_done():
+ if done:
+ reset()
+
+
+func set_heuristic(h):
+ # sets the heuristic from "human" or "model" nothing to change here
+ heuristic = h
+
+
+func get_done():
+ return done
+
+
+func set_done_false():
+ done = false
+
+
+func zero_reward():
+ reward = 0.0
diff --git a/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/godot_rl_agents.gd b/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/godot_rl_agents.gd
new file mode 100644
index 0000000000000000000000000000000000000000..e4fe13693a598c808aca1b64051d1c0c70783296
--- /dev/null
+++ b/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/godot_rl_agents.gd
@@ -0,0 +1,16 @@
+@tool
+extends EditorPlugin
+
+
+func _enter_tree():
+ # Initialization of the plugin goes here.
+ # Add the new type with a name, a parent type, a script and an icon.
+ add_custom_type("Sync", "Node", preload("sync.gd"), preload("icon.png"))
+ #add_custom_type("RaycastSensor2D2", "Node", preload("raycast_sensor_2d.gd"), preload("icon.png"))
+
+
+func _exit_tree():
+ # Clean-up of the plugin goes here.
+ # Always remember to remove it from the engine when deactivated.
+ remove_custom_type("Sync")
+ #remove_custom_type("RaycastSensor2D2")
diff --git a/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/icon.png b/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/icon.png
new file mode 100644
index 0000000000000000000000000000000000000000..ccb4ca000e3e1cf659fe367ab5bff67c1eb3467d
--- /dev/null
+++ b/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/icon.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:e3a8bc372d3313ce1ede4e7554472e37b322178b9488bfb709e296585abd3c44
+size 198
diff --git a/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/onnx/csharp/ONNXInference.cs b/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/onnx/csharp/ONNXInference.cs
new file mode 100644
index 0000000000000000000000000000000000000000..d2c6364a90eeac1ec8c6633d01029bffd352958e
--- /dev/null
+++ b/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/onnx/csharp/ONNXInference.cs
@@ -0,0 +1,103 @@
+using Godot;
+using Microsoft.ML.OnnxRuntime;
+using Microsoft.ML.OnnxRuntime.Tensors;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace GodotONNX
+{
+ ///
+ public partial class ONNXInference : GodotObject
+ {
+
+ private InferenceSession session;
+ ///
+ /// Path to the ONNX model. Use Initialize to change it.
+ ///
+ private string modelPath;
+ private int batchSize;
+
+ private SessionOptions SessionOpt;
+
+ //init function
+ ///
+ public void Initialize(string Path, int BatchSize)
+ {
+ modelPath = Path;
+ batchSize = BatchSize;
+ SessionOpt = SessionConfigurator.MakeConfiguredSessionOptions();
+ session = LoadModel(modelPath);
+
+ }
+ ///
+ public Godot.Collections.Dictionary> RunInference(Godot.Collections.Array obs, int state_ins)
+ {
+ //Current model: Any (Godot Rl Agents)
+ //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
+
+ //Fill the input tensors
+ // create span from inputSize
+ var span = new float[obs.Count]; //There's probably a better way to do this
+ for (int i = 0; i < obs.Count; i++)
+ {
+ span[i] = obs[i];
+ }
+
+ IReadOnlyCollection inputs = new List
+ {
+ NamedOnnxValue.CreateFromTensor("obs", new DenseTensor(span, new int[] { batchSize, obs.Count })),
+ NamedOnnxValue.CreateFromTensor("state_ins", new DenseTensor(new float[] { state_ins }, new int[] { batchSize }))
+ };
+ IReadOnlyCollection outputNames = new List { "output", "state_outs" }; //ONNX is sensible to these names, as well as the input names
+
+ IDisposableReadOnlyCollection results;
+ //We do not use "using" here so we get a better exception explaination later
+ try
+ {
+ results = session.Run(inputs, outputNames);
+ }
+ catch (OnnxRuntimeException e)
+ {
+ //This error usually means that the model is not compatible with the input, beacause of the input shape (size)
+ GD.Print("Error at inference: ", e);
+ return null;
+ }
+ //Can't convert IEnumerable to Variant, so we have to convert it to an array or something
+ Godot.Collections.Dictionary> output = new Godot.Collections.Dictionary>();
+ DisposableNamedOnnxValue output1 = results.First();
+ DisposableNamedOnnxValue output2 = results.Last();
+ Godot.Collections.Array output1Array = new Godot.Collections.Array();
+ Godot.Collections.Array output2Array = new Godot.Collections.Array();
+
+ foreach (float f in output1.AsEnumerable())
+ {
+ output1Array.Add(f);
+ }
+
+ foreach (float f in output2.AsEnumerable())
+ {
+ output2Array.Add(f);
+ }
+
+ output.Add(output1.Name, output1Array);
+ output.Add(output2.Name, output2Array);
+
+ //Output is a dictionary of arrays, ex: { "output" : [0.1, 0.2, 0.3, 0.4, ...], "state_outs" : [0.5, ...]}
+ results.Dispose();
+ return output;
+ }
+ ///
+ public InferenceSession LoadModel(string Path)
+ {
+ using Godot.FileAccess file = FileAccess.Open(Path, Godot.FileAccess.ModeFlags.Read);
+ byte[] model = file.GetBuffer((int)file.GetLength());
+ //file.Close(); file.Dispose(); //Close the file, then dispose the reference.
+ return new InferenceSession(model, SessionOpt); //Load the model
+ }
+ public void FreeDisposables()
+ {
+ session.Dispose();
+ SessionOpt.Dispose();
+ }
+ }
+}
diff --git a/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/onnx/csharp/SessionConfigurator.cs b/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/onnx/csharp/SessionConfigurator.cs
new file mode 100644
index 0000000000000000000000000000000000000000..3f77d784b8e875e6884e097b8a9a87d888f252cf
--- /dev/null
+++ b/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/onnx/csharp/SessionConfigurator.cs
@@ -0,0 +1,131 @@
+using Godot;
+using Microsoft.ML.OnnxRuntime;
+
+namespace GodotONNX
+{
+ ///
+
+ public static class SessionConfigurator
+ {
+ public enum ComputeName
+ {
+ CUDA,
+ ROCm,
+ DirectML,
+ CoreML,
+ CPU
+ }
+
+ ///
+ public static SessionOptions MakeConfiguredSessionOptions()
+ {
+ SessionOptions sessionOptions = new();
+ SetOptions(sessionOptions);
+ return sessionOptions;
+ }
+
+ private static void SetOptions(SessionOptions sessionOptions)
+ {
+ sessionOptions.LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_WARNING;
+ ApplySystemSpecificOptions(sessionOptions);
+ }
+
+ ///
+ static public void ApplySystemSpecificOptions(SessionOptions sessionOptions)
+ {
+ //Most code for this function is verbose only, the only reason it exists is to track
+ //implementation progress of the different compute APIs.
+
+ //December 2022: CUDA is not working.
+
+ string OSName = OS.GetName(); //Get OS Name
+
+ //ComputeName ComputeAPI = ComputeCheck(); //Get Compute API
+ // //TODO: Get CPU architecture
+
+ //Linux can use OpenVINO (C#) on x64 and ROCm on x86 (GDNative/C++)
+ //Windows can use OpenVINO (C#) on x64
+ //TODO: try TensorRT instead of CUDA
+ //TODO: Use OpenVINO for Intel Graphics
+
+ // Temporarily using CPU on all platforms to avoid errors detected with DML
+ ComputeName ComputeAPI = ComputeName.CPU;
+
+ //match OS and Compute API
+ GD.Print($"OS: {OSName} Compute API: {ComputeAPI}");
+
+ // CPU is set by default without appending necessary
+ // sessionOptions.AppendExecutionProvider_CPU(0);
+
+ /*
+ switch (OSName)
+ {
+ case "Windows": //Can use CUDA, DirectML
+ if (ComputeAPI is ComputeName.CUDA)
+ {
+ //CUDA
+ //sessionOptions.AppendExecutionProvider_CUDA(0);
+ //sessionOptions.AppendExecutionProvider_DML(0);
+ }
+ else if (ComputeAPI is ComputeName.DirectML)
+ {
+ //DirectML
+ //sessionOptions.AppendExecutionProvider_DML(0);
+ }
+ break;
+ case "X11": //Can use CUDA, ROCm
+ if (ComputeAPI is ComputeName.CUDA)
+ {
+ //CUDA
+ //sessionOptions.AppendExecutionProvider_CUDA(0);
+ }
+ if (ComputeAPI is ComputeName.ROCm)
+ {
+ //ROCm, only works on x86
+ //Research indicates that this has to be compiled as a GDNative plugin
+ //GD.Print("ROCm not supported yet, using CPU.");
+ //sessionOptions.AppendExecutionProvider_CPU(0);
+ }
+ break;
+ case "macOS": //Can use CoreML
+ if (ComputeAPI is ComputeName.CoreML)
+ { //CoreML
+ //TODO: Needs testing
+ //sessionOptions.AppendExecutionProvider_CoreML(0);
+ //CoreML on ARM64, out of the box, on x64 needs .tar file from GitHub
+ }
+ break;
+ default:
+ GD.Print("OS not Supported.");
+ break;
+ }
+ */
+ }
+
+
+ ///
+ public static ComputeName ComputeCheck()
+ {
+ string adapterName = Godot.RenderingServer.GetVideoAdapterName();
+ //string adapterVendor = Godot.RenderingServer.GetVideoAdapterVendor();
+ adapterName = adapterName.ToUpper(new System.Globalization.CultureInfo(""));
+ //TODO: GPU vendors for MacOS, what do they even use these days?
+
+ if (adapterName.Contains("INTEL"))
+ {
+ return ComputeName.DirectML;
+ }
+ if (adapterName.Contains("AMD") || adapterName.Contains("RADEON"))
+ {
+ return ComputeName.DirectML;
+ }
+ if (adapterName.Contains("NVIDIA"))
+ {
+ return ComputeName.CUDA;
+ }
+
+ GD.Print("Graphics Card not recognized."); //Should use CPU
+ return ComputeName.CPU;
+ }
+ }
+}
diff --git a/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/onnx/csharp/docs/ONNXInference.xml b/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/onnx/csharp/docs/ONNXInference.xml
new file mode 100644
index 0000000000000000000000000000000000000000..91b07d607dc89f11e957e13758d8c0ee4fb72be8
--- /dev/null
+++ b/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/onnx/csharp/docs/ONNXInference.xml
@@ -0,0 +1,31 @@
+
+
+
+
+ The main ONNXInference Class that handles the inference process.
+
+
+
+
+ Starts the inference process.
+
+ Path to the ONNX model, expects a path inside resources.
+ How many observations will the model recieve.
+
+
+
+ Runs the given input through the model and returns the output.
+
+ Dictionary containing all observations.
+ How many different agents are creating these observations.
+ A Dictionary of arrays, containing instructions based on the observations.
+
+
+
+ Loads the given model into the inference process, using the best Execution provider available.
+
+ Path to the ONNX model, expects a path inside resources.
+ InferenceSession ready to run.
+
+
+
\ No newline at end of file
diff --git a/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/onnx/csharp/docs/SessionConfigurator.xml b/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/onnx/csharp/docs/SessionConfigurator.xml
new file mode 100644
index 0000000000000000000000000000000000000000..f160c02f0d4cab92e10f799b6f4c5a71d4d6c0f2
--- /dev/null
+++ b/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/onnx/csharp/docs/SessionConfigurator.xml
@@ -0,0 +1,29 @@
+
+
+
+
+ The main SessionConfigurator Class that handles the execution options and providers for the inference process.
+
+
+
+
+ Creates a SessionOptions with all available execution providers.
+
+ SessionOptions with all available execution providers.
+
+
+
+ Appends any execution provider available in the current system.
+
+
+ This function is mainly verbose for tracking implementation progress of different compute APIs.
+
+
+
+
+ Checks for available GPUs.
+
+ An integer identifier for each compute platform.
+
+
+
\ No newline at end of file
diff --git a/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/onnx/wrapper/ONNX_wrapper.gd b/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/onnx/wrapper/ONNX_wrapper.gd
new file mode 100644
index 0000000000000000000000000000000000000000..d573582b995a2b8fe05553f7cf58fb2e3b58d482
--- /dev/null
+++ b/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/onnx/wrapper/ONNX_wrapper.gd
@@ -0,0 +1,27 @@
+extends Resource
+class_name ONNXModel
+var inferencer_script = load("res://addons/godot_rl_agents/onnx/csharp/ONNXInference.cs")
+
+var inferencer = null
+
+
+# Must provide the path to the model and the batch size
+func _init(model_path, batch_size):
+ inferencer = inferencer_script.new()
+ inferencer.Initialize(model_path, batch_size)
+
+
+# This function is the one that will be called from the game,
+# requires the observation as an array and the state_ins as an int
+# returns an Array containing the action the model takes.
+func run_inference(obs: Array, state_ins: int) -> Dictionary:
+ if inferencer == null:
+ printerr("Inferencer not initialized")
+ return {}
+ return inferencer.RunInference(obs, state_ins)
+
+
+func _notification(what):
+ if what == NOTIFICATION_PREDELETE:
+ inferencer.FreeDisposables()
+ inferencer.free()
diff --git a/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/plugin.cfg b/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/plugin.cfg
new file mode 100644
index 0000000000000000000000000000000000000000..b1bc988c80e3fe68e6d4279691fd5892e5ef323d
--- /dev/null
+++ b/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/plugin.cfg
@@ -0,0 +1,7 @@
+[plugin]
+
+name="GodotRLAgents"
+description="Custom nodes for the godot rl agents toolkit "
+author="Edward Beeching"
+version="0.1"
+script="godot_rl_agents.gd"
diff --git a/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/sensors/sensors_2d/ExampleRaycastSensor2D.tscn b/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/sensors/sensors_2d/ExampleRaycastSensor2D.tscn
new file mode 100644
index 0000000000000000000000000000000000000000..5edb6c7fc9da56e625d57185bdbafdbcc3fc67c5
--- /dev/null
+++ b/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/sensors/sensors_2d/ExampleRaycastSensor2D.tscn
@@ -0,0 +1,48 @@
+[gd_scene load_steps=5 format=3 uid="uid://ddeq7mn1ealyc"]
+
+[ext_resource type="Script" path="res://addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.gd" id="1"]
+
+[sub_resource type="GDScript" id="2"]
+script/source = "extends Node2D
+
+
+
+func _physics_process(delta: float) -> void:
+ print(\"step start\")
+
+"
+
+[sub_resource type="GDScript" id="1"]
+script/source = "extends RayCast2D
+
+var steps = 1
+
+func _physics_process(delta: float) -> void:
+ print(\"processing raycast\")
+ steps += 1
+ if steps % 2:
+ force_raycast_update()
+
+ print(is_colliding())
+"
+
+[sub_resource type="CircleShape2D" id="3"]
+
+[node name="ExampleRaycastSensor2D" type="Node2D"]
+script = SubResource("2")
+
+[node name="ExampleAgent" type="Node2D" parent="."]
+position = Vector2(573, 314)
+rotation = 0.286234
+
+[node name="RaycastSensor2D" type="Node2D" parent="ExampleAgent"]
+script = ExtResource("1")
+
+[node name="TestRayCast2D" type="RayCast2D" parent="."]
+script = SubResource("1")
+
+[node name="StaticBody2D" type="StaticBody2D" parent="."]
+position = Vector2(1, 52)
+
+[node name="CollisionShape2D" type="CollisionShape2D" parent="StaticBody2D"]
+shape = SubResource("3")
diff --git a/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/sensors/sensors_2d/GridSensor2D.gd b/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/sensors/sensors_2d/GridSensor2D.gd
new file mode 100644
index 0000000000000000000000000000000000000000..da170ba93919a8f28510ea8fc1ab876fe5876d34
--- /dev/null
+++ b/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/sensors/sensors_2d/GridSensor2D.gd
@@ -0,0 +1,235 @@
+@tool
+extends ISensor2D
+class_name GridSensor2D
+
+@export var debug_view := false:
+ get:
+ return debug_view
+ set(value):
+ debug_view = value
+ _update()
+
+@export_flags_2d_physics var detection_mask := 0:
+ get:
+ return detection_mask
+ set(value):
+ detection_mask = value
+ _update()
+
+@export var collide_with_areas := false:
+ get:
+ return collide_with_areas
+ set(value):
+ collide_with_areas = value
+ _update()
+
+@export var collide_with_bodies := true:
+ get:
+ return collide_with_bodies
+ set(value):
+ collide_with_bodies = value
+ _update()
+
+@export_range(1, 200, 0.1) var cell_width := 20.0:
+ get:
+ return cell_width
+ set(value):
+ cell_width = value
+ _update()
+
+@export_range(1, 200, 0.1) var cell_height := 20.0:
+ get:
+ return cell_height
+ set(value):
+ cell_height = value
+ _update()
+
+@export_range(1, 21, 2, "or_greater") var grid_size_x := 3:
+ get:
+ return grid_size_x
+ set(value):
+ grid_size_x = value
+ _update()
+
+@export_range(1, 21, 2, "or_greater") var grid_size_y := 3:
+ get:
+ return grid_size_y
+ set(value):
+ grid_size_y = value
+ _update()
+
+var _obs_buffer: PackedFloat64Array
+var _rectangle_shape: RectangleShape2D
+var _collision_mapping: Dictionary
+var _n_layers_per_cell: int
+
+var _highlighted_cell_color: Color
+var _standard_cell_color: Color
+
+
+func get_observation():
+ return _obs_buffer
+
+
+func _update():
+ if Engine.is_editor_hint():
+ if is_node_ready():
+ _spawn_nodes()
+
+
+func _ready() -> void:
+ _set_colors()
+
+ if Engine.is_editor_hint():
+ if get_child_count() == 0:
+ _spawn_nodes()
+ else:
+ _spawn_nodes()
+
+
+func _set_colors() -> void:
+ _standard_cell_color = Color(100.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0)
+ _highlighted_cell_color = Color(255.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0)
+
+
+func _get_collision_mapping() -> Dictionary:
+ # defines which layer is mapped to which cell obs index
+ var total_bits = 0
+ var collision_mapping = {}
+ for i in 32:
+ var bit_mask = 2 ** i
+ if (detection_mask & bit_mask) > 0:
+ collision_mapping[i] = total_bits
+ total_bits += 1
+
+ return collision_mapping
+
+
+func _spawn_nodes():
+ for cell in get_children():
+ cell.name = "_%s" % cell.name # Otherwise naming below will fail
+ cell.queue_free()
+
+ _collision_mapping = _get_collision_mapping()
+ #prints("collision_mapping", _collision_mapping, len(_collision_mapping))
+ # allocate memory for the observations
+ _n_layers_per_cell = len(_collision_mapping)
+ _obs_buffer = PackedFloat64Array()
+ _obs_buffer.resize(grid_size_x * grid_size_y * _n_layers_per_cell)
+ _obs_buffer.fill(0)
+ #prints(len(_obs_buffer), _obs_buffer )
+
+ _rectangle_shape = RectangleShape2D.new()
+ _rectangle_shape.set_size(Vector2(cell_width, cell_height))
+
+ var shift := Vector2(
+ -(grid_size_x / 2) * cell_width,
+ -(grid_size_y / 2) * cell_height,
+ )
+
+ for i in grid_size_x:
+ for j in grid_size_y:
+ var cell_position = Vector2(i * cell_width, j * cell_height) + shift
+ _create_cell(i, j, cell_position)
+
+
+func _create_cell(i: int, j: int, position: Vector2):
+ var cell := Area2D.new()
+ cell.position = position
+ cell.name = "GridCell %s %s" % [i, j]
+ cell.modulate = _standard_cell_color
+
+ if collide_with_areas:
+ cell.area_entered.connect(_on_cell_area_entered.bind(i, j))
+ cell.area_exited.connect(_on_cell_area_exited.bind(i, j))
+
+ if collide_with_bodies:
+ cell.body_entered.connect(_on_cell_body_entered.bind(i, j))
+ cell.body_exited.connect(_on_cell_body_exited.bind(i, j))
+
+ cell.collision_layer = 0
+ cell.collision_mask = detection_mask
+ cell.monitorable = true
+ add_child(cell)
+ cell.set_owner(get_tree().edited_scene_root)
+
+ var col_shape := CollisionShape2D.new()
+ col_shape.shape = _rectangle_shape
+ col_shape.name = "CollisionShape2D"
+ cell.add_child(col_shape)
+ col_shape.set_owner(get_tree().edited_scene_root)
+
+ if debug_view:
+ var quad = MeshInstance2D.new()
+ quad.name = "MeshInstance2D"
+ var quad_mesh = QuadMesh.new()
+
+ quad_mesh.set_size(Vector2(cell_width, cell_height))
+
+ quad.mesh = quad_mesh
+ cell.add_child(quad)
+ quad.set_owner(get_tree().edited_scene_root)
+
+
+func _update_obs(cell_i: int, cell_j: int, collision_layer: int, entered: bool):
+ for key in _collision_mapping:
+ var bit_mask = 2 ** key
+ if (collision_layer & bit_mask) > 0:
+ var collison_map_index = _collision_mapping[key]
+
+ var obs_index = (
+ (cell_i * grid_size_x * _n_layers_per_cell)
+ + (cell_j * _n_layers_per_cell)
+ + collison_map_index
+ )
+ #prints(obs_index, cell_i, cell_j)
+ if entered:
+ _obs_buffer[obs_index] += 1
+ else:
+ _obs_buffer[obs_index] -= 1
+
+
+func _toggle_cell(cell_i: int, cell_j: int):
+ var cell = get_node_or_null("GridCell %s %s" % [cell_i, cell_j])
+
+ if cell == null:
+ print("cell not found, returning")
+
+ var n_hits = 0
+ var start_index = (cell_i * grid_size_x * _n_layers_per_cell) + (cell_j * _n_layers_per_cell)
+ for i in _n_layers_per_cell:
+ n_hits += _obs_buffer[start_index + i]
+
+ if n_hits > 0:
+ cell.modulate = _highlighted_cell_color
+ else:
+ cell.modulate = _standard_cell_color
+
+
+func _on_cell_area_entered(area: Area2D, cell_i: int, cell_j: int):
+ #prints("_on_cell_area_entered", cell_i, cell_j)
+ _update_obs(cell_i, cell_j, area.collision_layer, true)
+ if debug_view:
+ _toggle_cell(cell_i, cell_j)
+ #print(_obs_buffer)
+
+
+func _on_cell_area_exited(area: Area2D, cell_i: int, cell_j: int):
+ #prints("_on_cell_area_exited", cell_i, cell_j)
+ _update_obs(cell_i, cell_j, area.collision_layer, false)
+ if debug_view:
+ _toggle_cell(cell_i, cell_j)
+
+
+func _on_cell_body_entered(body: Node2D, cell_i: int, cell_j: int):
+ #prints("_on_cell_body_entered", cell_i, cell_j)
+ _update_obs(cell_i, cell_j, body.collision_layer, true)
+ if debug_view:
+ _toggle_cell(cell_i, cell_j)
+
+
+func _on_cell_body_exited(body: Node2D, cell_i: int, cell_j: int):
+ #prints("_on_cell_body_exited", cell_i, cell_j)
+ _update_obs(cell_i, cell_j, body.collision_layer, false)
+ if debug_view:
+ _toggle_cell(cell_i, cell_j)
diff --git a/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/sensors/sensors_2d/ISensor2D.gd b/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/sensors/sensors_2d/ISensor2D.gd
new file mode 100644
index 0000000000000000000000000000000000000000..67669a1d71a3e37d780b396633951d7d1ac79edb
--- /dev/null
+++ b/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/sensors/sensors_2d/ISensor2D.gd
@@ -0,0 +1,25 @@
+extends Node2D
+class_name ISensor2D
+
+var _obs: Array = []
+var _active := false
+
+
+func get_observation():
+ pass
+
+
+func activate():
+ _active = true
+
+
+func deactivate():
+ _active = false
+
+
+func _update_observation():
+ pass
+
+
+func reset():
+ pass
diff --git a/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.gd b/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.gd
new file mode 100644
index 0000000000000000000000000000000000000000..9bb54ede90a6f6ffd5e65d89bf1bd561bc0832ed
--- /dev/null
+++ b/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.gd
@@ -0,0 +1,118 @@
+@tool
+extends ISensor2D
+class_name RaycastSensor2D
+
+@export_flags_2d_physics var collision_mask := 1:
+ get:
+ return collision_mask
+ set(value):
+ collision_mask = value
+ _update()
+
+@export var collide_with_areas := false:
+ get:
+ return collide_with_areas
+ set(value):
+ collide_with_areas = value
+ _update()
+
+@export var collide_with_bodies := true:
+ get:
+ return collide_with_bodies
+ set(value):
+ collide_with_bodies = value
+ _update()
+
+@export var n_rays := 16.0:
+ get:
+ return n_rays
+ set(value):
+ n_rays = value
+ _update()
+
+@export_range(5, 3000, 5.0) var ray_length := 200:
+ get:
+ return ray_length
+ set(value):
+ ray_length = value
+ _update()
+@export_range(5, 360, 5.0) var cone_width := 360.0:
+ get:
+ return cone_width
+ set(value):
+ cone_width = value
+ _update()
+
+@export var debug_draw := true:
+ get:
+ return debug_draw
+ set(value):
+ debug_draw = value
+ _update()
+
+var _angles = []
+var rays := []
+
+
+func _update():
+ if Engine.is_editor_hint():
+ if debug_draw:
+ _spawn_nodes()
+ else:
+ for ray in get_children():
+ if ray is RayCast2D:
+ remove_child(ray)
+
+
+func _ready() -> void:
+ _spawn_nodes()
+
+
+func _spawn_nodes():
+ for ray in rays:
+ ray.queue_free()
+ rays = []
+
+ _angles = []
+ var step = cone_width / (n_rays)
+ var start = step / 2 - cone_width / 2
+
+ for i in n_rays:
+ var angle = start + i * step
+ var ray = RayCast2D.new()
+ ray.set_target_position(
+ Vector2(ray_length * cos(deg_to_rad(angle)), ray_length * sin(deg_to_rad(angle)))
+ )
+ ray.set_name("node_" + str(i))
+ ray.enabled = false
+ ray.collide_with_areas = collide_with_areas
+ ray.collide_with_bodies = collide_with_bodies
+ ray.collision_mask = collision_mask
+ add_child(ray)
+ rays.append(ray)
+
+ _angles.append(start + i * step)
+
+
+func get_observation() -> Array:
+ return self.calculate_raycasts()
+
+
+func calculate_raycasts() -> Array:
+ var result = []
+ for ray in rays:
+ ray.enabled = true
+ ray.force_raycast_update()
+ var distance = _get_raycast_distance(ray)
+ result.append(distance)
+ ray.enabled = false
+ return result
+
+
+func _get_raycast_distance(ray: RayCast2D) -> float:
+ if !ray.is_colliding():
+ return 0.0
+
+ var distance = (global_position - ray.get_collision_point()).length()
+ distance = clamp(distance, 0.0, ray_length)
+ return (ray_length - distance) / ray_length
diff --git a/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.tscn b/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.tscn
new file mode 100644
index 0000000000000000000000000000000000000000..5ca402c08305efedbfc6afd0a1893a0ca2e11cfd
--- /dev/null
+++ b/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.tscn
@@ -0,0 +1,7 @@
+[gd_scene load_steps=2 format=3 uid="uid://drvfihk5esgmv"]
+
+[ext_resource type="Script" path="res://addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.gd" id="1"]
+
+[node name="RaycastSensor2D" type="Node2D"]
+script = ExtResource("1")
+n_rays = 17.0
diff --git a/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/sensors/sensors_3d/ExampleRaycastSensor3D.tscn b/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/sensors/sensors_3d/ExampleRaycastSensor3D.tscn
new file mode 100644
index 0000000000000000000000000000000000000000..a8057c7619cbb835709d2704074b0d5ebfa00a0c
--- /dev/null
+++ b/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/sensors/sensors_3d/ExampleRaycastSensor3D.tscn
@@ -0,0 +1,6 @@
+[gd_scene format=3 uid="uid://biu787qh4woik"]
+
+[node name="ExampleRaycastSensor3D" type="Node3D"]
+
+[node name="Camera3D" type="Camera3D" parent="."]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0.804183, 0, 2.70146)
diff --git a/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/sensors/sensors_3d/GridSensor3D.gd b/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/sensors/sensors_3d/GridSensor3D.gd
new file mode 100644
index 0000000000000000000000000000000000000000..03593cc04d74ce0d0f16a4518e59b9309a09a5a7
--- /dev/null
+++ b/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/sensors/sensors_3d/GridSensor3D.gd
@@ -0,0 +1,258 @@
+@tool
+extends ISensor3D
+class_name GridSensor3D
+
+@export var debug_view := false:
+ get:
+ return debug_view
+ set(value):
+ debug_view = value
+ _update()
+
+@export_flags_3d_physics var detection_mask := 0:
+ get:
+ return detection_mask
+ set(value):
+ detection_mask = value
+ _update()
+
+@export var collide_with_areas := false:
+ get:
+ return collide_with_areas
+ set(value):
+ collide_with_areas = value
+ _update()
+
+@export var collide_with_bodies := false:
+ # NOTE! The sensor will not detect StaticBody3D, add an area to static bodies to detect them
+ get:
+ return collide_with_bodies
+ set(value):
+ collide_with_bodies = value
+ _update()
+
+@export_range(0.1, 2, 0.1) var cell_width := 1.0:
+ get:
+ return cell_width
+ set(value):
+ cell_width = value
+ _update()
+
+@export_range(0.1, 2, 0.1) var cell_height := 1.0:
+ get:
+ return cell_height
+ set(value):
+ cell_height = value
+ _update()
+
+@export_range(1, 21, 2, "or_greater") var grid_size_x := 3:
+ get:
+ return grid_size_x
+ set(value):
+ grid_size_x = value
+ _update()
+
+@export_range(1, 21, 2, "or_greater") var grid_size_z := 3:
+ get:
+ return grid_size_z
+ set(value):
+ grid_size_z = value
+ _update()
+
+var _obs_buffer: PackedFloat64Array
+var _box_shape: BoxShape3D
+var _collision_mapping: Dictionary
+var _n_layers_per_cell: int
+
+var _highlighted_box_material: StandardMaterial3D
+var _standard_box_material: StandardMaterial3D
+
+
+func get_observation():
+ return _obs_buffer
+
+
+func reset():
+ _obs_buffer.fill(0)
+
+
+func _update():
+ if Engine.is_editor_hint():
+ if is_node_ready():
+ _spawn_nodes()
+
+
+func _ready() -> void:
+ _make_materials()
+
+ if Engine.is_editor_hint():
+ if get_child_count() == 0:
+ _spawn_nodes()
+ else:
+ _spawn_nodes()
+
+
+func _make_materials() -> void:
+ if _highlighted_box_material != null and _standard_box_material != null:
+ return
+
+ _standard_box_material = StandardMaterial3D.new()
+ _standard_box_material.set_transparency(1) # ALPHA
+ _standard_box_material.albedo_color = Color(
+ 100.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0
+ )
+
+ _highlighted_box_material = StandardMaterial3D.new()
+ _highlighted_box_material.set_transparency(1) # ALPHA
+ _highlighted_box_material.albedo_color = Color(
+ 255.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0
+ )
+
+
+func _get_collision_mapping() -> Dictionary:
+ # defines which layer is mapped to which cell obs index
+ var total_bits = 0
+ var collision_mapping = {}
+ for i in 32:
+ var bit_mask = 2 ** i
+ if (detection_mask & bit_mask) > 0:
+ collision_mapping[i] = total_bits
+ total_bits += 1
+
+ return collision_mapping
+
+
+func _spawn_nodes():
+ for cell in get_children():
+ cell.name = "_%s" % cell.name # Otherwise naming below will fail
+ cell.queue_free()
+
+ _collision_mapping = _get_collision_mapping()
+ #prints("collision_mapping", _collision_mapping, len(_collision_mapping))
+ # allocate memory for the observations
+ _n_layers_per_cell = len(_collision_mapping)
+ _obs_buffer = PackedFloat64Array()
+ _obs_buffer.resize(grid_size_x * grid_size_z * _n_layers_per_cell)
+ _obs_buffer.fill(0)
+ #prints(len(_obs_buffer), _obs_buffer )
+
+ _box_shape = BoxShape3D.new()
+ _box_shape.set_size(Vector3(cell_width, cell_height, cell_width))
+
+ var shift := Vector3(
+ -(grid_size_x / 2) * cell_width,
+ 0,
+ -(grid_size_z / 2) * cell_width,
+ )
+
+ for i in grid_size_x:
+ for j in grid_size_z:
+ var cell_position = Vector3(i * cell_width, 0.0, j * cell_width) + shift
+ _create_cell(i, j, cell_position)
+
+
+func _create_cell(i: int, j: int, position: Vector3):
+ var cell := Area3D.new()
+ cell.position = position
+ cell.name = "GridCell %s %s" % [i, j]
+
+ if collide_with_areas:
+ cell.area_entered.connect(_on_cell_area_entered.bind(i, j))
+ cell.area_exited.connect(_on_cell_area_exited.bind(i, j))
+
+ if collide_with_bodies:
+ cell.body_entered.connect(_on_cell_body_entered.bind(i, j))
+ cell.body_exited.connect(_on_cell_body_exited.bind(i, j))
+
+# cell.body_shape_entered.connect(_on_cell_body_shape_entered.bind(i, j))
+# cell.body_shape_exited.connect(_on_cell_body_shape_exited.bind(i, j))
+
+ cell.collision_layer = 0
+ cell.collision_mask = detection_mask
+ cell.monitorable = true
+ cell.input_ray_pickable = false
+ add_child(cell)
+ cell.set_owner(get_tree().edited_scene_root)
+
+ var col_shape := CollisionShape3D.new()
+ col_shape.shape = _box_shape
+ col_shape.name = "CollisionShape3D"
+ cell.add_child(col_shape)
+ col_shape.set_owner(get_tree().edited_scene_root)
+
+ if debug_view:
+ var box = MeshInstance3D.new()
+ box.name = "MeshInstance3D"
+ var box_mesh = BoxMesh.new()
+
+ box_mesh.set_size(Vector3(cell_width, cell_height, cell_width))
+ box_mesh.material = _standard_box_material
+
+ box.mesh = box_mesh
+ cell.add_child(box)
+ box.set_owner(get_tree().edited_scene_root)
+
+
+func _update_obs(cell_i: int, cell_j: int, collision_layer: int, entered: bool):
+ for key in _collision_mapping:
+ var bit_mask = 2 ** key
+ if (collision_layer & bit_mask) > 0:
+ var collison_map_index = _collision_mapping[key]
+
+ var obs_index = (
+ (cell_i * grid_size_x * _n_layers_per_cell)
+ + (cell_j * _n_layers_per_cell)
+ + collison_map_index
+ )
+ #prints(obs_index, cell_i, cell_j)
+ if entered:
+ _obs_buffer[obs_index] += 1
+ else:
+ _obs_buffer[obs_index] -= 1
+
+
+func _toggle_cell(cell_i: int, cell_j: int):
+ var cell = get_node_or_null("GridCell %s %s" % [cell_i, cell_j])
+
+ if cell == null:
+ print("cell not found, returning")
+
+ var n_hits = 0
+ var start_index = (cell_i * grid_size_x * _n_layers_per_cell) + (cell_j * _n_layers_per_cell)
+ for i in _n_layers_per_cell:
+ n_hits += _obs_buffer[start_index + i]
+
+ var cell_mesh = cell.get_node_or_null("MeshInstance3D")
+ if n_hits > 0:
+ cell_mesh.mesh.material = _highlighted_box_material
+ else:
+ cell_mesh.mesh.material = _standard_box_material
+
+
+func _on_cell_area_entered(area: Area3D, cell_i: int, cell_j: int):
+ #prints("_on_cell_area_entered", cell_i, cell_j)
+ _update_obs(cell_i, cell_j, area.collision_layer, true)
+ if debug_view:
+ _toggle_cell(cell_i, cell_j)
+ #print(_obs_buffer)
+
+
+func _on_cell_area_exited(area: Area3D, cell_i: int, cell_j: int):
+ #prints("_on_cell_area_exited", cell_i, cell_j)
+ _update_obs(cell_i, cell_j, area.collision_layer, false)
+ if debug_view:
+ _toggle_cell(cell_i, cell_j)
+
+
+func _on_cell_body_entered(body: Node3D, cell_i: int, cell_j: int):
+ #prints("_on_cell_body_entered", cell_i, cell_j)
+ _update_obs(cell_i, cell_j, body.collision_layer, true)
+ if debug_view:
+ _toggle_cell(cell_i, cell_j)
+
+
+func _on_cell_body_exited(body: Node3D, cell_i: int, cell_j: int):
+ #prints("_on_cell_body_exited", cell_i, cell_j)
+ _update_obs(cell_i, cell_j, body.collision_layer, false)
+ if debug_view:
+ _toggle_cell(cell_i, cell_j)
diff --git a/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/sensors/sensors_3d/ISensor3D.gd b/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/sensors/sensors_3d/ISensor3D.gd
new file mode 100644
index 0000000000000000000000000000000000000000..aca3c2db480c5f61058d565ae4652916af4c51ad
--- /dev/null
+++ b/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/sensors/sensors_3d/ISensor3D.gd
@@ -0,0 +1,25 @@
+extends Node3D
+class_name ISensor3D
+
+var _obs: Array = []
+var _active := false
+
+
+func get_observation():
+ pass
+
+
+func activate():
+ _active = true
+
+
+func deactivate():
+ _active = false
+
+
+func _update_observation():
+ pass
+
+
+func reset():
+ pass
diff --git a/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.gd b/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.gd
new file mode 100644
index 0000000000000000000000000000000000000000..1037e970c3dccd26c6b987533115d12fca790549
--- /dev/null
+++ b/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.gd
@@ -0,0 +1,21 @@
+extends Node3D
+class_name RGBCameraSensor3D
+var camera_pixels = null
+
+@onready var camera_texture := $Control/TextureRect/CameraTexture as Sprite2D
+@onready var sub_viewport := $SubViewport as SubViewport
+
+
+func get_camera_pixel_encoding():
+ return camera_texture.get_texture().get_image().get_data().hex_encode()
+
+
+func get_camera_shape() -> Array:
+ assert(
+ sub_viewport.size.x >= 36 and sub_viewport.size.y >= 36,
+ "SubViewport size must be 36x36 or larger."
+ )
+ if sub_viewport.transparent_bg:
+ return [4, sub_viewport.size.y, sub_viewport.size.x]
+ else:
+ return [3, sub_viewport.size.y, sub_viewport.size.x]
diff --git a/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.tscn b/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.tscn
new file mode 100644
index 0000000000000000000000000000000000000000..052b5577db16ab7d25f5f473a539b3099f400db8
--- /dev/null
+++ b/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.tscn
@@ -0,0 +1,41 @@
+[gd_scene load_steps=3 format=3 uid="uid://baaywi3arsl2m"]
+
+[ext_resource type="Script" path="res://addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.gd" id="1"]
+
+[sub_resource type="ViewportTexture" id="1"]
+viewport_path = NodePath("SubViewport")
+
+[node name="RGBCameraSensor3D" type="Node3D"]
+script = ExtResource("1")
+
+[node name="RemoteTransform3D" type="RemoteTransform3D" parent="."]
+remote_path = NodePath("../SubViewport/Camera3D")
+
+[node name="SubViewport" type="SubViewport" parent="."]
+size = Vector2i(32, 32)
+render_target_update_mode = 3
+
+[node name="Camera3D" type="Camera3D" parent="SubViewport"]
+near = 0.5
+
+[node name="Control" type="Control" parent="."]
+layout_mode = 3
+anchors_preset = 15
+anchor_right = 1.0
+anchor_bottom = 1.0
+grow_horizontal = 2
+grow_vertical = 2
+
+[node name="TextureRect" type="ColorRect" parent="Control"]
+layout_mode = 0
+offset_left = 1096.0
+offset_top = 534.0
+offset_right = 1114.0
+offset_bottom = 552.0
+scale = Vector2(10, 10)
+color = Color(0.00784314, 0.00784314, 0.00784314, 1)
+
+[node name="CameraTexture" type="Sprite2D" parent="Control/TextureRect"]
+texture = SubResource("1")
+offset = Vector2(9, 9)
+flip_v = true
diff --git a/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd b/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd
new file mode 100644
index 0000000000000000000000000000000000000000..1357529f9232c3323316212cc84042bde1afb6f2
--- /dev/null
+++ b/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd
@@ -0,0 +1,185 @@
+@tool
+extends ISensor3D
+class_name RayCastSensor3D
+@export_flags_3d_physics var collision_mask = 1:
+ get:
+ return collision_mask
+ set(value):
+ collision_mask = value
+ _update()
+@export_flags_3d_physics var boolean_class_mask = 1:
+ get:
+ return boolean_class_mask
+ set(value):
+ boolean_class_mask = value
+ _update()
+
+@export var n_rays_width := 6.0:
+ get:
+ return n_rays_width
+ set(value):
+ n_rays_width = value
+ _update()
+
+@export var n_rays_height := 6.0:
+ get:
+ return n_rays_height
+ set(value):
+ n_rays_height = value
+ _update()
+
+@export var ray_length := 10.0:
+ get:
+ return ray_length
+ set(value):
+ ray_length = value
+ _update()
+
+@export var cone_width := 60.0:
+ get:
+ return cone_width
+ set(value):
+ cone_width = value
+ _update()
+
+@export var cone_height := 60.0:
+ get:
+ return cone_height
+ set(value):
+ cone_height = value
+ _update()
+
+@export var collide_with_areas := false:
+ get:
+ return collide_with_areas
+ set(value):
+ collide_with_areas = value
+ _update()
+
+@export var collide_with_bodies := true:
+ get:
+ return collide_with_bodies
+ set(value):
+ collide_with_bodies = value
+ _update()
+
+@export var class_sensor := false
+
+var rays := []
+var geo = null
+
+
+func _update():
+ if Engine.is_editor_hint():
+ if is_node_ready():
+ _spawn_nodes()
+
+
+func _ready() -> void:
+ if Engine.is_editor_hint():
+ if get_child_count() == 0:
+ _spawn_nodes()
+ else:
+ _spawn_nodes()
+
+
+func _spawn_nodes():
+ print("spawning nodes")
+ for ray in get_children():
+ ray.queue_free()
+ if geo:
+ geo.clear()
+ #$Lines.remove_points()
+ rays = []
+
+ var horizontal_step = cone_width / (n_rays_width)
+ var vertical_step = cone_height / (n_rays_height)
+
+ var horizontal_start = horizontal_step / 2 - cone_width / 2
+ var vertical_start = vertical_step / 2 - cone_height / 2
+
+ var points = []
+
+ for i in n_rays_width:
+ for j in n_rays_height:
+ var angle_w = horizontal_start + i * horizontal_step
+ var angle_h = vertical_start + j * vertical_step
+ #angle_h = 0.0
+ var ray = RayCast3D.new()
+ var cast_to = to_spherical_coords(ray_length, angle_w, angle_h)
+ ray.set_target_position(cast_to)
+
+ points.append(cast_to)
+
+ ray.set_name("node_" + str(i) + " " + str(j))
+ ray.enabled = true
+ ray.collide_with_bodies = collide_with_bodies
+ ray.collide_with_areas = collide_with_areas
+ ray.collision_mask = collision_mask
+ add_child(ray)
+ ray.set_owner(get_tree().edited_scene_root)
+ rays.append(ray)
+ ray.force_raycast_update()
+
+
+# if Engine.editor_hint:
+# _create_debug_lines(points)
+
+
+func _create_debug_lines(points):
+ if not geo:
+ geo = ImmediateMesh.new()
+ add_child(geo)
+
+ geo.clear()
+ geo.begin(Mesh.PRIMITIVE_LINES)
+ for point in points:
+ geo.set_color(Color.AQUA)
+ geo.add_vertex(Vector3.ZERO)
+ geo.add_vertex(point)
+ geo.end()
+
+
+func display():
+ if geo:
+ geo.display()
+
+
+func to_spherical_coords(r, inc, azimuth) -> Vector3:
+ return Vector3(
+ r * sin(deg_to_rad(inc)) * cos(deg_to_rad(azimuth)),
+ r * sin(deg_to_rad(azimuth)),
+ r * cos(deg_to_rad(inc)) * cos(deg_to_rad(azimuth))
+ )
+
+
+func get_observation() -> Array:
+ return self.calculate_raycasts()
+
+
+func calculate_raycasts() -> Array:
+ var result = []
+ for ray in rays:
+ ray.set_enabled(true)
+ ray.force_raycast_update()
+ var distance = _get_raycast_distance(ray)
+
+ result.append(distance)
+ if class_sensor:
+ var hit_class: float = 0
+ if ray.get_collider():
+ var hit_collision_layer = ray.get_collider().collision_layer
+ hit_collision_layer = hit_collision_layer & collision_mask
+ hit_class = (hit_collision_layer & boolean_class_mask) > 0
+ result.append(float(hit_class))
+ ray.set_enabled(false)
+ return result
+
+
+func _get_raycast_distance(ray: RayCast3D) -> float:
+ if !ray.is_colliding():
+ return 0.0
+
+ var distance = (global_transform.origin - ray.get_collision_point()).length()
+ distance = clamp(distance, 0.0, ray_length)
+ return (ray_length - distance) / ray_length
diff --git a/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.tscn b/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.tscn
new file mode 100644
index 0000000000000000000000000000000000000000..35f9796596b2fb79bfcfe31e3d3a9637d9008e55
--- /dev/null
+++ b/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.tscn
@@ -0,0 +1,27 @@
+[gd_scene load_steps=2 format=3 uid="uid://b803cbh1fmy66"]
+
+[ext_resource type="Script" path="res://addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd" id="1"]
+
+[node name="RaycastSensor3D" type="Node3D"]
+script = ExtResource("1")
+n_rays_width = 4.0
+n_rays_height = 2.0
+ray_length = 11.0
+
+[node name="node_1 0" type="RayCast3D" parent="."]
+target_position = Vector3(-1.38686, -2.84701, 10.5343)
+
+[node name="node_1 1" type="RayCast3D" parent="."]
+target_position = Vector3(-1.38686, 2.84701, 10.5343)
+
+[node name="node_2 0" type="RayCast3D" parent="."]
+target_position = Vector3(1.38686, -2.84701, 10.5343)
+
+[node name="node_2 1" type="RayCast3D" parent="."]
+target_position = Vector3(1.38686, 2.84701, 10.5343)
+
+[node name="node_3 0" type="RayCast3D" parent="."]
+target_position = Vector3(4.06608, -2.84701, 9.81639)
+
+[node name="node_3 1" type="RayCast3D" parent="."]
+target_position = Vector3(4.06608, 2.84701, 9.81639)
diff --git a/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/sync.gd b/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/sync.gd
new file mode 100644
index 0000000000000000000000000000000000000000..77a2cbf6abcb5093ff0c9863999a3238bd22a166
--- /dev/null
+++ b/SimpleReachGoal/CSharpAll/addons/godot_rl_agents/sync.gd
@@ -0,0 +1,549 @@
+extends Node
+
+# --fixed-fps 2000 --disable-render-loop
+
+enum ControlModes { HUMAN, TRAINING, ONNX_INFERENCE }
+enum AgentControlModes { INHERIT_FROM_SYNC, HUMAN, TRAINING, ONNX_INFERENCE, RECORD_EXPERT_DEMOS }
+@export var control_mode: ControlModes = ControlModes.TRAINING
+@export_range(1, 10, 1, "or_greater") var action_repeat := 8
+@export_range(0, 10, 0.1, "or_greater") var speed_up := 1.0
+@export var onnx_model_path := ""
+
+# Onnx model stored for each requested path
+var onnx_models: Dictionary
+
+@onready var start_time = Time.get_ticks_msec()
+
+const MAJOR_VERSION := "0"
+const MINOR_VERSION := "7"
+const DEFAULT_PORT := "11008"
+const DEFAULT_SEED := "1"
+var stream: StreamPeerTCP = null
+var connected = false
+var message_center
+var should_connect = true
+
+var all_agents: Array
+var agents_training: Array
+var agents_inference: Array
+var agents_heuristic: Array
+
+## For recording expert demos
+var agent_demo_record: Node
+## File path for writing recorded trajectories
+var expert_demo_save_path: String
+## Stores recorded trajectories
+var demo_trajectories: Array
+## A trajectory includes obs: Array, acts: Array, terminal (set in Python env instead)
+var current_demo_trajectory: Array
+
+var need_to_send_obs = false
+var args = null
+var initialized = false
+var just_reset = false
+var onnx_model = null
+var n_action_steps = 0
+
+var _action_space: Dictionary
+var _action_space_inference: Array[Dictionary] = []
+var _obs_space: Dictionary
+
+
+# Called when the node enters the scene tree for the first time.
+func _ready():
+ await get_tree().root.ready
+ get_tree().set_pause(true)
+ _initialize()
+ await get_tree().create_timer(1.0).timeout
+ get_tree().set_pause(false)
+
+
+func _initialize():
+ _get_agents()
+ args = _get_args()
+ Engine.physics_ticks_per_second = _get_speedup() * 60 # Replace with function body.
+ Engine.time_scale = _get_speedup() * 1.0
+ prints(
+ "physics ticks",
+ Engine.physics_ticks_per_second,
+ Engine.time_scale,
+ _get_speedup(),
+ speed_up
+ )
+
+ _set_heuristic("human", all_agents)
+
+ _initialize_training_agents()
+ _initialize_inference_agents()
+ _initialize_demo_recording()
+
+ _set_seed()
+ _set_action_repeat()
+ initialized = true
+
+
+func _initialize_training_agents():
+ if agents_training.size() > 0:
+ _obs_space = agents_training[0].get_obs_space()
+ _action_space = agents_training[0].get_action_space()
+ connected = connect_to_server()
+ if connected:
+ _set_heuristic("model", agents_training)
+ _handshake()
+ _send_env_info()
+ else:
+ push_warning(
+ "Couldn't connect to Python server, using human controls instead. ",
+ "Did you start the training server using e.g. `gdrl` from the console?"
+ )
+
+
+func _initialize_inference_agents():
+ if agents_inference.size() > 0:
+ if control_mode == ControlModes.ONNX_INFERENCE:
+ assert(
+ FileAccess.file_exists(onnx_model_path),
+ "Onnx Model Path set on Sync node does not exist: %s" % onnx_model_path
+ )
+ onnx_models[onnx_model_path] = ONNXModel.new(onnx_model_path, 1)
+
+ for agent in agents_inference:
+ _action_space_inference.append(agent.get_action_space())
+
+ var agent_onnx_model: ONNXModel
+ if agent.onnx_model_path.is_empty():
+ assert(
+ onnx_models.has(onnx_model_path),
+ (
+ "Node %s has no onnx model path set " % agent.get_path()
+ + "and sync node's control mode is not set to OnnxInference. "
+ + "Either add the path to the AIController, "
+ + "or if you want to use the path set on sync node instead, "
+ + "set control mode to OnnxInference."
+ )
+ )
+ prints(
+ "Info: AIController %s" % agent.get_path(),
+ "has no onnx model path set.",
+ "Using path set on the sync node instead."
+ )
+ agent_onnx_model = onnx_models[onnx_model_path]
+ else:
+ if not onnx_models.has(agent.onnx_model_path):
+ assert(
+ FileAccess.file_exists(agent.onnx_model_path),
+ (
+ "Onnx Model Path set on %s node does not exist: %s"
+ % [agent.get_path(), agent.onnx_model_path]
+ )
+ )
+ onnx_models[agent.onnx_model_path] = ONNXModel.new(agent.onnx_model_path, 1)
+ agent_onnx_model = onnx_models[agent.onnx_model_path]
+
+ agent.onnx_model = agent_onnx_model
+ _set_heuristic("model", agents_inference)
+
+
+func _initialize_demo_recording():
+ if agent_demo_record:
+ expert_demo_save_path = agent_demo_record.expert_demo_save_path
+ assert(
+ not expert_demo_save_path.is_empty(),
+ "Expert demo save path set in %s is empty." % agent_demo_record.get_path()
+ )
+
+ InputMap.add_action("RemoveLastDemoEpisode")
+ InputMap.action_add_event(
+ "RemoveLastDemoEpisode", agent_demo_record.remove_last_episode_key
+ )
+ current_demo_trajectory.resize(2)
+ current_demo_trajectory[0] = []
+ current_demo_trajectory[1] = []
+ agent_demo_record.heuristic = "demo_record"
+
+
+func _physics_process(_delta):
+ # two modes, human control, agent control
+ # pause tree, send obs, get actions, set actions, unpause tree
+
+ _demo_record_process()
+
+ if n_action_steps % action_repeat != 0:
+ n_action_steps += 1
+ return
+
+ n_action_steps += 1
+
+ _training_process()
+ _inference_process()
+ _heuristic_process()
+
+
+func _training_process():
+ if connected:
+ get_tree().set_pause(true)
+
+ if just_reset:
+ just_reset = false
+ var obs = _get_obs_from_agents(agents_training)
+
+ var reply = {"type": "reset", "obs": obs}
+ _send_dict_as_json_message(reply)
+ # this should go straight to getting the action and setting it checked the agent, no need to perform one phyics tick
+ get_tree().set_pause(false)
+ return
+
+ if need_to_send_obs:
+ need_to_send_obs = false
+ var reward = _get_reward_from_agents()
+ var done = _get_done_from_agents()
+ #_reset_agents_if_done() # this ensures the new observation is from the next env instance : NEEDS REFACTOR
+
+ var obs = _get_obs_from_agents(agents_training)
+
+ var reply = {"type": "step", "obs": obs, "reward": reward, "done": done}
+ _send_dict_as_json_message(reply)
+
+ var handled = handle_message()
+
+
+func _inference_process():
+ if agents_inference.size() > 0:
+ var obs: Array = _get_obs_from_agents(agents_inference)
+ var actions = []
+
+ for agent_id in range(0, agents_inference.size()):
+ var action = agents_inference[agent_id].onnx_model.run_inference(
+ obs[agent_id]["obs"], 1.0
+ )
+ action["output"] = clamp_array(action["output"], -1.0, 1.0)
+ var action_dict = _extract_action_dict(
+ action["output"], _action_space_inference[agent_id]
+ )
+ actions.append(action_dict)
+
+ _set_agent_actions(actions, agents_inference)
+ _reset_agents_if_done(agents_inference)
+ get_tree().set_pause(false)
+
+
+func _demo_record_process():
+ if not agent_demo_record:
+ return
+
+ if Input.is_action_just_pressed("RemoveLastDemoEpisode"):
+ print("[Sync script][Demo recorder] Removing last recorded episode.")
+ demo_trajectories.remove_at(demo_trajectories.size() - 1)
+ print("Remaining episode count: %d" % demo_trajectories.size())
+
+ if n_action_steps % agent_demo_record.action_repeat != 0:
+ return
+
+ var obs_dict: Dictionary = agent_demo_record.get_obs()
+
+ # Get the current obs from the agent
+ assert(
+ obs_dict.has("obs"),
+ "Demo recorder needs an 'obs' key in get_obs() returned dictionary to record obs from."
+ )
+ current_demo_trajectory[0].append(obs_dict.obs)
+
+ # Get the action applied for the current obs from the agent
+ agent_demo_record.set_action()
+ var acts = agent_demo_record.get_action()
+
+ var terminal = agent_demo_record.get_done()
+ # Record actions only for non-terminal states
+ if terminal:
+ agent_demo_record.set_done_false()
+ else:
+ current_demo_trajectory[1].append(acts)
+
+ if terminal:
+ #current_demo_trajectory[2].append(true)
+ demo_trajectories.append(current_demo_trajectory.duplicate(true))
+ print("[Sync script][Demo recorder] Recorded episode count: %d" % demo_trajectories.size())
+ current_demo_trajectory[0].clear()
+ current_demo_trajectory[1].clear()
+
+
+func _heuristic_process():
+ for agent in agents_heuristic:
+ _reset_agents_if_done(agents_heuristic)
+
+
+func _extract_action_dict(action_array: Array, action_space: Dictionary):
+ var index = 0
+ var result = {}
+ for key in action_space.keys():
+ var size = action_space[key]["size"]
+ if action_space[key]["action_type"] == "discrete":
+ result[key] = round(action_array[index])
+ else:
+ result[key] = action_array.slice(index, index + size)
+ index += size
+
+ return result
+
+
+## For AIControllers that inherit mode from sync, sets the correct mode.
+func _set_agent_mode(agent: Node):
+ var agent_inherits_mode: bool = agent.control_mode == AgentControlModes.INHERIT_FROM_SYNC
+
+ if agent_inherits_mode:
+ match control_mode:
+ ControlModes.HUMAN:
+ agent.control_mode = AgentControlModes.HUMAN
+ ControlModes.TRAINING:
+ agent.control_mode = AgentControlModes.TRAINING
+ ControlModes.ONNX_INFERENCE:
+ agent.control_mode = AgentControlModes.ONNX_INFERENCE
+
+
+func _get_agents():
+ all_agents = get_tree().get_nodes_in_group("AGENT")
+ for agent in all_agents:
+ _set_agent_mode(agent)
+
+ if agent.control_mode == AgentControlModes.TRAINING:
+ agents_training.append(agent)
+ elif agent.control_mode == AgentControlModes.ONNX_INFERENCE:
+ agents_inference.append(agent)
+ elif agent.control_mode == AgentControlModes.HUMAN:
+ agents_heuristic.append(agent)
+ elif agent.control_mode == AgentControlModes.RECORD_EXPERT_DEMOS:
+ assert(
+ not agent_demo_record,
+ "Currently only a single AIController can be used for recording expert demos."
+ )
+ agent_demo_record = agent
+
+
+func _set_heuristic(heuristic, agents: Array):
+ for agent in agents:
+ agent.set_heuristic(heuristic)
+
+
+func _handshake():
+ print("performing handshake")
+
+ var json_dict = _get_dict_json_message()
+ assert(json_dict["type"] == "handshake")
+ var major_version = json_dict["major_version"]
+ var minor_version = json_dict["minor_version"]
+ if major_version != MAJOR_VERSION:
+ print("WARNING: major verison mismatch ", major_version, " ", MAJOR_VERSION)
+ if minor_version != MINOR_VERSION:
+ print("WARNING: minor verison mismatch ", minor_version, " ", MINOR_VERSION)
+
+ print("handshake complete")
+
+
+func _get_dict_json_message():
+ # returns a dictionary from of the most recent message
+ # this is not waiting
+ while stream.get_available_bytes() == 0:
+ stream.poll()
+ if stream.get_status() != 2:
+ print("server disconnected status, closing")
+ get_tree().quit()
+ return null
+
+ OS.delay_usec(10)
+
+ var message = stream.get_string()
+ var json_data = JSON.parse_string(message)
+
+ return json_data
+
+
+func _send_dict_as_json_message(dict):
+ stream.put_string(JSON.stringify(dict, "", false))
+
+
+func _send_env_info():
+ var json_dict = _get_dict_json_message()
+ assert(json_dict["type"] == "env_info")
+
+ var message = {
+ "type": "env_info",
+ "observation_space": _obs_space,
+ "action_space": _action_space,
+ "n_agents": len(agents_training)
+ }
+ _send_dict_as_json_message(message)
+
+
+func connect_to_server():
+ print("Waiting for one second to allow server to start")
+ OS.delay_msec(1000)
+ print("trying to connect to server")
+ stream = StreamPeerTCP.new()
+
+ # "localhost" was not working on windows VM, had to use the IP
+ var ip = "127.0.0.1"
+ var port = _get_port()
+ var connect = stream.connect_to_host(ip, port)
+ stream.set_no_delay(true) # TODO check if this improves performance or not
+ stream.poll()
+ # Fetch the status until it is either connected (2) or failed to connect (3)
+ while stream.get_status() < 2:
+ stream.poll()
+ return stream.get_status() == 2
+
+
+func _get_args():
+ print("getting command line arguments")
+ var arguments = {}
+ for argument in OS.get_cmdline_args():
+ print(argument)
+ if argument.find("=") > -1:
+ var key_value = argument.split("=")
+ arguments[key_value[0].lstrip("--")] = key_value[1]
+ else:
+ # Options without an argument will be present in the dictionary,
+ # with the value set to an empty string.
+ arguments[argument.lstrip("--")] = ""
+
+ return arguments
+
+
+func _get_speedup():
+ print(args)
+ return args.get("speedup", str(speed_up)).to_float()
+
+
+func _get_port():
+ return args.get("port", DEFAULT_PORT).to_int()
+
+
+func _set_seed():
+ var _seed = args.get("env_seed", DEFAULT_SEED).to_int()
+ seed(_seed)
+
+
+func _set_action_repeat():
+ action_repeat = args.get("action_repeat", str(action_repeat)).to_int()
+
+
+func disconnect_from_server():
+ stream.disconnect_from_host()
+
+
+func handle_message() -> bool:
+ # get json message: reset, step, close
+ var message = _get_dict_json_message()
+ if message["type"] == "close":
+ print("received close message, closing game")
+ get_tree().quit()
+ get_tree().set_pause(false)
+ return true
+
+ if message["type"] == "reset":
+ print("resetting all agents")
+ _reset_agents()
+ just_reset = true
+ get_tree().set_pause(false)
+ #print("resetting forcing draw")
+# RenderingServer.force_draw()
+# var obs = _get_obs_from_agents()
+# print("obs ", obs)
+# var reply = {
+# "type": "reset",
+# "obs": obs
+# }
+# _send_dict_as_json_message(reply)
+ return true
+
+ if message["type"] == "call":
+ var method = message["method"]
+ var returns = _call_method_on_agents(method)
+ var reply = {"type": "call", "returns": returns}
+ print("calling method from Python")
+ _send_dict_as_json_message(reply)
+ return handle_message()
+
+ if message["type"] == "action":
+ var action = message["action"]
+ _set_agent_actions(action, agents_training)
+ need_to_send_obs = true
+ get_tree().set_pause(false)
+ return true
+
+ print("message was not handled")
+ return false
+
+
+func _call_method_on_agents(method):
+ var returns = []
+ for agent in all_agents:
+ returns.append(agent.call(method))
+
+ return returns
+
+
+func _reset_agents_if_done(agents = all_agents):
+ for agent in agents:
+ if agent.get_done():
+ agent.set_done_false()
+
+
+func _reset_agents(agents = all_agents):
+ for agent in agents:
+ agent.needs_reset = true
+ #agent.reset()
+
+
+func _get_obs_from_agents(agents: Array = all_agents):
+ var obs = []
+ for agent in agents:
+ obs.append(agent.get_obs())
+ return obs
+
+
+func _get_reward_from_agents(agents: Array = agents_training):
+ var rewards = []
+ for agent in agents:
+ rewards.append(agent.get_reward())
+ agent.zero_reward()
+ return rewards
+
+
+func _get_done_from_agents(agents: Array = agents_training):
+ var dones = []
+ for agent in agents:
+ var done = agent.get_done()
+ if done:
+ agent.set_done_false()
+ dones.append(done)
+ return dones
+
+
+func _set_agent_actions(actions, agents: Array = all_agents):
+ for i in range(len(actions)):
+ agents[i].set_action(actions[i])
+
+
+func clamp_array(arr: Array, min: float, max: float):
+ var output: Array = []
+ for a in arr:
+ output.append(clamp(a, min, max))
+ return output
+
+
+## Save recorded export demos on window exit (Close game window instead of "Stop" button in Godot Editor)
+func _notification(what):
+ if demo_trajectories.size() == 0 or expert_demo_save_path.is_empty():
+ return
+
+ if what == NOTIFICATION_PREDELETE:
+ var json_string = JSON.stringify(demo_trajectories, "", false)
+ var file = FileAccess.open(expert_demo_save_path, FileAccess.WRITE)
+
+ if not file:
+ var error: Error = FileAccess.get_open_error()
+ assert(not error, "There was an error opening the file: %d" % error)
+
+ file.store_line(json_string)
+ var error = file.get_error()
+ assert(not error, "There was an error after trying to write to the file: %d" % error)
diff --git a/SimpleReachGoal/CSharpAll/icon.svg b/SimpleReachGoal/CSharpAll/icon.svg
new file mode 100644
index 0000000000000000000000000000000000000000..b370ceb72740b9a759fe11b364f0d4de27df42f8
--- /dev/null
+++ b/SimpleReachGoal/CSharpAll/icon.svg
@@ -0,0 +1 @@
+
diff --git a/SimpleReachGoal/CSharpAll/project.godot b/SimpleReachGoal/CSharpAll/project.godot
new file mode 100644
index 0000000000000000000000000000000000000000..a901e02ac6ff78da5143df2b6c934baa8e8b4b64
--- /dev/null
+++ b/SimpleReachGoal/CSharpAll/project.godot
@@ -0,0 +1,24 @@
+; Engine configuration file.
+; It's best edited using the editor UI and not directly,
+; since the parameters that go here are not all obvious.
+;
+; Format:
+; [section] ; section goes between []
+; param=value ; assign values to parameters
+
+config_version=5
+
+[application]
+
+config/name="SimpleReachGoal"
+run/main_scene="res://scenes/training_scene/training_scene.tscn"
+config/features=PackedStringArray("4.3", "C#", "Forward Plus")
+config/icon="res://icon.svg"
+
+[dotnet]
+
+project/assembly_name="SimpleReachGoal"
+
+[editor_plugins]
+
+enabled=PackedStringArray("res://addons/godot_rl_agents/plugin.cfg")
diff --git a/SimpleReachGoal/CSharpAll/scenes/game_scene/AreaPositionRandomizer.cs b/SimpleReachGoal/CSharpAll/scenes/game_scene/AreaPositionRandomizer.cs
new file mode 100644
index 0000000000000000000000000000000000000000..1d7ee4345e803f404988a501265be8c39921fa47
--- /dev/null
+++ b/SimpleReachGoal/CSharpAll/scenes/game_scene/AreaPositionRandomizer.cs
@@ -0,0 +1,31 @@
+using Godot;
+using System.Collections.Generic;
+
+public partial class AreaPositionRandomizer : Node3D
+{
+ private Area3D area;
+ private readonly List areaSpawnPoints = new();
+
+ // Called when the node enters the scene tree for the first time.
+ public override void _Ready()
+ {
+ foreach (Node node in GetChildren())
+ {
+ if (node is Area3D areaNode)
+ {
+ area = areaNode;
+ }
+ else if (node is MeshInstance3D mesh)
+ {
+ areaSpawnPoints.Add(mesh);
+ mesh.Visible = false;
+ }
+ }
+ }
+
+ public void Reset()
+ {
+ Vector3 newAreaPosition = areaSpawnPoints[GD.RandRange(0, areaSpawnPoints.Count - 1)].GlobalPosition;
+ area.GlobalPosition = newAreaPosition;
+ }
+}
diff --git a/SimpleReachGoal/CSharpAll/scenes/game_scene/GameSceneManager.cs b/SimpleReachGoal/CSharpAll/scenes/game_scene/GameSceneManager.cs
new file mode 100644
index 0000000000000000000000000000000000000000..fd6c5aedf833bbb3644d747d07a1d2127ea7176b
--- /dev/null
+++ b/SimpleReachGoal/CSharpAll/scenes/game_scene/GameSceneManager.cs
@@ -0,0 +1,24 @@
+using Godot;
+
+public partial class GameSceneManager : Node3D
+{
+ [Export]
+ public AreaPositionRandomizer GoalManager { get; set; }
+ [Export]
+ public AreaPositionRandomizer ObstacleManager { get; set; }
+ [Export]
+ public Player Player { get; set; }
+
+ // Called when the node enters the scene tree for the first time.
+ public override void _Ready()
+ {
+ Reset();
+ }
+
+ public void Reset()
+ {
+ GoalManager.Reset();
+ ObstacleManager.Reset();
+ Player.Reset();
+ }
+}
diff --git a/SimpleReachGoal/CSharpAll/scenes/game_scene/game_scene.tscn b/SimpleReachGoal/CSharpAll/scenes/game_scene/game_scene.tscn
new file mode 100644
index 0000000000000000000000000000000000000000..861af28960442de0aebe9b54251c0ec77e632a6e
--- /dev/null
+++ b/SimpleReachGoal/CSharpAll/scenes/game_scene/game_scene.tscn
@@ -0,0 +1,190 @@
+[gd_scene load_steps=13 format=3 uid="uid://qofctg4fc0c2"]
+
+[ext_resource type="Script" path="res://scenes/game_scene/GameSceneManager.cs" id="1_cplta"]
+[ext_resource type="Script" path="res://scenes/game_scene/AreaPositionRandomizer.cs" id="2_x2fdq"]
+[ext_resource type="PackedScene" uid="uid://fhnd4o88w5p4" path="res://scenes/player/player.tscn" id="3_j13wo"]
+
+[sub_resource type="StandardMaterial3D" id="StandardMaterial3D_g301e"]
+transparency = 1
+albedo_color = Color(0, 1, 0.166667, 0.756863)
+
+[sub_resource type="BoxMesh" id="BoxMesh_wnjao"]
+
+[sub_resource type="BoxShape3D" id="BoxShape3D_mblpq"]
+
+[sub_resource type="StandardMaterial3D" id="StandardMaterial3D_irk0a"]
+transparency = 1
+albedo_color = Color(0, 1, 0.166667, 0.313726)
+
+[sub_resource type="StandardMaterial3D" id="StandardMaterial3D_t0cxi"]
+transparency = 1
+albedo_color = Color(1, 0, 0, 0.756863)
+
+[sub_resource type="StandardMaterial3D" id="StandardMaterial3D_qu1jy"]
+transparency = 1
+albedo_color = Color(1, 0, 0, 0.313726)
+
+[sub_resource type="StandardMaterial3D" id="StandardMaterial3D_1ahva"]
+albedo_color = Color(0.8, 0.8, 0.8, 1)
+
+[sub_resource type="BoxMesh" id="BoxMesh_eh8qq"]
+material = SubResource("StandardMaterial3D_1ahva")
+size = Vector3(10, 0.1, 10)
+
+[sub_resource type="BoxShape3D" id="BoxShape3D_wmgsa"]
+size = Vector3(10, 1, 10)
+
+[node name="GameScene" type="Node3D" node_paths=PackedStringArray("GoalManager", "ObstacleManager", "Player")]
+script = ExtResource("1_cplta")
+GoalManager = NodePath("GoalManager")
+ObstacleManager = NodePath("ObstacleManager")
+Player = NodePath("Player")
+
+[node name="GoalManager" type="Node3D" parent="."]
+script = ExtResource("2_x2fdq")
+
+[node name="Goal" type="Area3D" parent="GoalManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 4, 0.5, -4)
+collision_layer = 2
+monitorable = false
+
+[node name="MeshInstance3D" type="MeshInstance3D" parent="GoalManager/Goal"]
+material_override = SubResource("StandardMaterial3D_g301e")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="CollisionShape3D" type="CollisionShape3D" parent="GoalManager/Goal"]
+shape = SubResource("BoxShape3D_mblpq")
+
+[node name="SpawnPosition" type="MeshInstance3D" parent="GoalManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 4, 0.5, 4)
+material_override = SubResource("StandardMaterial3D_irk0a")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition2" type="MeshInstance3D" parent="GoalManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -4, 0.5, 4)
+material_override = SubResource("StandardMaterial3D_irk0a")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition3" type="MeshInstance3D" parent="GoalManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -4, 0.5, -4)
+material_override = SubResource("StandardMaterial3D_irk0a")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition4" type="MeshInstance3D" parent="GoalManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 4, 0.5, -4)
+material_override = SubResource("StandardMaterial3D_irk0a")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="ObstacleManager" type="Node3D" parent="."]
+script = ExtResource("2_x2fdq")
+
+[node name="Obstacle" type="Area3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 2, 0.5, -2)
+collision_layer = 4
+monitorable = false
+
+[node name="MeshInstance3D" type="MeshInstance3D" parent="ObstacleManager/Obstacle"]
+material_override = SubResource("StandardMaterial3D_t0cxi")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="CollisionShape3D" type="CollisionShape3D" parent="ObstacleManager/Obstacle"]
+shape = SubResource("BoxShape3D_mblpq")
+
+[node name="SpawnPosition" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0.5, -2)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition2" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0.5, 2)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition3" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 2, 0.5, 0)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition4" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -2, 0.5, 0)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition5" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -2, 0.5, -1)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition6" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -2, 0.5, -2)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition7" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -1, 0.5, -2)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition8" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0.5, -2)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition9" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 2, 0.5, -2)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition10" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 2, 0.5, -1)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition11" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 2, 0.5, 1)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition12" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 2, 0.5, 2)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition13" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0.5, 2)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition14" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -1, 0.5, 2)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition15" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -2, 0.5, 2)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition16" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -2, 0.5, 1)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="Ground" type="StaticBody3D" parent="."]
+
+[node name="MeshInstance3D" type="MeshInstance3D" parent="Ground"]
+mesh = SubResource("BoxMesh_eh8qq")
+skeleton = NodePath("../..")
+
+[node name="CollisionShape3D" type="CollisionShape3D" parent="Ground"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, -0.45, 0)
+shape = SubResource("BoxShape3D_wmgsa")
+
+[node name="Player" parent="." node_paths=PackedStringArray("GameSceneManager", "Goal", "Obstacle", "AIController") instance=ExtResource("3_j13wo")]
+GameSceneManager = NodePath("..")
+Goal = NodePath("../GoalManager/Goal")
+Obstacle = NodePath("../ObstacleManager/Obstacle")
+AIController = NodePath("AIController3D")
+
+[connection signal="body_entered" from="GoalManager/Goal" to="Player" method="OnGoalBodyEntered"]
+[connection signal="body_entered" from="ObstacleManager/Obstacle" to="Player" method="OnObstacleBodyEntered"]
diff --git a/SimpleReachGoal/CSharpAll/scenes/player/AIControllerSharp3D.cs b/SimpleReachGoal/CSharpAll/scenes/player/AIControllerSharp3D.cs
new file mode 100644
index 0000000000000000000000000000000000000000..90aef7f62402df0acefc74c9ffb2dc6f7a77cea5
--- /dev/null
+++ b/SimpleReachGoal/CSharpAll/scenes/player/AIControllerSharp3D.cs
@@ -0,0 +1,128 @@
+using System;
+using Godot;
+using Dictionary = Godot.Collections.Dictionary;
+using Array = Godot.Collections.Array;
+
+[GlobalClass]
+public abstract partial class AIControllerSharp3D : Node3D {
+ public enum ControlModes { INHERIT_FROM_SYNC, HUMAN, TRAINING, ONNX_INFERENCE, RECORD_EXPERT_DEMOS }
+ [Export] public ControlModes control_mode = ControlModes.INHERIT_FROM_SYNC;
+ [Export] public string onnx_model_path = "";
+ [Export] public int reset_after = 1000;
+
+ [ExportGroup("Record expert demos mode options")]
+ // Path where the demos will be saved. The file can later be used for imitation learning.
+ [Export] public String expert_demo_save_path;
+ // The action that erases the last recorded episode from the currently recorded data.
+ [Export] public InputEvent remove_last_episode_key;
+ // Action will be repeated for n frames. Will introduce control lag if larger than 1.
+ // Can be used to ensure that action_repeat on inference && training matches
+ // the recorded demonstrations.
+ [Export] public int action_repeat = 1;
+
+ [ExportGroup("Debug")]
+ [Export] protected bool DebugOn;
+
+ // ONNXModel GDScript object
+ public Resource onnx_model;
+ public string heuristic = "human";
+ public bool done;
+ public float reward;
+ public int n_steps;
+ public bool needs_reset;
+
+ public Node2D _player;
+
+ public override void _Ready() {
+ base._Ready();
+ AddToGroup("AGENT");
+ }
+
+ public virtual void init(Node2D player) {
+ if (DebugOn) GD.Print("Initializing AIController...");
+ _player = player;
+ }
+
+ public virtual float get_reward() {
+ return reward;
+ }
+
+ //-- Methods that need implementing using the "extend script" option in Godot --#
+
+ public abstract Dictionary get_obs();
+
+
+ public abstract Dictionary get_action_space();
+
+ public abstract void set_action(Dictionary action);
+
+ //-----------------------------------------------------------------------------#
+
+
+ //-- Methods that sometimes need implementing using the "extend script" option in Godot --#
+ // Only needed if you are recording expert demos with this AIController
+ public virtual Array get_action() {
+ throw new NotImplementedException();
+ }
+
+ // -----------------------------------------------------------------------------#
+
+ public override void _PhysicsProcess(double delta) {
+ base._PhysicsProcess(delta);
+ n_steps += 1;
+ if(n_steps > reset_after) {
+ if (DebugOn) GD.Print("Timeout reached. Setting 'needs_reset' to true.");
+ needs_reset = true;
+ }
+ }
+
+ public virtual Dictionary get_obs_space() {
+ // may need overriding if the obs space is complex
+ Dictionary obs = get_obs();
+ Array size = new Array
+ {
+ ((Array)obs["obs"]).Count
+ };
+ return new Dictionary()
+ {
+ {
+ "obs", new Dictionary()
+ {
+ { "size", size },
+ { "space", "box" }
+ }
+ }
+ };
+ }
+
+ public void reset() {
+ if (DebugOn) GD.Print("Resetting AIController...");
+ n_steps = 0;
+ needs_reset = false;
+ }
+
+ public void reset_if_done() {
+ if (DebugOn) GD.Print("Resetting if done...");
+ if(done) {
+ reset();
+ }
+ }
+
+ public void set_heuristic(String h) {
+ if (DebugOn) GD.Print("Setting heuristic...");
+ // sets the heuristic from "human" || "model" nothing to change here
+ heuristic = h;
+ }
+
+ public bool get_done() {
+ return done;
+ }
+
+ public void set_done_false() {
+ done = false;
+ }
+
+ public void zero_reward() {
+ reward = 0.0f;
+ }
+}
diff --git a/SimpleReachGoal/CSharpAll/scenes/player/Player.cs b/SimpleReachGoal/CSharpAll/scenes/player/Player.cs
new file mode 100644
index 0000000000000000000000000000000000000000..f128ae4fca8854f204720730fd177cf96fc4f77b
--- /dev/null
+++ b/SimpleReachGoal/CSharpAll/scenes/player/Player.cs
@@ -0,0 +1,91 @@
+using Godot;
+
+public partial class Player : CharacterBody3D
+{
+ [Export]
+ public GameSceneManager GameSceneManager { get; set; }
+ [Export]
+ public Area3D Goal { get; set; }
+ [Export]
+ public Area3D Obstacle { get; set; }
+ [Export]
+ public PlayerAIController AIController { get; set; }
+ [Export]
+ public float Speed { get => speed; set => speed = value; }
+ public Vector2 RequestedMovement { get; set; }
+
+ private float speed = 5f;
+ private Transform3D initialTransform;
+
+ public override void _Ready()
+ {
+ initialTransform = Transform;
+ }
+
+ public override void _PhysicsProcess(double delta)
+ {
+ if (!IsOnFloor())
+ {
+ Velocity += GetGravity() * (float)delta;
+ }
+
+ // If controlled by human, takes the keyboard arrows as input
+ // otherwise, requested_movement will be set by the AIController based on RL agent's output actions
+ if (AIController.heuristic == "human")
+ {
+ RequestedMovement = Input.GetVector("ui_left", "ui_right", "ui_up", "ui_down");
+ }
+
+ RequestedMovement = RequestedMovement.LimitLength(1f) * Speed;
+
+ Velocity = new(RequestedMovement.X, Velocity.Y, RequestedMovement.Y);
+
+ // We only move when the episode is not marked as done
+ // to prevent repeating a possibly wrong action from the previous episode.
+ // This is related to the sync node Action Repeat functionality,
+ // we don't get a new action for every physics step. This check may
+ // not be required for every env, and is not used in all examples.
+ if (!AIController.done)
+ {
+ MoveAndSlide();
+ }
+
+ ResetOnPlayerFalling();
+
+ }
+
+ // Resets the game if the player has fallen down
+ private void ResetOnPlayerFalling()
+ {
+ if (GlobalPosition.Y < -1.0)
+ {
+ GameOver(-1.0);
+ }
+ }
+
+ // Ends the game, setting an optional reward
+ private void GameOver(double reward)
+ {
+ AIController.reward += (float)reward;
+ GameSceneManager.Reset();
+ }
+
+ // Resets the player and AIController
+ public void Reset()
+ {
+ AIController.EndEpisode();
+ Transform = initialTransform;
+ }
+
+ // When the goal is entered, we restart the game with a positive reward
+ public void OnGoalBodyEntered(Node3D body)
+ {
+ GameOver(1.0);
+ }
+
+ // When the obstacle is entered, we restart the game with a negative reward
+ public void OnObstacleBodyEntered(Node3D body)
+ {
+ GameOver(-1.0);
+ }
+}
diff --git a/SimpleReachGoal/CSharpAll/scenes/player/PlayerAIController.cs b/SimpleReachGoal/CSharpAll/scenes/player/PlayerAIController.cs
new file mode 100644
index 0000000000000000000000000000000000000000..7997840ab29b3dc99a25877e3f999f0b73cdc124
--- /dev/null
+++ b/SimpleReachGoal/CSharpAll/scenes/player/PlayerAIController.cs
@@ -0,0 +1,66 @@
+using Godot;
+using Godot.Collections;
+using System;
+using Array = Godot.Collections.Array;
+using Dictionary = Godot.Collections.Dictionary;
+
+public partial class PlayerAIController : AIControllerSharp3D
+{
+ [Export]
+ public Player Player;
+
+ [Export]
+ public Array RayCastSensors;
+
+ public override void _PhysicsProcess(double delta) {
+ // Intentionally not calling base._PhysicsProcess(delta)
+ n_steps += 1;
+
+ if(n_steps > reset_after) {
+ if (DebugOn) GD.Print("Timeout reached. Setting 'needs_reset' to true.");
+ Player.GameSceneManager.Reset();
+ }
+ }
+
+ public void EndEpisode() {
+ done = true;
+ reset();
+ }
+
+ public override Dictionary get_obs() {
+ var obs = new Array();
+ foreach (var sensor in RayCastSensors) {
+ var sensorObs = (Array)sensor.Call("get_observation");
+ obs += sensorObs;
+ }
+
+ float levelSize = 10;
+ Vector3 relativeGoalPosition = Player.ToLocal(Player.Goal.GlobalPosition);
+ Vector3 relativeObstaclePosition = Player.ToLocal(Player.Obstacle.GlobalPosition);
+
+ obs += new Array {
+ relativeGoalPosition.X / levelSize,
+ relativeGoalPosition.Z / levelSize,
+ relativeObstaclePosition.X / levelSize,
+ relativeObstaclePosition.Z / levelSize
+ };
+
+ return new Dictionary {
+ { "obs", obs }
+ };
+ }
+
+ public override Dictionary get_action_space() {
+ return new Dictionary {
+ {"move_action", new Dictionary {
+ {"size", 2}, {"action_type", "continuous"}
+ }}
+ };
+ }
+
+ public override void set_action(Dictionary action) {
+ float x = (float)((Array) action["move_action"])[0];
+ float y = (float)((Array) action["move_action"])[1];
+ Player.RequestedMovement = new Vector2(x, y);
+ }
+}
diff --git a/SimpleReachGoal/CSharpAll/scenes/player/player.tscn b/SimpleReachGoal/CSharpAll/scenes/player/player.tscn
new file mode 100644
index 0000000000000000000000000000000000000000..5f04aa4a702c5be939661e78fc43bd291f59f14f
--- /dev/null
+++ b/SimpleReachGoal/CSharpAll/scenes/player/player.tscn
@@ -0,0 +1,497 @@
+[gd_scene load_steps=7 format=3 uid="uid://fhnd4o88w5p4"]
+
+[ext_resource type="Script" path="res://scenes/player/Player.cs" id="1_73fx5"]
+[ext_resource type="Script" path="res://scenes/player/PlayerAIController.cs" id="2_c1qwq"]
+[ext_resource type="Script" path="res://addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd" id="3_qsyok"]
+
+[sub_resource type="StandardMaterial3D" id="StandardMaterial3D_owc64"]
+albedo_color = Color(0.929563, 0.63943, 7.70092e-07, 1)
+
+[sub_resource type="CapsuleMesh" id="CapsuleMesh_jc5om"]
+material = SubResource("StandardMaterial3D_owc64")
+radius = 0.25
+height = 1.0
+
+[sub_resource type="CapsuleShape3D" id="CapsuleShape3D_2gph3"]
+radius = 0.25
+height = 1.0
+
+[node name="Player" type="CharacterBody3D"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0.5, 0)
+script = ExtResource("1_73fx5")
+
+[node name="MeshInstance3D" type="MeshInstance3D" parent="."]
+mesh = SubResource("CapsuleMesh_jc5om")
+skeleton = NodePath("../..")
+
+[node name="CollisionShape3D" type="CollisionShape3D" parent="."]
+shape = SubResource("CapsuleShape3D_2gph3")
+
+[node name="AIController3D" type="Node3D" parent="." node_paths=PackedStringArray("Player", "RayCastSensors")]
+script = ExtResource("2_c1qwq")
+Player = NodePath("..")
+RayCastSensors = [NodePath("GoalRaycastSensor"), NodePath("ObstacleRaycastSensor"), NodePath("GroundRaycastSensor")]
+
+[node name="GoalRaycastSensor" type="Node3D" parent="AIController3D"]
+script = ExtResource("3_qsyok")
+collision_mask = 2
+boolean_class_mask = 0
+n_rays_width = 32.0
+n_rays_height = 1.0
+cone_width = 360.0
+cone_height = 0.0
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_0 0" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-0.980171, 0, -9.95185)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_1 0" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-2.90285, 0, -9.5694)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_2 0" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-4.71397, 0, -8.81921)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_3 0" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-6.34393, 0, -7.7301)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_4 0" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-7.7301, 0, -6.34393)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_5 0" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-8.81921, 0, -4.71397)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57424" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-9.5694, 0, -2.90285)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57425" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-9.95185, 0, -0.980171)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57426" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-9.95185, 0, 0.980171)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57427" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-9.5694, 0, 2.90285)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57428" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-8.81921, 0, 4.71397)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57429" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-7.7301, 0, 6.34393)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_12 0" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-6.34393, 0, 7.7301)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_13 0" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-4.71397, 0, 8.81921)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_14 0" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-2.90285, 0, 9.5694)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_15 0" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-0.980171, 0, 9.95185)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57430" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(0.980171, 0, 9.95185)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57431" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(2.90285, 0, 9.5694)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57432" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(4.71397, 0, 8.81921)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57433" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(6.34393, 0, 7.7301)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57434" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(7.7301, 0, 6.34393)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57435" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(8.81921, 0, 4.71397)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57436" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(9.5694, 0, 2.90285)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57437" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(9.95185, 0, 0.980171)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57438" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(9.95185, 0, -0.980171)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57439" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(9.5694, 0, -2.90285)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57440" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(8.81921, 0, -4.71397)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57441" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(7.7301, 0, -6.34393)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57442" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(6.34393, 0, -7.7301)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57443" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(4.71397, 0, -8.81921)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57444" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(2.90285, 0, -9.5694)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57445" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(0.980171, 0, -9.95185)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="ObstacleRaycastSensor" type="Node3D" parent="AIController3D"]
+script = ExtResource("3_qsyok")
+collision_mask = 4
+boolean_class_mask = 0
+n_rays_width = 32.0
+n_rays_height = 1.0
+cone_width = 360.0
+cone_height = 0.0
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_0 0" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-0.980171, 0, -9.95185)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_1 0" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-2.90285, 0, -9.5694)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_2 0" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-4.71397, 0, -8.81921)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_3 0" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-6.34393, 0, -7.7301)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_4 0" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-7.7301, 0, -6.34393)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_5 0" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-8.81921, 0, -4.71397)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56972" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-9.5694, 0, -2.90285)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56973" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-9.95185, 0, -0.980171)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56974" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-9.95185, 0, 0.980171)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56975" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-9.5694, 0, 2.90285)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56976" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-8.81921, 0, 4.71397)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56977" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-7.7301, 0, 6.34393)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_12 0" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-6.34393, 0, 7.7301)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_13 0" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-4.71397, 0, 8.81921)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_14 0" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-2.90285, 0, 9.5694)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_15 0" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-0.980171, 0, 9.95185)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56978" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(0.980171, 0, 9.95185)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56979" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(2.90285, 0, 9.5694)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56980" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(4.71397, 0, 8.81921)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56981" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(6.34393, 0, 7.7301)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56982" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(7.7301, 0, 6.34393)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56983" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(8.81921, 0, 4.71397)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56984" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(9.5694, 0, 2.90285)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56985" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(9.95185, 0, 0.980171)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56986" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(9.95185, 0, -0.980171)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56987" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(9.5694, 0, -2.90285)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56988" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(8.81921, 0, -4.71397)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56989" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(7.7301, 0, -6.34393)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56990" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(6.34393, 0, -7.7301)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56991" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(4.71397, 0, -8.81921)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56992" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(2.90285, 0, -9.5694)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56993" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(0.980171, 0, -9.95185)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="GroundRaycastSensor" type="Node3D" parent="AIController3D"]
+transform = Transform3D(1, 0, 0, 0, -4.37114e-08, -1, 0, 1, -4.37114e-08, 0, 0, 0)
+script = ExtResource("3_qsyok")
+boolean_class_mask = 0
+n_rays_width = 4.0
+n_rays_height = 4.0
+ray_length = 2.0
+cone_width = 90.0
+cone_height = 90.0
+
+[node name="node_0 0" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(-0.92388, -1.11114, 1.38268)
+
+[node name="@RayCast3D@24718" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(-1.08979, -0.390181, 1.63099)
+
+[node name="@RayCast3D@24719" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(-1.08979, 0.390181, 1.63099)
+
+[node name="@RayCast3D@24720" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(-0.92388, 1.11114, 1.38268)
+
+[node name="node_1 0" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(-0.324423, -1.11114, 1.63099)
+
+[node name="@RayCast3D@24721" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(-0.382683, -0.390181, 1.92388)
+
+[node name="@RayCast3D@24722" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(-0.382683, 0.390181, 1.92388)
+
+[node name="@RayCast3D@24723" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(-0.324423, 1.11114, 1.63099)
+
+[node name="@RayCast3D@24724" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(0.324423, -1.11114, 1.63099)
+
+[node name="@RayCast3D@24725" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(0.382683, -0.390181, 1.92388)
+
+[node name="@RayCast3D@24726" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(0.382683, 0.390181, 1.92388)
+
+[node name="@RayCast3D@24727" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(0.324423, 1.11114, 1.63099)
+
+[node name="@RayCast3D@24728" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(0.92388, -1.11114, 1.38268)
+
+[node name="@RayCast3D@24729" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(1.08979, -0.390181, 1.63099)
+
+[node name="@RayCast3D@24730" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(1.08979, 0.390181, 1.63099)
+
+[node name="@RayCast3D@24731" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(0.92388, 1.11114, 1.38268)
diff --git a/SimpleReachGoal/CSharpAll/scenes/training_scene/training_scene.tscn b/SimpleReachGoal/CSharpAll/scenes/training_scene/training_scene.tscn
new file mode 100644
index 0000000000000000000000000000000000000000..41d665aa97aaa334d32039cbefe6b4e0d63b3a3d
--- /dev/null
+++ b/SimpleReachGoal/CSharpAll/scenes/training_scene/training_scene.tscn
@@ -0,0 +1,83 @@
+[gd_scene load_steps=6 format=3 uid="uid://b12majbajmkqq"]
+
+[ext_resource type="PackedScene" uid="uid://qofctg4fc0c2" path="res://scenes/game_scene/game_scene.tscn" id="1_pdcwe"]
+[ext_resource type="Script" path="res://addons/godot_rl_agents/sync.gd" id="2_7kqnq"]
+
+[sub_resource type="ProceduralSkyMaterial" id="ProceduralSkyMaterial_kbbm2"]
+sky_horizon_color = Color(0.64625, 0.65575, 0.67075, 1)
+ground_horizon_color = Color(0.64625, 0.65575, 0.67075, 1)
+
+[sub_resource type="Sky" id="Sky_lpkw7"]
+sky_material = SubResource("ProceduralSkyMaterial_kbbm2")
+
+[sub_resource type="Environment" id="Environment_3ytk2"]
+background_mode = 2
+sky = SubResource("Sky_lpkw7")
+tonemap_mode = 2
+glow_enabled = true
+
+[node name="TrainingScene" type="Node3D"]
+
+[node name="WorldEnvironment" type="WorldEnvironment" parent="."]
+environment = SubResource("Environment_3ytk2")
+
+[node name="DirectionalLight3D" type="DirectionalLight3D" parent="."]
+transform = Transform3D(-0.866024, -0.433016, 0.250001, 0, 0.499998, 0.866026, -0.500003, 0.749999, -0.43301, 0, 0, 0)
+shadow_enabled = true
+
+[node name="GameScene" parent="." node_paths=PackedStringArray("GoalManager", "ObstacleManager", "Player") instance=ExtResource("1_pdcwe")]
+GoalManager = NodePath("GoalManager")
+ObstacleManager = NodePath("ObstacleManager")
+Player = NodePath("Player")
+
+[node name="GameScene2" parent="." node_paths=PackedStringArray("GoalManager", "ObstacleManager", "Player") instance=ExtResource("1_pdcwe")]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 100, 0, 0)
+GoalManager = NodePath("GoalManager")
+ObstacleManager = NodePath("ObstacleManager")
+Player = NodePath("Player")
+
+[node name="GameScene3" parent="." node_paths=PackedStringArray("GoalManager", "ObstacleManager", "Player") instance=ExtResource("1_pdcwe")]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 200, 0, 0)
+GoalManager = NodePath("GoalManager")
+ObstacleManager = NodePath("ObstacleManager")
+Player = NodePath("Player")
+
+[node name="GameScene4" parent="." node_paths=PackedStringArray("GoalManager", "ObstacleManager", "Player") instance=ExtResource("1_pdcwe")]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 300, 0, 0)
+GoalManager = NodePath("GoalManager")
+ObstacleManager = NodePath("ObstacleManager")
+Player = NodePath("Player")
+
+[node name="GameScene5" parent="." node_paths=PackedStringArray("GoalManager", "ObstacleManager", "Player") instance=ExtResource("1_pdcwe")]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 100)
+GoalManager = NodePath("GoalManager")
+ObstacleManager = NodePath("ObstacleManager")
+Player = NodePath("Player")
+
+[node name="GameScene6" parent="." node_paths=PackedStringArray("GoalManager", "ObstacleManager", "Player") instance=ExtResource("1_pdcwe")]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 100, 0, 100)
+GoalManager = NodePath("GoalManager")
+ObstacleManager = NodePath("ObstacleManager")
+Player = NodePath("Player")
+
+[node name="GameScene7" parent="." node_paths=PackedStringArray("GoalManager", "ObstacleManager", "Player") instance=ExtResource("1_pdcwe")]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 200, 0, 100)
+GoalManager = NodePath("GoalManager")
+ObstacleManager = NodePath("ObstacleManager")
+Player = NodePath("Player")
+
+[node name="GameScene8" parent="." node_paths=PackedStringArray("GoalManager", "ObstacleManager", "Player") instance=ExtResource("1_pdcwe")]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 300, 0, 100)
+GoalManager = NodePath("GoalManager")
+ObstacleManager = NodePath("ObstacleManager")
+Player = NodePath("Player")
+
+[node name="Camera3D" type="Camera3D" parent="."]
+transform = Transform3D(1, 0, 0, 0, 0.803856, 0.594823, 0, -0.594823, 0.803856, 0, 9.562, 11.843)
+fov = 51.7
+
+[node name="Sync" type="Node" parent="."]
+script = ExtResource("2_7kqnq")
+control_mode = 2
+speed_up = 8.0
+onnx_model_path = "SimpleReachGoal.onnx"
diff --git a/SimpleReachGoal/GDScript/.gitattributes b/SimpleReachGoal/GDScript/.gitattributes
new file mode 100644
index 0000000000000000000000000000000000000000..8ad74f78d9c9b9b8f3d68772c6d5aa0cb3fe47e9
--- /dev/null
+++ b/SimpleReachGoal/GDScript/.gitattributes
@@ -0,0 +1,2 @@
+# Normalize EOL for all files that Git considers text files.
+* text=auto eol=lf
diff --git a/SimpleReachGoal/GDScript/.gitignore b/SimpleReachGoal/GDScript/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..7de8ea58b7054d16d554ddea743ca5255256b122
--- /dev/null
+++ b/SimpleReachGoal/GDScript/.gitignore
@@ -0,0 +1,3 @@
+# Godot 4+ specific ignores
+.godot/
+android/
diff --git a/SimpleReachGoal/GDScript/SimpleReachGoal.csproj b/SimpleReachGoal/GDScript/SimpleReachGoal.csproj
new file mode 100644
index 0000000000000000000000000000000000000000..9e0f6e5f28fa39bd53a520b4df2afde5651b4452
--- /dev/null
+++ b/SimpleReachGoal/GDScript/SimpleReachGoal.csproj
@@ -0,0 +1,11 @@
+
+
+ net6.0
+ net7.0
+ net8.0
+ true
+
+
+
+
+
\ No newline at end of file
diff --git a/SimpleReachGoal/GDScript/SimpleReachGoal.onnx b/SimpleReachGoal/GDScript/SimpleReachGoal.onnx
new file mode 100644
index 0000000000000000000000000000000000000000..48bcd37248926f5ee3a2cf2356b989be1f93ec48
--- /dev/null
+++ b/SimpleReachGoal/GDScript/SimpleReachGoal.onnx
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:689832dbc64e368771499f65327f2f828076cc87e21f8296b86bdca5fe49e1e6
+size 40656
diff --git a/SimpleReachGoal/GDScript/SimpleReachGoal.sln b/SimpleReachGoal/GDScript/SimpleReachGoal.sln
new file mode 100644
index 0000000000000000000000000000000000000000..cac7cbea2c4eb2fff6dba72881672fb52ef40f35
--- /dev/null
+++ b/SimpleReachGoal/GDScript/SimpleReachGoal.sln
@@ -0,0 +1,19 @@
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio 2012
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SimpleReachGoal", "SimpleReachGoal.csproj", "{8B1C40FD-E462-48E5-B273-A0E360A0580B}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|Any CPU = Debug|Any CPU
+ ExportDebug|Any CPU = ExportDebug|Any CPU
+ ExportRelease|Any CPU = ExportRelease|Any CPU
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {8B1C40FD-E462-48E5-B273-A0E360A0580B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {8B1C40FD-E462-48E5-B273-A0E360A0580B}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {8B1C40FD-E462-48E5-B273-A0E360A0580B}.ExportDebug|Any CPU.ActiveCfg = ExportDebug|Any CPU
+ {8B1C40FD-E462-48E5-B273-A0E360A0580B}.ExportDebug|Any CPU.Build.0 = ExportDebug|Any CPU
+ {8B1C40FD-E462-48E5-B273-A0E360A0580B}.ExportRelease|Any CPU.ActiveCfg = ExportRelease|Any CPU
+ {8B1C40FD-E462-48E5-B273-A0E360A0580B}.ExportRelease|Any CPU.Build.0 = ExportRelease|Any CPU
+ EndGlobalSection
+EndGlobal
diff --git a/SimpleReachGoal/GDScript/addons/godot_rl_agents/controller/ai_controller_2d.gd b/SimpleReachGoal/GDScript/addons/godot_rl_agents/controller/ai_controller_2d.gd
new file mode 100644
index 0000000000000000000000000000000000000000..fb2365649bc6a900453f5ba262af82bd59fa5a6c
--- /dev/null
+++ b/SimpleReachGoal/GDScript/addons/godot_rl_agents/controller/ai_controller_2d.gd
@@ -0,0 +1,118 @@
+extends Node2D
+class_name AIController2D
+
+enum ControlModes { INHERIT_FROM_SYNC, HUMAN, TRAINING, ONNX_INFERENCE, RECORD_EXPERT_DEMOS }
+@export var control_mode: ControlModes = ControlModes.INHERIT_FROM_SYNC
+@export var onnx_model_path := ""
+@export var reset_after := 1000
+
+@export_group("Record expert demos mode options")
+## Path where the demos will be saved. The file can later be used for imitation learning.
+@export var expert_demo_save_path: String
+## The action that erases the last recorded episode from the currently recorded data.
+@export var remove_last_episode_key: InputEvent
+## Action will be repeated for n frames. Will introduce control lag if larger than 1.
+## Can be used to ensure that action_repeat on inference and training matches
+## the recorded demonstrations.
+@export var action_repeat: int = 1
+
+var onnx_model: ONNXModel
+
+var heuristic := "human"
+var done := false
+var reward := 0.0
+var n_steps := 0
+var needs_reset := false
+
+var _player: Node2D
+
+
+func _ready():
+ add_to_group("AGENT")
+
+
+func init(player: Node2D):
+ _player = player
+
+
+#-- Methods that need implementing using the "extend script" option in Godot --#
+func get_obs() -> Dictionary:
+ assert(false, "the get_obs method is not implemented when extending from ai_controller")
+ return {"obs": []}
+
+
+func get_reward() -> float:
+ assert(false, "the get_reward method is not implemented when extending from ai_controller")
+ return 0.0
+
+
+func get_action_space() -> Dictionary:
+ assert(
+ false,
+ "the get get_action_space method is not implemented when extending from ai_controller"
+ )
+ return {
+ "example_actions_continous": {"size": 2, "action_type": "continuous"},
+ "example_actions_discrete": {"size": 2, "action_type": "discrete"},
+ }
+
+
+func set_action(action) -> void:
+ assert(false, "the set_action method is not implemented when extending from ai_controller")
+
+
+#-----------------------------------------------------------------------------#
+
+
+#-- Methods that sometimes need implementing using the "extend script" option in Godot --#
+# Only needed if you are recording expert demos with this AIController
+func get_action() -> Array:
+ assert(
+ false,
+ "the get_action method is not implemented in extended AIController but demo_recorder is used"
+ )
+ return []
+
+
+# -----------------------------------------------------------------------------#
+
+
+func _physics_process(delta):
+ n_steps += 1
+ if n_steps > reset_after:
+ needs_reset = true
+
+
+func get_obs_space():
+ # may need overriding if the obs space is complex
+ var obs = get_obs()
+ return {
+ "obs": {"size": [len(obs["obs"])], "space": "box"},
+ }
+
+
+func reset():
+ n_steps = 0
+ needs_reset = false
+
+
+func reset_if_done():
+ if done:
+ reset()
+
+
+func set_heuristic(h):
+ # sets the heuristic from "human" or "model" nothing to change here
+ heuristic = h
+
+
+func get_done():
+ return done
+
+
+func set_done_false():
+ done = false
+
+
+func zero_reward():
+ reward = 0.0
diff --git a/SimpleReachGoal/GDScript/addons/godot_rl_agents/controller/ai_controller_3d.gd b/SimpleReachGoal/GDScript/addons/godot_rl_agents/controller/ai_controller_3d.gd
new file mode 100644
index 0000000000000000000000000000000000000000..a5b4ee61ac838c03d6e22283f17adce0e6b4bbfa
--- /dev/null
+++ b/SimpleReachGoal/GDScript/addons/godot_rl_agents/controller/ai_controller_3d.gd
@@ -0,0 +1,117 @@
+extends Node3D
+class_name AIController3D
+
+enum ControlModes { INHERIT_FROM_SYNC, HUMAN, TRAINING, ONNX_INFERENCE, RECORD_EXPERT_DEMOS }
+@export var control_mode: ControlModes = ControlModes.INHERIT_FROM_SYNC
+@export var onnx_model_path := ""
+@export var reset_after := 1000
+
+@export_group("Record expert demos mode options")
+## Path where the demos will be saved. The file can later be used for imitation learning.
+@export var expert_demo_save_path: String
+## The action that erases the last recorded episode from the currently recorded data.
+@export var remove_last_episode_key: InputEvent
+## Action will be repeated for n frames. Will introduce control lag if larger than 1.
+## Can be used to ensure that action_repeat on inference and training matches
+## the recorded demonstrations.
+@export var action_repeat: int = 1
+
+var onnx_model: ONNXModel
+
+var heuristic := "human"
+var done := false
+var reward := 0.0
+var n_steps := 0
+var needs_reset := false
+
+var _player: Node3D
+
+
+func _ready():
+ add_to_group("AGENT")
+
+
+func init(player: Node3D):
+ _player = player
+
+
+#-- Methods that need implementing using the "extend script" option in Godot --#
+func get_obs() -> Dictionary:
+ assert(false, "the get_obs method is not implemented when extending from ai_controller")
+ return {"obs": []}
+
+
+func get_reward() -> float:
+ assert(false, "the get_reward method is not implemented when extending from ai_controller")
+ return 0.0
+
+
+func get_action_space() -> Dictionary:
+ assert(
+ false, "the get_action_space method is not implemented when extending from ai_controller"
+ )
+ return {
+ "example_actions_continous": {"size": 2, "action_type": "continuous"},
+ "example_actions_discrete": {"size": 2, "action_type": "discrete"},
+ }
+
+
+func set_action(action) -> void:
+ assert(false, "the set_action method is not implemented when extending from ai_controller")
+
+
+#-----------------------------------------------------------------------------#
+
+
+#-- Methods that sometimes need implementing using the "extend script" option in Godot --#
+# Only needed if you are recording expert demos with this AIController
+func get_action() -> Array:
+ assert(
+ false,
+ "the get_action method is not implemented in extended AIController but demo_recorder is used"
+ )
+ return []
+
+
+# -----------------------------------------------------------------------------#
+
+
+func _physics_process(delta):
+ n_steps += 1
+ if n_steps > reset_after:
+ needs_reset = true
+
+
+func get_obs_space():
+ # may need overriding if the obs space is complex
+ var obs = get_obs()
+ return {
+ "obs": {"size": [len(obs["obs"])], "space": "box"},
+ }
+
+
+func reset():
+ n_steps = 0
+ needs_reset = false
+
+
+func reset_if_done():
+ if done:
+ reset()
+
+
+func set_heuristic(h):
+ # sets the heuristic from "human" or "model" nothing to change here
+ heuristic = h
+
+
+func get_done():
+ return done
+
+
+func set_done_false():
+ done = false
+
+
+func zero_reward():
+ reward = 0.0
diff --git a/SimpleReachGoal/GDScript/addons/godot_rl_agents/godot_rl_agents.gd b/SimpleReachGoal/GDScript/addons/godot_rl_agents/godot_rl_agents.gd
new file mode 100644
index 0000000000000000000000000000000000000000..e4fe13693a598c808aca1b64051d1c0c70783296
--- /dev/null
+++ b/SimpleReachGoal/GDScript/addons/godot_rl_agents/godot_rl_agents.gd
@@ -0,0 +1,16 @@
+@tool
+extends EditorPlugin
+
+
+func _enter_tree():
+ # Initialization of the plugin goes here.
+ # Add the new type with a name, a parent type, a script and an icon.
+ add_custom_type("Sync", "Node", preload("sync.gd"), preload("icon.png"))
+ #add_custom_type("RaycastSensor2D2", "Node", preload("raycast_sensor_2d.gd"), preload("icon.png"))
+
+
+func _exit_tree():
+ # Clean-up of the plugin goes here.
+ # Always remember to remove it from the engine when deactivated.
+ remove_custom_type("Sync")
+ #remove_custom_type("RaycastSensor2D2")
diff --git a/SimpleReachGoal/GDScript/addons/godot_rl_agents/icon.png b/SimpleReachGoal/GDScript/addons/godot_rl_agents/icon.png
new file mode 100644
index 0000000000000000000000000000000000000000..ccb4ca000e3e1cf659fe367ab5bff67c1eb3467d
--- /dev/null
+++ b/SimpleReachGoal/GDScript/addons/godot_rl_agents/icon.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:e3a8bc372d3313ce1ede4e7554472e37b322178b9488bfb709e296585abd3c44
+size 198
diff --git a/SimpleReachGoal/GDScript/addons/godot_rl_agents/onnx/csharp/ONNXInference.cs b/SimpleReachGoal/GDScript/addons/godot_rl_agents/onnx/csharp/ONNXInference.cs
new file mode 100644
index 0000000000000000000000000000000000000000..0741f0f263f34fffc44993e2b11a7544b0384ca1
--- /dev/null
+++ b/SimpleReachGoal/GDScript/addons/godot_rl_agents/onnx/csharp/ONNXInference.cs
@@ -0,0 +1,103 @@
+using Godot;
+using Microsoft.ML.OnnxRuntime;
+using Microsoft.ML.OnnxRuntime.Tensors;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace GodotONNX
+{
+ ///
+ public partial class ONNXInference : GodotObject
+ {
+
+ private InferenceSession session;
+ ///
+ /// Path to the ONNX model. Use Initialize to change it.
+ ///
+ private string modelPath;
+ private int batchSize;
+
+ private SessionOptions SessionOpt;
+
+ //init function
+ ///
+ public void Initialize(string Path, int BatchSize)
+ {
+ modelPath = Path;
+ batchSize = BatchSize;
+ SessionOpt = SessionConfigurator.MakeConfiguredSessionOptions();
+ session = LoadModel(modelPath);
+
+ }
+ ///
+ public Godot.Collections.Dictionary> RunInference(Godot.Collections.Array obs, int state_ins)
+ {
+ //Current model: Any (Godot Rl Agents)
+ //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
+
+ //Fill the input tensors
+ // create span from inputSize
+ var span = new float[obs.Count]; //There's probably a better way to do this
+ for (int i = 0; i < obs.Count; i++)
+ {
+ span[i] = obs[i];
+ }
+
+ IReadOnlyCollection inputs = new List
+ {
+ NamedOnnxValue.CreateFromTensor("obs", new DenseTensor(span, new int[] { batchSize, obs.Count })),
+ NamedOnnxValue.CreateFromTensor("state_ins", new DenseTensor(new float[] { state_ins }, new int[] { batchSize }))
+ };
+ IReadOnlyCollection outputNames = new List { "output", "state_outs" }; //ONNX is sensible to these names, as well as the input names
+
+ IDisposableReadOnlyCollection results;
+ //We do not use "using" here so we get a better exception explaination later
+ try
+ {
+ results = session.Run(inputs, outputNames);
+ }
+ catch (OnnxRuntimeException e)
+ {
+ //This error usually means that the model is not compatible with the input, beacause of the input shape (size)
+ GD.Print("Error at inference: ", e);
+ return null;
+ }
+ //Can't convert IEnumerable to Variant, so we have to convert it to an array or something
+ Godot.Collections.Dictionary> output = new Godot.Collections.Dictionary>();
+ DisposableNamedOnnxValue output1 = results.First();
+ DisposableNamedOnnxValue output2 = results.Last();
+ Godot.Collections.Array output1Array = new Godot.Collections.Array();
+ Godot.Collections.Array output2Array = new Godot.Collections.Array();
+
+ foreach (float f in output1.AsEnumerable())
+ {
+ output1Array.Add(f);
+ }
+
+ foreach (float f in output2.AsEnumerable())
+ {
+ output2Array.Add(f);
+ }
+
+ output.Add(output1.Name, output1Array);
+ output.Add(output2.Name, output2Array);
+
+ //Output is a dictionary of arrays, ex: { "output" : [0.1, 0.2, 0.3, 0.4, ...], "state_outs" : [0.5, ...]}
+ results.Dispose();
+ return output;
+ }
+ ///
+ public InferenceSession LoadModel(string Path)
+ {
+ using Godot.FileAccess file = FileAccess.Open(Path, Godot.FileAccess.ModeFlags.Read);
+ byte[] model = file.GetBuffer((int)file.GetLength());
+ //file.Close(); file.Dispose(); //Close the file, then dispose the reference.
+ return new InferenceSession(model, SessionOpt); //Load the model
+ }
+ public void FreeDisposables()
+ {
+ session.Dispose();
+ SessionOpt.Dispose();
+ }
+ }
+}
diff --git a/SimpleReachGoal/GDScript/addons/godot_rl_agents/onnx/csharp/SessionConfigurator.cs b/SimpleReachGoal/GDScript/addons/godot_rl_agents/onnx/csharp/SessionConfigurator.cs
new file mode 100644
index 0000000000000000000000000000000000000000..ad7a41cfee0dc3d497d9c1d03bd0752b09d49f3a
--- /dev/null
+++ b/SimpleReachGoal/GDScript/addons/godot_rl_agents/onnx/csharp/SessionConfigurator.cs
@@ -0,0 +1,131 @@
+using Godot;
+using Microsoft.ML.OnnxRuntime;
+
+namespace GodotONNX
+{
+ ///
+
+ public static class SessionConfigurator
+ {
+ public enum ComputeName
+ {
+ CUDA,
+ ROCm,
+ DirectML,
+ CoreML,
+ CPU
+ }
+
+ ///
+ public static SessionOptions MakeConfiguredSessionOptions()
+ {
+ SessionOptions sessionOptions = new();
+ SetOptions(sessionOptions);
+ return sessionOptions;
+ }
+
+ private static void SetOptions(SessionOptions sessionOptions)
+ {
+ sessionOptions.LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_WARNING;
+ ApplySystemSpecificOptions(sessionOptions);
+ }
+
+ ///
+ static public void ApplySystemSpecificOptions(SessionOptions sessionOptions)
+ {
+ //Most code for this function is verbose only, the only reason it exists is to track
+ //implementation progress of the different compute APIs.
+
+ //December 2022: CUDA is not working.
+
+ string OSName = OS.GetName(); //Get OS Name
+
+ //ComputeName ComputeAPI = ComputeCheck(); //Get Compute API
+ // //TODO: Get CPU architecture
+
+ //Linux can use OpenVINO (C#) on x64 and ROCm on x86 (GDNative/C++)
+ //Windows can use OpenVINO (C#) on x64
+ //TODO: try TensorRT instead of CUDA
+ //TODO: Use OpenVINO for Intel Graphics
+
+ // Temporarily using CPU on all platforms to avoid errors detected with DML
+ ComputeName ComputeAPI = ComputeName.CPU;
+
+ //match OS and Compute API
+ GD.Print($"OS: {OSName} Compute API: {ComputeAPI}");
+
+ // CPU is set by default without appending necessary
+ // sessionOptions.AppendExecutionProvider_CPU(0);
+
+ /*
+ switch (OSName)
+ {
+ case "Windows": //Can use CUDA, DirectML
+ if (ComputeAPI is ComputeName.CUDA)
+ {
+ //CUDA
+ //sessionOptions.AppendExecutionProvider_CUDA(0);
+ //sessionOptions.AppendExecutionProvider_DML(0);
+ }
+ else if (ComputeAPI is ComputeName.DirectML)
+ {
+ //DirectML
+ //sessionOptions.AppendExecutionProvider_DML(0);
+ }
+ break;
+ case "X11": //Can use CUDA, ROCm
+ if (ComputeAPI is ComputeName.CUDA)
+ {
+ //CUDA
+ //sessionOptions.AppendExecutionProvider_CUDA(0);
+ }
+ if (ComputeAPI is ComputeName.ROCm)
+ {
+ //ROCm, only works on x86
+ //Research indicates that this has to be compiled as a GDNative plugin
+ //GD.Print("ROCm not supported yet, using CPU.");
+ //sessionOptions.AppendExecutionProvider_CPU(0);
+ }
+ break;
+ case "macOS": //Can use CoreML
+ if (ComputeAPI is ComputeName.CoreML)
+ { //CoreML
+ //TODO: Needs testing
+ //sessionOptions.AppendExecutionProvider_CoreML(0);
+ //CoreML on ARM64, out of the box, on x64 needs .tar file from GitHub
+ }
+ break;
+ default:
+ GD.Print("OS not Supported.");
+ break;
+ }
+ */
+ }
+
+
+ ///
+ public static ComputeName ComputeCheck()
+ {
+ string adapterName = Godot.RenderingServer.GetVideoAdapterName();
+ //string adapterVendor = Godot.RenderingServer.GetVideoAdapterVendor();
+ adapterName = adapterName.ToUpper(new System.Globalization.CultureInfo(""));
+ //TODO: GPU vendors for MacOS, what do they even use these days?
+
+ if (adapterName.Contains("INTEL"))
+ {
+ return ComputeName.DirectML;
+ }
+ if (adapterName.Contains("AMD") || adapterName.Contains("RADEON"))
+ {
+ return ComputeName.DirectML;
+ }
+ if (adapterName.Contains("NVIDIA"))
+ {
+ return ComputeName.CUDA;
+ }
+
+ GD.Print("Graphics Card not recognized."); //Should use CPU
+ return ComputeName.CPU;
+ }
+ }
+}
diff --git a/SimpleReachGoal/GDScript/addons/godot_rl_agents/onnx/csharp/docs/ONNXInference.xml b/SimpleReachGoal/GDScript/addons/godot_rl_agents/onnx/csharp/docs/ONNXInference.xml
new file mode 100644
index 0000000000000000000000000000000000000000..91b07d607dc89f11e957e13758d8c0ee4fb72be8
--- /dev/null
+++ b/SimpleReachGoal/GDScript/addons/godot_rl_agents/onnx/csharp/docs/ONNXInference.xml
@@ -0,0 +1,31 @@
+
+
+
+
+ The main ONNXInference Class that handles the inference process.
+
+
+
+
+ Starts the inference process.
+
+ Path to the ONNX model, expects a path inside resources.
+ How many observations will the model recieve.
+
+
+
+ Runs the given input through the model and returns the output.
+
+ Dictionary containing all observations.
+ How many different agents are creating these observations.
+ A Dictionary of arrays, containing instructions based on the observations.
+
+
+
+ Loads the given model into the inference process, using the best Execution provider available.
+
+ Path to the ONNX model, expects a path inside resources.
+ InferenceSession ready to run.
+
+
+
\ No newline at end of file
diff --git a/SimpleReachGoal/GDScript/addons/godot_rl_agents/onnx/csharp/docs/SessionConfigurator.xml b/SimpleReachGoal/GDScript/addons/godot_rl_agents/onnx/csharp/docs/SessionConfigurator.xml
new file mode 100644
index 0000000000000000000000000000000000000000..f160c02f0d4cab92e10f799b6f4c5a71d4d6c0f2
--- /dev/null
+++ b/SimpleReachGoal/GDScript/addons/godot_rl_agents/onnx/csharp/docs/SessionConfigurator.xml
@@ -0,0 +1,29 @@
+
+
+
+
+ The main SessionConfigurator Class that handles the execution options and providers for the inference process.
+
+
+
+
+ Creates a SessionOptions with all available execution providers.
+
+ SessionOptions with all available execution providers.
+
+
+
+ Appends any execution provider available in the current system.
+
+
+ This function is mainly verbose for tracking implementation progress of different compute APIs.
+
+
+
+
+ Checks for available GPUs.
+
+ An integer identifier for each compute platform.
+
+
+
\ No newline at end of file
diff --git a/SimpleReachGoal/GDScript/addons/godot_rl_agents/onnx/wrapper/ONNX_wrapper.gd b/SimpleReachGoal/GDScript/addons/godot_rl_agents/onnx/wrapper/ONNX_wrapper.gd
new file mode 100644
index 0000000000000000000000000000000000000000..d573582b995a2b8fe05553f7cf58fb2e3b58d482
--- /dev/null
+++ b/SimpleReachGoal/GDScript/addons/godot_rl_agents/onnx/wrapper/ONNX_wrapper.gd
@@ -0,0 +1,27 @@
+extends Resource
+class_name ONNXModel
+var inferencer_script = load("res://addons/godot_rl_agents/onnx/csharp/ONNXInference.cs")
+
+var inferencer = null
+
+
+# Must provide the path to the model and the batch size
+func _init(model_path, batch_size):
+ inferencer = inferencer_script.new()
+ inferencer.Initialize(model_path, batch_size)
+
+
+# This function is the one that will be called from the game,
+# requires the observation as an array and the state_ins as an int
+# returns an Array containing the action the model takes.
+func run_inference(obs: Array, state_ins: int) -> Dictionary:
+ if inferencer == null:
+ printerr("Inferencer not initialized")
+ return {}
+ return inferencer.RunInference(obs, state_ins)
+
+
+func _notification(what):
+ if what == NOTIFICATION_PREDELETE:
+ inferencer.FreeDisposables()
+ inferencer.free()
diff --git a/SimpleReachGoal/GDScript/addons/godot_rl_agents/plugin.cfg b/SimpleReachGoal/GDScript/addons/godot_rl_agents/plugin.cfg
new file mode 100644
index 0000000000000000000000000000000000000000..b1bc988c80e3fe68e6d4279691fd5892e5ef323d
--- /dev/null
+++ b/SimpleReachGoal/GDScript/addons/godot_rl_agents/plugin.cfg
@@ -0,0 +1,7 @@
+[plugin]
+
+name="GodotRLAgents"
+description="Custom nodes for the godot rl agents toolkit "
+author="Edward Beeching"
+version="0.1"
+script="godot_rl_agents.gd"
diff --git a/SimpleReachGoal/GDScript/addons/godot_rl_agents/sensors/sensors_2d/ExampleRaycastSensor2D.tscn b/SimpleReachGoal/GDScript/addons/godot_rl_agents/sensors/sensors_2d/ExampleRaycastSensor2D.tscn
new file mode 100644
index 0000000000000000000000000000000000000000..5edb6c7fc9da56e625d57185bdbafdbcc3fc67c5
--- /dev/null
+++ b/SimpleReachGoal/GDScript/addons/godot_rl_agents/sensors/sensors_2d/ExampleRaycastSensor2D.tscn
@@ -0,0 +1,48 @@
+[gd_scene load_steps=5 format=3 uid="uid://ddeq7mn1ealyc"]
+
+[ext_resource type="Script" path="res://addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.gd" id="1"]
+
+[sub_resource type="GDScript" id="2"]
+script/source = "extends Node2D
+
+
+
+func _physics_process(delta: float) -> void:
+ print(\"step start\")
+
+"
+
+[sub_resource type="GDScript" id="1"]
+script/source = "extends RayCast2D
+
+var steps = 1
+
+func _physics_process(delta: float) -> void:
+ print(\"processing raycast\")
+ steps += 1
+ if steps % 2:
+ force_raycast_update()
+
+ print(is_colliding())
+"
+
+[sub_resource type="CircleShape2D" id="3"]
+
+[node name="ExampleRaycastSensor2D" type="Node2D"]
+script = SubResource("2")
+
+[node name="ExampleAgent" type="Node2D" parent="."]
+position = Vector2(573, 314)
+rotation = 0.286234
+
+[node name="RaycastSensor2D" type="Node2D" parent="ExampleAgent"]
+script = ExtResource("1")
+
+[node name="TestRayCast2D" type="RayCast2D" parent="."]
+script = SubResource("1")
+
+[node name="StaticBody2D" type="StaticBody2D" parent="."]
+position = Vector2(1, 52)
+
+[node name="CollisionShape2D" type="CollisionShape2D" parent="StaticBody2D"]
+shape = SubResource("3")
diff --git a/SimpleReachGoal/GDScript/addons/godot_rl_agents/sensors/sensors_2d/GridSensor2D.gd b/SimpleReachGoal/GDScript/addons/godot_rl_agents/sensors/sensors_2d/GridSensor2D.gd
new file mode 100644
index 0000000000000000000000000000000000000000..da170ba93919a8f28510ea8fc1ab876fe5876d34
--- /dev/null
+++ b/SimpleReachGoal/GDScript/addons/godot_rl_agents/sensors/sensors_2d/GridSensor2D.gd
@@ -0,0 +1,235 @@
+@tool
+extends ISensor2D
+class_name GridSensor2D
+
+@export var debug_view := false:
+ get:
+ return debug_view
+ set(value):
+ debug_view = value
+ _update()
+
+@export_flags_2d_physics var detection_mask := 0:
+ get:
+ return detection_mask
+ set(value):
+ detection_mask = value
+ _update()
+
+@export var collide_with_areas := false:
+ get:
+ return collide_with_areas
+ set(value):
+ collide_with_areas = value
+ _update()
+
+@export var collide_with_bodies := true:
+ get:
+ return collide_with_bodies
+ set(value):
+ collide_with_bodies = value
+ _update()
+
+@export_range(1, 200, 0.1) var cell_width := 20.0:
+ get:
+ return cell_width
+ set(value):
+ cell_width = value
+ _update()
+
+@export_range(1, 200, 0.1) var cell_height := 20.0:
+ get:
+ return cell_height
+ set(value):
+ cell_height = value
+ _update()
+
+@export_range(1, 21, 2, "or_greater") var grid_size_x := 3:
+ get:
+ return grid_size_x
+ set(value):
+ grid_size_x = value
+ _update()
+
+@export_range(1, 21, 2, "or_greater") var grid_size_y := 3:
+ get:
+ return grid_size_y
+ set(value):
+ grid_size_y = value
+ _update()
+
+var _obs_buffer: PackedFloat64Array
+var _rectangle_shape: RectangleShape2D
+var _collision_mapping: Dictionary
+var _n_layers_per_cell: int
+
+var _highlighted_cell_color: Color
+var _standard_cell_color: Color
+
+
+func get_observation():
+ return _obs_buffer
+
+
+func _update():
+ if Engine.is_editor_hint():
+ if is_node_ready():
+ _spawn_nodes()
+
+
+func _ready() -> void:
+ _set_colors()
+
+ if Engine.is_editor_hint():
+ if get_child_count() == 0:
+ _spawn_nodes()
+ else:
+ _spawn_nodes()
+
+
+func _set_colors() -> void:
+ _standard_cell_color = Color(100.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0)
+ _highlighted_cell_color = Color(255.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0)
+
+
+func _get_collision_mapping() -> Dictionary:
+ # defines which layer is mapped to which cell obs index
+ var total_bits = 0
+ var collision_mapping = {}
+ for i in 32:
+ var bit_mask = 2 ** i
+ if (detection_mask & bit_mask) > 0:
+ collision_mapping[i] = total_bits
+ total_bits += 1
+
+ return collision_mapping
+
+
+func _spawn_nodes():
+ for cell in get_children():
+ cell.name = "_%s" % cell.name # Otherwise naming below will fail
+ cell.queue_free()
+
+ _collision_mapping = _get_collision_mapping()
+ #prints("collision_mapping", _collision_mapping, len(_collision_mapping))
+ # allocate memory for the observations
+ _n_layers_per_cell = len(_collision_mapping)
+ _obs_buffer = PackedFloat64Array()
+ _obs_buffer.resize(grid_size_x * grid_size_y * _n_layers_per_cell)
+ _obs_buffer.fill(0)
+ #prints(len(_obs_buffer), _obs_buffer )
+
+ _rectangle_shape = RectangleShape2D.new()
+ _rectangle_shape.set_size(Vector2(cell_width, cell_height))
+
+ var shift := Vector2(
+ -(grid_size_x / 2) * cell_width,
+ -(grid_size_y / 2) * cell_height,
+ )
+
+ for i in grid_size_x:
+ for j in grid_size_y:
+ var cell_position = Vector2(i * cell_width, j * cell_height) + shift
+ _create_cell(i, j, cell_position)
+
+
+func _create_cell(i: int, j: int, position: Vector2):
+ var cell := Area2D.new()
+ cell.position = position
+ cell.name = "GridCell %s %s" % [i, j]
+ cell.modulate = _standard_cell_color
+
+ if collide_with_areas:
+ cell.area_entered.connect(_on_cell_area_entered.bind(i, j))
+ cell.area_exited.connect(_on_cell_area_exited.bind(i, j))
+
+ if collide_with_bodies:
+ cell.body_entered.connect(_on_cell_body_entered.bind(i, j))
+ cell.body_exited.connect(_on_cell_body_exited.bind(i, j))
+
+ cell.collision_layer = 0
+ cell.collision_mask = detection_mask
+ cell.monitorable = true
+ add_child(cell)
+ cell.set_owner(get_tree().edited_scene_root)
+
+ var col_shape := CollisionShape2D.new()
+ col_shape.shape = _rectangle_shape
+ col_shape.name = "CollisionShape2D"
+ cell.add_child(col_shape)
+ col_shape.set_owner(get_tree().edited_scene_root)
+
+ if debug_view:
+ var quad = MeshInstance2D.new()
+ quad.name = "MeshInstance2D"
+ var quad_mesh = QuadMesh.new()
+
+ quad_mesh.set_size(Vector2(cell_width, cell_height))
+
+ quad.mesh = quad_mesh
+ cell.add_child(quad)
+ quad.set_owner(get_tree().edited_scene_root)
+
+
+func _update_obs(cell_i: int, cell_j: int, collision_layer: int, entered: bool):
+ for key in _collision_mapping:
+ var bit_mask = 2 ** key
+ if (collision_layer & bit_mask) > 0:
+ var collison_map_index = _collision_mapping[key]
+
+ var obs_index = (
+ (cell_i * grid_size_x * _n_layers_per_cell)
+ + (cell_j * _n_layers_per_cell)
+ + collison_map_index
+ )
+ #prints(obs_index, cell_i, cell_j)
+ if entered:
+ _obs_buffer[obs_index] += 1
+ else:
+ _obs_buffer[obs_index] -= 1
+
+
+func _toggle_cell(cell_i: int, cell_j: int):
+ var cell = get_node_or_null("GridCell %s %s" % [cell_i, cell_j])
+
+ if cell == null:
+ print("cell not found, returning")
+
+ var n_hits = 0
+ var start_index = (cell_i * grid_size_x * _n_layers_per_cell) + (cell_j * _n_layers_per_cell)
+ for i in _n_layers_per_cell:
+ n_hits += _obs_buffer[start_index + i]
+
+ if n_hits > 0:
+ cell.modulate = _highlighted_cell_color
+ else:
+ cell.modulate = _standard_cell_color
+
+
+func _on_cell_area_entered(area: Area2D, cell_i: int, cell_j: int):
+ #prints("_on_cell_area_entered", cell_i, cell_j)
+ _update_obs(cell_i, cell_j, area.collision_layer, true)
+ if debug_view:
+ _toggle_cell(cell_i, cell_j)
+ #print(_obs_buffer)
+
+
+func _on_cell_area_exited(area: Area2D, cell_i: int, cell_j: int):
+ #prints("_on_cell_area_exited", cell_i, cell_j)
+ _update_obs(cell_i, cell_j, area.collision_layer, false)
+ if debug_view:
+ _toggle_cell(cell_i, cell_j)
+
+
+func _on_cell_body_entered(body: Node2D, cell_i: int, cell_j: int):
+ #prints("_on_cell_body_entered", cell_i, cell_j)
+ _update_obs(cell_i, cell_j, body.collision_layer, true)
+ if debug_view:
+ _toggle_cell(cell_i, cell_j)
+
+
+func _on_cell_body_exited(body: Node2D, cell_i: int, cell_j: int):
+ #prints("_on_cell_body_exited", cell_i, cell_j)
+ _update_obs(cell_i, cell_j, body.collision_layer, false)
+ if debug_view:
+ _toggle_cell(cell_i, cell_j)
diff --git a/SimpleReachGoal/GDScript/addons/godot_rl_agents/sensors/sensors_2d/ISensor2D.gd b/SimpleReachGoal/GDScript/addons/godot_rl_agents/sensors/sensors_2d/ISensor2D.gd
new file mode 100644
index 0000000000000000000000000000000000000000..67669a1d71a3e37d780b396633951d7d1ac79edb
--- /dev/null
+++ b/SimpleReachGoal/GDScript/addons/godot_rl_agents/sensors/sensors_2d/ISensor2D.gd
@@ -0,0 +1,25 @@
+extends Node2D
+class_name ISensor2D
+
+var _obs: Array = []
+var _active := false
+
+
+func get_observation():
+ pass
+
+
+func activate():
+ _active = true
+
+
+func deactivate():
+ _active = false
+
+
+func _update_observation():
+ pass
+
+
+func reset():
+ pass
diff --git a/SimpleReachGoal/GDScript/addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.gd b/SimpleReachGoal/GDScript/addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.gd
new file mode 100644
index 0000000000000000000000000000000000000000..9bb54ede90a6f6ffd5e65d89bf1bd561bc0832ed
--- /dev/null
+++ b/SimpleReachGoal/GDScript/addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.gd
@@ -0,0 +1,118 @@
+@tool
+extends ISensor2D
+class_name RaycastSensor2D
+
+@export_flags_2d_physics var collision_mask := 1:
+ get:
+ return collision_mask
+ set(value):
+ collision_mask = value
+ _update()
+
+@export var collide_with_areas := false:
+ get:
+ return collide_with_areas
+ set(value):
+ collide_with_areas = value
+ _update()
+
+@export var collide_with_bodies := true:
+ get:
+ return collide_with_bodies
+ set(value):
+ collide_with_bodies = value
+ _update()
+
+@export var n_rays := 16.0:
+ get:
+ return n_rays
+ set(value):
+ n_rays = value
+ _update()
+
+@export_range(5, 3000, 5.0) var ray_length := 200:
+ get:
+ return ray_length
+ set(value):
+ ray_length = value
+ _update()
+@export_range(5, 360, 5.0) var cone_width := 360.0:
+ get:
+ return cone_width
+ set(value):
+ cone_width = value
+ _update()
+
+@export var debug_draw := true:
+ get:
+ return debug_draw
+ set(value):
+ debug_draw = value
+ _update()
+
+var _angles = []
+var rays := []
+
+
+func _update():
+ if Engine.is_editor_hint():
+ if debug_draw:
+ _spawn_nodes()
+ else:
+ for ray in get_children():
+ if ray is RayCast2D:
+ remove_child(ray)
+
+
+func _ready() -> void:
+ _spawn_nodes()
+
+
+func _spawn_nodes():
+ for ray in rays:
+ ray.queue_free()
+ rays = []
+
+ _angles = []
+ var step = cone_width / (n_rays)
+ var start = step / 2 - cone_width / 2
+
+ for i in n_rays:
+ var angle = start + i * step
+ var ray = RayCast2D.new()
+ ray.set_target_position(
+ Vector2(ray_length * cos(deg_to_rad(angle)), ray_length * sin(deg_to_rad(angle)))
+ )
+ ray.set_name("node_" + str(i))
+ ray.enabled = false
+ ray.collide_with_areas = collide_with_areas
+ ray.collide_with_bodies = collide_with_bodies
+ ray.collision_mask = collision_mask
+ add_child(ray)
+ rays.append(ray)
+
+ _angles.append(start + i * step)
+
+
+func get_observation() -> Array:
+ return self.calculate_raycasts()
+
+
+func calculate_raycasts() -> Array:
+ var result = []
+ for ray in rays:
+ ray.enabled = true
+ ray.force_raycast_update()
+ var distance = _get_raycast_distance(ray)
+ result.append(distance)
+ ray.enabled = false
+ return result
+
+
+func _get_raycast_distance(ray: RayCast2D) -> float:
+ if !ray.is_colliding():
+ return 0.0
+
+ var distance = (global_position - ray.get_collision_point()).length()
+ distance = clamp(distance, 0.0, ray_length)
+ return (ray_length - distance) / ray_length
diff --git a/SimpleReachGoal/GDScript/addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.tscn b/SimpleReachGoal/GDScript/addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.tscn
new file mode 100644
index 0000000000000000000000000000000000000000..5ca402c08305efedbfc6afd0a1893a0ca2e11cfd
--- /dev/null
+++ b/SimpleReachGoal/GDScript/addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.tscn
@@ -0,0 +1,7 @@
+[gd_scene load_steps=2 format=3 uid="uid://drvfihk5esgmv"]
+
+[ext_resource type="Script" path="res://addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.gd" id="1"]
+
+[node name="RaycastSensor2D" type="Node2D"]
+script = ExtResource("1")
+n_rays = 17.0
diff --git a/SimpleReachGoal/GDScript/addons/godot_rl_agents/sensors/sensors_3d/ExampleRaycastSensor3D.tscn b/SimpleReachGoal/GDScript/addons/godot_rl_agents/sensors/sensors_3d/ExampleRaycastSensor3D.tscn
new file mode 100644
index 0000000000000000000000000000000000000000..a8057c7619cbb835709d2704074b0d5ebfa00a0c
--- /dev/null
+++ b/SimpleReachGoal/GDScript/addons/godot_rl_agents/sensors/sensors_3d/ExampleRaycastSensor3D.tscn
@@ -0,0 +1,6 @@
+[gd_scene format=3 uid="uid://biu787qh4woik"]
+
+[node name="ExampleRaycastSensor3D" type="Node3D"]
+
+[node name="Camera3D" type="Camera3D" parent="."]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0.804183, 0, 2.70146)
diff --git a/SimpleReachGoal/GDScript/addons/godot_rl_agents/sensors/sensors_3d/GridSensor3D.gd b/SimpleReachGoal/GDScript/addons/godot_rl_agents/sensors/sensors_3d/GridSensor3D.gd
new file mode 100644
index 0000000000000000000000000000000000000000..03593cc04d74ce0d0f16a4518e59b9309a09a5a7
--- /dev/null
+++ b/SimpleReachGoal/GDScript/addons/godot_rl_agents/sensors/sensors_3d/GridSensor3D.gd
@@ -0,0 +1,258 @@
+@tool
+extends ISensor3D
+class_name GridSensor3D
+
+@export var debug_view := false:
+ get:
+ return debug_view
+ set(value):
+ debug_view = value
+ _update()
+
+@export_flags_3d_physics var detection_mask := 0:
+ get:
+ return detection_mask
+ set(value):
+ detection_mask = value
+ _update()
+
+@export var collide_with_areas := false:
+ get:
+ return collide_with_areas
+ set(value):
+ collide_with_areas = value
+ _update()
+
+@export var collide_with_bodies := false:
+ # NOTE! The sensor will not detect StaticBody3D, add an area to static bodies to detect them
+ get:
+ return collide_with_bodies
+ set(value):
+ collide_with_bodies = value
+ _update()
+
+@export_range(0.1, 2, 0.1) var cell_width := 1.0:
+ get:
+ return cell_width
+ set(value):
+ cell_width = value
+ _update()
+
+@export_range(0.1, 2, 0.1) var cell_height := 1.0:
+ get:
+ return cell_height
+ set(value):
+ cell_height = value
+ _update()
+
+@export_range(1, 21, 2, "or_greater") var grid_size_x := 3:
+ get:
+ return grid_size_x
+ set(value):
+ grid_size_x = value
+ _update()
+
+@export_range(1, 21, 2, "or_greater") var grid_size_z := 3:
+ get:
+ return grid_size_z
+ set(value):
+ grid_size_z = value
+ _update()
+
+var _obs_buffer: PackedFloat64Array
+var _box_shape: BoxShape3D
+var _collision_mapping: Dictionary
+var _n_layers_per_cell: int
+
+var _highlighted_box_material: StandardMaterial3D
+var _standard_box_material: StandardMaterial3D
+
+
+func get_observation():
+ return _obs_buffer
+
+
+func reset():
+ _obs_buffer.fill(0)
+
+
+func _update():
+ if Engine.is_editor_hint():
+ if is_node_ready():
+ _spawn_nodes()
+
+
+func _ready() -> void:
+ _make_materials()
+
+ if Engine.is_editor_hint():
+ if get_child_count() == 0:
+ _spawn_nodes()
+ else:
+ _spawn_nodes()
+
+
+func _make_materials() -> void:
+ if _highlighted_box_material != null and _standard_box_material != null:
+ return
+
+ _standard_box_material = StandardMaterial3D.new()
+ _standard_box_material.set_transparency(1) # ALPHA
+ _standard_box_material.albedo_color = Color(
+ 100.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0
+ )
+
+ _highlighted_box_material = StandardMaterial3D.new()
+ _highlighted_box_material.set_transparency(1) # ALPHA
+ _highlighted_box_material.albedo_color = Color(
+ 255.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0
+ )
+
+
+func _get_collision_mapping() -> Dictionary:
+ # defines which layer is mapped to which cell obs index
+ var total_bits = 0
+ var collision_mapping = {}
+ for i in 32:
+ var bit_mask = 2 ** i
+ if (detection_mask & bit_mask) > 0:
+ collision_mapping[i] = total_bits
+ total_bits += 1
+
+ return collision_mapping
+
+
+func _spawn_nodes():
+ for cell in get_children():
+ cell.name = "_%s" % cell.name # Otherwise naming below will fail
+ cell.queue_free()
+
+ _collision_mapping = _get_collision_mapping()
+ #prints("collision_mapping", _collision_mapping, len(_collision_mapping))
+ # allocate memory for the observations
+ _n_layers_per_cell = len(_collision_mapping)
+ _obs_buffer = PackedFloat64Array()
+ _obs_buffer.resize(grid_size_x * grid_size_z * _n_layers_per_cell)
+ _obs_buffer.fill(0)
+ #prints(len(_obs_buffer), _obs_buffer )
+
+ _box_shape = BoxShape3D.new()
+ _box_shape.set_size(Vector3(cell_width, cell_height, cell_width))
+
+ var shift := Vector3(
+ -(grid_size_x / 2) * cell_width,
+ 0,
+ -(grid_size_z / 2) * cell_width,
+ )
+
+ for i in grid_size_x:
+ for j in grid_size_z:
+ var cell_position = Vector3(i * cell_width, 0.0, j * cell_width) + shift
+ _create_cell(i, j, cell_position)
+
+
+func _create_cell(i: int, j: int, position: Vector3):
+ var cell := Area3D.new()
+ cell.position = position
+ cell.name = "GridCell %s %s" % [i, j]
+
+ if collide_with_areas:
+ cell.area_entered.connect(_on_cell_area_entered.bind(i, j))
+ cell.area_exited.connect(_on_cell_area_exited.bind(i, j))
+
+ if collide_with_bodies:
+ cell.body_entered.connect(_on_cell_body_entered.bind(i, j))
+ cell.body_exited.connect(_on_cell_body_exited.bind(i, j))
+
+# cell.body_shape_entered.connect(_on_cell_body_shape_entered.bind(i, j))
+# cell.body_shape_exited.connect(_on_cell_body_shape_exited.bind(i, j))
+
+ cell.collision_layer = 0
+ cell.collision_mask = detection_mask
+ cell.monitorable = true
+ cell.input_ray_pickable = false
+ add_child(cell)
+ cell.set_owner(get_tree().edited_scene_root)
+
+ var col_shape := CollisionShape3D.new()
+ col_shape.shape = _box_shape
+ col_shape.name = "CollisionShape3D"
+ cell.add_child(col_shape)
+ col_shape.set_owner(get_tree().edited_scene_root)
+
+ if debug_view:
+ var box = MeshInstance3D.new()
+ box.name = "MeshInstance3D"
+ var box_mesh = BoxMesh.new()
+
+ box_mesh.set_size(Vector3(cell_width, cell_height, cell_width))
+ box_mesh.material = _standard_box_material
+
+ box.mesh = box_mesh
+ cell.add_child(box)
+ box.set_owner(get_tree().edited_scene_root)
+
+
+func _update_obs(cell_i: int, cell_j: int, collision_layer: int, entered: bool):
+ for key in _collision_mapping:
+ var bit_mask = 2 ** key
+ if (collision_layer & bit_mask) > 0:
+ var collison_map_index = _collision_mapping[key]
+
+ var obs_index = (
+ (cell_i * grid_size_x * _n_layers_per_cell)
+ + (cell_j * _n_layers_per_cell)
+ + collison_map_index
+ )
+ #prints(obs_index, cell_i, cell_j)
+ if entered:
+ _obs_buffer[obs_index] += 1
+ else:
+ _obs_buffer[obs_index] -= 1
+
+
+func _toggle_cell(cell_i: int, cell_j: int):
+ var cell = get_node_or_null("GridCell %s %s" % [cell_i, cell_j])
+
+ if cell == null:
+ print("cell not found, returning")
+
+ var n_hits = 0
+ var start_index = (cell_i * grid_size_x * _n_layers_per_cell) + (cell_j * _n_layers_per_cell)
+ for i in _n_layers_per_cell:
+ n_hits += _obs_buffer[start_index + i]
+
+ var cell_mesh = cell.get_node_or_null("MeshInstance3D")
+ if n_hits > 0:
+ cell_mesh.mesh.material = _highlighted_box_material
+ else:
+ cell_mesh.mesh.material = _standard_box_material
+
+
+func _on_cell_area_entered(area: Area3D, cell_i: int, cell_j: int):
+ #prints("_on_cell_area_entered", cell_i, cell_j)
+ _update_obs(cell_i, cell_j, area.collision_layer, true)
+ if debug_view:
+ _toggle_cell(cell_i, cell_j)
+ #print(_obs_buffer)
+
+
+func _on_cell_area_exited(area: Area3D, cell_i: int, cell_j: int):
+ #prints("_on_cell_area_exited", cell_i, cell_j)
+ _update_obs(cell_i, cell_j, area.collision_layer, false)
+ if debug_view:
+ _toggle_cell(cell_i, cell_j)
+
+
+func _on_cell_body_entered(body: Node3D, cell_i: int, cell_j: int):
+ #prints("_on_cell_body_entered", cell_i, cell_j)
+ _update_obs(cell_i, cell_j, body.collision_layer, true)
+ if debug_view:
+ _toggle_cell(cell_i, cell_j)
+
+
+func _on_cell_body_exited(body: Node3D, cell_i: int, cell_j: int):
+ #prints("_on_cell_body_exited", cell_i, cell_j)
+ _update_obs(cell_i, cell_j, body.collision_layer, false)
+ if debug_view:
+ _toggle_cell(cell_i, cell_j)
diff --git a/SimpleReachGoal/GDScript/addons/godot_rl_agents/sensors/sensors_3d/ISensor3D.gd b/SimpleReachGoal/GDScript/addons/godot_rl_agents/sensors/sensors_3d/ISensor3D.gd
new file mode 100644
index 0000000000000000000000000000000000000000..aca3c2db480c5f61058d565ae4652916af4c51ad
--- /dev/null
+++ b/SimpleReachGoal/GDScript/addons/godot_rl_agents/sensors/sensors_3d/ISensor3D.gd
@@ -0,0 +1,25 @@
+extends Node3D
+class_name ISensor3D
+
+var _obs: Array = []
+var _active := false
+
+
+func get_observation():
+ pass
+
+
+func activate():
+ _active = true
+
+
+func deactivate():
+ _active = false
+
+
+func _update_observation():
+ pass
+
+
+func reset():
+ pass
diff --git a/SimpleReachGoal/GDScript/addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.gd b/SimpleReachGoal/GDScript/addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.gd
new file mode 100644
index 0000000000000000000000000000000000000000..1037e970c3dccd26c6b987533115d12fca790549
--- /dev/null
+++ b/SimpleReachGoal/GDScript/addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.gd
@@ -0,0 +1,21 @@
+extends Node3D
+class_name RGBCameraSensor3D
+var camera_pixels = null
+
+@onready var camera_texture := $Control/TextureRect/CameraTexture as Sprite2D
+@onready var sub_viewport := $SubViewport as SubViewport
+
+
+func get_camera_pixel_encoding():
+ return camera_texture.get_texture().get_image().get_data().hex_encode()
+
+
+func get_camera_shape() -> Array:
+ assert(
+ sub_viewport.size.x >= 36 and sub_viewport.size.y >= 36,
+ "SubViewport size must be 36x36 or larger."
+ )
+ if sub_viewport.transparent_bg:
+ return [4, sub_viewport.size.y, sub_viewport.size.x]
+ else:
+ return [3, sub_viewport.size.y, sub_viewport.size.x]
diff --git a/SimpleReachGoal/GDScript/addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.tscn b/SimpleReachGoal/GDScript/addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.tscn
new file mode 100644
index 0000000000000000000000000000000000000000..052b5577db16ab7d25f5f473a539b3099f400db8
--- /dev/null
+++ b/SimpleReachGoal/GDScript/addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.tscn
@@ -0,0 +1,41 @@
+[gd_scene load_steps=3 format=3 uid="uid://baaywi3arsl2m"]
+
+[ext_resource type="Script" path="res://addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.gd" id="1"]
+
+[sub_resource type="ViewportTexture" id="1"]
+viewport_path = NodePath("SubViewport")
+
+[node name="RGBCameraSensor3D" type="Node3D"]
+script = ExtResource("1")
+
+[node name="RemoteTransform3D" type="RemoteTransform3D" parent="."]
+remote_path = NodePath("../SubViewport/Camera3D")
+
+[node name="SubViewport" type="SubViewport" parent="."]
+size = Vector2i(32, 32)
+render_target_update_mode = 3
+
+[node name="Camera3D" type="Camera3D" parent="SubViewport"]
+near = 0.5
+
+[node name="Control" type="Control" parent="."]
+layout_mode = 3
+anchors_preset = 15
+anchor_right = 1.0
+anchor_bottom = 1.0
+grow_horizontal = 2
+grow_vertical = 2
+
+[node name="TextureRect" type="ColorRect" parent="Control"]
+layout_mode = 0
+offset_left = 1096.0
+offset_top = 534.0
+offset_right = 1114.0
+offset_bottom = 552.0
+scale = Vector2(10, 10)
+color = Color(0.00784314, 0.00784314, 0.00784314, 1)
+
+[node name="CameraTexture" type="Sprite2D" parent="Control/TextureRect"]
+texture = SubResource("1")
+offset = Vector2(9, 9)
+flip_v = true
diff --git a/SimpleReachGoal/GDScript/addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd b/SimpleReachGoal/GDScript/addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd
new file mode 100644
index 0000000000000000000000000000000000000000..1357529f9232c3323316212cc84042bde1afb6f2
--- /dev/null
+++ b/SimpleReachGoal/GDScript/addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd
@@ -0,0 +1,185 @@
+@tool
+extends ISensor3D
+class_name RayCastSensor3D
+@export_flags_3d_physics var collision_mask = 1:
+ get:
+ return collision_mask
+ set(value):
+ collision_mask = value
+ _update()
+@export_flags_3d_physics var boolean_class_mask = 1:
+ get:
+ return boolean_class_mask
+ set(value):
+ boolean_class_mask = value
+ _update()
+
+@export var n_rays_width := 6.0:
+ get:
+ return n_rays_width
+ set(value):
+ n_rays_width = value
+ _update()
+
+@export var n_rays_height := 6.0:
+ get:
+ return n_rays_height
+ set(value):
+ n_rays_height = value
+ _update()
+
+@export var ray_length := 10.0:
+ get:
+ return ray_length
+ set(value):
+ ray_length = value
+ _update()
+
+@export var cone_width := 60.0:
+ get:
+ return cone_width
+ set(value):
+ cone_width = value
+ _update()
+
+@export var cone_height := 60.0:
+ get:
+ return cone_height
+ set(value):
+ cone_height = value
+ _update()
+
+@export var collide_with_areas := false:
+ get:
+ return collide_with_areas
+ set(value):
+ collide_with_areas = value
+ _update()
+
+@export var collide_with_bodies := true:
+ get:
+ return collide_with_bodies
+ set(value):
+ collide_with_bodies = value
+ _update()
+
+@export var class_sensor := false
+
+var rays := []
+var geo = null
+
+
+func _update():
+ if Engine.is_editor_hint():
+ if is_node_ready():
+ _spawn_nodes()
+
+
+func _ready() -> void:
+ if Engine.is_editor_hint():
+ if get_child_count() == 0:
+ _spawn_nodes()
+ else:
+ _spawn_nodes()
+
+
+func _spawn_nodes():
+ print("spawning nodes")
+ for ray in get_children():
+ ray.queue_free()
+ if geo:
+ geo.clear()
+ #$Lines.remove_points()
+ rays = []
+
+ var horizontal_step = cone_width / (n_rays_width)
+ var vertical_step = cone_height / (n_rays_height)
+
+ var horizontal_start = horizontal_step / 2 - cone_width / 2
+ var vertical_start = vertical_step / 2 - cone_height / 2
+
+ var points = []
+
+ for i in n_rays_width:
+ for j in n_rays_height:
+ var angle_w = horizontal_start + i * horizontal_step
+ var angle_h = vertical_start + j * vertical_step
+ #angle_h = 0.0
+ var ray = RayCast3D.new()
+ var cast_to = to_spherical_coords(ray_length, angle_w, angle_h)
+ ray.set_target_position(cast_to)
+
+ points.append(cast_to)
+
+ ray.set_name("node_" + str(i) + " " + str(j))
+ ray.enabled = true
+ ray.collide_with_bodies = collide_with_bodies
+ ray.collide_with_areas = collide_with_areas
+ ray.collision_mask = collision_mask
+ add_child(ray)
+ ray.set_owner(get_tree().edited_scene_root)
+ rays.append(ray)
+ ray.force_raycast_update()
+
+
+# if Engine.editor_hint:
+# _create_debug_lines(points)
+
+
+func _create_debug_lines(points):
+ if not geo:
+ geo = ImmediateMesh.new()
+ add_child(geo)
+
+ geo.clear()
+ geo.begin(Mesh.PRIMITIVE_LINES)
+ for point in points:
+ geo.set_color(Color.AQUA)
+ geo.add_vertex(Vector3.ZERO)
+ geo.add_vertex(point)
+ geo.end()
+
+
+func display():
+ if geo:
+ geo.display()
+
+
+func to_spherical_coords(r, inc, azimuth) -> Vector3:
+ return Vector3(
+ r * sin(deg_to_rad(inc)) * cos(deg_to_rad(azimuth)),
+ r * sin(deg_to_rad(azimuth)),
+ r * cos(deg_to_rad(inc)) * cos(deg_to_rad(azimuth))
+ )
+
+
+func get_observation() -> Array:
+ return self.calculate_raycasts()
+
+
+func calculate_raycasts() -> Array:
+ var result = []
+ for ray in rays:
+ ray.set_enabled(true)
+ ray.force_raycast_update()
+ var distance = _get_raycast_distance(ray)
+
+ result.append(distance)
+ if class_sensor:
+ var hit_class: float = 0
+ if ray.get_collider():
+ var hit_collision_layer = ray.get_collider().collision_layer
+ hit_collision_layer = hit_collision_layer & collision_mask
+ hit_class = (hit_collision_layer & boolean_class_mask) > 0
+ result.append(float(hit_class))
+ ray.set_enabled(false)
+ return result
+
+
+func _get_raycast_distance(ray: RayCast3D) -> float:
+ if !ray.is_colliding():
+ return 0.0
+
+ var distance = (global_transform.origin - ray.get_collision_point()).length()
+ distance = clamp(distance, 0.0, ray_length)
+ return (ray_length - distance) / ray_length
diff --git a/SimpleReachGoal/GDScript/addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.tscn b/SimpleReachGoal/GDScript/addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.tscn
new file mode 100644
index 0000000000000000000000000000000000000000..35f9796596b2fb79bfcfe31e3d3a9637d9008e55
--- /dev/null
+++ b/SimpleReachGoal/GDScript/addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.tscn
@@ -0,0 +1,27 @@
+[gd_scene load_steps=2 format=3 uid="uid://b803cbh1fmy66"]
+
+[ext_resource type="Script" path="res://addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd" id="1"]
+
+[node name="RaycastSensor3D" type="Node3D"]
+script = ExtResource("1")
+n_rays_width = 4.0
+n_rays_height = 2.0
+ray_length = 11.0
+
+[node name="node_1 0" type="RayCast3D" parent="."]
+target_position = Vector3(-1.38686, -2.84701, 10.5343)
+
+[node name="node_1 1" type="RayCast3D" parent="."]
+target_position = Vector3(-1.38686, 2.84701, 10.5343)
+
+[node name="node_2 0" type="RayCast3D" parent="."]
+target_position = Vector3(1.38686, -2.84701, 10.5343)
+
+[node name="node_2 1" type="RayCast3D" parent="."]
+target_position = Vector3(1.38686, 2.84701, 10.5343)
+
+[node name="node_3 0" type="RayCast3D" parent="."]
+target_position = Vector3(4.06608, -2.84701, 9.81639)
+
+[node name="node_3 1" type="RayCast3D" parent="."]
+target_position = Vector3(4.06608, 2.84701, 9.81639)
diff --git a/SimpleReachGoal/GDScript/addons/godot_rl_agents/sync.gd b/SimpleReachGoal/GDScript/addons/godot_rl_agents/sync.gd
new file mode 100644
index 0000000000000000000000000000000000000000..340ec2041bed6488e931f504025bdc54cc828d90
--- /dev/null
+++ b/SimpleReachGoal/GDScript/addons/godot_rl_agents/sync.gd
@@ -0,0 +1,548 @@
+extends Node
+
+# --fixed-fps 2000 --disable-render-loop
+
+enum ControlModes { HUMAN, TRAINING, ONNX_INFERENCE }
+@export var control_mode: ControlModes = ControlModes.TRAINING
+@export_range(1, 10, 1, "or_greater") var action_repeat := 8
+@export_range(0, 10, 0.1, "or_greater") var speed_up := 1.0
+@export var onnx_model_path := ""
+
+# Onnx model stored for each requested path
+var onnx_models: Dictionary
+
+@onready var start_time = Time.get_ticks_msec()
+
+const MAJOR_VERSION := "0"
+const MINOR_VERSION := "7"
+const DEFAULT_PORT := "11008"
+const DEFAULT_SEED := "1"
+var stream: StreamPeerTCP = null
+var connected = false
+var message_center
+var should_connect = true
+
+var all_agents: Array
+var agents_training: Array
+var agents_inference: Array
+var agents_heuristic: Array
+
+## For recording expert demos
+var agent_demo_record: Node
+## File path for writing recorded trajectories
+var expert_demo_save_path: String
+## Stores recorded trajectories
+var demo_trajectories: Array
+## A trajectory includes obs: Array, acts: Array, terminal (set in Python env instead)
+var current_demo_trajectory: Array
+
+var need_to_send_obs = false
+var args = null
+var initialized = false
+var just_reset = false
+var onnx_model = null
+var n_action_steps = 0
+
+var _action_space: Dictionary
+var _action_space_inference: Array[Dictionary] = []
+var _obs_space: Dictionary
+
+
+# Called when the node enters the scene tree for the first time.
+func _ready():
+ await get_tree().root.ready
+ get_tree().set_pause(true)
+ _initialize()
+ await get_tree().create_timer(1.0).timeout
+ get_tree().set_pause(false)
+
+
+func _initialize():
+ _get_agents()
+ args = _get_args()
+ Engine.physics_ticks_per_second = _get_speedup() * 60 # Replace with function body.
+ Engine.time_scale = _get_speedup() * 1.0
+ prints(
+ "physics ticks",
+ Engine.physics_ticks_per_second,
+ Engine.time_scale,
+ _get_speedup(),
+ speed_up
+ )
+
+ _set_heuristic("human", all_agents)
+
+ _initialize_training_agents()
+ _initialize_inference_agents()
+ _initialize_demo_recording()
+
+ _set_seed()
+ _set_action_repeat()
+ initialized = true
+
+
+func _initialize_training_agents():
+ if agents_training.size() > 0:
+ _obs_space = agents_training[0].get_obs_space()
+ _action_space = agents_training[0].get_action_space()
+ connected = connect_to_server()
+ if connected:
+ _set_heuristic("model", agents_training)
+ _handshake()
+ _send_env_info()
+ else:
+ push_warning(
+ "Couldn't connect to Python server, using human controls instead. ",
+ "Did you start the training server using e.g. `gdrl` from the console?"
+ )
+
+
+func _initialize_inference_agents():
+ if agents_inference.size() > 0:
+ if control_mode == ControlModes.ONNX_INFERENCE:
+ assert(
+ FileAccess.file_exists(onnx_model_path),
+ "Onnx Model Path set on Sync node does not exist: %s" % onnx_model_path
+ )
+ onnx_models[onnx_model_path] = ONNXModel.new(onnx_model_path, 1)
+
+ for agent in agents_inference:
+ _action_space_inference.append(agent.get_action_space())
+
+ var agent_onnx_model: ONNXModel
+ if agent.onnx_model_path.is_empty():
+ assert(
+ onnx_models.has(onnx_model_path),
+ (
+ "Node %s has no onnx model path set " % agent.get_path()
+ + "and sync node's control mode is not set to OnnxInference. "
+ + "Either add the path to the AIController, "
+ + "or if you want to use the path set on sync node instead, "
+ + "set control mode to OnnxInference."
+ )
+ )
+ prints(
+ "Info: AIController %s" % agent.get_path(),
+ "has no onnx model path set.",
+ "Using path set on the sync node instead."
+ )
+ agent_onnx_model = onnx_models[onnx_model_path]
+ else:
+ if not onnx_models.has(agent.onnx_model_path):
+ assert(
+ FileAccess.file_exists(agent.onnx_model_path),
+ (
+ "Onnx Model Path set on %s node does not exist: %s"
+ % [agent.get_path(), agent.onnx_model_path]
+ )
+ )
+ onnx_models[agent.onnx_model_path] = ONNXModel.new(agent.onnx_model_path, 1)
+ agent_onnx_model = onnx_models[agent.onnx_model_path]
+
+ agent.onnx_model = agent_onnx_model
+ _set_heuristic("model", agents_inference)
+
+
+func _initialize_demo_recording():
+ if agent_demo_record:
+ expert_demo_save_path = agent_demo_record.expert_demo_save_path
+ assert(
+ not expert_demo_save_path.is_empty(),
+ "Expert demo save path set in %s is empty." % agent_demo_record.get_path()
+ )
+
+ InputMap.add_action("RemoveLastDemoEpisode")
+ InputMap.action_add_event(
+ "RemoveLastDemoEpisode", agent_demo_record.remove_last_episode_key
+ )
+ current_demo_trajectory.resize(2)
+ current_demo_trajectory[0] = []
+ current_demo_trajectory[1] = []
+ agent_demo_record.heuristic = "demo_record"
+
+
+func _physics_process(_delta):
+ # two modes, human control, agent control
+ # pause tree, send obs, get actions, set actions, unpause tree
+
+ _demo_record_process()
+
+ if n_action_steps % action_repeat != 0:
+ n_action_steps += 1
+ return
+
+ n_action_steps += 1
+
+ _training_process()
+ _inference_process()
+ _heuristic_process()
+
+
+func _training_process():
+ if connected:
+ get_tree().set_pause(true)
+
+ if just_reset:
+ just_reset = false
+ var obs = _get_obs_from_agents(agents_training)
+
+ var reply = {"type": "reset", "obs": obs}
+ _send_dict_as_json_message(reply)
+ # this should go straight to getting the action and setting it checked the agent, no need to perform one phyics tick
+ get_tree().set_pause(false)
+ return
+
+ if need_to_send_obs:
+ need_to_send_obs = false
+ var reward = _get_reward_from_agents()
+ var done = _get_done_from_agents()
+ #_reset_agents_if_done() # this ensures the new observation is from the next env instance : NEEDS REFACTOR
+
+ var obs = _get_obs_from_agents(agents_training)
+
+ var reply = {"type": "step", "obs": obs, "reward": reward, "done": done}
+ _send_dict_as_json_message(reply)
+
+ var handled = handle_message()
+
+
+func _inference_process():
+ if agents_inference.size() > 0:
+ var obs: Array = _get_obs_from_agents(agents_inference)
+ var actions = []
+
+ for agent_id in range(0, agents_inference.size()):
+ var action = agents_inference[agent_id].onnx_model.run_inference(
+ obs[agent_id]["obs"], 1.0
+ )
+ action["output"] = clamp_array(action["output"], -1.0, 1.0)
+ var action_dict = _extract_action_dict(
+ action["output"], _action_space_inference[agent_id]
+ )
+ actions.append(action_dict)
+
+ _set_agent_actions(actions, agents_inference)
+ _reset_agents_if_done(agents_inference)
+ get_tree().set_pause(false)
+
+
+func _demo_record_process():
+ if not agent_demo_record:
+ return
+
+ if Input.is_action_just_pressed("RemoveLastDemoEpisode"):
+ print("[Sync script][Demo recorder] Removing last recorded episode.")
+ demo_trajectories.remove_at(demo_trajectories.size() - 1)
+ print("Remaining episode count: %d" % demo_trajectories.size())
+
+ if n_action_steps % agent_demo_record.action_repeat != 0:
+ return
+
+ var obs_dict: Dictionary = agent_demo_record.get_obs()
+
+ # Get the current obs from the agent
+ assert(
+ obs_dict.has("obs"),
+ "Demo recorder needs an 'obs' key in get_obs() returned dictionary to record obs from."
+ )
+ current_demo_trajectory[0].append(obs_dict.obs)
+
+ # Get the action applied for the current obs from the agent
+ agent_demo_record.set_action()
+ var acts = agent_demo_record.get_action()
+
+ var terminal = agent_demo_record.get_done()
+ # Record actions only for non-terminal states
+ if terminal:
+ agent_demo_record.set_done_false()
+ else:
+ current_demo_trajectory[1].append(acts)
+
+ if terminal:
+ #current_demo_trajectory[2].append(true)
+ demo_trajectories.append(current_demo_trajectory.duplicate(true))
+ print("[Sync script][Demo recorder] Recorded episode count: %d" % demo_trajectories.size())
+ current_demo_trajectory[0].clear()
+ current_demo_trajectory[1].clear()
+
+
+func _heuristic_process():
+ for agent in agents_heuristic:
+ _reset_agents_if_done(agents_heuristic)
+
+
+func _extract_action_dict(action_array: Array, action_space: Dictionary):
+ var index = 0
+ var result = {}
+ for key in action_space.keys():
+ var size = action_space[key]["size"]
+ if action_space[key]["action_type"] == "discrete":
+ result[key] = round(action_array[index])
+ else:
+ result[key] = action_array.slice(index, index + size)
+ index += size
+
+ return result
+
+
+## For AIControllers that inherit mode from sync, sets the correct mode.
+func _set_agent_mode(agent: Node):
+ var agent_inherits_mode: bool = agent.control_mode == agent.ControlModes.INHERIT_FROM_SYNC
+
+ if agent_inherits_mode:
+ match control_mode:
+ ControlModes.HUMAN:
+ agent.control_mode = agent.ControlModes.HUMAN
+ ControlModes.TRAINING:
+ agent.control_mode = agent.ControlModes.TRAINING
+ ControlModes.ONNX_INFERENCE:
+ agent.control_mode = agent.ControlModes.ONNX_INFERENCE
+
+
+func _get_agents():
+ all_agents = get_tree().get_nodes_in_group("AGENT")
+ for agent in all_agents:
+ _set_agent_mode(agent)
+
+ if agent.control_mode == agent.ControlModes.TRAINING:
+ agents_training.append(agent)
+ elif agent.control_mode == agent.ControlModes.ONNX_INFERENCE:
+ agents_inference.append(agent)
+ elif agent.control_mode == agent.ControlModes.HUMAN:
+ agents_heuristic.append(agent)
+ elif agent.control_mode == agent.ControlModes.RECORD_EXPERT_DEMOS:
+ assert(
+ not agent_demo_record,
+ "Currently only a single AIController can be used for recording expert demos."
+ )
+ agent_demo_record = agent
+
+
+func _set_heuristic(heuristic, agents: Array):
+ for agent in agents:
+ agent.set_heuristic(heuristic)
+
+
+func _handshake():
+ print("performing handshake")
+
+ var json_dict = _get_dict_json_message()
+ assert(json_dict["type"] == "handshake")
+ var major_version = json_dict["major_version"]
+ var minor_version = json_dict["minor_version"]
+ if major_version != MAJOR_VERSION:
+ print("WARNING: major verison mismatch ", major_version, " ", MAJOR_VERSION)
+ if minor_version != MINOR_VERSION:
+ print("WARNING: minor verison mismatch ", minor_version, " ", MINOR_VERSION)
+
+ print("handshake complete")
+
+
+func _get_dict_json_message():
+ # returns a dictionary from of the most recent message
+ # this is not waiting
+ while stream.get_available_bytes() == 0:
+ stream.poll()
+ if stream.get_status() != 2:
+ print("server disconnected status, closing")
+ get_tree().quit()
+ return null
+
+ OS.delay_usec(10)
+
+ var message = stream.get_string()
+ var json_data = JSON.parse_string(message)
+
+ return json_data
+
+
+func _send_dict_as_json_message(dict):
+ stream.put_string(JSON.stringify(dict, "", false))
+
+
+func _send_env_info():
+ var json_dict = _get_dict_json_message()
+ assert(json_dict["type"] == "env_info")
+
+ var message = {
+ "type": "env_info",
+ "observation_space": _obs_space,
+ "action_space": _action_space,
+ "n_agents": len(agents_training)
+ }
+ _send_dict_as_json_message(message)
+
+
+func connect_to_server():
+ print("Waiting for one second to allow server to start")
+ OS.delay_msec(1000)
+ print("trying to connect to server")
+ stream = StreamPeerTCP.new()
+
+ # "localhost" was not working on windows VM, had to use the IP
+ var ip = "127.0.0.1"
+ var port = _get_port()
+ var connect = stream.connect_to_host(ip, port)
+ stream.set_no_delay(true) # TODO check if this improves performance or not
+ stream.poll()
+ # Fetch the status until it is either connected (2) or failed to connect (3)
+ while stream.get_status() < 2:
+ stream.poll()
+ return stream.get_status() == 2
+
+
+func _get_args():
+ print("getting command line arguments")
+ var arguments = {}
+ for argument in OS.get_cmdline_args():
+ print(argument)
+ if argument.find("=") > -1:
+ var key_value = argument.split("=")
+ arguments[key_value[0].lstrip("--")] = key_value[1]
+ else:
+ # Options without an argument will be present in the dictionary,
+ # with the value set to an empty string.
+ arguments[argument.lstrip("--")] = ""
+
+ return arguments
+
+
+func _get_speedup():
+ print(args)
+ return args.get("speedup", str(speed_up)).to_float()
+
+
+func _get_port():
+ return args.get("port", DEFAULT_PORT).to_int()
+
+
+func _set_seed():
+ var _seed = args.get("env_seed", DEFAULT_SEED).to_int()
+ seed(_seed)
+
+
+func _set_action_repeat():
+ action_repeat = args.get("action_repeat", str(action_repeat)).to_int()
+
+
+func disconnect_from_server():
+ stream.disconnect_from_host()
+
+
+func handle_message() -> bool:
+ # get json message: reset, step, close
+ var message = _get_dict_json_message()
+ if message["type"] == "close":
+ print("received close message, closing game")
+ get_tree().quit()
+ get_tree().set_pause(false)
+ return true
+
+ if message["type"] == "reset":
+ print("resetting all agents")
+ _reset_agents()
+ just_reset = true
+ get_tree().set_pause(false)
+ #print("resetting forcing draw")
+# RenderingServer.force_draw()
+# var obs = _get_obs_from_agents()
+# print("obs ", obs)
+# var reply = {
+# "type": "reset",
+# "obs": obs
+# }
+# _send_dict_as_json_message(reply)
+ return true
+
+ if message["type"] == "call":
+ var method = message["method"]
+ var returns = _call_method_on_agents(method)
+ var reply = {"type": "call", "returns": returns}
+ print("calling method from Python")
+ _send_dict_as_json_message(reply)
+ return handle_message()
+
+ if message["type"] == "action":
+ var action = message["action"]
+ _set_agent_actions(action, agents_training)
+ need_to_send_obs = true
+ get_tree().set_pause(false)
+ return true
+
+ print("message was not handled")
+ return false
+
+
+func _call_method_on_agents(method):
+ var returns = []
+ for agent in all_agents:
+ returns.append(agent.call(method))
+
+ return returns
+
+
+func _reset_agents_if_done(agents = all_agents):
+ for agent in agents:
+ if agent.get_done():
+ agent.set_done_false()
+
+
+func _reset_agents(agents = all_agents):
+ for agent in agents:
+ agent.needs_reset = true
+ #agent.reset()
+
+
+func _get_obs_from_agents(agents: Array = all_agents):
+ var obs = []
+ for agent in agents:
+ obs.append(agent.get_obs())
+ return obs
+
+
+func _get_reward_from_agents(agents: Array = agents_training):
+ var rewards = []
+ for agent in agents:
+ rewards.append(agent.get_reward())
+ agent.zero_reward()
+ return rewards
+
+
+func _get_done_from_agents(agents: Array = agents_training):
+ var dones = []
+ for agent in agents:
+ var done = agent.get_done()
+ if done:
+ agent.set_done_false()
+ dones.append(done)
+ return dones
+
+
+func _set_agent_actions(actions, agents: Array = all_agents):
+ for i in range(len(actions)):
+ agents[i].set_action(actions[i])
+
+
+func clamp_array(arr: Array, min: float, max: float):
+ var output: Array = []
+ for a in arr:
+ output.append(clamp(a, min, max))
+ return output
+
+
+## Save recorded export demos on window exit (Close game window instead of "Stop" button in Godot Editor)
+func _notification(what):
+ if demo_trajectories.size() == 0 or expert_demo_save_path.is_empty():
+ return
+
+ if what == NOTIFICATION_PREDELETE:
+ var json_string = JSON.stringify(demo_trajectories, "", false)
+ var file = FileAccess.open(expert_demo_save_path, FileAccess.WRITE)
+
+ if not file:
+ var error: Error = FileAccess.get_open_error()
+ assert(not error, "There was an error opening the file: %d" % error)
+
+ file.store_line(json_string)
+ var error = file.get_error()
+ assert(not error, "There was an error after trying to write to the file: %d" % error)
diff --git a/SimpleReachGoal/GDScript/icon.svg b/SimpleReachGoal/GDScript/icon.svg
new file mode 100644
index 0000000000000000000000000000000000000000..b370ceb72740b9a759fe11b364f0d4de27df42f8
--- /dev/null
+++ b/SimpleReachGoal/GDScript/icon.svg
@@ -0,0 +1 @@
+
diff --git a/SimpleReachGoal/GDScript/project.godot b/SimpleReachGoal/GDScript/project.godot
new file mode 100644
index 0000000000000000000000000000000000000000..a901e02ac6ff78da5143df2b6c934baa8e8b4b64
--- /dev/null
+++ b/SimpleReachGoal/GDScript/project.godot
@@ -0,0 +1,24 @@
+; Engine configuration file.
+; It's best edited using the editor UI and not directly,
+; since the parameters that go here are not all obvious.
+;
+; Format:
+; [section] ; section goes between []
+; param=value ; assign values to parameters
+
+config_version=5
+
+[application]
+
+config/name="SimpleReachGoal"
+run/main_scene="res://scenes/training_scene/training_scene.tscn"
+config/features=PackedStringArray("4.3", "C#", "Forward Plus")
+config/icon="res://icon.svg"
+
+[dotnet]
+
+project/assembly_name="SimpleReachGoal"
+
+[editor_plugins]
+
+enabled=PackedStringArray("res://addons/godot_rl_agents/plugin.cfg")
diff --git a/SimpleReachGoal/GDScript/scenes/game_scene/area_position_randomizer.gd b/SimpleReachGoal/GDScript/scenes/game_scene/area_position_randomizer.gd
new file mode 100644
index 0000000000000000000000000000000000000000..e1c3f6ce2f800d8db8300b16e567a5bed4a2ce3f
--- /dev/null
+++ b/SimpleReachGoal/GDScript/scenes/game_scene/area_position_randomizer.gd
@@ -0,0 +1,19 @@
+extends Node3D
+class_name AreaPositionRandomizer
+
+var area: Area3D
+var area_spawn_points: Array[MeshInstance3D]
+
+
+func _ready():
+ for node in get_children():
+ if node is Area3D:
+ area = node
+ else:
+ area_spawn_points.append(node)
+ node.visible = false
+
+
+func reset():
+ var new_area_position: Vector3 = area_spawn_points.pick_random().global_position
+ area.global_position = new_area_position
diff --git a/SimpleReachGoal/GDScript/scenes/game_scene/game_scene.tscn b/SimpleReachGoal/GDScript/scenes/game_scene/game_scene.tscn
new file mode 100644
index 0000000000000000000000000000000000000000..e4ca35f27c94be5e19a676a769f8b25f5f63f287
--- /dev/null
+++ b/SimpleReachGoal/GDScript/scenes/game_scene/game_scene.tscn
@@ -0,0 +1,190 @@
+[gd_scene load_steps=13 format=3 uid="uid://qofctg4fc0c2"]
+
+[ext_resource type="Script" path="res://scenes/game_scene/area_position_randomizer.gd" id="1_btskf"]
+[ext_resource type="Script" path="res://scenes/game_scene/game_scene_manager.gd" id="1_ihj32"]
+[ext_resource type="PackedScene" uid="uid://fhnd4o88w5p4" path="res://scenes/player/player.tscn" id="3_j13wo"]
+
+[sub_resource type="StandardMaterial3D" id="StandardMaterial3D_g301e"]
+transparency = 1
+albedo_color = Color(0, 1, 0.166667, 0.756863)
+
+[sub_resource type="BoxMesh" id="BoxMesh_wnjao"]
+
+[sub_resource type="BoxShape3D" id="BoxShape3D_mblpq"]
+
+[sub_resource type="StandardMaterial3D" id="StandardMaterial3D_irk0a"]
+transparency = 1
+albedo_color = Color(0, 1, 0.166667, 0.313726)
+
+[sub_resource type="StandardMaterial3D" id="StandardMaterial3D_t0cxi"]
+transparency = 1
+albedo_color = Color(1, 0, 0, 0.756863)
+
+[sub_resource type="StandardMaterial3D" id="StandardMaterial3D_qu1jy"]
+transparency = 1
+albedo_color = Color(1, 0, 0, 0.313726)
+
+[sub_resource type="StandardMaterial3D" id="StandardMaterial3D_1ahva"]
+albedo_color = Color(0.8, 0.8, 0.8, 1)
+
+[sub_resource type="BoxMesh" id="BoxMesh_eh8qq"]
+material = SubResource("StandardMaterial3D_1ahva")
+size = Vector3(10, 0.1, 10)
+
+[sub_resource type="BoxShape3D" id="BoxShape3D_wmgsa"]
+size = Vector3(10, 1, 10)
+
+[node name="GameScene" type="Node3D" node_paths=PackedStringArray("goal_manager", "obstacle_manager", "player")]
+script = ExtResource("1_ihj32")
+goal_manager = NodePath("GoalManager")
+obstacle_manager = NodePath("ObstacleManager")
+player = NodePath("Player")
+
+[node name="GoalManager" type="Node3D" parent="."]
+script = ExtResource("1_btskf")
+
+[node name="Goal" type="Area3D" parent="GoalManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 4, 0.5, -4)
+collision_layer = 2
+monitorable = false
+
+[node name="MeshInstance3D" type="MeshInstance3D" parent="GoalManager/Goal"]
+material_override = SubResource("StandardMaterial3D_g301e")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="CollisionShape3D" type="CollisionShape3D" parent="GoalManager/Goal"]
+shape = SubResource("BoxShape3D_mblpq")
+
+[node name="SpawnPosition" type="MeshInstance3D" parent="GoalManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 4, 0.5, 4)
+material_override = SubResource("StandardMaterial3D_irk0a")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition2" type="MeshInstance3D" parent="GoalManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -4, 0.5, 4)
+material_override = SubResource("StandardMaterial3D_irk0a")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition3" type="MeshInstance3D" parent="GoalManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -4, 0.5, -4)
+material_override = SubResource("StandardMaterial3D_irk0a")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition4" type="MeshInstance3D" parent="GoalManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 4, 0.5, -4)
+material_override = SubResource("StandardMaterial3D_irk0a")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="ObstacleManager" type="Node3D" parent="."]
+script = ExtResource("1_btskf")
+
+[node name="Obstacle" type="Area3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 2, 0.5, -2)
+collision_layer = 4
+monitorable = false
+
+[node name="MeshInstance3D" type="MeshInstance3D" parent="ObstacleManager/Obstacle"]
+material_override = SubResource("StandardMaterial3D_t0cxi")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="CollisionShape3D" type="CollisionShape3D" parent="ObstacleManager/Obstacle"]
+shape = SubResource("BoxShape3D_mblpq")
+
+[node name="SpawnPosition" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0.5, -2)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition2" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0.5, 2)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition3" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 2, 0.5, 0)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition4" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -2, 0.5, 0)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition5" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -2, 0.5, -1)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition6" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -2, 0.5, -2)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition7" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -1, 0.5, -2)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition8" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0.5, -2)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition9" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 2, 0.5, -2)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition10" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 2, 0.5, -1)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition11" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 2, 0.5, 1)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition12" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 2, 0.5, 2)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition13" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0.5, 2)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition14" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -1, 0.5, 2)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition15" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -2, 0.5, 2)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="SpawnPosition16" type="MeshInstance3D" parent="ObstacleManager"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -2, 0.5, 1)
+material_override = SubResource("StandardMaterial3D_qu1jy")
+mesh = SubResource("BoxMesh_wnjao")
+
+[node name="Ground" type="StaticBody3D" parent="."]
+
+[node name="MeshInstance3D" type="MeshInstance3D" parent="Ground"]
+mesh = SubResource("BoxMesh_eh8qq")
+skeleton = NodePath("../..")
+
+[node name="CollisionShape3D" type="CollisionShape3D" parent="Ground"]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, -0.45, 0)
+shape = SubResource("BoxShape3D_wmgsa")
+
+[node name="Player" parent="." node_paths=PackedStringArray("game_scene_manager", "goal", "obstacle", "ai_controller") instance=ExtResource("3_j13wo")]
+game_scene_manager = NodePath("..")
+goal = NodePath("../GoalManager/Goal")
+obstacle = NodePath("../ObstacleManager/Obstacle")
+ai_controller = NodePath("AIController3D")
+
+[connection signal="body_entered" from="GoalManager/Goal" to="Player" method="_on_goal_body_entered"]
+[connection signal="body_entered" from="ObstacleManager/Obstacle" to="Player" method="_on_obstacle_body_entered"]
diff --git a/SimpleReachGoal/GDScript/scenes/game_scene/game_scene_manager.gd b/SimpleReachGoal/GDScript/scenes/game_scene/game_scene_manager.gd
new file mode 100644
index 0000000000000000000000000000000000000000..678734a7f597541716797773e17eaacb4e365e67
--- /dev/null
+++ b/SimpleReachGoal/GDScript/scenes/game_scene/game_scene_manager.gd
@@ -0,0 +1,16 @@
+extends Node3D
+class_name GameSceneManager
+
+@export var goal_manager: AreaPositionRandomizer
+@export var obstacle_manager: AreaPositionRandomizer
+@export var player: Player
+
+
+func _ready() -> void:
+ reset()
+
+
+func reset():
+ goal_manager.reset()
+ obstacle_manager.reset()
+ player.reset()
diff --git a/SimpleReachGoal/GDScript/scenes/player/player.gd b/SimpleReachGoal/GDScript/scenes/player/player.gd
new file mode 100644
index 0000000000000000000000000000000000000000..c02f322983f16271990be62d51cd1a1afeef96b5
--- /dev/null
+++ b/SimpleReachGoal/GDScript/scenes/player/player.gd
@@ -0,0 +1,65 @@
+extends CharacterBody3D
+class_name Player
+
+@export var game_scene_manager: GameSceneManager
+@export var goal: Area3D
+@export var obstacle: Area3D
+
+@export var ai_controller: PlayerAIController
+@export var speed = 5.0
+
+@onready var initial_transform = transform
+
+var requested_movement: Vector2
+
+
+func _physics_process(delta: float) -> void:
+ if not is_on_floor():
+ velocity += get_gravity() * delta
+
+ # If controlled by human, takes the keyboard arrows as input
+ # otherwise, requested_movement will be set by the AIController based on RL agent's output actions
+ if ai_controller.heuristic == "human":
+ requested_movement = Input.get_vector("ui_left", "ui_right", "ui_up", "ui_down")
+
+ requested_movement = requested_movement.limit_length(1.0) * speed
+
+ velocity = Vector3(requested_movement.x, velocity.y, requested_movement.y)
+
+ # We only move when the episode is not marked as done
+ # to prevent repeating a possibly wrong action from the previous episode.
+ # This is related to the sync node Action Repeat functionality,
+ # we don't get a new action for every physics step. This check may
+ # not be required for every env, and is not used in all examples.
+ if not ai_controller.done:
+ move_and_slide()
+
+ reset_on_player_falling()
+
+
+## Resets the game if the player has fallen down
+func reset_on_player_falling():
+ if global_position.y < -1.0:
+ game_over(-1.0)
+
+
+## Ends the game, setting an optional reward
+func game_over(reward: float = 0.0):
+ ai_controller.reward += reward
+ game_scene_manager.reset()
+
+
+## Resets the player and AIController
+func reset():
+ ai_controller.end_episode()
+ transform = initial_transform
+
+
+## When the goal is entered, we restart the game with a positive reward
+func _on_goal_body_entered(body: Node3D) -> void:
+ game_over(1.0)
+
+
+## When the obstacle is entered, we restart the game with a negative reward
+func _on_obstacle_body_entered(body: Node3D) -> void:
+ game_over(-1.0)
diff --git a/SimpleReachGoal/GDScript/scenes/player/player.tscn b/SimpleReachGoal/GDScript/scenes/player/player.tscn
new file mode 100644
index 0000000000000000000000000000000000000000..06d45de3c5dc59634074b2d1cbebc559fadaf980
--- /dev/null
+++ b/SimpleReachGoal/GDScript/scenes/player/player.tscn
@@ -0,0 +1,498 @@
+[gd_scene load_steps=7 format=3 uid="uid://fhnd4o88w5p4"]
+
+[ext_resource type="Script" path="res://scenes/player/player.gd" id="1_s6f1a"]
+[ext_resource type="Script" path="res://scenes/player/player_ai_controller.gd" id="2_suigr"]
+[ext_resource type="Script" path="res://addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd" id="3_qsyok"]
+
+[sub_resource type="StandardMaterial3D" id="StandardMaterial3D_owc64"]
+albedo_color = Color(0.929563, 0.63943, 7.70092e-07, 1)
+
+[sub_resource type="CapsuleMesh" id="CapsuleMesh_jc5om"]
+material = SubResource("StandardMaterial3D_owc64")
+radius = 0.25
+height = 1.0
+
+[sub_resource type="CapsuleShape3D" id="CapsuleShape3D_2gph3"]
+radius = 0.25
+height = 1.0
+
+[node name="Player" type="CharacterBody3D" node_paths=PackedStringArray("ai_controller")]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0.5, 0)
+script = ExtResource("1_s6f1a")
+ai_controller = NodePath("AIController3D")
+
+[node name="MeshInstance3D" type="MeshInstance3D" parent="."]
+mesh = SubResource("CapsuleMesh_jc5om")
+skeleton = NodePath("../..")
+
+[node name="CollisionShape3D" type="CollisionShape3D" parent="."]
+shape = SubResource("CapsuleShape3D_2gph3")
+
+[node name="AIController3D" type="Node3D" parent="." node_paths=PackedStringArray("player", "raycast_sensors")]
+script = ExtResource("2_suigr")
+player = NodePath("..")
+raycast_sensors = [NodePath("GoalRaycastSensor"), NodePath("ObstacleRaycastSensor"), NodePath("GroundRaycastSensor")]
+
+[node name="GoalRaycastSensor" type="Node3D" parent="AIController3D"]
+script = ExtResource("3_qsyok")
+collision_mask = 2
+boolean_class_mask = 0
+n_rays_width = 32.0
+n_rays_height = 1.0
+cone_width = 360.0
+cone_height = 0.0
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_0 0" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-0.980171, 0, -9.95185)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_1 0" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-2.90285, 0, -9.5694)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_2 0" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-4.71397, 0, -8.81921)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_3 0" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-6.34393, 0, -7.7301)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_4 0" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-7.7301, 0, -6.34393)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_5 0" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-8.81921, 0, -4.71397)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57424" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-9.5694, 0, -2.90285)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57425" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-9.95185, 0, -0.980171)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57426" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-9.95185, 0, 0.980171)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57427" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-9.5694, 0, 2.90285)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57428" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-8.81921, 0, 4.71397)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57429" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-7.7301, 0, 6.34393)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_12 0" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-6.34393, 0, 7.7301)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_13 0" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-4.71397, 0, 8.81921)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_14 0" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-2.90285, 0, 9.5694)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_15 0" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(-0.980171, 0, 9.95185)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57430" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(0.980171, 0, 9.95185)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57431" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(2.90285, 0, 9.5694)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57432" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(4.71397, 0, 8.81921)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57433" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(6.34393, 0, 7.7301)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57434" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(7.7301, 0, 6.34393)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57435" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(8.81921, 0, 4.71397)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57436" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(9.5694, 0, 2.90285)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57437" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(9.95185, 0, 0.980171)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57438" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(9.95185, 0, -0.980171)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57439" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(9.5694, 0, -2.90285)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57440" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(8.81921, 0, -4.71397)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57441" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(7.7301, 0, -6.34393)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57442" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(6.34393, 0, -7.7301)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57443" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(4.71397, 0, -8.81921)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57444" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(2.90285, 0, -9.5694)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@57445" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
+target_position = Vector3(0.980171, 0, -9.95185)
+collision_mask = 2
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="ObstacleRaycastSensor" type="Node3D" parent="AIController3D"]
+script = ExtResource("3_qsyok")
+collision_mask = 4
+boolean_class_mask = 0
+n_rays_width = 32.0
+n_rays_height = 1.0
+cone_width = 360.0
+cone_height = 0.0
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_0 0" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-0.980171, 0, -9.95185)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_1 0" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-2.90285, 0, -9.5694)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_2 0" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-4.71397, 0, -8.81921)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_3 0" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-6.34393, 0, -7.7301)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_4 0" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-7.7301, 0, -6.34393)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_5 0" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-8.81921, 0, -4.71397)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56972" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-9.5694, 0, -2.90285)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56973" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-9.95185, 0, -0.980171)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56974" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-9.95185, 0, 0.980171)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56975" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-9.5694, 0, 2.90285)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56976" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-8.81921, 0, 4.71397)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56977" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-7.7301, 0, 6.34393)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_12 0" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-6.34393, 0, 7.7301)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_13 0" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-4.71397, 0, 8.81921)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_14 0" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-2.90285, 0, 9.5694)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="node_15 0" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(-0.980171, 0, 9.95185)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56978" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(0.980171, 0, 9.95185)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56979" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(2.90285, 0, 9.5694)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56980" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(4.71397, 0, 8.81921)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56981" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(6.34393, 0, 7.7301)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56982" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(7.7301, 0, 6.34393)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56983" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(8.81921, 0, 4.71397)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56984" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(9.5694, 0, 2.90285)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56985" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(9.95185, 0, 0.980171)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56986" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(9.95185, 0, -0.980171)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56987" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(9.5694, 0, -2.90285)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56988" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(8.81921, 0, -4.71397)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56989" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(7.7301, 0, -6.34393)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56990" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(6.34393, 0, -7.7301)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56991" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(4.71397, 0, -8.81921)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56992" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(2.90285, 0, -9.5694)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="@RayCast3D@56993" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
+target_position = Vector3(0.980171, 0, -9.95185)
+collision_mask = 4
+collide_with_areas = true
+collide_with_bodies = false
+
+[node name="GroundRaycastSensor" type="Node3D" parent="AIController3D"]
+transform = Transform3D(1, 0, 0, 0, -4.37114e-08, -1, 0, 1, -4.37114e-08, 0, 0, 0)
+script = ExtResource("3_qsyok")
+boolean_class_mask = 0
+n_rays_width = 4.0
+n_rays_height = 4.0
+ray_length = 2.0
+cone_width = 90.0
+cone_height = 90.0
+
+[node name="node_0 0" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(-0.92388, -1.11114, 1.38268)
+
+[node name="@RayCast3D@24718" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(-1.08979, -0.390181, 1.63099)
+
+[node name="@RayCast3D@24719" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(-1.08979, 0.390181, 1.63099)
+
+[node name="@RayCast3D@24720" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(-0.92388, 1.11114, 1.38268)
+
+[node name="node_1 0" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(-0.324423, -1.11114, 1.63099)
+
+[node name="@RayCast3D@24721" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(-0.382683, -0.390181, 1.92388)
+
+[node name="@RayCast3D@24722" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(-0.382683, 0.390181, 1.92388)
+
+[node name="@RayCast3D@24723" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(-0.324423, 1.11114, 1.63099)
+
+[node name="@RayCast3D@24724" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(0.324423, -1.11114, 1.63099)
+
+[node name="@RayCast3D@24725" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(0.382683, -0.390181, 1.92388)
+
+[node name="@RayCast3D@24726" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(0.382683, 0.390181, 1.92388)
+
+[node name="@RayCast3D@24727" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(0.324423, 1.11114, 1.63099)
+
+[node name="@RayCast3D@24728" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(0.92388, -1.11114, 1.38268)
+
+[node name="@RayCast3D@24729" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(1.08979, -0.390181, 1.63099)
+
+[node name="@RayCast3D@24730" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(1.08979, 0.390181, 1.63099)
+
+[node name="@RayCast3D@24731" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
+target_position = Vector3(0.92388, 1.11114, 1.38268)
diff --git a/SimpleReachGoal/GDScript/scenes/player/player_ai_controller.gd b/SimpleReachGoal/GDScript/scenes/player/player_ai_controller.gd
new file mode 100644
index 0000000000000000000000000000000000000000..6d4343393b6c57ee9c302ccb747943860f1c05fb
--- /dev/null
+++ b/SimpleReachGoal/GDScript/scenes/player/player_ai_controller.gd
@@ -0,0 +1,48 @@
+extends AIController3D
+class_name PlayerAIController
+
+@export var player: Player
+@export var raycast_sensors: Array[RayCastSensor3D]
+
+
+func _physics_process(delta):
+ n_steps += 1
+
+ if n_steps > reset_after:
+ player.game_scene_manager.reset()
+
+
+func end_episode():
+ done = true
+ reset()
+
+
+func get_obs() -> Dictionary:
+ var obs: PackedFloat32Array = []
+ for sensor in raycast_sensors:
+ obs.append_array(sensor.get_observation())
+
+ var level_size: float = 10
+ var relative_goal_position: Vector3 = player.to_local(player.goal.global_position)
+ var relative_obstacle_position: Vector3 = player.to_local(player.obstacle.global_position)
+ obs.append_array(
+ [
+ relative_goal_position.x / level_size,
+ relative_goal_position.z / level_size,
+ relative_obstacle_position.x / level_size,
+ relative_obstacle_position.z / level_size
+ ]
+ )
+ return {"obs": obs}
+
+
+func get_reward() -> float:
+ return reward
+
+
+func get_action_space() -> Dictionary:
+ return {"move_action": {"size": 2, "action_type": "continuous"}}
+
+
+func set_action(action) -> void:
+ player.requested_movement = Vector2(action.move_action[0], action.move_action[1])
diff --git a/SimpleReachGoal/GDScript/scenes/training_scene/training_scene.tscn b/SimpleReachGoal/GDScript/scenes/training_scene/training_scene.tscn
new file mode 100644
index 0000000000000000000000000000000000000000..928701e55d87d2a39d1a48675722f58c9214fce3
--- /dev/null
+++ b/SimpleReachGoal/GDScript/scenes/training_scene/training_scene.tscn
@@ -0,0 +1,82 @@
+[gd_scene load_steps=6 format=3 uid="uid://b12majbajmkqq"]
+
+[ext_resource type="PackedScene" uid="uid://qofctg4fc0c2" path="res://scenes/game_scene/game_scene.tscn" id="1_pdcwe"]
+[ext_resource type="Script" path="res://addons/godot_rl_agents/sync.gd" id="2_7kqnq"]
+
+[sub_resource type="ProceduralSkyMaterial" id="ProceduralSkyMaterial_kbbm2"]
+sky_horizon_color = Color(0.64625, 0.65575, 0.67075, 1)
+ground_horizon_color = Color(0.64625, 0.65575, 0.67075, 1)
+
+[sub_resource type="Sky" id="Sky_lpkw7"]
+sky_material = SubResource("ProceduralSkyMaterial_kbbm2")
+
+[sub_resource type="Environment" id="Environment_3ytk2"]
+background_mode = 2
+sky = SubResource("Sky_lpkw7")
+tonemap_mode = 2
+glow_enabled = true
+
+[node name="TrainingScene" type="Node3D"]
+
+[node name="WorldEnvironment" type="WorldEnvironment" parent="."]
+environment = SubResource("Environment_3ytk2")
+
+[node name="DirectionalLight3D" type="DirectionalLight3D" parent="."]
+transform = Transform3D(-0.866024, -0.433016, 0.250001, 0, 0.499998, 0.866026, -0.500003, 0.749999, -0.43301, 0, 0, 0)
+shadow_enabled = true
+
+[node name="GameScene" parent="." node_paths=PackedStringArray("goal_manager", "obstacle_manager", "player") instance=ExtResource("1_pdcwe")]
+goal_manager = NodePath("GoalManager")
+obstacle_manager = NodePath("ObstacleManager")
+player = NodePath("Player")
+
+[node name="GameScene2" parent="." node_paths=PackedStringArray("goal_manager", "obstacle_manager", "player") instance=ExtResource("1_pdcwe")]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 100, 0, 0)
+goal_manager = NodePath("GoalManager")
+obstacle_manager = NodePath("ObstacleManager")
+player = NodePath("Player")
+
+[node name="GameScene3" parent="." node_paths=PackedStringArray("goal_manager", "obstacle_manager", "player") instance=ExtResource("1_pdcwe")]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 200, 0, 0)
+goal_manager = NodePath("GoalManager")
+obstacle_manager = NodePath("ObstacleManager")
+player = NodePath("Player")
+
+[node name="GameScene4" parent="." node_paths=PackedStringArray("goal_manager", "obstacle_manager", "player") instance=ExtResource("1_pdcwe")]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 300, 0, 0)
+goal_manager = NodePath("GoalManager")
+obstacle_manager = NodePath("ObstacleManager")
+player = NodePath("Player")
+
+[node name="GameScene5" parent="." node_paths=PackedStringArray("goal_manager", "obstacle_manager", "player") instance=ExtResource("1_pdcwe")]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 100)
+goal_manager = NodePath("GoalManager")
+obstacle_manager = NodePath("ObstacleManager")
+player = NodePath("Player")
+
+[node name="GameScene6" parent="." node_paths=PackedStringArray("goal_manager", "obstacle_manager", "player") instance=ExtResource("1_pdcwe")]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 100, 0, 100)
+goal_manager = NodePath("GoalManager")
+obstacle_manager = NodePath("ObstacleManager")
+player = NodePath("Player")
+
+[node name="GameScene7" parent="." node_paths=PackedStringArray("goal_manager", "obstacle_manager", "player") instance=ExtResource("1_pdcwe")]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 200, 0, 100)
+goal_manager = NodePath("GoalManager")
+obstacle_manager = NodePath("ObstacleManager")
+player = NodePath("Player")
+
+[node name="GameScene8" parent="." node_paths=PackedStringArray("goal_manager", "obstacle_manager", "player") instance=ExtResource("1_pdcwe")]
+transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 300, 0, 100)
+goal_manager = NodePath("GoalManager")
+obstacle_manager = NodePath("ObstacleManager")
+player = NodePath("Player")
+
+[node name="Camera3D" type="Camera3D" parent="."]
+transform = Transform3D(1, 0, 0, 0, 0.803856, 0.594823, 0, -0.594823, 0.803856, 0, 9.562, 11.843)
+fov = 51.7
+
+[node name="Sync" type="Node" parent="."]
+script = ExtResource("2_7kqnq")
+speed_up = 16.0
+onnx_model_path = "SimpleReachGoal.onnx"
diff --git a/SimpleReachGoal/readme.md b/SimpleReachGoal/readme.md
new file mode 100644
index 0000000000000000000000000000000000000000..b46303fc60ee26281c3b411d56aad6fd45e647bd
--- /dev/null
+++ b/SimpleReachGoal/readme.md
@@ -0,0 +1,77 @@
+# SimpleReachGoal
+A simple reach the goal environment that is designed to be easy to train for running quick tests.
+
+https://github.com/edbeeching/godot_rl_agents_examples/assets/61947090/cf1f4f71-d92e-4036-916d-322d6986d121
+
+The env comes in three variants (each has its own project folder):
+- `GDScript` standard implementation using gdscript for everything except ONNX inference,
+- `CSharp` implements most of the game code except the extended AIController using C#,
+- `CSharpAll` implements a wrapper for AIController written in C# as well.
+
+Check the [working with CSharp](https://github.com/edbeeching/godot_rl_agents/blob/main/docs/WORKING_WITH_CSHARP.md) guide for more information about the CSharp variants.
+
+# Goal:
+
+The agent needs to enter the green goal area while avoiding the red obstacle area, and without falling outside of the game area. The goal and obstacle areas are randomly set to one of the possible positions at the beginning of each episode. All possible positions are shown in the screenshot below.
+
+![Area spawn positions](https://github.com/edbeeching/godot_rl_agents_examples/assets/61947090/e0b44c9d-6a23-4db9-82a5-5c40f7272f8d)
+
+# Observations:
+
+The agent uses 3 Raycast sensors, each configured to detect different object types:
+
+- GoalRaycastSensor (detects the green goal area using 32 rays)
+- ObstacleRaycastSensor (detects the red obstacle area using 32 rays)
+- GroundRaycastSensor (detects the ground below the player using 16 rays)
+
+![Raycast sensors](https://github.com/edbeeching/godot_rl_agents_examples/assets/61947090/e1f28658-e5b1-4ea0-b7a8-69dc42efc610)
+
+In addition to the sensors, the agent also has relative positions to the goal and obstacle added to its observations.
+
+
+# Rewards:
+
+The environment has sparse rewards:
+
++1 For entering the green area,
+
+-1 For entering the red area,
+
+-1 For falling outside of the game area.
+
+In each of those cases, the episode resets after the event. The episode also resets on timeout.
+
+
+# Training results (GDScript version):
+![Training rewards](https://github.com/edbeeching/godot_rl_agents_examples/assets/61947090/9c19928c-ed47-4ff7-9eb7-160b4a61ef88)
+These are the training stats from the training session used to train the onnx file included in the GDScript env. The reward are from training directly, not using deterministic evaluation.
+
+SB3 example script was used for training, with the following changes:
+
+```python
+ policy_kwargs = dict(
+ log_std_init=log(0.5)
+ )
+ model: PPO = PPO(
+ "MultiInputPolicy",
+ env,
+ ent_coef=0,
+ verbose=2,
+ n_steps=32,
+ tensorboard_log=args.experiment_dir,
+ learning_rate=learning_rate,
+ policy_kwargs=policy_kwargs
+ )
+```
+
+SB3 example script cmd arguments:
+
+```python
+--timesteps=50_000
+--onnx_export_path=simplereachgoal.onnx
+```
+
+Training was launched from Godot editor, and took about 3 minutes to complete to get the results from the video at the top of this page.
+
+- The base (gdscript) environment and CSharp variant was made by [Ivan267](https://github.com/Ivan-267)
+- The CSharpAll variant was made by [LorinczAdrien](https://github.com/LorinczAdrien)
diff --git a/readme.md b/readme.md
new file mode 100644
index 0000000000000000000000000000000000000000..d3ff7fe636b7aed71e2825315429138b2fadc09e
--- /dev/null
+++ b/readme.md
@@ -0,0 +1,3 @@
+# Test examples
+
+This folder contains examples which are mainly made for testing and experimentation, they may not be as stable as the main examples.
\ No newline at end of file