aboutsummaryrefslogtreecommitdiff
path: root/NorthstarDLL/bitbuf.h
blob: 520e5d0a9df2c6199c3ae91ea77f659b0ead3497 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
#pragma once

#define INLINE inline

#define BITS_PER_INT 32

INLINE int GetBitForBitnum(int bitNum)
{
	static int bitsForBitnum[] = {
		(1 << 0),  (1 << 1),  (1 << 2),	 (1 << 3),	(1 << 4),  (1 << 5),  (1 << 6),	 (1 << 7),	(1 << 8),  (1 << 9),  (1 << 10),
		(1 << 11), (1 << 12), (1 << 13), (1 << 14), (1 << 15), (1 << 16), (1 << 17), (1 << 18), (1 << 19), (1 << 20), (1 << 21),
		(1 << 22), (1 << 23), (1 << 24), (1 << 25), (1 << 26), (1 << 27), (1 << 28), (1 << 29), (1 << 30), (1 << 31),
	};

	return bitsForBitnum[(bitNum) & (BITS_PER_INT - 1)];
}

#undef BITS_PER_INT

using u8 = uint8_t;
using u16 = uint16_t;
using u32 = uint32_t;
using u64 = uint64_t;
using uptr = uintptr_t;

using i8 = int8_t;
using i16 = int16_t;
using i32 = int32_t;
using i64 = int64_t;
using iptr = intptr_t;

// Endianess, don't use on PPC64 nor ARM64BE
#define LittleDWord(val) (val)

static INLINE void StoreLittleDWord(u32* base, size_t dwordIndex, u32 dword)
{
	base[dwordIndex] = LittleDWord(dword);
}

static INLINE u32 LoadLittleDWord(u32* base, size_t dwordIndex)
{
	return LittleDWord(base[dwordIndex]);
}

#include <algorithm>

static inline const u32 s_nMaskTable[33] = {
	0,
	(1 << 1) - 1,
	(1 << 2) - 1,
	(1 << 3) - 1,
	(1 << 4) - 1,
	(1 << 5) - 1,
	(1 << 6) - 1,
	(1 << 7) - 1,
	(1 << 8) - 1,
	(1 << 9) - 1,
	(1 << 10) - 1,
	(1 << 11) - 1,
	(1 << 12) - 1,
	(1 << 13) - 1,
	(1 << 14) - 1,
	(1 << 15) - 1,
	(1 << 16) - 1,
	(1 << 17) - 1,
	(1 << 18) - 1,
	(1 << 19) - 1,
	(1 << 20) - 1,
	(1 << 21) - 1,
	(1 << 22) - 1,
	(1 << 23) - 1,
	(1 << 24) - 1,
	(1 << 25) - 1,
	(1 << 26) - 1,
	(1 << 27) - 1,
	(1 << 28) - 1,
	(1 << 29) - 1,
	(1 << 30) - 1,
	0x7fffffff,
	0xffffffff,
};

enum EBitCoordType
{
	kCW_None,
	kCW_LowPrecision,
	kCW_Integral
};

class BitBufferBase
{
  protected:
	INLINE void SetName(const char* name)
	{
		m_BufferName = name;
	}

  public:
	INLINE bool IsOverflowed()
	{
		return m_Overflow;
	}
	INLINE void SetOverflowed()
	{
		m_Overflow = true;
	}

	INLINE const char* GetName()
	{
		return m_BufferName;
	}

  private:
	const char* m_BufferName = "";

  protected:
	u8 m_Overflow = false;
};

class BFRead : public BitBufferBase
{
  public:
	BFRead() = default;

	INLINE BFRead(uptr data, size_t byteLength, size_t startPos = 0, const char* bufferName = 0)
	{
		StartReading(data, byteLength, startPos);

		if (bufferName)
			SetName(bufferName);
	}

  public:
	INLINE void StartReading(uptr data, size_t byteLength, size_t startPos = 0)
	{
		m_Data = reinterpret_cast<u32 const*>(data);
		m_DataIn = m_Data;

		m_DataBytes = byteLength;
		m_DataBits = byteLength << 3;

		m_DataEnd = reinterpret_cast<u32 const*>(reinterpret_cast<u8 const*>(m_Data) + m_DataBytes);

		Seek(startPos);
	}

	INLINE void GrabNextDWord(bool overflow = false)
	{
		if (m_Data == m_DataEnd)
		{
			m_CachedBitsLeft = 1;
			m_CachedBufWord = 0;

			m_DataIn++;

			if (overflow)
				SetOverflowed();
		}
		else
		{
			if (m_DataIn > m_DataEnd)
			{
				SetOverflowed();
				m_CachedBufWord = 0;
			}
			else
			{
				m_CachedBufWord = LittleDWord(*(m_DataIn++));
			}
		}
	}

	INLINE void FetchNext()
	{
		m_CachedBitsLeft = 32;
		GrabNextDWord(false);
	}

	INLINE i32 ReadOneBit()
	{
		i32 ret = m_CachedBufWord & 1;

		if (--m_CachedBitsLeft == 0)
			FetchNext();
		else
			m_CachedBufWord >>= 1;

		return ret;
	}

	INLINE u32 ReadUBitLong(i32 numBits)
	{
		if (m_CachedBitsLeft >= numBits)
		{
			u32 ret = m_CachedBufWord & s_nMaskTable[numBits];

			m_CachedBitsLeft -= numBits;

			if (m_CachedBitsLeft)
				m_CachedBufWord >>= numBits;
			else
				FetchNext();

			return ret;
		}
		else
		{
			// need to merge words
			u32 ret = m_CachedBufWord;
			numBits -= m_CachedBitsLeft;

			GrabNextDWord(true);

			if (IsOverflowed())
				return 0;

			ret |= ((m_CachedBufWord & s_nMaskTable[numBits]) << m_CachedBitsLeft);

			m_CachedBitsLeft = 32 - numBits;
			m_CachedBufWord >>= numBits;

			return ret;
		}
	}

	INLINE i32 ReadSBitLong(int numBits)
	{
		i32 ret = ReadUBitLong(numBits);
		return (ret << (32 - numBits)) >> (32 - numBits);
	}

	INLINE u32 ReadUBitVar()
	{
		u32 ret = ReadUBitLong(6);

		switch (ret & (16 | 32))
		{
		case 16:
			ret = (ret & 15) | (ReadUBitLong(4) << 4);
			// Assert(ret >= 16);
			break;
		case 32:
			ret = (ret & 15) | (ReadUBitLong(8) << 4);
			// Assert(ret >= 256);
			break;
		case 48:
			ret = (ret & 15) | (ReadUBitLong(32 - 4) << 4);
			// Assert(ret >= 4096);
			break;
		}

		return ret;
	}

	INLINE u32 PeekUBitLong(i32 numBits)
	{
		i32 nSaveBA = m_CachedBitsLeft;
		i32 nSaveW = m_CachedBufWord;
		u32 const* pSaveP = m_DataIn;
		u32 nRet = ReadUBitLong(numBits);

		m_CachedBitsLeft = nSaveBA;
		m_CachedBufWord = nSaveW;
		m_DataIn = pSaveP;

		return nRet;
	}

	INLINE float ReadBitFloat()
	{
		u32 value = ReadUBitLong(32);
		return *reinterpret_cast<float*>(&value);
	}

	/*INLINE float ReadBitCoord() {
		i32   intval = 0, fractval = 0, signbit = 0;
		float value = 0.0;

		// Read the required integer and fraction flags
		intval = ReadOneBit();
		fractval = ReadOneBit();

		// If we got either parse them, otherwise it's a zero.
		if (intval || fractval) {
			// Read the sign bit
			signbit = ReadOneBit();

			// If there's an integer, read it in
			if (intval) {
				// Adjust the integers from [0..MAX_COORD_VALUE-1] to [1..MAX_COORD_VALUE]
				intval = ReadUBitLong(COORD_INTEGER_BITS) + 1;
			}

			// If there's a fraction, read it in
			if (fractval) {
				fractval = ReadUBitLong(COORD_FRACTIONAL_BITS);
			}

			// Calculate the correct floating point value
			value = intval + ((float)fractval * COORD_RESOLUTION);

			// Fixup the sign if negative.
			if (signbit)
				value = -value;
		}

		return value;
	}

	INLINE float ReadBitCoordMP() {
		i32   intval = 0, fractval = 0, signbit = 0;
		float value = 0.0;

		bool inBounds = ReadOneBit() ? true : false;

		// Read the required integer and fraction flags
		intval = ReadOneBit();

		// If we got either parse them, otherwise it's a zero.
		if (intval) {
			// Read the sign bit
			signbit = ReadOneBit();

			// If there's an integer, read it in
			// Adjust the integers from [0..MAX_COORD_VALUE-1] to [1..MAX_COORD_VALUE]
			if (inBounds)
				value = ReadUBitLong(COORD_INTEGER_BITS_MP) + 1;
			else
				value = ReadUBitLong(COORD_INTEGER_BITS) + 1;
		}

		// Fixup the sign if negative.
		if (signbit)
			value = -value;

		return value;
	}

	INLINE float ReadBitCellCoord(int bits, EBitCoordType coordType) {
		bool bIntegral = (coordType == kCW_Integral);
		bool bLowPrecision = (coordType == kCW_LowPrecision);

		int   intval = 0, fractval = 0;
		float value = 0.0;

		if (bIntegral)
			value = ReadUBitLong(bits);
		else {
			intval = ReadUBitLong(bits);

			// If there's a fraction, read it in
			fractval = ReadUBitLong(bLowPrecision ? COORD_FRACTIONAL_BITS_MP_LOWPRECISION : COORD_FRACTIONAL_BITS);

			// Calculate the correct floating point value
			value = intval + ((float)fractval * (bLowPrecision ? COORD_RESOLUTION_LOWPRECISION : COORD_RESOLUTION));
		}

		return value;
	}

	INLINE float ReadBitNormal() {
		// Read the sign bit
		i32 signbit = ReadOneBit();

		// Read the fractional part
		u32 fractval = ReadUBitLong(NORMAL_FRACTIONAL_BITS);

		// Calculate the correct floating point value
		float value = (float)fractval * NORMAL_RESOLUTION;

		// Fixup the sign if negative.
		if (signbit)
			value = -value;

		return value;
	}

	INLINE void ReadBitVec3Coord(Vector& fa) {
		i32 xflag, yflag, zflag;

		// This vector must be initialized! Otherwise, If any of the flags aren't set,
		// the corresponding component will not be read and will be stack garbage.
		fa.Init(0, 0, 0);

		xflag = ReadOneBit();
		yflag = ReadOneBit();
		zflag = ReadOneBit();

		if (xflag)
			fa[0] = ReadBitCoord();
		if (yflag)
			fa[1] = ReadBitCoord();
		if (zflag)
			fa[2] = ReadBitCoord();
	}

	INLINE void ReadBitVec3Normal(Vector& fa) {
		i32 xflag = ReadOneBit();
		i32 yflag = ReadOneBit();

		if (xflag)
			fa[0] = ReadBitNormal();
		else
			fa[0] = 0.0f;

		if (yflag)
			fa[1] = ReadBitNormal();
		else
			fa[1] = 0.0f;

		// The first two imply the third (but not its sign)
		i32 znegative = ReadOneBit();

		float fafafbfb = fa[0] * fa[0] + fa[1] * fa[1];
		if (fafafbfb < 1.0f)
			fa[2] = sqrt(1.0f - fafafbfb);
		else
			fa[2] = 0.0f;

		if (znegative)
			fa[2] = -fa[2];
	}

	INLINE void ReadBitAngles(QAngle& fa) {
		Vector tmp;
		ReadBitVec3Coord(tmp);
		fa.Init(tmp.x, tmp.y, tmp.z);
	}*/

	INLINE float ReadBitAngle(int numBits)
	{
		float shift = (float)(GetBitForBitnum(numBits));

		i32 i = ReadUBitLong(numBits);
		float fReturn = (float)i * (360.0 / shift);

		return fReturn;
	}

	INLINE i32 ReadChar()
	{
		return ReadSBitLong(sizeof(char) << 3);
	}
	INLINE u32 ReadByte()
	{
		return ReadUBitLong(sizeof(unsigned char) << 3);
	}

	INLINE i32 ReadShort()
	{
		return ReadSBitLong(sizeof(short) << 3);
	}
	INLINE u32 ReadWord()
	{
		return ReadUBitLong(sizeof(unsigned short) << 3);
	}

	INLINE i32 ReadLong()
	{
		return (i32)(ReadUBitLong(sizeof(i32) << 3));
	}
	INLINE float ReadFloat()
	{
		u32 temp = ReadUBitLong(sizeof(float) << 3);
		return *reinterpret_cast<float*>(&temp);
	}

	INLINE u32 ReadVarInt32()
	{
		constexpr int kMaxVarint32Bytes = 5;

		u32 result = 0;
		int count = 0;
		u32 b;

		do
		{
			if (count == kMaxVarint32Bytes)
				return result;

			b = ReadUBitLong(8);
			result |= (b & 0x7F) << (7 * count);
			++count;
		} while (b & 0x80);

		return result;
	}

	INLINE u64 ReadVarInt64()
	{
		constexpr int kMaxVarintBytes = 10;

		u64 result = 0;
		int count = 0;
		u64 b;

		do
		{
			if (count == kMaxVarintBytes)
				return result;

			b = ReadUBitLong(8);
			result |= static_cast<u64>(b & 0x7F) << (7 * count);
			++count;
		} while (b & 0x80);

		return result;
	}

	INLINE void ReadBits(uptr outData, u32 bitLength)
	{
		u8* out = reinterpret_cast<u8*>(outData);
		int bitsLeft = bitLength;

		// align output to dword boundary
		while (((uptr)out & 3) != 0 && bitsLeft >= 8)
		{
			*out = (unsigned char)ReadUBitLong(8);
			++out;
			bitsLeft -= 8;
		}

		// read dwords
		while (bitsLeft >= 32)
		{
			*((u32*)out) = ReadUBitLong(32);
			out += sizeof(u32);
			bitsLeft -= 32;
		}

		// read remaining bytes
		while (bitsLeft >= 8)
		{
			*out = ReadUBitLong(8);
			++out;
			bitsLeft -= 8;
		}

		// read remaining bits
		if (bitsLeft)
			*out = ReadUBitLong(bitsLeft);
	}

	INLINE bool ReadBytes(uptr outData, u32 byteLength)
	{
		ReadBits(outData, byteLength << 3);
		return !IsOverflowed();
	}

	INLINE bool ReadString(char* str, i32 maxLength, bool stopAtLineTermination = false, i32* outNumChars = 0)
	{
		bool tooSmall = false;
		int iChar = 0;

		while (1)
		{
			char val = ReadChar();

			if (val == 0)
				break;
			else if (stopAtLineTermination && val == '\n')
				break;

			if (iChar < (maxLength - 1))
			{
				str[iChar] = val;
				++iChar;
			}
			else
			{
				tooSmall = true;
			}
		}

		// Make sure it's null-terminated.
		// Assert(iChar < maxLength);
		str[iChar] = 0;

		if (outNumChars)
			*outNumChars = iChar;

		return !IsOverflowed() && !tooSmall;
	}

	INLINE char* ReadAndAllocateString(bool* hasOverflowed = 0)
	{
		char str[2048];

		int chars = 0;
		bool overflowed = !ReadString(str, sizeof(str), false, &chars);

		if (hasOverflowed)
			*hasOverflowed = overflowed;

		// Now copy into the output and return it;
		char* ret = new char[chars + 1];
		for (u32 i = 0; i <= chars; i++)
			ret[i] = str[i];

		return ret;
	}

	INLINE i64 ReadLongLong()
	{
		i64 retval;
		u32* longs = (u32*)&retval;

		// Read the two DWORDs according to network endian
		const short endianIndex = 0x0100;
		u8* idx = (u8*)&endianIndex;

		longs[*idx++] = ReadUBitLong(sizeof(i32) << 3);
		longs[*idx] = ReadUBitLong(sizeof(i32) << 3);

		return retval;
	}

	INLINE bool Seek(size_t startPos)
	{
		bool bSucc = true;

		if (startPos < 0 || startPos > m_DataBits)
		{
			SetOverflowed();
			bSucc = false;
			startPos = m_DataBits;
		}

		// non-multiple-of-4 bytes at head of buffer. We put the "round off"
		// at the head to make reading and detecting the end efficient.
		int nHead = m_DataBytes & 3;

		int posBytes = startPos / 8;
		if ((m_DataBytes < 4) || (nHead && (posBytes < nHead)))
		{
			// partial first dword
			u8 const* partial = (u8 const*)m_Data;

			if (m_Data)
			{
				m_CachedBufWord = *(partial++);
				if (nHead > 1)
					m_CachedBufWord |= (*partial++) << 8;
				if (nHead > 2)
					m_CachedBufWord |= (*partial++) << 16;
			}

			m_DataIn = (u32 const*)partial;

			m_CachedBufWord >>= (startPos & 31);
			m_CachedBitsLeft = (nHead << 3) - (startPos & 31);
		}
		else
		{
			int adjustedPos = startPos - (nHead << 3);

			m_DataIn = reinterpret_cast<u32 const*>(reinterpret_cast<u8 const*>(m_Data) + ((adjustedPos / 32) << 2) + nHead);

			if (m_Data)
			{
				m_CachedBitsLeft = 32;
				GrabNextDWord();
			}
			else
			{
				m_CachedBufWord = 0;
				m_CachedBitsLeft = 1;
			}

			m_CachedBufWord >>= (adjustedPos & 31);
			m_CachedBitsLeft = std::min(m_CachedBitsLeft, u32(32 - (adjustedPos & 31))); // in case grabnextdword overflowed
		}

		return bSucc;
	}

	INLINE size_t GetNumBitsRead()
	{
		if (!m_Data)
			return 0;

		size_t nCurOfs = size_t(((iptr(m_DataIn) - iptr(m_Data)) / 4) - 1);
		nCurOfs *= 32;
		nCurOfs += (32 - m_CachedBitsLeft);

		size_t nAdjust = 8 * (m_DataBytes & 3);
		return std::min(nCurOfs + nAdjust, m_DataBits);
	}

	INLINE bool SeekRelative(size_t offset)
	{
		return Seek(GetNumBitsRead() + offset);
	}

	INLINE size_t TotalBytesAvailable()
	{
		return m_DataBytes;
	}

	INLINE size_t GetNumBitsLeft()
	{
		return m_DataBits - GetNumBitsRead();
	}
	INLINE size_t GetNumBytesLeft()
	{
		return GetNumBitsLeft() >> 3;
	}

  private:
	size_t m_DataBits; // 0x0010
	size_t m_DataBytes; // 0x0018

	u32 m_CachedBufWord; // 0x0020
	u32 m_CachedBitsLeft; // 0x0024

	const u32* m_DataIn; // 0x0028
	const u32* m_DataEnd; // 0x0030
	const u32* m_Data; // 0x0038
};

class BFWrite : public BitBufferBase
{
  public:
	BFWrite() = default;

	INLINE BFWrite(uptr data, size_t byteLength, const char* bufferName = 0)
	{
		StartWriting(data, byteLength);

		if (bufferName)
			SetName(bufferName);
	}

  public:
	INLINE void StartWriting(uptr data, size_t byteLength)
	{
		m_Data = reinterpret_cast<u32*>(data);
		m_DataOut = m_Data;

		m_DataBytes = byteLength;
		m_DataBits = byteLength << 3;

		m_DataEnd = reinterpret_cast<u32*>(reinterpret_cast<u8*>(m_Data) + m_DataBytes);
	}

	INLINE int GetNumBitsLeft()
	{
		return m_OutBitsLeft + (32 * (m_DataEnd - m_DataOut - 1));
	}

	INLINE void Reset()
	{
		m_Overflow = false;
		m_OutBufWord = 0;
		m_OutBitsLeft = 32;
		m_DataOut = m_Data;
	}

	INLINE void TempFlush()
	{
		if (m_OutBitsLeft != 32)
		{
			if (m_DataOut == m_DataEnd)
				SetOverflowed();
			else
				StoreLittleDWord(m_DataOut, 0, LoadLittleDWord(m_DataOut, 0) & ~s_nMaskTable[32 - m_OutBitsLeft] | m_OutBufWord);
		}

		m_Flushed = true;
	}

	INLINE u8* GetBasePointer()
	{
		TempFlush();
		return reinterpret_cast<u8*>(m_Data);
	}

	INLINE u8* GetData()
	{
		return GetBasePointer();
	}

	INLINE void Finish()
	{
		if (m_OutBitsLeft != 32)
		{
			if (m_DataOut == m_DataEnd)
				SetOverflowed();

			StoreLittleDWord(m_DataOut, 0, m_OutBufWord);
		}
	}

	INLINE void FlushNoCheck()
	{
		StoreLittleDWord(m_DataOut++, 0, m_OutBufWord);

		m_OutBitsLeft = 32;
		m_OutBufWord = 0;
	}

	INLINE void Flush()
	{
		if (m_DataOut == m_DataEnd)
			SetOverflowed();
		else
			StoreLittleDWord(m_DataOut++, 0, m_OutBufWord);

		m_OutBitsLeft = 32;
		m_OutBufWord = 0;
	}

	INLINE void WriteOneBitNoCheck(i32 value)
	{
		m_OutBufWord |= (value & 1) << (32 - m_OutBitsLeft);

		if (--m_OutBitsLeft == 0)
			FlushNoCheck();
	}

	INLINE void WriteOneBit(i32 value)
	{
		m_OutBufWord |= (value & 1) << (32 - m_OutBitsLeft);

		if (--m_OutBitsLeft == 0)
			Flush();
	}

	INLINE void WriteUBitLong(u32 data, i32 numBits, bool checkRange = true)
	{
		if (numBits <= m_OutBitsLeft)
		{
			if (checkRange)
				m_OutBufWord |= (data) << (32 - m_OutBitsLeft);
			else
				m_OutBufWord |= (data & s_nMaskTable[numBits]) << (32 - m_OutBitsLeft);

			m_OutBitsLeft -= numBits;

			if (m_OutBitsLeft == 0)
				Flush();
		}
		else
		{
			// split dwords case
			i32 overflowBits = (numBits - m_OutBitsLeft);
			m_OutBufWord |= (data & s_nMaskTable[m_OutBitsLeft]) << (32 - m_OutBitsLeft);
			Flush();
			m_OutBufWord = (data >> (numBits - overflowBits));
			m_OutBitsLeft = 32 - overflowBits;
		}
	}

	INLINE void WriteSBitLong(i32 data, i32 numBits)
	{
		WriteUBitLong((u32)data, numBits, false);
	}

	INLINE void WriteUBitVar(u32 n)
	{
		if (n < 16)
			WriteUBitLong(n, 6);
		else if (n < 256)
			WriteUBitLong((n & 15) | 16 | ((n & (128 | 64 | 32 | 16)) << 2), 10);
		else if (n < 4096)
			WriteUBitLong((n & 15) | 32 | ((n & (2048 | 1024 | 512 | 256 | 128 | 64 | 32 | 16)) << 2), 14);
		else
		{
			WriteUBitLong((n & 15) | 48, 6);
			WriteUBitLong((n >> 4), 32 - 4);
		}
	}

	INLINE void WriteBitFloat(float value)
	{
		auto temp = &value;
		WriteUBitLong(*reinterpret_cast<u32*>(temp), 32);
	}

	INLINE void WriteFloat(float value)
	{
		auto temp = &value;
		WriteUBitLong(*reinterpret_cast<u32*>(temp), 32);
	}

	INLINE bool WriteBits(const uptr data, i32 numBits)
	{
		u8* out = (u8*)data;
		i32 numBitsLeft = numBits;

		// Bounds checking..
		if ((GetNumBitsWritten() + numBits) > m_DataBits)
		{
			SetOverflowed();
			return false;
		}

		// !! speed!! need fast paths
		// write remaining bytes
		while (numBitsLeft >= 8)
		{
			WriteUBitLong(*out, 8, false);
			++out;
			numBitsLeft -= 8;
		}

		// write remaining bits
		if (numBitsLeft)
			WriteUBitLong(*out, numBitsLeft, false);

		return !IsOverflowed();
	}

	INLINE bool WriteBytes(const uptr data, i32 numBytes)
	{
		return WriteBits(data, numBytes << 3);
	}

	INLINE i32 GetNumBitsWritten()
	{
		return (32 - m_OutBitsLeft) + (32 * (m_DataOut - m_Data));
	}

	INLINE i32 GetNumBytesWritten()
	{
		return (GetNumBitsWritten() + 7) >> 3;
	}

	INLINE void WriteChar(i32 val)
	{
		WriteSBitLong(val, sizeof(char) << 3);
	}

	INLINE void WriteByte(i32 val)
	{
		WriteUBitLong(val, sizeof(unsigned char) << 3, false);
	}

	INLINE void WriteShort(i32 val)
	{
		WriteSBitLong(val, sizeof(short) << 3);
	}

	INLINE void WriteWord(i32 val)
	{
		WriteUBitLong(val, sizeof(unsigned short) << 3);
	}

	INLINE bool WriteString(const char* str)
	{
		if (str)
			while (*str)
				WriteChar(*(str++));

		WriteChar(0);

		return !IsOverflowed();
	}

	INLINE void WriteLongLong(i64 val)
	{
		u32* pLongs = (u32*)&val;

		// Insert the two DWORDS according to network endian
		const short endianIndex = 0x0100;
		u8* idx = (u8*)&endianIndex;

		WriteUBitLong(pLongs[*idx++], sizeof(i32) << 3);
		WriteUBitLong(pLongs[*idx], sizeof(i32) << 3);
	}

	/*INLINE void WriteBitCoord(const float f) {
		i32 signbit = (f <= -COORD_RESOLUTION);
		i32 intval = (i32)abs(f);
		i32 fractval = abs((i32)(f * COORD_DENOMINATOR)) & (COORD_DENOMINATOR - 1);

		// Send the bit flags that indicate whether we have an integer part and/or a fraction part.
		WriteOneBit(intval);
		WriteOneBit(fractval);

		if (intval || fractval) {
			// Send the sign bit
			WriteOneBit(signbit);

			// Send the integer if we have one.
			if (intval) {
				// Adjust the integers from [1..MAX_COORD_VALUE] to [0..MAX_COORD_VALUE-1]
				intval--;
				WriteUBitLong((u32)intval, COORD_INTEGER_BITS);
			}

			// Send the fraction if we have one
			if (fractval) {
				WriteUBitLong((u32)fractval, COORD_FRACTIONAL_BITS);
			}
		}
	}

	INLINE void WriteBitCoordMP(const float f) {
		i32 signbit = (f <= -COORD_RESOLUTION);
		i32 intval = (i32)abs(f);
		i32 fractval = (abs((i32)(f * COORD_DENOMINATOR)) & (COORD_DENOMINATOR - 1));

		bool bInBounds = intval < (1 << COORD_INTEGER_BITS_MP);

		WriteOneBit(bInBounds);

		// Send the sign bit
		WriteOneBit(intval);

		if (intval) {
			WriteOneBit(signbit);

			// Send the integer if we have one.
			// Adjust the integers from [1..MAX_COORD_VALUE] to [0..MAX_COORD_VALUE-1]
			intval--;

			if (bInBounds)
				WriteUBitLong((u32)intval, COORD_INTEGER_BITS_MP);
			else
				WriteUBitLong((u32)intval, COORD_INTEGER_BITS);
		}
	}

	INLINE void WriteBitCellCoord(const float f, int bits, EBitCoordType coordType) {
		bool bIntegral = (coordType == kCW_Integral);
		bool bLowPrecision = (coordType == kCW_LowPrecision);

		i32 intval = (i32)abs(f);
		i32 fractval = bLowPrecision ? (abs((i32)(f * COORD_DENOMINATOR_LOWPRECISION)) & (COORD_DENOMINATOR_LOWPRECISION - 1)) :
	(abs((i32)(f * COORD_DENOMINATOR)) & (COORD_DENOMINATOR - 1));

		if (bIntegral)
			WriteUBitLong((u32)intval, bits);
		else {
			WriteUBitLong((u32)intval, bits);
			WriteUBitLong((u32)fractval, bLowPrecision ? COORD_FRACTIONAL_BITS_MP_LOWPRECISION : COORD_FRACTIONAL_BITS);
		}
	}*/

	INLINE void SeekToBit(int bit)
	{
		TempFlush();

		m_DataOut = m_Data + (bit / 32);
		m_OutBufWord = LoadLittleDWord(m_DataOut, 0);
		m_OutBitsLeft = 32 - (bit & 31);
	}

	/*INLINE void WriteBitVec3Coord(const Vector& fa) {
		i32 xflag, yflag, zflag;

		xflag = (fa[0] >= COORD_RESOLUTION) || (fa[0] <= -COORD_RESOLUTION);
		yflag = (fa[1] >= COORD_RESOLUTION) || (fa[1] <= -COORD_RESOLUTION);
		zflag = (fa[2] >= COORD_RESOLUTION) || (fa[2] <= -COORD_RESOLUTION);

		WriteOneBit(xflag);
		WriteOneBit(yflag);
		WriteOneBit(zflag);

		if (xflag)
			WriteBitCoord(fa[0]);
		if (yflag)
			WriteBitCoord(fa[1]);
		if (zflag)
			WriteBitCoord(fa[2]);
	}

	INLINE void WriteBitNormal(float f) {
		i32 signbit = (f <= -NORMAL_RESOLUTION);

		// NOTE: Since +/-1 are valid values for a normal, I'm going to encode that as all ones
		u32 fractval = abs((i32)(f * NORMAL_DENOMINATOR));

		// clamp..
		if (fractval > NORMAL_DENOMINATOR)
			fractval = NORMAL_DENOMINATOR;

		// Send the sign bit
		WriteOneBit(signbit);

		// Send the fractional component
		WriteUBitLong(fractval, NORMAL_FRACTIONAL_BITS);
	}

	INLINE void WriteBitVec3Normal(const Vector& fa) {
		i32 xflag, yflag;

		xflag = (fa[0] >= NORMAL_RESOLUTION) || (fa[0] <= -NORMAL_RESOLUTION);
		yflag = (fa[1] >= NORMAL_RESOLUTION) || (fa[1] <= -NORMAL_RESOLUTION);

		WriteOneBit(xflag);
		WriteOneBit(yflag);

		if (xflag)
			WriteBitNormal(fa[0]);
		if (yflag)
			WriteBitNormal(fa[1]);

		// Write z sign bit
		i32 signbit = (fa[2] <= -NORMAL_RESOLUTION);
		WriteOneBit(signbit);
	}*/

	INLINE void WriteBitAngle(float angle, int numBits)
	{
		u32 shift = GetBitForBitnum(numBits);
		u32 mask = shift - 1;

		i32 d = (i32)((angle / 360.0) * shift);
		d &= mask;

		WriteUBitLong((u32)d, numBits);
	}

	INLINE bool WriteBitsFromBuffer(BFRead* in, int numBits)
	{
		while (numBits > 32)
		{
			WriteUBitLong(in->ReadUBitLong(32), 32);
			numBits -= 32;
		}

		WriteUBitLong(in->ReadUBitLong(numBits), numBits);
		return !IsOverflowed() && !in->IsOverflowed();
	}

	/*INLINE void WriteBitAngles(const QAngle& fa) {
		// FIXME:
		Vector tmp(fa.x, fa.y, fa.z);
		WriteBitVec3Coord(tmp);
	}*/

  private:
	size_t m_DataBits = 0;
	size_t m_DataBytes = 0;

	u32 m_OutBufWord = 0;
	u32 m_OutBitsLeft = 32;

	u32* m_DataOut = nullptr;
	u32* m_DataEnd = nullptr;
	u32* m_Data = nullptr;

	bool m_Flushed = false; // :flushed:
};

#undef INLINE