-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathTABRawBinBlock.cs
More file actions
1636 lines (1494 loc) · 69.2 KB
/
TABRawBinBlock.cs
File metadata and controls
1636 lines (1494 loc) · 69.2 KB
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 System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Collections.ObjectModel;
namespace MapInfo.IO
{
/// <summary>
/// This is the base class used for all other data block types...
/// it contains all the base functions to handle binary data.
/// Это базовый класс для всех остальных типов блоков данных ...
/// Он содержит все базовые функции для обработки двоичных данных.
/// </summary>
internal class TABRawBinBlock
{
#region
/// <summary>
/// Связанный дескриптор файла
/// </summary>
public Stream m_fp; // Associated file handle
protected long Position
{
get { return m_fp.Position; }
set { m_fp.Position = value; }
}
protected TABAccess m_eAccess = new TABAccess(); // Read/Write access mode
protected SupportedBlockTypes m_nBlockType;
/// <summary>
/// Буфер содержит данные блоков
/// </summary>
protected byte m_pabyBuf; // Buffer to contain the block's data
/// <summary>
/// Размер текущего блока (и буфера)
/// </summary>
protected int m_nBlockSize; // Size of current block (and buffer)
/// <summary>
/// Количество байтов, используемых в буфере
/// </summary>
protected int m_nSizeUsed; // Number of bytes used in buffer
/// <summary>
/// TRUE=Блоки должны быть всегда nSize байт
/// FALSE=последний блок может быть меньше, чем nSize
/// </summary>
protected bool m_bHardBlockSize = new bool();
/// <summary>
/// Расположение текущего блока в файле
/// </summary>
protected int m_nFileOffset; // Location of current block in the file
/// <summary>
/// Следующий байт для чтения из m_pabyBuf []
/// </summary>
protected int m_nCurPos; // Next byte to read from m_pabyBuf[]
/// <summary>
/// Размер заголовка файла, если отличается от размера блока (используется GotoByteInFile ())
/// </summary>
protected int m_nFirstBlockPtr; // Size of file header when different from block size (used by GotoByteInFile())
/// <summary>
/// Используется только для обнаружения изменений
/// </summary>
protected bool m_bModified = false; // Used only to detect changes
public Int32 GetStartAddress()
{
return m_nFileOffset;
}
public void SetModifiedFlag(bool bModified)
{
m_bModified = bModified;
}
/// <summary>
/// This semi-private method gives a direct access to the internal buffer... /n
/// to be used with extreme care!
/// Это полу-частный метод дает прямой доступ к внутренним буфером,
/// который будет использоваться с особой осторожностью!
/// </summary>
/// <returns></returns>
public int GetCurDataPtr()
{
return (m_pabyBuf + m_nCurPos);
}
#endregion
public TABRawBinBlock() { }
public TABRawBinBlock(Stream stream)
{
m_fp = stream;
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="eAccessMode"></param>
/// <param name="bHardBlockSize"></param>
public TABRawBinBlock(TABAccess eAccessMode, bool bHardBlockSize)
{
m_bHardBlockSize = bHardBlockSize;
m_eAccess = eAccessMode;
m_nFirstBlockPtr = 0;
m_nBlockSize = m_nSizeUsed = m_nFileOffset = m_nCurPos = 0;
}
/// <summary>
/// Load data from the specified file location and initialize the block.
/// Загрузка данных из указанного местоположения файла и инициализировать блок.
/// </summary>
/// <param name="fpSrc"></param>
/// <param name="nOffset"></param>
/// <param name="nSize"></param>
/// <returns>
/// Returns 0 if succesful or -1 if an error happened, in which case CPLError() will have been called.
/// Возвращает 0, если успешным или -1, если произошло ошибок, и в этом случае CPLError () будет были названы.
/// </returns>
private bool ReadFromFile(Stream fpSrc, int nOffset, int nSize /*= 512*/)
{
if (fpSrc == null || nSize == 0)
{
throw new Exception("Утверждение не удалось!"); //CPLError(CE_Failure, CPLE_AssertionFailed, );
//return false;
}
m_fp = fpSrc;
m_nFileOffset = nOffset;
m_nCurPos = 0;
m_bModified = false;
//pabyBuf = (GByte)CPLMalloc(nSize * sizeof(GByte)); // Alloc a buffer to contain the data
// ----------------------------------------------------------------
// * Read from the file
// *---------------------------------------------------------------
//if (VSIFSeek(fpSrc, nOffset, SEEK_SET) != 0 || (m_nSizeUsed = VSIFRead(pabyBuf, sizeof(GByte), nSize, fpSrc)) == 0 || (m_bHardBlockSize && m_nSizeUsed != nSize))
//{
// CPLError(CE_Failure, CPLE_FileIO, "ReadFromFile() failed reading %d bytes at offset %d.", nSize, nOffset);
// CPLFree(pabyBuf);
// return -1;
//}
// ---------------------------------------------------------------
// Init block with the data we just read
// ---------------------------------------------------------------
return InitBlockFromData(fpSrc, nSize, m_nSizeUsed, nOffset);
}
/// <summary>
/// Set the binary data buffer and initialize the block.
/// Установите двоичный буфер данных и инициализируйте блок.
/// Вызов ReadFromFile () автоматически вызывает InitBlockFromData () для завершения
/// инициализации блока после чтения данных из файла. Производные классы должны
/// осуществлять свою собственную версию InitBlockFromData (), если они нуждаются
/// в особой инициализации ... в этом случае происходит InitBlockFromData () должен вызвать
/// InitBlockFromData (), прежде чем делать что-нибудь еще.
/// </summary>
/// <param name="pabyBuf"></param>
/// <param name="nBlockSize"></param>
/// <param name="nSizeUsed"></param>
/// <param name="bMakeCopy"></param>
/// <param name="fpSrc"></param>
/// <param name="nOffset"></param>
/// <returns></returns>
private bool InitBlockFromData(Stream fpSrc, int nBlockSize, int nSizeUsed, int nOffset)
{
m_fp = fpSrc;
m_nFileOffset = nOffset;
m_nCurPos = 0;
//m_bModified = 0;
// ----------------------------------------------------------------
// * Alloc or realloc the buffer to contain the data if necessary
// *---------------------------------------------------------------
//if (bMakeCopy == null)
//{
// if (m_pabyBuf != null)
// CPLFree(m_pabyBuf);
// m_pabyBuf = pabyBuf;
// m_nBlockSize = nBlockSize;
// m_nSizeUsed = nSizeUsed;
//}
//else if (m_pabyBuf == null || nBlockSize != m_nBlockSize)
//{
// //m_pabyBuf = (GByte)CPLRealloc(m_pabyBuf, nBlockSize * sizeof(GByte));
// m_nBlockSize = nBlockSize;
// m_nSizeUsed = nSizeUsed;
// //C++ TO C# CONVERTER TODO TASK: The memory management function 'memcpy' has no equivalent in C#:
// //memcpy(m_pabyBuf, pabyBuf, m_nSizeUsed);
//}
// ----------------------------------------------------------------
// * Extract block type... header block (first block in a file) has
// * no block type, so we assign one by default.
// *---------------------------------------------------------------
if (m_nFileOffset == 0)
m_nBlockType = SupportedBlockTypes.TABMAP_HEADER_BLOCK;
else
{
// Block type will be validated only if GetBlockType() is called
// Тип блока будут проверяться только в том случае GetBlockType () вызывается
Position = 0;
m_nBlockType = (SupportedBlockTypes)Read(1)[0];
}
return true;
}
//*********************************************************************
// * TABCreateMAPBlockFromFile()
// *
// * Load data from the specified file location and create and initialize
// * a TABMAP*Block of the right type to handle it.
// *
// * Returns the new object if succesful or NULL if an error happened, in
// * which case CPLError() will have been called.
// *********************************************************************
// private TABRawBinBlock TABCreateMAPBlockFromFile(ref FILE fpSrc, int nOffset, int nSize, GBool bHardBlockSize, TABAccess eAccessMode)
//{
// TABRawBinBlock poBlock = null;
// GByte pabyBuf;
// if (fpSrc == null || nSize == 0)
// {
// CPLError(CE_Failure, CPLE_AssertionFailed, "TABCreateMAPBlockFromFile(): Assertion Failed!");
// return null;
// }
//// ----------------------------------------------------------------
//// * Alloc a buffer to contain the data
//// *---------------------------------------------------------------
// pabyBuf = (GByte)CPLMalloc(nSize *sizeof(GByte));
//// ----------------------------------------------------------------
//// * Read from the file
//// *---------------------------------------------------------------
// if (VSIFSeek(fpSrc, nOffset, SEEK_SET) != 0 || VSIFRead(pabyBuf, sizeof(GByte), nSize, fpSrc)!=(uint)nSize)
// {
// CPLError(CE_Failure, CPLE_FileIO, "TABCreateMAPBlockFromFile() failed reading %d bytes at offset %d.", nSize, nOffset);
// CPLFree(pabyBuf);
// return null;
// }
//// ----------------------------------------------------------------
//// * Create an object of the right type
//// * Header block is different: it does not start with the object
//// * type byte but it is always the first block in a file
//// *---------------------------------------------------------------
// if (nOffset == 0)
// {
// poBlock = new TABMAPHeaderBlock;
// }
// else
// {
// switch(pabyBuf[0])
// {
// case TABMAP_INDEX_BLOCK:
// poBlock = new TABMAPIndexBlock(eAccessMode);
// break;
// case TABMAP_OBJECT_BLOCK:
// poBlock = new TABMAPObjectBlock(eAccessMode);
// break;
// case TABMAP_COORD_BLOCK:
// poBlock = new TABMAPCoordBlock(eAccessMode);
// break;
// case TABMAP_TOOL_BLOCK:
// poBlock = new TABMAPToolBlock(eAccessMode);
// break;
// case TABMAP_GARB_BLOCK:
// default:
// poBlock = new TABRawBinBlock(eAccessMode, bHardBlockSize);
// break;
// }
// }
//// ----------------------------------------------------------------
//// * Init new object with the data we just read
//// *---------------------------------------------------------------
// if (poBlock.InitBlockFromData(pabyBuf, nSize, nSize, 0, fpSrc, nOffset) != 0)
// {
// // Some error happened... and CPLError() has been called
// poBlock = null;
// poBlock = null;
// }
// return poBlock;
//}
public SupportedBlockTypes GetBlockClass()
{
// Extract block type... header block (first block in a file) has no block type, so we assign one by default.
// Экстракт блок типа ... Блок заголовка (первый блок в файле) не имеет тип блока, так что мы назначить его по умолчанию.
if (m_fp == null)
return SupportedBlockTypes.TAB_RAWBIN_BLOCK;
else
{
// Block type will be validated only if GetBlockType() is called
// Тип блока будут проверяться только в том случае GetBlockType () вызывается
//Position = 0;
return (SupportedBlockTypes)Read(1)[0];
}
}
private byte[] read = new byte[8];
protected byte[] Read(int count)
{
m_fp.Read(read, 0, count);
return read;
}
protected void Read(ref byte var)
{
m_fp.Read(read, 0, 1);
var = read[0];
}
protected void Read(ref short var)
{
m_fp.Read(read, 0, 2);
var = BitConverter.ToInt16(read, 0);
}
protected void Read(ref int var)
{
m_fp.Read(read, 0, 4);
var = BitConverter.ToInt32(read, 0);
}
protected void Read(ref long var)
{
m_fp.Read(read, 0, 8);
var = BitConverter.ToInt64(read, 0);
}
protected void Read(ref double var)
{
m_fp.Read(read, 0, 8);
var = BitConverter.ToDouble(read, 0);
}
static public void ReadVars(Stream m_fp, ref object var)
{
byte[] read = new byte[8];
//for (int i = 0; i < list.Length; i++)
//{
if ((var) is byte)
{
m_fp.Read(read, 0, 1);
var = read[0];
}
else if ((var) is short)
{
m_fp.Read(read, 0, 2);
var = BitConverter.ToInt16(read, 0);
}
else if ((var) is int)
{
m_fp.Read(read, 0, 4);
var = BitConverter.ToInt32(read, 0);
}
else if ((var) is long)
{
m_fp.Read(read, 0, 8);
var = BitConverter.ToInt64(read, 0);
}
else if ((var) is double)
{
m_fp.Read(read, 0, 8);
var = BitConverter.ToDouble(read, 0);
//};
}
}
}
/// <summary>
/// Режим доступа: чтение или запись,
/// </summary>
public enum TABAccess : int
{
TABRead,
TABWrite,
TABReadWrite // ReadWrite not implemented yet
}
/// <summary>
/// структура, что используется для хранения параметров проекции из заголовка .MAP
/// </summary>
public class TABProjInfo
{
public byte nProjId; // See MapInfo Ref. Manual, App. F and G
public byte nEllipsoidId;
public byte nUnitsId;
/// <summary>
/// params in same order as in .MIF COORDSYS
/// </summary>
public double[] adProjParams = new double[6];
/// <summary>
/// Datum Id added in MapInfo 7.8+ (.map V500)
/// </summary>
public short nDatumId = 0;
/// <summary>
/// Before that, we had to always lookup datum parameters to establish datum id
/// </summary>
public double dDatumShiftX;
public double dDatumShiftY;
public double dDatumShiftZ;
public double[] adDatumParams = new double[5];
/// <summary>
/// Affine parameters only in .map version 500 and up
/// <remarks>false=No affine param, true=Affine params</remarks>
/// </summary>
public bool nAffineFlag;
public byte nAffineUnits;
/// <summary>
/// Affine params A-F
/// </summary>
public double[] dAffineParam = new double[6];
}
internal class TABRawBlock
{
public const short Size = 0x200;
internal byte[] read; // = new byte[Size];
internal List<byte[]> raws = new List<byte[]>();
public short Position = 0;
//public SupportedBlockTypes BlockClass = SupportedBlockTypes.TAB_RAWBIN_BLOCK;
public static byte[] GetBlock(Stream stream)
{
byte[] block = new byte[Size];
stream.Read(block, 0, Size);
return block;
}
public static SupportedBlockTypes GetBlockClass(byte[] block)
{
if (block != null)
return (SupportedBlockTypes)block[0];
else
return SupportedBlockTypes.TAB_RAWBIN_BLOCK;
}
public TABRawBlock() { }
/// <summary>
/// Читаем блок
/// </summary>
/// <param name="stream"></param>
public TABRawBlock(byte[] block)
{
Add(block);
}
public virtual void Add(byte[] block)
{
read = block;
raws.Add(read);
}
//public TABRawBlock(TABRawBlock blk)
//{
// read = blk.read;
// Position = blk.Position;
// //BlockClass = blk.BlockClass;
//}
protected byte[] Read(short count)
{
byte[] var = new byte[count];
//read.CopyTo(var, Position);
Array.Copy(read, Position, var, 0, count);
Position += count;
return var;
}
protected void Read(ref byte var)
{
var = read[Position];
Position += 1;
}
public byte ReadByte()
{
byte var = 0;
Read(ref var);
return var;
}
protected void Read(ref sbyte var)
{
var = (sbyte)read[Position];
Position += 1;
}
public sbyte ReadSByte()
{
sbyte var = 0;
Read(ref var);
return var;
}
protected void Read(ref short var)
{
var = BitConverter.ToInt16(read, Position);
Position += 2;
}
public short ReadInt16()
{
short var = 0;
Read(ref var);
return var;
}
protected void Read(ref int var)
{
var = BitConverter.ToInt32(read, Position);
Position += 4;
}
public int ReadInt32()
{
int var = 0;
Read(ref var);
return var;
}
protected void Read(ref long var)
{
var = BitConverter.ToInt64(read, 8);
Position += 8;
}
protected void Read(ref double var)
{
var = BitConverter.ToDouble(read, Position);
Position += 8;
}
public double ReadDouble()
{
double var = 0;
Read(ref var);
return var;
}
}
/// <summary>
/// Supported .MAP block types (the first byte at the beginning of a block)
/// Поддерживаемые типы блоков .MAP (первый байт в начале блока)
/// </summary>
enum SupportedBlockTypes : sbyte
{
/// <summary>
/// TAB_RAWBIN_BLOCK = -1
/// </summary>
TAB_RAWBIN_BLOCK = -1,
/// <summary>
/// TABMAP_HEADER_BLOCK = 0
/// </summary>
TABMAP_HEADER_BLOCK = 0,
TABMAP_INDEX_BLOCK = 1,
TABMAP_OBJECT_BLOCK = 2,
TABMAP_COORD_BLOCK = 3,
TABMAP_GARB_BLOCK = 4,
TABMAP_TOOL_BLOCK = 5,
TABMAP_LAST_VALID_BLOCK_TYPE = 5
}
/// <summary>
/// Общая информация о системной таблице и внутренней структуры координат
/// </summary>
internal class TABMAPHeaderBlock : TABRawBlock
{
#region Vars
// Set various constants used in generating the header block.
// Установите различные константы, используемые в создании блока заголовка.
public const int HDR_MAGIC_COOKIE = 42424242;
public const int HDR_VERSION_NUMBER = 500;
//public const int HDR_DATA_BLOCK_SIZE = 512;
public const byte HDR_DEF_ORG_QUADRANT = 1; // N-E Quadrant
public const int HDR_DEF_REFLECTXAXIS = 0;
public const int HDR_OBJ_LEN_ARRAY_SIZE = 73;
// The header block starts with an array of map object length constants.
// Блок заголовка начинается с массива констант длины объекта карты.
internal static byte[] gabyObjLenArray = {
0x00,0x0a,0x0e,0x15,0x0e,0x16,0x1b,0xa2,
0xa6,0xab,0x1a,0x2a,0x2f,0xa5,0xa9,0xb5,
0xa7,0xb5,0xd9,0x0f,0x17,0x23,0x13,0x1f,
0x2b,0x0f,0x17,0x23,0x4f,0x57,0x63,0x9c,
0xa4,0xa9,0xa0,0xa8,0xad,0xa4,0xa8,0xad,
0x16,0x1a,0x39,0x0d,0x11,0x37,0xa5,0xa9,
0xb5,0xa4,0xa8,0xad,0xb2,0xb6,0xdc,0xbd,
0xbd,0xf4,0x2b,0x2f,0x55,0xc8,0xcc,0xd8,
0xc7,0xcb,0xd0,0xd3,0xd7,0xfd,0xc2,0xc2,
0xf9};
//0x0 1 1 Header Block identifier (Value: 0x0) [!]
public Byte identifier;
//0x1 1 1 Header Block header
public Byte header;
//:
//:Unknown (For length of header data offset see 0x163)
//:
//0x33/0x2D/0x27/0x1F
//:
//: (Value 0x0 [!])
//: 0xFF
public byte[] Unknown = new byte[253];
//0x100 4 1 Magic Number (0x28757B2 i.e.42424242) [?]
public int MagicNumber;
// Установите допустимые значения по умолчанию для переменных.
/// <summary>
/// 0x104 2 1 Map File Version (not equal to table version)
/// </summary>
public short m_nMAPVersionNumber = HDR_VERSION_NUMBER;
/// <summary>
/// 0x106 2 1 Unknown value: 0x200 [!], BlockSize[??]
/// </summary>
short m_nBlockSize = Size;
/// <summary>
/// 0x108 8 1 CoordSysToDistUnits: Miles/LatDegree for Lat/Long maps 1.0 for all others [!]
/// </summary>
double m_dCoordsys2DistUnits = 1.0;
/// <summary>
/// 0x110 4 4 Coordinates of Minimum Bounding Rectangle (MBR)
/// </summary>
int m_nXMin = -1000000000;
int m_nYMin = -1000000000;
int m_nXMax = 1000000000;
int m_nYMax = 1000000000;
//m_bIntBoundsOverflow = FALSE;
/// 0x120 4 4 Coordinates of Default View of table
/// <summary>
/// 0x130 4 1 Offset of Object Definition Index (see also 0x15F)
/// </summary>
int m_nFirstIndexBlock = 0;
/// <summary>
/// 0x134 4 1 Offset of the beginning of Deleted Block sequence
/// </summary>
int m_nFirstGarbageBlock = 0;
/// <summary>
/// 0x138 4 1 Offset of Resources Block
/// </summary>
int m_nFirstToolBlock = 0;
/// <summary>
/// 0x13C 4 1 Number of Symbol elements
/// </summary>
int m_numPointObjects = 0;
/// <summary>
/// 0x140 4 1 Number of Line elements
/// </summary>
int m_numLineObjects = 0;
/// <summary>
/// 0x144 4 1 Number of Region elements
/// </summary>
int m_numRegionObjects = 0;
/// <summary>
/// 0x148 4 1 Number of Text elements
/// </summary>
int m_numTextObjects = 0;
/// <summary>
/// 0x14C 4 1 MaxCoordBufSize
/// </summary>
int m_nMaxCoordBufSize = 0;
/// 0x14E 14 1 14 Unknown bytes (Probably reserved and set to zero)
// For detailed information on distance unit values see:
// MapInfoProgramDirectory/Ut/Reproject/MapInfoUnits.db
/// <summary>
/// 0x15E Map File Distance Units
/// </summary>
byte m_nDistUnitsCode = 7; // Meters
/// <summary>
/// 0x15F 1 1 Type of Element Indexing data (see also 0x130)
/// 0 = NoData
/// 1 = Object Definition Block (NoIndex block)
/// 2 = Index Block
/// </summary>
byte m_nMaxSpIndexDepth = 0;
/// <summary>
/// 0x160 1 1 CoordPrecision
/// Value:6 for Lat/Long maps
/// Value:8 for Cartesian maps
/// Value:1 for Projected maps
/// </summary>
byte m_nCoordPrecision = 3; // ??? 3 Digits of precision
/// <summary>
/// 0x161 1 1 CoordOriginCode
/// Value:2 for Lat/Long maps
/// Value:1 for Cartesian and Projected maps
/// </summary>
byte m_nCoordOriginQuadrant = HDR_DEF_ORG_QUADRANT; // ???
/// <summary>
/// 0x162 1 1 ReflectAxisCode
/// Value:1 for Lat/Long maps
/// Value:0 for Cartesian and Projected maps
/// </summary>
byte m_nReflectXAxisCoord = HDR_DEF_REFLECTXAXIS;
/// <summary>
/// 0x163 1 1 ObjLenArraySize (at start of this block)
/// </summary>
byte m_nMaxObjLenArrayId = HDR_OBJ_LEN_ARRAY_SIZE - 1; // See gabyObjLenArray[]
/// <summary>
/// 0x164 1 1 Number of pen resources
/// </summary>
byte m_numPenDefs = 0;
/// <summary>
/// 0x165 1 1 Number of brush resources
/// </summary>
byte m_numBrushDefs = 0;
/// <summary>
/// 0x166 1 1 Number of symbol resources
/// </summary>
byte m_numSymbolDefs = 0;
/// <summary>
/// 0x167 1 1 Number of text resources
/// </summary>
byte m_numFontDefs = 0;
/// <summary>
/// 0x168 2 1 Number of Resource Blocks
/// </summary>
short m_numMapToolBlocks = 0;
TABProjInfo m_sProj = new TABProjInfo()
{
//0x16D 1 1 Projection type
nProjId = 0,
//0x16E 1 1 Datum (See also &H1C0, &H1C8, &H1D0)
nEllipsoidId = 0,
//&H16F 1 1 Units of coordinate system (Values equal to &H15E)
nUnitsId = 7
};
double m_XScale = 1000.0; // Default coord range (before SetCoordSysBounds())
double m_YScale = 1000.0; // will be [-1000000.000 .. 1000000.000]
double m_XDispl = 0.0;
double m_YDispl = 0.0;
#endregion
/// <summary>
/// Конструктор
/// </summary>
/// <param name="stream"></param>
public TABMAPHeaderBlock(byte[] block)
: base(block)
{
Position = 0x100;
Read(ref MagicNumber);
if (MagicNumber != HDR_MAGIC_COOKIE)
throw new IOException(string.Format("Неверный Magic Cookie: есть {0} /n ожидалось {1}", MagicNumber, HDR_MAGIC_COOKIE));
// Переменные-члены инициализации
// Вместо того, чтобы в течение 30 Get / Set методы, мы сделаем все члены данных общественности и мы будем инициализировать их здесь.
// По этой причине, этот класс следует использовать с осторожностью.
Read(ref m_nMAPVersionNumber);
Read(ref m_nBlockSize);
Read(ref m_dCoordsys2DistUnits);
Read(ref m_nXMin);
Read(ref m_nYMin);
Read(ref m_nXMax);
Read(ref m_nYMax);
Position = 0x130; // Skip 16 unknown bytes
Read(ref m_nFirstIndexBlock);
Read(ref m_nFirstGarbageBlock);
Read(ref m_nFirstToolBlock);
Read(ref m_numPointObjects);
Read(ref m_numLineObjects);
Read(ref m_numRegionObjects);
Read(ref m_numTextObjects);
Read(ref m_nMaxCoordBufSize);
Position = 0x15e; // Skip 14 unknown bytes
Read(ref m_nDistUnitsCode);
Read(ref m_nMaxSpIndexDepth);
Read(ref m_nCoordPrecision);
Read(ref m_nCoordOriginQuadrant);
Read(ref m_nReflectXAxisCoord);
Read(ref m_nMaxObjLenArrayId); // See gabyObjLenArray[]
Read(ref m_numPenDefs);
Read(ref m_numBrushDefs);
Read(ref m_numSymbolDefs);
Read(ref m_numFontDefs);
Read(ref m_numMapToolBlocks);
// DatumId никогда не был установлен (всегда 0), пока MapInfo 7.8. См ошибку 910
// MAP Номер версии составляет 500 в этом случае.
Read(ref m_sProj.nDatumId);
if (m_nMAPVersionNumber < HDR_VERSION_NUMBER) m_sProj.nDatumId = 0;
++Position; // Skip unknown byte
//&H16D 1 1 Projection type
Read(ref m_sProj.nProjId);
//&H16E 1 1 Datum (See also &H1C0, &H1C8, &H1D0)
Read(ref m_sProj.nEllipsoidId);
//&H16F 1 1 Units of coordinate system (Values equal to &H15E)
Read(ref m_sProj.nUnitsId);
Read(ref m_XScale);
Read(ref m_YScale);
Read(ref m_XDispl);
Read(ref m_YDispl);
// In V.100 files, the scale and displacement do not appear to be set.
// we'll use m_nCoordPrecision to define the scale factor instead.
//
if (m_nMAPVersionNumber <= 100)
{
m_XScale = m_YScale = Math.Pow(10.0, m_nCoordPrecision);
m_XDispl = m_YDispl = 0.0;
}
for (byte i = 0; i < 6; i++)
{
Read(ref m_sProj.adProjParams[i]);
}
Read(ref m_sProj.dDatumShiftX);
Read(ref m_sProj.dDatumShiftY);
Read(ref m_sProj.dDatumShiftZ);
// In V.200 files, the next 5 datum params are unused and they
// * sometimes contain junk bytes... in this case we set adDatumParams[]
// * to 0 for the rest of the lib to be happy.
for (byte i = 0; i < 5; i++)
{
Read(ref m_sProj.adDatumParams[i]);
if (m_nMAPVersionNumber <= 200)
m_sProj.adDatumParams[i] = 0.0;
}
}
public override void Add(byte[] block)
{
base.Add(block);
Position = 0;
//Array.Resize(ref read, TABRawBlock.Size * 2);
//Array.Copy(block.read, 0, read, TABRawBlock.Size, TABRawBlock.Size);
m_sProj.nAffineFlag = false;
//if (m_nMAPVersionNumber >= 500 && m_nSizeUsed > 512)
//{
// Read Affine parameters A,B,C,D,E,F
// only if version 500+ and block is larger than 512 bytes
byte nInUse = 0;
Read(ref nInUse);
if (nInUse != 0)
{
m_sProj.nAffineFlag = true;
Read(ref m_sProj.nAffineUnits);
Position += 6;
//0x0208; // Skip unused bytes
for (byte i = 0; i < 6; i++)
{
Read(ref m_sProj.dAffineParam[i]);
}
}
//}
}
}
internal class TABMAPIndexBlock : TABRawBlock
{
public TABMAPIndexBlock(byte[] block)
//: base(block)
{
Add(block);
}
public override void Add(byte[] block)
{
base.Add(block);
Position = 1;
if (link == null)
link = new byte[1];
else
Array.Resize(ref link, link.Length + 1);
Read(ref link[link.Length - 1]);
Read(ref m_numEntries);
//m_asEntries = new TABMAPIndexEntry[m_numEntries];
for (byte i = 0; i < m_numEntries; i++)
{
TABMAPIndexEntry tmp = new TABMAPIndexEntry();
Read(ref tmp.XMin);
Read(ref tmp.YMin);
Read(ref tmp.XMax);
Read(ref tmp.YMax);
Read(ref tmp.Id);
m_asEntries.Add(tmp);
}
}
#region
//Index Block header (length: &H4)
//---------------------------------------------------------------
//&H0 1 1 Index Block identifier (Value: &H1) [!]
//&H1 1 1 Link
public byte[] link; //= new byte[0];
//&H2 1 2 Number of Index data blocks
public short m_numEntries = 0;
//Index data (length: &H14)
//---------------------------------------------------------------
//&H0 4 4 Object Definition Block MBR (XMin, YMin, XMax, YMax)
//&H10 4 1 Object Definition Block offset
public List<TABMAPIndexEntry> m_asEntries = new List<TABMAPIndexEntry>();// = new TABMAPIndexEntry[TABMAPIndexEntry.TAB_MAX_ENTRIES_INDEX_BLOCK];
// Use these to keep track of current block's MBR
protected int m_nMinX = 1000000000;
protected int m_nMinY = 1000000000;
protected int m_nMaxX = -1000000000;
protected int m_nMaxY = -1000000000;
//protected TABBinBlockManager m_poBlockManagerRef;
// Info about child currently loaded
protected TABMAPIndexBlock m_poCurChild;
protected int m_nCurChildIndex;
// Also need to know about its parent
protected TABMAPIndexBlock m_poParentRef;
//int GetNumFreeEntries();
public int GetNumEntries()
{
return m_numEntries;
}
//TABMAPIndexEntry GetEntry(int iIndex);
//int AddEntry(TABMAPIndexEntry entry, bool bAddInThisNodeOnly);
//int GetCurMaxDepth();
//void GetMBR(ref int nXMin, ref int nYMin, ref int nXMax, ref int nYMax);
//public int GetNodeBlockPtr()
//{
// //return GetStartAddress();
//}
//C++ TO C# CONVERTER TODO TASK: The implementation of the following method could not be found:
// void SetMAPBlockManagerRef(ref TABBinBlockManager poBlockMgr);
//C++ TO C# CONVERTER TODO TASK: The implementation of the following method could not be found:
// void SetParentRef(TABMAPIndexBlock poParent);
//C++ TO C# CONVERTER TODO TASK: The implementation of the following method could not be found:
// void SetCurChildRef(TABMAPIndexBlock poChild, int nChildIndex);
public int GetCurChildIndex()
{
return m_nCurChildIndex;
}
public TABMAPIndexBlock GetCurChild()
{
return m_poCurChild;
}
public TABMAPIndexBlock GetParentRef()
{
return m_poParentRef;
}
// int SplitNode(GInt32 nNewEntryXMin, GInt32 nNewEntryYMin, GInt32 nNewEntryXMax, GInt32 nNewEntryYMax);
// int SplitRootNode(GInt32 nNewEntryXMin, GInt32 nNewEntryYMin, GInt32 nNewEntryXMax, GInt32 nNewEntryYMax);
// void UpdateCurChildMBR(GInt32 nXMin, GInt32 nYMin, GInt32 nXMax, GInt32 nYMax, GInt32 nBlockPtr);
// void RecomputeMBR();
// int InsertEntry(GInt32 XMin, GInt32 YMin, GInt32 XMax, GInt32 YMax, GInt32 nBlockPtr);
// int ChooseSubEntryForInsert(GInt32 nXMin, GInt32 nYMin, GInt32 nXMax, GInt32 nYMax);
// GInt32 ChooseLeafForInsert(GInt32 nXMin, GInt32 nYMin, GInt32 nXMax, GInt32 nYMax);
// int UpdateLeafEntry(GInt32 nBlockPtr, GInt32 nXMin, GInt32 nYMin, GInt32 nXMax, GInt32 nYMax);
// int GetCurLeafEntryMBR(GInt32 nBlockPtr, ref GInt32 nXMin, ref GInt32 nYMin, ref GInt32 nXMax, ref GInt32 nYMax);
// Static utility functions for node splitting, also used by the TABMAPObjectBlock class.
// static double ComputeAreaDiff(GInt32 nNodeXMin, GInt32 nNodeYMin, GInt32 nNodeXMax, GInt32 nNodeYMax, GInt32 nEntryXMin, GInt32 nEntryYMin, GInt32 nEntryXMax, GInt32 nEntryYMax);
// static int PickSeedsForSplit(ref TABMAPIndexEntry pasEntries, int numEntries, int nSrcCurChildIndex, GInt32 nNewEntryXMin, GInt32 nNewEntryYMin, GInt32 nNewEntryXMax, GInt32 nNewEntryYMax, ref int nSeed1, ref int nSeed2);
#endregion
}
/// <summary>
/// Class to handle Read/Write operation on .MAP Object data Blocks (Type 02)
/// </summary>
internal class TABMAPObjectBlock : TABRawBlock
{
public TABMAPObjectBlock(byte[] block)
//: base(block)
{
Add(block);
}
public override void Add(byte[] block)
{
base.Add(block);