diff --git a/.gitattributes b/.gitattributes index 28df5f900b358436f0267334b3e3e9af33f917ba..76c9e2fb58b85f542670d5acac6952be3fb8f5e9 100644 --- a/.gitattributes +++ b/.gitattributes @@ -53,3 +53,7 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.jpg filter=lfs diff=lfs merge=lfs -text *.jpeg filter=lfs diff=lfs merge=lfs -text *.webp filter=lfs diff=lfs merge=lfs -text +scenes/blender/car_base.blend filter=lfs diff=lfs merge=lfs -text +scenes/blender/house.blend filter=lfs diff=lfs merge=lfs -text +scenes/blender/trees.blend filter=lfs diff=lfs merge=lfs -text +scenes/blender/windmill.blend filter=lfs diff=lfs merge=lfs -text diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e162e9261ac7b7d08746d7a8bfbae19cedaf9c04 --- /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 HovercraftRacing 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 edbeeching/godot_rl_HovercraftRacing +``` + + + diff --git a/RacingExample.csproj b/RacingExample.csproj new file mode 100644 index 0000000000000000000000000000000000000000..ae05f6f4379a129959012db33715a5b2efa596da --- /dev/null +++ b/RacingExample.csproj @@ -0,0 +1,10 @@ + + + net6.0 + true + GodotRLAgents + + + + + \ No newline at end of file diff --git a/RacingExample.csproj.old b/RacingExample.csproj.old new file mode 100644 index 0000000000000000000000000000000000000000..db33125fd850a19ac001954f977dbe30011f0788 --- /dev/null +++ b/RacingExample.csproj.old @@ -0,0 +1,10 @@ + + + net6.0 + true + GodotRLAgents + + + + + \ No newline at end of file diff --git a/RacingExample.sln b/RacingExample.sln new file mode 100644 index 0000000000000000000000000000000000000000..35b5c0e8e6fb14aa847bd6350c60cc57d6817a5d --- /dev/null +++ b/RacingExample.sln @@ -0,0 +1,19 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 2012 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RacingExample", "RacingExample.csproj", "{E2999C40-6DD8-43BC-9D9A-473B12290385}" +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 + {E2999C40-6DD8-43BC-9D9A-473B12290385}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E2999C40-6DD8-43BC-9D9A-473B12290385}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E2999C40-6DD8-43BC-9D9A-473B12290385}.ExportDebug|Any CPU.ActiveCfg = ExportDebug|Any CPU + {E2999C40-6DD8-43BC-9D9A-473B12290385}.ExportDebug|Any CPU.Build.0 = ExportDebug|Any CPU + {E2999C40-6DD8-43BC-9D9A-473B12290385}.ExportRelease|Any CPU.ActiveCfg = ExportRelease|Any CPU + {E2999C40-6DD8-43BC-9D9A-473B12290385}.ExportRelease|Any CPU.Build.0 = ExportRelease|Any CPU + EndGlobalSection +EndGlobal diff --git a/addons/godot_rl_agents/controller/ai_controller_2d.gd b/addons/godot_rl_agents/controller/ai_controller_2d.gd new file mode 100644 index 0000000000000000000000000000000000000000..e9080f0115c0729a12ace5f712c9e41e7ed252e4 --- /dev/null +++ b/addons/godot_rl_agents/controller/ai_controller_2d.gd @@ -0,0 +1,82 @@ +extends Node2D +class_name AIController2D + +@export var reset_after := 1000 + +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 get set_action method is not implemented when extending from ai_controller") +# -----------------------------------------------------------------------------# + +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/addons/godot_rl_agents/controller/ai_controller_3d.gd b/addons/godot_rl_agents/controller/ai_controller_3d.gd new file mode 100644 index 0000000000000000000000000000000000000000..d256b2acf9697d69b7b9fc31f5b0a0c708c7e2ae --- /dev/null +++ b/addons/godot_rl_agents/controller/ai_controller_3d.gd @@ -0,0 +1,80 @@ +extends Node3D +class_name AIController3D + +@export var reset_after := 1000 + +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 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 get set_action method is not implemented when extending from ai_controller") +# -----------------------------------------------------------------------------# + +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/addons/godot_rl_agents/godot_rl_agents.gd b/addons/godot_rl_agents/godot_rl_agents.gd new file mode 100644 index 0000000000000000000000000000000000000000..e4fe13693a598c808aca1b64051d1c0c70783296 --- /dev/null +++ b/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/addons/godot_rl_agents/icon.png b/addons/godot_rl_agents/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..ccb4ca000e3e1cf659fe367ab5bff67c1eb3467d --- /dev/null +++ b/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/addons/godot_rl_agents/icon.png.import b/addons/godot_rl_agents/icon.png.import new file mode 100644 index 0000000000000000000000000000000000000000..169c6571feea6ee1812cfd4845765c64fe57e230 --- /dev/null +++ b/addons/godot_rl_agents/icon.png.import @@ -0,0 +1,34 @@ +[remap] + +importer="texture" +type="CompressedTexture2D" +uid="uid://dlg5s1ygj8c34" +path="res://.godot/imported/icon.png-45a871b53434e556222f5901d598ab34.ctex" +metadata={ +"vram_texture": false +} + +[deps] + +source_file="res://addons/godot_rl_agents/icon.png" +dest_files=["res://.godot/imported/icon.png-45a871b53434e556222f5901d598ab34.ctex"] + +[params] + +compress/mode=0 +compress/high_quality=false +compress/lossy_quality=0.7 +compress/hdr_compression=1 +compress/normal_map=0 +compress/channel_pack=0 +mipmaps/generate=false +mipmaps/limit=-1 +roughness/mode=0 +roughness/src_normal="" +process/fix_alpha_border=true +process/premult_alpha=false +process/normal_map_invert_y=false +process/hdr_as_srgb=false +process/hdr_clamp_exposure=false +process/size_limit=0 +detect_3d/compress_to=1 diff --git a/addons/godot_rl_agents/onnx/csharp/ONNXInference.cs b/addons/godot_rl_agents/onnx/csharp/ONNXInference.cs new file mode 100644 index 0000000000000000000000000000000000000000..0741f0f263f34fffc44993e2b11a7544b0384ca1 --- /dev/null +++ b/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/addons/godot_rl_agents/onnx/csharp/SessionConfigurator.cs b/addons/godot_rl_agents/onnx/csharp/SessionConfigurator.cs new file mode 100644 index 0000000000000000000000000000000000000000..ad7a41cfee0dc3d497d9c1d03bd0752b09d49f3a --- /dev/null +++ b/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/addons/godot_rl_agents/onnx/csharp/docs/ONNXInference.xml b/addons/godot_rl_agents/onnx/csharp/docs/ONNXInference.xml new file mode 100644 index 0000000000000000000000000000000000000000..91b07d607dc89f11e957e13758d8c0ee4fb72be8 --- /dev/null +++ b/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/addons/godot_rl_agents/onnx/csharp/docs/SessionConfigurator.xml b/addons/godot_rl_agents/onnx/csharp/docs/SessionConfigurator.xml new file mode 100644 index 0000000000000000000000000000000000000000..f160c02f0d4cab92e10f799b6f4c5a71d4d6c0f2 --- /dev/null +++ b/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/addons/godot_rl_agents/onnx/wrapper/ONNX_wrapper.gd b/addons/godot_rl_agents/onnx/wrapper/ONNX_wrapper.gd new file mode 100644 index 0000000000000000000000000000000000000000..c7b14b350db11cb32f433e6b6cff6470d6cda7cf --- /dev/null +++ b/addons/godot_rl_agents/onnx/wrapper/ONNX_wrapper.gd @@ -0,0 +1,24 @@ +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/addons/godot_rl_agents/plugin.cfg b/addons/godot_rl_agents/plugin.cfg new file mode 100644 index 0000000000000000000000000000000000000000..b1bc988c80e3fe68e6d4279691fd5892e5ef323d --- /dev/null +++ b/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/addons/godot_rl_agents/sensors/sensors_2d/ExampleRaycastSensor2D.tscn b/addons/godot_rl_agents/sensors/sensors_2d/ExampleRaycastSensor2D.tscn new file mode 100644 index 0000000000000000000000000000000000000000..5edb6c7fc9da56e625d57185bdbafdbcc3fc67c5 --- /dev/null +++ b/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/addons/godot_rl_agents/sensors/sensors_2d/GridSensor2D.gd b/addons/godot_rl_agents/sensors/sensors_2d/GridSensor2D.gd new file mode 100644 index 0000000000000000000000000000000000000000..12f29570b72916d60a6bae6fc2fb0a9ddbcd0be2 --- /dev/null +++ b/addons/godot_rl_agents/sensors/sensors_2d/GridSensor2D.gd @@ -0,0 +1,216 @@ +@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/addons/godot_rl_agents/sensors/sensors_2d/ISensor2D.gd b/addons/godot_rl_agents/sensors/sensors_2d/ISensor2D.gd new file mode 100644 index 0000000000000000000000000000000000000000..ec20f08a8d37cf1232fc12d8ee4f23b5ba845602 --- /dev/null +++ b/addons/godot_rl_agents/sensors/sensors_2d/ISensor2D.gd @@ -0,0 +1,20 @@ +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/addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.gd b/addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.gd new file mode 100644 index 0000000000000000000000000000000000000000..09363c409f59b0ef1d68131b77c0a2cba71805d8 --- /dev/null +++ b/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,200,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 = true + 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 _physics_process(delta: float) -> void: + if self._active: + self._obs = calculate_raycasts() + +func get_observation() -> Array: + if len(self._obs) == 0: + print("obs was null, forcing raycast update") + return self.calculate_raycasts() + return self._obs + + +func calculate_raycasts() -> Array: + var result = [] + for ray in rays: + ray.force_raycast_update() + var distance = _get_raycast_distance(ray) + result.append(distance) + 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/addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.tscn b/addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.tscn new file mode 100644 index 0000000000000000000000000000000000000000..5ca402c08305efedbfc6afd0a1893a0ca2e11cfd --- /dev/null +++ b/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/addons/godot_rl_agents/sensors/sensors_3d/ExampleRaycastSensor3D.tscn b/addons/godot_rl_agents/sensors/sensors_3d/ExampleRaycastSensor3D.tscn new file mode 100644 index 0000000000000000000000000000000000000000..a8057c7619cbb835709d2704074b0d5ebfa00a0c --- /dev/null +++ b/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/addons/godot_rl_agents/sensors/sensors_3d/GridSensor3D.gd b/addons/godot_rl_agents/sensors/sensors_3d/GridSensor3D.gd new file mode 100644 index 0000000000000000000000000000000000000000..cfce8a84b57661c40662f7b2d53ea5243da54b7e --- /dev/null +++ b/addons/godot_rl_agents/sensors/sensors_3d/GridSensor3D.gd @@ -0,0 +1,233 @@ +@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/addons/godot_rl_agents/sensors/sensors_3d/ISensor3D.gd b/addons/godot_rl_agents/sensors/sensors_3d/ISensor3D.gd new file mode 100644 index 0000000000000000000000000000000000000000..d57503b5006e9384c4a9ce7de348d74a5b58d322 --- /dev/null +++ b/addons/godot_rl_agents/sensors/sensors_3d/ISensor3D.gd @@ -0,0 +1,20 @@ +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/addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.gd b/addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.gd new file mode 100644 index 0000000000000000000000000000000000000000..b5f340de48288024f42f35923aa562cb367409f5 --- /dev/null +++ b/addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.gd @@ -0,0 +1,14 @@ +extends Node3D +class_name RGBCameraSensor3D +var camera_pixels = null + +@onready var camera_texture := $Control/TextureRect/CameraTexture as Sprite2D + +func get_camera_pixel_encoding(): + return camera_texture.get_texture().get_image().get_data().hex_encode() + +func get_camera_shape()-> Array: + if $SubViewport.transparent_bg: + return [$SubViewport.size[0], $SubViewport.size[1], 4] + else: + return [$SubViewport.size[0], $SubViewport.size[1], 3] diff --git a/addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.tscn b/addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.tscn new file mode 100644 index 0000000000000000000000000000000000000000..052b5577db16ab7d25f5f473a539b3099f400db8 --- /dev/null +++ b/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/addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd b/addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd new file mode 100644 index 0000000000000000000000000000000000000000..ab701d982b0381b41e528cf1218e13fc0269d3ce --- /dev/null +++ b/addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd @@ -0,0 +1,166 @@ +@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 = 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(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/addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.tscn b/addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.tscn new file mode 100644 index 0000000000000000000000000000000000000000..35f9796596b2fb79bfcfe31e3d3a9637d9008e55 --- /dev/null +++ b/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/addons/godot_rl_agents/sync.gd b/addons/godot_rl_agents/sync.gd new file mode 100644 index 0000000000000000000000000000000000000000..b17daa991c839890f55b3988df9411ec421aa042 --- /dev/null +++ b/addons/godot_rl_agents/sync.gd @@ -0,0 +1,342 @@ +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(1, 10, 1, "or_greater") var speed_up = 1 +@export var onnx_model_path := "" + +@onready var start_time = Time.get_ticks_msec() + +const MAJOR_VERSION := "0" +const MINOR_VERSION := "3" +const DEFAULT_PORT := "11008" +const DEFAULT_SEED := "1" +var stream : StreamPeerTCP = null +var connected = false +var message_center +var should_connect = true +var agents +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 _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() + _obs_space = agents[0].get_obs_space() + _action_space = agents[0].get_action_space() + 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") + match control_mode: + ControlModes.TRAINING: + connected = connect_to_server() + if connected: + _set_heuristic("model") + _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?") + 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_model = ONNXModel.new(onnx_model_path, 1) + _set_heuristic("model") + + _set_seed() + _set_action_repeat() + initialized = true + +func _physics_process(_delta): + # two modes, human control, agent control + # pause tree, send obs, get actions, set actions, unpause tree + if n_action_steps % action_repeat != 0: + n_action_steps += 1 + return + + n_action_steps += 1 + + if connected: + get_tree().set_pause(true) + + if just_reset: + just_reset = false + var obs = _get_obs_from_agents() + + 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() + + var reply = { + "type": "step", + "obs": obs, + "reward": reward, + "done": done + } + _send_dict_as_json_message(reply) + + var handled = handle_message() + + elif onnx_model != null: + var obs : Array = _get_obs_from_agents() + + var actions = [] + for o in obs: + var action = onnx_model.run_inference(o["obs"], 1.0) + action["output"] = clamp_array(action["output"], -1.0, 1.0) + var action_dict = _extract_action_dict(action["output"]) + actions.append(action_dict) + + _set_agent_actions(actions) + need_to_send_obs = true + get_tree().set_pause(false) + _reset_agents_if_done() + + else: + _reset_agents_if_done() + +func _extract_action_dict(action_array: Array): + 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 + +func _get_agents(): + agents = get_tree().get_nodes_in_group("AGENT") + +func _set_heuristic(heuristic): + 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) + } + _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_int() + +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_all_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) + 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 agents: + returns.append(agent.call(method)) + + return returns + + +func _reset_agents_if_done(): + for agent in agents: + if agent.get_done(): + agent.set_done_false() + +func _reset_all_agents(): + for agent in agents: + agent.needs_reset = true + #agent.reset() + +func _get_obs_from_agents(): + var obs = [] + for agent in agents: + obs.append(agent.get_obs()) + + return obs + +func _get_reward_from_agents(): + var rewards = [] + for agent in agents: + rewards.append(agent.get_reward()) + agent.zero_reward() + return rewards + +func _get_done_from_agents(): + 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): + 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 diff --git a/asset-license.md b/asset-license.md new file mode 100644 index 0000000000000000000000000000000000000000..4f69648b2f8e52436bd90f5f1169d9d7212cf616 --- /dev/null +++ b/asset-license.md @@ -0,0 +1,5 @@ +Hovercraft Racing Environment made by Ivan-267 using Godot, Godot RL Agents, and Blender. + +The following license is only for the assets (.blend files) in the folder "scenes/blender": +Author: https://github.com/Ivan-267 +License: https://creativecommons.org/licenses/by/4.0/ \ No newline at end of file diff --git a/icon.svg b/icon.svg new file mode 100644 index 0000000000000000000000000000000000000000..b370ceb72740b9a759fe11b364f0d4de27df42f8 --- /dev/null +++ b/icon.svg @@ -0,0 +1 @@ + diff --git a/icon.svg.import b/icon.svg.import new file mode 100644 index 0000000000000000000000000000000000000000..cc587d1b832a9a858cb295efdcb8a3d9bd40c966 --- /dev/null +++ b/icon.svg.import @@ -0,0 +1,37 @@ +[remap] + +importer="texture" +type="CompressedTexture2D" +uid="uid://b8abixqka5atk" +path="res://.godot/imported/icon.svg-218a8f2b3041327d8a5756f3a245f83b.ctex" +metadata={ +"vram_texture": false +} + +[deps] + +source_file="res://icon.svg" +dest_files=["res://.godot/imported/icon.svg-218a8f2b3041327d8a5756f3a245f83b.ctex"] + +[params] + +compress/mode=0 +compress/high_quality=false +compress/lossy_quality=0.7 +compress/hdr_compression=1 +compress/normal_map=0 +compress/channel_pack=0 +mipmaps/generate=false +mipmaps/limit=-1 +roughness/mode=0 +roughness/src_normal="" +process/fix_alpha_border=true +process/premult_alpha=false +process/normal_map_invert_y=false +process/hdr_as_srgb=false +process/hdr_clamp_exposure=false +process/size_limit=0 +detect_3d/compress_to=1 +svg/scale=1.0 +editor/scale_with_editor_scale=false +editor/convert_colors_with_editor_theme=false diff --git a/model.onnx b/model.onnx new file mode 100644 index 0000000000000000000000000000000000000000..6605b39d6406c86436dc4d543f058336e5e87583 --- /dev/null +++ b/model.onnx @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0363b72528e3814052e3d156d490660cfbb5ccac7eae94506345daadcd899fea +size 31693 diff --git a/project.godot b/project.godot new file mode 100644 index 0000000000000000000000000000000000000000..7725be80aad8aba996bd3975a98c2cd32ec96233 --- /dev/null +++ b/project.godot @@ -0,0 +1,51 @@ +; 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="HovercraftRacingExample" +run/main_scene="res://scenes/main_scene/main_scene.tscn" +config/features=PackedStringArray("4.2", "C#", "GL Compatibility") +config/icon="res://icon.svg" + +[dotnet] + +project/assembly_name="RacingExample" + +[editor_plugins] + +enabled=PackedStringArray("res://addons/godot_rl_agents/plugin.cfg") + +[input] + +move_forward={ +"deadzone": 0.5, +"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":87,"key_label":0,"unicode":119,"echo":false,"script":null) +] +} +move_backward={ +"deadzone": 0.5, +"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":83,"key_label":0,"unicode":115,"echo":false,"script":null) +] +} +steer_left={ +"deadzone": 0.5, +"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":65,"key_label":0,"unicode":97,"echo":false,"script":null) +] +} +steer_right={ +"deadzone": 0.5, +"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":68,"key_label":0,"unicode":100,"echo":false,"script":null) +] +} + +[rendering] + +renderer/rendering_method.mobile="gl_compatibility" diff --git a/readme.md b/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..0a727ccd402ee5905a15b4fd62d6ca148631c26b --- /dev/null +++ b/readme.md @@ -0,0 +1,57 @@ +## Hovercraft Racing Environment + +https://github.com/edbeeching/godot_rl_agents_examples/assets/61947090/09cfa8ef-4d1a-46d3-a38a-0b7cdf1e1000 + +A 1v1 hovercraft racing environment with: + +- `Human VS AI` (use `WASD` keys to control the car), or `AI vs AI` mode, +- Adjustable number of laps (can be set to 0 for infinite race), +- Basic powerups (push forward or push backward). + +### Observations: +- Velocity of the car in local reference, +- 3 sampled `next track points` in the car's local reference, +- Wall detecting raycast sensor observations, +- Other car detecting raycast sensor observations, +- Position of the other car in the current car's local reference, +- Position of the nearest powerup in the car's local reference, +- Category of the powerup, as there are only two powerups it can be either `[0, 1]` or `[1, 0]`. + +### Action space: +```gdscript +func get_action_space() -> Dictionary: + return { + "acceleration": {"size": 1, "action_type": "continuous"}, + "steering": {"size": 1, "action_type": "continuous"}, + } +``` + +### Rewards: +- Step reward based on the car's track offset difference from the previous step (advancing on the track gives a positive reward, moving backward gives a negative reward), +- Negative step reward for moving backward, +- Negative reward for colliding with a wall or the other car, +- Optional reward for driving over a powerup (can be adjusted in Godot Editor in the scene of the powerup), currently set to 0 for both powerups. + +### Game over / episode end conditions: +![image](https://github.com/edbeeching/godot_rl_agents_examples/assets/61947090/d9fdf617-0c4a-479e-8feb-cab9880345e6) + +The episode ends for each car after each lap in infinite race mode if `total laps` is set to 0, without restarting the cars, +or if larger than 0, after the set amount of total laps has been completed by any car, in that case the winner is announced (except in training mode), and the cars are automatically restarted for the next race. + +`Seconds Until Race Begins` is only applicable to inference (`AI vs AI` or `Player vs AI` modes). + +### Running inference with the pretrained onnx model: +![image](https://github.com/edbeeching/godot_rl_agents_examples/assets/61947090/2f9dfd2b-9835-42e0-9bf5-5f45e896967b) + +After opening the project in Godot, open the main_scene (should open by default), select a game mode, and click on `Play`. + +### Training: + +- Set the game mode to `Training` before starting starting training. You can use for instance the [sb3 example](https://github.com/edbeeching/godot_rl_agents/blob/main/examples/stable_baselines3_example.py) to train. + +- In the `game_scene`'s `Cars` node, there's a property `Number of Car Groups To Spawn` which allows multiple car groups to spawn and collect experiences during training (during inference, only 1 car group is spawned). Since this is a `1v1` example, each car group is set so a car can only collide with the other car from its own group and the walls. This is done by the car manager script by setting each car to its own physics layer and adjusting the masks (also for the raycast sensor that detects the other car). Settings this value too high may make the environment not work correctly, as there is a limit in the number of physics layers available. + +![image](https://github.com/edbeeching/godot_rl_agents_examples/assets/61947090/94752856-8729-4cde-8151-3aaf65bab155) + + + diff --git a/scenes/blender/car_base.blend b/scenes/blender/car_base.blend new file mode 100644 index 0000000000000000000000000000000000000000..572fb7cf44bfa8cdb53965d2fcbb15c66e4e11b7 --- /dev/null +++ b/scenes/blender/car_base.blend @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b91e60c28c39a4883d9f44f608a22e5e4ac24a8a78d0f0594138337799263427 +size 1041840 diff --git a/scenes/blender/car_base.blend.import b/scenes/blender/car_base.blend.import new file mode 100644 index 0000000000000000000000000000000000000000..4a1c376b7b26936e61d3257c28f8423eda29e523 --- /dev/null +++ b/scenes/blender/car_base.blend.import @@ -0,0 +1,50 @@ +[remap] + +importer="scene" +importer_version=1 +type="PackedScene" +uid="uid://busv5hvcvkgvk" +path="res://.godot/imported/car_base.blend-d9f62a57eda3c9dd4112c044b073ef67.scn" + +[deps] + +source_file="res://scenes/blender/car_base.blend" +dest_files=["res://.godot/imported/car_base.blend-d9f62a57eda3c9dd4112c044b073ef67.scn"] + +[params] + +nodes/root_type="" +nodes/root_name="" +nodes/apply_root_scale=true +nodes/root_scale=1.0 +meshes/ensure_tangents=true +meshes/generate_lods=true +meshes/create_shadow_meshes=true +meshes/light_baking=1 +meshes/lightmap_texel_size=0.2 +meshes/force_disable_compression=false +skins/use_named_skins=true +animation/import=true +animation/fps=30 +animation/trimming=false +animation/remove_immutable_tracks=true +import_script/path="" +_subresources={} +gltf/naming_version=1 +gltf/embedded_image_handling=1 +blender/nodes/visible=0 +blender/nodes/punctual_lights=true +blender/nodes/cameras=true +blender/nodes/custom_properties=true +blender/nodes/modifiers=1 +blender/meshes/colors=false +blender/meshes/uvs=true +blender/meshes/normals=true +blender/meshes/tangents=true +blender/meshes/skins=2 +blender/meshes/export_bones_deforming_mesh_only=false +blender/materials/unpack_enabled=true +blender/materials/export_materials=1 +blender/animation/limit_playback=true +blender/animation/always_sample=true +blender/animation/group_tracks=true diff --git a/scenes/blender/house.blend b/scenes/blender/house.blend new file mode 100644 index 0000000000000000000000000000000000000000..7ce0d8a06e010ecc66802e2c3cb2a162bcef35bb --- /dev/null +++ b/scenes/blender/house.blend @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0b0f9b041e2bc25ce73615eeedf71077c977abac7d622fa975422f8ab8b51277 +size 1014696 diff --git a/scenes/blender/house.blend.import b/scenes/blender/house.blend.import new file mode 100644 index 0000000000000000000000000000000000000000..fe00e8df57d0447cab59246593e2393db9c832bf --- /dev/null +++ b/scenes/blender/house.blend.import @@ -0,0 +1,50 @@ +[remap] + +importer="scene" +importer_version=1 +type="PackedScene" +uid="uid://3e7yw00iuurq" +path="res://.godot/imported/house.blend-6fb6d2c34379d4022b539c2204cf88b3.scn" + +[deps] + +source_file="res://scenes/blender/house.blend" +dest_files=["res://.godot/imported/house.blend-6fb6d2c34379d4022b539c2204cf88b3.scn"] + +[params] + +nodes/root_type="" +nodes/root_name="" +nodes/apply_root_scale=true +nodes/root_scale=1.0 +meshes/ensure_tangents=true +meshes/generate_lods=true +meshes/create_shadow_meshes=true +meshes/light_baking=1 +meshes/lightmap_texel_size=0.2 +meshes/force_disable_compression=false +skins/use_named_skins=true +animation/import=true +animation/fps=30 +animation/trimming=false +animation/remove_immutable_tracks=true +import_script/path="" +_subresources={} +gltf/naming_version=1 +gltf/embedded_image_handling=1 +blender/nodes/visible=0 +blender/nodes/punctual_lights=true +blender/nodes/cameras=true +blender/nodes/custom_properties=true +blender/nodes/modifiers=1 +blender/meshes/colors=false +blender/meshes/uvs=true +blender/meshes/normals=true +blender/meshes/tangents=true +blender/meshes/skins=2 +blender/meshes/export_bones_deforming_mesh_only=false +blender/materials/unpack_enabled=true +blender/materials/export_materials=1 +blender/animation/limit_playback=true +blender/animation/always_sample=true +blender/animation/group_tracks=true diff --git a/scenes/blender/house2.blend b/scenes/blender/house2.blend new file mode 100644 index 0000000000000000000000000000000000000000..74e63467794230d18d9ced01fb11465c45e88b6d Binary files /dev/null and b/scenes/blender/house2.blend differ diff --git a/scenes/blender/house2.blend.import b/scenes/blender/house2.blend.import new file mode 100644 index 0000000000000000000000000000000000000000..6f19542f0a4395df6669913c28b48ce3b9857a07 --- /dev/null +++ b/scenes/blender/house2.blend.import @@ -0,0 +1,50 @@ +[remap] + +importer="scene" +importer_version=1 +type="PackedScene" +uid="uid://cxw7jj1pbn018" +path="res://.godot/imported/house2.blend-64bdd71244920b0d7baf13d8cbf0d624.scn" + +[deps] + +source_file="res://scenes/blender/house2.blend" +dest_files=["res://.godot/imported/house2.blend-64bdd71244920b0d7baf13d8cbf0d624.scn"] + +[params] + +nodes/root_type="" +nodes/root_name="" +nodes/apply_root_scale=true +nodes/root_scale=1.0 +meshes/ensure_tangents=true +meshes/generate_lods=true +meshes/create_shadow_meshes=true +meshes/light_baking=1 +meshes/lightmap_texel_size=0.2 +meshes/force_disable_compression=false +skins/use_named_skins=true +animation/import=true +animation/fps=30 +animation/trimming=false +animation/remove_immutable_tracks=true +import_script/path="" +_subresources={} +gltf/naming_version=1 +gltf/embedded_image_handling=1 +blender/nodes/visible=0 +blender/nodes/punctual_lights=true +blender/nodes/cameras=true +blender/nodes/custom_properties=true +blender/nodes/modifiers=1 +blender/meshes/colors=false +blender/meshes/uvs=true +blender/meshes/normals=true +blender/meshes/tangents=true +blender/meshes/skins=2 +blender/meshes/export_bones_deforming_mesh_only=false +blender/materials/unpack_enabled=true +blender/materials/export_materials=1 +blender/animation/limit_playback=true +blender/animation/always_sample=true +blender/animation/group_tracks=true diff --git a/scenes/blender/reverse-turbo-powerup.blend b/scenes/blender/reverse-turbo-powerup.blend new file mode 100644 index 0000000000000000000000000000000000000000..394a2738a59ce032123e69ae5d53af8e96f7ed7d Binary files /dev/null and b/scenes/blender/reverse-turbo-powerup.blend differ diff --git a/scenes/blender/reverse-turbo-powerup.blend.import b/scenes/blender/reverse-turbo-powerup.blend.import new file mode 100644 index 0000000000000000000000000000000000000000..9c7c48100d7682aa7851c7774cd096a14e559c11 --- /dev/null +++ b/scenes/blender/reverse-turbo-powerup.blend.import @@ -0,0 +1,50 @@ +[remap] + +importer="scene" +importer_version=1 +type="PackedScene" +uid="uid://cup4jp8weealn" +path="res://.godot/imported/reverse-turbo-powerup.blend-e6421eae54c5a9bdf71a63d19ee003c3.scn" + +[deps] + +source_file="res://scenes/blender/reverse-turbo-powerup.blend" +dest_files=["res://.godot/imported/reverse-turbo-powerup.blend-e6421eae54c5a9bdf71a63d19ee003c3.scn"] + +[params] + +nodes/root_type="" +nodes/root_name="" +nodes/apply_root_scale=true +nodes/root_scale=1.0 +meshes/ensure_tangents=true +meshes/generate_lods=true +meshes/create_shadow_meshes=true +meshes/light_baking=1 +meshes/lightmap_texel_size=0.2 +meshes/force_disable_compression=false +skins/use_named_skins=true +animation/import=true +animation/fps=30 +animation/trimming=false +animation/remove_immutable_tracks=true +import_script/path="" +_subresources={} +gltf/naming_version=1 +gltf/embedded_image_handling=1 +blender/nodes/visible=0 +blender/nodes/punctual_lights=true +blender/nodes/cameras=true +blender/nodes/custom_properties=true +blender/nodes/modifiers=1 +blender/meshes/colors=false +blender/meshes/uvs=true +blender/meshes/normals=true +blender/meshes/tangents=true +blender/meshes/skins=2 +blender/meshes/export_bones_deforming_mesh_only=false +blender/materials/unpack_enabled=true +blender/materials/export_materials=1 +blender/animation/limit_playback=true +blender/animation/always_sample=true +blender/animation/group_tracks=true diff --git a/scenes/blender/rock.blend b/scenes/blender/rock.blend new file mode 100644 index 0000000000000000000000000000000000000000..fda55ddcb0c246bc316b6d7239a6225554d300ba Binary files /dev/null and b/scenes/blender/rock.blend differ diff --git a/scenes/blender/rock.blend.import b/scenes/blender/rock.blend.import new file mode 100644 index 0000000000000000000000000000000000000000..ff8186ecd382892f5d0f224ecab70fa20466e150 --- /dev/null +++ b/scenes/blender/rock.blend.import @@ -0,0 +1,50 @@ +[remap] + +importer="scene" +importer_version=1 +type="PackedScene" +uid="uid://dc63wc5xni2t5" +path="res://.godot/imported/rock.blend-c0899d6f8a73f961232e1fc91a119c6e.scn" + +[deps] + +source_file="res://scenes/blender/rock.blend" +dest_files=["res://.godot/imported/rock.blend-c0899d6f8a73f961232e1fc91a119c6e.scn"] + +[params] + +nodes/root_type="" +nodes/root_name="" +nodes/apply_root_scale=true +nodes/root_scale=1.0 +meshes/ensure_tangents=true +meshes/generate_lods=true +meshes/create_shadow_meshes=true +meshes/light_baking=1 +meshes/lightmap_texel_size=0.2 +meshes/force_disable_compression=false +skins/use_named_skins=true +animation/import=true +animation/fps=30 +animation/trimming=false +animation/remove_immutable_tracks=true +import_script/path="" +_subresources={} +gltf/naming_version=1 +gltf/embedded_image_handling=1 +blender/nodes/visible=0 +blender/nodes/punctual_lights=true +blender/nodes/cameras=true +blender/nodes/custom_properties=true +blender/nodes/modifiers=1 +blender/meshes/colors=false +blender/meshes/uvs=true +blender/meshes/normals=true +blender/meshes/tangents=true +blender/meshes/skins=2 +blender/meshes/export_bones_deforming_mesh_only=false +blender/materials/unpack_enabled=true +blender/materials/export_materials=1 +blender/animation/limit_playback=true +blender/animation/always_sample=true +blender/animation/group_tracks=true diff --git a/scenes/blender/rock2.blend b/scenes/blender/rock2.blend new file mode 100644 index 0000000000000000000000000000000000000000..f482c00de1ea55763f04628b6e15512cfbb518c1 Binary files /dev/null and b/scenes/blender/rock2.blend differ diff --git a/scenes/blender/rock2.blend.import b/scenes/blender/rock2.blend.import new file mode 100644 index 0000000000000000000000000000000000000000..6c5e782c0f69690866fbbcfba06dae5d9483b658 --- /dev/null +++ b/scenes/blender/rock2.blend.import @@ -0,0 +1,50 @@ +[remap] + +importer="scene" +importer_version=1 +type="PackedScene" +uid="uid://by6lfo2x0i2db" +path="res://.godot/imported/rock2.blend-654587e47c845dfb50b773391398d597.scn" + +[deps] + +source_file="res://scenes/blender/rock2.blend" +dest_files=["res://.godot/imported/rock2.blend-654587e47c845dfb50b773391398d597.scn"] + +[params] + +nodes/root_type="" +nodes/root_name="" +nodes/apply_root_scale=true +nodes/root_scale=1.0 +meshes/ensure_tangents=true +meshes/generate_lods=true +meshes/create_shadow_meshes=true +meshes/light_baking=1 +meshes/lightmap_texel_size=0.2 +meshes/force_disable_compression=false +skins/use_named_skins=true +animation/import=true +animation/fps=30 +animation/trimming=false +animation/remove_immutable_tracks=true +import_script/path="" +_subresources={} +gltf/naming_version=1 +gltf/embedded_image_handling=1 +blender/nodes/visible=0 +blender/nodes/punctual_lights=true +blender/nodes/cameras=true +blender/nodes/custom_properties=true +blender/nodes/modifiers=1 +blender/meshes/colors=false +blender/meshes/uvs=true +blender/meshes/normals=true +blender/meshes/tangents=true +blender/meshes/skins=2 +blender/meshes/export_bones_deforming_mesh_only=false +blender/materials/unpack_enabled=true +blender/materials/export_materials=1 +blender/animation/limit_playback=true +blender/animation/always_sample=true +blender/animation/group_tracks=true diff --git a/scenes/blender/tree.blend b/scenes/blender/tree.blend new file mode 100644 index 0000000000000000000000000000000000000000..0120d938f63131759740257b2c38f9267f6f019e Binary files /dev/null and b/scenes/blender/tree.blend differ diff --git a/scenes/blender/tree.blend.import b/scenes/blender/tree.blend.import new file mode 100644 index 0000000000000000000000000000000000000000..987337584bdf0422c4f7ca95985ebe4db8e6b60f --- /dev/null +++ b/scenes/blender/tree.blend.import @@ -0,0 +1,50 @@ +[remap] + +importer="scene" +importer_version=1 +type="PackedScene" +uid="uid://bthooolpfuotf" +path="res://.godot/imported/tree.blend-596b3e93f4bfe8ad3b9e02bd11b75358.scn" + +[deps] + +source_file="res://scenes/blender/tree.blend" +dest_files=["res://.godot/imported/tree.blend-596b3e93f4bfe8ad3b9e02bd11b75358.scn"] + +[params] + +nodes/root_type="" +nodes/root_name="" +nodes/apply_root_scale=true +nodes/root_scale=1.0 +meshes/ensure_tangents=true +meshes/generate_lods=true +meshes/create_shadow_meshes=true +meshes/light_baking=1 +meshes/lightmap_texel_size=0.2 +meshes/force_disable_compression=false +skins/use_named_skins=true +animation/import=true +animation/fps=30 +animation/trimming=false +animation/remove_immutable_tracks=true +import_script/path="" +_subresources={} +gltf/naming_version=1 +gltf/embedded_image_handling=1 +blender/nodes/visible=0 +blender/nodes/punctual_lights=true +blender/nodes/cameras=true +blender/nodes/custom_properties=true +blender/nodes/modifiers=1 +blender/meshes/colors=false +blender/meshes/uvs=true +blender/meshes/normals=true +blender/meshes/tangents=true +blender/meshes/skins=2 +blender/meshes/export_bones_deforming_mesh_only=false +blender/materials/unpack_enabled=true +blender/materials/export_materials=1 +blender/animation/limit_playback=true +blender/animation/always_sample=true +blender/animation/group_tracks=true diff --git a/scenes/blender/tree2.blend b/scenes/blender/tree2.blend new file mode 100644 index 0000000000000000000000000000000000000000..d5022ac0f7b6765bfde98d2d4c9e23ff893fa85e Binary files /dev/null and b/scenes/blender/tree2.blend differ diff --git a/scenes/blender/tree2.blend.import b/scenes/blender/tree2.blend.import new file mode 100644 index 0000000000000000000000000000000000000000..fa5ef82bd05f9ff6c84037445a4439aceb2f4459 --- /dev/null +++ b/scenes/blender/tree2.blend.import @@ -0,0 +1,50 @@ +[remap] + +importer="scene" +importer_version=1 +type="PackedScene" +uid="uid://b34nhulmucjqo" +path="res://.godot/imported/tree2.blend-0ad60925bcb92ad04e187e6a3a32440f.scn" + +[deps] + +source_file="res://scenes/blender/tree2.blend" +dest_files=["res://.godot/imported/tree2.blend-0ad60925bcb92ad04e187e6a3a32440f.scn"] + +[params] + +nodes/root_type="" +nodes/root_name="" +nodes/apply_root_scale=true +nodes/root_scale=1.0 +meshes/ensure_tangents=true +meshes/generate_lods=true +meshes/create_shadow_meshes=true +meshes/light_baking=1 +meshes/lightmap_texel_size=0.2 +meshes/force_disable_compression=false +skins/use_named_skins=true +animation/import=true +animation/fps=30 +animation/trimming=false +animation/remove_immutable_tracks=true +import_script/path="" +_subresources={} +gltf/naming_version=1 +gltf/embedded_image_handling=1 +blender/nodes/visible=0 +blender/nodes/punctual_lights=true +blender/nodes/cameras=true +blender/nodes/custom_properties=true +blender/nodes/modifiers=1 +blender/meshes/colors=false +blender/meshes/uvs=true +blender/meshes/normals=true +blender/meshes/tangents=true +blender/meshes/skins=2 +blender/meshes/export_bones_deforming_mesh_only=false +blender/materials/unpack_enabled=true +blender/materials/export_materials=1 +blender/animation/limit_playback=true +blender/animation/always_sample=true +blender/animation/group_tracks=true diff --git a/scenes/blender/tree3.blend b/scenes/blender/tree3.blend new file mode 100644 index 0000000000000000000000000000000000000000..f9e3668c841c5d7fa5d579e49f36bd078193d5c6 Binary files /dev/null and b/scenes/blender/tree3.blend differ diff --git a/scenes/blender/tree3.blend.import b/scenes/blender/tree3.blend.import new file mode 100644 index 0000000000000000000000000000000000000000..28f277e82559da6a27613ce1e9b4ed21ee73c639 --- /dev/null +++ b/scenes/blender/tree3.blend.import @@ -0,0 +1,50 @@ +[remap] + +importer="scene" +importer_version=1 +type="PackedScene" +uid="uid://d4euoxxmvf36y" +path="res://.godot/imported/tree3.blend-8f8e13ff98d396eac844580b759d5631.scn" + +[deps] + +source_file="res://scenes/blender/tree3.blend" +dest_files=["res://.godot/imported/tree3.blend-8f8e13ff98d396eac844580b759d5631.scn"] + +[params] + +nodes/root_type="" +nodes/root_name="" +nodes/apply_root_scale=true +nodes/root_scale=1.0 +meshes/ensure_tangents=true +meshes/generate_lods=true +meshes/create_shadow_meshes=true +meshes/light_baking=1 +meshes/lightmap_texel_size=0.2 +meshes/force_disable_compression=false +skins/use_named_skins=true +animation/import=true +animation/fps=30 +animation/trimming=false +animation/remove_immutable_tracks=true +import_script/path="" +_subresources={} +gltf/naming_version=1 +gltf/embedded_image_handling=1 +blender/nodes/visible=0 +blender/nodes/punctual_lights=true +blender/nodes/cameras=true +blender/nodes/custom_properties=true +blender/nodes/modifiers=1 +blender/meshes/colors=false +blender/meshes/uvs=true +blender/meshes/normals=true +blender/meshes/tangents=true +blender/meshes/skins=2 +blender/meshes/export_bones_deforming_mesh_only=false +blender/materials/unpack_enabled=true +blender/materials/export_materials=1 +blender/animation/limit_playback=true +blender/animation/always_sample=true +blender/animation/group_tracks=true diff --git a/scenes/blender/tree4.blend b/scenes/blender/tree4.blend new file mode 100644 index 0000000000000000000000000000000000000000..960dfe62564c3a4f5225438bc4338abc9096172a Binary files /dev/null and b/scenes/blender/tree4.blend differ diff --git a/scenes/blender/tree4.blend.import b/scenes/blender/tree4.blend.import new file mode 100644 index 0000000000000000000000000000000000000000..9d71280279054abec8dd310b06dfa67cedfe068f --- /dev/null +++ b/scenes/blender/tree4.blend.import @@ -0,0 +1,50 @@ +[remap] + +importer="scene" +importer_version=1 +type="PackedScene" +uid="uid://bkxpl480o8sgg" +path="res://.godot/imported/tree4.blend-518b622bce8fbab1ac73511de1c0d6ea.scn" + +[deps] + +source_file="res://scenes/blender/tree4.blend" +dest_files=["res://.godot/imported/tree4.blend-518b622bce8fbab1ac73511de1c0d6ea.scn"] + +[params] + +nodes/root_type="" +nodes/root_name="" +nodes/apply_root_scale=true +nodes/root_scale=1.0 +meshes/ensure_tangents=true +meshes/generate_lods=true +meshes/create_shadow_meshes=true +meshes/light_baking=1 +meshes/lightmap_texel_size=0.2 +meshes/force_disable_compression=false +skins/use_named_skins=true +animation/import=true +animation/fps=30 +animation/trimming=false +animation/remove_immutable_tracks=true +import_script/path="" +_subresources={} +gltf/naming_version=1 +gltf/embedded_image_handling=1 +blender/nodes/visible=0 +blender/nodes/punctual_lights=true +blender/nodes/cameras=true +blender/nodes/custom_properties=true +blender/nodes/modifiers=1 +blender/meshes/colors=false +blender/meshes/uvs=true +blender/meshes/normals=true +blender/meshes/tangents=true +blender/meshes/skins=2 +blender/meshes/export_bones_deforming_mesh_only=false +blender/materials/unpack_enabled=true +blender/materials/export_materials=1 +blender/animation/limit_playback=true +blender/animation/always_sample=true +blender/animation/group_tracks=true diff --git a/scenes/blender/tree5.blend b/scenes/blender/tree5.blend new file mode 100644 index 0000000000000000000000000000000000000000..381380e01aa58af9ac671b52d5c3a043de80c122 Binary files /dev/null and b/scenes/blender/tree5.blend differ diff --git a/scenes/blender/tree5.blend.import b/scenes/blender/tree5.blend.import new file mode 100644 index 0000000000000000000000000000000000000000..32eabcccb931705a15f75da4616dce8f065c1ebe --- /dev/null +++ b/scenes/blender/tree5.blend.import @@ -0,0 +1,50 @@ +[remap] + +importer="scene" +importer_version=1 +type="PackedScene" +uid="uid://dme0teqo2whno" +path="res://.godot/imported/tree5.blend-22e65db763f0b480016a90d4e1a1e3f6.scn" + +[deps] + +source_file="res://scenes/blender/tree5.blend" +dest_files=["res://.godot/imported/tree5.blend-22e65db763f0b480016a90d4e1a1e3f6.scn"] + +[params] + +nodes/root_type="" +nodes/root_name="" +nodes/apply_root_scale=true +nodes/root_scale=1.0 +meshes/ensure_tangents=true +meshes/generate_lods=true +meshes/create_shadow_meshes=true +meshes/light_baking=1 +meshes/lightmap_texel_size=0.2 +meshes/force_disable_compression=false +skins/use_named_skins=true +animation/import=true +animation/fps=30 +animation/trimming=false +animation/remove_immutable_tracks=true +import_script/path="" +_subresources={} +gltf/naming_version=1 +gltf/embedded_image_handling=1 +blender/nodes/visible=0 +blender/nodes/punctual_lights=true +blender/nodes/cameras=true +blender/nodes/custom_properties=true +blender/nodes/modifiers=1 +blender/meshes/colors=false +blender/meshes/uvs=true +blender/meshes/normals=true +blender/meshes/tangents=true +blender/meshes/skins=2 +blender/meshes/export_bones_deforming_mesh_only=false +blender/materials/unpack_enabled=true +blender/materials/export_materials=1 +blender/animation/limit_playback=true +blender/animation/always_sample=true +blender/animation/group_tracks=true diff --git a/scenes/blender/trees.blend b/scenes/blender/trees.blend new file mode 100644 index 0000000000000000000000000000000000000000..878dc670386ab4f750ec3521994d5d63871bf8ff --- /dev/null +++ b/scenes/blender/trees.blend @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9bd34b01af16242b00dd4d066188d7f296bd77977dcc2060b07235896dd0ecd6 +size 1064524 diff --git a/scenes/blender/trees.blend.import b/scenes/blender/trees.blend.import new file mode 100644 index 0000000000000000000000000000000000000000..fb00b315fe48a33b4edae2c82a73cd68bab44281 --- /dev/null +++ b/scenes/blender/trees.blend.import @@ -0,0 +1,50 @@ +[remap] + +importer="scene" +importer_version=1 +type="PackedScene" +uid="uid://durrn43ia8p0w" +path="res://.godot/imported/trees.blend-715275b055fa38986bdd049a9628a487.scn" + +[deps] + +source_file="res://scenes/blender/trees.blend" +dest_files=["res://.godot/imported/trees.blend-715275b055fa38986bdd049a9628a487.scn"] + +[params] + +nodes/root_type="" +nodes/root_name="" +nodes/apply_root_scale=true +nodes/root_scale=1.0 +meshes/ensure_tangents=true +meshes/generate_lods=true +meshes/create_shadow_meshes=true +meshes/light_baking=1 +meshes/lightmap_texel_size=0.2 +meshes/force_disable_compression=false +skins/use_named_skins=true +animation/import=true +animation/fps=30 +animation/trimming=false +animation/remove_immutable_tracks=true +import_script/path="" +_subresources={} +gltf/naming_version=1 +gltf/embedded_image_handling=1 +blender/nodes/visible=0 +blender/nodes/punctual_lights=true +blender/nodes/cameras=true +blender/nodes/custom_properties=true +blender/nodes/modifiers=1 +blender/meshes/colors=false +blender/meshes/uvs=true +blender/meshes/normals=true +blender/meshes/tangents=true +blender/meshes/skins=2 +blender/meshes/export_bones_deforming_mesh_only=false +blender/materials/unpack_enabled=true +blender/materials/export_materials=1 +blender/animation/limit_playback=true +blender/animation/always_sample=true +blender/animation/group_tracks=true diff --git a/scenes/blender/turbo-powerup.blend b/scenes/blender/turbo-powerup.blend new file mode 100644 index 0000000000000000000000000000000000000000..a61cbc5209494cfc7535e61041329746747a6f09 Binary files /dev/null and b/scenes/blender/turbo-powerup.blend differ diff --git a/scenes/blender/turbo-powerup.blend.import b/scenes/blender/turbo-powerup.blend.import new file mode 100644 index 0000000000000000000000000000000000000000..6323c4c40f71f28c76872e86065b7ce19b39b34f --- /dev/null +++ b/scenes/blender/turbo-powerup.blend.import @@ -0,0 +1,50 @@ +[remap] + +importer="scene" +importer_version=1 +type="PackedScene" +uid="uid://i6n8o3eubq4s" +path="res://.godot/imported/turbo-powerup.blend-151d2bf6f4a4f5c58e7939b282791d47.scn" + +[deps] + +source_file="res://scenes/blender/turbo-powerup.blend" +dest_files=["res://.godot/imported/turbo-powerup.blend-151d2bf6f4a4f5c58e7939b282791d47.scn"] + +[params] + +nodes/root_type="" +nodes/root_name="" +nodes/apply_root_scale=true +nodes/root_scale=1.0 +meshes/ensure_tangents=true +meshes/generate_lods=true +meshes/create_shadow_meshes=true +meshes/light_baking=1 +meshes/lightmap_texel_size=0.2 +meshes/force_disable_compression=false +skins/use_named_skins=true +animation/import=true +animation/fps=30 +animation/trimming=false +animation/remove_immutable_tracks=true +import_script/path="" +_subresources={} +gltf/naming_version=1 +gltf/embedded_image_handling=1 +blender/nodes/visible=0 +blender/nodes/punctual_lights=true +blender/nodes/cameras=true +blender/nodes/custom_properties=true +blender/nodes/modifiers=1 +blender/meshes/colors=false +blender/meshes/uvs=true +blender/meshes/normals=true +blender/meshes/tangents=true +blender/meshes/skins=2 +blender/meshes/export_bones_deforming_mesh_only=false +blender/materials/unpack_enabled=true +blender/materials/export_materials=1 +blender/animation/limit_playback=true +blender/animation/always_sample=true +blender/animation/group_tracks=true diff --git a/scenes/blender/windmill.blend b/scenes/blender/windmill.blend new file mode 100644 index 0000000000000000000000000000000000000000..ba88ee0fda18d8d7434b93785afaffec6274804c --- /dev/null +++ b/scenes/blender/windmill.blend @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fd027e7e1eb33692ed1b2f500b8222fab0d843cb19848abc1961b8e4125dcea3 +size 1041636 diff --git a/scenes/blender/windmill.blend.import b/scenes/blender/windmill.blend.import new file mode 100644 index 0000000000000000000000000000000000000000..e69c14f672c3f343ac8637e89b75d8d21268fe6a --- /dev/null +++ b/scenes/blender/windmill.blend.import @@ -0,0 +1,50 @@ +[remap] + +importer="scene" +importer_version=1 +type="PackedScene" +uid="uid://rwnopf1jlov5" +path="res://.godot/imported/windmill.blend-9b432f6a3fc5d771497431367f6495d3.scn" + +[deps] + +source_file="res://scenes/blender/windmill.blend" +dest_files=["res://.godot/imported/windmill.blend-9b432f6a3fc5d771497431367f6495d3.scn"] + +[params] + +nodes/root_type="" +nodes/root_name="" +nodes/apply_root_scale=true +nodes/root_scale=1.0 +meshes/ensure_tangents=true +meshes/generate_lods=true +meshes/create_shadow_meshes=true +meshes/light_baking=1 +meshes/lightmap_texel_size=0.2 +meshes/force_disable_compression=false +skins/use_named_skins=true +animation/import=true +animation/fps=30 +animation/trimming=false +animation/remove_immutable_tracks=true +import_script/path="" +_subresources={} +gltf/naming_version=1 +gltf/embedded_image_handling=1 +blender/nodes/visible=0 +blender/nodes/punctual_lights=true +blender/nodes/cameras=true +blender/nodes/custom_properties=true +blender/nodes/modifiers=1 +blender/meshes/colors=false +blender/meshes/uvs=true +blender/meshes/normals=true +blender/meshes/tangents=true +blender/meshes/skins=2 +blender/meshes/export_bones_deforming_mesh_only=false +blender/materials/unpack_enabled=true +blender/materials/export_materials=1 +blender/animation/limit_playback=true +blender/animation/always_sample=true +blender/animation/group_tracks=true diff --git a/scenes/car/car.gd b/scenes/car/car.gd new file mode 100644 index 0000000000000000000000000000000000000000..e1f0375db1207fa58de34da704717ad9c5db37a6 --- /dev/null +++ b/scenes/car/car.gd @@ -0,0 +1,214 @@ +extends RigidBody3D +class_name Car + +var track: Track +var other_car: Car + +# Car performance settings +var acceleration = 30.0 +var torque = 7.0 +var backward_acceleration_ratio = 0.75 + +@onready var ai_controller: CarAIController = $CarAIController +@onready var raycast_sensor_wall: RayCastSensor3D = $RayCastSensorWall +@onready var raycast_sensor_other_car: RayCastSensorAddSetCollisionMaskValue = $RayCastSensorOtherCar +@onready var camera: Camera3D = $"Camera3D" + +var ui: UI +var thrusters: Array[Thruster] + +## Set by AIController during inference +var requested_acceleration: float +## Set by AIController during inference +var requested_steering: float + +# Track related data +var track_length: float +var previous_offset: float +var next_checkpoint_offset: float +var current_offset: float +var laps_passed: int +var first_checkpoint_offset: float + + +# Game settings data +var infinite_race: bool +var total_laps: int +var seconds_until_race_begins: int +var training_mode: bool + +var initial_transform: Transform3D +var _just_reset: bool + + +func _ready(): + thrusters.append_array( + [ + get_node("Thruster1Particles"), + get_node("Thruster2Particles") + ] + ) + + ai_controller.init(self) + initial_transform = global_transform + track_length = track.track_path.curve.get_baked_length() + first_checkpoint_offset = track_length / 30.0 + + +func reset(): + laps_passed = 0 + next_checkpoint_offset = first_checkpoint_offset + + global_transform = initial_transform + + for thruster in thrusters: + thruster.set_thruster_strength(0) + + if not training_mode: + if camera.current: + ui.set_current_lap_text(laps_passed + 1) + ui.show_get_ready_text(seconds_until_race_begins) + + process_mode = Node.PROCESS_MODE_DISABLED + await get_tree().create_timer(seconds_until_race_begins, true, true).timeout + process_mode = Node.PROCESS_MODE_INHERIT + + _just_reset = true + +func _integrate_forces(state): + if _just_reset: + state.linear_velocity = Vector3.ZERO + state.angular_velocity = Vector3.ZERO + state.transform = initial_transform + _just_reset = false + + +func get_next_checkpoint_offset() -> float: + return fmod(next_checkpoint_offset + track_length / 30.0, track_length) + + +func get_other_car_position_in_local_reference() -> Array[float]: + var local_position = ( + to_local(global_position - other_car.global_position).limit_length(150.0) / 150.0 + ) + return [local_position.x, local_position.z] + + +func _physics_process(_delta): + if ai_controller.needs_reset: + ai_controller.reset() + reset() + + var acceleration_to_apply := 0.0 + var steering_to_apply := 0.0 + + if ai_controller.heuristic == "human": + update_track_related_data() + + if Input.is_action_pressed("move_forward"): + acceleration_to_apply += acceleration + if Input.is_action_pressed("move_backward"): + acceleration_to_apply -= acceleration * backward_acceleration_ratio + + if Input.is_action_pressed("steer_left"): + steering_to_apply += torque + if Input.is_action_pressed("steer_right"): + steering_to_apply -= torque + else: + if requested_acceleration < 0: + requested_acceleration *= backward_acceleration_ratio + acceleration_to_apply = requested_acceleration * acceleration + steering_to_apply = requested_steering * torque + + apply_central_force(global_transform.basis.z * acceleration_to_apply) + apply_torque(global_transform.basis.y * steering_to_apply) + + for thruster in thrusters: + thruster.set_thruster_strength(abs(acceleration_to_apply) * 0.05) + + +func handle_victory(): + if laps_passed >= total_laps and other_car.laps_passed < total_laps: + if not training_mode: + ui.show_winner_text(name, seconds_until_race_begins) + await get_tree().create_timer(seconds_until_race_begins, true, true).timeout + + _end_episode(0) + other_car._end_episode(0) + + +## Updates any data needed before the AI controller sends observations +func prepare_for_sending_obs(): + update_track_related_data() + + +## Update the data for tracking the current progress along the track +func update_track_related_data(): + update_current_offset() + update_checkpoint() + + +func update_current_offset(): + current_offset = track.track_path.curve.get_closest_offset(global_position) + + +func update_checkpoint(): + if abs(current_offset - next_checkpoint_offset) < (track_length / 60.0): + next_checkpoint_offset = get_next_checkpoint_offset() + if is_equal_approx(next_checkpoint_offset, track_length / 30.0): + laps_passed += 1 + if camera.current and not training_mode: + ui.set_current_lap_text(laps_passed + 1) + if not infinite_race: + handle_victory() + else: + _end_episode() + + +func update_reward(): + var offset_difference = current_offset - previous_offset + + if offset_difference > (track_length / 2.0): + offset_difference = offset_difference - track_length + + if offset_difference < -(track_length / 2.0): + offset_difference = offset_difference + track_length + + ## Reward for moving along the track (positive or negative depending on direction) + ai_controller.reward += offset_difference / 10.0 + + ## Backward movement penalty + ai_controller.reward += min(0.0, get_normalized_velocity_in_player_reference().z + 0.1) * 5.0 + + previous_offset = current_offset + pass + + +func get_next_track_points(num_points: int, step_size: float) -> Array: + var temp_array: Array[float] = [] + var closest_offset = current_offset + + for i in range(0, num_points): + var current_point = track.track_path.curve.sample_baked( + fmod(closest_offset + step_size * (i + 1), track_length) + ) + var local = to_local(current_point) / (num_points * step_size) + temp_array.append_array([local.x, local.z]) + return temp_array + + +func _end_episode(final_reward: float = 0.0): + ai_controller.reward += final_reward + ai_controller.done = true + ai_controller.reset() + + if not infinite_race: + reset() + + +func get_normalized_velocity_in_player_reference(): + return (global_transform.basis.inverse() * linear_velocity).limit_length(42.0) / 42.0 + + +func _on_body_entered(_body): + ai_controller.reward -= 4.0 diff --git a/scenes/car/car.tscn b/scenes/car/car.tscn new file mode 100644 index 0000000000000000000000000000000000000000..16f9d592d88a98b671be67b92943ed89b74f5200 --- /dev/null +++ b/scenes/car/car.tscn @@ -0,0 +1,281 @@ +[gd_scene load_steps=16 format=3 uid="uid://c68mety64bigp"] + +[ext_resource type="Script" path="res://scenes/car/car.gd" id="1_0gshy"] +[ext_resource type="PackedScene" uid="uid://c7pyws8sguicn" path="res://scenes/blender/car_base.blend" id="2_lbr3a"] +[ext_resource type="Script" path="res://scenes/car/propeller.gd" id="3_s0gu7"] +[ext_resource type="Script" path="res://scenes/car/raycast_sensor_3d_add_set_collision_mask_value.gd" id="4_e1dys"] +[ext_resource type="Script" path="res://scenes/car/car_ai_controller.gd" id="5_e2db2"] +[ext_resource type="Script" path="res://scenes/car/thruster.gd" id="6_k7k6o"] + +[sub_resource type="PhysicsMaterial" id="PhysicsMaterial_ypfti"] +friction = 0.55 + +[sub_resource type="CapsuleShape3D" id="CapsuleShape3D_av0n1"] +radius = 1.86536 +height = 3.80065 + +[sub_resource type="Gradient" id="Gradient_mgod5"] +offsets = PackedFloat32Array(0, 0.481113, 0.578529) +colors = PackedColorArray(1, 0.635294, 0, 1, 0.811765, 0.109804, 0, 0.0235294, 0, 0, 0, 0.0784314) + +[sub_resource type="GradientTexture1D" id="GradientTexture1D_vuvka"] +gradient = SubResource("Gradient_mgod5") + +[sub_resource type="ParticleProcessMaterial" id="ParticleProcessMaterial_3cba4"] +resource_local_to_scene = true +direction = Vector3(0, 0, -1) +spread = 2.0 +initial_velocity_min = 0.02 +initial_velocity_max = 0.1 +gravity = Vector3(0, 0, 0) +scale_min = 0.5 +color_ramp = SubResource("GradientTexture1D_vuvka") + +[sub_resource type="Gradient" id="Gradient_nm2v8"] +colors = PackedColorArray(1, 1, 1, 1, 1, 1, 1, 0) + +[sub_resource type="GradientTexture2D" id="GradientTexture2D_vf6a5"] +gradient = SubResource("Gradient_nm2v8") +fill = 1 +fill_from = Vector2(0.5, 0.5) +fill_to = Vector2(0, 0.5) + +[sub_resource type="StandardMaterial3D" id="StandardMaterial3D_618ls"] +transparency = 1 +shading_mode = 0 +vertex_color_use_as_albedo = true +albedo_texture = SubResource("GradientTexture2D_vf6a5") +billboard_mode = 3 +particles_anim_h_frames = 1 +particles_anim_v_frames = 1 +particles_anim_loop = false + +[sub_resource type="QuadMesh" id="QuadMesh_4n6j1"] +material = SubResource("StandardMaterial3D_618ls") +size = Vector2(0.1, 0.1) + +[node name="Car" type="RigidBody3D"] +collision_layer = 0 +collision_mask = 0 +axis_lock_linear_y = true +axis_lock_angular_x = true +axis_lock_angular_z = true +physics_material_override = SubResource("PhysicsMaterial_ypfti") +continuous_cd = true +max_contacts_reported = 1 +contact_monitor = true +linear_damp = 1.0 +angular_damp = 1.0 +script = ExtResource("1_0gshy") + +[node name="car_base" parent="." instance=ExtResource("2_lbr3a")] + +[node name="Propeller" parent="car_base" index="5"] +process_mode = 1 +script = ExtResource("3_s0gu7") + +[node name="Propeller_001" parent="car_base" index="6"] +process_mode = 1 +script = ExtResource("3_s0gu7") + +[node name="Propeller_002" parent="car_base" index="7"] +process_mode = 1 +script = ExtResource("3_s0gu7") + +[node name="Propeller_003" parent="car_base" index="8"] +process_mode = 1 +script = ExtResource("3_s0gu7") + +[node name="CollisionShape3D" type="CollisionShape3D" parent="."] +transform = Transform3D(0.5, 0, 0, 0, -2.18557e-08, -0.5, 0, 0.5, -2.18557e-08, 0, 0.102682, 4.48839e-09) +shape = SubResource("CapsuleShape3D_av0n1") + +[node name="RayCastSensorWall" type="Node3D" parent="."] +script = ExtResource("4_e1dys") +n_rays_width = 17.0 +n_rays_height = 1.0 +ray_length = 45.0 +cone_width = 360.0 +cone_height = 0.0 +collide_with_areas = true + +[node name="@RayCast3D@70840" type="RayCast3D" parent="RayCastSensorWall"] +target_position = Vector3(-8.26873, 0, -44.2338) +collide_with_areas = true + +[node name="@RayCast3D@70841" type="RayCast3D" parent="RayCastSensorWall"] +target_position = Vector3(-23.6894, 0, -38.2598) +collide_with_areas = true + +[node name="@RayCast3D@70842" type="RayCast3D" parent="RayCastSensorWall"] +target_position = Vector3(-35.9108, 0, -27.1186) +collide_with_areas = true + +[node name="@RayCast3D@70843" type="RayCast3D" parent="RayCastSensorWall"] +target_position = Vector3(-43.2822, 0, -12.3148) +collide_with_areas = true + +[node name="@RayCast3D@70844" type="RayCast3D" parent="RayCastSensorWall"] +target_position = Vector3(-44.808, 0, 4.15208) +collide_with_areas = true + +[node name="@RayCast3D@70845" type="RayCast3D" parent="RayCastSensorWall"] +target_position = Vector3(-40.2823, 0, 20.0582) +collide_with_areas = true + +[node name="@RayCast3D@70846" type="RayCast3D" parent="RayCastSensorWall"] +target_position = Vector3(-30.3163, 0, 33.2554) +collide_with_areas = true + +[node name="@RayCast3D@70847" type="RayCast3D" parent="RayCastSensorWall"] +target_position = Vector3(-16.2559, 0, 41.9613) +collide_with_areas = true + +[node name="@RayCast3D@70848" type="RayCast3D" parent="RayCastSensorWall"] +target_position = Vector3(0, 0, 45) +collide_with_areas = true + +[node name="@RayCast3D@70849" type="RayCast3D" parent="RayCastSensorWall"] +target_position = Vector3(16.2559, 0, 41.9613) +collide_with_areas = true + +[node name="@RayCast3D@70850" type="RayCast3D" parent="RayCastSensorWall"] +target_position = Vector3(30.3163, 0, 33.2554) +collide_with_areas = true + +[node name="@RayCast3D@70851" type="RayCast3D" parent="RayCastSensorWall"] +target_position = Vector3(40.2823, 0, 20.0582) +collide_with_areas = true + +[node name="@RayCast3D@70852" type="RayCast3D" parent="RayCastSensorWall"] +target_position = Vector3(44.808, 0, 4.15208) +collide_with_areas = true + +[node name="@RayCast3D@70853" type="RayCast3D" parent="RayCastSensorWall"] +target_position = Vector3(43.2822, 0, -12.3148) +collide_with_areas = true + +[node name="@RayCast3D@70854" type="RayCast3D" parent="RayCastSensorWall"] +target_position = Vector3(35.9108, 0, -27.1186) +collide_with_areas = true + +[node name="@RayCast3D@70855" type="RayCast3D" parent="RayCastSensorWall"] +target_position = Vector3(23.6894, 0, -38.2598) +collide_with_areas = true + +[node name="@RayCast3D@70856" type="RayCast3D" parent="RayCastSensorWall"] +target_position = Vector3(8.26873, 0, -44.2338) +collide_with_areas = true + +[node name="RayCastSensorOtherCar" type="Node3D" parent="."] +script = ExtResource("4_e1dys") +collision_mask = 0 +boolean_class_mask = 0 +n_rays_width = 17.0 +n_rays_height = 1.0 +ray_length = 45.0 +cone_width = 360.0 +cone_height = 0.0 +collide_with_areas = true + +[node name="_RayCast3D_70840" type="RayCast3D" parent="RayCastSensorOtherCar"] +target_position = Vector3(-8.26873, 0, -44.2338) +collide_with_areas = true + +[node name="_RayCast3D_70841" type="RayCast3D" parent="RayCastSensorOtherCar"] +target_position = Vector3(-23.6894, 0, -38.2598) +collide_with_areas = true + +[node name="_RayCast3D_70842" type="RayCast3D" parent="RayCastSensorOtherCar"] +target_position = Vector3(-35.9108, 0, -27.1186) +collide_with_areas = true + +[node name="_RayCast3D_70843" type="RayCast3D" parent="RayCastSensorOtherCar"] +target_position = Vector3(-43.2822, 0, -12.3148) +collide_with_areas = true + +[node name="_RayCast3D_70844" type="RayCast3D" parent="RayCastSensorOtherCar"] +target_position = Vector3(-44.808, 0, 4.15208) +collide_with_areas = true + +[node name="_RayCast3D_70845" type="RayCast3D" parent="RayCastSensorOtherCar"] +target_position = Vector3(-40.2823, 0, 20.0582) +collide_with_areas = true + +[node name="_RayCast3D_70846" type="RayCast3D" parent="RayCastSensorOtherCar"] +target_position = Vector3(-30.3163, 0, 33.2554) +collide_with_areas = true + +[node name="_RayCast3D_70847" type="RayCast3D" parent="RayCastSensorOtherCar"] +target_position = Vector3(-16.2559, 0, 41.9613) +collide_with_areas = true + +[node name="_RayCast3D_70848" type="RayCast3D" parent="RayCastSensorOtherCar"] +target_position = Vector3(0, 0, 45) +collide_with_areas = true + +[node name="_RayCast3D_70849" type="RayCast3D" parent="RayCastSensorOtherCar"] +target_position = Vector3(16.2559, 0, 41.9613) +collide_with_areas = true + +[node name="_RayCast3D_70850" type="RayCast3D" parent="RayCastSensorOtherCar"] +target_position = Vector3(30.3163, 0, 33.2554) +collide_with_areas = true + +[node name="_RayCast3D_70851" type="RayCast3D" parent="RayCastSensorOtherCar"] +target_position = Vector3(40.2823, 0, 20.0582) +collide_with_areas = true + +[node name="_RayCast3D_70852" type="RayCast3D" parent="RayCastSensorOtherCar"] +target_position = Vector3(44.808, 0, 4.15208) +collide_with_areas = true + +[node name="_RayCast3D_70853" type="RayCast3D" parent="RayCastSensorOtherCar"] +target_position = Vector3(43.2822, 0, -12.3148) +collide_with_areas = true + +[node name="_RayCast3D_70854" type="RayCast3D" parent="RayCastSensorOtherCar"] +target_position = Vector3(35.9108, 0, -27.1186) +collide_with_areas = true + +[node name="_RayCast3D_70855" type="RayCast3D" parent="RayCastSensorOtherCar"] +target_position = Vector3(23.6894, 0, -38.2598) +collide_with_areas = true + +[node name="_RayCast3D_70856" type="RayCast3D" parent="RayCastSensorOtherCar"] +target_position = Vector3(8.26873, 0, -44.2338) +collide_with_areas = true + +[node name="CarAIController" type="Node3D" parent="."] +script = ExtResource("5_e2db2") +reset_after = 50000 + +[node name="Thruster1Particles" type="GPUParticles3D" parent="."] +process_mode = 1 +transform = Transform3D(15.625, 0, 0, 0, 15.625, -6.8299e-07, 0, 6.8299e-07, 15.625, 0.106975, -0.128882, -0.737488) +amount = 32 +lifetime = 0.23 +local_coords = true +trail_lifetime = 0.2 +process_material = SubResource("ParticleProcessMaterial_3cba4") +draw_pass_1 = SubResource("QuadMesh_4n6j1") +script = ExtResource("6_k7k6o") + +[node name="Thruster2Particles" type="GPUParticles3D" parent="."] +process_mode = 1 +transform = Transform3D(15.625, 0, 0, 0, 15.625, -6.8299e-07, 0, 6.8299e-07, 15.625, -0.106975, -0.128882, -0.737487) +amount = 32 +lifetime = 0.23 +local_coords = true +trail_lifetime = 0.2 +process_material = SubResource("ParticleProcessMaterial_3cba4") +draw_pass_1 = SubResource("QuadMesh_4n6j1") +script = ExtResource("6_k7k6o") + +[node name="Camera3D" type="Camera3D" parent="."] +transform = Transform3D(-1, -1.90707e-08, 8.53174e-08, 0, 0.975917, 0.218143, -8.74228e-08, 0.218143, -0.975917, 0, 0.94, -3.37) + +[connection signal="body_entered" from="." to="." method="_on_body_entered"] +[connection signal="body_exited" from="." to="." method="_on_body_exited"] + +[editable path="car_base"] diff --git a/scenes/car/car_ai_controller.gd b/scenes/car/car_ai_controller.gd new file mode 100644 index 0000000000000000000000000000000000000000..179abb2a18414469f16c1330698614921e0ca712 --- /dev/null +++ b/scenes/car/car_ai_controller.gd @@ -0,0 +1,57 @@ +extends AIController3D +class_name CarAIController + +var track: Track + +var human_controlled_on_inference: bool + + +func reset(): + n_steps = 0 + needs_reset = false + + +func get_obs_for_car(car: Car): + var player_velocity = car.get_normalized_velocity_in_player_reference() + var observations: Array = [player_velocity.x, player_velocity.z, car.angular_velocity.y / 5.0] + + observations.append_array(car.get_next_track_points(3, 20)) + observations.append_array(car.raycast_sensor_wall.get_observation()) + observations.append_array(car.raycast_sensor_other_car.get_observation()) + observations.append_array(car.get_other_car_position_in_local_reference()) + + var closest_powerup = track.get_closest_powerup(car.global_position) as Powerup + var powerup_relative_position = ( + (car.to_local(closest_powerup.global_position)).limit_length(150) / 150.0 + ) + var powerup_obs: Array[float] = [powerup_relative_position.x, powerup_relative_position.z] + powerup_obs.append_array(closest_powerup.category_as_array_one_hot_encoded) + observations.append_array(powerup_obs) + return observations + + +func get_obs() -> Dictionary: + _player.prepare_for_sending_obs() + return {"obs": get_obs_for_car(_player)} + + +func get_reward() -> float: + _player.update_reward() + return reward + + +func get_action_space() -> Dictionary: + return { + "acceleration": {"size": 1, "action_type": "continuous"}, + "steering": {"size": 1, "action_type": "continuous"}, + } + + +## This override disables restarting the episode due to timeout +func _physics_process(_delta): + n_steps += 1 + + +func set_action(action) -> void: + _player.requested_acceleration = clampf(action.acceleration[0], -1.0, 1.0) + _player.requested_steering = clampf(action.steering[0], -1.0, 1.0) diff --git a/scenes/car/car_manager.gd b/scenes/car/car_manager.gd new file mode 100644 index 0000000000000000000000000000000000000000..e8d28b1e733f0838e791451cb9fbbd0a0ba86da0 --- /dev/null +++ b/scenes/car/car_manager.gd @@ -0,0 +1,89 @@ +extends Node3D + +class_name CarManager + +@export var track: Track +@export var car_scene: PackedScene + +## Each car group consists of 2 cars +@export var number_of_car_groups_to_spawn: int = 2 + +var ui: UI + +var training_mode: bool = true +var player_vs_ai_mode: bool = false +var infinite_race: bool = true +var total_laps: int +var seconds_until_race_begins: int + + +# Called when the node enters the scene tree for the first time. +func _ready(): + spawn_cars(number_of_car_groups_to_spawn) + + +func spawn_cars(car_group_amount): + if not training_mode: + car_group_amount = 1 + + var car1color: Color = Color.from_hsv(randf_range(0, 1), 0.6, 0.6) + var car2color: Color = car1color + car2color.h = fmod(car1color.h + randf_range(0.2, 0.8), 1.0) + + var player_car_id: int = randi_range(0, 1) + + for group_id in range(0, car_group_amount): + var spawned_cars: Array[Car] = [] + + for car_id in range(0, 2): + var car = car_scene.instantiate() as Car + car.name = "AI-%d%d" % [group_id, car_id] + car.track = track + + # Detect collision with walls + car.set_collision_mask_value(1, true) + + # Detect collision with other car + var current_car_layer := 2 + car_id + (group_id * 2) + var other_car_layer := 2 + ((car_id + 1) % 2) + (group_id * 2) + car.set_collision_layer_value(current_car_layer, true) + car.set_collision_mask_value(other_car_layer, true) + + var car_transform: Transform3D = track.track_path.curve.sample_baked_with_rotation(0.0) + car_transform = car_transform.rotated_local(Vector3.UP, PI) + car_transform.origin += Vector3.UP + car_transform.origin += car_transform.basis.x * (car_id * 2.0 - 1.5) + car.global_transform = car_transform + + car.infinite_race = infinite_race + car.total_laps = total_laps + car.ui = ui + car.seconds_until_race_begins = seconds_until_race_begins + car.training_mode = training_mode + + var car_body: MeshInstance3D = car.get_node("car_base/Body") as MeshInstance3D + var new_material: StandardMaterial3D = ( + car_body.get_active_material(0).duplicate() as StandardMaterial3D + ) + + var color: Color = car1color if car_id == 0 else car2color + new_material.albedo_color = color + car_body.set_surface_override_material(0, new_material) + + spawned_cars.append(car) + add_child(car) + + if car_id == 1: + car.other_car = spawned_cars[0] + spawned_cars[0].other_car = car + + if player_vs_ai_mode and player_car_id == car_id: + car.name = "Player" + car.get_node("Camera3D").current = true + car.get_node("CarAIController").human_controlled_on_inference = true + + # Raycast detect collision with other car + car.raycast_sensor_other_car.set_collision_mask_value(other_car_layer, true) + car.ai_controller.track = track + + car.reset() diff --git a/scenes/car/car_manager.tscn b/scenes/car/car_manager.tscn new file mode 100644 index 0000000000000000000000000000000000000000..1002af21894e5d404440748fb3762d8b0461175f --- /dev/null +++ b/scenes/car/car_manager.tscn @@ -0,0 +1,8 @@ +[gd_scene load_steps=3 format=3 uid="uid://qkw7dc6ny444"] + +[ext_resource type="Script" path="res://scenes/car/car_manager.gd" id="1_4htxb"] +[ext_resource type="PackedScene" uid="uid://c68mety64bigp" path="res://scenes/car/car.tscn" id="2_crxv0"] + +[node name="CarManager" type="Node3D"] +script = ExtResource("1_4htxb") +car_scene = ExtResource("2_crxv0") diff --git a/scenes/car/propeller.gd b/scenes/car/propeller.gd new file mode 100644 index 0000000000000000000000000000000000000000..53fc94f6822e20720709c8d66e4744490f16ffce --- /dev/null +++ b/scenes/car/propeller.gd @@ -0,0 +1,7 @@ +extends MeshInstance3D + +## Provides rotating propeller animation +@export var propeller_rotation_speed := 30.0 + +func _physics_process(delta): + rotate_object_local(Vector3.UP, propeller_rotation_speed * delta) diff --git a/scenes/car/raycast_sensor_3d_add_set_collision_mask_value.gd b/scenes/car/raycast_sensor_3d_add_set_collision_mask_value.gd new file mode 100644 index 0000000000000000000000000000000000000000..fae5b001fb058691d39b5bfda0ad22ba749ef387 --- /dev/null +++ b/scenes/car/raycast_sensor_3d_add_set_collision_mask_value.gd @@ -0,0 +1,6 @@ +extends RayCastSensor3D +class_name RayCastSensorAddSetCollisionMaskValue + +func set_collision_mask_value(layer_number: int, value: bool): + for ray in rays: + ray.set_collision_mask_value(layer_number, value) diff --git a/scenes/car/sync_allow_human_control_on_inference.gd b/scenes/car/sync_allow_human_control_on_inference.gd new file mode 100644 index 0000000000000000000000000000000000000000..8e1584c04c32c5a843ab3562fe779b93f1cb83fc --- /dev/null +++ b/scenes/car/sync_allow_human_control_on_inference.gd @@ -0,0 +1,8 @@ +extends "res://addons/godot_rl_agents/sync.gd" +class_name SyncAllowHumanControlOnInference + +func _set_heuristic(heuristic): + for agent in agents: + # If an agent instance is to be controlled by the player, skip changing heuristic from "human" (the default) + if not agent.human_controlled_on_inference: + agent.set_heuristic(heuristic) diff --git a/scenes/car/thruster.gd b/scenes/car/thruster.gd new file mode 100644 index 0000000000000000000000000000000000000000..976f0a2971d328903801b3ff548735661a56696e --- /dev/null +++ b/scenes/car/thruster.gd @@ -0,0 +1,10 @@ +extends GPUParticles3D +class_name Thruster + +var thruster_strength: float + +@onready var material: ParticleProcessMaterial = process_material + +func set_thruster_strength(strength: float): + material.initial_velocity_min = 0.022 * strength + 0.015 + material.initial_velocity_max = 0.1 * strength + 0.015 diff --git a/scenes/game_scene/UI.gd b/scenes/game_scene/UI.gd new file mode 100644 index 0000000000000000000000000000000000000000..4a7140b90c8f8ee39b246bb6319e7e6014c48bc5 --- /dev/null +++ b/scenes/game_scene/UI.gd @@ -0,0 +1,40 @@ +extends Control +class_name UI + +@export var current_lap: Label +@export var get_ready: Label +@export var winner: Label + +var total_laps: int + +func _ready(): + winner.visible = false + +func set_current_lap_text(lap: int): + if not current_lap.visible: + current_lap.visible = true + + if total_laps == 0: + current_lap.text = "Lap: %d/∞" % lap + else: + current_lap.text = "Lap: %d/%d" % [lap, total_laps] + + +func show_get_ready_text(seconds_remaining: int): + get_ready.visible = true + for seconds in range(seconds_remaining, 0, -1): + get_ready.text = "Get ready! Race starting in: %d" % seconds + await get_tree().create_timer(1, true, true).timeout + deactivate_get_ready_text() + +func deactivate_get_ready_text(): + get_ready.visible = false + +func show_winner_text(winner_name: String, seconds_until_deactivated: int = 0): + winner.text = "The winner is %s!" % winner_name + winner.visible = true + await get_tree().create_timer(seconds_until_deactivated, true, true).timeout + deactivate_winner_text() + +func deactivate_winner_text(): + winner.visible = false diff --git a/scenes/game_scene/game_manager.gd b/scenes/game_scene/game_manager.gd new file mode 100644 index 0000000000000000000000000000000000000000..2aa40173e6a5be7d944adaab7262f35dbae6923a --- /dev/null +++ b/scenes/game_scene/game_manager.gd @@ -0,0 +1,40 @@ +extends Node3D + +enum GameModes { TRAINING, AI_VS_AI, PLAYER_VS_AI } +@export var game_mode: GameModes = GameModes.TRAINING +@export var game_scene: PackedScene + +## If set to 0, it will be an infinite race without announcing winners. +@export_range(0, 10, 1, "or_greater") var total_laps := 0 + +@export var seconds_until_race_begins: int = 5 + + +func _ready(): + var new_game_scene: Node3D = game_scene.instantiate() + var sync = new_game_scene.get_node("Sync") as SyncAllowHumanControlOnInference + var cars = new_game_scene.get_node("Cars") as CarManager + var ui = new_game_scene.get_node("UI") as UI + var track = new_game_scene.get_node("Track") as Track + + cars.infinite_race = false if total_laps > 0 else true + cars.total_laps = total_laps + ui.total_laps = total_laps + cars.ui = ui + cars.seconds_until_race_begins = seconds_until_race_begins + + match game_mode: + GameModes.TRAINING: + sync.control_mode = sync.ControlModes.TRAINING + track.training_mode = true + sync.speed_up = 20.0 + GameModes.AI_VS_AI: + sync.control_mode = sync.ControlModes.ONNX_INFERENCE + cars.training_mode = false + sync.speed_up = 1.0 + GameModes.PLAYER_VS_AI: + sync.control_mode = sync.ControlModes.ONNX_INFERENCE + cars.training_mode = false + cars.player_vs_ai_mode = true + sync.speed_up = 1.0 + add_child(new_game_scene) diff --git a/scenes/game_scene/game_scene.tscn b/scenes/game_scene/game_scene.tscn new file mode 100644 index 0000000000000000000000000000000000000000..b0f144ab65ec626f9f5d06d5e7573e479f915b0f --- /dev/null +++ b/scenes/game_scene/game_scene.tscn @@ -0,0 +1,352 @@ +[gd_scene load_steps=39 format=3 uid="uid://dqb4x6b4gfiq3"] + +[ext_resource type="Script" path="res://scenes/track/track.gd" id="1_eraeg"] +[ext_resource type="PackedScene" uid="uid://btq75ag6rkb8w" path="res://scenes/track/checkpoint.tscn" id="2_kplf2"] +[ext_resource type="PackedScene" uid="uid://nc0c705yeiad" path="res://scenes/blender/rock.blend" id="3_wvqgn"] +[ext_resource type="PackedScene" uid="uid://illlhd3ii08e" path="res://scenes/blender/rock2.blend" id="4_gkjus"] +[ext_resource type="PackedScene" uid="uid://fw03ms4srid4" path="res://scenes/blender/tree.blend" id="4_qwgxh"] +[ext_resource type="PackedScene" uid="uid://cxm7d8jq4kuel" path="res://scenes/blender/tree2.blend" id="5_051ri"] +[ext_resource type="PackedScene" uid="uid://c1oi504d42b6j" path="res://scenes/track/windmill.tscn" id="6_djis2"] +[ext_resource type="PackedScene" uid="uid://c78p4qwxklpxv" path="res://scenes/blender/tree3.blend" id="6_w17qq"] +[ext_resource type="PackedScene" uid="uid://c58ogt6th7xqn" path="res://scenes/blender/tree4.blend" id="7_42mh8"] +[ext_resource type="PackedScene" uid="uid://c0klg0d436txx" path="res://scenes/blender/tree5.blend" id="8_ftc8r"] +[ext_resource type="PackedScene" uid="uid://c4uwdcusug3ux" path="res://scenes/track/turbo_powerup.tscn" id="10_g6xuj"] +[ext_resource type="PackedScene" uid="uid://c8wjel5fyyfgg" path="res://scenes/track/reverse_turbo_powerup.tscn" id="11_rvn62"] +[ext_resource type="PackedScene" uid="uid://b5fvhpui2jqhv" path="res://scenes/blender/house.blend" id="12_jp4aw"] +[ext_resource type="PackedScene" uid="uid://1na3logqa0u3" path="res://scenes/blender/house2.blend" id="14_t13kj"] +[ext_resource type="Script" path="res://scenes/car/sync_allow_human_control_on_inference.gd" id="16_47pia"] +[ext_resource type="PackedScene" uid="uid://qkw7dc6ny444" path="res://scenes/car/car_manager.tscn" id="16_i65dl"] +[ext_resource type="Script" path="res://scenes/game_scene/UI.gd" id="17_1xllr"] + +[sub_resource type="StandardMaterial3D" id="StandardMaterial3D_p0ylt"] +transparency = 1 +albedo_color = Color(0.8, 0.8, 0.8, 1) + +[sub_resource type="Gradient" id="Gradient_35fhw"] +interpolation_mode = 1 +offsets = PackedFloat32Array(0, 0.5) +colors = PackedColorArray(0.0627451, 0, 0, 1, 1, 1, 0, 1) + +[sub_resource type="GradientTexture1D" id="GradientTexture1D_exfeh"] +gradient = SubResource("Gradient_35fhw") +width = 64 + +[sub_resource type="StandardMaterial3D" id="StandardMaterial3D_s06bd"] +cull_mode = 2 +albedo_texture = SubResource("GradientTexture1D_exfeh") +roughness = 0.0 +refraction_scale = 0.0 + +[sub_resource type="Gradient" id="Gradient_dqyuu"] +interpolation_mode = 1 +offsets = PackedFloat32Array(0, 0.5) +colors = PackedColorArray(0, 0, 0, 0, 1, 1, 1, 1) + +[sub_resource type="GradientTexture1D" id="GradientTexture1D_mp6fq"] +gradient = SubResource("Gradient_dqyuu") +width = 64 + +[sub_resource type="StandardMaterial3D" id="StandardMaterial3D_fwfq4"] +transparency = 1 +albedo_texture = SubResource("GradientTexture1D_mp6fq") + +[sub_resource type="Gradient" id="Gradient_6f18m"] +colors = PackedColorArray(0.2, 0.2, 0.2, 1, 0.06, 0.06, 0.06, 1) + +[sub_resource type="FastNoiseLite" id="FastNoiseLite_hwiyf"] +noise_type = 3 +frequency = 0.1563 +fractal_gain = 0.83 +fractal_weighted_strength = 0.33 + +[sub_resource type="NoiseTexture2D" id="NoiseTexture2D_dac54"] +color_ramp = SubResource("Gradient_6f18m") +noise = SubResource("FastNoiseLite_hwiyf") + +[sub_resource type="StandardMaterial3D" id="StandardMaterial3D_7elja"] +albedo_texture = SubResource("NoiseTexture2D_dac54") +uv1_scale = Vector3(0.2, 0.2, 0.2) +uv1_triplanar = true + +[sub_resource type="Curve3D" id="Curve3D_5j3hw"] +bake_interval = 0.1 +_data = { +"points": PackedVector3Array(22.7055, 0, 1.89175, -22.7055, 0, -1.89175, 0.764469, 0, 77.9037, 0, 0, 0, 0, 0, 0, -29.8344, -0.00012207, 41.8395, 22.5464, -0.00012207, -18.5012, -22.5464, 0.00012207, 18.5012, -68.5292, 0, 36.6527, -21.6077, 0, 6.40967, 21.6077, 0, -6.40967, -77.9995, 0, 10.4469, 0, 0, 0, 0, 0, 0, -65.6174, 0, -21.6066, 0, 0, 0, 0, 0, 0, -69.1102, 0, -43.1108, 0, 0, 0, 0, 0, 0, -77.6366, 0, -64.7269, -29.0616, 0.00012207, 1.92143, 29.0616, -0.00012207, -1.92143, -52.2977, -0.00012207, -88.2644, 7.27809, -0.00012207, -32.903, -7.27809, 0.00012207, 32.903, 52.1795, -0.00012207, -91.4526, -18.2936, 0, -37.8456, 18.2936, 0, 37.8456, 125.738, 0, -41.3968, 0, 0, 0, 0, 0, 0, 88.594, 0, 6.66104, 0, 0, 0, 0, 0, 0, 65.0917, 0, 16.8612, -12.6871, -0.00012207, -22.5404, 12.6871, 0.00012207, 22.5404, 42.2424, 0, 61.3878, 0, 0, 0, 0, 0, 0, 0.764469, 0, 77.9037), +"tilts": PackedFloat32Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) +} +point_count = 14 + +[sub_resource type="StandardMaterial3D" id="StandardMaterial3D_med5r"] +roughness = 0.5 + +[sub_resource type="ProceduralSkyMaterial" id="ProceduralSkyMaterial_x2c37"] +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_osfbh"] +sky_material = SubResource("ProceduralSkyMaterial_x2c37") + +[sub_resource type="Environment" id="Environment_2xai3"] +background_mode = 2 +sky = SubResource("Sky_osfbh") +tonemap_mode = 2 +volumetric_fog_density = 0.01 + +[sub_resource type="Gradient" id="Gradient_lm1w0"] +colors = PackedColorArray(0, 0.290196, 0, 1, 0, 0.231373, 0, 1) + +[sub_resource type="FastNoiseLite" id="FastNoiseLite_o8xj6"] +noise_type = 3 +seed = 660 +frequency = 0.006 +fractal_octaves = 2 +fractal_lacunarity = 10.845 + +[sub_resource type="NoiseTexture2D" id="NoiseTexture2D_2pabx"] +width = 256 +height = 256 +seamless = true +seamless_blend_skirt = 0.675 +color_ramp = SubResource("Gradient_lm1w0") +noise = SubResource("FastNoiseLite_o8xj6") + +[sub_resource type="StandardMaterial3D" id="StandardMaterial3D_5w71k"] +diffuse_mode = 3 +specular_mode = 2 +albedo_texture = SubResource("NoiseTexture2D_2pabx") +metallic_specular = 0.0 +uv1_scale = Vector3(5, 6, 1) + +[sub_resource type="PlaneMesh" id="PlaneMesh_6aq33"] +size = Vector2(400, 400) + +[node name="GameScene" type="Node3D"] + +[node name="Track" type="Node3D" parent="." node_paths=PackedStringArray("track_path")] +script = ExtResource("1_eraeg") +track_path = NodePath("Path") +checkpoints = Array[PackedScene]([ExtResource("2_kplf2")]) +checkpoint_frequency_meters = 50 +trees = Array[PackedScene]([ExtResource("4_qwgxh"), ExtResource("5_051ri"), ExtResource("6_w17qq"), ExtResource("7_42mh8"), ExtResource("8_ftc8r")]) +tree_frequency_meters = 6 +rocks = Array[PackedScene]([ExtResource("3_wvqgn"), ExtResource("4_gkjus")]) +rock_frequency_meters = 70 +powerup_scene = Array[PackedScene]([ExtResource("10_g6xuj"), ExtResource("11_rvn62")]) + +[node name="EdgeLine" type="CSGPolygon3D" parent="Track"] +polygon = PackedVector2Array(-4, 0.105, -4, 0.11, -3.8, 0.11, -3.8, 0.105) +mode = 2 +path_node = NodePath("../Path") +path_interval_type = 0 +path_interval = 1.0 +path_simplify_angle = 7.9 +path_rotation = 2 +path_local = false +path_continuous_u = true +path_u_distance = 3.0 +path_joined = true +material = SubResource("StandardMaterial3D_p0ylt") + +[node name="EdgeLine2" type="CSGPolygon3D" parent="Track/EdgeLine"] +polygon = PackedVector2Array(4, 0.105, 4, 0.11, 3.8, 0.11, 3.8, 0.105) +mode = 2 +path_node = NodePath("../../Path") +path_interval_type = 0 +path_interval = 1.0 +path_simplify_angle = 7.9 +path_rotation = 2 +path_local = false +path_continuous_u = true +path_u_distance = 3.0 +path_joined = true +material = SubResource("StandardMaterial3D_p0ylt") + +[node name="Wall" type="CSGPolygon3D" parent="Track"] +polygon = PackedVector2Array(-5.195, 0, -4.75, 0.6, -4.66, 0.6, -4.5, 0.11, -4.5, 0.105) +mode = 2 +path_node = NodePath("../Path") +path_interval_type = 0 +path_interval = 1.0 +path_simplify_angle = 7.9 +path_rotation = 2 +path_local = false +path_continuous_u = true +path_u_distance = 3.0 +path_joined = true +material = SubResource("StandardMaterial3D_s06bd") + +[node name="Wall2" type="CSGPolygon3D" parent="Track/Wall"] +polygon = PackedVector2Array(5.195, 0, 4.75, 0.6, 4.66, 0.6, 4.5, 0.11, 4.5, 0.105) +mode = 2 +path_node = NodePath("../../Path") +path_interval_type = 0 +path_interval = 1.0 +path_simplify_angle = 7.9 +path_rotation = 2 +path_local = false +path_continuous_u = true +path_u_distance = 3.0 +path_joined = true +material = SubResource("StandardMaterial3D_s06bd") + +[node name="WallCollision" type="CSGPolygon3D" parent="Track"] +visible = false +use_collision = true +polygon = PackedVector2Array(-5, 0, -5, 3, -4.5, 3, -4.5, 0.11, -4.5, 0.105) +mode = 2 +path_node = NodePath("../Path") +path_interval_type = 0 +path_interval = 1.0 +path_simplify_angle = 7.9 +path_rotation = 2 +path_local = false +path_continuous_u = true +path_u_distance = 3.0 +path_joined = true + +[node name="WallCollision2" type="CSGPolygon3D" parent="Track/WallCollision"] +polygon = PackedVector2Array(5, 0, 5, 3, 4.5, 3, 4.5, 0.11, 4.5, 0.105) +mode = 2 +path_node = NodePath("../../Path") +path_interval_type = 0 +path_interval = 1.0 +path_simplify_angle = 7.9 +path_rotation = 2 +path_local = false +path_continuous_u = true +path_u_distance = 3.0 +path_joined = true + +[node name="CenterLine" type="CSGPolygon3D" parent="Track"] +polygon = PackedVector2Array(-0.1, 0.105, 0, 0.11, 0, 0.11, 0, 0.105) +mode = 2 +path_node = NodePath("../Path") +path_interval_type = 0 +path_interval = 1.0 +path_simplify_angle = 7.9 +path_rotation = 2 +path_local = false +path_continuous_u = true +path_u_distance = 3.0 +path_joined = true +material = SubResource("StandardMaterial3D_fwfq4") + +[node name="TrackGeometry" type="CSGPolygon3D" parent="Track"] +polygon = PackedVector2Array(-5, 0, -4, 0.1, 4, 0.1, 5, 0) +mode = 2 +path_node = NodePath("../Path") +path_interval_type = 0 +path_interval = 0.1 +path_simplify_angle = 10.0 +path_rotation = 2 +path_local = false +path_continuous_u = false +path_u_distance = 1.0 +path_joined = true +material = SubResource("StandardMaterial3D_7elja") + +[node name="Path" type="Path3D" parent="Track"] +curve = SubResource("Curve3D_5j3hw") + +[node name="house" parent="Track" instance=ExtResource("12_jp4aw")] +transform = Transform3D(-0.965926, 0, 0.258819, 0, 1, 0, -0.258819, 0, -0.965926, -33.182, 0, -25.8549) + +[node name="house3" parent="Track" instance=ExtResource("12_jp4aw")] +transform = Transform3D(-0.965926, 0, 0.258819, 0, 1, 0, -0.258819, 0, -0.965926, 43.8925, 0, -45.1047) + +[node name="house4" parent="Track" instance=ExtResource("12_jp4aw")] +transform = Transform3D(-0.965926, 0, 0.258819, 0, 1, 0, -0.258819, 0, -0.965926, 126.893, 0, -75.1047) + +[node name="windmill" parent="Track" instance=ExtResource("6_djis2")] +transform = Transform3D(-0.965926, 0, 0.258819, 0, 1, 0, -0.258819, 0, -0.965926, 16.3976, 0, -61.7746) + +[node name="house2" parent="Track" instance=ExtResource("14_t13kj")] +transform = Transform3D(-1, 0, 8.74228e-08, 0, 1, 0, -8.74228e-08, 0, -1, 42.6668, 0, -0.215065) + +[node name="house5" parent="Track" instance=ExtResource("14_t13kj")] +transform = Transform3D(1, 0, -2.13163e-14, 0, 1, 0, 2.13163e-14, 0, 1, -100.333, 0, -22.2151) + +[node name="StartingLine" type="CSGBox3D" parent="Track"] +material_override = SubResource("StandardMaterial3D_med5r") +size = Vector3(7.6, 0.22, 0.2) + +[node name="Cars" parent="." node_paths=PackedStringArray("track") instance=ExtResource("16_i65dl")] +track = NodePath("../Track") +number_of_car_groups_to_spawn = 14 + +[node name="Sync" type="Node" parent="."] +script = ExtResource("16_47pia") +onnx_model_path = "model.onnx" + +[node name="DirectionalLight3D" type="DirectionalLight3D" parent="."] +transform = Transform3D(1, 0, 0, 0, 0.707107, 0.707107, 0, -0.707107, 0.707107, 0, 14, 0) +shadow_enabled = true + +[node name="WorldEnvironment" type="WorldEnvironment" parent="."] +environment = SubResource("Environment_2xai3") + +[node name="UI" type="Control" parent="." node_paths=PackedStringArray("current_lap", "get_ready", "winner")] +layout_mode = 3 +anchors_preset = 15 +anchor_right = 1.0 +anchor_bottom = 1.0 +grow_horizontal = 2 +grow_vertical = 2 +script = ExtResource("17_1xllr") +current_lap = NodePath("CurrentLap") +get_ready = NodePath("VBoxContainer/GetReady") +winner = NodePath("VBoxContainer/Winner") + +[node name="VBoxContainer" type="VBoxContainer" parent="UI"] +layout_mode = 1 +anchors_preset = 5 +anchor_left = 0.5 +anchor_right = 0.5 +offset_left = -174.5 +offset_top = 100.0 +offset_right = 174.5 +offset_bottom = 189.0 +grow_horizontal = 2 + +[node name="Winner" type="Label" parent="UI/VBoxContainer"] +visible = false +custom_minimum_size = Vector2(0, 50) +layout_mode = 2 +theme_override_colors/font_color = Color(1, 1, 0, 1) +theme_override_colors/font_outline_color = Color(0, 0, 0, 1) +theme_override_constants/outline_size = 20 +theme_override_font_sizes/font_size = 25 +text = "The winner is ..." +horizontal_alignment = 1 +uppercase = true +metadata/_edit_use_anchors_ = true + +[node name="GetReady" type="Label" parent="UI/VBoxContainer"] +visible = false +layout_mode = 2 +theme_override_colors/font_outline_color = Color(0, 0, 0, 1) +theme_override_constants/outline_size = 20 +theme_override_font_sizes/font_size = 25 +text = "Get ready! Race starting in ..." +horizontal_alignment = 1 +metadata/_edit_use_anchors_ = true + +[node name="CurrentLap" type="Label" parent="UI"] +visible = false +layout_mode = 1 +anchors_preset = -1 +offset_left = 20.0 +offset_top = 20.0 +offset_right = 231.0 +offset_bottom = 23.0 +theme_override_colors/font_color = Color(1, 1, 0, 1) +theme_override_colors/font_outline_color = Color(0, 0, 0, 1) +theme_override_constants/outline_size = 10 +theme_override_font_sizes/font_size = 25 +text = "Lap: 0/0" + +[node name="Ground" type="MeshInstance3D" parent="."] +material_override = SubResource("StandardMaterial3D_5w71k") +mesh = SubResource("PlaneMesh_6aq33") + +[editable path="Cars"] diff --git a/scenes/main_scene/main_scene.tscn b/scenes/main_scene/main_scene.tscn new file mode 100644 index 0000000000000000000000000000000000000000..91fe4097790dad020c088e2d35fda3fc22e320f6 --- /dev/null +++ b/scenes/main_scene/main_scene.tscn @@ -0,0 +1,11 @@ +[gd_scene load_steps=3 format=3 uid="uid://7oe2m3pdd0sr"] + +[ext_resource type="Script" path="res://scenes/game_scene/game_manager.gd" id="1_akdmg"] +[ext_resource type="PackedScene" uid="uid://dqb4x6b4gfiq3" path="res://scenes/game_scene/game_scene.tscn" id="2_wgm2p"] + +[node name="GameManager" type="Node3D"] +script = ExtResource("1_akdmg") +game_mode = 2 +game_scene = ExtResource("2_wgm2p") +total_laps = 3 +seconds_until_race_begins = 3 diff --git a/scenes/track/checkpoint.tscn b/scenes/track/checkpoint.tscn new file mode 100644 index 0000000000000000000000000000000000000000..07438ad41b83e203cbe8a26b57ca779695c4db4b --- /dev/null +++ b/scenes/track/checkpoint.tscn @@ -0,0 +1,22 @@ +[gd_scene load_steps=2 format=3 uid="uid://btq75ag6rkb8w"] + +[sub_resource type="StandardMaterial3D" id="StandardMaterial3D_hgr52"] +albedo_color = Color(0.968627, 0.811765, 0.105882, 1) +roughness = 0.9 + +[node name="Node3D" type="Node3D"] + +[node name="CSGBox3D" type="CSGBox3D" parent="."] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 6, 1.5, 0) +size = Vector3(1, 4, 1) +material = SubResource("StandardMaterial3D_hgr52") + +[node name="CSGBox3D2" type="CSGBox3D" parent="."] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -6, 1.5, 0) +size = Vector3(1, 4, 1) +material = SubResource("StandardMaterial3D_hgr52") + +[node name="CSGBox3D3" type="CSGBox3D" parent="."] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 4, 0) +size = Vector3(13, 1, 1) +material = SubResource("StandardMaterial3D_hgr52") diff --git a/scenes/track/powerup.gd b/scenes/track/powerup.gd new file mode 100644 index 0000000000000000000000000000000000000000..471ff34eb6cea376f69fb2887f8d199ecf7bb71d --- /dev/null +++ b/scenes/track/powerup.gd @@ -0,0 +1,19 @@ +extends Area3D +class_name Powerup + +## Direction of impulse that the powerup adds, +## e.g. Vector3(0, 0, -1) would add a forward impulse to the powerup +@export var impulse_direction_relative_to_powerup: Vector3 = Vector3(0.0, 0.0, 1.0) +@export var impulse_to_apply: float = 15 + +## Used for observations, one hot encoded category, array size should match on all powerups +@export var category_as_array_one_hot_encoded: Array[int] = [0, 1] + +@export var ai_controller_reward := 0.0 + + +func _on_body_entered(body): + var car = body as Car + if car: + car.apply_central_impulse(global_transform.basis * impulse_direction_relative_to_powerup * impulse_to_apply) + car.ai_controller.reward += ai_controller_reward diff --git a/scenes/track/reverse_turbo_powerup.tscn b/scenes/track/reverse_turbo_powerup.tscn new file mode 100644 index 0000000000000000000000000000000000000000..69bc1b1fbec67aaeafaadee99c827bf29d4246ac --- /dev/null +++ b/scenes/track/reverse_turbo_powerup.tscn @@ -0,0 +1,23 @@ +[gd_scene load_steps=4 format=3 uid="uid://c8wjel5fyyfgg"] + +[ext_resource type="Script" path="res://scenes/track/powerup.gd" id="1_brunt"] +[ext_resource type="PackedScene" uid="uid://ckqcpkmd1jrjj" path="res://scenes/blender/reverse-turbo-powerup.blend" id="2_uedjs"] + +[sub_resource type="BoxShape3D" id="BoxShape3D_mkppf"] +size = Vector3(1.209, 0.632, 2.432) + +[node name="ReverseTurboPowerup" type="Area3D"] +collision_layer = 0 +collision_mask = 4294967295 +monitorable = false +script = ExtResource("1_brunt") +impulse_to_apply = -18.0 +category_as_array_one_hot_encoded = Array[int]([1, 0]) + +[node name="CollisionShape3D" type="CollisionShape3D" parent="."] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0.277, 0) +shape = SubResource("BoxShape3D_mkppf") + +[node name="reverse-turbo-powerup" parent="." instance=ExtResource("2_uedjs")] + +[connection signal="body_entered" from="." to="." method="_on_body_entered"] diff --git a/scenes/track/rotor.gd b/scenes/track/rotor.gd new file mode 100644 index 0000000000000000000000000000000000000000..24cd48fe4510ce6bc7aca2727721b737c5475088 --- /dev/null +++ b/scenes/track/rotor.gd @@ -0,0 +1,5 @@ +extends MeshInstance3D + +func _physics_process(delta): + rotation.x += delta + pass diff --git a/scenes/track/track.gd b/scenes/track/track.gd new file mode 100644 index 0000000000000000000000000000000000000000..740d92f8e0a6d4eedf260ea12f309881d1a17d9d --- /dev/null +++ b/scenes/track/track.gd @@ -0,0 +1,106 @@ +extends Node3D +class_name Track + +@export var track_path: Path3D + +@export_group("Checkpoint objects to add to the track:") +@export var checkpoints: Array[PackedScene] +@export var checkpoint_frequency_meters: int + +@export_group("Tree objects to add to the track:") +@export var trees: Array[PackedScene] +@export var tree_frequency_meters: int + +@export_group("Rock objects to add to the track:") +@export var rocks: Array[PackedScene] +@export var rock_frequency_meters: int + +@export_group("Powerup objects to add to the track:") +@export var powerup_scene: Array[PackedScene] + +var powerups: Array[Powerup] + +## Training mode disables generating decoration objects +var training_mode: bool = false + +var _random: RandomNumberGenerator = RandomNumberGenerator.new() + +@onready var starting_line = $StartingLine + +# Called when the node enters the scene tree for the first time. +func _ready(): + _random.seed = 10 + instantiate_powerups_on_track() + starting_line.global_transform = get_starting_position() + + if not training_mode: + instantiate_scene_instances_on_track(checkpoints, checkpoint_frequency_meters) + instantiate_scene_instances_on_track(trees, tree_frequency_meters, true, true) + instantiate_scene_instances_on_track(rocks, rock_frequency_meters, true, true) + + +func get_starting_position() -> Transform3D: + return track_path.curve.sample_baked_with_rotation(0.0) + + +func instantiate_scene_instances_on_track( + scene: Array[PackedScene], + frequency_meters: int, + randomize_instances_outside_track: bool = false, + randomize_rotation: bool = false +): + for offset in range(frequency_meters, track_path.curve.get_baked_length(), frequency_meters): + var instance: Node3D = scene[_random.randi_range(0, scene.size() - 1)].instantiate() + add_child(instance) + instance.global_transform = track_path.curve.sample_baked_with_rotation(offset) + if randomize_instances_outside_track: + var direction: int = 1 if _random.randi_range(0, 1) == 0 else -1 + var z_random_range = frequency_meters / 25.0 + var x_min_distance = 15.0 + var x_random_distance_max_offset = 5.0 + instance.global_transform.origin += ( + (instance.global_basis.z * _random.randf_range(-z_random_range, z_random_range)) + + ( + instance.global_basis.x + * direction + * (x_min_distance + _random.randf_range(0, x_random_distance_max_offset)) + ) + ) + if randomize_rotation: + instance.rotate_y(_random.randf_range(-PI, PI)) + + +func instantiate_powerups_on_track(): + var min_powerup_distance := 40.0 + + var powerup_offsets: Array[float] = [] + for offset in range( + min_powerup_distance, track_path.curve.get_baked_length(), min_powerup_distance + ): + powerup_offsets.append(offset) + + # Randomly remove some powerups + for i in range(0, (powerup_offsets.size() / 2.0)): + powerup_offsets.remove_at(_random.randi_range(0, powerup_offsets.size() - 1)) + + for offset in powerup_offsets: + # Place a random powerup + var instance: Powerup = ( + powerup_scene[_random.randi_range(0, powerup_scene.size() - 1)].instantiate() + ) + add_child(instance) + instance.global_transform = track_path.curve.sample_baked_with_rotation(offset) + var random_direction = 1 if _random.randi_range(0, 1) == 0 else -1 + instance.global_transform.origin += instance.basis.x * random_direction * 1.25 + powerups.append(instance) + + +func get_closest_powerup(from_global_position: Vector3) -> Powerup: + var smallest_distance = INF + var closest_powerup: Powerup + for powerup in powerups: + var distance = powerup.global_position.distance_to(from_global_position) + if distance < smallest_distance: + smallest_distance = distance + closest_powerup = powerup + return closest_powerup diff --git a/scenes/track/turbo_powerup.tscn b/scenes/track/turbo_powerup.tscn new file mode 100644 index 0000000000000000000000000000000000000000..1ac7f3babf65d514db6d1aba6f14b7f1e22c3104 --- /dev/null +++ b/scenes/track/turbo_powerup.tscn @@ -0,0 +1,23 @@ +[gd_scene load_steps=4 format=3 uid="uid://c4uwdcusug3ux"] + +[ext_resource type="PackedScene" uid="uid://dqguh82c6ny4c" path="res://scenes/blender/turbo-powerup.blend" id="1_oksqt"] +[ext_resource type="Script" path="res://scenes/track/powerup.gd" id="1_vgk4v"] + +[sub_resource type="BoxShape3D" id="BoxShape3D_4ka6o"] +size = Vector3(1.209, 0.632, 2.432) + +[node name="TurboPowerup" type="Area3D"] +collision_layer = 0 +collision_mask = 4294967295 +monitorable = false +script = ExtResource("1_vgk4v") +impulse_direction_relative_to_powerup = Vector3(0, 0, -1) +impulse_to_apply = 18.0 + +[node name="turbo-powerup" parent="." instance=ExtResource("1_oksqt")] + +[node name="CollisionShape3D" type="CollisionShape3D" parent="."] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0.277, 0) +shape = SubResource("BoxShape3D_4ka6o") + +[connection signal="body_entered" from="." to="." method="_on_body_entered"] diff --git a/scenes/track/windmill.tscn b/scenes/track/windmill.tscn new file mode 100644 index 0000000000000000000000000000000000000000..01f3a86df028ced22fd412ae9f16756ed91cf43f --- /dev/null +++ b/scenes/track/windmill.tscn @@ -0,0 +1,13 @@ +[gd_scene load_steps=3 format=3 uid="uid://c1oi504d42b6j"] + +[ext_resource type="PackedScene" uid="uid://smkg3gt56rxx" path="res://scenes/blender/windmill.blend" id="1_j8xwd"] +[ext_resource type="Script" path="res://scenes/track/rotor.gd" id="2_ejtw2"] + +[node name="windmill" type="Node3D"] + +[node name="windmill" parent="." instance=ExtResource("1_j8xwd")] + +[node name="rotor" parent="windmill" index="1"] +script = ExtResource("2_ejtw2") + +[editable path="windmill"]