Anvil
Anvil.Services.TwoDimArrayFactory Class Reference

Creates a deserialized 2da structure using a ITwoDimArray converter. More...

Public Member Functions

 TwoDimArrayFactory (InjectionService injectionService)
 
T? Get2DA< T > (string name, bool forceRefresh=false)
 Deserializes the given 2da using the specified format. More...
 

Detailed Description

Creates a deserialized 2da structure using a ITwoDimArray converter.

Examples

/*
* Define a implementation to deserialize "xptable.2da", and use this class to determine how much XP is remaining until the next level.
*/
using System.Linq;
using Anvil.API;
namespace NWN.Anvil.Samples
{
// This is the deserialization class for this specific type of 2da.
// We can implement our own helper functions here that operate on the 2da data, and cache it.
public sealed class ExpTableEntry : ITwoDimArrayEntry
{
public int Level { get; private set; }
public int XP { get; private set; }
// RowIndex is already populated externally, and we do not need to assign it in InterpretEntry.
public int RowIndex { get; init; }
// InterpretEntry is where we populate our entry properties (Level & XP) with the correct data.
public void InterpretEntry(TwoDimArrayEntry entry)
{
Level = entry.GetInt("Level").GetValueOrDefault(0);
XP = entry.GetInt("XP").GetValueOrDefault(0);
}
}
[ServiceBinding(typeof(XPReportService))]
public class XPReportService
{
// The TwoDimArray is created here.
// ExpTableEntry (the type above) is passed in as a type parameter to be used to create our row data from exptable.2da.
private readonly TwoDimArray<ExpTableEntry> expTable = NwGameTables.GetTable<ExpTableEntry>("exptable.2da")!;
public XPReportService()
{
NwModule.Instance.OnClientEnter += OnClientEnter;
}
private void OnClientEnter(ModuleEvents.OnClientEnter onClientEnter)
{
NwPlayer player = onClientEnter.Player;
NwCreature? creature = player.ControlledCreature;
if (creature == null)
{
return;
}
int nextLevel = GetLevelFromXp(creature.Xp) + 1;
if (nextLevel > MaxLevel)
{
return;
}
player.SendServerMessage($"Next level up: {GetXpForLevel(nextLevel) - creature.Xp}");
}
public int MaxLevel => expTable[^1].Level;
public int GetXpForLevel(int level)
{
return expTable.First(entry => entry.Level == level).XP;
}
public int GetLevelFromXp(int xp)
{
int level = 1;
foreach (ExpTableEntry entry in expTable.Rows)
{
if (entry.XP > xp)
{
break;
}
level = entry.Level;
}
return level;
}
}
}

Member Function Documentation

◆ Get2DA< T >()

T? Anvil.Services.TwoDimArrayFactory.Get2DA< T > ( string  name,
bool  forceRefresh = false 
)
inline

Deserializes the given 2da using the specified format.

Parameters
nameThe name of the 2DA resource.
forceRefreshIf true, always reloads the 2DA instead of using a cached version.
Template Parameters
TThe ITwoDimArray type to use to deserialize.
Returns
The deserialized 2DA.
Type Constraints
T :ITwoDimArray 
T :new() 

The documentation for this class was generated from the following file: