-
Notifications
You must be signed in to change notification settings - Fork 13
/
p3dnga.cpp
744 lines (586 loc) · 17.9 KB
/
p3dnga.cpp
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
/***************************************************************************
Copyright (C) 2014 Sergey Prokhorchuk
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
***************************************************************************/
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <time.h>
#if defined(_MSC_VER)
#include <direct.h>
#else
#include <unistd.h>
#endif
#include <string>
#include <map>
#include "zipstore/zipstore.h"
#include <ngpcore/p3dcompat.h>
#include <ngpcore/p3diostream.h>
#include <ngput/p3dospath.h>
#include "p3dapp.h"
#include "p3dnga.h"
static bool IsValidFileNameChar(char c)
{
return (c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') ||
c == '_' ||
c == '-' ||
c == ' ';
}
static bool IsValidFileName (const char *FileName)
{
bool dot = false;
const char *c = FileName;
while (*c != '\0')
{
if (IsValidFileNameChar(*c) || *c == '/')
{
}
else if (*c == '.')
{
if (dot)
{
return false; // don't allow two consequent dots
}
}
else
{
return false;
}
dot = *c == '.';
c++;
}
return true;
}
static bool ShowConfirmationDialog
(const char *Message)
{
return wxMessageBox(wxString(Message,wxConvUTF8),
wxT("Confirmation"),
wxYES_NO | wxCANCEL) == wxYES;
}
static void DisplayErrorMessage(const char *Message)
{
::wxMessageBox(wxString(Message,wxConvUTF8),wxT("Error"),wxOK | wxICON_ERROR);
}
namespace {
class OutFileStream : public ZS::OutStream
{
public :
OutFileStream (const char *FileName);
virtual ~OutFileStream ();
virtual void Write (const void *Data,
size_t Size);
virtual unsigned long GetPos () const;
virtual void Seek (unsigned long Pos);
public :
FILE *File;
};
OutFileStream::OutFileStream (const char *FileName)
{
File = fopen(FileName,"wb");
if (File == NULL)
{
throw ZS::Error(ZS::Error::IO_ERROR);
}
}
OutFileStream::~OutFileStream ()
{
if (fclose(File) != 0)
{
throw ZS::Error(ZS::Error::IO_ERROR);
}
}
void
OutFileStream::Write (const void *Data,
size_t Size)
{
if (fwrite(Data,1,Size,File) != Size)
{
throw ZS::Error(ZS::Error::IO_ERROR);
}
}
unsigned long
OutFileStream::GetPos () const
{
return ftell(File);
}
void
OutFileStream::Seek (unsigned long Pos)
{
if (fseek(File,Pos,SEEK_SET) != 0)
{
throw ZS::Error(ZS::Error::IO_ERROR);
}
}
class OutputStringStream : public P3DOutputStringStream
{
public :
OutputStringStream (ZS::Writer &Writer);
virtual void WriteString (const char *Buffer);
virtual void AutoLnEnable ();
virtual void AutoLnDisable ();
private :
bool AutoLn;
ZS::Writer &Writer;
};
OutputStringStream::OutputStringStream
(ZS::Writer &_Writer)
: Writer(_Writer)
{
}
void OutputStringStream::WriteString
(const char *Buffer)
{
Writer.WriteData(Buffer,strlen(Buffer));
if (AutoLn)
{
Writer.WriteData("\n",1);
}
}
void OutputStringStream::AutoLnEnable
()
{
AutoLn = true;
}
void OutputStringStream::AutoLnDisable
()
{
AutoLn = false;
}
class NGAMaterialSaver : public P3DMaterialSaver
{
public :
virtual void Save (P3DOutputStringStream
*TargetStream,
const P3DMaterialInstance
*Material) const;
void SaveTextures (ZS::Writer &ZipWriter) const;
private :
void ProcessTextures (const P3DMaterialInstanceSimple
*Material,
P3DMaterialDef *MaterialDef) const;
void ProcessTexture (P3DMaterialDef *MaterialDef,
unsigned int TexLayer,
const char *TexName,
const char *FileName) const;
void SaveTexture (ZS::Writer &ZipWriter,
const char *TexName,
const char *FileName) const;
static
std::string TexName2NGATexName (const char *TexName);
typedef std::map<std::string,std::string> TextureBindings;
mutable TextureBindings Textures;
};
void NGAMaterialSaver::Save
(P3DOutputStringStream
*TargetStream,
const P3DMaterialInstance
*Material) const
{
const P3DMaterialInstanceSimple
*MaterialImpl = (const P3DMaterialInstanceSimple*)Material;
const P3DMaterialDef *OriginalMaterialDef = Material->GetMaterialDef();
P3DMaterialDef NewMaterialDef(*OriginalMaterialDef);
ProcessTextures(MaterialImpl,&NewMaterialDef);
NewMaterialDef.Save(TargetStream);
}
void NGAMaterialSaver::SaveTextures
(ZS::Writer &ZipWriter) const
{
for (TextureBindings::const_iterator Iter = Textures.begin();
Iter != Textures.end();
++Iter)
{
const char *TexName = Iter->first.c_str();
const char *FileName = Iter->second.c_str();
if (!IsValidFileName(TexName))
{
wxString message = wxString::Format(wxT("Texture name %s contains invalid character(s)"),TexName);
throw P3DExceptionGeneric(message.mb_str());
}
SaveTexture(ZipWriter,TexName,FileName);
}
}
void NGAMaterialSaver::SaveTexture
(ZS::Writer &ZipWriter,
const char *TexName,
const char *FileName) const
{
FILE *SrcFile;
SrcFile = fopen(FileName,"rb");
if (SrcFile == NULL)
{
throw P3DExceptionGeneric("Unable to open texture file");
}
try
{
ZipWriter.BeginFile(TexName,time(NULL));
char Buffer[8 * 1024];
size_t Size;
do
{
Size = fread(Buffer,1,sizeof(Buffer),SrcFile);
if (Size > 0)
{
ZipWriter.WriteData(Buffer,Size);
}
} while (Size == sizeof(Buffer));
if (ferror(SrcFile))
{
throw P3DExceptionGeneric("Texture file read error");
}
fclose(SrcFile);
}
catch (...)
{
fclose(SrcFile);
throw;
}
}
class InFileStream : public ZS::InStream
{
public :
InFileStream (const char *fileName);
virtual ~InFileStream ();
virtual void Read (void *dest,
size_t size);
virtual unsigned long GetSize () const;
virtual unsigned long GetPos () const;
virtual void Seek (unsigned long pos);
public :
FILE *file;
};
InFileStream::InFileStream (const char *fileName)
{
file = fopen(fileName,"rb");
if (file == NULL)
{
throw ZS::Error(ZS::Error::IO_ERROR);
}
}
InFileStream::~InFileStream ()
{
if (fclose(file) != 0)
{
throw ZS::Error(ZS::Error::IO_ERROR);
}
}
void
InFileStream::Read (void *dest,
size_t size)
{
if (fread(dest,1,size,file) != size)
{
throw ZS::Error(ZS::Error::IO_ERROR);
}
}
unsigned long
InFileStream::GetSize () const
{
unsigned long currPos = GetPos();
if (fseek(file,0,SEEK_END) != 0)
{
throw ZS::Error(ZS::Error::IO_ERROR);
}
unsigned long size = GetPos();
if (fseek(file,currPos,SEEK_SET) != 0)
{
throw ZS::Error(ZS::Error::IO_ERROR);
}
return size;
}
unsigned long
InFileStream::GetPos () const
{
return ftell(file);
}
void
InFileStream::Seek (unsigned long pos)
{
if (fseek(file,pos,SEEK_SET) != 0)
{
throw ZS::Error(ZS::Error::IO_ERROR);
}
}
void NGAMaterialSaver::ProcessTextures
(const P3DMaterialInstanceSimple
*Material,
P3DMaterialDef *MaterialDef) const
{
for (unsigned int LayerIndex = 0; LayerIndex < P3D_MAX_TEX_LAYERS; LayerIndex++)
{
const char *TexName = MaterialDef->GetTexName(LayerIndex);
if (TexName != 0)
{
const char *FileName = Material->GetTexFileName(LayerIndex);
if (FileName != 0)
{
ProcessTexture(MaterialDef,LayerIndex,TexName,FileName);
}
}
}
}
void NGAMaterialSaver::ProcessTexture
(P3DMaterialDef *MaterialDef,
unsigned int TexLayer,
const char *TexName,
const char *FileName) const
{
std::string NGATexName = TexName2NGATexName(TexName);
TextureBindings::const_iterator Entry = Textures.find(NGATexName);
std::string FileNameStr(FileName);
if (Entry == Textures.end())
{
Textures[NGATexName] = FileNameStr;
}
else if (Entry->second == FileNameStr)
{
// Textures array already contains this texture
}
else
{
throw P3DExceptionGeneric(".NGA doesn't support several textures with the same base name");
}
MaterialDef->SetTexName(TexLayer,P3DPathName::BaseName(TexName).c_str());
}
std::string NGAMaterialSaver::TexName2NGATexName
(const char *TexName)
{
std::string BaseName = P3DPathName::BaseName(TexName);
return std::string(P3D_LOCAL_TEXTURES_PATH) + "/" + BaseName;
}
}
static void SaveModel (ZS::Writer &ZipWriter,
NGAMaterialSaver &MaterialSaver)
{
wxString NGPFileName(P3DApp::GetApp()->GetDerivedFileName(wxString("ngp",wxConvUTF8)));
if (!IsValidFileName(NGPFileName.mb_str()))
{
wxString message = wxString::Format(wxT("Model file name %s contains invalid character(s)"),NGPFileName.mb_str().data());
throw P3DExceptionGeneric(message.mb_str());
}
ZipWriter.BeginFile(NGPFileName.mb_str(),time(NULL));
OutputStringStream OutputStream(ZipWriter);
P3DApp::GetApp()->GetModel()->Save(&OutputStream,&MaterialSaver);
}
static void SaveTextures (ZS::Writer &ZipWriter,
NGAMaterialSaver &MaterialSaver)
{
MaterialSaver.SaveTextures(ZipWriter);
}
static void WriteNGPToNGA (ZS::Writer &ZipWriter)
{
NGAMaterialSaver MaterialSaver;
SaveModel(ZipWriter,MaterialSaver);
SaveTextures(ZipWriter,MaterialSaver);
}
static void ExportToFile (const char *FileName)
{
OutFileStream OutStream(FileName);
ZS::Writer ZipWriter(OutStream);
WriteNGPToNGA(ZipWriter);
ZipWriter.Close();
}
void P3DNGAExport ()
{
wxString FileName;
FileName = ::wxFileSelector(wxT("File name"),
wxT(""),
P3DApp::GetApp()->GetDerivedFileName(wxT("nga")),
wxT(".nga"),
wxT("*.nga"),
wxFD_SAVE | wxFD_OVERWRITE_PROMPT);
if (!FileName.empty())
{
try
{
ExportToFile(FileName.mb_str());
}
catch (P3DException &e)
{
DisplayErrorMessage(e.GetMessage());
}
catch (ZS::Error &e)
{
DisplayErrorMessage(e.GetMessage());
}
}
}
static bool FileExists (const char *FileName)
{
struct stat Info;
return stat(FileName,&Info) == 0;
}
static void MkDir (const char *DirName)
{
#if !defined(_WIN32)
if (mkdir(DirName,0777) != 0)
#else
if (mkdir(DirName) != 0)
#endif
{
throw P3DExceptionGeneric("unable to create directory");
}
}
static void MkDirIfNotExists (const char *DirName)
{
if (!FileExists(DirName))
{
MkDir(DirName);
}
}
static FILE *CreateFileInDir (const char *FileName,
const char *DirName)
{
std::string DirPrefix(DirName);
const char *Ptr = strchr(FileName,'/');
while (Ptr != NULL)
{
std::string PartDirName = DirPrefix + '/' + std::string(FileName,Ptr - FileName);
MkDirIfNotExists(PartDirName.c_str());
Ptr = strchr(Ptr + 1,'/');
}
std::string FullFileName(DirPrefix + '/' + FileName);
if (FileExists(FullFileName.c_str()))
{
std::string ConfirmationMessage(std::string("Do you want to overwrite file ") + FullFileName + "?");
if (!ShowConfirmationDialog(ConfirmationMessage.c_str()))
{
throw P3DExceptionGeneric("Import cancelled");
}
}
FILE *DestFile = fopen(FullFileName.c_str(),"wb");
if (DestFile == NULL)
{
throw P3DExceptionGeneric("unable to create file");
}
return DestFile;
}
static void UnpackIntoFile (FILE *DestFile,
ZS::Reader::File &SrcFile)
{
char Buffer[8 * 1024];
size_t BytesToCopy;
size_t BytesToRead;
BytesToCopy = SrcFile.GetSize();
BytesToRead = sizeof(Buffer);
while (BytesToCopy > 0)
{
if (BytesToRead > BytesToCopy)
{
BytesToRead = BytesToCopy;
}
SrcFile.Read(Buffer,BytesToRead);
if (fwrite(Buffer,1,BytesToRead,DestFile) != BytesToRead)
{
throw P3DExceptionGeneric("file write error");
}
BytesToCopy -= BytesToRead;
}
}
static void UnpackFileFromZip (const char *DestDir,
ZS::Reader::File &File)
{
FILE *DestFile;
const char *FileName;
FileName = File.GetName();
if (!IsValidFileName(FileName))
{
throw P3DExceptionGeneric("invalid filename inside .nga archive found");
}
DestFile = CreateFileInDir(FileName,DestDir);
UnpackIntoFile(DestFile,File);
if (fclose(DestFile) != 0)
{
throw P3DExceptionGeneric("error while unpacking file");
}
}
static bool StrEqualIgnoreCase (const char *S1,
const char *S2)
{
while (tolower(*S1) == tolower(*S2) && *S1 != '\0' && *S2 != '\0')
{
S1++;
S2++;
}
return *S1 == *S2;
}
static bool IsNGPFile (const char *FileName)
{
P3DPathName PathName(FileName);
return StrEqualIgnoreCase(PathName.GetExtension().c_str(),"ngp");
}
static std::string UnpackNGA (const char *DestDir,
ZS::Reader &Reader)
{
std::string NGPFileName;
Reader.SeekFirst();
while (!Reader.IsEOF())
{
ZS::Reader::File CurrFile = Reader.GetFile();
if (IsNGPFile(CurrFile.GetName()))
{
if (NGPFileName.empty())
{
NGPFileName = CurrFile.GetName();
}
else
{
throw P3DExceptionGeneric(".nga file is broken - it contains more than one .ngp entry");
}
}
UnpackFileFromZip(DestDir,CurrFile);
Reader.SeekNext();
}
if (NGPFileName.empty())
{
throw P3DExceptionGeneric(".nga file is broken - it does not contain .ngp entry");
}
return std::string(DestDir) + '/' + NGPFileName;
}
static std::string ImportFromFile (const char *DestDir,
const char *FileName)
{
InFileStream InStream(FileName);
ZS::Reader Reader(InStream);
MkDirIfNotExists(DestDir);
return UnpackNGA(DestDir,Reader);
}
std::string P3DNGAImport ()
{
std::string NGPFileName;
wxString FileName;
FileName = ::wxFileSelector(wxT("File name"),wxT(""),wxT(""),wxT(".nga"),wxT("*.nga"),wxFD_OPEN | wxFD_FILE_MUST_EXIST);
if (!FileName.empty())
{
wxString DestDir = ::wxDirSelector(wxT("Choose a folder to unpack .nga to"));
if (!DestDir.empty())
{
try
{
NGPFileName = ImportFromFile(DestDir.mb_str(),FileName.mb_str());
}
catch (P3DException &e)
{
DisplayErrorMessage(e.GetMessage());
}
catch (ZS::Error &e)
{
DisplayErrorMessage(e.GetMessage());
}
}
}
return NGPFileName;
}