Skip to content
Merged
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
55 changes: 37 additions & 18 deletions src/ShipInventoryUpdated/Helpers/API/ItemIdentifier.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
using ShipInventoryUpdated.Dependencies.LethalLib;
using System.Security.Cryptography;
using System.Text;
using ShipInventoryUpdated.Dependencies.LethalLib;
using Unity.Collections;

namespace ShipInventoryUpdated.Helpers.API;

internal static class ItemIdentifier
{
private const string INVALID_ITEM_ID = "InvalidItem";
private static readonly Dictionary<Item?, string> ItemToHash = new();
private static readonly Dictionary<string, Item> HashToItem = new();

/// <summary>
/// Fetches the generic ID of the given item
Expand All @@ -14,15 +19,27 @@ public static string GetID(Item? item)
if (item == null)
return INVALID_ITEM_ID;

if (ItemToHash.TryGetValue(item, out var hashedId))
return hashedId;

string? id = null;

if (Dependency.Enabled)
{
var moddedID = Dependency.GetID(item);
id = Dependency.GetID(item);

if (moddedID != null)
return moddedID;
}
id ??= item.itemName;

return $"Vanilla/{item.itemName}";
using var sha256Hash = SHA256.Create();

var rawData = Encoding.Default.GetBytes(id);
var hashedData = sha256Hash.ComputeHash(rawData);
hashedId = Encoding.Default.GetString(hashedData);
hashedId = new FixedString32Bytes(hashedId).ToString();

ItemToHash.Add(item, hashedId);
HashToItem.TryAdd(hashedId, item);

return hashedId;
}

/// <summary>
Expand All @@ -33,22 +50,24 @@ public static string GetID(Item? item)
if (id == INVALID_ITEM_ID)
return null;

if (HashToItem.TryGetValue(id, out var item))
return item;

if (Dependency.Enabled)
{
var moddedItem = Dependency.GetItem(id);
item = Dependency.GetItem(id);

if (moddedItem != null)
return moddedItem;
if (item == null)
{
var itemList = StartOfRound.Instance?.allItemsList?.itemsList ?? [];
item = itemList.FirstOrDefault(i => GetID(i) == id);
}

foreach (var item in StartOfRound.Instance?.allItemsList?.itemsList ?? [])
{
var currentId = GetID(item);
if (item == null)
return null;

if (currentId == id)
return item;
}
HashToItem.Add(id, item);
ItemToHash.TryAdd(item, id);

return null;
return item;
}
}