Compare commits

...

8 Commits

Author SHA1 Message Date
Jonathan 628da80ed3 Merge pull request 'feature/entity_rework' (#52) from feature/entity_rework into develop
2 months ago
Katharina Ziolkowski 0dfbd73978 Reverted ItemOnGround to make everything compile again
2 months ago
Katharina Ziolkowski 8a93b00e72 Merge branch 'develop' into feature/entity_rework
2 months ago
Katharina Ziolkowski ba7d550c3f Implemented Save and Load functionality
2 months ago
Katharina Ziolkowski b65a3bbd6d Managed the freeing of entityplacers. Also cleaned up EntityManager
2 months ago
Katharina Ziolkowski bcbc074c86 First adjustments to the Entity System to make it work with different types
2 months ago
jonathan 745f54b375 WIP
2 months ago
jonathan 59d313d97d Added basic entity scripts
4 months ago

@ -8,4 +8,7 @@
<Folder Include="prefabs\UI\Inventory\" />
<Folder Include="scripts\CSharp\Low Code\Randomizer\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.4" />
</ItemGroup>
</Project>

@ -4,19 +4,22 @@ importer="scene"
importer_version=1
type="PackedScene"
uid="uid://b3kyrsoobmkhp"
valid=false
path="res://.godot/imported/best_house_blender.blend-ac89c74aef2f275bdf4b4baadee17c0c.scn"
[deps]
source_file="res://art/mockups/3d/best_house_blender.blend"
dest_files=["res://.godot/imported/best_house_blender.blend-ac89c74aef2f275bdf4b4baadee17c0c.scn"]
[params]
nodes/root_type=""
nodes/root_name=""
nodes/root_script=null
nodes/apply_root_scale=true
nodes/root_scale=1.0
nodes/import_as_skeleton_bones=false
nodes/use_name_suffixes=true
nodes/use_node_type_suffixes=true
meshes/ensure_tangents=true
meshes/generate_lods=true
@ -31,6 +34,9 @@ animation/trimming=false
animation/remove_immutable_tracks=true
animation/import_rest_as_RESET=false
import_script/path=""
materials/extract=0
materials/extract_format=0
materials/extract_path=""
_subresources={}
blender/nodes/visible=0
blender/nodes/active_collection_only=false
@ -50,3 +56,4 @@ blender/materials/export_materials=1
blender/animation/limit_playback=true
blender/animation/always_sample=true
blender/animation/group_tracks=true
gltf/naming_version=0

@ -0,0 +1,15 @@
[gd_scene load_steps=4 format=3 uid="uid://hdfejdnmp8sl"]
[ext_resource type="Script" uid="uid://umop2b1m1qm8" path="res://scripts/CSharp/GameEntity/Management/EntityManager.cs" id="1_2bwns"]
[ext_resource type="Script" uid="uid://bogqp274y1pgr" path="res://scripts/CSharp/GameEntity/Management/EntityNodeCreator.cs" id="2_8m173"]
[ext_resource type="PackedScene" uid="uid://sbf12hin4kes" path="res://prefabs/Interactables/trash_object.tscn" id="3_v3vdc"]
[node name="EntityManager" type="Node" node_paths=PackedStringArray("_nodeCreator")]
script = ExtResource("1_2bwns")
_nodeCreator = NodePath("EntityCreator")
[node name="EntityCreator" type="Node" parent="."]
script = ExtResource("2_8m173")
_entityPrefabs = Dictionary[String, PackedScene]({
"TrashEntity": ExtResource("3_v3vdc")
})

@ -35,6 +35,7 @@ FightWorldAutoload="*res://prefabs/fight/fight_world_autoload.tscn"
SaveGameManager="*res://scripts/CSharp/Common/Savegame/SaveGameManager.cs"
SettingsSaveController="*res://scripts/CSharp/Common/Savegame/SettingsSaveController.cs"
DayAndNight="*res://prefabs/day_and_night/day_and_night.tscn"
EntityManager="*res://prefabs/entity_system/entity_manager.tscn"
[dialogic]
@ -224,6 +225,10 @@ folder_colors={
"res://shader/": "pink"
}
[filesystem]
import/blender/enabled=false
[global_group]
Saveable=""
@ -310,6 +315,16 @@ NextDayCheat={
"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":32,"key_label":0,"unicode":32,"location":0,"echo":false,"script":null)
]
}
DebugEntities={
"deadzone": 0.2,
"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":66,"key_label":0,"unicode":98,"location":0,"echo":false,"script":null)
]
}
SaveGame={
"deadzone": 0.2,
"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":4194336,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null)
]
}
[internationalization]

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

@ -1,10 +1,13 @@
using Babushka.scripts.CSharp.GameEntity.LoadSave;
using Godot;
using Newtonsoft.Json.Linq;
namespace Babushka.scripts.CSharp.Common.Inventory;
// Do not instantiate this resource
// But it has to be a resource because Godot
[GlobalClass]
public partial class ItemInstance: Resource
public partial class ItemInstance : Resource, IJsonSerializable
{
[Export] public required ItemResource blueprint;
[Export] public int amount = 1;
@ -17,4 +20,18 @@ public partial class ItemInstance: Resource
amount = amount
};
}
}
public void LoadFromJson(JObject json)
{
var blueprintPath = json.GetStringValue("blueprint");
blueprint = GD.Load<ItemResource>(blueprintPath);
amount = json.GetIntValue("amount");
}
public JObject SaveToJson()
{
return new(
new JProperty("blueprint", blueprint.ResourcePath),
new JProperty("amount", amount));
}
}

@ -1,4 +1,6 @@
using Godot;
using Babushka.scripts.CSharp.GameEntity.LoadSave;
using Godot;
using Newtonsoft.Json.Linq;
namespace Babushka.scripts.CSharp.Common.Inventory;

@ -0,0 +1,27 @@
using System;
using Babushka.scripts.CSharp.GameEntity.LoadSave;
using Newtonsoft.Json.Linq;
namespace Babushka.scripts.CSharp.GameEntity.Entities;
public class Entity
{
public long id;
public virtual string EntityType => "";
public Entity()
{
id = new Random().NextInt64();
}
public virtual void SaveEntity(JObject json)
{
json["id"] = id;
json["type"] = EntityType;
}
public virtual void LoadEntity(JObject json)
{
id = json.GetLongValue("id");
}
}

@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using Newtonsoft.Json.Linq;
namespace Babushka.scripts.CSharp.GameEntity.Entities;
public class LoadedScenesEntity : Entity
{
private HashSet<string> _loadedScenes = new();
public override string EntityType => OWN_TYPE_NAME;
public const string OWN_TYPE_NAME = "LoadedScenesEntity";
public void AddScene(string sceneName) => _loadedScenes.Add(sceneName);
public bool WasSceneLoaded(string sceneName) => _loadedScenes.Contains(sceneName);
public override void SaveEntity(JObject json)
{
base.SaveEntity(json);
json["scenes"] = new JArray(_loadedScenes);
}
public override void LoadEntity(JObject json)
{
base.LoadEntity(json);
JArray array = (JArray?) json["scenes"] ?? throw new Exception("No scenes found in LoadedScenesEntity.");
_loadedScenes = array.ToObject<HashSet<string>>()!;
}
}

@ -0,0 +1,32 @@
using Babushka.scripts.CSharp.GameEntity.LoadSave;
using Godot;
using Newtonsoft.Json.Linq;
namespace Babushka.scripts.CSharp.GameEntity.Entities;
public abstract class PositionalEntity : Entity
{
public Vector2 position;
public string sceneName = "none";
public override void SaveEntity(JObject json)
{
base.SaveEntity(json);
json["posx"] = position.X;
json["posy"] = position.Y;
json["scene"] = sceneName;
}
public override void LoadEntity(JObject json)
{
base.LoadEntity(json);
position = new Vector2(
json.GetFloatValue("posx"),
json.GetFloatValue("posy"));
sceneName = json.GetStringValue("scene");
}
// Deals with Instantiation of the node
public abstract void InstantiateEntityNode(Node2D parent);
}

@ -0,0 +1,23 @@
using Babushka.scripts.CSharp.GameEntity.Management;
using Godot;
namespace Babushka.scripts.CSharp.GameEntity.Entities;
public class TrashEntity : PositionalEntity
{
public override string EntityType => OWN_TYPE_NAME;
public const string OWN_TYPE_NAME = "TrashEntity";
private EntityNodeCreator _creator;
public TrashEntity()
{
}
public override void InstantiateEntityNode(Node2D parent)
{
if(_creator == null) _creator = EntityManager.Instance.NodeCreator;
var entityNode = _creator.InstantiateNode(EntityType);
parent.AddChild(entityNode);
entityNode.GlobalPosition = position;
}
}

@ -0,0 +1,16 @@
using Babushka.scripts.CSharp.GameEntity.Entities;
using Godot;
namespace Babushka.scripts.CSharp.GameEntity.EntityNodes;
public partial class TrashEntityNode : Node2D
{
private TrashEntity _trashEntity;
public void Initialize(TrashEntity trashEntity)
{
_trashEntity = trashEntity;
}
}

@ -0,0 +1,26 @@
using Babushka.scripts.CSharp.GameEntity.Entities;
using Babushka.scripts.CSharp.GameEntity.Management;
using Godot;
namespace Babushka.scripts.CSharp.GameEntity.EntityPlacer;
public partial class TrashEntityPlacer : Node2D
{
private string _trashEntityType = TrashEntity.OWN_TYPE_NAME;
public override void _Ready()
{
string sceneName = EntityManager.Instance.CurrentEntitySceneContainer!.sceneName;
var loadedScenesEntity = EntityManager.Instance.GetUniqueEntity<LoadedScenesEntity>();
if (!loadedScenesEntity.WasSceneLoaded(sceneName))
{
TrashEntity entity = new TrashEntity();
entity.sceneName = sceneName;
entity.position = GlobalPosition;
EntityManager.Instance.AddEntity(entity);
}
QueueFree();
}
}

@ -0,0 +1,44 @@
using Newtonsoft.Json.Linq;
namespace Babushka.scripts.CSharp.GameEntity.LoadSave;
public static class EntityLoadSaveUtil
{
private static void AssertTokenType(this JObject json, string key, JTokenType type)
{
var token = json[key];
if (token == null) throw new MalformedJsonException(json, key, "does not exist");
//if (!token.HasValues) throw new MalformedJsonException(json, key, "has no value");
if (token.Type != type) throw new MalformedJsonException(json, key, $"is not of type {type}");
}
public static long GetLongValue(this JObject json, string key)
{
AssertTokenType(json, key, JTokenType.Integer);
return json.Value<long>(key);
}
public static int GetIntValue(this JObject json, string key)
{
AssertTokenType(json, key, JTokenType.Integer);
return json.Value<int>(key);
}
public static float GetFloatValue(this JObject json, string key)
{
AssertTokenType(json, key, JTokenType.Float);
return json.Value<float>(key);
}
public static JObject GetObject(this JObject json, string key)
{
AssertTokenType(json, key, JTokenType.Object);
return json.Value<JObject>(key)!;
}
public static string GetStringValue(this JObject json, string key)
{
AssertTokenType(json, key, JTokenType.String);
return json.Value<string>(key)!;
}
}

@ -0,0 +1,9 @@
using Newtonsoft.Json.Linq;
namespace Babushka.scripts.CSharp.GameEntity.LoadSave;
public interface IJsonSerializable
{
public void LoadFromJson(JObject json);
public JObject SaveToJson();
}

@ -0,0 +1,12 @@
using System;
using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
namespace Babushka.scripts.CSharp.GameEntity.LoadSave;
public class MalformedJsonException(JObject actualJson, string key, string problem) : Exception
{
public override string Message => $"JsonObject was malformed: {key} {problem}";
public override IDictionary Data => new Dictionary<string, JObject> { { "json", actualJson } };
}

@ -0,0 +1,157 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Babushka.scripts.CSharp.GameEntity.Entities;
using Godot;
using Newtonsoft.Json.Linq;
using Entity = Babushka.scripts.CSharp.GameEntity.Entities.Entity;
using PositionalEntity = Babushka.scripts.CSharp.GameEntity.Entities.PositionalEntity;
namespace Babushka.scripts.CSharp.GameEntity.Management;
/// <summary>
/// Manages the lifecycle and interactions of all entities within the game, including their creation, retrieval,
/// and organization. The EntityManager serves as a centralized hub for managing both standard and positional entities.
/// </summary>
public partial class EntityManager : Node
{
public static EntityManager Instance;
[Export] private EntityNodeCreator _nodeCreator = null!;
[Export] private string saveDirectory = "user://save_data/";
private EntitySceneContainer? _currentEntitySceneContainer;
private readonly List<Entity> _allEntities = new();
public IEnumerable<Entity> AllEntities => _allEntities;
public IEnumerable<PositionalEntity> AllPositionalEntities => _allEntities.OfType<PositionalEntity>();
public EntitySceneContainer? CurrentEntitySceneContainer => _currentEntitySceneContainer;
public EntityNodeCreator NodeCreator => _nodeCreator;
public override void _EnterTree()
{
Instance = this;
Load();
}
public override void _Input(InputEvent @event)
{
// for debugging purposes
if (@event.IsActionPressed("DebugEntities"))
{
GD.Print("Entities:");
foreach (var entity in AllEntities)
{
GD.Print(entity.EntityType + " " + entity.id);
}
}
if(@event.IsActionPressed("SaveGame")) Save();
}
public void Save()
{
JArray array = new JArray();
foreach (var entity in AllEntities)
{
JObject saveData = new JObject();
entity.SaveEntity(saveData);
array.Add(saveData);
}
using var SaveFile = FileAccess.Open(saveDirectory + "save.json", FileAccess.ModeFlags.Write);
SaveFile.StoreString(array.ToString());
}
public void Load()
{
using var saveFile = FileAccess.Open(saveDirectory + "save.json", FileAccess.ModeFlags.Read);
if (saveFile == null) return;
JArray array = JArray.Parse(saveFile.GetAsText());
foreach (var token in array)
{
var jobj = (JObject)token;
if (jobj == null) continue;
if (jobj.TryGetValue("type", out var entityType))
{
string entityTypeString = (string) entityType!;
Entity entity = InitializeEntity(entityTypeString);
entity.LoadEntity(jobj);
AddEntity(entity);
}
}
}
private Entity InitializeEntity(string type)
{
Entity entity = type switch
{
TrashEntity.OWN_TYPE_NAME => new TrashEntity(),
LoadedScenesEntity.OWN_TYPE_NAME => new LoadedScenesEntity(),
_ => throw new Exception($"Trying to load unknown entity type: {type}")
};
return entity;
}
#region ENTITY MANAGEMENT
/// <summary>
/// Adds an entity to the list of managed entities. If the entity is a positional entity
/// and its scene matches the current scene container, it is also instantiated in the scene.
/// </summary>
/// <param name="entity">The entity to be added to the manager.</param>
public void AddEntity(Entity entity)
{
if (!_allEntities.Contains(entity))
_allEntities.Add(entity);
if(entity is PositionalEntity positionalEntity && positionalEntity.sceneName == _currentEntitySceneContainer?.sceneName)
InstantiatePositionalEntityNode(positionalEntity);
}
private void InstantiatePositionalEntityNode(PositionalEntity entity)
{
if(_currentEntitySceneContainer == null) return;
entity.InstantiateEntityNode(_currentEntitySceneContainer);
}
/// <summary>
/// Retrieves the first entity of the specified type from the list of managed entities.
/// If no such entity exists, creates a new instance of the specified type, adds it to the manager, and returns it.
/// </summary>
/// <typeparam name="T">The type of entity to retrieve or create. Must inherit from the Entity class and have a parameterless constructor.</typeparam>
/// <returns>The first entity of the specified type or a newly created entity of that type if none were found.</returns>
public T GetUniqueEntity<T>() where T : Entity, new()
{
var result = AllEntities.OfType<T>().FirstOrDefault();
if (result == null)
{
var newEntity = new T();
AddEntity(newEntity);
result = newEntity;
}
return result;
}
#endregion
#region SCENE CONTAINER ACCESS
public void SetSceneContainer(EntitySceneContainer sceneContainer)
{
_currentEntitySceneContainer = sceneContainer;
}
public void UnsetSceneContainer()
{
_currentEntitySceneContainer = null;
}
#endregion
}

@ -0,0 +1,14 @@
using PositionalEntity = Babushka.scripts.CSharp.GameEntity.Entities.PositionalEntity;
namespace Babushka.scripts.CSharp.GameEntity.Management;
public static class EntityManagerUtil
{
public static void AddIfNeeded(this EntitySceneContainer? self, PositionalEntity entity)
{
if(self == null) return;
if(self.sceneName != entity.sceneName) return;
self.AddEntity(entity);
}
}

@ -0,0 +1,25 @@
using System;
using Godot;
using Godot.Collections;
namespace Babushka.scripts.CSharp.GameEntity.Management;
public partial class EntityNodeCreator : Node
{
[Export] private Dictionary<string, PackedScene> _entityPrefabs;
public Node2D InstantiateNode(string type)
{
if (string.IsNullOrEmpty(type))
{
throw new NullReferenceException("The type provided for Node instantiation cannot be null or empty.");
}
if (!_entityPrefabs.ContainsKey(type))
{
throw new Exception($"The type provided for Node instantiation ({type}) is not specified in the EntityNodeCreator dictionary.");
}
return _entityPrefabs[type].Instantiate<Node2D>();
}
}

@ -0,0 +1,48 @@
using System.Linq;
using Babushka.scripts.CSharp.GameEntity.Entities;
using Godot;
using PositionalEntity = Babushka.scripts.CSharp.GameEntity.Entities.PositionalEntity;
namespace Babushka.scripts.CSharp.GameEntity.Management;
public partial class EntitySceneContainer : Node2D
{
[Export] public string sceneName = "none";
public override void _EnterTree()
{
EntityManager.Instance.SetSceneContainer(this);
}
public override void _ExitTree()
{
EntityManager.Instance.Save();
EntityManager.Instance.UnsetSceneContainer();
}
public override void _Ready()
{
AddAllEntities();
CallDeferred(nameof(RegisterWithScenesEntity));
}
private void RegisterWithScenesEntity()
{
var loadedScenesEntity = EntityManager.Instance.GetUniqueEntity<LoadedScenesEntity>();
loadedScenesEntity.AddScene(sceneName);
}
public void AddAllEntities()
{
foreach (var positionalEntity in EntityManager.Instance.AllPositionalEntities.Where(x => x.sceneName == sceneName))
{
AddEntity(positionalEntity);
}
}
public void AddEntity(PositionalEntity entity)
{
entity.InstantiateEntityNode(this);
}
}

@ -12,6 +12,9 @@ uniform float brightness_add : hint_range(-1.0, 1.0) = 0.0;
// Contrast multiplier in RGB space. 1.0 means no change.
uniform float contrast_mult : hint_range(0.0, 2.0) = 1.0;
//Cached Color value to reapply modulate
varying vec4 modulate;
// Converts an RGB color to HSV.
vec3 rgb2hsv(vec3 c) {
float cMax = max(max(c.r, c.g), c.b);
@ -65,6 +68,10 @@ vec3 hsv2rgb(vec3 c) {
return rgb + vec3(m);
}
void vertex(){
modulate = COLOR;
}
void fragment() {
// Get the original texture color.
vec4 tex_color = texture(TEXTURE, UV);
@ -89,4 +96,6 @@ void fragment() {
// Output the final color while preserving the original alpha.
COLOR = vec4(col, tex_color.a);
//reapply vertex color value to keep modulate changes
COLOR = COLOR * modulate;
}

@ -2,8 +2,14 @@ shader_type canvas_item;
uniform vec2 tiling_scale = vec2(5.0, 5.0);
uniform sampler2D noise : repeat_enable;
varying vec4 modulate;
void vertex() {
modulate = COLOR;
}
void fragment() {
vec2 uv = vec2(UV.x * tiling_scale.x, UV.y * tiling_scale.y); // Change 10.0 to control tiling scale
COLOR = texture(TEXTURE, fract(uv));
COLOR = COLOR * modulate;
}

@ -26,6 +26,9 @@ uniform float heightOffset : hint_range(0.0, 1.0);
// With the offset value, you can if you want different moves for each asset. Just put a random value (1, 2, 3) in the editor. Don't forget to mark the material as unique if you use this
uniform float offset = 0;
// caching color settings to reapply modulate value
varying vec4 modulate;
float getWind(vec2 vertex, vec2 uv, float time){
float diff = pow(maxStrength - minStrength, 2.0);
float strength = clamp(minStrength + diff + sin(time / interval) * diff, minStrength, maxStrength) * strengthScale;
@ -47,8 +50,13 @@ float noise(vec2 x) {
}
void vertex() {
modulate = COLOR;
vec4 pos = MODEL_MATRIX * vec4(0.0, 0.0, 0.0, 1.0);
//float time = TIME * speed + sin(VERTEX.x * noise(VERTEX.xy) * offset);
float time = TIME * speed + sin(pos.x * offset) * cos( pos.x * offset) ;
VERTEX.x += getWind(VERTEX.xy, UV, time);
}
void fragment() {
COLOR = modulate * COLOR;
}
Loading…
Cancel
Save