aboutsummaryrefslogtreecommitdiff
path: root/tools/lzpack/main.cpp
blob: f684d188fd5f381a6f1c4ed7b8f5abc9c1b87fce (plain) (blame)
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
#include <stdio.h>
#include <tinyxml2.h>

#include "lzconfig.h"
#include "lzp.h"
#include "filelist.h"


#define BUFF_SIZE	4096


typedef struct {
	char			id[3];
	unsigned char	numFiles;
} QLP_HEAD;

typedef struct {
	char			fileName[16];
	unsigned int	fileSize;
	unsigned int	offset;
} QLP_FILE;


typedef struct {
	char			name[16];
	unsigned int	size;
	unsigned int	offset;			// In 2048 byte sector units
} PCK_FILE;

typedef struct {
	char		id[3];
	u_char		numFiles;
	PCK_FILE	file[85];	// File entries
	int			lba;		// LBA of the PCK file (in 2048 byte sector units)
} PCK_TOC;


namespace param {

	bool	AlwaysOverwrite		= false;
	char	ScriptFile[MAX_PATH]= { 0 };

}


int ParseCreateElement(tinyxml2::XMLElement* element);

char* lcase(char* str);
const char* TrimPathName(const char* path);


int main(int argc, const char* argv[]) {

    printf("LZPack v0.61b - File Compression and Packing Utility\n");
    printf("2016-2019 Meido-Tek Productions (Lameguy64)\n\n");

	if (argc <= 1) {

		printf("Parameters:\n");
		printf("   lzpack [-y] <scriptFile>\n\n");
		printf("   -y           - Always overwrite existing files.\n");
		printf("   <scriptFile> - Script file to parse (in XML format, see readme.txt).\n");

		exit(0);

	}


	// Parse arguments
	for(int i=1; i<argc; i++) {

        if (strcmp("-y", argv[i]) == 0) {

			param::AlwaysOverwrite = true;

        } else if ((argv[i][0] == '-') || (argv[i][0] == '/')) {

			printf("Unknown parameter: %s\n", argv[i]);

        } else {

        	strcpy(param::ScriptFile, argv[i]);

        }

	}

	if (strlen(param::ScriptFile) == 0) {
		printf("ERROR: No script file specified.\n");
		exit(EXIT_FAILURE);
	}


	tinyxml2::XMLDocument document;

	switch(document.LoadFile(param::ScriptFile)) {
	case tinyxml2::XML_SUCCESS:

		break;

	case tinyxml2::XML_ERROR_FILE_NOT_FOUND:

		printf("ERROR: Could not find file: %s\n", param::ScriptFile);
		exit(EXIT_FAILURE);

	case tinyxml2::XML_ERROR_FILE_COULD_NOT_BE_OPENED:
	case tinyxml2::XML_ERROR_FILE_READ_ERROR:

		printf("ERROR: Could not load file: %s\n", param::ScriptFile);
		exit(EXIT_FAILURE);

	case tinyxml2::XML_ERROR_EMPTY_DOCUMENT:

		printf("ERROR: %s is empty.\n", param::ScriptFile);
		exit(EXIT_FAILURE);

	default:

		printf("ERROR: Unknown error when loading %s\n", param::ScriptFile);
		exit(EXIT_FAILURE);

	}


    tinyxml2::XMLElement* element = document.FirstChildElement("lzp_project");

	if (element == NULL) {

		printf("ERROR: <lzp_project> element not found.\n");
		exit(EXIT_FAILURE);

	}


	tinyxml2::XMLElement* createElement = element->FirstChildElement("create");

	while(createElement != NULL) {

		ParseCreateElement(createElement);

		createElement = createElement->NextSiblingElement();

	}


    return(0);

}


int CreateLZPfile(const char* packFile, FileListClass* fileList) {

	FILE*		packp;
	LZP_FILE*	entry=new LZP_FILE[fileList->EntryCount()];
	int			overallSize=0;
	int			overallPackedSize=0;

    packp = fopen(packFile, "wb");

    fseek(packp, sizeof(LZP_HEAD)+(sizeof(LZP_FILE)*fileList->EntryCount()), SEEK_SET);

	for(int i=0; i<fileList->EntryCount(); i++) {

        const char* name;

        if (fileList->Entry(i)->aliasName == NULL) {

			name = TrimPathName(fileList->Entry(i)->fileName);

        } else {

        	name = fileList->Entry(i)->aliasName;

        }

        if (strlen(name) > 15) {

            printf("ERROR: Entry '%s' has more than 15 characters.\n", name);
            fclose(packp);
            unlink(packFile);
            delete entry;

            return(0);

        }

		strcpy(entry[i].fileName, name);

		if (fileList->Entry(i)->aliasName == NULL) {
			printf("   Packing %s... ", fileList->Entry(i)->fileName);
		} else {
			printf("   Packing %s as %s... ", fileList->Entry(i)->fileName, fileList->Entry(i)->aliasName);
		}


		FILE*	fp = fopen(fileList->Entry(i)->fileName, "rb");

		fseek(fp, 0, SEEK_END);
        int fileSize = ftell(fp);
		fseek(fp, 0, SEEK_SET);

        char* fileBuff = new char[fileSize];
		fread(fileBuff, fileSize, 1, fp);

		fclose(fp);


        char*	compBuff = new char[fileSize+16384];
        int		compSize = lzCompress(compBuff, fileBuff, fileSize, 2);


        entry[i].crc		= lzCRC32(compBuff, compSize, LZP_CRC32_REMAINDER);
		entry[i].fileSize	= fileSize;
		entry[i].packedSize	= compSize;
        entry[i].offset		= ftell(packp);

        fwrite(compBuff, compSize, 1, packp);

        delete compBuff;
        delete fileBuff;

		printf("Ok. (%.02f%%)\n", 100.f*((float)compSize/fileSize));

		overallSize			+= fileSize;
		overallPackedSize	+= compSize;

	}


    LZP_HEAD head;

    strncpy(head.id, "LZP", sizeof(head.id));
    head.numFiles = fileList->EntryCount();

	fseek(packp, 0, SEEK_SET);
	fwrite(&head, sizeof(LZP_HEAD), 1, packp);

    fwrite(entry, sizeof(LZP_FILE), fileList->EntryCount(), packp);

	fclose(packp);
	delete entry;

    printf("Packed %d file(s) totaling %d bytes (%.02f%% compression ratio).\n",
		fileList->EntryCount(),
		overallPackedSize,
		100.f*((float)overallPackedSize/overallSize)
	);


	return(true);

}

int CreateQLPfile(const char* packFile, FileListClass* fileList) {

    FILE*		packp;
	QLP_HEAD	head;
	QLP_FILE*	fileEntry=new QLP_FILE[fileList->EntryCount()];

	strncpy(head.id, "QLP", 3);
	head.numFiles = fileList->EntryCount();

	packp = fopen(packFile, "wb");

	fseek(packp, sizeof(QLP_HEAD)+(sizeof(QLP_FILE)*head.numFiles), SEEK_SET);

	for(int i=0; i<head.numFiles; i++) {

		// Get name for the file entry either from its source file name or specified alias
		const char* name;

        if (fileList->Entry(i)->aliasName == NULL) {

			name = TrimPathName(fileList->Entry(i)->fileName);

        } else {

        	name = fileList->Entry(i)->aliasName;

        }

		// Make sure entry name does not exceed 15 characters (16 with null terminator byte)
        if (strlen(name) > 15) {

            printf("ERROR: Entry '%s' has more than 15 characters.\n", name);
            fclose(packp);
            unlink(packFile);
            delete fileEntry;

            return(0);

        }

		strcpy(fileEntry[i].fileName, name);

		if (fileList->Entry(i)->aliasName == NULL) {

			printf("   Packing %s... ", fileList->Entry(i)->fileName);

		} else {

			printf("   Packing %s as %s... ", fileList->Entry(i)->fileName, fileList->Entry(i)->aliasName);

		}

		// Make sure written data is aligned in multiples of 4 bytes
		if ((4*((ftell(packp)+3)/4)) != ftell(packp))
			fseek(packp, (4*((ftell(packp)+3)/4)), SEEK_SET);

		// Set name and offset of file entry
		memset(fileEntry[i].fileName, 0x00, 16);
		strcpy(fileEntry[i].fileName, name);
		fileEntry[i].offset = ftell(packp);

		// Open file and copy its contents to the pack file
		FILE* fp = fopen(fileList->Entry(i)->fileName, "rb");

		int bytesCopied = 0;
		char* copyBuff = new char[BUFF_SIZE];

		while(!feof(fp)) {

			int bytesRead = fread(copyBuff, 1, BUFF_SIZE, fp);

			fwrite(copyBuff, bytesRead, 1, packp);

            bytesCopied += bytesRead;

		}

		delete copyBuff;
		fclose(fp);

		fileEntry[i].fileSize = bytesCopied;

		printf("Done.\n");

	}

	printf("Packed %d file(s) totaling %d bytes.\n", head.numFiles, (int)ftell(packp));

	fseek(packp, 0, SEEK_SET);
	fwrite(&head, sizeof(QLP_HEAD), 1, packp);

	fwrite(fileEntry, sizeof(QLP_FILE), head.numFiles, packp);

	fclose(packp);
	delete fileEntry;

	return(true);

}

int CreatePCKfile(const char* packFile, FileListClass* fileList) {

	FILE*	packp;
	PCK_TOC	toc;

	memset(&toc, 0x00, sizeof(PCK_TOC));

	toc.numFiles = fileList->EntryCount();

    packp = fopen(packFile, "wb");

	fseek(packp, 2048, SEEK_SET);

	for(int i=0; i<toc.numFiles; i++) {

		// Get name for the file entry either from its source file name or specified alias
		const char* name;

        if (fileList->Entry(i)->aliasName == NULL) {

			name = TrimPathName(fileList->Entry(i)->fileName);

        } else {

        	name = fileList->Entry(i)->aliasName;

        }

		// Make sure entry name does not exceed 15 characters (16 with null terminator byte)
        if (strlen(name) > 15) {

            printf("ERROR: Entry '%s' has more than 15 characters.\n", name);
            fclose(packp);
            unlink(packFile);

            return(0);

        }

		strcpy(toc.file[i].name, name);
		toc.file[i].offset = ftell(packp)/2048;

		if (fileList->Entry(i)->aliasName == NULL) {

			printf("   Packing %s... ", fileList->Entry(i)->fileName);

		} else {

			printf("   Packing %s as %s... ", fileList->Entry(i)->fileName, fileList->Entry(i)->aliasName);

		}

		FILE* fp = fopen(fileList->Entry(i)->fileName, "rb");
		char* buff = new char[BUFF_SIZE];

		int bytesTotal = 0;

        while(!feof(fp)) {

			int bytesRead = fread(buff, 1, BUFF_SIZE, fp);
            fwrite(buff, 1, bytesRead, packp);
			bytesTotal += bytesRead;

        }

		fclose(fp);
		delete buff;

		toc.file[i].size = bytesTotal;

		if ((2048*((ftell(packp)+2047)/2048)) != ftell(packp)) {

			int pad = (2048*(((ftell(packp)%2048)+2047)/2048))-(ftell(packp)%2048);
			char* padding = new char[pad];

			memset(padding, 0x00, pad);
			fwrite(padding, pad, 1, packp);
			delete padding;
		}

		printf("Done.\n");

	}

    printf("Packed %d file(s) totaling %d bytes.\n", toc.numFiles, (int)ftell(packp));

	strncpy(toc.id, "PCK", 3);

    fseek(packp, 0, SEEK_SET);
    fwrite(&toc, sizeof(PCK_TOC), 1, packp);

    fclose(packp);

	return(true);

}

int ParseCreateElement(tinyxml2::XMLElement* element) {


	const char* packName = element->Attribute("packname");

    if (packName == NULL) {
		printf("ERROR: No 'packname' attribute found in <create> element.\n");
		return(false);
    }


	int	packFormat;

	{

		char*		packType = (char*)element->Attribute("format");

		if (packType == NULL) {

			packType = strdup("lzp");

		} else {

			packType = strdup(packType);
			lcase(packType);

		}

		if (strcmp("lzp", packType) == 0) {
			packFormat = 0;
		} else if (strcmp("qlp", packType) == 0) {
			packFormat = 1;
		} else if (strcmp("pck", packType) == 0) {
			packFormat = 2;
		} else {

			printf("ERROR: Unknown pack format: %s\n", packType);
			free(packType);
			return(false);

		}

		free(packType);

	}


	printf("Creating %s in ", packName);
	switch(packFormat) {
	case 0:

		printf("LZP");
		break;

	case 1:

		printf("QLP");
		break;

	case 2:

		printf("PCK");
		break;

	}
	printf(" format...\n");


	tinyxml2::XMLElement* fileElement = element->FirstChildElement("file");

	if (fileElement == NULL) {
		printf("ERROR: No file element(s) found.\n");
		return(false);
	}


    FileListClass fileList;

    while(1) {

		bool	valid = true;

		int		entryWindowSize = LZP_WINDOW_SIZE;
		int		entryHash1Size	= LZP_HASH1_SIZE;
		int		entryHash2Size	= LZP_HASH2_SIZE;

		if (fileElement->GetText() == NULL) {
			printf("WARNING: <file> element not containing text found.\n");
			valid = false;
		}


		FILE* fp = fopen(fileElement->GetText(), "rb");
		if (!fp) {
			printf("WARNING: File '%s' either does not exist or it cannot be opened.\n", fileElement->GetText());
			valid = false;
		}
		fclose(fp);


		if (valid) {
			fileList.AddFileEntry(
				fileElement->GetText(),
				fileElement->Attribute("alias"),
				entryWindowSize,
				entryHash1Size,
				entryHash2Size
			);
		}


		fileElement = fileElement->NextSiblingElement();

		if (fileElement == NULL)
			break;

    }


	if (fileList.EntryCount() == 0) {
		printf("No file(s) to pack.\n");
		return(true);
	}

	switch(packFormat) {
	case 0:	// Create LZP
		CreateLZPfile(packName, &fileList);
		break;
	case 1:	// Create QLP
		CreateQLPfile(packName, &fileList);
		break;
	case 2:	// Create PCK
		CreatePCKfile(packName, &fileList);
		break;
	}


    return(true);

}


const char* TrimPathName(const char* path) {

    if ((strrchr(path, '\\') == NULL) && (strrchr(path, '/') == NULL)) {

        return(path);

    } else {

		if (strrchr(path, '\\') == NULL)
			return(strrchr(path, '/')+1);

		return(strrchr(path, '\\')+1);

    }

}

char* lcase(char* str) {

	for(int i=0; str[i]!=0x00; i++)
		str[i] = tolower(str[i]);

	return(str);

}