-
Notifications
You must be signed in to change notification settings - Fork 58
/
Param.cs
1202 lines (1067 loc) · 44 KB
/
Param.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using SoulsFormats;
using Andre.Core;
namespace Andre.Formats;
/// <summary>
/// An alternative to the SoulsFormats param class that's designed to be faster to read/write and be
/// much more memory efficient. This tries to match the SoulsFormats PARAM API as much as possible but
/// has some differences out of necessity. The main difference is rows and cells are separate rather
/// than each row having an array of cells. For convenience, a CellHandle struct was added that provides
/// a similar API to the SoulsFormats Cell.
/// A lot of this code is based off the SoulsFormats PARAM class (especially the read/write), so thanks TKGP.
/// </summary>
public class Param : SoulsFile<Param>
{
/// <summary>
/// First set of flags indicating file format; highly speculative.
/// </summary>
[Flags]
public enum FormatFlags1 : byte
{
/// <summary>
/// No flags set.
/// </summary>
None = 0,
/// <summary>
/// Unknown.
/// </summary>
Flag01 = 0b0000_0001,
/// <summary>
/// Expanded header with 32-bit data offset.
/// </summary>
IntDataOffset = 0b0000_0010,
/// <summary>
/// Expanded header with 64-bit data offset.
/// </summary>
LongDataOffset = 0b0000_0100,
/// <summary>
/// Unused?
/// </summary>
Flag08 = 0b0000_1000,
/// <summary>
/// Unused?
/// </summary>
Flag10 = 0b0001_0000,
/// <summary>
/// Unused?
/// </summary>
Flag20 = 0b0010_0000,
/// <summary>
/// Unused?
/// </summary>
Flag40 = 0b0100_0000,
/// <summary>
/// Param type string is written separately instead of fixed-width in the header.
/// </summary>
OffsetParamType = 0b1000_0000
}
/// <summary>
/// Second set of flags indicating file format; highly speculative.
/// </summary>
[Flags]
public enum FormatFlags2 : byte
{
/// <summary>
/// No flags set.
/// </summary>
None = 0,
/// <summary>
/// Row names are written as UTF-16.
/// </summary>
UnicodeRowNames = 0b0000_0001,
/// <summary>
/// Unknown.
/// </summary>
Flag02 = 0b0000_0010,
/// <summary>
/// Unknown.
/// </summary>
Flag04 = 0b0000_0100,
/// <summary>
/// Unused?
/// </summary>
Flag08 = 0b0000_1000,
/// <summary>
/// Unused?
/// </summary>
Flag10 = 0b0001_0000,
/// <summary>
/// Unused?
/// </summary>
Flag20 = 0b0010_0000,
/// <summary>
/// Unused?
/// </summary>
Flag40 = 0b0100_0000,
/// <summary>
/// Unused?
/// </summary>
Flag80 = 0b1000_0000
}
private StridedByteArray _paramData = new(0, 1);
private List<Row> _rows = new();
/// <summary>
/// Create an empty param. Param specific header data must be set before saving and ApplyParamdef()
/// must be called before using the Row APIs.
/// </summary>
public Param()
{
BigEndian = false;
Format2D = FormatFlags1.None;
Format2E = FormatFlags2.None;
ParamdefDataVersion = 0;
ParamdefFormatVersion = 0;
Unk06 = 0;
ParamType = null;
}
/// <summary>
/// Create an empty param conforming to a specified paramdef. Param specific header data must be
/// set before saving.
/// </summary>
/// <param name="paramdef">The paramdef that this param conforms to</param>
/// <param name="bigEndian">Whether the param is stored in big endian or not</param>
/// <param name="regulationVersion">For versioned paramdefs, the regulation version to apply</param>
public Param(PARAMDEF paramdef, bool bigEndian = false, ulong regulationVersion = ulong.MaxValue)
{
BigEndian = bigEndian;
Format2D = FormatFlags1.None;
Format2E = FormatFlags2.None;
ParamdefDataVersion = paramdef.DataVersion;
ParamdefFormatVersion = 0;
Unk06 = 0;
ParamType = paramdef.ParamType;
ApplyParamdef(paramdef, regulationVersion);
}
/// <summary>
/// Creates a new empty param inheriting config/paramdef from a source.
/// </summary>
/// <param name="source"></param>
public Param(Param source)
{
BigEndian = source.BigEndian;
Format2D = source.Format2D;
Format2E = source.Format2E;
ParamdefFormatVersion = source.ParamdefFormatVersion;
Unk06 = source.Unk06;
ParamdefDataVersion = source.ParamdefDataVersion;
ParamType = source.ParamType;
RowSize = source.RowSize;
_paramData = new StridedByteArray((uint)source._rows.Count, (uint)RowSize, BigEndian);
Columns = source.Columns;
AppliedParamdef = source.AppliedParamdef;
}
/// <summary>
/// Whether the file is big-endian; true for PS3/360 files, false otherwise.
/// </summary>
public bool BigEndian { get; set; }
/// <summary>
/// Flags indicating format of the file.
/// </summary>
public FormatFlags1 Format2D { get; set; }
/// <summary>
/// More flags indicating format of the file.
/// </summary>
public FormatFlags2 Format2E { get; set; }
/// <summary>
/// Originally matched the paramdef for version 101, but since is always 0 or 0xFF.
/// </summary>
public byte ParamdefFormatVersion { get; set; }
/// <summary>
/// Unknown.
/// </summary>
public short Unk06 { get; set; }
/// <summary>
/// Indicates a revision of the row data structure.
/// </summary>
public short ParamdefDataVersion { get; set; }
/// <summary>
/// Identifies corresponding params and paramdefs.
/// </summary>
public string? ParamType { get; set; }
/// <summary>
/// Detected size of the row in bytes. Empty params will have a size of 0 and params constructed
/// from scratch without a paramdef applied will have a size of -1
/// </summary>
public int RowSize { get; private set; } = -1;
/// <summary>
/// List of rows in the param. The list itself is readonly and the row API should be used to add and
/// delete rows, but this can be reset to a specified list of rows so long as all the rows are
/// constructed with this param as the parent.
/// </summary>
public IReadOnlyList<Row> Rows
{
get => _rows;
set
{
if (value == null)
throw new ArgumentNullException();
if (Rows.Any(r => r.Parent != this))
{
throw new ArgumentException("Attempting to add rows created from another Param");
}
_rows = new List<Row>(value);
}
}
/// <summary>
/// List of columns created from the applied paramdef. You can iterate through these and use the columns
/// to access the specific data of rows.
/// </summary>
public IReadOnlyList<Column> Columns { get; private set; } = new List<Column>();
/// <summary>
/// The applied paramdef
/// </summary>
public PARAMDEF? AppliedParamdef { get; private set; }
/// <summary>
/// Gets the index of the Row with ID id or returns null
/// </summary>
/// <param name="id">The ID of the row to find</param>
public Row? this[int id]
{
get
{
for (var i = 0; i < Rows.Count; i++)
{
if (Rows[i].ID == id)
return Rows[i];
}
return null;
}
}
/// <summary>
/// Gets a param column from a field name in the paramdef. Note that this currently runs in quadratic time
/// with respect to the number of paramdef fields and this should not be used in hot code. Mostly available
/// for compatability with Soulsformats PARAM class.
/// </summary>
/// <param name="name">The internal name of the paramdef field to lookup</param>
public Column? this[string name] => Columns.FirstOrDefault(cell => cell.Def.InternalName == name);
/// <summary>
/// Delete all the rows in the param
/// </summary>
public void ClearRows()
{
if (AppliedParamdef == null)
throw new Exception("Paramdef must be applied to use row management APIs");
_rows.Clear();
}
/// <summary>
/// Adds a row at the end of the param row lists. Row must be created with this param as the parent.
/// </summary>
/// <param name="row">The row to add</param>
public void AddRow(Row row)
{
if (AppliedParamdef == null)
throw new Exception("Paramdef must be applied to use row management APIs");
if (row.Parent != this)
throw new ArgumentException();
_rows.Add(row);
}
/// <summary>
/// Inserts a row in the row list at a specified index. Row must be created with this param as the parent.
/// </summary>
/// <param name="index"></param>
/// <param name="row"></param>
public void InsertRow(int index, Row row)
{
if (AppliedParamdef == null)
throw new Exception("Paramdef must be applied to use row management APIs");
if (row.Parent != this)
throw new ArgumentException();
_rows.Insert(index, row);
}
/// <summary>
/// Returns the index of a specified row in this param, or -1 if the row is not found. This runs
/// in linear time with respect to the total size of the param and should not be used in hot code.
/// </summary>
/// <param name="row"></param>
/// <returns>The index of the row, or -1 if the row is not found.</returns>
public int IndexOfRow(Row? row)
{
if (AppliedParamdef == null)
throw new Exception("Paramdef must be applied to use row management APIs");
if (row == null || row.Parent != this)
throw new ArgumentException();
return _rows.IndexOf(row);
}
/// <summary>
/// Removes a row from the param if the row is found. This runs in linear time for the search and then
/// the shifting.
/// </summary>
/// <param name="row">The row to search for</param>
/// <returns>True if the row was found and removed</returns>
public bool RemoveRow(Row row)
{
if (AppliedParamdef == null)
throw new Exception("Paramdef must be applied to use row management APIs");
if (row.Parent != this)
throw new ArgumentException();
return _rows.Remove(row);
}
/// <summary>
/// Removes a row from the param at a specified index. This runs in linear time for the shifting but
/// is generally faster than removing by row reference.
/// </summary>
/// <param name="index"></param>
public void RemoveRowAt(int index)
{
if (AppliedParamdef == null)
throw new Exception("Paramdef must be applied to use row management APIs");
_rows.RemoveAt(index);
}
/// <summary>
/// Apply a paramdef to a newly created/read param. For params that were read, the computed row
/// size from the layout must match the row size of the param file read. For params created from
/// scratch, the row size will be computed from the layout. The endianess of the param should be
/// set before this method is called.
/// </summary>
/// <param name="def">The paramdef to apply</param>
/// <param name="regulationVersion">
/// For version aware paramdefs, the regulation version of the param the
/// paramdef is being applied to
/// </param>
public void ApplyParamdef(PARAMDEF def, ulong regulationVersion = ulong.MaxValue)
{
if (AppliedParamdef != null)
throw new ArgumentException("Param already has a paramdef applied.");
AppliedParamdef = def;
var columns = new List<Column>(def.Fields.Count);
var bitOffset = -1;
uint byteOffset = 0;
uint lastSize = 0;
var bitType = PARAMDEF.DefType.u8;
foreach (PARAMDEF.Field? field in def.Fields)
{
if (def.VersionAware && !field.IsValidForRegulationVersion(regulationVersion))
continue;
PARAMDEF.DefType type = field.DisplayType;
var isBitType = ParamUtil.IsBitType(type);
if (!isBitType || (isBitType && field.BitSize == -1))
{
// Advance the offset if we were last reading bits
if (bitOffset != -1)
byteOffset += lastSize;
columns.Add(ParamUtil.IsArrayType(type)
? new Column(field, byteOffset, (uint)field.ArrayLength)
: new Column(field, byteOffset));
switch (type)
{
case PARAMDEF.DefType.s8:
case PARAMDEF.DefType.u8:
byteOffset += 1;
break;
case PARAMDEF.DefType.s16:
case PARAMDEF.DefType.u16:
byteOffset += 2;
break;
case PARAMDEF.DefType.s32:
case PARAMDEF.DefType.u32:
case PARAMDEF.DefType.f32:
case PARAMDEF.DefType.b32:
case PARAMDEF.DefType.angle32:
byteOffset += 4;
break;
case PARAMDEF.DefType.f64:
byteOffset += 8;
break;
case PARAMDEF.DefType.fixstr:
case PARAMDEF.DefType.dummy8:
byteOffset += (uint)field.ArrayLength;
break;
case PARAMDEF.DefType.fixstrW:
byteOffset += (uint)field.ArrayLength * 2;
break;
default:
throw new NotImplementedException($"Unsupported field type: {type}");
}
bitOffset = -1;
}
else
{
PARAMDEF.DefType newBitType = type == PARAMDEF.DefType.dummy8 ? PARAMDEF.DefType.u8 : type;
var bitLimit = ParamUtil.GetBitLimit(newBitType);
if (field.BitSize == 0)
throw new NotImplementedException("Bit size 0 is not supported.");
if (field.BitSize > bitLimit)
throw new InvalidDataException(
$"Bit size {field.BitSize} is too large to fit in type {newBitType}.");
lastSize = (uint)ParamUtil.GetValueSize(newBitType);
if (bitOffset == -1 || newBitType != bitType || bitOffset + field.BitSize > bitLimit)
{
if (bitOffset != -1)
byteOffset += lastSize;
bitOffset = 0;
bitType = newBitType;
}
columns.Add(new Column(field, byteOffset, field.BitSize, (uint)bitOffset));
bitOffset += field.BitSize;
}
}
// Get the final size
if (bitOffset != -1)
byteOffset += lastSize;
if (RowSize == -1)
{
// Param is being created from scratch. Set the row size and create an initial data store
RowSize = (int)byteOffset;
_paramData = new StridedByteArray(32, (uint)RowSize, BigEndian);
}
// If a row size is already read it must match our computed row size
else if (byteOffset != RowSize)
{
throw new Exception($@"Row size paramdef mismatch for {ParamType}");
}
Columns = columns;
}
/// <summary>
/// A bug in prior versions of DSMS and other param editors would save soundCutsceneParam as
/// 32 bytes instead of 36 bytes. Fortunately appending 0s at the end should be enough to fix
/// these params.
/// </summary>
private void FixupERSoundCutsceneParam()
{
var newData = new StridedByteArray((uint)Rows.Count, 36, BigEndian);
for (var i = 0; i < Rows.Count; i++)
{
newData.AddZeroedElement();
_paramData.CopyData(newData, (uint)i, (uint)i);
}
_paramData = newData;
RowSize = 36;
}
/// <summary>
/// People were using Yapped and other param editors to save botched ER 1.06 params, so we need
/// to fix them up again. Fortunately the only modified paramdef was ChrModelParam, and the new
/// field is always 0, so we can easily fix them.
/// </summary>
public void FixupERChrModelParam()
{
if (RowSize != 12)
return;
var newData = new StridedByteArray((uint)Rows.Count, 16, BigEndian);
for (var i = 0; i < Rows.Count; i++)
{
newData.AddZeroedElement();
_paramData.CopyData(newData, (uint)i, (uint)i);
}
_paramData = newData;
RowSize = 16;
}
protected override void Read(BinaryReaderEx br)
{
br.Position = 0x2C;
br.BigEndian = BigEndian = br.AssertByte([0, 0xFF]) == 0xFF;
Format2D = (FormatFlags1)br.ReadByte();
Format2E = (FormatFlags2)br.ReadByte();
ParamdefFormatVersion = br.ReadByte();
br.Position = 0;
// The strings offset in the header is highly unreliable; only use it as a last resort
long actualStringsOffset = 0;
long stringsOffset = br.ReadUInt32();
if ((Format2D.HasFlag(FormatFlags1.Flag01) && Format2D.HasFlag(FormatFlags1.IntDataOffset)) ||
Format2D.HasFlag(FormatFlags1.LongDataOffset))
{
br.AssertInt16([0]);
}
else
{
br.ReadUInt16(); // Data start
}
Unk06 = br.ReadInt16();
ParamdefDataVersion = br.ReadInt16();
var rowCount = br.ReadUInt16();
long paramTypeOffset = 0;
if (Format2D.HasFlag(FormatFlags1.OffsetParamType))
{
br.AssertInt32(0);
paramTypeOffset = br.ReadInt64();
br.AssertPattern(0x14, 0x00);
// ParamType itself will be checked after rows.
actualStringsOffset = paramTypeOffset;
}
else
{
ParamType = br.ReadFixStr(0x20);
}
br.Skip(4); // Format
if (Format2D.HasFlag(FormatFlags1.Flag01) && Format2D.HasFlag(FormatFlags1.IntDataOffset))
{
br.ReadInt32(); // Data start
br.AssertInt32(0);
br.AssertInt32(0);
br.AssertInt32(0);
}
else if (Format2D.HasFlag(FormatFlags1.LongDataOffset))
{
br.ReadInt64(); // Data start
br.AssertInt64(0);
}
Rows = new List<Row>(rowCount);
for (var i = 0; i < rowCount; i++)
{
long nameOffset;
int id;
string? name = null;
uint dataIndex;
if (Format2D.HasFlag(FormatFlags1.LongDataOffset))
{
id = br.ReadInt32();
br.ReadInt32(); // I would like to assert 0, but some of the generatordbglocation params in DS2S have garbage here
dataIndex = (uint)br.ReadInt64();
nameOffset = br.ReadInt64();
}
else
{
id = br.ReadInt32();
dataIndex = br.ReadUInt32();
nameOffset = br.ReadUInt32();
}
if (nameOffset != 0)
{
if (actualStringsOffset == 0 || nameOffset < actualStringsOffset)
actualStringsOffset = nameOffset;
if (Format2E.HasFlag(FormatFlags2.UnicodeRowNames))
name = br.GetUTF16(nameOffset);
else
name = br.GetShiftJIS(nameOffset);
}
_rows.Add(new Row(id, name, this, dataIndex));
}
if (Rows.Count > 1)
RowSize = (int)(Rows[1].DataIndex - Rows[0].DataIndex);
else if (Rows.Count == 1)
RowSize = (int)((actualStringsOffset == 0 ? (uint)stringsOffset : (uint)actualStringsOffset) -
Rows[0].DataIndex);
else
RowSize = 0;
uint dataStart = 0;
if (Rows.Count > 0)
{
dataStart = Rows.Min(row => row.DataIndex);
br.Position = dataStart;
var rowData = br.ReadBytes(Rows.Count * RowSize);
_paramData = new StridedByteArray(rowData, (uint)RowSize, BigEndian);
// Convert raw data offsets into indices
foreach (Row r in Rows)
{
r.DataIndex = (r.DataIndex - dataStart) / (uint)RowSize;
}
}
if (Format2D.HasFlag(FormatFlags1.OffsetParamType))
{
// Check if ParamTypeOffset is valid.
if (paramTypeOffset == dataStart + (rowCount * RowSize))
{
ParamType = br.GetASCII(paramTypeOffset);
}
}
if (ParamType == "SOUND_CUTSCENE_PARAM_ST" && ParamdefDataVersion == 6 && RowSize == 32)
{
FixupERSoundCutsceneParam();
}
}
protected override void Write(BinaryWriterEx bw)
{
if (AppliedParamdef == null)
throw new InvalidOperationException("Params cannot be written without applying a paramdef.");
bw.BigEndian = BigEndian;
bw.ReserveUInt32("StringsOffset");
if ((Format2D.HasFlag(FormatFlags1.Flag01) && Format2D.HasFlag(FormatFlags1.IntDataOffset)) ||
Format2D.HasFlag(FormatFlags1.LongDataOffset))
{
bw.WriteInt16(0);
}
else
{
bw.ReserveUInt16("DataStart");
}
bw.WriteInt16(Unk06);
bw.WriteInt16(ParamdefDataVersion);
if (Rows.Count > ushort.MaxValue)
throw new OverflowException(
$"Param \"{AppliedParamdef.ParamType}\" has more than {ushort.MaxValue} rows and cannot be saved.");
bw.WriteUInt16((ushort)Rows.Count);
if (Format2D.HasFlag(FormatFlags1.OffsetParamType))
{
bw.WriteInt32(0);
bw.ReserveInt64("ParamTypeOffset");
bw.WritePattern(0x14, 0x00);
}
else
{
// This padding heuristic isn't completely accurate, not that it matters
bw.WriteFixStr(ParamType, 0x20, (byte)(Format2D.HasFlag(FormatFlags1.Flag01) ? 0x20 : 0x00));
}
bw.WriteByte((byte)(BigEndian ? 0xFF : 0x00));
bw.WriteByte((byte)Format2D);
bw.WriteByte((byte)Format2E);
bw.WriteByte(ParamdefFormatVersion);
if (Format2D.HasFlag(FormatFlags1.Flag01) && Format2D.HasFlag(FormatFlags1.IntDataOffset))
{
bw.ReserveUInt32("DataStart");
bw.WriteInt32(0);
bw.WriteInt32(0);
bw.WriteInt32(0);
}
else if (Format2D.HasFlag(FormatFlags1.LongDataOffset))
{
bw.ReserveInt64("DataStart");
bw.WriteInt64(0);
}
// Write row headers
for (var i = 0; i < Rows.Count; i++)
{
if (Format2D.HasFlag(FormatFlags1.LongDataOffset))
{
bw.WriteInt32(Rows[i].ID);
bw.WriteInt32(0);
bw.ReserveInt64($"RowOffset{i}");
bw.ReserveInt64($"NameOffset{i}");
}
else
{
bw.WriteInt32(Rows[i].ID);
bw.ReserveUInt32($"RowOffset{i}");
bw.ReserveUInt32($"NameOffset{i}");
}
}
// This is probably pretty stupid
if (Format2D == FormatFlags1.Flag01)
bw.WritePattern(0x20, 0x00);
if (Format2D.HasFlag(FormatFlags1.Flag01) && Format2D.HasFlag(FormatFlags1.IntDataOffset))
bw.FillUInt32("DataStart", (uint)bw.Position);
else if (Format2D.HasFlag(FormatFlags1.LongDataOffset))
bw.FillInt64("DataStart", bw.Position);
else
bw.FillUInt16("DataStart", (ushort)bw.Position);
// Write row data
for (var i = 0; i < Rows.Count; i++)
{
if (Format2D.HasFlag(FormatFlags1.LongDataOffset))
bw.FillInt64($"RowOffset{i}", bw.Position);
else
bw.FillUInt32($"RowOffset{i}", (uint)bw.Position);
Span<byte> data = _paramData.DataForElement(Rows[i].DataIndex);
bw.WriteBytes(data);
}
bw.FillUInt32("StringsOffset", (uint)bw.Position);
if (Format2D.HasFlag(FormatFlags1.OffsetParamType))
{
bw.FillInt64("ParamTypeOffset", bw.Position);
bw.WriteASCII(ParamType, true);
}
// Write row names
var stringOffsetDictionary = new Dictionary<string, long>();
for (var i = 0; i < Rows.Count; i++)
{
var rowName = Rows[i].Name ?? string.Empty;
stringOffsetDictionary.TryGetValue(rowName, out var nameOffset);
if (nameOffset == 0)
{
nameOffset = bw.Position;
if (Format2E.HasFlag(FormatFlags2.UnicodeRowNames))
bw.WriteUTF16(rowName, true);
else
bw.WriteShiftJIS(rowName, true);
stringOffsetDictionary.Add(rowName, nameOffset);
}
if (Format2D.HasFlag(FormatFlags1.LongDataOffset))
bw.FillInt64($"NameOffset{i}", nameOffset);
else
bw.FillUInt32($"NameOffset{i}", (uint)nameOffset);
}
bw.WriteInt16(0); //FS Seems to end their params with an empty string
}
/// <summary>
/// A param row, which represents a single collection of values for fields specified in a paramdef. Each
/// row has an ID, which is usually unique but not always, and may optionally have a name. Unlike a
/// Soulsformats PARAM row, this row is tied to a specific instance of the Param class as the parent,
/// and must be cloned to the target Param instance before being added to that Param. This is because
/// a Row doesn't store any data on its own but merely references specific data managed by the parent
/// Param instance.
/// </summary>
public class Row
{
internal readonly Param Parent;
internal uint DataIndex;
internal Row(int id, string? name, Param parent, uint dataIndex)
{
ID = id;
Name = name;
Parent = parent;
DataIndex = dataIndex;
}
/// <summary>
/// Creates a new empty row with all fields zeroed out. This row must then be manually added to
/// the parent Param.
/// </summary>
/// <param name="id">The ID for this row</param>
/// <param name="name">The name for this row</param>
/// <param name="parent">The Param that this row will be added to/associated with</param>
public Row(int id, string? name, Param parent)
{
ID = id;
Name = name;
Parent = parent;
DataIndex = parent._paramData.AddZeroedElement();
}
/// <summary>
/// Clones a row with all the field data copied from the existing row to the new one. This
/// row will have the same ID and name and must be manually added to the Param instance
/// associated with the row this row was cloned from.
/// </summary>
/// <param name="clone">The row to clone</param>
public Row(Row clone)
{
Parent = clone.Parent;
ID = clone.ID;
Name = clone.Name;
DataIndex = Parent._paramData.AddZeroedElement();
Parent._paramData.CopyData(DataIndex, clone.DataIndex);
}
/// <summary>
/// Clones a row with all the field data copied from the existing row to the new one. This
/// row will have the same ID and name, but will be associated with the Param provided instead
/// of the Param associated with the original row.
/// </summary>
/// <param name="clone">The row to clone</param>
/// <param name="newParent">The Param to associate this new clone with</param>
public Row(Row clone, Param newParent)
{
Parent = newParent;
ID = clone.ID;
Name = clone.Name;
DataIndex = Parent._paramData.AddZeroedElement();
clone.Parent._paramData.CopyData(Parent._paramData, DataIndex, clone.DataIndex);
}
/// <summary>
/// The ID for this row. Should be a unique identifier in theory but in practice it isn't always
/// guaranteed to be unique.
/// </summary>
public int ID { get; set; }
/// <summary>
/// The optional name for this row. These are usually stripped in many Fromsoft games but
/// community created names exist for many different games/params.
/// </summary>
public string? Name { get; set; }
/// <summary>
/// The enumerable list of columns representing the fields in this row
/// </summary>
public IEnumerable<Column> Columns => Parent.Columns;
/// <summary>
/// Gets a list of cells for this row that allow getting/setting the value for the fields in
/// this row. This is provided to assist migrating Soulsformats based code but this has allocation
/// overhead and the column API should be used instead.
/// </summary>
public IReadOnlyList<Cell> Cells
{
get
{
var cells = new List<Cell>(Columns.Count());
foreach (Column cell in Columns)
{
cells.Add(new Cell(this, cell));
}
return cells;
}
}
/// <summary>
/// The paramdef for this row.
/// </summary>
public PARAMDEF? Def => Parent.AppliedParamdef;
/// <summary>
/// Gets a cell for a specific field. This is mainly provided for API compatibility with SoulsFormats
/// and is not recommended for new code.
/// </summary>
/// <param name="field">The name of the field to look up</param>
public Cell? this[string field]
{
get
{
Column? cell = Columns.FirstOrDefault(cell => cell.Def.InternalName == field);
return cell != null ? new Cell(this, cell) : null;
}
}
/// <summary>
/// Gets a cell for a specific field in this row using a column. Using the column API directly is
/// the recommended way to access and modify field data, but there are cases where having a value
/// type cell handle can be useful.
/// </summary>
/// <param name="field">The column representing the field to create a cell for</param>
public Cell this[Column field] => new(this, field);
/// <summary>
/// Compares if the ID and field data of this row is the same as another row. The other row does
/// not need to have the same parent Param as this row.
/// </summary>
/// <param name="other">The row to compare to</param>
/// <returns>True if the IDs of the two rows match and the field data is byte equal.</returns>
public bool DataEquals(Row? other)
{
if (other == null)
return false;
if (ID != other.ID)
return false;
return Parent._paramData.DataEquals(other.Parent._paramData, other.DataIndex, DataIndex);
}
~Row()
{
Parent._paramData.RemoveAt(DataIndex);
}
/// <summary>
/// Gets a cell handle from a name or throw an exception if the field name is not found. This is
/// not very efficient and it is not recommended to use this in a hot code path.
/// </summary>
/// <param name="field">The field to look for</param>
/// <returns>A cell handle for the field</returns>
/// <exception cref="ArgumentException">Throws if field name doesn't exist</exception>
public Cell GetCellHandleOrThrow(string field)
{
Column? cell = Columns.FirstOrDefault(cell => cell.Def.InternalName == field);
if (cell == null)
throw new ArgumentException();
return new Cell(this, cell);
}
}
/// <summary>
/// Similar to the SoulsFormats PARAM Cell class, a cell represents a specific field within a specific
/// row. In other words, it represents the cross of a specified row and column. This is meant to be a
/// mostly drop in replacement for existing code using the SF PARAM Cell API, but it is now a value type
/// that is created on demand and therefore more lightweight. For new code, usage of this is not
/// recommended.
/// </summary>
public readonly struct Cell
{
private readonly Row _row;
private readonly Column _column;
internal Cell(Row row, Column column)
{
_row = row;
_column = column;
}
/// <summary>
/// Property to get and set the value of this cell using the appropriate type for the field.
/// </summary>
public object Value
{
get => _column.GetValue(_row);
set => _column.SetValue(_row, value);
}
/// <summary>
/// Alternate accessor to set the value of the cell in cases where properties can't be used.
/// </summary>
/// <param name="value">The value to set the cell to</param>
public void SetValue(object value)
{
_column.SetValue(_row, value);
}
/// <summary>
/// The paramdef field definition for this cell
/// </summary>
public PARAMDEF.Field Def => _column.Def;
}
/// <summary>
/// Represents a Column (param field) in the param. Unlike the Soulsformats Cell, which represents a
/// value for a specific param field in a specific row, a column isn't associated with any specific row
/// but is instead used as an accessor to a specific paramdef field in any given row.
/// </summary>
public class Column
{
private readonly uint _arrayLength;
private readonly uint _bitOffset;
private readonly int _bitSize;
private readonly uint _byteOffset;
internal Column(PARAMDEF.Field def, uint byteOffset, uint arrayLength = 1)
{
Def = def;
_byteOffset = byteOffset;
_arrayLength = arrayLength;
_bitSize = -1;
_bitOffset = 0;
ValueType = TypeForParamDefType(def.DisplayType, arrayLength > 1);
}