Skip to content

a lot of changes fixed a lot of bug fixes and added a lot of todo's and many more #389

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 15 commits into
base: dev
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System.Numerics;
using System.Numerics;
using Walgelijk;
using Walgelijk.AssetManager;
using Walgelijk.Physics;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System;
using System;
using System.Numerics;
using System.Runtime.CompilerServices;
using Walgelijk;
Expand Down Expand Up @@ -73,12 +73,6 @@ public override void Update()
Utilities.NanFallback(Input.WorldMousePosition) :
(character.Positioning.Head.GlobalPosition + new Vector2(character.Positioning.FlipScaling * 10000, 0));

//if (equipped != null && equipped.Data.WeaponType is WeaponType.Firearm)
//{
// var th = float.Atan2(character.AimDirection.Y, character.AimDirection.X) * character.Positioning.fli;
// character.AimTargetPosition += Vector2.TransformNormal(new Vector2(0, equipped.BarrelEndPoint.Y), Matrix3x2.CreateRotation(th));
//}

character.RelativeAimTargetPosition = character.AimTargetPosition - character.AimOrigin;
}
else
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using MIR.LevelEditor.Objects;
using MIR.LevelEditor.Objects;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using MIR.LevelEditor.Objects;
using MIR.LevelEditor.Objects;
using System;
using System.Collections.Generic;
using System.Linq;
Expand All @@ -14,19 +14,72 @@ namespace MIR;
public class EnemySpawningSystem : Walgelijk.System
{
private readonly List<Routine> routines = [];
private readonly HashSet<Entity> liveEnemies = new();
private int cachedEnemyCount = 0;

public override void OnActivate()
{
// Force initial count
_ = GetLiveEnemyCount();
}

public override void OnDeactivate()
{
foreach (var r in routines)
RoutineScheduler.Stop(r);

routines.Clear();
liveEnemies.Clear();
cachedEnemyCount = 0;
}

private void UpdateEnemyStatus(Entity entity, CharacterComponent character)
{
if (!MadnessUtils.FindPlayer(Scene, out _, out var player))
{
// No player found, clear everything
if (liveEnemies.Count > 0)
{
liveEnemies.Clear();
cachedEnemyCount = 0;
}
return;
}

bool isEnemy = character.IsAlive
&& !Scene.HasTag(entity, Tags.Player)
&& character.Faction.IsEnemiesWith(player.Faction);

bool wasEnemy = liveEnemies.Contains(entity);

if (isEnemy && !wasEnemy)
{
liveEnemies.Add(entity);
cachedEnemyCount++;
}
else if (!isEnemy && wasEnemy)
{
liveEnemies.Remove(entity);
cachedEnemyCount--;
}
}

public override void Update()
{
if (MadnessUtils.IsPaused(Scene) || MadnessUtils.EditingInExperimentMode(Scene) || MadnessUtils.IsCutscenePlaying(Scene))
return;

// Check for character state changes
foreach (var character in Scene.GetAllComponentsOfType<CharacterComponent>())
{
bool isCurrentlyEnemy = liveEnemies.Contains(character.Entity);
if (character.IsAlive != isCurrentlyEnemy)
{
// Character state changed (died or revived)
UpdateEnemyStatus(character.Entity, character);
}
}

if (!Scene.FindAnyComponent<EnemySpawningComponent>(out var spawningComponent) || !spawningComponent.Enabled)
return;

Expand Down Expand Up @@ -120,12 +173,21 @@ private int GetLiveEnemyCount()
if (!MadnessUtils.FindPlayer(Scene, out _, out var player))
return 0;

// TODO improve speed
return Scene.GetAllComponentsOfType<CharacterComponent>().Count(c =>
c.IsAlive
&& !Scene.HasTag(c.Entity, Tags.Player)
&& c.Faction.IsEnemiesWith(player.Faction)
);
// Perform full recount
liveEnemies.Clear();

foreach (var character in Scene.GetAllComponentsOfType<CharacterComponent>())
{
if (character.IsAlive
&& !Scene.HasTag(character.Entity, Tags.Player)
&& character.Faction.IsEnemiesWith(player.Faction))
{
liveEnemies.Add(character.Entity);
}
}

cachedEnemyCount = liveEnemies.Count;
return cachedEnemyCount;
}

private int GetMaxEnemyCount(EnemySpawningComponent spawningComponent, int liveEnemyCount, LevelProgressComponent? lvlProgress)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using MIR.Cutscenes;
using MIR.Cutscenes;
using System;
using System.Diagnostics;
using System.Globalization;
Expand Down
37 changes: 18 additions & 19 deletions src/MadnessInteractiveReloaded/Program.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
using HarmonyLib;
using HarmonyLib;
using System;
using System.IO;
using System.Linq;
using Walgelijk;
using Walgelijk.AssetManager;
using System.Text;

namespace MIR;

Expand Down Expand Up @@ -138,27 +139,26 @@ private static void Main(string? mode = null, string? input = null, string? outp

return;
}
#endif
}

private static void WriteLog(string path)
{
// Add a disk logger to the ILogger thing

//var impl = Logger.Implementations.FirstOrDefault(a => a is DiskLogger);
//if (impl == null || impl is not DiskLogger diskLogger)
//{
// File.WriteAllText(path, "Disk logger could not be found. No log was recorded. This is catastrophic.");
// return;
//}
//try
//{
// File.Copy(diskLogger.TargetPath, path);
//}
//catch (Exception e)
//{
// File.WriteAllText(path, "Log could not be copied to target location: " + e);
// return;
//}
try
{
var logContent = new StringBuilder();
logContent.AppendLine($"Crash log generated at {DateTime.Now}");
logContent.AppendLine($"Game Version: {GameVersion.Version}");
logContent.AppendLine($"OS: {Environment.OSVersion}");
logContent.AppendLine($"Runtime: {Environment.Version}");

// Write the log content to file
File.WriteAllText(path, logContent.ToString());
}
catch (Exception e)
{
File.WriteAllText(path, $"Failed to write crash log: {e}");
}
}

private static void WriteComponents(string path)
Expand Down Expand Up @@ -219,6 +219,5 @@ private static void WriteFieldsProperties<T>(T obj, StreamWriter w) where T : no
var value = item.GetValue(obj);
w.WriteLine("\t\tp_{0}: {1}", item.Name, value);
}
#endif
}
}
87 changes: 79 additions & 8 deletions src/MadnessInteractiveReloaded/Registries/Registry.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
Expand All @@ -8,12 +8,47 @@ namespace MIR;
public class Registry<T> : IRegistry<string, T> where T : class
{
private readonly ConcurrentDictionary<string, T> dict = new();
private readonly bool disposeOnRemove;

public Registry(bool disposeOnRemove = true)
{
this.disposeOnRemove = disposeOnRemove;
}

public int Count => dict.Count;

public void Clear() => dict.Clear();
public void Clear()
{
if (disposeOnRemove)
{
foreach (var item in dict.Values)
{
if (item is IDisposable disposable)
{
try
{
disposable.Dispose();
}
catch (Exception e)
{
Logger.Error($"Error disposing item in registry: {e}");
}
}
}
}
dict.Clear();
}

public T Get(string key) => dict[key];
public T Get(string key)
{
if (key == null)
throw new ArgumentNullException(nameof(key));

if (dict.TryGetValue(key, out var value))
return value;

throw new KeyNotFoundException($"Key '{key}' not found in registry");
}

public IEnumerable<string> GetAllKeys() => dict.Keys;

Expand Down Expand Up @@ -41,17 +76,53 @@ public bool TryGetKeyFor(T value, [NotNullWhen(true)] out string? key)

public void Unregister(string key)
{
dict.TryRemove(key, out _); //👍👍
if (key == null)
throw new ArgumentNullException(nameof(key));

if (dict.TryRemove(key, out var value) && disposeOnRemove && value is IDisposable disposable)
{
try
{
disposable.Dispose();
}
catch (Exception e)
{
Logger.Error($"Error disposing value for key '{key}': {e}");
}
}
}

public void Register(string key, T val)
{
if (!dict.TryAdd(key, val))
if (key == null)
throw new ArgumentNullException(nameof(key));
if (val == null)
throw new ArgumentNullException(nameof(val));

if (dict.TryGetValue(key, out var oldValue))
{
if (disposeOnRemove && oldValue is IDisposable disposable)
{
try
{
disposable.Dispose();
}
catch (Exception e)
{
Logger.Error($"Error disposing old value for key '{key}': {e}");
}
}

if (!dict.TryUpdate(key, val, oldValue))
{
throw new InvalidOperationException($"Concurrent modification detected while updating key '{key}'");
}
Logger.Log($"Registry {GetType().Name} replaced value at key '{key}'");
}
else if (!dict.TryAdd(key, val))
{
dict[key] = val;
Logger.Log($"Registry {this} replaced {key}");
throw new InvalidOperationException($"Failed to add value at key '{key}' - concurrent modification detected");
}
//throw new Exception($"Already registered a value at {key}");
}

public T this[string key] => Get(key);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System.Linq;
using System.Linq;
using System.Numerics;
using Walgelijk;
using Walgelijk.AssetManager;
Expand All @@ -17,9 +17,15 @@ public class CampaignMenuSystem : Walgelijk.System
// TODO maybe use a shared rendertexure for this?
public static RenderTexture PlayerDrawTarget = new(512, 512, flags: RenderTargetFlags.None);
private Rect campaignBoxRect;
private bool isLoadingCampaign = false;

private static readonly MenuCharacterRenderer menuCharacterRenderer = new();

public override void OnActivate()
{
isLoadingCampaign = false;
}

public override void Render()
{
if (!MadnessUtils.FindPlayer(Scene, out _, out var character))
Expand Down Expand Up @@ -247,10 +253,9 @@ public override void Update()
"cmpgn-menu-play" :
(stats.LevelIndex >= campaign.Levels.Length ? "cmpgn-menu-restart" : "cmpgn-menu-continue");
Ui.Layout.Size(130, 40).StickRight().StickBottom().Order(1);
if (Ui.Button(Localisation.Get(btnKey)))
if (Ui.Button(Localisation.Get(btnKey)) && !isLoadingCampaign)
{
// TODO ensure we cant press this button while loading a campaign

isLoadingCampaign = true; // prevent double click
var i = stats.LevelIndex;

if (i >= campaign.Levels.Length) // we completed the campaign, restart
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using Walgelijk.Onion;
using Walgelijk.Onion;
using Walgelijk.SimpleDrawing;
using Walgelijk;
using Walgelijk.Localisation;
Expand Down Expand Up @@ -232,10 +232,12 @@ private enum Screen
// TODO put in component lol
private string? selectedLevel;
private Screen currentScreen = Screen.LevelSelect;
private bool isLoadingLevel = false;

public override void OnActivate()
{
currentScreen = Screen.LevelSelect;
isLoadingLevel = false;
}

public override void Update()
Expand Down Expand Up @@ -381,10 +383,9 @@ private void LevelSelectGrid(Campaign campaign)

Ui.Theme.FontSize(24).OutlineWidth(2).Padding(12).Once();
Ui.Layout.FitContainer(0.2f, null).Scale(-12, 0).Height(60).StickBottom().StickRight();
if (Ui.Button("Proceed"))
if (Ui.Button("Proceed") && !isLoadingLevel)
{
// TODO ensure we cant press this button while loading a campaign

isLoadingLevel = true; // prevent double click
Game.Scene = LevelLoadingScene.Create(Game, Registries.Levels.Get(selectedLevel).Level, SceneCacheSettings.NoCache);
MadnessUtils.Flash(Colors.Black, 0.2f);
}
Expand Down
Loading