From 102c3742487dba76ec72d5f56a2c3041344b2d68 Mon Sep 17 00:00:00 2001 From: Sebastian Leonhardt Date: Fri, 8 Jan 2016 01:05:36 +0100 Subject: added xrick game original xrick code by 'BigOrno' at: http://www.bigorno.net/xrick/ Rockbox port, plus bugfixes at: https://github.com/pierluigi-vicinanza/xrick Further changes: * Additonal fixes from g#3026 * Port to modern plugin API * Add Pluginlib keymap fallback * Support all >1bpp screens * Fix build warnings in miniz * Better error message when resources are missing Change-Id: Id83928bc2539901b0221692f65cbca41389c58e7 --- apps/plugins/CATEGORIES | 1 + apps/plugins/SUBDIRS | 4 + apps/plugins/xrick/3rd_party/miniz/miniz.c | 4928 +++++++++++++++++++++++++ apps/plugins/xrick/README.md | 88 + apps/plugins/xrick/README.rockbox | 16 + apps/plugins/xrick/SOURCES | 40 + apps/plugins/xrick/config.h | 58 + apps/plugins/xrick/control.c | 24 + apps/plugins/xrick/control.h | 41 + apps/plugins/xrick/data/img.c | 23 + apps/plugins/xrick/data/img.h | 39 + apps/plugins/xrick/data/pics.c | 29 + apps/plugins/xrick/data/pics.h | 41 + apps/plugins/xrick/data/sounds.c | 44 + apps/plugins/xrick/data/sounds.h | 87 + apps/plugins/xrick/data/sprites.c | 22 + apps/plugins/xrick/data/sprites.h | 70 + apps/plugins/xrick/data/tiles.c | 22 + apps/plugins/xrick/data/tiles.h | 70 + apps/plugins/xrick/debug.h | 84 + apps/plugins/xrick/devtools.c | 247 ++ apps/plugins/xrick/devtools.h | 25 + apps/plugins/xrick/draw.c | 702 ++++ apps/plugins/xrick/draw.h | 65 + apps/plugins/xrick/e_bomb.c | 158 + apps/plugins/xrick/e_bomb.h | 36 + apps/plugins/xrick/e_bonus.c | 60 + apps/plugins/xrick/e_bonus.h | 25 + apps/plugins/xrick/e_box.c | 109 + apps/plugins/xrick/e_box.h | 25 + apps/plugins/xrick/e_bullet.c | 84 + apps/plugins/xrick/e_bullet.h | 32 + apps/plugins/xrick/e_rick.c | 606 +++ apps/plugins/xrick/e_rick.h | 50 + apps/plugins/xrick/e_sbonus.c | 88 + apps/plugins/xrick/e_sbonus.h | 30 + apps/plugins/xrick/e_them.c | 738 ++++ apps/plugins/xrick/e_them.h | 31 + apps/plugins/xrick/ents.c | 540 +++ apps/plugins/xrick/ents.h | 118 + apps/plugins/xrick/game.c | 722 ++++ apps/plugins/xrick/game.h | 73 + apps/plugins/xrick/maps.c | 253 ++ apps/plugins/xrick/maps.h | 159 + apps/plugins/xrick/rects.c | 57 + apps/plugins/xrick/rects.h | 32 + apps/plugins/xrick/res_magic.c | 18 + apps/plugins/xrick/resources.c | 1297 +++++++ apps/plugins/xrick/resources.h | 165 + apps/plugins/xrick/scr_gameover.c | 92 + apps/plugins/xrick/scr_getname.c | 290 ++ apps/plugins/xrick/scr_imain.c | 170 + apps/plugins/xrick/scr_imap.c | 293 ++ apps/plugins/xrick/scr_pause.c | 50 + apps/plugins/xrick/scr_xrick.c | 101 + apps/plugins/xrick/screens.h | 74 + apps/plugins/xrick/scroller.c | 165 + apps/plugins/xrick/scroller.h | 31 + apps/plugins/xrick/system/basic_funcs.c | 33 + apps/plugins/xrick/system/basic_funcs.h | 141 + apps/plugins/xrick/system/basic_types.h | 48 + apps/plugins/xrick/system/main_rockbox.c | 43 + apps/plugins/xrick/system/miniz_config.h | 38 + apps/plugins/xrick/system/rockboxcodes.h | 110 + apps/plugins/xrick/system/sysarg_rockbox.c | 49 + apps/plugins/xrick/system/sysevt_rockbox.c | 156 + apps/plugins/xrick/system/sysfile_rockbox.c | 122 + apps/plugins/xrick/system/sysmem_rockbox.c | 156 + apps/plugins/xrick/system/sysmenu_rockbox.c | 200 + apps/plugins/xrick/system/sysmenu_rockbox.h | 32 + apps/plugins/xrick/system/syssnd_rockbox.c | 483 +++ apps/plugins/xrick/system/syssnd_rockbox.h | 48 + apps/plugins/xrick/system/system.h | 178 + apps/plugins/xrick/system/system_rockbox.c | 262 ++ apps/plugins/xrick/system/sysvid_rockbox.c | 402 ++ apps/plugins/xrick/util.c | 230 ++ apps/plugins/xrick/util.h | 29 + apps/plugins/xrick/xrick.make | 31 + docs/CREDITS | 127 +- manual/plugins/images/ss-xrick-220x176x16.png | Bin 0 -> 7938 bytes manual/plugins/images/ss-xrick-240x320x16.png | Bin 0 -> 9160 bytes manual/plugins/images/ss-xrick-320x240x16.png | Bin 0 -> 9346 bytes manual/plugins/main.tex | 5 + manual/plugins/xrick.tex | 107 + utils/rbutilqt/base/playerbuildinfo.cpp | 1 + utils/rbutilqt/base/playerbuildinfo.h | 1 + utils/rbutilqt/gui/selectiveinstallwidget.cpp | 1 + utils/rbutilqt/rbutil.ini | 1 + 88 files changed, 16514 insertions(+), 62 deletions(-) create mode 100644 apps/plugins/xrick/3rd_party/miniz/miniz.c create mode 100644 apps/plugins/xrick/README.md create mode 100644 apps/plugins/xrick/README.rockbox create mode 100644 apps/plugins/xrick/SOURCES create mode 100644 apps/plugins/xrick/config.h create mode 100644 apps/plugins/xrick/control.c create mode 100644 apps/plugins/xrick/control.h create mode 100644 apps/plugins/xrick/data/img.c create mode 100644 apps/plugins/xrick/data/img.h create mode 100644 apps/plugins/xrick/data/pics.c create mode 100644 apps/plugins/xrick/data/pics.h create mode 100644 apps/plugins/xrick/data/sounds.c create mode 100644 apps/plugins/xrick/data/sounds.h create mode 100644 apps/plugins/xrick/data/sprites.c create mode 100644 apps/plugins/xrick/data/sprites.h create mode 100644 apps/plugins/xrick/data/tiles.c create mode 100644 apps/plugins/xrick/data/tiles.h create mode 100644 apps/plugins/xrick/debug.h create mode 100644 apps/plugins/xrick/devtools.c create mode 100644 apps/plugins/xrick/devtools.h create mode 100644 apps/plugins/xrick/draw.c create mode 100644 apps/plugins/xrick/draw.h create mode 100644 apps/plugins/xrick/e_bomb.c create mode 100644 apps/plugins/xrick/e_bomb.h create mode 100644 apps/plugins/xrick/e_bonus.c create mode 100644 apps/plugins/xrick/e_bonus.h create mode 100644 apps/plugins/xrick/e_box.c create mode 100644 apps/plugins/xrick/e_box.h create mode 100644 apps/plugins/xrick/e_bullet.c create mode 100644 apps/plugins/xrick/e_bullet.h create mode 100644 apps/plugins/xrick/e_rick.c create mode 100644 apps/plugins/xrick/e_rick.h create mode 100644 apps/plugins/xrick/e_sbonus.c create mode 100644 apps/plugins/xrick/e_sbonus.h create mode 100644 apps/plugins/xrick/e_them.c create mode 100644 apps/plugins/xrick/e_them.h create mode 100644 apps/plugins/xrick/ents.c create mode 100644 apps/plugins/xrick/ents.h create mode 100644 apps/plugins/xrick/game.c create mode 100644 apps/plugins/xrick/game.h create mode 100644 apps/plugins/xrick/maps.c create mode 100644 apps/plugins/xrick/maps.h create mode 100644 apps/plugins/xrick/rects.c create mode 100644 apps/plugins/xrick/rects.h create mode 100644 apps/plugins/xrick/res_magic.c create mode 100644 apps/plugins/xrick/resources.c create mode 100644 apps/plugins/xrick/resources.h create mode 100644 apps/plugins/xrick/scr_gameover.c create mode 100644 apps/plugins/xrick/scr_getname.c create mode 100644 apps/plugins/xrick/scr_imain.c create mode 100644 apps/plugins/xrick/scr_imap.c create mode 100644 apps/plugins/xrick/scr_pause.c create mode 100644 apps/plugins/xrick/scr_xrick.c create mode 100644 apps/plugins/xrick/screens.h create mode 100644 apps/plugins/xrick/scroller.c create mode 100644 apps/plugins/xrick/scroller.h create mode 100644 apps/plugins/xrick/system/basic_funcs.c create mode 100644 apps/plugins/xrick/system/basic_funcs.h create mode 100644 apps/plugins/xrick/system/basic_types.h create mode 100644 apps/plugins/xrick/system/main_rockbox.c create mode 100644 apps/plugins/xrick/system/miniz_config.h create mode 100644 apps/plugins/xrick/system/rockboxcodes.h create mode 100644 apps/plugins/xrick/system/sysarg_rockbox.c create mode 100644 apps/plugins/xrick/system/sysevt_rockbox.c create mode 100644 apps/plugins/xrick/system/sysfile_rockbox.c create mode 100644 apps/plugins/xrick/system/sysmem_rockbox.c create mode 100644 apps/plugins/xrick/system/sysmenu_rockbox.c create mode 100644 apps/plugins/xrick/system/sysmenu_rockbox.h create mode 100644 apps/plugins/xrick/system/syssnd_rockbox.c create mode 100644 apps/plugins/xrick/system/syssnd_rockbox.h create mode 100644 apps/plugins/xrick/system/system.h create mode 100644 apps/plugins/xrick/system/system_rockbox.c create mode 100644 apps/plugins/xrick/system/sysvid_rockbox.c create mode 100644 apps/plugins/xrick/util.c create mode 100644 apps/plugins/xrick/util.h create mode 100644 apps/plugins/xrick/xrick.make create mode 100755 manual/plugins/images/ss-xrick-220x176x16.png create mode 100755 manual/plugins/images/ss-xrick-240x320x16.png create mode 100755 manual/plugins/images/ss-xrick-320x240x16.png create mode 100755 manual/plugins/xrick.tex diff --git a/apps/plugins/CATEGORIES b/apps/plugins/CATEGORIES index c91d02ade8..5e22bea980 100644 --- a/apps/plugins/CATEGORIES +++ b/apps/plugins/CATEGORIES @@ -200,5 +200,6 @@ wavview,viewers wolf3d,games wormlet,games xobox,games +xrick,games xworld,games zxbox,viewers diff --git a/apps/plugins/SUBDIRS b/apps/plugins/SUBDIRS index 7884989d1c..c874927205 100644 --- a/apps/plugins/SUBDIRS +++ b/apps/plugins/SUBDIRS @@ -89,3 +89,7 @@ lua lua_scripts picross #endif + +#if (LCD_DEPTH > 1) +xrick +#endif diff --git a/apps/plugins/xrick/3rd_party/miniz/miniz.c b/apps/plugins/xrick/3rd_party/miniz/miniz.c new file mode 100644 index 0000000000..7c26f3b4ba --- /dev/null +++ b/apps/plugins/xrick/3rd_party/miniz/miniz.c @@ -0,0 +1,4928 @@ +/* miniz.c v1.15 - public domain deflate/inflate, zlib-subset, ZIP reading/writing/appending, PNG writing + See "unlicense" statement at the end of this file. + Rich Geldreich , last updated Oct. 13, 2013 + Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951: http://www.ietf.org/rfc/rfc1951.txt + + Most API's defined in miniz.c are optional. For example, to disable the archive related functions just define + MINIZ_NO_ARCHIVE_APIS, or to get rid of all stdio usage define MINIZ_NO_STDIO (see the list below for more macros). + + * Change History + 10/13/13 v1.15 r4 - Interim bugfix release while I work on the next major release with Zip64 support (almost there!): + - Critical fix for the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY bug (thanks kahmyong.moon@hp.com) which could cause locate files to not find files. This bug + would only have occured in earlier versions if you explicitly used this flag, OR if you used mz_zip_extract_archive_file_to_heap() or mz_zip_add_mem_to_archive_file_in_place() + (which used this flag). If you can't switch to v1.15 but want to fix this bug, just remove the uses of this flag from both helper funcs (and of course don't use the flag). + - Bugfix in mz_zip_reader_extract_to_mem_no_alloc() from kymoon when pUser_read_buf is not NULL and compressed size is > uncompressed size + - Fixing mz_zip_reader_extract_*() funcs so they don't try to extract compressed data from directory entries, to account for weird zipfiles which contain zero-size compressed data on dir entries. + Hopefully this fix won't cause any issues on weird zip archives, because it assumes the low 16-bits of zip external attributes are DOS attributes (which I believe they always are in practice). + - Fixing mz_zip_reader_is_file_a_directory() so it doesn't check the internal attributes, just the filename and external attributes + - mz_zip_reader_init_file() - missing MZ_FCLOSE() call if the seek failed + - Added cmake support for Linux builds which builds all the examples, tested with clang v3.3 and gcc v4.6. + - Clang fix for tdefl_write_image_to_png_file_in_memory() from toffaletti + - Merged MZ_FORCEINLINE fix from hdeanclark + - Fix include before config #ifdef, thanks emil.brink + - Added tdefl_write_image_to_png_file_in_memory_ex(): supports Y flipping (super useful for OpenGL apps), and explicit control over the compression level (so you can + set it to 1 for real-time compression). + - Merged in some compiler fixes from paulharris's github repro. + - Retested this build under Windows (VS 2010, including static analysis), tcc 0.9.26, gcc v4.6 and clang v3.3. + - Added example6.c, which dumps an image of the mandelbrot set to a PNG file. + - Modified example2 to help test the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY flag more. + - In r3: Bugfix to mz_zip_writer_add_file() found during merge: Fix possible src file fclose() leak if alignment bytes+local header file write faiiled + - In r4: Minor bugfix to mz_zip_writer_add_from_zip_reader(): Was pushing the wrong central dir header offset, appears harmless in this release, but it became a problem in the zip64 branch + 5/20/12 v1.14 - MinGW32/64 GCC 4.6.1 compiler fixes: added MZ_FORCEINLINE, #include (thanks fermtect). + 5/19/12 v1.13 - From jason@cornsyrup.org and kelwert@mtu.edu - Fix mz_crc32() so it doesn't compute the wrong CRC-32's when mz_ulong is 64-bit. + - Temporarily/locally slammed in "typedef unsigned long mz_ulong" and re-ran a randomized regression test on ~500k files. + - Eliminated a bunch of warnings when compiling with GCC 32-bit/64. + - Ran all examples, miniz.c, and tinfl.c through MSVC 2008's /analyze (static analysis) option and fixed all warnings (except for the silly + "Use of the comma-operator in a tested expression.." analysis warning, which I purposely use to work around a MSVC compiler warning). + - Created 32-bit and 64-bit Codeblocks projects/workspace. Built and tested Linux executables. The codeblocks workspace is compatible with Linux+Win32/x64. + - Added miniz_tester solution/project, which is a useful little app derived from LZHAM's tester app that I use as part of the regression test. + - Ran miniz.c and tinfl.c through another series of regression testing on ~500,000 files and archives. + - Modified example5.c so it purposely disables a bunch of high-level functionality (MINIZ_NO_STDIO, etc.). (Thanks to corysama for the MINIZ_NO_STDIO bug report.) + - Fix ftell() usage in examples so they exit with an error on files which are too large (a limitation of the examples, not miniz itself). + 4/12/12 v1.12 - More comments, added low-level example5.c, fixed a couple minor level_and_flags issues in the archive API's. + level_and_flags can now be set to MZ_DEFAULT_COMPRESSION. Thanks to Bruce Dawson for the feedback/bug report. + 5/28/11 v1.11 - Added statement from unlicense.org + 5/27/11 v1.10 - Substantial compressor optimizations: + - Level 1 is now ~4x faster than before. The L1 compressor's throughput now varies between 70-110MB/sec. on a + - Core i7 (actual throughput varies depending on the type of data, and x64 vs. x86). + - Improved baseline L2-L9 compression perf. Also, greatly improved compression perf. issues on some file types. + - Refactored the compression code for better readability and maintainability. + - Added level 10 compression level (L10 has slightly better ratio than level 9, but could have a potentially large + drop in throughput on some files). + 5/15/11 v1.09 - Initial stable release. + + * Low-level Deflate/Inflate implementation notes: + + Compression: Use the "tdefl" API's. The compressor supports raw, static, and dynamic blocks, lazy or + greedy parsing, match length filtering, RLE-only, and Huffman-only streams. It performs and compresses + approximately as well as zlib. + + Decompression: Use the "tinfl" API's. The entire decompressor is implemented as a single function + coroutine: see tinfl_decompress(). It supports decompression into a 32KB (or larger power of 2) wrapping buffer, or into a memory + block large enough to hold the entire file. + + The low-level tdefl/tinfl API's do not make any use of dynamic memory allocation. + + * zlib-style API notes: + + miniz.c implements a fairly large subset of zlib. There's enough functionality present for it to be a drop-in + zlib replacement in many apps: + The z_stream struct, optional memory allocation callbacks + deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound + inflateInit/inflateInit2/inflate/inflateEnd + compress, compress2, compressBound, uncompress + CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly routines. + Supports raw deflate streams or standard zlib streams with adler-32 checking. + + Limitations: + The callback API's are not implemented yet. No support for gzip headers or zlib static dictionaries. + I've tried to closely emulate zlib's various flavors of stream flushing and return status codes, but + there are no guarantees that miniz.c pulls this off perfectly. + + * PNG writing: See the tdefl_write_image_to_png_file_in_memory() function, originally written by + Alex Evans. Supports 1-4 bytes/pixel images. + + * ZIP archive API notes: + + The ZIP archive API's where designed with simplicity and efficiency in mind, with just enough abstraction to + get the job done with minimal fuss. There are simple API's to retrieve file information, read files from + existing archives, create new archives, append new files to existing archives, or clone archive data from + one archive to another. It supports archives located in memory or the heap, on disk (using stdio.h), + or you can specify custom file read/write callbacks. + + - Archive reading: Just call this function to read a single file from a disk archive: + + void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, + size_t *pSize, mz_uint zip_flags); + + For more complex cases, use the "mz_zip_reader" functions. Upon opening an archive, the entire central + directory is located and read as-is into memory, and subsequent file access only occurs when reading individual files. + + - Archives file scanning: The simple way is to use this function to scan a loaded archive for a specific file: + + int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); + + The locate operation can optionally check file comments too, which (as one example) can be used to identify + multiple versions of the same file in an archive. This function uses a simple linear search through the central + directory, so it's not very fast. + + Alternately, you can iterate through all the files in an archive (using mz_zip_reader_get_num_files()) and + retrieve detailed info on each file by calling mz_zip_reader_file_stat(). + + - Archive creation: Use the "mz_zip_writer" functions. The ZIP writer immediately writes compressed file data + to disk and builds an exact image of the central directory in memory. The central directory image is written + all at once at the end of the archive file when the archive is finalized. + + The archive writer can optionally align each file's local header and file data to any power of 2 alignment, + which can be useful when the archive will be read from optical media. Also, the writer supports placing + arbitrary data blobs at the very beginning of ZIP archives. Archives written using either feature are still + readable by any ZIP tool. + + - Archive appending: The simple way to add a single file to an archive is to call this function: + + mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, + const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); + + The archive will be created if it doesn't already exist, otherwise it'll be appended to. + Note the appending is done in-place and is not an atomic operation, so if something goes wrong + during the operation it's possible the archive could be left without a central directory (although the local + file headers and file data will be fine, so the archive will be recoverable). + + For more complex archive modification scenarios: + 1. The safest way is to use a mz_zip_reader to read the existing archive, cloning only those bits you want to + preserve into a new archive using using the mz_zip_writer_add_from_zip_reader() function (which compiles the + compressed file data as-is). When you're done, delete the old archive and rename the newly written archive, and + you're done. This is safe but requires a bunch of temporary disk space or heap memory. + + 2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using mz_zip_writer_init_from_reader(), + append new files as needed, then finalize the archive which will write an updated central directory to the + original archive. (This is basically what mz_zip_add_mem_to_archive_file_in_place() does.) There's a + possibility that the archive's central directory could be lost with this method if anything goes wrong, though. + + - ZIP archive support limitations: + No zip64 or spanning support. Extraction functions can only handle unencrypted, stored or deflated files. + Requires streams capable of seeking. + + * This is a header file library, like stb_image.c. To get only a header file, either cut and paste the + below header, or create miniz.h, #define MINIZ_HEADER_FILE_ONLY, and then include miniz.c from it. + + * Important: For best perf. be sure to customize the below macros for your target platform: + #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 + #define MINIZ_LITTLE_ENDIAN 1 + #define MINIZ_HAS_64BIT_REGISTERS 1 + + * On platforms using glibc, Be sure to "#define _LARGEFILE64_SOURCE 1" before including miniz.c to ensure miniz + uses the 64-bit variants: fopen64(), stat64(), etc. Otherwise you won't be able to process large files + (i.e. 32-bit stat() fails for me on files > 0x7FFFFFFF bytes). +*/ + +#ifndef MINIZ_HEADER_INCLUDED +#define MINIZ_HEADER_INCLUDED + +#include + +// Defines to completely disable specific portions of miniz.c: +// If all macros here are defined the only functionality remaining will be CRC-32, adler-32, tinfl, and tdefl. + +// Define MINIZ_NO_STDIO to disable all usage and any functions which rely on stdio for file I/O. +//#define MINIZ_NO_STDIO + +// If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able to get the current time, or +// get/set file times, and the C run-time funcs that get/set times won't be called. +// The current downside is the times written to your archives will be from 1979. +//#define MINIZ_NO_TIME + +// Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's. +//#define MINIZ_NO_ARCHIVE_APIS + +// Define MINIZ_NO_ARCHIVE_APIS to disable all writing related ZIP archive API's. +//#define MINIZ_NO_ARCHIVE_WRITING_APIS + +// Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression API's. +//#define MINIZ_NO_ZLIB_APIS + +// Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent conflicts against stock zlib. +//#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES + +// Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc. +// Note if MINIZ_NO_MALLOC is defined then the user must always provide custom user alloc/free/realloc +// callbacks to the zlib and archive API's, and a few stand-alone helper API's which don't provide custom user +// functions (such as tdefl_compress_mem_to_heap() and tinfl_decompress_mem_to_heap()) won't work. +//#define MINIZ_NO_MALLOC + +#if defined(__TINYC__) && (defined(__linux) || defined(__linux__)) + // TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc on Linux + #define MINIZ_NO_TIME +#endif + +#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS) + #include +#endif + +#if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || defined(__i386) || defined(__i486__) || defined(__i486) || defined(i386) || defined(__ia64__) || defined(__x86_64__) +// MINIZ_X86_OR_X64_CPU is only used to help set the below macros. +#define MINIZ_X86_OR_X64_CPU 1 +#endif + +#if (__BYTE_ORDER__==__ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU +// Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. +#define MINIZ_LITTLE_ENDIAN 1 +#endif + +#if MINIZ_X86_OR_X64_CPU +// Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient integer loads and stores from unaligned addresses. +#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 +#endif + +#if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || defined(_LP64) || defined(__LP64__) || defined(__ia64__) || defined(__x86_64__) +// Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are reasonably fast (and don't involve compiler generated calls to helper functions). +#define MINIZ_HAS_64BIT_REGISTERS 1 +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +// ------------------- zlib-style API Definitions. + +// For more compatibility with zlib, miniz.c uses unsigned long for some parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits! +typedef unsigned long mz_ulong; + +// mz_free() internally uses the MZ_FREE() macro (which by default calls free() unless you've modified the MZ_MALLOC macro) to release a block allocated from the heap. +void mz_free(void *p); + +#define MZ_ADLER32_INIT (1) +// mz_adler32() returns the initial adler-32 value to use when called with ptr==NULL. +mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len); + +#define MZ_CRC32_INIT (0) +// mz_crc32() returns the initial CRC-32 value to use when called with ptr==NULL. +mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len); + +// Compression strategies. +enum { MZ_DEFAULT_STRATEGY = 0, MZ_FILTERED = 1, MZ_HUFFMAN_ONLY = 2, MZ_RLE = 3, MZ_FIXED = 4 }; + +// Method +#define MZ_DEFLATED 8 + +#ifndef MINIZ_NO_ZLIB_APIS + +// Heap allocation callbacks. +// Note that mz_alloc_func parameter types purpsosely differ from zlib's: items/size is size_t, not unsigned long. +typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size); +typedef void (*mz_free_func)(void *opaque, void *address); +typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items, size_t size); + +#define MZ_VERSION "9.1.15" +#define MZ_VERNUM 0x91F0 +#define MZ_VER_MAJOR 9 +#define MZ_VER_MINOR 1 +#define MZ_VER_REVISION 15 +#define MZ_VER_SUBREVISION 0 + +// Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The other values are for advanced use (refer to the zlib docs). +enum { MZ_NO_FLUSH = 0, MZ_PARTIAL_FLUSH = 1, MZ_SYNC_FLUSH = 2, MZ_FULL_FLUSH = 3, MZ_FINISH = 4, MZ_BLOCK = 5 }; + +// Return status codes. MZ_PARAM_ERROR is non-standard. +enum { MZ_OK = 0, MZ_STREAM_END = 1, MZ_NEED_DICT = 2, MZ_ERRNO = -1, MZ_STREAM_ERROR = -2, MZ_DATA_ERROR = -3, MZ_MEM_ERROR = -4, MZ_BUF_ERROR = -5, MZ_VERSION_ERROR = -6, MZ_PARAM_ERROR = -10000 }; + +// Compression levels: 0-9 are the standard zlib-style levels, 10 is best possible compression (not zlib compatible, and may be very slow), MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL. +enum { MZ_NO_COMPRESSION = 0, MZ_BEST_SPEED = 1, MZ_BEST_COMPRESSION = 9, MZ_UBER_COMPRESSION = 10, MZ_DEFAULT_LEVEL = 6, MZ_DEFAULT_COMPRESSION = -1 }; + +// Window bits +#define MZ_DEFAULT_WINDOW_BITS 15 + +struct mz_internal_state; + +// Compression/decompression stream struct. +typedef struct mz_stream_s +{ + const unsigned char *next_in; // pointer to next byte to read + unsigned int avail_in; // number of bytes available at next_in + mz_ulong total_in; // total number of bytes consumed so far + + unsigned char *next_out; // pointer to next byte to write + unsigned int avail_out; // number of bytes that can be written to next_out + mz_ulong total_out; // total number of bytes produced so far + + char *msg; // error msg (unused) + struct mz_internal_state *state; // internal state, allocated by zalloc/zfree + + mz_alloc_func zalloc; // optional heap allocation function (defaults to malloc) + mz_free_func zfree; // optional heap free function (defaults to free) + void *opaque; // heap alloc function user pointer + + int data_type; // data_type (unused) + mz_ulong adler; // adler32 of the source or uncompressed data + mz_ulong reserved; // not used +} mz_stream; + +typedef mz_stream *mz_streamp; + +// Returns the version string of miniz.c. +const char *mz_version(void); + +// mz_deflateInit() initializes a compressor with default options: +// Parameters: +// pStream must point to an initialized mz_stream struct. +// level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION]. +// level 1 enables a specially optimized compression function that's been optimized purely for performance, not ratio. +// (This special func. is currently only enabled when MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.) +// Return values: +// MZ_OK on success. +// MZ_STREAM_ERROR if the stream is bogus. +// MZ_PARAM_ERROR if the input parameters are bogus. +// MZ_MEM_ERROR on out of memory. +int mz_deflateInit(mz_streamp pStream, int level); + +// mz_deflateInit2() is like mz_deflate(), except with more control: +// Additional parameters: +// method must be MZ_DEFLATED +// window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no header or footer) +// mem_level must be between [1, 9] (it's checked but ignored by miniz.c) +int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy); + +// Quickly resets a compressor without having to reallocate anything. Same as calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2(). +int mz_deflateReset(mz_streamp pStream); + +// mz_deflate() compresses the input to output, consuming as much of the input and producing as much output as possible. +// Parameters: +// pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. +// flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or MZ_FINISH. +// Return values: +// MZ_OK on success (when flushing, or if more input is needed but not available, and/or there's more output to be written but the output buffer is full). +// MZ_STREAM_END if all input has been consumed and all output bytes have been written. Don't call mz_deflate() on the stream anymore. +// MZ_STREAM_ERROR if the stream is bogus. +// MZ_PARAM_ERROR if one of the parameters is invalid. +// MZ_BUF_ERROR if no forward progress is possible because the input and/or output buffers are empty. (Fill up the input buffer or free up some output space and try again.) +int mz_deflate(mz_streamp pStream, int flush); + +// mz_deflateEnd() deinitializes a compressor: +// Return values: +// MZ_OK on success. +// MZ_STREAM_ERROR if the stream is bogus. +int mz_deflateEnd(mz_streamp pStream); + +// mz_deflateBound() returns a (very) conservative upper bound on the amount of data that could be generated by deflate(), assuming flush is set to only MZ_NO_FLUSH or MZ_FINISH. +mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len); + +// Single-call compression functions mz_compress() and mz_compress2(): +// Returns MZ_OK on success, or one of the error codes from mz_deflate() on failure. +int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); +int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level); + +// mz_compressBound() returns a (very) conservative upper bound on the amount of data that could be generated by calling mz_compress(). +mz_ulong mz_compressBound(mz_ulong source_len); + +// Initializes a decompressor. +int mz_inflateInit(mz_streamp pStream); + +// mz_inflateInit2() is like mz_inflateInit() with an additional option that controls the window size and whether or not the stream has been wrapped with a zlib header/footer: +// window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate). +int mz_inflateInit2(mz_streamp pStream, int window_bits); + +// Decompresses the input stream to the output, consuming only as much of the input as needed, and writing as much to the output as possible. +// Parameters: +// pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. +// flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH. +// On the first call, if flush is MZ_FINISH it's assumed the input and output buffers are both sized large enough to decompress the entire stream in a single call (this is slightly faster). +// MZ_FINISH implies that there are no more source bytes available beside what's already in the input buffer, and that the output buffer is large enough to hold the rest of the decompressed data. +// Return values: +// MZ_OK on success. Either more input is needed but not available, and/or there's more output to be written but the output buffer is full. +// MZ_STREAM_END if all needed input has been consumed and all output bytes have been written. For zlib streams, the adler-32 of the decompressed data has also been verified. +// MZ_STREAM_ERROR if the stream is bogus. +// MZ_DATA_ERROR if the deflate stream is invalid. +// MZ_PARAM_ERROR if one of the parameters is invalid. +// MZ_BUF_ERROR if no forward progress is possible because the input buffer is empty but the inflater needs more input to continue, or if the output buffer is not large enough. Call mz_inflate() again +// with more input data, or with more room in the output buffer (except when using single call decompression, described above). +int mz_inflate(mz_streamp pStream, int flush); + +// Deinitializes a decompressor. +int mz_inflateEnd(mz_streamp pStream); + +// Single-call decompression. +// Returns MZ_OK on success, or one of the error codes from mz_inflate() on failure. +int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); + +// Returns a string description of the specified error code, or NULL if the error code is invalid. +const char *mz_error(int err); + +// Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used as a drop-in replacement for the subset of zlib that miniz.c supports. +// Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you use zlib in the same project. +#ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES + typedef unsigned char Byte; + typedef unsigned int uInt; + typedef mz_ulong uLong; + typedef Byte Bytef; + typedef uInt uIntf; + typedef char charf; + typedef int intf; + typedef void *voidpf; + typedef uLong uLongf; + typedef void *voidp; + typedef void *const voidpc; + #define Z_NULL 0 + #define Z_NO_FLUSH MZ_NO_FLUSH + #define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH + #define Z_SYNC_FLUSH MZ_SYNC_FLUSH + #define Z_FULL_FLUSH MZ_FULL_FLUSH + #define Z_FINISH MZ_FINISH + #define Z_BLOCK MZ_BLOCK + #define Z_OK MZ_OK + #define Z_STREAM_END MZ_STREAM_END + #define Z_NEED_DICT MZ_NEED_DICT + #define Z_ERRNO MZ_ERRNO + #define Z_STREAM_ERROR MZ_STREAM_ERROR + #define Z_DATA_ERROR MZ_DATA_ERROR + #define Z_MEM_ERROR MZ_MEM_ERROR + #define Z_BUF_ERROR MZ_BUF_ERROR + #define Z_VERSION_ERROR MZ_VERSION_ERROR + #define Z_PARAM_ERROR MZ_PARAM_ERROR + #define Z_NO_COMPRESSION MZ_NO_COMPRESSION + #define Z_BEST_SPEED MZ_BEST_SPEED + #define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION + #define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION + #define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY + #define Z_FILTERED MZ_FILTERED + #define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY + #define Z_RLE MZ_RLE + #define Z_FIXED MZ_FIXED + #define Z_DEFLATED MZ_DEFLATED + #define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS + #define alloc_func mz_alloc_func + #define free_func mz_free_func + #define internal_state mz_internal_state + #define z_stream mz_stream + #define deflateInit mz_deflateInit + #define deflateInit2 mz_deflateInit2 + #define deflateReset mz_deflateReset + #define deflate mz_deflate + #define deflateEnd mz_deflateEnd + #define deflateBound mz_deflateBound + #define compress mz_compress + #define compress2 mz_compress2 + #define compressBound mz_compressBound + #define inflateInit mz_inflateInit + #define inflateInit2 mz_inflateInit2 + #define inflate mz_inflate + #define inflateEnd mz_inflateEnd + #define uncompress mz_uncompress + #define crc32 mz_crc32 + #define adler32 mz_adler32 + #define MAX_WBITS 15 + #define MAX_MEM_LEVEL 9 + #define zError mz_error + #define ZLIB_VERSION MZ_VERSION + #define ZLIB_VERNUM MZ_VERNUM + #define ZLIB_VER_MAJOR MZ_VER_MAJOR + #define ZLIB_VER_MINOR MZ_VER_MINOR + #define ZLIB_VER_REVISION MZ_VER_REVISION + #define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION + #define zlibVersion mz_version + #define zlib_version mz_version() +#endif // #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES + +#endif // MINIZ_NO_ZLIB_APIS + +// ------------------- Types and macros + +typedef unsigned char mz_uint8; +typedef signed short mz_int16; +typedef unsigned short mz_uint16; +typedef unsigned int mz_uint32; +typedef unsigned int mz_uint; +typedef long long mz_int64; +typedef unsigned long long mz_uint64; +typedef int mz_bool; + +#define MZ_FALSE (0) +#define MZ_TRUE (1) + +// An attempt to work around MSVC's spammy "warning C4127: conditional expression is constant" message. +#ifdef _MSC_VER + #define MZ_MACRO_END while (0, 0) +#else + #define MZ_MACRO_END while (0) +#endif + +// ------------------- ZIP archive reading/writing + +#ifndef MINIZ_NO_ARCHIVE_APIS + +enum +{ + MZ_ZIP_MAX_IO_BUF_SIZE = 64*1024, + MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 260, + MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 256 +}; + +typedef struct +{ + mz_uint32 m_file_index; + mz_uint32 m_central_dir_ofs; + mz_uint16 m_version_made_by; + mz_uint16 m_version_needed; + mz_uint16 m_bit_flag; + mz_uint16 m_method; +#ifndef MINIZ_NO_TIME + time_t m_time; +#endif + mz_uint32 m_crc32; + mz_uint64 m_comp_size; + mz_uint64 m_uncomp_size; + mz_uint16 m_internal_attr; + mz_uint32 m_external_attr; + mz_uint64 m_local_header_ofs; + mz_uint32 m_comment_size; + char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE]; + char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE]; +} mz_zip_archive_file_stat; + +typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n); +typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n); + +struct mz_zip_internal_state_tag; +typedef struct mz_zip_internal_state_tag mz_zip_internal_state; + +typedef enum +{ + MZ_ZIP_MODE_INVALID = 0, + MZ_ZIP_MODE_READING = 1, + MZ_ZIP_MODE_WRITING = 2, + MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3 +} mz_zip_mode; + +typedef struct mz_zip_archive_tag +{ + mz_uint64 m_archive_size; + mz_uint64 m_central_directory_file_ofs; + mz_uint m_total_files; + mz_zip_mode m_zip_mode; + + mz_uint m_file_offset_alignment; + + mz_alloc_func m_pAlloc; + mz_free_func m_pFree; + mz_realloc_func m_pRealloc; + void *m_pAlloc_opaque; + + mz_file_read_func m_pRead; + mz_file_write_func m_pWrite; + void *m_pIO_opaque; + + mz_zip_internal_state *m_pState; + +} mz_zip_archive; + +typedef enum +{ + MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100, + MZ_ZIP_FLAG_IGNORE_PATH = 0x0200, + MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400, + MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800 +} mz_zip_flags; + +// ZIP archive reading + +// Inits a ZIP archive reader. +// These functions read and validate the archive's central directory. +mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags); +mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags); + +#ifndef MINIZ_NO_STDIO +mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags); +#endif + +// Returns the total number of files in the archive. +mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip); + +// Returns detailed information about an archive file entry. +mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat); + +// Determines if an archive file entry is a directory entry. +mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index); +mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index); + +// Retrieves the filename of an archive file entry. +// Returns the number of bytes written to pFilename, or if filename_buf_size is 0 this function returns the number of bytes needed to fully store the filename. +mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size); + +// Attempts to locates a file in the archive's central directory. +// Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH +// Returns -1 if the file cannot be found. +int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); + +// Extracts a archive file to a memory buffer using no memory allocation. +mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); +mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); + +// Extracts a archive file to a memory buffer. +mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags); +mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags); + +// Extracts a archive file to a dynamically allocated heap buffer. +void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags); +void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags); + +// Extracts a archive file using a callback function to output the file's data. +mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); +mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); + +#ifndef MINIZ_NO_STDIO +// Extracts a archive file to a disk file and sets its last accessed and modified times. +// This function only extracts files, not archive directory records. +mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags); +mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags); +#endif + +// Ends archive reading, freeing all allocations, and closing the input archive file if mz_zip_reader_init_file() was used. +mz_bool mz_zip_reader_end(mz_zip_archive *pZip); + +// ZIP archive writing + +#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + +// Inits a ZIP archive writer. +mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size); +mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size); + +#ifndef MINIZ_NO_STDIO +mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning); +#endif + +// Converts a ZIP archive reader object into a writer object, to allow efficient in-place file appends to occur on an existing archive. +// For archives opened using mz_zip_reader_init_file, pFilename must be the archive's filename so it can be reopened for writing. If the file can't be reopened, mz_zip_reader_end() will be called. +// For archives opened using mz_zip_reader_init_mem, the memory block must be growable using the realloc callback (which defaults to realloc unless you've overridden it). +// Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's user provided m_pWrite function cannot be NULL. +// Note: In-place archive modification is not recommended unless you know what you're doing, because if execution stops or something goes wrong before +// the archive is finalized the file's central directory will be hosed. +mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename); + +// Adds the contents of a memory buffer to an archive. These functions record the current local time into the archive. +// To add a directory entry, call this method with an archive name ending in a forwardslash with empty buffer. +// level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. +mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags); +mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32); + +#ifndef MINIZ_NO_STDIO +// Adds the contents of a disk file to an archive. This function also records the disk file's modified time into the archive. +// level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. +mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); +#endif + +// Adds a file to an archive by fully cloning the data from another archive. +// This function fully clones the source file's compressed data (no recompression), along with its full filename, extra data, and comment fields. +mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index); + +// Finalizes the archive by writing the central directory records followed by the end of central directory record. +// After an archive is finalized, the only valid call on the mz_zip_archive struct is mz_zip_writer_end(). +// An archive must be manually finalized by calling this function for it to be valid. +mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip); +mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, size_t *pSize); + +// Ends archive writing, freeing all allocations, and closing the output file if mz_zip_writer_init_file() was used. +// Note for the archive to be valid, it must have been finalized before ending. +mz_bool mz_zip_writer_end(mz_zip_archive *pZip); + +// Misc. high-level helper functions: + +// mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically) appends a memory blob to a ZIP archive. +// level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. +mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); + +// Reads a single file from an archive into a heap block. +// Returns NULL on failure. +void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint zip_flags); + +#endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + +#endif // #ifndef MINIZ_NO_ARCHIVE_APIS + +// ------------------- Low-level Decompression API Definitions + +// Decompression flags used by tinfl_decompress(). +// TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the input is a raw deflate stream. +// TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available beyond the end of the supplied input buffer. If clear, the input buffer contains all remaining input. +// TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large enough to hold the entire decompressed stream. If clear, the output buffer is at least the size of the dictionary (typically 32KB). +// TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the decompressed bytes. +enum +{ + TINFL_FLAG_PARSE_ZLIB_HEADER = 1, + TINFL_FLAG_HAS_MORE_INPUT = 2, + TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4, + TINFL_FLAG_COMPUTE_ADLER32 = 8 +}; + +// High level decompression functions: +// tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block allocated via malloc(). +// On entry: +// pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data to decompress. +// On return: +// Function returns a pointer to the decompressed data, or NULL on failure. +// *pOut_len will be set to the decompressed data's size, which could be larger than src_buf_len on uncompressible data. +// The caller must call mz_free() on the returned block when it's no longer needed. +void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); + +// tinfl_decompress_mem_to_mem() decompresses a block in memory to another block in memory. +// Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes written on success. +#define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1)) +size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); + +// tinfl_decompress_mem_to_callback() decompresses a block in memory to an internal 32KB buffer, and a user provided callback function will be called to flush the buffer. +// Returns 1 on success or 0 on failure. +typedef int (*tinfl_put_buf_func_ptr)(const void* pBuf, int len, void *pUser); +int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); + +struct tinfl_decompressor_tag; typedef struct tinfl_decompressor_tag tinfl_decompressor; + +// Max size of LZ dictionary. +#define TINFL_LZ_DICT_SIZE 32768 + +// Return status. +typedef enum +{ + TINFL_STATUS_BAD_PARAM = -3, + TINFL_STATUS_ADLER32_MISMATCH = -2, + TINFL_STATUS_FAILED = -1, + TINFL_STATUS_DONE = 0, + TINFL_STATUS_NEEDS_MORE_INPUT = 1, + TINFL_STATUS_HAS_MORE_OUTPUT = 2 +} tinfl_status; + +// Initializes the decompressor to its initial state. +#define tinfl_init(r) do { (r)->m_state = 0; } MZ_MACRO_END +#define tinfl_get_adler32(r) (r)->m_check_adler32 + +// Main low-level decompressor coroutine function. This is the only function actually needed for decompression. All the other functions are just high-level helpers for improved usability. +// This is a universal API, i.e. it can be used as a building block to build any desired higher level decompression API. In the limit case, it can be called once per every byte input or output. +tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags); + +// Internal/private bits follow. +enum +{ + TINFL_MAX_HUFF_TABLES = 3, TINFL_MAX_HUFF_SYMBOLS_0 = 288, TINFL_MAX_HUFF_SYMBOLS_1 = 32, TINFL_MAX_HUFF_SYMBOLS_2 = 19, + TINFL_FAST_LOOKUP_BITS = 10, TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS +}; + +typedef struct +{ + mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0]; + mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE], m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2]; +} tinfl_huff_table; + +#if MINIZ_HAS_64BIT_REGISTERS + #define TINFL_USE_64BIT_BITBUF 1 +#endif + +#if TINFL_USE_64BIT_BITBUF + typedef mz_uint64 tinfl_bit_buf_t; + #define TINFL_BITBUF_SIZE (64) +#else + typedef mz_uint32 tinfl_bit_buf_t; + #define TINFL_BITBUF_SIZE (32) +#endif + +struct tinfl_decompressor_tag +{ + mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, m_check_adler32, m_dist, m_counter, m_num_extra, m_table_sizes[TINFL_MAX_HUFF_TABLES]; + tinfl_bit_buf_t m_bit_buf; + size_t m_dist_from_out_buf_start; + tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES]; + mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137]; +}; + +// ------------------- Low-level Compression API Definitions + +// Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly slower, and raw/dynamic blocks will be output more frequently). +#define TDEFL_LESS_MEMORY 0 + +// tdefl_init() compression flags logically OR'd together (low 12 bits contain the max. number of probes per dictionary search): +// TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap compression), 4095=Huffman+LZ (slowest/best compression). +enum +{ + TDEFL_HUFFMAN_ONLY = 0, TDEFL_DEFAULT_MAX_PROBES = 128, TDEFL_MAX_PROBES_MASK = 0xFFF +}; + +// TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before the deflate data, and the Adler-32 of the source data at the end. Otherwise, you'll get raw deflate data. +// TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even when not writing zlib headers). +// TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more efficient lazy parsing. +// TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's initialization time to the minimum, but the output may vary from run to run given the same input (depending on the contents of memory). +// TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1) +// TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled. +// TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables. +// TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks. +// The low 12 bits are reserved to control the max # of hash probes per dictionary lookup (see TDEFL_MAX_PROBES_MASK). +enum +{ + TDEFL_WRITE_ZLIB_HEADER = 0x01000, + TDEFL_COMPUTE_ADLER32 = 0x02000, + TDEFL_GREEDY_PARSING_FLAG = 0x04000, + TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000, + TDEFL_RLE_MATCHES = 0x10000, + TDEFL_FILTER_MATCHES = 0x20000, + TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000, + TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000 +}; + +// High level compression functions: +// tdefl_compress_mem_to_heap() compresses a block in memory to a heap block allocated via malloc(). +// On entry: +// pSrc_buf, src_buf_len: Pointer and size of source block to compress. +// flags: The max match finder probes (default is 128) logically OR'd against the above flags. Higher probes are slower but improve compression. +// On return: +// Function returns a pointer to the compressed data, or NULL on failure. +// *pOut_len will be set to the compressed data's size, which could be larger than src_buf_len on uncompressible data. +// The caller must free() the returned block when it's no longer needed. +void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); + +// tdefl_compress_mem_to_mem() compresses a block in memory to another block in memory. +// Returns 0 on failure. +size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); + +// Compresses an image to a compressed PNG file in memory. +// On entry: +// pImage, w, h, and num_chans describe the image to compress. num_chans may be 1, 2, 3, or 4. +// The image pitch in bytes per scanline will be w*num_chans. The leftmost pixel on the top scanline is stored first in memory. +// level may range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc. or a decent default is MZ_DEFAULT_LEVEL +// If flip is true, the image will be flipped on the Y axis (useful for OpenGL apps). +// On return: +// Function returns a pointer to the compressed data, or NULL on failure. +// *pLen_out will be set to the size of the PNG image file. +// The caller must mz_free() the returned heap block (which will typically be larger than *pLen_out) when it's no longer needed. +void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip); +void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out); + +// Output stream interface. The compressor uses this interface to write compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time. +typedef mz_bool (*tdefl_put_buf_func_ptr)(const void* pBuf, int len, void *pUser); + +// tdefl_compress_mem_to_output() compresses a block to an output stream. The above helpers use this function internally. +mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); + +enum { TDEFL_MAX_HUFF_TABLES = 3, TDEFL_MAX_HUFF_SYMBOLS_0 = 288, TDEFL_MAX_HUFF_SYMBOLS_1 = 32, TDEFL_MAX_HUFF_SYMBOLS_2 = 19, TDEFL_LZ_DICT_SIZE = 32768, TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1, TDEFL_MIN_MATCH_LEN = 3, TDEFL_MAX_MATCH_LEN = 258 }; + +// TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed output block (using static/fixed Huffman codes). +#if TDEFL_LESS_MEMORY +enum { TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13 ) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 12, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS }; +#else +enum { TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13 ) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 15, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS }; +#endif + +// The low-level tdefl functions below may be used directly if the above helper functions aren't flexible enough. The low-level functions don't make any heap allocations, unlike the above helper functions. +typedef enum +{ + TDEFL_STATUS_BAD_PARAM = -2, + TDEFL_STATUS_PUT_BUF_FAILED = -1, + TDEFL_STATUS_OKAY = 0, + TDEFL_STATUS_DONE = 1, +} tdefl_status; + +// Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums +typedef enum +{ + TDEFL_NO_FLUSH = 0, + TDEFL_SYNC_FLUSH = 2, + TDEFL_FULL_FLUSH = 3, + TDEFL_FINISH = 4 +} tdefl_flush; + +// tdefl's compression state structure. +typedef struct +{ + tdefl_put_buf_func_ptr m_pPut_buf_func; + void *m_pPut_buf_user; + mz_uint m_flags, m_max_probes[2]; + int m_greedy_parsing; + mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size; + mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end; + mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, m_bit_buffer; + mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit, m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index, m_wants_to_finish; + tdefl_status m_prev_return_status; + const void *m_pIn_buf; + void *m_pOut_buf; + size_t *m_pIn_buf_size, *m_pOut_buf_size; + tdefl_flush m_flush; + const mz_uint8 *m_pSrc; + size_t m_src_buf_left, m_out_buf_ofs; + mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1]; + mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; + mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; + mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; + mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE]; + mz_uint16 m_next[TDEFL_LZ_DICT_SIZE]; + mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE]; + mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE]; +} tdefl_compressor; + +// Initializes the compressor. +// There is no corresponding deinit() function because the tdefl API's do not dynamically allocate memory. +// pBut_buf_func: If NULL, output data will be supplied to the specified callback. In this case, the user should call the tdefl_compress_buffer() API for compression. +// If pBut_buf_func is NULL the user should always call the tdefl_compress() API. +// flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, etc.) +tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); + +// Compresses a block of data, consuming as much of the specified input buffer as possible, and writing as much compressed data to the specified output buffer as possible. +tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush); + +// tdefl_compress_buffer() is only usable when the tdefl_init() is called with a non-NULL tdefl_put_buf_func_ptr. +// tdefl_compress_buffer() always consumes the entire input buffer. +tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush); + +tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d); +mz_uint32 tdefl_get_adler32(tdefl_compressor *d); + +// Can't use tdefl_create_comp_flags_from_zip_params if MINIZ_NO_ZLIB_APIS isn't defined, because it uses some of its macros. +#ifndef MINIZ_NO_ZLIB_APIS +// Create tdefl_compress() flags given zlib-style compression parameters. +// level may range from [0,10] (where 10 is absolute max compression, but may be much slower on some files) +// window_bits may be -15 (raw deflate) or 15 (zlib) +// strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, MZ_RLE, or MZ_FIXED +mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy); +#endif // #ifndef MINIZ_NO_ZLIB_APIS + +#ifdef __cplusplus +} +#endif + +#endif // MINIZ_HEADER_INCLUDED + +// ------------------- End of Header: Implementation follows. (If you only want the header, define MINIZ_HEADER_FILE_ONLY.) + +#ifndef MINIZ_HEADER_FILE_ONLY + +typedef unsigned char mz_validate_uint16[sizeof(mz_uint16)==2 ? 1 : -1]; +typedef unsigned char mz_validate_uint32[sizeof(mz_uint32)==4 ? 1 : -1]; +typedef unsigned char mz_validate_uint64[sizeof(mz_uint64)==8 ? 1 : -1]; + +#include + +#ifdef MINIZ_NO_ASSERT + #define MZ_ASSERT(x) +#else + #include + #define MZ_ASSERT(x) assert(x) +#endif + +#ifdef MINIZ_NO_MALLOC + #define MZ_MALLOC(x) NULL + #define MZ_FREE(x) (void)x, ((void)0) + #define MZ_REALLOC(p, x) NULL +#else + #define MZ_MALLOC(x) malloc(x) + #define MZ_FREE(x) free(x) + #define MZ_REALLOC(p, x) realloc(p, x) +#endif + +#define MZ_MAX(a,b) (((a)>(b))?(a):(b)) +#define MZ_MIN(a,b) (((a)<(b))?(a):(b)) +#define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj)) + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN + #define MZ_READ_LE16(p) *((const mz_uint16 *)(p)) + #define MZ_READ_LE32(p) *((const mz_uint32 *)(p)) +#else + #define MZ_READ_LE16(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U)) + #define MZ_READ_LE32(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U)) +#endif + +#ifdef _MSC_VER + #define MZ_FORCEINLINE __forceinline +#elif defined(__GNUC__) + #define MZ_FORCEINLINE inline __attribute__((__always_inline__)) +#else + #define MZ_FORCEINLINE inline +#endif + +#ifdef __cplusplus + extern "C" { +#endif + +// ------------------- zlib-style API's + +mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len) +{ + mz_uint32 i, s1 = (mz_uint32)(adler & 0xffff), s2 = (mz_uint32)(adler >> 16); size_t block_len = buf_len % 5552; + if (!ptr) return MZ_ADLER32_INIT; + while (buf_len) { + for (i = 0; i + 7 < block_len; i += 8, ptr += 8) { + s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1; + s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1; + } + for ( ; i < block_len; ++i) s1 += *ptr++, s2 += s1; + s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552; + } + return (s2 << 16) + s1; +} + +// Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C implementation that balances processor cache usage against speed": http://www.geocities.com/malbrain/ +mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) +{ + static const mz_uint32 s_crc32[16] = { 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c, + 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c }; + mz_uint32 crcu32 = (mz_uint32)crc; + if (!ptr) return MZ_CRC32_INIT; + crcu32 = ~crcu32; while (buf_len--) { mz_uint8 b = *ptr++; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)]; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)]; } + return ~crcu32; +} + +void mz_free(void *p) +{ + MZ_FREE(p); +} + +#ifndef MINIZ_NO_ZLIB_APIS + +static void *def_alloc_func(void *opaque, size_t items, size_t size) { (void)opaque, (void)items, (void)size; return MZ_MALLOC(items * size); } +static void def_free_func(void *opaque, void *address) { (void)opaque, (void)address; MZ_FREE(address); } +static void *def_realloc_func(void *opaque, void *address, size_t items, size_t size) { (void)opaque, (void)address, (void)items, (void)size; return MZ_REALLOC(address, items * size); } + +const char *mz_version(void) +{ + return MZ_VERSION; +} + +int mz_deflateInit(mz_streamp pStream, int level) +{ + return mz_deflateInit2(pStream, level, MZ_DEFLATED, MZ_DEFAULT_WINDOW_BITS, 9, MZ_DEFAULT_STRATEGY); +} + +int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy) +{ + tdefl_compressor *pComp; + mz_uint comp_flags = TDEFL_COMPUTE_ADLER32 | tdefl_create_comp_flags_from_zip_params(level, window_bits, strategy); + + if (!pStream) return MZ_STREAM_ERROR; + if ((method != MZ_DEFLATED) || ((mem_level < 1) || (mem_level > 9)) || ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS))) return MZ_PARAM_ERROR; + + pStream->data_type = 0; + pStream->adler = MZ_ADLER32_INIT; + pStream->msg = NULL; + pStream->reserved = 0; + pStream->total_in = 0; + pStream->total_out = 0; + if (!pStream->zalloc) pStream->zalloc = def_alloc_func; + if (!pStream->zfree) pStream->zfree = def_free_func; + + pComp = (tdefl_compressor *)pStream->zalloc(pStream->opaque, 1, sizeof(tdefl_compressor)); + if (!pComp) + return MZ_MEM_ERROR; + + pStream->state = (struct mz_internal_state *)pComp; + + if (tdefl_init(pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY) + { + mz_deflateEnd(pStream); + return MZ_PARAM_ERROR; + } + + return MZ_OK; +} + +int mz_deflateReset(mz_streamp pStream) +{ + if ((!pStream) || (!pStream->state) || (!pStream->zalloc) || (!pStream->zfree)) return MZ_STREAM_ERROR; + pStream->total_in = pStream->total_out = 0; + tdefl_init((tdefl_compressor*)pStream->state, NULL, NULL, ((tdefl_compressor*)pStream->state)->m_flags); + return MZ_OK; +} + +int mz_deflate(mz_streamp pStream, int flush) +{ + size_t in_bytes, out_bytes; + mz_ulong orig_total_in, orig_total_out; + int mz_status = MZ_OK; + + if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) || (!pStream->next_out)) return MZ_STREAM_ERROR; + if (!pStream->avail_out) return MZ_BUF_ERROR; + + if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH; + + if (((tdefl_compressor*)pStream->state)->m_prev_return_status == TDEFL_STATUS_DONE) + return (flush == MZ_FINISH) ? MZ_STREAM_END : MZ_BUF_ERROR; + + orig_total_in = pStream->total_in; orig_total_out = pStream->total_out; + for ( ; ; ) + { + tdefl_status defl_status; + in_bytes = pStream->avail_in; out_bytes = pStream->avail_out; + + defl_status = tdefl_compress((tdefl_compressor*)pStream->state, pStream->next_in, &in_bytes, pStream->next_out, &out_bytes, (tdefl_flush)flush); + pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; + pStream->total_in += (mz_uint)in_bytes; pStream->adler = tdefl_get_adler32((tdefl_compressor*)pStream->state); + + pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes; + pStream->total_out += (mz_uint)out_bytes; + + if (defl_status < 0) + { + mz_status = MZ_STREAM_ERROR; + break; + } + else if (defl_status == TDEFL_STATUS_DONE) + { + mz_status = MZ_STREAM_END; + break; + } + else if (!pStream->avail_out) + break; + else if ((!pStream->avail_in) && (flush != MZ_FINISH)) + { + if ((flush) || (pStream->total_in != orig_total_in) || (pStream->total_out != orig_total_out)) + break; + return MZ_BUF_ERROR; // Can't make forward progress without some input. + } + } + return mz_status; +} + +int mz_deflateEnd(mz_streamp pStream) +{ + if (!pStream) return MZ_STREAM_ERROR; + if (pStream->state) + { + pStream->zfree(pStream->opaque, pStream->state); + pStream->state = NULL; + } + return MZ_OK; +} + +mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len) +{ + (void)pStream; + // This is really over conservative. (And lame, but it's actually pretty tricky to compute a true upper bound given the way tdefl's blocking works.) + return MZ_MAX(128 + (source_len * 110) / 100, 128 + source_len + ((source_len / (31 * 1024)) + 1) * 5); +} + +int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level) +{ + int status; + mz_stream stream; + memset(&stream, 0, sizeof(stream)); + + // In case mz_ulong is 64-bits (argh I hate longs). + if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR; + + stream.next_in = pSource; + stream.avail_in = (mz_uint32)source_len; + stream.next_out = pDest; + stream.avail_out = (mz_uint32)*pDest_len; + + status = mz_deflateInit(&stream, level); + if (status != MZ_OK) return status; + + status = mz_deflate(&stream, MZ_FINISH); + if (status != MZ_STREAM_END) + { + mz_deflateEnd(&stream); + return (status == MZ_OK) ? MZ_BUF_ERROR : status; + } + + *pDest_len = stream.total_out; + return mz_deflateEnd(&stream); +} + +int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) +{ + return mz_compress2(pDest, pDest_len, pSource, source_len, MZ_DEFAULT_COMPRESSION); +} + +mz_ulong mz_compressBound(mz_ulong source_len) +{ + return mz_deflateBound(NULL, source_len); +} + +typedef struct +{ + tinfl_decompressor m_decomp; + mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed; int m_window_bits; + mz_uint8 m_dict[TINFL_LZ_DICT_SIZE]; + tinfl_status m_last_status; +} inflate_state; + +int mz_inflateInit2(mz_streamp pStream, int window_bits) +{ + inflate_state *pDecomp; + if (!pStream) return MZ_STREAM_ERROR; + if ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS)) return MZ_PARAM_ERROR; + + pStream->data_type = 0; + pStream->adler = 0; + pStream->msg = NULL; + pStream->total_in = 0; + pStream->total_out = 0; + pStream->reserved = 0; + if (!pStream->zalloc) pStream->zalloc = def_alloc_func; + if (!pStream->zfree) pStream->zfree = def_free_func; + + pDecomp = (inflate_state*)pStream->zalloc(pStream->opaque, 1, sizeof(inflate_state)); + if (!pDecomp) return MZ_MEM_ERROR; + + pStream->state = (struct mz_internal_state *)pDecomp; + + tinfl_init(&pDecomp->m_decomp); + pDecomp->m_dict_ofs = 0; + pDecomp->m_dict_avail = 0; + pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT; + pDecomp->m_first_call = 1; + pDecomp->m_has_flushed = 0; + pDecomp->m_window_bits = window_bits; + + return MZ_OK; +} + +int mz_inflateInit(mz_streamp pStream) +{ + return mz_inflateInit2(pStream, MZ_DEFAULT_WINDOW_BITS); +} + +int mz_inflate(mz_streamp pStream, int flush) +{ + inflate_state* pState; + mz_uint n, first_call, decomp_flags = TINFL_FLAG_COMPUTE_ADLER32; + size_t in_bytes, out_bytes, orig_avail_in; + tinfl_status status; + + if ((!pStream) || (!pStream->state)) return MZ_STREAM_ERROR; + if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH; + if ((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH)) return MZ_STREAM_ERROR; + + pState = (inflate_state*)pStream->state; + if (pState->m_window_bits > 0) decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER; + orig_avail_in = pStream->avail_in; + + first_call = pState->m_first_call; pState->m_first_call = 0; + if (pState->m_last_status < 0) return MZ_DATA_ERROR; + + if (pState->m_has_flushed && (flush != MZ_FINISH)) return MZ_STREAM_ERROR; + pState->m_has_flushed |= (flush == MZ_FINISH); + + if ((flush == MZ_FINISH) && (first_call)) + { + // MZ_FINISH on the first call implies that the input and output buffers are large enough to hold the entire compressed/decompressed file. + decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF; + in_bytes = pStream->avail_in; out_bytes = pStream->avail_out; + status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pStream->next_out, pStream->next_out, &out_bytes, decomp_flags); + pState->m_last_status = status; + pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes; + pStream->adler = tinfl_get_adler32(&pState->m_decomp); + pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes; pStream->total_out += (mz_uint)out_bytes; + + if (status < 0) + return MZ_DATA_ERROR; + else if (status != TINFL_STATUS_DONE) + { + pState->m_last_status = TINFL_STATUS_FAILED; + return MZ_BUF_ERROR; + } + return MZ_STREAM_END; + } + // flush != MZ_FINISH then we must assume there's more input. + if (flush != MZ_FINISH) decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT; + + if (pState->m_dict_avail) + { + n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); + memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); + pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n; + pState->m_dict_avail -= n; pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); + return ((pState->m_last_status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; + } + + for ( ; ; ) + { + in_bytes = pStream->avail_in; + out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs; + + status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pState->m_dict, pState->m_dict + pState->m_dict_ofs, &out_bytes, decomp_flags); + pState->m_last_status = status; + + pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; + pStream->total_in += (mz_uint)in_bytes; pStream->adler = tinfl_get_adler32(&pState->m_decomp); + + pState->m_dict_avail = (mz_uint)out_bytes; + + n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); + memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); + pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n; + pState->m_dict_avail -= n; pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); + + if (status < 0) + return MZ_DATA_ERROR; // Stream is corrupted (there could be some uncompressed data left in the output dictionary - oh well). + else if ((status == TINFL_STATUS_NEEDS_MORE_INPUT) && (!orig_avail_in)) + return MZ_BUF_ERROR; // Signal caller that we can't make forward progress without supplying more input or by setting flush to MZ_FINISH. + else if (flush == MZ_FINISH) + { + // The output buffer MUST be large to hold the remaining uncompressed data when flush==MZ_FINISH. + if (status == TINFL_STATUS_DONE) + return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END; + // status here must be TINFL_STATUS_HAS_MORE_OUTPUT, which means there's at least 1 more byte on the way. If there's no more room left in the output buffer then something is wrong. + else if (!pStream->avail_out) + return MZ_BUF_ERROR; + } + else if ((status == TINFL_STATUS_DONE) || (!pStream->avail_in) || (!pStream->avail_out) || (pState->m_dict_avail)) + break; + } + + return ((status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; +} + +int mz_inflateEnd(mz_streamp pStream) +{ + if (!pStream) + return MZ_STREAM_ERROR; + if (pStream->state) + { + pStream->zfree(pStream->opaque, pStream->state); + pStream->state = NULL; + } + return MZ_OK; +} + +int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) +{ + mz_stream stream; + int status; + memset(&stream, 0, sizeof(stream)); + + // In case mz_ulong is 64-bits (argh I hate longs). + if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR; + + stream.next_in = pSource; + stream.avail_in = (mz_uint32)source_len; + stream.next_out = pDest; + stream.avail_out = (mz_uint32)*pDest_len; + + status = mz_inflateInit(&stream); + if (status != MZ_OK) + return status; + + status = mz_inflate(&stream, MZ_FINISH); + if (status != MZ_STREAM_END) + { + mz_inflateEnd(&stream); + return ((status == MZ_BUF_ERROR) && (!stream.avail_in)) ? MZ_DATA_ERROR : status; + } + *pDest_len = stream.total_out; + + return mz_inflateEnd(&stream); +} + +const char *mz_error(int err) +{ + static struct { int m_err; const char *m_pDesc; } s_error_descs[] = + { + { MZ_OK, "" }, { MZ_STREAM_END, "stream end" }, { MZ_NEED_DICT, "need dictionary" }, { MZ_ERRNO, "file error" }, { MZ_STREAM_ERROR, "stream error" }, + { MZ_DATA_ERROR, "data error" }, { MZ_MEM_ERROR, "out of memory" }, { MZ_BUF_ERROR, "buf error" }, { MZ_VERSION_ERROR, "version error" }, { MZ_PARAM_ERROR, "parameter error" } + }; + mz_uint i; for (i = 0; i < sizeof(s_error_descs) / sizeof(s_error_descs[0]); ++i) if (s_error_descs[i].m_err == err) return s_error_descs[i].m_pDesc; + return NULL; +} + +#endif //MINIZ_NO_ZLIB_APIS + +// ------------------- Low-level Decompression (completely independent from all compression API's) + +#define TINFL_MEMCPY(d, s, l) memcpy(d, s, l) +#define TINFL_MEMSET(p, c, l) memset(p, c, l) + +#define TINFL_CR_BEGIN switch(r->m_state) { case 0: +#define TINFL_CR_RETURN(state_index, result) do { status = result; r->m_state = state_index; goto common_exit; case state_index:; } MZ_MACRO_END +#define TINFL_CR_RETURN_FOREVER(state_index, result) do { for ( ; ; ) { TINFL_CR_RETURN(state_index, result); } } MZ_MACRO_END +#define TINFL_CR_FINISH } + +// TODO: If the caller has indicated that there's no more input, and we attempt to read beyond the input buf, then something is wrong with the input because the inflator never +// reads ahead more than it needs to. Currently TINFL_GET_BYTE() pads the end of the stream with 0's in this scenario. +#define TINFL_GET_BYTE(state_index, c) do { \ + if (pIn_buf_cur >= pIn_buf_end) { \ + for ( ; ; ) { \ + if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { \ + TINFL_CR_RETURN(state_index, TINFL_STATUS_NEEDS_MORE_INPUT); \ + if (pIn_buf_cur < pIn_buf_end) { \ + c = *pIn_buf_cur++; \ + break; \ + } \ + } else { \ + c = 0; \ + break; \ + } \ + } \ + } else c = *pIn_buf_cur++; } MZ_MACRO_END + +#define TINFL_NEED_BITS(state_index, n) do { mz_uint c; TINFL_GET_BYTE(state_index, c); bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); num_bits += 8; } while (num_bits < (mz_uint)(n)) +#define TINFL_SKIP_BITS(state_index, n) do { if (num_bits < (mz_uint)(n)) { TINFL_NEED_BITS(state_index, n); } bit_buf >>= (n); num_bits -= (n); } MZ_MACRO_END +#define TINFL_GET_BITS(state_index, b, n) do { if (num_bits < (mz_uint)(n)) { TINFL_NEED_BITS(state_index, n); } b = bit_buf & ((1 << (n)) - 1); bit_buf >>= (n); num_bits -= (n); } MZ_MACRO_END + +// TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes remaining in the input buffer falls below 2. +// It reads just enough bytes from the input stream that are needed to decode the next Huffman code (and absolutely no more). It works by trying to fully decode a +// Huffman code by using whatever bits are currently present in the bit buffer. If this fails, it reads another byte, and tries again until it succeeds or until the +// bit buffer contains >=15 bits (deflate's max. Huffman code size). +#define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \ + do { \ + temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \ + if (temp >= 0) { \ + code_len = temp >> 9; \ + if ((code_len) && (num_bits >= code_len)) \ + break; \ + } else if (num_bits > TINFL_FAST_LOOKUP_BITS) { \ + code_len = TINFL_FAST_LOOKUP_BITS; \ + do { \ + temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ + } while ((temp < 0) && (num_bits >= (code_len + 1))); if (temp >= 0) break; \ + } TINFL_GET_BYTE(state_index, c); bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); num_bits += 8; \ + } while (num_bits < 15); + +// TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex than you would initially expect because the zlib API expects the decompressor to never read +// beyond the final byte of the deflate stream. (In other words, when this macro wants to read another byte from the input, it REALLY needs another byte in order to fully +// decode the next Huffman code.) Handling this properly is particularly important on raw deflate (non-zlib) streams, which aren't followed by a byte aligned adler-32. +// The slow path is only executed at the very end of the input buffer. +#define TINFL_HUFF_DECODE(state_index, sym, pHuff) do { \ + int temp; mz_uint code_len, c; \ + if (num_bits < 15) { \ + if ((pIn_buf_end - pIn_buf_cur) < 2) { \ + TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \ + } else { \ + bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); pIn_buf_cur += 2; num_bits += 16; \ + } \ + } \ + if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) \ + code_len = temp >> 9, temp &= 511; \ + else { \ + code_len = TINFL_FAST_LOOKUP_BITS; do { temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; } while (temp < 0); \ + } sym = temp; bit_buf >>= code_len; num_bits -= code_len; } MZ_MACRO_END + +tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags) +{ + static const int s_length_base[31] = { 3,4,5,6,7,8,9,10,11,13, 15,17,19,23,27,31,35,43,51,59, 67,83,99,115,131,163,195,227,258,0,0 }; + static const int s_length_extra[31]= { 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 }; + static const int s_dist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, 257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0}; + static const int s_dist_extra[32] = { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; + static const mz_uint8 s_length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 }; + static const int s_min_table_sizes[3] = { 257, 1, 4 }; + + tinfl_status status = TINFL_STATUS_FAILED; mz_uint32 num_bits, dist, counter, num_extra; tinfl_bit_buf_t bit_buf; + const mz_uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end = pIn_buf_next + *pIn_buf_size; + mz_uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end = pOut_buf_next + *pOut_buf_size; + size_t out_buf_size_mask = (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF) ? (size_t)-1 : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1, dist_from_out_buf_start; + + // Ensure the output buffer's size is a power of 2, unless the output buffer is large enough to hold the entire output file (in which case it doesn't matter). + if (((out_buf_size_mask + 1) & out_buf_size_mask) || (pOut_buf_next < pOut_buf_start)) { *pIn_buf_size = *pOut_buf_size = 0; return TINFL_STATUS_BAD_PARAM; } + + num_bits = r->m_num_bits; bit_buf = r->m_bit_buf; dist = r->m_dist; counter = r->m_counter; num_extra = r->m_num_extra; dist_from_out_buf_start = r->m_dist_from_out_buf_start; + TINFL_CR_BEGIN + + bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0; r->m_z_adler32 = r->m_check_adler32 = 1; + if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) + { + TINFL_GET_BYTE(1, r->m_zhdr0); TINFL_GET_BYTE(2, r->m_zhdr1); + counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) || (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8)); + if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) || ((out_buf_size_mask + 1) < (size_t)(1U << (8U + (r->m_zhdr0 >> 4))))); + if (counter) { TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED); } + } + + do + { + TINFL_GET_BITS(3, r->m_final, 3); r->m_type = r->m_final >> 1; + if (r->m_type == 0) + { + TINFL_SKIP_BITS(5, num_bits & 7); + for (counter = 0; counter < 4; ++counter) { if (num_bits) TINFL_GET_BITS(6, r->m_raw_header[counter], 8); else TINFL_GET_BYTE(7, r->m_raw_header[counter]); } + if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) != (mz_uint)(0xFFFF ^ (r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) { TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED); } + while ((counter) && (num_bits)) + { + TINFL_GET_BITS(51, dist, 8); + while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT); } + *pOut_buf_cur++ = (mz_uint8)dist; + counter--; + } + while (counter) + { + size_t n; while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT); } + while (pIn_buf_cur >= pIn_buf_end) + { + if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) + { + TINFL_CR_RETURN(38, TINFL_STATUS_NEEDS_MORE_INPUT); + } + else + { + TINFL_CR_RETURN_FOREVER(40, TINFL_STATUS_FAILED); + } + } + n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur), (size_t)(pIn_buf_end - pIn_buf_cur)), counter); + TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n); pIn_buf_cur += n; pOut_buf_cur += n; counter -= (mz_uint)n; + } + } + else if (r->m_type == 3) + { + TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED); + } + else + { + if (r->m_type == 1) + { + mz_uint8 *p = r->m_tables[0].m_code_size; mz_uint i; + r->m_table_sizes[0] = 288; r->m_table_sizes[1] = 32; TINFL_MEMSET(r->m_tables[1].m_code_size, 5, 32); + for ( i = 0; i <= 143; ++i) *p++ = 8; + for ( ; i <= 255; ++i) *p++ = 9; + for ( ; i <= 279; ++i) *p++ = 7; + for ( ; i <= 287; ++i) *p++ = 8; + } + else + { + for (counter = 0; counter < 3; counter++) { TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]); r->m_table_sizes[counter] += s_min_table_sizes[counter]; } + MZ_CLEAR_OBJ(r->m_tables[2].m_code_size); for (counter = 0; counter < r->m_table_sizes[2]; counter++) { mz_uint s; TINFL_GET_BITS(14, s, 3); r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (mz_uint8)s; } + r->m_table_sizes[2] = 19; + } + for ( ; (int)r->m_type >= 0; r->m_type--) + { + int tree_next, tree_cur; tinfl_huff_table *pTable; + mz_uint i, j, used_syms, total, sym_index, next_code[17], total_syms[16]; pTable = &r->m_tables[r->m_type]; MZ_CLEAR_OBJ(total_syms); MZ_CLEAR_OBJ(pTable->m_look_up); MZ_CLEAR_OBJ(pTable->m_tree); + for (i = 0; i < r->m_table_sizes[r->m_type]; ++i) total_syms[pTable->m_code_size[i]]++; + used_syms = 0, total = 0; next_code[0] = next_code[1] = 0; + for (i = 1; i <= 15; ++i) { used_syms += total_syms[i]; next_code[i + 1] = (total = ((total + total_syms[i]) << 1)); } + if ((65536 != total) && (used_syms > 1)) + { + TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED); + } + for (tree_next = -1, sym_index = 0; sym_index < r->m_table_sizes[r->m_type]; ++sym_index) + { + mz_uint rev_code = 0, l, cur_code, code_size = pTable->m_code_size[sym_index]; if (!code_size) continue; + cur_code = next_code[code_size]++; for (l = code_size; l > 0; l--, cur_code >>= 1) rev_code = (rev_code << 1) | (cur_code & 1); + if (code_size <= TINFL_FAST_LOOKUP_BITS) { mz_int16 k = (mz_int16)((code_size << 9) | sym_index); while (rev_code < TINFL_FAST_LOOKUP_SIZE) { pTable->m_look_up[rev_code] = k; rev_code += (1 << code_size); } continue; } + if (0 == (tree_cur = pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)])) { pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; } + rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1); + for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--) + { + tree_cur -= ((rev_code >>= 1) & 1); + if (!pTable->m_tree[-tree_cur - 1]) { pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; } else tree_cur = pTable->m_tree[-tree_cur - 1]; + } + tree_cur -= ((rev_code >>= 1) & 1); pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index; + } + if (r->m_type == 2) + { + for (counter = 0; counter < (r->m_table_sizes[0] + r->m_table_sizes[1]); ) + { + mz_uint s; TINFL_HUFF_DECODE(16, dist, &r->m_tables[2]); if (dist < 16) { r->m_len_codes[counter++] = (mz_uint8)dist; continue; } + if ((dist == 16) && (!counter)) + { + TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED); + } + num_extra = "\02\03\07"[dist - 16]; TINFL_GET_BITS(18, s, num_extra); s += "\03\03\013"[dist - 16]; + TINFL_MEMSET(r->m_len_codes + counter, (dist == 16) ? r->m_len_codes[counter - 1] : 0, s); counter += s; + } + if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter) + { + TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED); + } + TINFL_MEMCPY(r->m_tables[0].m_code_size, r->m_len_codes, r->m_table_sizes[0]); TINFL_MEMCPY(r->m_tables[1].m_code_size, r->m_len_codes + r->m_table_sizes[0], r->m_table_sizes[1]); + } + } + for ( ; ; ) + { + mz_uint8 *pSrc; + for ( ; ; ) + { + if (((pIn_buf_end - pIn_buf_cur) < 4) || ((pOut_buf_end - pOut_buf_cur) < 2)) + { + TINFL_HUFF_DECODE(23, counter, &r->m_tables[0]); + if (counter >= 256) + break; + while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT); } + *pOut_buf_cur++ = (mz_uint8)counter; + } + else + { + int sym2; mz_uint code_len; +#if TINFL_USE_64BIT_BITBUF + if (num_bits < 30) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits); pIn_buf_cur += 4; num_bits += 32; } +#else + if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; } +#endif + if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) + code_len = sym2 >> 9; + else + { + code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0); + } + counter = sym2; bit_buf >>= code_len; num_bits -= code_len; + if (counter & 256) + break; + +#if !TINFL_USE_64BIT_BITBUF + if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; } +#endif + if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) + code_len = sym2 >> 9; + else + { + code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0); + } + bit_buf >>= code_len; num_bits -= code_len; + + pOut_buf_cur[0] = (mz_uint8)counter; + if (sym2 & 256) + { + pOut_buf_cur++; + counter = sym2; + break; + } + pOut_buf_cur[1] = (mz_uint8)sym2; + pOut_buf_cur += 2; + } + } + if ((counter &= 511) == 256) break; + + num_extra = s_length_extra[counter - 257]; counter = s_length_base[counter - 257]; + if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(25, extra_bits, num_extra); counter += extra_bits; } + + TINFL_HUFF_DECODE(26, dist, &r->m_tables[1]); + num_extra = s_dist_extra[dist]; dist = s_dist_base[dist]; + if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(27, extra_bits, num_extra); dist += extra_bits; } + + dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start; + if ((dist > dist_from_out_buf_start) && (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) + { + TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED); + } + + pSrc = pOut_buf_start + ((dist_from_out_buf_start - dist) & out_buf_size_mask); + + if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end) + { + while (counter--) + { + while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT); } + *pOut_buf_cur++ = pOut_buf_start[(dist_from_out_buf_start++ - dist) & out_buf_size_mask]; + } + continue; + } +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES + else if ((counter >= 9) && (counter <= dist)) + { + const mz_uint8 *pSrc_end = pSrc + (counter & ~7); + do + { + ((mz_uint32 *)pOut_buf_cur)[0] = ((const mz_uint32 *)pSrc)[0]; + ((mz_uint32 *)pOut_buf_cur)[1] = ((const mz_uint32 *)pSrc)[1]; + pOut_buf_cur += 8; + } while ((pSrc += 8) < pSrc_end); + if ((counter &= 7) < 3) + { + if (counter) + { + pOut_buf_cur[0] = pSrc[0]; + if (counter > 1) + pOut_buf_cur[1] = pSrc[1]; + pOut_buf_cur += counter; + } + continue; + } + } +#endif + do + { + pOut_buf_cur[0] = pSrc[0]; + pOut_buf_cur[1] = pSrc[1]; + pOut_buf_cur[2] = pSrc[2]; + pOut_buf_cur += 3; pSrc += 3; + } while ((int)(counter -= 3) > 2); + if ((int)counter > 0) + { + pOut_buf_cur[0] = pSrc[0]; + if ((int)counter > 1) + pOut_buf_cur[1] = pSrc[1]; + pOut_buf_cur += counter; + } + } + } + } while (!(r->m_final & 1)); + if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) + { + TINFL_SKIP_BITS(32, num_bits & 7); for (counter = 0; counter < 4; ++counter) { mz_uint s; if (num_bits) TINFL_GET_BITS(41, s, 8); else TINFL_GET_BYTE(42, s); r->m_z_adler32 = (r->m_z_adler32 << 8) | s; } + } + TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE); + TINFL_CR_FINISH + +common_exit: + r->m_num_bits = num_bits; r->m_bit_buf = bit_buf; r->m_dist = dist; r->m_counter = counter; r->m_num_extra = num_extra; r->m_dist_from_out_buf_start = dist_from_out_buf_start; + *pIn_buf_size = pIn_buf_cur - pIn_buf_next; *pOut_buf_size = pOut_buf_cur - pOut_buf_next; + if ((decomp_flags & (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) && (status >= 0)) + { + const mz_uint8 *ptr = pOut_buf_next; size_t buf_len = *pOut_buf_size; + mz_uint32 i, s1 = r->m_check_adler32 & 0xffff, s2 = r->m_check_adler32 >> 16; size_t block_len = buf_len % 5552; + while (buf_len) + { + for (i = 0; i + 7 < block_len; i += 8, ptr += 8) + { + s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1; + s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1; + } + for ( ; i < block_len; ++i) s1 += *ptr++, s2 += s1; + s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552; + } + r->m_check_adler32 = (s2 << 16) + s1; if ((status == TINFL_STATUS_DONE) && (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) && (r->m_check_adler32 != r->m_z_adler32)) status = TINFL_STATUS_ADLER32_MISMATCH; + } + return status; +} + +// Higher level helper functions. +void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) +{ + tinfl_decompressor decomp; void *pBuf = NULL, *pNew_buf; size_t src_buf_ofs = 0, out_buf_capacity = 0; + *pOut_len = 0; + tinfl_init(&decomp); + for ( ; ; ) + { + size_t src_buf_size = src_buf_len - src_buf_ofs, dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity; + tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8*)pSrc_buf + src_buf_ofs, &src_buf_size, (mz_uint8*)pBuf, pBuf ? (mz_uint8*)pBuf + *pOut_len : NULL, &dst_buf_size, + (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); + if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT)) + { + MZ_FREE(pBuf); *pOut_len = 0; return NULL; + } + src_buf_ofs += src_buf_size; + *pOut_len += dst_buf_size; + if (status == TINFL_STATUS_DONE) break; + new_out_buf_capacity = out_buf_capacity * 2; if (new_out_buf_capacity < 128) new_out_buf_capacity = 128; + pNew_buf = MZ_REALLOC(pBuf, new_out_buf_capacity); + if (!pNew_buf) + { + MZ_FREE(pBuf); *pOut_len = 0; return NULL; + } + pBuf = pNew_buf; out_buf_capacity = new_out_buf_capacity; + } + return pBuf; +} + +size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) +{ + tinfl_decompressor decomp; tinfl_status status; tinfl_init(&decomp); + status = tinfl_decompress(&decomp, (const mz_uint8*)pSrc_buf, &src_buf_len, (mz_uint8*)pOut_buf, (mz_uint8*)pOut_buf, &out_buf_len, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); + return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED : out_buf_len; +} + +int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) +{ + int result = 0; + tinfl_decompressor decomp; + mz_uint8 *pDict = (mz_uint8*)MZ_MALLOC(TINFL_LZ_DICT_SIZE); size_t in_buf_ofs = 0, dict_ofs = 0; + if (!pDict) + return TINFL_STATUS_FAILED; + tinfl_init(&decomp); + for ( ; ; ) + { + size_t in_buf_size = *pIn_buf_size - in_buf_ofs, dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs; + tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8*)pIn_buf + in_buf_ofs, &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size, + (flags & ~(TINFL_FLAG_HAS_MORE_INPUT | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))); + in_buf_ofs += in_buf_size; + if ((dst_buf_size) && (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user))) + break; + if (status != TINFL_STATUS_HAS_MORE_OUTPUT) + { + result = (status == TINFL_STATUS_DONE); + break; + } + dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1); + } + MZ_FREE(pDict); + *pIn_buf_size = in_buf_ofs; + return result; +} + +// ------------------- Low-level Compression (independent from all decompression API's) + +// Purposely making these tables static for faster init and thread safety. +static const mz_uint16 s_tdefl_len_sym[256] = { + 257,258,259,260,261,262,263,264,265,265,266,266,267,267,268,268,269,269,269,269,270,270,270,270,271,271,271,271,272,272,272,272, + 273,273,273,273,273,273,273,273,274,274,274,274,274,274,274,274,275,275,275,275,275,275,275,275,276,276,276,276,276,276,276,276, + 277,277,277,277,277,277,277,277,277,277,277,277,277,277,277,277,278,278,278,278,278,278,278,278,278,278,278,278,278,278,278,278, + 279,279,279,279,279,279,279,279,279,279,279,279,279,279,279,279,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280, + 281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281, + 282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282, + 283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283, + 284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,285 }; + +static const mz_uint8 s_tdefl_len_extra[256] = { + 0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, + 4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, + 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, + 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,0 }; + +static const mz_uint8 s_tdefl_small_dist_sym[512] = { + 0,1,2,3,4,4,5,5,6,6,6,6,7,7,7,7,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11, + 11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13, + 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,14,14,14,14,14,14,14,14,14,14,14,14, + 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14, + 14,14,14,14,14,14,14,14,14,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15, + 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,17,17,17,17,17,17,17,17,17,17,17,17,17,17, + 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17, + 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17, + 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17 }; + +static const mz_uint8 s_tdefl_small_dist_extra[512] = { + 0,0,0,0,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5, + 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, + 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, + 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, + 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, + 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, + 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, + 7,7,7,7,7,7,7,7 }; + +static const mz_uint8 s_tdefl_large_dist_sym[128] = { + 0,0,18,19,20,20,21,21,22,22,22,22,23,23,23,23,24,24,24,24,24,24,24,24,25,25,25,25,25,25,25,25,26,26,26,26,26,26,26,26,26,26,26,26, + 26,26,26,26,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28, + 28,28,28,28,28,28,28,28,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29 }; + +static const mz_uint8 s_tdefl_large_dist_extra[128] = { + 0,0,8,8,9,9,9,9,10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12, + 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13, + 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13 }; + +// Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted values. +typedef struct { mz_uint16 m_key, m_sym_index; } tdefl_sym_freq; +static tdefl_sym_freq* tdefl_radix_sort_syms(mz_uint num_syms, tdefl_sym_freq* pSyms0, tdefl_sym_freq* pSyms1) +{ + mz_uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2]; tdefl_sym_freq* pCur_syms = pSyms0, *pNew_syms = pSyms1; MZ_CLEAR_OBJ(hist); + for (i = 0; i < num_syms; i++) { mz_uint freq = pSyms0[i].m_key; hist[freq & 0xFF]++; hist[256 + ((freq >> 8) & 0xFF)]++; } + while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256])) total_passes--; + for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8) + { + const mz_uint32* pHist = &hist[pass << 8]; + mz_uint offsets[256], cur_ofs = 0; + for (i = 0; i < 256; i++) { offsets[i] = cur_ofs; cur_ofs += pHist[i]; } + for (i = 0; i < num_syms; i++) pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] = pCur_syms[i]; + { tdefl_sym_freq* t = pCur_syms; pCur_syms = pNew_syms; pNew_syms = t; } + } + return pCur_syms; +} + +// tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat, alistair@cs.mu.oz.au, Jyrki Katajainen, jyrki@diku.dk, November 1996. +static void tdefl_calculate_minimum_redundancy(tdefl_sym_freq *A, int n) +{ + int root, leaf, next, avbl, used, dpth; + if (n==0) return; else if (n==1) { A[0].m_key = 1; return; } + A[0].m_key += A[1].m_key; root = 0; leaf = 2; + for (next=1; next < n-1; next++) + { + if (leaf>=n || A[root].m_key=n || (root=0; next--) A[next].m_key = A[A[next].m_key].m_key+1; + avbl = 1; used = dpth = 0; root = n-2; next = n-1; + while (avbl>0) + { + while (root>=0 && (int)A[root].m_key==dpth) { used++; root--; } + while (avbl>used) { A[next--].m_key = (mz_uint16)(dpth); avbl--; } + avbl = 2*used; dpth++; used = 0; + } +} + +// Limits canonical Huffman code table's max code size. +enum { TDEFL_MAX_SUPPORTED_HUFF_CODESIZE = 32 }; +static void tdefl_huffman_enforce_max_code_size(int *pNum_codes, int code_list_len, int max_code_size) +{ + int i; mz_uint32 total = 0; if (code_list_len <= 1) return; + for (i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++) pNum_codes[max_code_size] += pNum_codes[i]; + for (i = max_code_size; i > 0; i--) total += (((mz_uint32)pNum_codes[i]) << (max_code_size - i)); + while (total != (1UL << max_code_size)) + { + pNum_codes[max_code_size]--; + for (i = max_code_size - 1; i > 0; i--) if (pNum_codes[i]) { pNum_codes[i]--; pNum_codes[i + 1] += 2; break; } + total--; + } +} + +static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num, int table_len, int code_size_limit, int static_table) +{ + int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE]; mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1]; MZ_CLEAR_OBJ(num_codes); + if (static_table) + { + for (i = 0; i < table_len; i++) num_codes[d->m_huff_code_sizes[table_num][i]]++; + } + else + { + tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], syms1[TDEFL_MAX_HUFF_SYMBOLS], *pSyms; + int num_used_syms = 0; + const mz_uint16 *pSym_count = &d->m_huff_count[table_num][0]; + for (i = 0; i < table_len; i++) if (pSym_count[i]) { syms0[num_used_syms].m_key = (mz_uint16)pSym_count[i]; syms0[num_used_syms++].m_sym_index = (mz_uint16)i; } + + pSyms = tdefl_radix_sort_syms(num_used_syms, syms0, syms1); tdefl_calculate_minimum_redundancy(pSyms, num_used_syms); + + for (i = 0; i < num_used_syms; i++) num_codes[pSyms[i].m_key]++; + + tdefl_huffman_enforce_max_code_size(num_codes, num_used_syms, code_size_limit); + + MZ_CLEAR_OBJ(d->m_huff_code_sizes[table_num]); MZ_CLEAR_OBJ(d->m_huff_codes[table_num]); + for (i = 1, j = num_used_syms; i <= code_size_limit; i++) + for (l = num_codes[i]; l > 0; l--) d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (mz_uint8)(i); + } + + next_code[1] = 0; for (j = 0, i = 2; i <= code_size_limit; i++) next_code[i] = j = ((j + num_codes[i - 1]) << 1); + + for (i = 0; i < table_len; i++) + { + mz_uint rev_code = 0, code, code_size; if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0) continue; + code = next_code[code_size]++; for (l = code_size; l > 0; l--, code >>= 1) rev_code = (rev_code << 1) | (code & 1); + d->m_huff_codes[table_num][i] = (mz_uint16)rev_code; + } +} + +#define TDEFL_PUT_BITS(b, l) do { \ + mz_uint bits = b; mz_uint len = l; MZ_ASSERT(bits <= ((1U << len) - 1U)); \ + d->m_bit_buffer |= (bits << d->m_bits_in); d->m_bits_in += len; \ + while (d->m_bits_in >= 8) { \ + if (d->m_pOutput_buf < d->m_pOutput_buf_end) \ + *d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \ + d->m_bit_buffer >>= 8; \ + d->m_bits_in -= 8; \ + } \ +} MZ_MACRO_END + +#define TDEFL_RLE_PREV_CODE_SIZE() { if (rle_repeat_count) { \ + if (rle_repeat_count < 3) { \ + d->m_huff_count[2][prev_code_size] = (mz_uint16)(d->m_huff_count[2][prev_code_size] + rle_repeat_count); \ + while (rle_repeat_count--) packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \ + } else { \ + d->m_huff_count[2][16] = (mz_uint16)(d->m_huff_count[2][16] + 1); packed_code_sizes[num_packed_code_sizes++] = 16; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_repeat_count - 3); \ +} rle_repeat_count = 0; } } + +#define TDEFL_RLE_ZERO_CODE_SIZE() { if (rle_z_count) { \ + if (rle_z_count < 3) { \ + d->m_huff_count[2][0] = (mz_uint16)(d->m_huff_count[2][0] + rle_z_count); while (rle_z_count--) packed_code_sizes[num_packed_code_sizes++] = 0; \ + } else if (rle_z_count <= 10) { \ + d->m_huff_count[2][17] = (mz_uint16)(d->m_huff_count[2][17] + 1); packed_code_sizes[num_packed_code_sizes++] = 17; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 3); \ + } else { \ + d->m_huff_count[2][18] = (mz_uint16)(d->m_huff_count[2][18] + 1); packed_code_sizes[num_packed_code_sizes++] = 18; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 11); \ +} rle_z_count = 0; } } + +static mz_uint8 s_tdefl_packed_code_size_syms_swizzle[] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; + +static void tdefl_start_dynamic_block(tdefl_compressor *d) +{ + int num_lit_codes, num_dist_codes, num_bit_lengths; mz_uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count, rle_repeat_count, packed_code_sizes_index; + mz_uint8 code_sizes_to_pack[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], packed_code_sizes[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], prev_code_size = 0xFF; + + d->m_huff_count[0][256] = 1; + + tdefl_optimize_huffman_table(d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, MZ_FALSE); + tdefl_optimize_huffman_table(d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, MZ_FALSE); + + for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--) if (d->m_huff_code_sizes[0][num_lit_codes - 1]) break; + for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--) if (d->m_huff_code_sizes[1][num_dist_codes - 1]) break; + + memcpy(code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes); + memcpy(code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0], num_dist_codes); + total_code_sizes_to_pack = num_lit_codes + num_dist_codes; num_packed_code_sizes = 0; rle_z_count = 0; rle_repeat_count = 0; + + memset(&d->m_huff_count[2][0], 0, sizeof(d->m_huff_count[2][0]) * TDEFL_MAX_HUFF_SYMBOLS_2); + for (i = 0; i < total_code_sizes_to_pack; i++) + { + mz_uint8 code_size = code_sizes_to_pack[i]; + if (!code_size) + { + TDEFL_RLE_PREV_CODE_SIZE(); + if (++rle_z_count == 138) { TDEFL_RLE_ZERO_CODE_SIZE(); } + } + else + { + TDEFL_RLE_ZERO_CODE_SIZE(); + if (code_size != prev_code_size) + { + TDEFL_RLE_PREV_CODE_SIZE(); + d->m_huff_count[2][code_size] = (mz_uint16)(d->m_huff_count[2][code_size] + 1); packed_code_sizes[num_packed_code_sizes++] = code_size; + } + else if (++rle_repeat_count == 6) + { + TDEFL_RLE_PREV_CODE_SIZE(); + } + } + prev_code_size = code_size; + } + if (rle_repeat_count) { TDEFL_RLE_PREV_CODE_SIZE(); } else { TDEFL_RLE_ZERO_CODE_SIZE(); } + + tdefl_optimize_huffman_table(d, 2, TDEFL_MAX_HUFF_SYMBOLS_2, 7, MZ_FALSE); + + TDEFL_PUT_BITS(2, 2); + + TDEFL_PUT_BITS(num_lit_codes - 257, 5); + TDEFL_PUT_BITS(num_dist_codes - 1, 5); + + for (num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--) if (d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[num_bit_lengths]]) break; + num_bit_lengths = MZ_MAX(4, (num_bit_lengths + 1)); TDEFL_PUT_BITS(num_bit_lengths - 4, 4); + for (i = 0; (int)i < num_bit_lengths; i++) TDEFL_PUT_BITS(d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[i]], 3); + + for (packed_code_sizes_index = 0; packed_code_sizes_index < num_packed_code_sizes; ) + { + mz_uint code = packed_code_sizes[packed_code_sizes_index++]; MZ_ASSERT(code < TDEFL_MAX_HUFF_SYMBOLS_2); + TDEFL_PUT_BITS(d->m_huff_codes[2][code], d->m_huff_code_sizes[2][code]); + if (code >= 16) TDEFL_PUT_BITS(packed_code_sizes[packed_code_sizes_index++], "\02\03\07"[code - 16]); + } +} + +static void tdefl_start_static_block(tdefl_compressor *d) +{ + mz_uint i; + mz_uint8 *p = &d->m_huff_code_sizes[0][0]; + + for (i = 0; i <= 143; ++i) *p++ = 8; + for ( ; i <= 255; ++i) *p++ = 9; + for ( ; i <= 279; ++i) *p++ = 7; + for ( ; i <= 287; ++i) *p++ = 8; + + memset(d->m_huff_code_sizes[1], 5, 32); + + tdefl_optimize_huffman_table(d, 0, 288, 15, MZ_TRUE); + tdefl_optimize_huffman_table(d, 1, 32, 15, MZ_TRUE); + + TDEFL_PUT_BITS(1, 2); +} + +static const mz_uint mz_bitmasks[17] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF }; + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS +static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) +{ + mz_uint flags; + mz_uint8 *pLZ_codes; + mz_uint8 *pOutput_buf = d->m_pOutput_buf; + mz_uint8 *pLZ_code_buf_end = d->m_pLZ_code_buf; + mz_uint64 bit_buffer = d->m_bit_buffer; + mz_uint bits_in = d->m_bits_in; + +#define TDEFL_PUT_BITS_FAST(b, l) { bit_buffer |= (((mz_uint64)(b)) << bits_in); bits_in += (l); } + + flags = 1; + for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end; flags >>= 1) + { + if (flags == 1) + flags = *pLZ_codes++ | 0x100; + + if (flags & 1) + { + mz_uint s0, s1, n0, n1, sym, num_extra_bits; + mz_uint match_len = pLZ_codes[0], match_dist = *(const mz_uint16 *)(pLZ_codes + 1); pLZ_codes += 3; + + MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS_FAST(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); + + // This sequence coaxes MSVC into using cmov's vs. jmp's. + s0 = s_tdefl_small_dist_sym[match_dist & 511]; + n0 = s_tdefl_small_dist_extra[match_dist & 511]; + s1 = s_tdefl_large_dist_sym[match_dist >> 8]; + n1 = s_tdefl_large_dist_extra[match_dist >> 8]; + sym = (match_dist < 512) ? s0 : s1; + num_extra_bits = (match_dist < 512) ? n0 : n1; + + MZ_ASSERT(d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS_FAST(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); + } + else + { + mz_uint lit = *pLZ_codes++; + MZ_ASSERT(d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); + + if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) + { + flags >>= 1; + lit = *pLZ_codes++; + MZ_ASSERT(d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); + + if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) + { + flags >>= 1; + lit = *pLZ_codes++; + MZ_ASSERT(d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); + } + } + } + + if (pOutput_buf >= d->m_pOutput_buf_end) + return MZ_FALSE; + + *(mz_uint64*)pOutput_buf = bit_buffer; + pOutput_buf += (bits_in >> 3); + bit_buffer >>= (bits_in & ~7); + bits_in &= 7; + } + +#undef TDEFL_PUT_BITS_FAST + + d->m_pOutput_buf = pOutput_buf; + d->m_bits_in = 0; + d->m_bit_buffer = 0; + + while (bits_in) + { + mz_uint32 n = MZ_MIN(bits_in, 16); + TDEFL_PUT_BITS((mz_uint)bit_buffer & mz_bitmasks[n], n); + bit_buffer >>= n; + bits_in -= n; + } + + TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); + + return (d->m_pOutput_buf < d->m_pOutput_buf_end); +} +#else +static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) +{ + mz_uint flags; + mz_uint8 *pLZ_codes; + + flags = 1; + for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf; flags >>= 1) + { + if (flags == 1) + flags = *pLZ_codes++ | 0x100; + if (flags & 1) + { + mz_uint sym, num_extra_bits; + mz_uint match_len = pLZ_codes[0], match_dist = (pLZ_codes[1] | (pLZ_codes[2] << 8)); pLZ_codes += 3; + + MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); + + if (match_dist < 512) + { + sym = s_tdefl_small_dist_sym[match_dist]; num_extra_bits = s_tdefl_small_dist_extra[match_dist]; + } + else + { + sym = s_tdefl_large_dist_sym[match_dist >> 8]; num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8]; + } + MZ_ASSERT(d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); + } + else + { + mz_uint lit = *pLZ_codes++; + MZ_ASSERT(d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); + } + } + + TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); + + return (d->m_pOutput_buf < d->m_pOutput_buf_end); +} +#endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS + +static mz_bool tdefl_compress_block(tdefl_compressor *d, mz_bool static_block) +{ + if (static_block) + tdefl_start_static_block(d); + else + tdefl_start_dynamic_block(d); + return tdefl_compress_lz_codes(d); +} + +static int tdefl_flush_block(tdefl_compressor *d, int flush) +{ + mz_uint saved_bit_buf, saved_bits_in; + mz_uint8 *pSaved_output_buf; + mz_bool comp_block_succeeded = MZ_FALSE; + int n, use_raw_block = ((d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS) != 0) && (d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size; + mz_uint8 *pOutput_buf_start = ((d->m_pPut_buf_func == NULL) && ((*d->m_pOut_buf_size - d->m_out_buf_ofs) >= TDEFL_OUT_BUF_SIZE)) ? ((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs) : d->m_output_buf; + + d->m_pOutput_buf = pOutput_buf_start; + d->m_pOutput_buf_end = d->m_pOutput_buf + TDEFL_OUT_BUF_SIZE - 16; + + MZ_ASSERT(!d->m_output_flush_remaining); + d->m_output_flush_ofs = 0; + d->m_output_flush_remaining = 0; + + *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> d->m_num_flags_left); + d->m_pLZ_code_buf -= (d->m_num_flags_left == 8); + + if ((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index)) + { + TDEFL_PUT_BITS(0x78, 8); TDEFL_PUT_BITS(0x01, 8); + } + + TDEFL_PUT_BITS(flush == TDEFL_FINISH, 1); + + pSaved_output_buf = d->m_pOutput_buf; saved_bit_buf = d->m_bit_buffer; saved_bits_in = d->m_bits_in; + + if (!use_raw_block) + comp_block_succeeded = tdefl_compress_block(d, (d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS) || (d->m_total_lz_bytes < 48)); + + // If the block gets expanded, forget the current contents of the output buffer and send a raw block instead. + if ( ((use_raw_block) || ((d->m_total_lz_bytes) && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >= d->m_total_lz_bytes))) && + ((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size) ) + { + mz_uint i; d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; + TDEFL_PUT_BITS(0, 2); + if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } + for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF) + { + TDEFL_PUT_BITS(d->m_total_lz_bytes & 0xFFFF, 16); + } + for (i = 0; i < d->m_total_lz_bytes; ++i) + { + TDEFL_PUT_BITS(d->m_dict[(d->m_lz_code_buf_dict_pos + i) & TDEFL_LZ_DICT_SIZE_MASK], 8); + } + } + // Check for the extremely unlikely (if not impossible) case of the compressed block not fitting into the output buffer when using dynamic codes. + else if (!comp_block_succeeded) + { + d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; + tdefl_compress_block(d, MZ_TRUE); + } + + if (flush) + { + if (flush == TDEFL_FINISH) + { + if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } + if (d->m_flags & TDEFL_WRITE_ZLIB_HEADER) { mz_uint i, a = d->m_adler32; for (i = 0; i < 4; i++) { TDEFL_PUT_BITS((a >> 24) & 0xFF, 8); a <<= 8; } } + } + else + { + mz_uint i, z = 0; TDEFL_PUT_BITS(0, 3); if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } for (i = 2; i; --i, z ^= 0xFFFF) { TDEFL_PUT_BITS(z & 0xFFFF, 16); } + } + } + + MZ_ASSERT(d->m_pOutput_buf < d->m_pOutput_buf_end); + + memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); + memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); + + d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8; d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes; d->m_total_lz_bytes = 0; d->m_block_index++; + + if ((n = (int)(d->m_pOutput_buf - pOutput_buf_start)) != 0) + { + if (d->m_pPut_buf_func) + { + *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; + if (!(*d->m_pPut_buf_func)(d->m_output_buf, n, d->m_pPut_buf_user)) + return (d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED); + } + else if (pOutput_buf_start == d->m_output_buf) + { + int bytes_to_copy = (int)MZ_MIN((size_t)n, (size_t)(*d->m_pOut_buf_size - d->m_out_buf_ofs)); + memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf, bytes_to_copy); + d->m_out_buf_ofs += bytes_to_copy; + if ((n -= bytes_to_copy) != 0) + { + d->m_output_flush_ofs = bytes_to_copy; + d->m_output_flush_remaining = n; + } + } + else + { + d->m_out_buf_ofs += n; + } + } + + return d->m_output_flush_remaining; +} + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES +#define TDEFL_READ_UNALIGNED_WORD(p) *(const mz_uint16*)(p) +static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) +{ + mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; + mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; + const mz_uint16 *s = (const mz_uint16*)(d->m_dict + pos), *p, *q; + mz_uint16 c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]), s01 = TDEFL_READ_UNALIGNED_WORD(s); + MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); if (max_match_len <= match_len) return; + for ( ; ; ) + { + for ( ; ; ) + { + if (--num_probes_left == 0) return; + #define TDEFL_PROBE \ + next_probe_pos = d->m_next[probe_pos]; \ + if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) return; \ + probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ + if (TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) break; + TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE; + } + if (!dist) break; q = (const mz_uint16*)(d->m_dict + probe_pos); if (TDEFL_READ_UNALIGNED_WORD(q) != s01) continue; p = s; probe_len = 32; + do { } while ( (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && + (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0) ); + if (!probe_len) + { + *pMatch_dist = dist; *pMatch_len = MZ_MIN(max_match_len, TDEFL_MAX_MATCH_LEN); break; + } + else if ((probe_len = ((mz_uint)(p - s) * 2) + (mz_uint)(*(const mz_uint8*)p == *(const mz_uint8*)q)) > match_len) + { + *pMatch_dist = dist; if ((*pMatch_len = match_len = MZ_MIN(max_match_len, probe_len)) == max_match_len) break; + c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]); + } + } +} +#else +static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) +{ + mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; + mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; + const mz_uint8 *s = d->m_dict + pos, *p, *q; + mz_uint8 c0 = d->m_dict[pos + match_len], c1 = d->m_dict[pos + match_len - 1]; + MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); if (max_match_len <= match_len) return; + for ( ; ; ) + { + for ( ; ; ) + { + if (--num_probes_left == 0) return; + #define TDEFL_PROBE \ + next_probe_pos = d->m_next[probe_pos]; \ + if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) return; \ + probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ + if ((d->m_dict[probe_pos + match_len] == c0) && (d->m_dict[probe_pos + match_len - 1] == c1)) break; + TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE; + } + if (!dist) + break; + p = s; + q = d->m_dict + probe_pos; + for (probe_len = 0; probe_len < max_match_len; probe_len++) + if (*p++ != *q++) break; + if (probe_len > match_len) + { + *pMatch_dist = dist; if ((*pMatch_len = match_len = probe_len) == max_match_len) return; + c0 = d->m_dict[pos + match_len]; c1 = d->m_dict[pos + match_len - 1]; + } + } +} +#endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN +static mz_bool tdefl_compress_fast(tdefl_compressor *d) +{ + // Faster, minimally featured LZRW1-style match+parse loop with better register utilization. Intended for applications where raw throughput is valued more highly than ratio. + mz_uint lookahead_pos = d->m_lookahead_pos, lookahead_size = d->m_lookahead_size, dict_size = d->m_dict_size, total_lz_bytes = d->m_total_lz_bytes, num_flags_left = d->m_num_flags_left; + mz_uint8 *pLZ_code_buf = d->m_pLZ_code_buf, *pLZ_flags = d->m_pLZ_flags; + mz_uint cur_pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; + + while ((d->m_src_buf_left) || ((d->m_flush) && (lookahead_size))) + { + const mz_uint TDEFL_COMP_FAST_LOOKAHEAD_SIZE = 4096; + mz_uint dst_pos = (lookahead_pos + lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; + mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(d->m_src_buf_left, TDEFL_COMP_FAST_LOOKAHEAD_SIZE - lookahead_size); + d->m_src_buf_left -= num_bytes_to_process; + lookahead_size += num_bytes_to_process; + + while (num_bytes_to_process) + { + mz_uint32 n = MZ_MIN(TDEFL_LZ_DICT_SIZE - dst_pos, num_bytes_to_process); + memcpy(d->m_dict + dst_pos, d->m_pSrc, n); + if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) + memcpy(d->m_dict + TDEFL_LZ_DICT_SIZE + dst_pos, d->m_pSrc, MZ_MIN(n, (TDEFL_MAX_MATCH_LEN - 1) - dst_pos)); + d->m_pSrc += n; + dst_pos = (dst_pos + n) & TDEFL_LZ_DICT_SIZE_MASK; + num_bytes_to_process -= n; + } + + dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - lookahead_size, dict_size); + if ((!d->m_flush) && (lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE)) break; + + while (lookahead_size >= 4) + { + mz_uint cur_match_dist, cur_match_len = 1; + mz_uint8 *pCur_dict = d->m_dict + cur_pos; + mz_uint first_trigram = (*(const mz_uint32 *)pCur_dict) & 0xFFFFFF; + mz_uint hash = (first_trigram ^ (first_trigram >> (24 - (TDEFL_LZ_HASH_BITS - 8)))) & TDEFL_LEVEL1_HASH_SIZE_MASK; + mz_uint probe_pos = d->m_hash[hash]; + d->m_hash[hash] = (mz_uint16)lookahead_pos; + + if (((cur_match_dist = (mz_uint16)(lookahead_pos - probe_pos)) <= dict_size) && ((*(const mz_uint32 *)(d->m_dict + (probe_pos &= TDEFL_LZ_DICT_SIZE_MASK)) & 0xFFFFFF) == first_trigram)) + { + const mz_uint16 *p = (const mz_uint16 *)pCur_dict; + const mz_uint16 *q = (const mz_uint16 *)(d->m_dict + probe_pos); + mz_uint32 probe_len = 32; + do { } while ( (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && + (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0) ); + cur_match_len = ((mz_uint)(p - (const mz_uint16 *)pCur_dict) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q); + if (!probe_len) + cur_match_len = cur_match_dist ? TDEFL_MAX_MATCH_LEN : 0; + + if ((cur_match_len < TDEFL_MIN_MATCH_LEN) || ((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U*1024U))) + { + cur_match_len = 1; + *pLZ_code_buf++ = (mz_uint8)first_trigram; + *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); + d->m_huff_count[0][(mz_uint8)first_trigram]++; + } + else + { + mz_uint32 s0, s1; + cur_match_len = MZ_MIN(cur_match_len, lookahead_size); + + MZ_ASSERT((cur_match_len >= TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 1) && (cur_match_dist <= TDEFL_LZ_DICT_SIZE)); + + cur_match_dist--; + + pLZ_code_buf[0] = (mz_uint8)(cur_match_len - TDEFL_MIN_MATCH_LEN); + *(mz_uint16 *)(&pLZ_code_buf[1]) = (mz_uint16)cur_match_dist; + pLZ_code_buf += 3; + *pLZ_flags = (mz_uint8)((*pLZ_flags >> 1) | 0x80); + + s0 = s_tdefl_small_dist_sym[cur_match_dist & 511]; + s1 = s_tdefl_large_dist_sym[cur_match_dist >> 8]; + d->m_huff_count[1][(cur_match_dist < 512) ? s0 : s1]++; + + d->m_huff_count[0][s_tdefl_len_sym[cur_match_len - TDEFL_MIN_MATCH_LEN]]++; + } + } + else + { + *pLZ_code_buf++ = (mz_uint8)first_trigram; + *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); + d->m_huff_count[0][(mz_uint8)first_trigram]++; + } + + if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; } + + total_lz_bytes += cur_match_len; + lookahead_pos += cur_match_len; + dict_size = MZ_MIN(dict_size + cur_match_len, TDEFL_LZ_DICT_SIZE); + cur_pos = (cur_pos + cur_match_len) & TDEFL_LZ_DICT_SIZE_MASK; + MZ_ASSERT(lookahead_size >= cur_match_len); + lookahead_size -= cur_match_len; + + if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) + { + int n; + d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; + d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; + if ((n = tdefl_flush_block(d, 0)) != 0) + return (n < 0) ? MZ_FALSE : MZ_TRUE; + total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left; + } + } + + while (lookahead_size) + { + mz_uint8 lit = d->m_dict[cur_pos]; + + total_lz_bytes++; + *pLZ_code_buf++ = lit; + *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); + if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; } + + d->m_huff_count[0][lit]++; + + lookahead_pos++; + dict_size = MZ_MIN(dict_size + 1, TDEFL_LZ_DICT_SIZE); + cur_pos = (cur_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; + lookahead_size--; + + if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) + { + int n; + d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; + d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; + if ((n = tdefl_flush_block(d, 0)) != 0) + return (n < 0) ? MZ_FALSE : MZ_TRUE; + total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left; + } + } + } + + d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; + d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; + return MZ_TRUE; +} +#endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN + +static MZ_FORCEINLINE void tdefl_record_literal(tdefl_compressor *d, mz_uint8 lit) +{ + d->m_total_lz_bytes++; + *d->m_pLZ_code_buf++ = lit; + *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> 1); if (--d->m_num_flags_left == 0) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; } + d->m_huff_count[0][lit]++; +} + +static MZ_FORCEINLINE void tdefl_record_match(tdefl_compressor *d, mz_uint match_len, mz_uint match_dist) +{ + mz_uint32 s0, s1; + + MZ_ASSERT((match_len >= TDEFL_MIN_MATCH_LEN) && (match_dist >= 1) && (match_dist <= TDEFL_LZ_DICT_SIZE)); + + d->m_total_lz_bytes += match_len; + + d->m_pLZ_code_buf[0] = (mz_uint8)(match_len - TDEFL_MIN_MATCH_LEN); + + match_dist -= 1; + d->m_pLZ_code_buf[1] = (mz_uint8)(match_dist & 0xFF); + d->m_pLZ_code_buf[2] = (mz_uint8)(match_dist >> 8); d->m_pLZ_code_buf += 3; + + *d->m_pLZ_flags = (mz_uint8)((*d->m_pLZ_flags >> 1) | 0x80); if (--d->m_num_flags_left == 0) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; } + + s0 = s_tdefl_small_dist_sym[match_dist & 511]; s1 = s_tdefl_large_dist_sym[(match_dist >> 8) & 127]; + d->m_huff_count[1][(match_dist < 512) ? s0 : s1]++; + + if (match_len >= TDEFL_MIN_MATCH_LEN) d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++; +} + +static mz_bool tdefl_compress_normal(tdefl_compressor *d) +{ + const mz_uint8 *pSrc = d->m_pSrc; size_t src_buf_left = d->m_src_buf_left; + tdefl_flush flush = d->m_flush; + + while ((src_buf_left) || ((flush) && (d->m_lookahead_size))) + { + mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos; + // Update dictionary and hash chains. Keeps the lookahead size equal to TDEFL_MAX_MATCH_LEN. + if ((d->m_lookahead_size + d->m_dict_size) >= (TDEFL_MIN_MATCH_LEN - 1)) + { + mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK, ins_pos = d->m_lookahead_pos + d->m_lookahead_size - 2; + mz_uint hash = (d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK]; + mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(src_buf_left, TDEFL_MAX_MATCH_LEN - d->m_lookahead_size); + const mz_uint8 *pSrc_end = pSrc + num_bytes_to_process; + src_buf_left -= num_bytes_to_process; + d->m_lookahead_size += num_bytes_to_process; + while (pSrc != pSrc_end) + { + mz_uint8 c = *pSrc++; d->m_dict[dst_pos] = c; if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; + hash = ((hash << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); + d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)(ins_pos); + dst_pos = (dst_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; ins_pos++; + } + } + else + { + while ((src_buf_left) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) + { + mz_uint8 c = *pSrc++; + mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; + src_buf_left--; + d->m_dict[dst_pos] = c; + if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) + d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; + if ((++d->m_lookahead_size + d->m_dict_size) >= TDEFL_MIN_MATCH_LEN) + { + mz_uint ins_pos = d->m_lookahead_pos + (d->m_lookahead_size - 1) - 2; + mz_uint hash = ((d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << (TDEFL_LZ_HASH_SHIFT * 2)) ^ (d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); + d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)(ins_pos); + } + } + } + d->m_dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size); + if ((!flush) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) + break; + + // Simple lazy/greedy parsing state machine. + len_to_move = 1; cur_match_dist = 0; cur_match_len = d->m_saved_match_len ? d->m_saved_match_len : (TDEFL_MIN_MATCH_LEN - 1); cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; + if (d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS)) + { + if ((d->m_dict_size) && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) + { + mz_uint8 c = d->m_dict[(cur_pos - 1) & TDEFL_LZ_DICT_SIZE_MASK]; + cur_match_len = 0; while (cur_match_len < d->m_lookahead_size) { if (d->m_dict[cur_pos + cur_match_len] != c) break; cur_match_len++; } + if (cur_match_len < TDEFL_MIN_MATCH_LEN) cur_match_len = 0; else cur_match_dist = 1; + } + } + else + { + tdefl_find_match(d, d->m_lookahead_pos, d->m_dict_size, d->m_lookahead_size, &cur_match_dist, &cur_match_len); + } + if (((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U*1024U)) || (cur_pos == cur_match_dist) || ((d->m_flags & TDEFL_FILTER_MATCHES) && (cur_match_len <= 5))) + { + cur_match_dist = cur_match_len = 0; + } + if (d->m_saved_match_len) + { + if (cur_match_len > d->m_saved_match_len) + { + tdefl_record_literal(d, (mz_uint8)d->m_saved_lit); + if (cur_match_len >= 128) + { + tdefl_record_match(d, cur_match_len, cur_match_dist); + d->m_saved_match_len = 0; len_to_move = cur_match_len; + } + else + { + d->m_saved_lit = d->m_dict[cur_pos]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len; + } + } + else + { + tdefl_record_match(d, d->m_saved_match_len, d->m_saved_match_dist); + len_to_move = d->m_saved_match_len - 1; d->m_saved_match_len = 0; + } + } + else if (!cur_match_dist) + tdefl_record_literal(d, d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]); + else if ((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) || (cur_match_len >= 128)) + { + tdefl_record_match(d, cur_match_len, cur_match_dist); + len_to_move = cur_match_len; + } + else + { + d->m_saved_lit = d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len; + } + // Move the lookahead forward by len_to_move bytes. + d->m_lookahead_pos += len_to_move; + MZ_ASSERT(d->m_lookahead_size >= len_to_move); + d->m_lookahead_size -= len_to_move; + d->m_dict_size = MZ_MIN(d->m_dict_size + len_to_move, TDEFL_LZ_DICT_SIZE); + // Check if it's time to flush the current LZ codes to the internal output buffer. + if ( (d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) || + ( (d->m_total_lz_bytes > 31*1024) && (((((mz_uint)(d->m_pLZ_code_buf - d->m_lz_code_buf) * 115) >> 7) >= d->m_total_lz_bytes) || (d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) ) + { + int n; + d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left; + if ((n = tdefl_flush_block(d, 0)) != 0) + return (n < 0) ? MZ_FALSE : MZ_TRUE; + } + } + + d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left; + return MZ_TRUE; +} + +static tdefl_status tdefl_flush_output_buffer(tdefl_compressor *d) +{ + if (d->m_pIn_buf_size) + { + *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; + } + + if (d->m_pOut_buf_size) + { + size_t n = MZ_MIN(*d->m_pOut_buf_size - d->m_out_buf_ofs, d->m_output_flush_remaining); + memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf + d->m_output_flush_ofs, n); + d->m_output_flush_ofs += (mz_uint)n; + d->m_output_flush_remaining -= (mz_uint)n; + d->m_out_buf_ofs += n; + + *d->m_pOut_buf_size = d->m_out_buf_ofs; + } + + return (d->m_finished && !d->m_output_flush_remaining) ? TDEFL_STATUS_DONE : TDEFL_STATUS_OKAY; +} + +tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush) +{ + if (!d) + { + if (pIn_buf_size) *pIn_buf_size = 0; + if (pOut_buf_size) *pOut_buf_size = 0; + return TDEFL_STATUS_BAD_PARAM; + } + + d->m_pIn_buf = pIn_buf; d->m_pIn_buf_size = pIn_buf_size; + d->m_pOut_buf = pOut_buf; d->m_pOut_buf_size = pOut_buf_size; + d->m_pSrc = (const mz_uint8 *)(pIn_buf); d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0; + d->m_out_buf_ofs = 0; + d->m_flush = flush; + + if ( ((d->m_pPut_buf_func != NULL) == ((pOut_buf != NULL) || (pOut_buf_size != NULL))) || (d->m_prev_return_status != TDEFL_STATUS_OKAY) || + (d->m_wants_to_finish && (flush != TDEFL_FINISH)) || (pIn_buf_size && *pIn_buf_size && !pIn_buf) || (pOut_buf_size && *pOut_buf_size && !pOut_buf) ) + { + if (pIn_buf_size) *pIn_buf_size = 0; + if (pOut_buf_size) *pOut_buf_size = 0; + return (d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM); + } + d->m_wants_to_finish |= (flush == TDEFL_FINISH); + + if ((d->m_output_flush_remaining) || (d->m_finished)) + return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN + if (((d->m_flags & TDEFL_MAX_PROBES_MASK) == 1) && + ((d->m_flags & TDEFL_GREEDY_PARSING_FLAG) != 0) && + ((d->m_flags & (TDEFL_FILTER_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS | TDEFL_RLE_MATCHES)) == 0)) + { + if (!tdefl_compress_fast(d)) + return d->m_prev_return_status; + } + else +#endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN + { + if (!tdefl_compress_normal(d)) + return d->m_prev_return_status; + } + + if ((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) && (pIn_buf)) + d->m_adler32 = (mz_uint32)mz_adler32(d->m_adler32, (const mz_uint8 *)pIn_buf, d->m_pSrc - (const mz_uint8 *)pIn_buf); + + if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) && (!d->m_output_flush_remaining)) + { + if (tdefl_flush_block(d, flush) < 0) + return d->m_prev_return_status; + d->m_finished = (flush == TDEFL_FINISH); + if (flush == TDEFL_FULL_FLUSH) { MZ_CLEAR_OBJ(d->m_hash); MZ_CLEAR_OBJ(d->m_next); d->m_dict_size = 0; } + } + + return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); +} + +tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush) +{ + MZ_ASSERT(d->m_pPut_buf_func); return tdefl_compress(d, pIn_buf, &in_buf_size, NULL, NULL, flush); +} + +tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) +{ + d->m_pPut_buf_func = pPut_buf_func; d->m_pPut_buf_user = pPut_buf_user; + d->m_flags = (mz_uint)(flags); d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3; d->m_greedy_parsing = (flags & TDEFL_GREEDY_PARSING_FLAG) != 0; + d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3; + if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) MZ_CLEAR_OBJ(d->m_hash); + d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size = d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0; + d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished = d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0; + d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8; + d->m_pOutput_buf = d->m_output_buf; d->m_pOutput_buf_end = d->m_output_buf; d->m_prev_return_status = TDEFL_STATUS_OKAY; + d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0; d->m_adler32 = 1; + d->m_pIn_buf = NULL; d->m_pOut_buf = NULL; + d->m_pIn_buf_size = NULL; d->m_pOut_buf_size = NULL; + d->m_flush = TDEFL_NO_FLUSH; d->m_pSrc = NULL; d->m_src_buf_left = 0; d->m_out_buf_ofs = 0; + memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); + memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); + return TDEFL_STATUS_OKAY; +} + +tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d) +{ + return d->m_prev_return_status; +} + +mz_uint32 tdefl_get_adler32(tdefl_compressor *d) +{ + return d->m_adler32; +} + +mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) +{ + tdefl_compressor *pComp; mz_bool succeeded; if (((buf_len) && (!pBuf)) || (!pPut_buf_func)) return MZ_FALSE; + pComp = (tdefl_compressor*)MZ_MALLOC(sizeof(tdefl_compressor)); if (!pComp) return MZ_FALSE; + succeeded = (tdefl_init(pComp, pPut_buf_func, pPut_buf_user, flags) == TDEFL_STATUS_OKAY); + succeeded = succeeded && (tdefl_compress_buffer(pComp, pBuf, buf_len, TDEFL_FINISH) == TDEFL_STATUS_DONE); + MZ_FREE(pComp); return succeeded; +} + +typedef struct +{ + size_t m_size, m_capacity; + mz_uint8 *m_pBuf; + mz_bool m_expandable; +} tdefl_output_buffer; + +static mz_bool tdefl_output_buffer_putter(const void *pBuf, int len, void *pUser) +{ + tdefl_output_buffer *p = (tdefl_output_buffer *)pUser; + size_t new_size = p->m_size + len; + if (new_size > p->m_capacity) + { + size_t new_capacity = p->m_capacity; mz_uint8 *pNew_buf; if (!p->m_expandable) return MZ_FALSE; + do { new_capacity = MZ_MAX(128U, new_capacity << 1U); } while (new_size > new_capacity); + pNew_buf = (mz_uint8*)MZ_REALLOC(p->m_pBuf, new_capacity); if (!pNew_buf) return MZ_FALSE; + p->m_pBuf = pNew_buf; p->m_capacity = new_capacity; + } + memcpy((mz_uint8*)p->m_pBuf + p->m_size, pBuf, len); p->m_size = new_size; + return MZ_TRUE; +} + +void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) +{ + tdefl_output_buffer out_buf; MZ_CLEAR_OBJ(out_buf); + if (!pOut_len) return MZ_FALSE; else *pOut_len = 0; + out_buf.m_expandable = MZ_TRUE; + if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) return NULL; + *pOut_len = out_buf.m_size; return out_buf.m_pBuf; +} + +size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) +{ + tdefl_output_buffer out_buf; MZ_CLEAR_OBJ(out_buf); + if (!pOut_buf) return 0; + out_buf.m_pBuf = (mz_uint8*)pOut_buf; out_buf.m_capacity = out_buf_len; + if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) return 0; + return out_buf.m_size; +} + +#ifndef MINIZ_NO_ZLIB_APIS +static const mz_uint s_tdefl_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 }; + +// level may actually range from [0,10] (10 is a "hidden" max level, where we want a bit more compression and it's fine if throughput to fall off a cliff on some files). +mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy) +{ + mz_uint comp_flags = s_tdefl_num_probes[(level >= 0) ? MZ_MIN(10, level) : MZ_DEFAULT_LEVEL] | ((level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0); + if (window_bits > 0) comp_flags |= TDEFL_WRITE_ZLIB_HEADER; + + if (!level) comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS; + else if (strategy == MZ_FILTERED) comp_flags |= TDEFL_FILTER_MATCHES; + else if (strategy == MZ_HUFFMAN_ONLY) comp_flags &= ~TDEFL_MAX_PROBES_MASK; + else if (strategy == MZ_FIXED) comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS; + else if (strategy == MZ_RLE) comp_flags |= TDEFL_RLE_MATCHES; + + return comp_flags; +} +#endif //MINIZ_NO_ZLIB_APIS + +#ifdef _MSC_VER +#pragma warning (push) +#pragma warning (disable:4204) // nonstandard extension used : non-constant aggregate initializer (also supported by GNU C and C99, so no big deal) +#endif + +// Simple PNG writer function by Alex Evans, 2011. Released into the public domain: https://gist.github.com/908299, more context at +// http://altdevblogaday.org/2011/04/06/a-smaller-jpg-encoder/. +// This is actually a modification of Alex's original code so PNG files generated by this function pass pngcheck. +void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip) +{ + // Using a local copy of this array here in case MINIZ_NO_ZLIB_APIS was defined. + static const mz_uint s_tdefl_png_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 }; + tdefl_compressor *pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); tdefl_output_buffer out_buf; int i, bpl = w * num_chans, y, z; mz_uint32 c; *pLen_out = 0; + if (!pComp) return NULL; + MZ_CLEAR_OBJ(out_buf); out_buf.m_expandable = MZ_TRUE; out_buf.m_capacity = 57+MZ_MAX(64, (1+bpl)*h); if (NULL == (out_buf.m_pBuf = (mz_uint8*)MZ_MALLOC(out_buf.m_capacity))) { MZ_FREE(pComp); return NULL; } + // write dummy header + for (z = 41; z; --z) tdefl_output_buffer_putter(&z, 1, &out_buf); + // compress image data + tdefl_init(pComp, tdefl_output_buffer_putter, &out_buf, s_tdefl_png_num_probes[MZ_MIN(10, level)] | TDEFL_WRITE_ZLIB_HEADER); + for (y = 0; y < h; ++y) { tdefl_compress_buffer(pComp, &z, 1, TDEFL_NO_FLUSH); tdefl_compress_buffer(pComp, (mz_uint8*)pImage + (flip ? (h - 1 - y) : y) * bpl, bpl, TDEFL_NO_FLUSH); } + if (tdefl_compress_buffer(pComp, NULL, 0, TDEFL_FINISH) != TDEFL_STATUS_DONE) { MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; } + // write real header + *pLen_out = out_buf.m_size-41; + { + static const mz_uint8 chans[] = {0x00, 0x00, 0x04, 0x02, 0x06}; + mz_uint8 pnghdr[41]={0x89,0x50,0x4e,0x47,0x0d,0x0a,0x1a,0x0a,0x00,0x00,0x00,0x0d,0x49,0x48,0x44,0x52, + 0,0,(mz_uint8)(w>>8),(mz_uint8)w,0,0,(mz_uint8)(h>>8),(mz_uint8)h,8,chans[num_chans],0,0,0,0,0,0,0, + (mz_uint8)(*pLen_out>>24),(mz_uint8)(*pLen_out>>16),(mz_uint8)(*pLen_out>>8),(mz_uint8)*pLen_out,0x49,0x44,0x41,0x54}; + c=(mz_uint32)mz_crc32(MZ_CRC32_INIT,pnghdr+12,17); for (i=0; i<4; ++i, c<<=8) ((mz_uint8*)(pnghdr+29))[i]=(mz_uint8)(c>>24); + memcpy(out_buf.m_pBuf, pnghdr, 41); + } + // write footer (IDAT CRC-32, followed by IEND chunk) + if (!tdefl_output_buffer_putter("\0\0\0\0\0\0\0\0\x49\x45\x4e\x44\xae\x42\x60\x82", 16, &out_buf)) { *pLen_out = 0; MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; } + c = (mz_uint32)mz_crc32(MZ_CRC32_INIT,out_buf.m_pBuf+41-4, *pLen_out+4); for (i=0; i<4; ++i, c<<=8) (out_buf.m_pBuf+out_buf.m_size-16)[i] = (mz_uint8)(c >> 24); + // compute final size of file, grab compressed data buffer and return + *pLen_out += 57; MZ_FREE(pComp); return out_buf.m_pBuf; +} +void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out) +{ + // Level 6 corresponds to TDEFL_DEFAULT_MAX_PROBES or MZ_DEFAULT_LEVEL (but we can't depend on MZ_DEFAULT_LEVEL being available in case the zlib API's where #defined out) + return tdefl_write_image_to_png_file_in_memory_ex(pImage, w, h, num_chans, pLen_out, 6, MZ_FALSE); +} + +#ifdef _MSC_VER +#pragma warning (pop) +#endif + +// ------------------- .ZIP archive reading + +#ifndef MINIZ_NO_ARCHIVE_APIS + +#ifdef MINIZ_NO_STDIO + #define MZ_FILE void * +#else + #include + #include + + #if defined(_MSC_VER) || defined(__MINGW64__) + static FILE *mz_fopen(const char *pFilename, const char *pMode) + { + FILE* pFile = NULL; + fopen_s(&pFile, pFilename, pMode); + return pFile; + } + static FILE *mz_freopen(const char *pPath, const char *pMode, FILE *pStream) + { + FILE* pFile = NULL; + if (freopen_s(&pFile, pPath, pMode, pStream)) + return NULL; + return pFile; + } + #ifndef MINIZ_NO_TIME + #include + #endif + #define MZ_FILE FILE + #define MZ_FOPEN mz_fopen + #define MZ_FCLOSE fclose + #define MZ_FREAD fread + #define MZ_FWRITE fwrite + #define MZ_FTELL64 _ftelli64 + #define MZ_FSEEK64 _fseeki64 + #define MZ_FILE_STAT_STRUCT _stat + #define MZ_FILE_STAT _stat + #define MZ_FFLUSH fflush + #define MZ_FREOPEN mz_freopen + #define MZ_DELETE_FILE remove + #elif defined(__MINGW32__) + #ifndef MINIZ_NO_TIME + #include + #endif + #define MZ_FILE FILE + #define MZ_FOPEN(f, m) fopen(f, m) + #define MZ_FCLOSE fclose + #define MZ_FREAD fread + #define MZ_FWRITE fwrite + #define MZ_FTELL64 ftello64 + #define MZ_FSEEK64 fseeko64 + #define MZ_FILE_STAT_STRUCT _stat + #define MZ_FILE_STAT _stat + #define MZ_FFLUSH fflush + #define MZ_FREOPEN(f, m, s) freopen(f, m, s) + #define MZ_DELETE_FILE remove + #elif defined(__TINYC__) + #ifndef MINIZ_NO_TIME + #include + #endif + #define MZ_FILE FILE + #define MZ_FOPEN(f, m) fopen(f, m) + #define MZ_FCLOSE fclose + #define MZ_FREAD fread + #define MZ_FWRITE fwrite + #define MZ_FTELL64 ftell + #define MZ_FSEEK64 fseek + #define MZ_FILE_STAT_STRUCT stat + #define MZ_FILE_STAT stat + #define MZ_FFLUSH fflush + #define MZ_FREOPEN(f, m, s) freopen(f, m, s) + #define MZ_DELETE_FILE remove + #elif defined(__GNUC__) && _LARGEFILE64_SOURCE + #ifndef MINIZ_NO_TIME + #include + #endif + #define MZ_FILE FILE + #define MZ_FOPEN(f, m) fopen64(f, m) + #define MZ_FCLOSE fclose + #define MZ_FREAD fread + #define MZ_FWRITE fwrite + #define MZ_FTELL64 ftello64 + #define MZ_FSEEK64 fseeko64 + #define MZ_FILE_STAT_STRUCT stat64 + #define MZ_FILE_STAT stat64 + #define MZ_FFLUSH fflush + #define MZ_FREOPEN(p, m, s) freopen64(p, m, s) + #define MZ_DELETE_FILE remove + #else + #ifndef MINIZ_NO_TIME + #include + #endif + #define MZ_FILE FILE + #define MZ_FOPEN(f, m) fopen(f, m) + #define MZ_FCLOSE fclose + #define MZ_FREAD fread + #define MZ_FWRITE fwrite + #define MZ_FTELL64 ftello + #define MZ_FSEEK64 fseeko + #define MZ_FILE_STAT_STRUCT stat + #define MZ_FILE_STAT stat + #define MZ_FFLUSH fflush + #define MZ_FREOPEN(f, m, s) freopen(f, m, s) + #define MZ_DELETE_FILE remove + #endif // #ifdef _MSC_VER +#endif // #ifdef MINIZ_NO_STDIO + +#define MZ_TOLOWER(c) ((((c) >= 'A') && ((c) <= 'Z')) ? ((c) - 'A' + 'a') : (c)) + +// Various ZIP archive enums. To completely avoid cross platform compiler alignment and platform endian issues, miniz.c doesn't use structs for any of this stuff. +enum +{ + // ZIP archive identifiers and record sizes + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06054b50, MZ_ZIP_CENTRAL_DIR_HEADER_SIG = 0x02014b50, MZ_ZIP_LOCAL_DIR_HEADER_SIG = 0x04034b50, + MZ_ZIP_LOCAL_DIR_HEADER_SIZE = 30, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE = 46, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE = 22, + // Central directory header record offsets + MZ_ZIP_CDH_SIG_OFS = 0, MZ_ZIP_CDH_VERSION_MADE_BY_OFS = 4, MZ_ZIP_CDH_VERSION_NEEDED_OFS = 6, MZ_ZIP_CDH_BIT_FLAG_OFS = 8, + MZ_ZIP_CDH_METHOD_OFS = 10, MZ_ZIP_CDH_FILE_TIME_OFS = 12, MZ_ZIP_CDH_FILE_DATE_OFS = 14, MZ_ZIP_CDH_CRC32_OFS = 16, + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS = 20, MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS = 24, MZ_ZIP_CDH_FILENAME_LEN_OFS = 28, MZ_ZIP_CDH_EXTRA_LEN_OFS = 30, + MZ_ZIP_CDH_COMMENT_LEN_OFS = 32, MZ_ZIP_CDH_DISK_START_OFS = 34, MZ_ZIP_CDH_INTERNAL_ATTR_OFS = 36, MZ_ZIP_CDH_EXTERNAL_ATTR_OFS = 38, MZ_ZIP_CDH_LOCAL_HEADER_OFS = 42, + // Local directory header offsets + MZ_ZIP_LDH_SIG_OFS = 0, MZ_ZIP_LDH_VERSION_NEEDED_OFS = 4, MZ_ZIP_LDH_BIT_FLAG_OFS = 6, MZ_ZIP_LDH_METHOD_OFS = 8, MZ_ZIP_LDH_FILE_TIME_OFS = 10, + MZ_ZIP_LDH_FILE_DATE_OFS = 12, MZ_ZIP_LDH_CRC32_OFS = 14, MZ_ZIP_LDH_COMPRESSED_SIZE_OFS = 18, MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS = 22, + MZ_ZIP_LDH_FILENAME_LEN_OFS = 26, MZ_ZIP_LDH_EXTRA_LEN_OFS = 28, + // End of central directory offsets + MZ_ZIP_ECDH_SIG_OFS = 0, MZ_ZIP_ECDH_NUM_THIS_DISK_OFS = 4, MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS = 6, MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 8, + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS = 10, MZ_ZIP_ECDH_CDIR_SIZE_OFS = 12, MZ_ZIP_ECDH_CDIR_OFS_OFS = 16, MZ_ZIP_ECDH_COMMENT_SIZE_OFS = 20, +}; + +typedef struct +{ + void *m_p; + size_t m_size, m_capacity; + mz_uint m_element_size; +} mz_zip_array; + +struct mz_zip_internal_state_tag +{ + mz_zip_array m_central_dir; + mz_zip_array m_central_dir_offsets; + mz_zip_array m_sorted_central_dir_offsets; + MZ_FILE *m_pFile; + void *m_pMem; + size_t m_mem_size; + size_t m_mem_capacity; +}; + +#define MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(array_ptr, element_size) (array_ptr)->m_element_size = element_size +#define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) ((element_type *)((array_ptr)->m_p))[index] + +static MZ_FORCEINLINE void mz_zip_array_clear(mz_zip_archive *pZip, mz_zip_array *pArray) +{ + pZip->m_pFree(pZip->m_pAlloc_opaque, pArray->m_p); + memset(pArray, 0, sizeof(mz_zip_array)); +} + +static mz_bool mz_zip_array_ensure_capacity(mz_zip_archive *pZip, mz_zip_array *pArray, size_t min_new_capacity, mz_uint growing) +{ + void *pNew_p; size_t new_capacity = min_new_capacity; MZ_ASSERT(pArray->m_element_size); if (pArray->m_capacity >= min_new_capacity) return MZ_TRUE; + if (growing) { new_capacity = MZ_MAX(1, pArray->m_capacity); while (new_capacity < min_new_capacity) new_capacity *= 2; } + if (NULL == (pNew_p = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pArray->m_p, pArray->m_element_size, new_capacity))) return MZ_FALSE; + pArray->m_p = pNew_p; pArray->m_capacity = new_capacity; + return MZ_TRUE; +} + +static MZ_FORCEINLINE mz_bool mz_zip_array_reserve(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_capacity, mz_uint growing) +{ + if (new_capacity > pArray->m_capacity) { if (!mz_zip_array_ensure_capacity(pZip, pArray, new_capacity, growing)) return MZ_FALSE; } + return MZ_TRUE; +} + +static MZ_FORCEINLINE mz_bool mz_zip_array_resize(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_size, mz_uint growing) +{ + if (new_size > pArray->m_capacity) { if (!mz_zip_array_ensure_capacity(pZip, pArray, new_size, growing)) return MZ_FALSE; } + pArray->m_size = new_size; + return MZ_TRUE; +} + +static MZ_FORCEINLINE mz_bool mz_zip_array_ensure_room(mz_zip_archive *pZip, mz_zip_array *pArray, size_t n) +{ + return mz_zip_array_reserve(pZip, pArray, pArray->m_size + n, MZ_TRUE); +} + +static MZ_FORCEINLINE mz_bool mz_zip_array_push_back(mz_zip_archive *pZip, mz_zip_array *pArray, const void *pElements, size_t n) +{ + size_t orig_size = pArray->m_size; if (!mz_zip_array_resize(pZip, pArray, orig_size + n, MZ_TRUE)) return MZ_FALSE; + memcpy((mz_uint8*)pArray->m_p + orig_size * pArray->m_element_size, pElements, n * pArray->m_element_size); + return MZ_TRUE; +} + +#ifndef MINIZ_NO_TIME +static time_t mz_zip_dos_to_time_t(int dos_time, int dos_date) +{ + struct tm tm; + memset(&tm, 0, sizeof(tm)); tm.tm_isdst = -1; + tm.tm_year = ((dos_date >> 9) & 127) + 1980 - 1900; tm.tm_mon = ((dos_date >> 5) & 15) - 1; tm.tm_mday = dos_date & 31; + tm.tm_hour = (dos_time >> 11) & 31; tm.tm_min = (dos_time >> 5) & 63; tm.tm_sec = (dos_time << 1) & 62; + return mktime(&tm); +} + +static void mz_zip_time_to_dos_time(time_t time, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date) +{ +#ifdef _MSC_VER + struct tm tm_struct; + struct tm *tm = &tm_struct; + errno_t err = localtime_s(tm, &time); + if (err) + { + *pDOS_date = 0; *pDOS_time = 0; + return; + } +#else + struct tm *tm = localtime(&time); +#endif + *pDOS_time = (mz_uint16)(((tm->tm_hour) << 11) + ((tm->tm_min) << 5) + ((tm->tm_sec) >> 1)); + *pDOS_date = (mz_uint16)(((tm->tm_year + 1900 - 1980) << 9) + ((tm->tm_mon + 1) << 5) + tm->tm_mday); +} +#endif + +#ifndef MINIZ_NO_STDIO +static mz_bool mz_zip_get_file_modified_time(const char *pFilename, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date) +{ +#ifdef MINIZ_NO_TIME + (void)pFilename; *pDOS_date = *pDOS_time = 0; +#else + struct MZ_FILE_STAT_STRUCT file_stat; + // On Linux with x86 glibc, this call will fail on large files (>= 0x80000000 bytes) unless you compiled with _LARGEFILE64_SOURCE. Argh. + if (MZ_FILE_STAT(pFilename, &file_stat) != 0) + return MZ_FALSE; + mz_zip_time_to_dos_time(file_stat.st_mtime, pDOS_time, pDOS_date); +#endif // #ifdef MINIZ_NO_TIME + return MZ_TRUE; +} + +#ifndef MINIZ_NO_TIME +static mz_bool mz_zip_set_file_times(const char *pFilename, time_t access_time, time_t modified_time) +{ + struct utimbuf t; t.actime = access_time; t.modtime = modified_time; + return !utime(pFilename, &t); +} +#endif // #ifndef MINIZ_NO_TIME +#endif // #ifndef MINIZ_NO_STDIO + +static mz_bool mz_zip_reader_init_internal(mz_zip_archive *pZip, mz_uint32 flags) +{ + (void)flags; + if ((!pZip) || (pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) + return MZ_FALSE; + + if (!pZip->m_pAlloc) pZip->m_pAlloc = def_alloc_func; + if (!pZip->m_pFree) pZip->m_pFree = def_free_func; + if (!pZip->m_pRealloc) pZip->m_pRealloc = def_realloc_func; + + pZip->m_zip_mode = MZ_ZIP_MODE_READING; + pZip->m_archive_size = 0; + pZip->m_central_directory_file_ofs = 0; + pZip->m_total_files = 0; + + if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) + return MZ_FALSE; + memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); + return MZ_TRUE; +} + +static MZ_FORCEINLINE mz_bool mz_zip_reader_filename_less(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, mz_uint r_index) +{ + const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; + const mz_uint8 *pR = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, r_index)); + mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS), r_len = MZ_READ_LE16(pR + MZ_ZIP_CDH_FILENAME_LEN_OFS); + mz_uint8 l = 0, r = 0; + pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pR += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + pE = pL + MZ_MIN(l_len, r_len); + while (pL < pE) + { + if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) + break; + pL++; pR++; + } + return (pL == pE) ? (l_len < r_len) : (l < r); +} + +#define MZ_SWAP_UINT32(a, b) do { mz_uint32 t = a; a = b; b = t; } MZ_MACRO_END + +// Heap sort of lowercased filenames, used to help accelerate plain central directory searches by mz_zip_reader_locate_file(). (Could also use qsort(), but it could allocate memory.) +static void mz_zip_reader_sort_central_dir_offsets_by_filename(mz_zip_archive *pZip) +{ + mz_zip_internal_state *pState = pZip->m_pState; + const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; + const mz_zip_array *pCentral_dir = &pState->m_central_dir; + mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32, 0); + const int size = pZip->m_total_files; + int start = (size - 2) >> 1, end; + while (start >= 0) + { + int child, root = start; + for ( ; ; ) + { + if ((child = (root << 1) + 1) >= size) + break; + child += (((child + 1) < size) && (mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1]))); + if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) + break; + MZ_SWAP_UINT32(pIndices[root], pIndices[child]); root = child; + } + start--; + } + + end = size - 1; + while (end > 0) + { + int child, root = 0; + MZ_SWAP_UINT32(pIndices[end], pIndices[0]); + for ( ; ; ) + { + if ((child = (root << 1) + 1) >= end) + break; + child += (((child + 1) < end) && mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1])); + if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) + break; + MZ_SWAP_UINT32(pIndices[root], pIndices[child]); root = child; + } + end--; + } +} + +static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip, mz_uint32 flags) +{ + mz_uint cdir_size, num_this_disk, cdir_disk_index; + mz_uint64 cdir_ofs; + mz_int64 cur_file_ofs; + const mz_uint8 *p; + mz_uint32 buf_u32[4096 / sizeof(mz_uint32)]; mz_uint8 *pBuf = (mz_uint8 *)buf_u32; + mz_bool sort_central_dir = ((flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0); + // Basic sanity checks - reject files which are too small, and check the first 4 bytes of the file to make sure a local header is there. + if (pZip->m_archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + return MZ_FALSE; + // Find the end of central directory record by scanning the file from the end towards the beginning. + cur_file_ofs = MZ_MAX((mz_int64)pZip->m_archive_size - (mz_int64)sizeof(buf_u32), 0); + for ( ; ; ) + { + int i, n = (int)MZ_MIN(sizeof(buf_u32), pZip->m_archive_size - cur_file_ofs); + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, n) != (mz_uint)n) + return MZ_FALSE; + for (i = n - 4; i >= 0; --i) + if (MZ_READ_LE32(pBuf + i) == MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) + break; + if (i >= 0) + { + cur_file_ofs += i; + break; + } + if ((!cur_file_ofs) || ((pZip->m_archive_size - cur_file_ofs) >= (0xFFFF + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE))) + return MZ_FALSE; + cur_file_ofs = MZ_MAX(cur_file_ofs - (sizeof(buf_u32) - 3), 0); + } + // Read and verify the end of central directory record. + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + return MZ_FALSE; + if ((MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_SIG_OFS) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) || + ((pZip->m_total_files = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS)) != MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS))) + return MZ_FALSE; + + num_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS); + cdir_disk_index = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS); + if (((num_this_disk | cdir_disk_index) != 0) && ((num_this_disk != 1) || (cdir_disk_index != 1))) + return MZ_FALSE; + + if ((cdir_size = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_SIZE_OFS)) < pZip->m_total_files * MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) + return MZ_FALSE; + + cdir_ofs = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_OFS_OFS); + if ((cdir_ofs + (mz_uint64)cdir_size) > pZip->m_archive_size) + return MZ_FALSE; + + pZip->m_central_directory_file_ofs = cdir_ofs; + + if (pZip->m_total_files) + { + mz_uint i, n; + + // Read the entire central directory into a heap block, and allocate another heap block to hold the unsorted central dir file record offsets, and another to hold the sorted indices. + if ((!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir, cdir_size, MZ_FALSE)) || + (!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir_offsets, pZip->m_total_files, MZ_FALSE))) + return MZ_FALSE; + + if (sort_central_dir) + { + if (!mz_zip_array_resize(pZip, &pZip->m_pState->m_sorted_central_dir_offsets, pZip->m_total_files, MZ_FALSE)) + return MZ_FALSE; + } + + if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs, pZip->m_pState->m_central_dir.m_p, cdir_size) != cdir_size) + return MZ_FALSE; + + // Now create an index into the central directory file records, do some basic sanity checking on each record, and check for zip64 entries (which are not yet supported). + p = (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p; + for (n = cdir_size, i = 0; i < pZip->m_total_files; ++i) + { + mz_uint total_header_size, comp_size, decomp_size, disk_index; + if ((n < MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) || (MZ_READ_LE32(p) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG)) + return MZ_FALSE; + MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, i) = (mz_uint32)(p - (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p); + if (sort_central_dir) + MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_sorted_central_dir_offsets, mz_uint32, i) = i; + comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); + decomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); + if (((!MZ_READ_LE32(p + MZ_ZIP_CDH_METHOD_OFS)) && (decomp_size != comp_size)) || (decomp_size && !comp_size) || (decomp_size == 0xFFFFFFFF) || (comp_size == 0xFFFFFFFF)) + return MZ_FALSE; + disk_index = MZ_READ_LE16(p + MZ_ZIP_CDH_DISK_START_OFS); + if ((disk_index != num_this_disk) && (disk_index != 1)) + return MZ_FALSE; + if (((mz_uint64)MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS) + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + comp_size) > pZip->m_archive_size) + return MZ_FALSE; + if ((total_header_size = MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS)) > n) + return MZ_FALSE; + n -= total_header_size; p += total_header_size; + } + } + + if (sort_central_dir) + mz_zip_reader_sort_central_dir_offsets_by_filename(pZip); + + return MZ_TRUE; +} + +mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags) +{ + if ((!pZip) || (!pZip->m_pRead)) + return MZ_FALSE; + if (!mz_zip_reader_init_internal(pZip, flags)) + return MZ_FALSE; + pZip->m_archive_size = size; + if (!mz_zip_reader_read_central_dir(pZip, flags)) + { + mz_zip_reader_end(pZip); + return MZ_FALSE; + } + return MZ_TRUE; +} + +static size_t mz_zip_mem_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) +{ + mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; + size_t s = (file_ofs >= pZip->m_archive_size) ? 0 : (size_t)MZ_MIN(pZip->m_archive_size - file_ofs, n); + memcpy(pBuf, (const mz_uint8 *)pZip->m_pState->m_pMem + file_ofs, s); + return s; +} + +mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags) +{ + if (!mz_zip_reader_init_internal(pZip, flags)) + return MZ_FALSE; + pZip->m_archive_size = size; + pZip->m_pRead = mz_zip_mem_read_func; + pZip->m_pIO_opaque = pZip; +#ifdef __cplusplus + pZip->m_pState->m_pMem = const_cast(pMem); +#else + pZip->m_pState->m_pMem = (void *)pMem; +#endif + pZip->m_pState->m_mem_size = size; + if (!mz_zip_reader_read_central_dir(pZip, flags)) + { + mz_zip_reader_end(pZip); + return MZ_FALSE; + } + return MZ_TRUE; +} + +#ifndef MINIZ_NO_STDIO +static size_t mz_zip_file_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) +{ + mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; + mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); + if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) + return 0; + return MZ_FREAD(pBuf, 1, n, pZip->m_pState->m_pFile); +} + +mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags) +{ + mz_uint64 file_size; + MZ_FILE *pFile = MZ_FOPEN(pFilename, "rb"); + if (!pFile) + return MZ_FALSE; + if (MZ_FSEEK64(pFile, 0, SEEK_END)) + { + MZ_FCLOSE(pFile); + return MZ_FALSE; + } + file_size = MZ_FTELL64(pFile); + if (!mz_zip_reader_init_internal(pZip, flags)) + { + MZ_FCLOSE(pFile); + return MZ_FALSE; + } + pZip->m_pRead = mz_zip_file_read_func; + pZip->m_pIO_opaque = pZip; + pZip->m_pState->m_pFile = pFile; + pZip->m_archive_size = file_size; + if (!mz_zip_reader_read_central_dir(pZip, flags)) + { + mz_zip_reader_end(pZip); + return MZ_FALSE; + } + return MZ_TRUE; +} +#endif // #ifndef MINIZ_NO_STDIO + +mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip) +{ + return pZip ? pZip->m_total_files : 0; +} + +static MZ_FORCEINLINE const mz_uint8 *mz_zip_reader_get_cdh(mz_zip_archive *pZip, mz_uint file_index) +{ + if ((!pZip) || (!pZip->m_pState) || (file_index >= pZip->m_total_files) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) + return NULL; + return &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); +} + +mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index) +{ + mz_uint m_bit_flag; + const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); + if (!p) + return MZ_FALSE; + m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); + return (m_bit_flag & 1); +} + +mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index) +{ + mz_uint filename_len, external_attr; + const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); + if (!p) + return MZ_FALSE; + + // First see if the filename ends with a '/' character. + filename_len = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); + if (filename_len) + { + if (*(p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_len - 1) == '/') + return MZ_TRUE; + } + + // Bugfix: This code was also checking if the internal attribute was non-zero, which wasn't correct. + // Most/all zip writers (hopefully) set DOS file/directory attributes in the low 16-bits, so check for the DOS directory flag and ignore the source OS ID in the created by field. + // FIXME: Remove this check? Is it necessary - we already check the filename. + external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); + if ((external_attr & 0x10) != 0) + return MZ_TRUE; + + return MZ_FALSE; +} + +mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat) +{ + mz_uint n; + const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); + if ((!p) || (!pStat)) + return MZ_FALSE; + + // Unpack the central directory record. + pStat->m_file_index = file_index; + pStat->m_central_dir_ofs = MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index); + pStat->m_version_made_by = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS); + pStat->m_version_needed = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_NEEDED_OFS); + pStat->m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); + pStat->m_method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS); +#ifndef MINIZ_NO_TIME + pStat->m_time = mz_zip_dos_to_time_t(MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_TIME_OFS), MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_DATE_OFS)); +#endif + pStat->m_crc32 = MZ_READ_LE32(p + MZ_ZIP_CDH_CRC32_OFS); + pStat->m_comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); + pStat->m_uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); + pStat->m_internal_attr = MZ_READ_LE16(p + MZ_ZIP_CDH_INTERNAL_ATTR_OFS); + pStat->m_external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); + pStat->m_local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS); + + // Copy as much of the filename and comment as possible. + n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE - 1); + memcpy(pStat->m_filename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); pStat->m_filename[n] = '\0'; + + n = MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS); n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE - 1); + pStat->m_comment_size = n; + memcpy(pStat->m_comment, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS), n); pStat->m_comment[n] = '\0'; + + return MZ_TRUE; +} + +mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size) +{ + mz_uint n; + const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); + if (!p) { if (filename_buf_size) pFilename[0] = '\0'; return 0; } + n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); + if (filename_buf_size) + { + n = MZ_MIN(n, filename_buf_size - 1); + memcpy(pFilename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); + pFilename[n] = '\0'; + } + return n + 1; +} + +static MZ_FORCEINLINE mz_bool mz_zip_reader_string_equal(const char *pA, const char *pB, mz_uint len, mz_uint flags) +{ + mz_uint i; + if (flags & MZ_ZIP_FLAG_CASE_SENSITIVE) + return 0 == memcmp(pA, pB, len); + for (i = 0; i < len; ++i) + if (MZ_TOLOWER(pA[i]) != MZ_TOLOWER(pB[i])) + return MZ_FALSE; + return MZ_TRUE; +} + +static MZ_FORCEINLINE int mz_zip_reader_filename_compare(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, const char *pR, mz_uint r_len) +{ + const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; + mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS); + mz_uint8 l = 0, r = 0; + pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + pE = pL + MZ_MIN(l_len, r_len); + while (pL < pE) + { + if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) + break; + pL++; pR++; + } + return (pL == pE) ? (int)(l_len - r_len) : (l - r); +} + +static int mz_zip_reader_locate_file_binary_search(mz_zip_archive *pZip, const char *pFilename) +{ + mz_zip_internal_state *pState = pZip->m_pState; + const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; + const mz_zip_array *pCentral_dir = &pState->m_central_dir; + mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32, 0); + const int size = pZip->m_total_files; + const mz_uint filename_len = (mz_uint)strlen(pFilename); + int l = 0, h = size - 1; + while (l <= h) + { + int m = (l + h) >> 1, file_index = pIndices[m], comp = mz_zip_reader_filename_compare(pCentral_dir, pCentral_dir_offsets, file_index, pFilename, filename_len); + if (!comp) + return file_index; + else if (comp < 0) + l = m + 1; + else + h = m - 1; + } + return -1; +} + +int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags) +{ + mz_uint file_index; size_t name_len, comment_len; + if ((!pZip) || (!pZip->m_pState) || (!pName) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) + return -1; + if (((flags & (MZ_ZIP_FLAG_IGNORE_PATH | MZ_ZIP_FLAG_CASE_SENSITIVE)) == 0) && (!pComment) && (pZip->m_pState->m_sorted_central_dir_offsets.m_size)) + return mz_zip_reader_locate_file_binary_search(pZip, pName); + name_len = strlen(pName); if (name_len > 0xFFFF) return -1; + comment_len = pComment ? strlen(pComment) : 0; if (comment_len > 0xFFFF) return -1; + for (file_index = 0; file_index < pZip->m_total_files; file_index++) + { + const mz_uint8 *pHeader = &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); + mz_uint filename_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_FILENAME_LEN_OFS); + const char *pFilename = (const char *)pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + if (filename_len < name_len) + continue; + if (comment_len) + { + mz_uint file_extra_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_EXTRA_LEN_OFS), file_comment_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_COMMENT_LEN_OFS); + const char *pFile_comment = pFilename + filename_len + file_extra_len; + if ((file_comment_len != comment_len) || (!mz_zip_reader_string_equal(pComment, pFile_comment, file_comment_len, flags))) + continue; + } + if ((flags & MZ_ZIP_FLAG_IGNORE_PATH) && (filename_len)) + { + int ofs = filename_len - 1; + do + { + if ((pFilename[ofs] == '/') || (pFilename[ofs] == '\\') || (pFilename[ofs] == ':')) + break; + } while (--ofs >= 0); + ofs++; + pFilename += ofs; filename_len -= ofs; + } + if ((filename_len == name_len) && (mz_zip_reader_string_equal(pName, pFilename, filename_len, flags))) + return file_index; + } + return -1; +} + +mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) +{ + int status = TINFL_STATUS_DONE; + mz_uint64 needed_size, cur_file_ofs, comp_remaining, out_buf_ofs = 0, read_buf_size, read_buf_ofs = 0, read_buf_avail; + mz_zip_archive_file_stat file_stat; + void *pRead_buf; + mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; + tinfl_decompressor inflator; + + if ((buf_size) && (!pBuf)) + return MZ_FALSE; + + if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) + return MZ_FALSE; + + // Empty file, or a directory (but not always a directory - I've seen odd zips with directories that have compressed data which inflates to 0 bytes) + if (!file_stat.m_comp_size) + return MZ_TRUE; + + // Entry is a subdirectory (I've seen old zips with dir entries which have compressed deflate data which inflates to 0 bytes, but these entries claim to uncompress to 512 bytes in the headers). + // I'm torn how to handle this case - should it fail instead? + if (mz_zip_reader_is_file_a_directory(pZip, file_index)) + return MZ_TRUE; + + // Encryption and patch files are not supported. + if (file_stat.m_bit_flag & (1 | 32)) + return MZ_FALSE; + + // This function only supports stored and deflate. + if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) + return MZ_FALSE; + + // Ensure supplied output buffer is large enough. + needed_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat.m_comp_size : file_stat.m_uncomp_size; + if (buf_size < needed_size) + return MZ_FALSE; + + // Read and parse the local directory entry. + cur_file_ofs = file_stat.m_local_header_ofs; + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return MZ_FALSE; + if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + return MZ_FALSE; + + cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) + return MZ_FALSE; + + if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) + { + // The file is stored or the caller has requested the compressed data. + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, (size_t)needed_size) != needed_size) + return MZ_FALSE; + return ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) != 0) || (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) == file_stat.m_crc32); + } + + // Decompress the file either directly from memory or from a file input buffer. + tinfl_init(&inflator); + + if (pZip->m_pState->m_pMem) + { + // Read directly from the archive in memory. + pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; + read_buf_size = read_buf_avail = file_stat.m_comp_size; + comp_remaining = 0; + } + else if (pUser_read_buf) + { + // Use a user provided read buffer. + if (!user_read_buf_size) + return MZ_FALSE; + pRead_buf = (mz_uint8 *)pUser_read_buf; + read_buf_size = user_read_buf_size; + read_buf_avail = 0; + comp_remaining = file_stat.m_comp_size; + } + else + { + // Temporarily allocate a read buffer. + read_buf_size = MZ_MIN(file_stat.m_comp_size, MZ_ZIP_MAX_IO_BUF_SIZE); +#ifdef _MSC_VER + if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF)) +#else + if (((sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF)) +#endif + return MZ_FALSE; + if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) + return MZ_FALSE; + read_buf_avail = 0; + comp_remaining = file_stat.m_comp_size; + } + + do + { + size_t in_buf_size, out_buf_size = (size_t)(file_stat.m_uncomp_size - out_buf_ofs); + if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) + { + read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) + { + status = TINFL_STATUS_FAILED; + break; + } + cur_file_ofs += read_buf_avail; + comp_remaining -= read_buf_avail; + read_buf_ofs = 0; + } + in_buf_size = (size_t)read_buf_avail; + status = tinfl_decompress(&inflator, (mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pBuf, (mz_uint8 *)pBuf + out_buf_ofs, &out_buf_size, TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF | (comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0)); + read_buf_avail -= in_buf_size; + read_buf_ofs += in_buf_size; + out_buf_ofs += out_buf_size; + } while (status == TINFL_STATUS_NEEDS_MORE_INPUT); + + if (status == TINFL_STATUS_DONE) + { + // Make sure the entire file was decompressed, and check its CRC. + if ((out_buf_ofs != file_stat.m_uncomp_size) || (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32)) + status = TINFL_STATUS_FAILED; + } + + if ((!pZip->m_pState->m_pMem) && (!pUser_read_buf)) + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + + return status == TINFL_STATUS_DONE; +} + +mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) +{ + int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); + if (file_index < 0) + return MZ_FALSE; + return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, pUser_read_buf, user_read_buf_size); +} + +mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags) +{ + return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, NULL, 0); +} + +mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags) +{ + return mz_zip_reader_extract_file_to_mem_no_alloc(pZip, pFilename, pBuf, buf_size, flags, NULL, 0); +} + +void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags) +{ + mz_uint64 comp_size, uncomp_size, alloc_size; + const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); + void *pBuf; + + if (pSize) + *pSize = 0; + if (!p) + return NULL; + + comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); + uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); + + alloc_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? comp_size : uncomp_size; +#ifdef _MSC_VER + if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF)) +#else + if (((sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF)) +#endif + return NULL; + if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)alloc_size))) + return NULL; + + if (!mz_zip_reader_extract_to_mem(pZip, file_index, pBuf, (size_t)alloc_size, flags)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return NULL; + } + + if (pSize) *pSize = (size_t)alloc_size; + return pBuf; +} + +void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags) +{ + int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); + if (file_index < 0) + { + if (pSize) *pSize = 0; + return MZ_FALSE; + } + return mz_zip_reader_extract_to_heap(pZip, file_index, pSize, flags); +} + +mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) +{ + int status = TINFL_STATUS_DONE; mz_uint file_crc32 = MZ_CRC32_INIT; + mz_uint64 read_buf_size, read_buf_ofs = 0, read_buf_avail, comp_remaining, out_buf_ofs = 0, cur_file_ofs; + mz_zip_archive_file_stat file_stat; + void *pRead_buf = NULL; void *pWrite_buf = NULL; + mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; + + if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) + return MZ_FALSE; + + // Empty file, or a directory (but not always a directory - I've seen odd zips with directories that have compressed data which inflates to 0 bytes) + if (!file_stat.m_comp_size) + return MZ_TRUE; + + // Entry is a subdirectory (I've seen old zips with dir entries which have compressed deflate data which inflates to 0 bytes, but these entries claim to uncompress to 512 bytes in the headers). + // I'm torn how to handle this case - should it fail instead? + if (mz_zip_reader_is_file_a_directory(pZip, file_index)) + return MZ_TRUE; + + // Encryption and patch files are not supported. + if (file_stat.m_bit_flag & (1 | 32)) + return MZ_FALSE; + + // This function only supports stored and deflate. + if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) + return MZ_FALSE; + + // Read and parse the local directory entry. + cur_file_ofs = file_stat.m_local_header_ofs; + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return MZ_FALSE; + if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + return MZ_FALSE; + + cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) + return MZ_FALSE; + + // Decompress the file either directly from memory or from a file input buffer. + if (pZip->m_pState->m_pMem) + { + pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; + read_buf_size = read_buf_avail = file_stat.m_comp_size; + comp_remaining = 0; + } + else + { + read_buf_size = MZ_MIN(file_stat.m_comp_size, MZ_ZIP_MAX_IO_BUF_SIZE); + if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) + return MZ_FALSE; + read_buf_avail = 0; + comp_remaining = file_stat.m_comp_size; + } + + if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) + { + // The file is stored or the caller has requested the compressed data. + if (pZip->m_pState->m_pMem) + { +#ifdef _MSC_VER + if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > 0xFFFFFFFF)) +#else + if (((sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > 0xFFFFFFFF)) +#endif + return MZ_FALSE; + if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)file_stat.m_comp_size) != file_stat.m_comp_size) + status = TINFL_STATUS_FAILED; + else if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)file_stat.m_comp_size); + cur_file_ofs += file_stat.m_comp_size; + out_buf_ofs += file_stat.m_comp_size; + comp_remaining = 0; + } + else + { + while (comp_remaining) + { + read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) + { + status = TINFL_STATUS_FAILED; + break; + } + + if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)read_buf_avail); + + if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) + { + status = TINFL_STATUS_FAILED; + break; + } + cur_file_ofs += read_buf_avail; + out_buf_ofs += read_buf_avail; + comp_remaining -= read_buf_avail; + } + } + } + else + { + tinfl_decompressor inflator; + tinfl_init(&inflator); + + if (NULL == (pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, TINFL_LZ_DICT_SIZE))) + status = TINFL_STATUS_FAILED; + else + { + do + { + mz_uint8 *pWrite_buf_cur = (mz_uint8 *)pWrite_buf + (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); + size_t in_buf_size, out_buf_size = TINFL_LZ_DICT_SIZE - (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); + if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) + { + read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) + { + status = TINFL_STATUS_FAILED; + break; + } + cur_file_ofs += read_buf_avail; + comp_remaining -= read_buf_avail; + read_buf_ofs = 0; + } + + in_buf_size = (size_t)read_buf_avail; + status = tinfl_decompress(&inflator, (const mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pWrite_buf, pWrite_buf_cur, &out_buf_size, comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0); + read_buf_avail -= in_buf_size; + read_buf_ofs += in_buf_size; + + if (out_buf_size) + { + if (pCallback(pOpaque, out_buf_ofs, pWrite_buf_cur, out_buf_size) != out_buf_size) + { + status = TINFL_STATUS_FAILED; + break; + } + file_crc32 = (mz_uint32)mz_crc32(file_crc32, pWrite_buf_cur, out_buf_size); + if ((out_buf_ofs += out_buf_size) > file_stat.m_uncomp_size) + { + status = TINFL_STATUS_FAILED; + break; + } + } + } while ((status == TINFL_STATUS_NEEDS_MORE_INPUT) || (status == TINFL_STATUS_HAS_MORE_OUTPUT)); + } + } + + if ((status == TINFL_STATUS_DONE) && (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) + { + // Make sure the entire file was decompressed, and check its CRC. + if ((out_buf_ofs != file_stat.m_uncomp_size) || (file_crc32 != file_stat.m_crc32)) + status = TINFL_STATUS_FAILED; + } + + if (!pZip->m_pState->m_pMem) + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + if (pWrite_buf) + pZip->m_pFree(pZip->m_pAlloc_opaque, pWrite_buf); + + return status == TINFL_STATUS_DONE; +} + +mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) +{ + int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); + if (file_index < 0) + return MZ_FALSE; + return mz_zip_reader_extract_to_callback(pZip, file_index, pCallback, pOpaque, flags); +} + +#ifndef MINIZ_NO_STDIO +static size_t mz_zip_file_write_callback(void *pOpaque, mz_uint64 ofs, const void *pBuf, size_t n) +{ + (void)ofs; return MZ_FWRITE(pBuf, 1, n, (MZ_FILE*)pOpaque); +} + +mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags) +{ + mz_bool status; + mz_zip_archive_file_stat file_stat; + MZ_FILE *pFile; + if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) + return MZ_FALSE; + pFile = MZ_FOPEN(pDst_filename, "wb"); + if (!pFile) + return MZ_FALSE; + status = mz_zip_reader_extract_to_callback(pZip, file_index, mz_zip_file_write_callback, pFile, flags); + if (MZ_FCLOSE(pFile) == EOF) + return MZ_FALSE; +#ifndef MINIZ_NO_TIME + if (status) + mz_zip_set_file_times(pDst_filename, file_stat.m_time, file_stat.m_time); +#endif + return status; +} +#endif // #ifndef MINIZ_NO_STDIO + +mz_bool mz_zip_reader_end(mz_zip_archive *pZip) +{ + if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) + return MZ_FALSE; + + if (pZip->m_pState) + { + mz_zip_internal_state *pState = pZip->m_pState; pZip->m_pState = NULL; + mz_zip_array_clear(pZip, &pState->m_central_dir); + mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); + mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); + +#ifndef MINIZ_NO_STDIO + if (pState->m_pFile) + { + MZ_FCLOSE(pState->m_pFile); + pState->m_pFile = NULL; + } +#endif // #ifndef MINIZ_NO_STDIO + + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + } + pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; + + return MZ_TRUE; +} + +#ifndef MINIZ_NO_STDIO +mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags) +{ + int file_index = mz_zip_reader_locate_file(pZip, pArchive_filename, NULL, flags); + if (file_index < 0) + return MZ_FALSE; + return mz_zip_reader_extract_to_file(pZip, file_index, pDst_filename, flags); +} +#endif + +// ------------------- .ZIP archive writing + +#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + +static void mz_write_le16(mz_uint8 *p, mz_uint16 v) { p[0] = (mz_uint8)v; p[1] = (mz_uint8)(v >> 8); } +static void mz_write_le32(mz_uint8 *p, mz_uint32 v) { p[0] = (mz_uint8)v; p[1] = (mz_uint8)(v >> 8); p[2] = (mz_uint8)(v >> 16); p[3] = (mz_uint8)(v >> 24); } +#define MZ_WRITE_LE16(p, v) mz_write_le16((mz_uint8 *)(p), (mz_uint16)(v)) +#define MZ_WRITE_LE32(p, v) mz_write_le32((mz_uint8 *)(p), (mz_uint32)(v)) + +mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size) +{ + if ((!pZip) || (pZip->m_pState) || (!pZip->m_pWrite) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) + return MZ_FALSE; + + if (pZip->m_file_offset_alignment) + { + // Ensure user specified file offset alignment is a power of 2. + if (pZip->m_file_offset_alignment & (pZip->m_file_offset_alignment - 1)) + return MZ_FALSE; + } + + if (!pZip->m_pAlloc) pZip->m_pAlloc = def_alloc_func; + if (!pZip->m_pFree) pZip->m_pFree = def_free_func; + if (!pZip->m_pRealloc) pZip->m_pRealloc = def_realloc_func; + + pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; + pZip->m_archive_size = existing_size; + pZip->m_central_directory_file_ofs = 0; + pZip->m_total_files = 0; + + if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) + return MZ_FALSE; + memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); + return MZ_TRUE; +} + +static size_t mz_zip_heap_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) +{ + mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; + mz_zip_internal_state *pState = pZip->m_pState; + mz_uint64 new_size = MZ_MAX(file_ofs + n, pState->m_mem_size); +#ifdef _MSC_VER + if ((!n) || ((0, sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF))) +#else + if ((!n) || ((sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF))) +#endif + return 0; + if (new_size > pState->m_mem_capacity) + { + void *pNew_block; + size_t new_capacity = MZ_MAX(64, pState->m_mem_capacity); while (new_capacity < new_size) new_capacity *= 2; + if (NULL == (pNew_block = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pState->m_pMem, 1, new_capacity))) + return 0; + pState->m_pMem = pNew_block; pState->m_mem_capacity = new_capacity; + } + memcpy((mz_uint8 *)pState->m_pMem + file_ofs, pBuf, n); + pState->m_mem_size = (size_t)new_size; + return n; +} + +mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size) +{ + pZip->m_pWrite = mz_zip_heap_write_func; + pZip->m_pIO_opaque = pZip; + if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning)) + return MZ_FALSE; + if (0 != (initial_allocation_size = MZ_MAX(initial_allocation_size, size_to_reserve_at_beginning))) + { + if (NULL == (pZip->m_pState->m_pMem = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, initial_allocation_size))) + { + mz_zip_writer_end(pZip); + return MZ_FALSE; + } + pZip->m_pState->m_mem_capacity = initial_allocation_size; + } + return MZ_TRUE; +} + +#ifndef MINIZ_NO_STDIO +static size_t mz_zip_file_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) +{ + mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; + mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); + if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) + return 0; + return MZ_FWRITE(pBuf, 1, n, pZip->m_pState->m_pFile); +} + +mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning) +{ + MZ_FILE *pFile; + pZip->m_pWrite = mz_zip_file_write_func; + pZip->m_pIO_opaque = pZip; + if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning)) + return MZ_FALSE; + if (NULL == (pFile = MZ_FOPEN(pFilename, "wb"))) + { + mz_zip_writer_end(pZip); + return MZ_FALSE; + } + pZip->m_pState->m_pFile = pFile; + if (size_to_reserve_at_beginning) + { + mz_uint64 cur_ofs = 0; char buf[4096]; MZ_CLEAR_OBJ(buf); + do + { + size_t n = (size_t)MZ_MIN(sizeof(buf), size_to_reserve_at_beginning); + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_ofs, buf, n) != n) + { + mz_zip_writer_end(pZip); + return MZ_FALSE; + } + cur_ofs += n; size_to_reserve_at_beginning -= n; + } while (size_to_reserve_at_beginning); + } + return MZ_TRUE; +} +#endif // #ifndef MINIZ_NO_STDIO + +mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename) +{ + mz_zip_internal_state *pState; + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) + return MZ_FALSE; + // No sense in trying to write to an archive that's already at the support max size + if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) + return MZ_FALSE; + + pState = pZip->m_pState; + + if (pState->m_pFile) + { +#ifdef MINIZ_NO_STDIO + pFilename; return MZ_FALSE; +#else + // Archive is being read from stdio - try to reopen as writable. + if (pZip->m_pIO_opaque != pZip) + return MZ_FALSE; + if (!pFilename) + return MZ_FALSE; + pZip->m_pWrite = mz_zip_file_write_func; + if (NULL == (pState->m_pFile = MZ_FREOPEN(pFilename, "r+b", pState->m_pFile))) + { + // The mz_zip_archive is now in a bogus state because pState->m_pFile is NULL, so just close it. + mz_zip_reader_end(pZip); + return MZ_FALSE; + } +#endif // #ifdef MINIZ_NO_STDIO + } + else if (pState->m_pMem) + { + // Archive lives in a memory block. Assume it's from the heap that we can resize using the realloc callback. + if (pZip->m_pIO_opaque != pZip) + return MZ_FALSE; + pState->m_mem_capacity = pState->m_mem_size; + pZip->m_pWrite = mz_zip_heap_write_func; + } + // Archive is being read via a user provided read function - make sure the user has specified a write function too. + else if (!pZip->m_pWrite) + return MZ_FALSE; + + // Start writing new files at the archive's current central directory location. + pZip->m_archive_size = pZip->m_central_directory_file_ofs; + pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; + pZip->m_central_directory_file_ofs = 0; + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags) +{ + return mz_zip_writer_add_mem_ex(pZip, pArchive_name, pBuf, buf_size, NULL, 0, level_and_flags, 0, 0); +} + +typedef struct +{ + mz_zip_archive *m_pZip; + mz_uint64 m_cur_archive_file_ofs; + mz_uint64 m_comp_size; +} mz_zip_writer_add_state; + +static mz_bool mz_zip_writer_add_put_buf_callback(const void* pBuf, int len, void *pUser) +{ + mz_zip_writer_add_state *pState = (mz_zip_writer_add_state *)pUser; + if ((int)pState->m_pZip->m_pWrite(pState->m_pZip->m_pIO_opaque, pState->m_cur_archive_file_ofs, pBuf, len) != len) + return MZ_FALSE; + pState->m_cur_archive_file_ofs += len; + pState->m_comp_size += len; + return MZ_TRUE; +} + +static mz_bool mz_zip_writer_create_local_dir_header(mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date) +{ + (void)pZip; + memset(pDst, 0, MZ_ZIP_LOCAL_DIR_HEADER_SIZE); + MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_SIG_OFS, MZ_ZIP_LOCAL_DIR_HEADER_SIG); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_VERSION_NEEDED_OFS, method ? 20 : 0); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_BIT_FLAG_OFS, bit_flags); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_METHOD_OFS, method); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_TIME_OFS, dos_time); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_DATE_OFS, dos_date); + MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_CRC32_OFS, uncomp_crc32); + MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS, comp_size); + MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS, uncomp_size); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILENAME_LEN_OFS, filename_size); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_EXTRA_LEN_OFS, extra_size); + return MZ_TRUE; +} + +static mz_bool mz_zip_writer_create_central_dir_header(mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs, mz_uint32 ext_attributes) +{ + (void)pZip; + memset(pDst, 0, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_SIG_OFS, MZ_ZIP_CENTRAL_DIR_HEADER_SIG); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_VERSION_NEEDED_OFS, method ? 20 : 0); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_BIT_FLAG_OFS, bit_flags); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_METHOD_OFS, method); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_TIME_OFS, dos_time); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_DATE_OFS, dos_date); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_CRC32_OFS, uncomp_crc32); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, comp_size); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, uncomp_size); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILENAME_LEN_OFS, filename_size); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_EXTRA_LEN_OFS, extra_size); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_COMMENT_LEN_OFS, comment_size); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS, ext_attributes); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_header_ofs); + return MZ_TRUE; +} + +static mz_bool mz_zip_writer_add_to_central_dir(mz_zip_archive *pZip, const char *pFilename, mz_uint16 filename_size, const void *pExtra, mz_uint16 extra_size, const void *pComment, mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs, mz_uint32 ext_attributes) +{ + mz_zip_internal_state *pState = pZip->m_pState; + mz_uint32 central_dir_ofs = (mz_uint32)pState->m_central_dir.m_size; + size_t orig_central_dir_size = pState->m_central_dir.m_size; + mz_uint8 central_dir_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; + + // No zip64 support yet + if ((local_header_ofs > 0xFFFFFFFF) || (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + extra_size + comment_size) > 0xFFFFFFFF)) + return MZ_FALSE; + + if (!mz_zip_writer_create_central_dir_header(pZip, central_dir_header, filename_size, extra_size, comment_size, uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time, dos_date, local_header_ofs, ext_attributes)) + return MZ_FALSE; + + if ((!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_dir_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pFilename, filename_size)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pExtra, extra_size)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pComment, comment_size)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, ¢ral_dir_ofs, 1))) + { + // Try to push the central directory array back into its original state. + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return MZ_FALSE; + } + + return MZ_TRUE; +} + +static mz_bool mz_zip_writer_validate_archive_name(const char *pArchive_name) +{ + // Basic ZIP archive filename validity checks: Valid filenames cannot start with a forward slash, cannot contain a drive letter, and cannot use DOS-style backward slashes. + if (*pArchive_name == '/') + return MZ_FALSE; + while (*pArchive_name) + { + if ((*pArchive_name == '\\') || (*pArchive_name == ':')) + return MZ_FALSE; + pArchive_name++; + } + return MZ_TRUE; +} + +static mz_uint mz_zip_writer_compute_padding_needed_for_file_alignment(mz_zip_archive *pZip) +{ + mz_uint32 n; + if (!pZip->m_file_offset_alignment) + return 0; + n = (mz_uint32)(pZip->m_archive_size & (pZip->m_file_offset_alignment - 1)); + return (pZip->m_file_offset_alignment - n) & (pZip->m_file_offset_alignment - 1); +} + +static mz_bool mz_zip_writer_write_zeros(mz_zip_archive *pZip, mz_uint64 cur_file_ofs, mz_uint32 n) +{ + char buf[4096]; + memset(buf, 0, MZ_MIN(sizeof(buf), n)); + while (n) + { + mz_uint32 s = MZ_MIN(sizeof(buf), n); + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_file_ofs, buf, s) != s) + return MZ_FALSE; + cur_file_ofs += s; n -= s; + } + return MZ_TRUE; +} + +mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32) +{ + mz_uint16 method = 0, dos_time = 0, dos_date = 0; + mz_uint level, ext_attributes = 0, num_alignment_padding_bytes; + mz_uint64 local_dir_header_ofs = pZip->m_archive_size, cur_archive_file_ofs = pZip->m_archive_size, comp_size = 0; + size_t archive_name_size; + mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; + tdefl_compressor *pComp = NULL; + mz_bool store_data_uncompressed; + mz_zip_internal_state *pState; + + if ((int)level_and_flags < 0) + level_and_flags = MZ_DEFAULT_LEVEL; + level = level_and_flags & 0xF; + store_data_uncompressed = ((!level) || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)); + + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || ((buf_size) && (!pBuf)) || (!pArchive_name) || ((comment_size) && (!pComment)) || (pZip->m_total_files == 0xFFFF) || (level > MZ_UBER_COMPRESSION)) + return MZ_FALSE; + + pState = pZip->m_pState; + + if ((!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (uncomp_size)) + return MZ_FALSE; + // No zip64 support yet + if ((buf_size > 0xFFFFFFFF) || (uncomp_size > 0xFFFFFFFF)) + return MZ_FALSE; + if (!mz_zip_writer_validate_archive_name(pArchive_name)) + return MZ_FALSE; + +#ifndef MINIZ_NO_TIME + { + time_t cur_time; time(&cur_time); + mz_zip_time_to_dos_time(cur_time, &dos_time, &dos_date); + } +#endif // #ifndef MINIZ_NO_TIME + + archive_name_size = strlen(pArchive_name); + if (archive_name_size > 0xFFFF) + return MZ_FALSE; + + num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); + + // no zip64 support yet + if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + comment_size + archive_name_size) > 0xFFFFFFFF)) + return MZ_FALSE; + + if ((archive_name_size) && (pArchive_name[archive_name_size - 1] == '/')) + { + // Set DOS Subdirectory attribute bit. + ext_attributes |= 0x10; + // Subdirectories cannot contain data. + if ((buf_size) || (uncomp_size)) + return MZ_FALSE; + } + + // Try to do any allocations before writing to the archive, so if an allocation fails the file remains unmodified. (A good idea if we're doing an in-place modification.) + if ((!mz_zip_array_ensure_room(pZip, &pState->m_central_dir, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size)) || (!mz_zip_array_ensure_room(pZip, &pState->m_central_dir_offsets, 1))) + return MZ_FALSE; + + if ((!store_data_uncompressed) && (buf_size)) + { + if (NULL == (pComp = (tdefl_compressor *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)))) + return MZ_FALSE; + } + + if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes + sizeof(local_dir_header))) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return MZ_FALSE; + } + local_dir_header_ofs += num_alignment_padding_bytes; + if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } + cur_archive_file_ofs += num_alignment_padding_bytes + sizeof(local_dir_header); + + MZ_CLEAR_OBJ(local_dir_header); + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return MZ_FALSE; + } + cur_archive_file_ofs += archive_name_size; + + if (!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + { + uncomp_crc32 = (mz_uint32)mz_crc32(MZ_CRC32_INIT, (const mz_uint8*)pBuf, buf_size); + uncomp_size = buf_size; + if (uncomp_size <= 3) + { + level = 0; + store_data_uncompressed = MZ_TRUE; + } + } + + if (store_data_uncompressed) + { + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pBuf, buf_size) != buf_size) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return MZ_FALSE; + } + + cur_archive_file_ofs += buf_size; + comp_size = buf_size; + + if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) + method = MZ_DEFLATED; + } + else if (buf_size) + { + mz_zip_writer_add_state state; + + state.m_pZip = pZip; + state.m_cur_archive_file_ofs = cur_archive_file_ofs; + state.m_comp_size = 0; + + if ((tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) || + (tdefl_compress_buffer(pComp, pBuf, buf_size, TDEFL_FINISH) != TDEFL_STATUS_DONE)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return MZ_FALSE; + } + + comp_size = state.m_comp_size; + cur_archive_file_ofs = state.m_cur_archive_file_ofs; + + method = MZ_DEFLATED; + } + + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + pComp = NULL; + + // no zip64 support yet + if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF)) + return MZ_FALSE; + + if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date)) + return MZ_FALSE; + + if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) + return MZ_FALSE; + + if (!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date, local_dir_header_ofs, ext_attributes)) + return MZ_FALSE; + + pZip->m_total_files++; + pZip->m_archive_size = cur_archive_file_ofs; + + return MZ_TRUE; +} + +#ifndef MINIZ_NO_STDIO +mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags) +{ + mz_uint uncomp_crc32 = MZ_CRC32_INIT, level, num_alignment_padding_bytes; + mz_uint16 method = 0, dos_time = 0, dos_date = 0, ext_attributes = 0; + mz_uint64 local_dir_header_ofs = pZip->m_archive_size, cur_archive_file_ofs = pZip->m_archive_size, uncomp_size = 0, comp_size = 0; + size_t archive_name_size; + mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; + MZ_FILE *pSrc_file = NULL; + + if ((int)level_and_flags < 0) + level_and_flags = MZ_DEFAULT_LEVEL; + level = level_and_flags & 0xF; + + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pArchive_name) || ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION)) + return MZ_FALSE; + if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) + return MZ_FALSE; + if (!mz_zip_writer_validate_archive_name(pArchive_name)) + return MZ_FALSE; + + archive_name_size = strlen(pArchive_name); + if (archive_name_size > 0xFFFF) + return MZ_FALSE; + + num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); + + // no zip64 support yet + if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + comment_size + archive_name_size) > 0xFFFFFFFF)) + return MZ_FALSE; + + if (!mz_zip_get_file_modified_time(pSrc_filename, &dos_time, &dos_date)) + return MZ_FALSE; + + pSrc_file = MZ_FOPEN(pSrc_filename, "rb"); + if (!pSrc_file) + return MZ_FALSE; + MZ_FSEEK64(pSrc_file, 0, SEEK_END); + uncomp_size = MZ_FTELL64(pSrc_file); + MZ_FSEEK64(pSrc_file, 0, SEEK_SET); + + if (uncomp_size > 0xFFFFFFFF) + { + // No zip64 support yet + MZ_FCLOSE(pSrc_file); + return MZ_FALSE; + } + if (uncomp_size <= 3) + level = 0; + + if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes + sizeof(local_dir_header))) + { + MZ_FCLOSE(pSrc_file); + return MZ_FALSE; + } + local_dir_header_ofs += num_alignment_padding_bytes; + if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } + cur_archive_file_ofs += num_alignment_padding_bytes + sizeof(local_dir_header); + + MZ_CLEAR_OBJ(local_dir_header); + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) + { + MZ_FCLOSE(pSrc_file); + return MZ_FALSE; + } + cur_archive_file_ofs += archive_name_size; + + if (uncomp_size) + { + mz_uint64 uncomp_remaining = uncomp_size; + void *pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, MZ_ZIP_MAX_IO_BUF_SIZE); + if (!pRead_buf) + { + MZ_FCLOSE(pSrc_file); + return MZ_FALSE; + } + + if (!level) + { + while (uncomp_remaining) + { + mz_uint n = (mz_uint)MZ_MIN(MZ_ZIP_MAX_IO_BUF_SIZE, uncomp_remaining); + if ((MZ_FREAD(pRead_buf, 1, n, pSrc_file) != n) || (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pRead_buf, n) != n)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + MZ_FCLOSE(pSrc_file); + return MZ_FALSE; + } + uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, n); + uncomp_remaining -= n; + cur_archive_file_ofs += n; + } + comp_size = uncomp_size; + } + else + { + mz_bool result = MZ_FALSE; + mz_zip_writer_add_state state; + tdefl_compressor *pComp = (tdefl_compressor *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)); + if (!pComp) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + MZ_FCLOSE(pSrc_file); + return MZ_FALSE; + } + + state.m_pZip = pZip; + state.m_cur_archive_file_ofs = cur_archive_file_ofs; + state.m_comp_size = 0; + + if (tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + MZ_FCLOSE(pSrc_file); + return MZ_FALSE; + } + + for ( ; ; ) + { + size_t in_buf_size = (mz_uint32)MZ_MIN(uncomp_remaining, MZ_ZIP_MAX_IO_BUF_SIZE); + tdefl_status status; + + if (MZ_FREAD(pRead_buf, 1, in_buf_size, pSrc_file) != in_buf_size) + break; + + uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, in_buf_size); + uncomp_remaining -= in_buf_size; + + status = tdefl_compress_buffer(pComp, pRead_buf, in_buf_size, uncomp_remaining ? TDEFL_NO_FLUSH : TDEFL_FINISH); + if (status == TDEFL_STATUS_DONE) + { + result = MZ_TRUE; + break; + } + else if (status != TDEFL_STATUS_OKAY) + break; + } + + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + + if (!result) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + MZ_FCLOSE(pSrc_file); + return MZ_FALSE; + } + + comp_size = state.m_comp_size; + cur_archive_file_ofs = state.m_cur_archive_file_ofs; + + method = MZ_DEFLATED; + } + + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + } + + MZ_FCLOSE(pSrc_file); pSrc_file = NULL; + + // no zip64 support yet + if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF)) + return MZ_FALSE; + + if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date)) + return MZ_FALSE; + + if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) + return MZ_FALSE; + + if (!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date, local_dir_header_ofs, ext_attributes)) + return MZ_FALSE; + + pZip->m_total_files++; + pZip->m_archive_size = cur_archive_file_ofs; + + return MZ_TRUE; +} +#endif // #ifndef MINIZ_NO_STDIO + +mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index) +{ + mz_uint n, bit_flags, num_alignment_padding_bytes; + mz_uint64 comp_bytes_remaining, local_dir_header_ofs; + mz_uint64 cur_src_file_ofs, cur_dst_file_ofs; + mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; + mz_uint8 central_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; + size_t orig_central_dir_size; + mz_zip_internal_state *pState; + void *pBuf; const mz_uint8 *pSrc_central_header; + + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING)) + return MZ_FALSE; + if (NULL == (pSrc_central_header = mz_zip_reader_get_cdh(pSource_zip, file_index))) + return MZ_FALSE; + pState = pZip->m_pState; + + num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); + + // no zip64 support yet + if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) + return MZ_FALSE; + + cur_src_file_ofs = MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS); + cur_dst_file_ofs = pZip->m_archive_size; + + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return MZ_FALSE; + if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + return MZ_FALSE; + cur_src_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; + + if (!mz_zip_writer_write_zeros(pZip, cur_dst_file_ofs, num_alignment_padding_bytes)) + return MZ_FALSE; + cur_dst_file_ofs += num_alignment_padding_bytes; + local_dir_header_ofs = cur_dst_file_ofs; + if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return MZ_FALSE; + cur_dst_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; + + n = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + comp_bytes_remaining = n + MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); + + if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)MZ_MAX(sizeof(mz_uint32) * 4, MZ_MIN(MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining))))) + return MZ_FALSE; + + while (comp_bytes_remaining) + { + n = (mz_uint)MZ_MIN(MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining); + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, n) != n) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return MZ_FALSE; + } + cur_src_file_ofs += n; + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return MZ_FALSE; + } + cur_dst_file_ofs += n; + + comp_bytes_remaining -= n; + } + + bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS); + if (bit_flags & 8) + { + // Copy data descriptor + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, sizeof(mz_uint32) * 4) != sizeof(mz_uint32) * 4) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return MZ_FALSE; + } + + n = sizeof(mz_uint32) * ((MZ_READ_LE32(pBuf) == 0x08074b50) ? 4 : 3); + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return MZ_FALSE; + } + + cur_src_file_ofs += n; + cur_dst_file_ofs += n; + } + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + + // no zip64 support yet + if (cur_dst_file_ofs > 0xFFFFFFFF) + return MZ_FALSE; + + orig_central_dir_size = pState->m_central_dir.m_size; + + memcpy(central_header, pSrc_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); + MZ_WRITE_LE32(central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_dir_header_ofs); + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) + return MZ_FALSE; + + n = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_COMMENT_LEN_OFS); + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n)) + { + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return MZ_FALSE; + } + + if (pState->m_central_dir.m_size > 0xFFFFFFFF) + return MZ_FALSE; + n = (mz_uint32)orig_central_dir_size; + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &n, 1)) + { + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return MZ_FALSE; + } + + pZip->m_total_files++; + pZip->m_archive_size = cur_dst_file_ofs; + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip) +{ + mz_zip_internal_state *pState; + mz_uint64 central_dir_ofs, central_dir_size; + mz_uint8 hdr[MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE]; + + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING)) + return MZ_FALSE; + + pState = pZip->m_pState; + + // no zip64 support yet + if ((pZip->m_total_files > 0xFFFF) || ((pZip->m_archive_size + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) + return MZ_FALSE; + + central_dir_ofs = 0; + central_dir_size = 0; + if (pZip->m_total_files) + { + // Write central directory + central_dir_ofs = pZip->m_archive_size; + central_dir_size = pState->m_central_dir.m_size; + pZip->m_central_directory_file_ofs = central_dir_ofs; + if (pZip->m_pWrite(pZip->m_pIO_opaque, central_dir_ofs, pState->m_central_dir.m_p, (size_t)central_dir_size) != central_dir_size) + return MZ_FALSE; + pZip->m_archive_size += central_dir_size; + } + + // Write end of central directory record + MZ_CLEAR_OBJ(hdr); + MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_SIG_OFS, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG); + MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS, pZip->m_total_files); + MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS, pZip->m_total_files); + MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_SIZE_OFS, central_dir_size); + MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_OFS_OFS, central_dir_ofs); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, sizeof(hdr)) != sizeof(hdr)) + return MZ_FALSE; +#ifndef MINIZ_NO_STDIO + if ((pState->m_pFile) && (MZ_FFLUSH(pState->m_pFile) == EOF)) + return MZ_FALSE; +#endif // #ifndef MINIZ_NO_STDIO + + pZip->m_archive_size += sizeof(hdr); + + pZip->m_zip_mode = MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED; + return MZ_TRUE; +} + +mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, size_t *pSize) +{ + if ((!pZip) || (!pZip->m_pState) || (!pBuf) || (!pSize)) + return MZ_FALSE; + if (pZip->m_pWrite != mz_zip_heap_write_func) + return MZ_FALSE; + if (!mz_zip_writer_finalize_archive(pZip)) + return MZ_FALSE; + + *pBuf = pZip->m_pState->m_pMem; + *pSize = pZip->m_pState->m_mem_size; + pZip->m_pState->m_pMem = NULL; + pZip->m_pState->m_mem_size = pZip->m_pState->m_mem_capacity = 0; + return MZ_TRUE; +} + +mz_bool mz_zip_writer_end(mz_zip_archive *pZip) +{ + mz_zip_internal_state *pState; + mz_bool status = MZ_TRUE; + if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || ((pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) && (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED))) + return MZ_FALSE; + + pState = pZip->m_pState; + pZip->m_pState = NULL; + mz_zip_array_clear(pZip, &pState->m_central_dir); + mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); + mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); + +#ifndef MINIZ_NO_STDIO + if (pState->m_pFile) + { + MZ_FCLOSE(pState->m_pFile); + pState->m_pFile = NULL; + } +#endif // #ifndef MINIZ_NO_STDIO + + if ((pZip->m_pWrite == mz_zip_heap_write_func) && (pState->m_pMem)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pState->m_pMem); + pState->m_pMem = NULL; + } + + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; + return status; +} + +#ifndef MINIZ_NO_STDIO +mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags) +{ + mz_bool status, created_new_archive = MZ_FALSE; + mz_zip_archive zip_archive; + struct MZ_FILE_STAT_STRUCT file_stat; + MZ_CLEAR_OBJ(zip_archive); + if ((int)level_and_flags < 0) + level_and_flags = MZ_DEFAULT_LEVEL; + if ((!pZip_filename) || (!pArchive_name) || ((buf_size) && (!pBuf)) || ((comment_size) && (!pComment)) || ((level_and_flags & 0xF) > MZ_UBER_COMPRESSION)) + return MZ_FALSE; + if (!mz_zip_writer_validate_archive_name(pArchive_name)) + return MZ_FALSE; + if (MZ_FILE_STAT(pZip_filename, &file_stat) != 0) + { + // Create a new archive. + if (!mz_zip_writer_init_file(&zip_archive, pZip_filename, 0)) + return MZ_FALSE; + created_new_archive = MZ_TRUE; + } + else + { + // Append to an existing archive. + if (!mz_zip_reader_init_file(&zip_archive, pZip_filename, level_and_flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY)) + return MZ_FALSE; + if (!mz_zip_writer_init_from_reader(&zip_archive, pZip_filename)) + { + mz_zip_reader_end(&zip_archive); + return MZ_FALSE; + } + } + status = mz_zip_writer_add_mem_ex(&zip_archive, pArchive_name, pBuf, buf_size, pComment, comment_size, level_and_flags, 0, 0); + // Always finalize, even if adding failed for some reason, so we have a valid central directory. (This may not always succeed, but we can try.) + if (!mz_zip_writer_finalize_archive(&zip_archive)) + status = MZ_FALSE; + if (!mz_zip_writer_end(&zip_archive)) + status = MZ_FALSE; + if ((!status) && (created_new_archive)) + { + // It's a new archive and something went wrong, so just delete it. + int ignoredStatus = MZ_DELETE_FILE(pZip_filename); + (void)ignoredStatus; + } + return status; +} + +void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint flags) +{ + int file_index; + mz_zip_archive zip_archive; + void *p = NULL; + + if (pSize) + *pSize = 0; + + if ((!pZip_filename) || (!pArchive_name)) + return NULL; + + MZ_CLEAR_OBJ(zip_archive); + if (!mz_zip_reader_init_file(&zip_archive, pZip_filename, flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY)) + return NULL; + + if ((file_index = mz_zip_reader_locate_file(&zip_archive, pArchive_name, NULL, flags)) >= 0) + p = mz_zip_reader_extract_to_heap(&zip_archive, file_index, pSize, flags); + + mz_zip_reader_end(&zip_archive); + return p; +} + +#endif // #ifndef MINIZ_NO_STDIO + +#endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + +#endif // #ifndef MINIZ_NO_ARCHIVE_APIS + +#ifdef __cplusplus +} +#endif + +#endif // MINIZ_HEADER_FILE_ONLY + +/* + This is free and unencumbered software released into the public domain. + + Anyone is free to copy, modify, publish, use, compile, sell, or + distribute this software, either in source code form or as a compiled + binary, for any purpose, commercial or non-commercial, and by any + means. + + In jurisdictions that recognize copyright laws, the author or authors + of this software dedicate any and all copyright interest in the + software to the public domain. We make this dedication for the benefit + of the public at large and to the detriment of our heirs and + successors. We intend this dedication to be an overt act of + relinquishment in perpetuity of all present and future rights to this + software under copyright law. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + + For more information, please refer to +*/ diff --git a/apps/plugins/xrick/README.md b/apps/plugins/xrick/README.md new file mode 100644 index 0000000000..ecb4c19b50 --- /dev/null +++ b/apps/plugins/xrick/README.md @@ -0,0 +1,88 @@ +xrick +===== + +xrick is a clone of [Rick Dangerous](http://en.wikipedia.org/wiki/Rick_Dangerous), +known to run on Linux, Windows, BeOs, Amiga, QNX, all sorts of gaming consoles... + +License agreement & legal bable +------------------------------- + +* Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net) (http://www.bigorno.net/xrick/) +* Copyright (C) 2008-2014 Pierluigi Vicinanza (pierluigi DOT vicinanza AT gmail.com) + +I (BigOrno) have written the initial [xrick](http://www.bigorno.net/xrick/) code. +However, graphics and maps and sounds are by the authors of the original Rick Dangerous +game, and "Rick Dangerous" remains a trademark of its owner(s) -- maybe +Core Design (who wrote the game) or FireBird (who published it). +As of today, I have not been successful at contacting Core Design. + +This makes it a bit difficult to formally release the whole code, +including data for graphics and maps and sounds, under the terms of +licences such as the GNU General Public Licence. So the code is +released "in the spirit" of the GNU GPL. Whatever that means. + +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. + +Building +-------- + +**Requirements:** + +* [CMake](http://www.cmake.org/) +* [SDL](https://www.libsdl.org/download-1.2.php) version 1.2.x +* [zlib](http://www.zlib.net/) + +1. *Create a build directory* + + ``` + $ cd xrick-x.x.x + $ mkdir build + $ cd build + ``` + +2. *Generate your Makefile* + + `$ cmake ../source/xrick/projects/cmake` + +3. *Build* + + `$ make` + +4. *Install (optional)* + + `$ make install` + +Platform specific notes can be found in README.platforms. + +Usage +----- + +`xrick --help` will tell you all about command-line options. + +Controls +-------- + +- left, right, up (jump) or down (crawl): arrow keys or Z, X, O and K. +- fire: SPACE, end: E, pause: P, exit: ESC. +- use left, right, up, down + fire to poke something with your stick, + lay a stick of dynamite, or fire a bullet. +- toggle fullscreen: F1 ; zoom in/out: F2, F3. +- mute: F4 ; volume up/down: F5, F6. +- cheat modes, "trainer": F7 ; "never die": F8 ; "expose": F9. + +More details at http://www.bigorno.net/xrick/ + +Release History +--------------- + +Please see the file called CHANGELOG.md. + +Contacts +-------- + +Report problems or ask questions to: + +* _BigOrno_ (bigorno@bigorno.net) +* _Pierluigi Vicinanza_ (pierluigi DOT vicinanza AT gmail.com) diff --git a/apps/plugins/xrick/README.rockbox b/apps/plugins/xrick/README.rockbox new file mode 100644 index 0000000000..fe6bcd2fd3 --- /dev/null +++ b/apps/plugins/xrick/README.rockbox @@ -0,0 +1,16 @@ +xrick on Rockbox +---------------- + +Based on the upstream #021212 release. + +Currently enabled on all players that have at least 2-bit (ie greyscale) +display, but is optimized for color displays of 320x200 or larger. + +You will need the data files extracted into your player's root +directory. For example: + + $ unzip xrick-data.zip -d /mnt/myMp3Player + +Note that most players do not have a tuned keymap for xrick, instead +relying on the standard "pluginlib" bindings that are most likely +sub-optimal. Patches welcome! diff --git a/apps/plugins/xrick/SOURCES b/apps/plugins/xrick/SOURCES new file mode 100644 index 0000000000..f3acdd541a --- /dev/null +++ b/apps/plugins/xrick/SOURCES @@ -0,0 +1,40 @@ +control.c +devtools.c +draw.c +e_bomb.c +e_bonus.c +e_box.c +e_bullet.c +e_rick.c +e_sbonus.c +e_them.c +ents.c +game.c +maps.c +rects.c +res_magic.c +resources.c +scr_gameover.c +scr_getname.c +scr_imain.c +scr_imap.c +scr_pause.c +scr_xrick.c +scroller.c +util.c + +data/img.c +data/pics.c +data/sounds.c +data/sprites.c +data/tiles.c + +system/main_rockbox.c +system/sysarg_rockbox.c +system/sysevt_rockbox.c +system/sysfile_rockbox.c +system/sysmem_rockbox.c +system/sysmenu_rockbox.c +system/syssnd_rockbox.c +system/system_rockbox.c +system/sysvid_rockbox.c diff --git a/apps/plugins/xrick/config.h b/apps/plugins/xrick/config.h new file mode 100644 index 0000000000..31ecc79bb7 --- /dev/null +++ b/apps/plugins/xrick/config.h @@ -0,0 +1,58 @@ + /*************************************************************************** + * __________ __ ___. + * Open \______ \ ____ ____ | | _\_ |__ _______ ___ + * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ / + * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < < + * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \ + * \/ \/ \/ \/ \/ + * $Id$ + * + * Port of xrick, a Rick Dangerous clone, to Rockbox. + * See http://www.bigorno.net/xrick/ + * + * Copyright (C) 2008-2014 Pierluigi Vicinanza + * + * 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 software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ****************************************************************************/ + +#ifndef XRICK_CONFIG_H +#define XRICK_CONFIG_H + +/* graphics (choose one) */ +#define GFXST +#undef GFXPC + +/* sound support */ +#define ENABLE_SOUND + +/* cheats support */ +#define ENABLE_CHEATS + +/* development tools */ +#undef ENABLE_DEVTOOLS + +/* Print debug info to screen */ +#undef ENABLE_SYSPRINTF_TO_SCREEN + +/* enable/disable subsystem debug */ +#undef DEBUG_MEMORY +#undef DEBUG_ENTS +#undef DEBUG_SCROLLER +#undef DEBUG_MAPS +#undef DEBUG_JOYSTICK +#undef DEBUG_EVENTS +#undef DEBUG_AUDIO +#undef DEBUG_AUDIO2 +#undef DEBUG_VIDEO +#undef DEBUG_VIDEO2 + +#endif /* ndef XRICK_CONFIG_H */ + +/* eof */ diff --git a/apps/plugins/xrick/control.c b/apps/plugins/xrick/control.c new file mode 100644 index 0000000000..27fbe97376 --- /dev/null +++ b/apps/plugins/xrick/control.c @@ -0,0 +1,24 @@ +/* + * xrick/control.c + * + * Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net). + * Copyright (C) 2008-2014 Pierluigi Vicinanza. + * All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#include "xrick/control.h" + +unsigned control_status = 0; +extern inline bool control_test(control_t c); +extern inline void control_set(control_t c); +extern inline void control_clear(control_t c); +bool control_active = true; + +/* eof */ diff --git a/apps/plugins/xrick/control.h b/apps/plugins/xrick/control.h new file mode 100644 index 0000000000..91d0a8a195 --- /dev/null +++ b/apps/plugins/xrick/control.h @@ -0,0 +1,41 @@ +/* + * xrick/control.h + * + * Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net). + * Copyright (C) 2008-2014 Pierluigi Vicinanza. + * All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#ifndef _CONTROL_H +#define _CONTROL_H + +#include "xrick/system/basic_types.h" + +typedef enum +{ + Control_UP = (1 << 0), + Control_DOWN = (1 << 1), + Control_LEFT = (1 << 2), + Control_RIGHT = (1 << 3), + Control_PAUSE = (1 << 4), + Control_END = (1 << 5), + Control_EXIT = (1 << 6), + Control_FIRE = (1 << 7) +} control_t; + +extern unsigned control_status; +inline bool control_test(control_t c) { return control_status & c; } +inline void control_set(control_t c) { control_status |= c; } +inline void control_clear(control_t c) { control_status &= ~c; } +extern bool control_active; + +#endif /* ndef _CONTROL_H */ + +/* eof */ diff --git a/apps/plugins/xrick/data/img.c b/apps/plugins/xrick/data/img.c new file mode 100644 index 0000000000..2226df3c48 --- /dev/null +++ b/apps/plugins/xrick/data/img.c @@ -0,0 +1,23 @@ +/* + * xrick/data/img.c + * + * Copyright (C) 2008-2014 Pierluigi Vicinanza. All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#include "xrick/data/img.h" + +#include /* NULL */ + +/* + * globals + */ +img_t *img_splash = NULL; + +/* eof */ diff --git a/apps/plugins/xrick/data/img.h b/apps/plugins/xrick/data/img.h new file mode 100644 index 0000000000..96952627f9 --- /dev/null +++ b/apps/plugins/xrick/data/img.h @@ -0,0 +1,39 @@ +/* + * xrick/data/img.h + * + * Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net). + * Copyright (C) 2008-2014 Pierluigi Vicinanza. + * All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#ifndef _IMG_H +#define _IMG_H + +#include "xrick/system/basic_types.h" + +typedef struct { + U8 r, g, b, nothing; +} img_color_t; + +typedef struct { + U16 width; + U16 height; + U16 xPos; + U16 yPos; + U16 ncolors; + img_color_t *colors; + U8 *pixels; +} img_t; + +extern img_t *img_splash; + +#endif /* ndef _IMG_H */ + +/* eof */ diff --git a/apps/plugins/xrick/data/pics.c b/apps/plugins/xrick/data/pics.c new file mode 100644 index 0000000000..103bfd8344 --- /dev/null +++ b/apps/plugins/xrick/data/pics.c @@ -0,0 +1,29 @@ +/* + * xrick/data/pics.c + * + * Copyright (C) 2008-2014 Pierluigi Vicinanza. All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#include "xrick/data/pics.h" + +#ifdef GFXST + +#include /* NULL */ + +/* + * globals + */ +pic_t *pic_haf = NULL; +pic_t *pic_congrats = NULL; +pic_t *pic_splash = NULL; + +#endif /* GFXST */ + +/* eof */ diff --git a/apps/plugins/xrick/data/pics.h b/apps/plugins/xrick/data/pics.h new file mode 100644 index 0000000000..0c540b125e --- /dev/null +++ b/apps/plugins/xrick/data/pics.h @@ -0,0 +1,41 @@ +/* + * xrick/data/pics.h + * + * Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net). + * Copyright (C) 2008-2014 Pierluigi Vicinanza. + * All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#ifndef _PICS_H +#define _PICS_H + +#include "xrick/config.h" + +#ifdef GFXST + +#include "xrick/system/basic_types.h" + +typedef struct { + U16 width; + U16 height; + U16 xPos; + U16 yPos; + U32 *pixels; +} pic_t; + +extern pic_t *pic_haf; +extern pic_t *pic_congrats; +extern pic_t *pic_splash; + +#endif /* GFXST */ + +#endif /* ndef _PICS_H */ + +/* eof */ diff --git a/apps/plugins/xrick/data/sounds.c b/apps/plugins/xrick/data/sounds.c new file mode 100644 index 0000000000..853e7cd198 --- /dev/null +++ b/apps/plugins/xrick/data/sounds.c @@ -0,0 +1,44 @@ +/* + * xrick/data/sounds.c + * + * Copyright (C) 2008-2014 Pierluigi Vicinanza. All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#include "xrick/data/sounds.h" + +#ifdef ENABLE_SOUND + +#include /* NULL */ + +sound_t *soundBombshht = NULL; +sound_t *soundBonus = NULL; +sound_t *soundBox = NULL; +sound_t *soundBullet = NULL; +sound_t *soundCrawl = NULL; +sound_t *soundDie = NULL; +sound_t *soundEntity[SOUNDS_NBR_ENTITIES]; +sound_t *soundExplode = NULL; +sound_t *soundGameover = NULL; +sound_t *soundJump = NULL; +sound_t *soundPad = NULL; +sound_t *soundSbonus1 = NULL; +sound_t *soundSbonus2 = NULL; +sound_t *soundStick = NULL; +sound_t *soundTune0 = NULL; +sound_t *soundTune1 = NULL; +sound_t *soundTune2 = NULL; +sound_t *soundTune3 = NULL; +sound_t *soundTune4 = NULL; +sound_t *soundTune5 = NULL; +sound_t *soundWalk = NULL; + +#endif /* ENABLE_SOUND */ + +/* eof */ \ No newline at end of file diff --git a/apps/plugins/xrick/data/sounds.h b/apps/plugins/xrick/data/sounds.h new file mode 100644 index 0000000000..5d89b3e9ee --- /dev/null +++ b/apps/plugins/xrick/data/sounds.h @@ -0,0 +1,87 @@ +/* + * xrick/data/sounds.h + * + * Copyright (C) 2008-2014 Pierluigi Vicinanza. All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#ifndef _SOUNDS_H +#define _SOUNDS_H + +#include "xrick/config.h" + +#ifdef ENABLE_SOUND + +#include "xrick/system/basic_types.h" + +typedef struct { + char *name; + U8 *buf; + U32 len; + bool dispose; +} sound_t; + +enum +{ + /* expected format is 8-bit mono at 22050Hz */ + Wave_SAMPLE_RATE = 22050, + Wave_AUDIO_FORMAT = 1, /* PCM = 1 (i.e. Linear quantization) */ + Wave_CHANNEL_COUNT = 1, + Wave_BITS_PER_SAMPLE = 8, +}; + +typedef struct { + /* "RIFF" chunk descriptor */ + U8 riffChunkId[4]; + U8 riffChunkSize[4]; + U8 riffType[4]; + /* "fmt" sub-chunk */ + U8 formatChunkId[4]; + U8 formatChunkSize[4]; + U8 audioFormat[2]; + U8 channelCount[2]; + U8 sampleRate[4]; + U8 byteRate[4]; + U8 blockAlign[2]; + U8 bitsPerSample[2]; + /* "data" sub-chunk */ + U8 dataChunkId[4]; + U8 dataChunkSize[4]; +} wave_header_t; + +/* apparently there are 10 entity sounds in original game (ref. "e_them.c" notes)? However we only have 9 so far... */ +enum { SOUNDS_NBR_ENTITIES = 10 }; + +extern sound_t *soundBombshht; +extern sound_t *soundBonus; +extern sound_t *soundBox; +extern sound_t *soundBullet; +extern sound_t *soundCrawl; +extern sound_t *soundDie; +extern sound_t *soundEntity[SOUNDS_NBR_ENTITIES]; +extern sound_t *soundExplode; +extern sound_t *soundGameover; +extern sound_t *soundJump; +extern sound_t *soundPad; +extern sound_t *soundSbonus1; +extern sound_t *soundSbonus2; +extern sound_t *soundStick; +extern sound_t *soundTune0; +extern sound_t *soundTune1; +extern sound_t *soundTune2; +extern sound_t *soundTune3; +extern sound_t *soundTune4; +extern sound_t *soundTune5; +extern sound_t *soundWalk; + +#endif /* ENABLE_SOUND */ + +#endif /* ndef _SOUNDS_H */ + +/* eof */ \ No newline at end of file diff --git a/apps/plugins/xrick/data/sprites.c b/apps/plugins/xrick/data/sprites.c new file mode 100644 index 0000000000..461861e85e --- /dev/null +++ b/apps/plugins/xrick/data/sprites.c @@ -0,0 +1,22 @@ +/* + * xrick/data/sprites.c + * + * Copyright (C) 2008-2014 Pierluigi Vicinanza. All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#include "xrick/data/sprites.h" + +/* + * globals + */ +size_t sprites_nbr_sprites = 0; +sprite_t *sprites_data = NULL; + +/* eof */ diff --git a/apps/plugins/xrick/data/sprites.h b/apps/plugins/xrick/data/sprites.h new file mode 100644 index 0000000000..124ad4bc85 --- /dev/null +++ b/apps/plugins/xrick/data/sprites.h @@ -0,0 +1,70 @@ +/* + * xrick/data/sprites.h + * + * Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net). + * Copyright (C) 2008-2014 Pierluigi Vicinanza. + * All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +/* + * NOTES -- PC version + * + * A sprite consists in 4 columns and 21 rows of (U16 mask, U16 pict), + * each pair representing 8 pixels (cga encoding, two bits per pixels). + * Sprites are stored in 'sprites.bin' and are loaded by spr_init. Memory + * is freed by spr_shutdown. + * + * There are four sprites planes. Plane 0 is the raw content of 'sprites.bin', + * and planes 1, 2 and 3 contain copies of plane 0 with all sprites shifted + * 2, 4 and 6 pixels to the right. + */ + +#ifndef _SPRITES_H_ +#define _SPRITES_H_ + +#include "xrick/config.h" + +#include "xrick/system/basic_types.h" + +#include /* size_t */ + +#ifdef GFXPC + +typedef struct { + U16 mask; + U16 pict; +} spriteX_t; + +enum { + SPRITES_NBR_ROWS = 21, + SPRITES_NBR_COLS = 4 +}; +typedef spriteX_t sprite_t[SPRITES_NBR_COLS][SPRITES_NBR_ROWS]; /* one sprite */ + +#endif /* GFXPC */ + + +#ifdef GFXST + +enum { + SPRITES_NBR_ROWS = 21, + SPRITES_NBR_COLS = 4, + SPRITES_NBR_DATA = SPRITES_NBR_ROWS * SPRITES_NBR_COLS +}; +typedef U32 sprite_t[SPRITES_NBR_DATA]; + +#endif /* GFXST */ + +extern size_t sprites_nbr_sprites; +extern sprite_t *sprites_data; + +#endif /* ndef _SPRITES_H_ */ + +/* eof */ diff --git a/apps/plugins/xrick/data/tiles.c b/apps/plugins/xrick/data/tiles.c new file mode 100644 index 0000000000..17d702ee6b --- /dev/null +++ b/apps/plugins/xrick/data/tiles.c @@ -0,0 +1,22 @@ +/* + * xrick/data/tiles.c + * + * Copyright (C) 2008-2014 Pierluigi Vicinanza. All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#include "xrick/data/tiles.h" + +/* + * globals + */ +size_t tiles_nbr_banks = 0; +tile_t *tiles_data = NULL; + +/* eof */ diff --git a/apps/plugins/xrick/data/tiles.h b/apps/plugins/xrick/data/tiles.h new file mode 100644 index 0000000000..35bc07184e --- /dev/null +++ b/apps/plugins/xrick/data/tiles.h @@ -0,0 +1,70 @@ +/* + * xrick/data/tiles.h + * + * Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net). + * Copyright (C) 2008-2014 Pierluigi Vicinanza. + * All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +/* + * NOTES + * + * A tile consists in one column and 8 rows of 8 U16 (cga encoding, two + * bits per pixel). The tl_tiles array contains all tiles, with the + * following structure: + * + * 0x0000 - 0x00FF tiles for main intro + * 0x0100 - 0x01FF tiles for map intro + * 0x0200 - 0x0327 unused + * 0x0328 - 0x0427 game tiles, page 0 + * 0x0428 - 0x0527 game tiles, page 1 + * 0x0527 - 0x05FF unused + */ + +#ifndef _TILES_H +#define _TILES_H + +#include "xrick/system/basic_types.h" + +#include "xrick/config.h" + +#include /* size_t */ + +/* + * three special tile numbers + */ +enum { + TILES_BULLET = 0x01, + TILES_BOMB = 0x02, + TILES_RICK = 0x03 +}; + +/* + * one single tile + */ +enum { TILES_NBR_LINES = 0x08 }; + +#ifdef GFXPC +typedef U16 tile_t[TILES_NBR_LINES]; +#endif +#ifdef GFXST +typedef U32 tile_t[TILES_NBR_LINES]; +#endif + +/* + * tiles banks (each bank is 0x100 tiles) + */ +enum { TILES_NBR_TILES = 0x100 }; +extern size_t tiles_nbr_banks; +extern tile_t *tiles_data; + +#endif /* ndef _TILES_H */ + +/* eof */ diff --git a/apps/plugins/xrick/debug.h b/apps/plugins/xrick/debug.h new file mode 100644 index 0000000000..5bf777213b --- /dev/null +++ b/apps/plugins/xrick/debug.h @@ -0,0 +1,84 @@ +/* + * xrick/debug.h + * + * Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net). + * Copyright (C) 2008-2014 Pierluigi Vicinanza. + * All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#ifndef _DEBUG_H +#define _DEBUG_H + +#include "xrick/config.h" + +/* define IFDEBUG macros */ +#ifdef DEBUG_MEMORY +#define IFDEBUG_MEMORY(X); X +#else +#define IFDEBUG_MEMORY(X); +#endif + +#ifdef DEBUG_ENTS +#define IFDEBUG_ENTS(X); X +#else +#define IFDEBUG_ENTS(X); +#endif + +#ifdef DEBUG_SCROLLER +#define IFDEBUG_SCROLLER(X); X +#else +#define IFDEBUG_SCROLLER(X); +#endif + +#ifdef DEBUG_MAPS +#define IFDEBUG_MAPS(X); X +#else +#define IFDEBUG_MAPS(X); +#endif + +#ifdef DEBUG_JOYSTICK +#define IFDEBUG_JOYSTICK(X); X +#else +#define IFDEBUG_JOYSTICK(X); +#endif + +#ifdef DEBUG_EVENTS +#define IFDEBUG_EVENTS(X); X +#else +#define IFDEBUG_EVENTS(X); +#endif + +#ifdef DEBUG_AUDIO +#define IFDEBUG_AUDIO(X); X +#else +#define IFDEBUG_AUDIO(X); +#endif + +#ifdef DEBUG_AUDIO2 +#define IFDEBUG_AUDIO2(X); X +#else +#define IFDEBUG_AUDIO2(X); +#endif + +#ifdef DEBUG_VIDEO +#define IFDEBUG_VIDEO(X); X +#else +#define IFDEBUG_VIDEO(X); +#endif + +#ifdef DEBUG_VIDEO2 +#define IFDEBUG_VIDEO2(X); X +#else +#define IFDEBUG_VIDEO2(X); +#endif + +#endif /* ndef _DEBUG_H */ + +/* eof */ diff --git a/apps/plugins/xrick/devtools.c b/apps/plugins/xrick/devtools.c new file mode 100644 index 0000000000..56fd5a7106 --- /dev/null +++ b/apps/plugins/xrick/devtools.c @@ -0,0 +1,247 @@ +/* + * xrick/devtools.c + * + * Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net). + * Copyright (C) 2008-2014 Pierluigi Vicinanza. + * All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#include "xrick/config.h" + +#ifdef ENABLE_DEVTOOLS + +#include "xrick/devtools.h" +#include "xrick/game.h" +#include "xrick/control.h" +#include "xrick/screens.h" +#include "xrick/draw.h" +#include "xrick/data/sprites.h" +#include "xrick/maps.h" +#include "xrick/system/system.h" + +/* + * DevTools + */ + +U8 +devtools_run(void) +{ + static U8 seq = 0; + static U8 pos = 0; + static U8 pos2 = 0; + U8 i, j, k, l; + U8 s[128]; + + if (seq == 0) { + sysvid_clear(); + game_rects = &draw_SCREENRECT; +#ifdef GFXPC + draw_filter = 0xffff; +#endif + seq = 1; + } + + switch (seq) { + case 1: /* draw tiles */ + sysvid_clear(); + draw_tilesBank = 0; + sys_snprintf(s, sizeof(s), "TILES@BANK@%d\376", pos); + draw_setfb(4, 4); + draw_tilesListImm(s); + k = 0; + for (i = 0; i < 0x10; i++) { + draw_setfb(80 + i * 0x0a, 14); + draw_tile((i<10?0x30:'A'-10) + i); + draw_setfb(64, 30 + i * 0x0a); + draw_tile((i<10?0x30:'A'-10) + i); + } + draw_tilesBank = pos; + for (i = 0; i < 0x10; i++) + for (j = 0; j < 0x10; j++) { + draw_setfb(80 + j * 0x0a, 30 + i * 0x0a); + draw_tile(k++); + } + seq = 10; + break; + case 10: /* wait for key pressed */ + if (control_test(Control_FIRE)) + seq = 98; + if (control_test(Control_UP)) + seq = 12; + if (control_test(Control_DOWN)) + seq = 13; + if (control_test(Control_RIGHT)) + seq = 11; + break; + case 11: /* wait for key released */ + if (!(control_test(Control_RIGHT))) { + pos = 0; + seq = 21; + } + break; + case 12: /* wait for key released */ + if (!(control_test(Control_UP))) { + if (pos < 4) pos++; + seq = 1; + } + break; + case 13: /* wait for key released */ + if (!(control_test(Control_DOWN))) { + if (pos > 0) pos--; + seq = 1; + } + break; + case 21: /* draw sprites */ + sysvid_clear(); + draw_tilesBank = 0; + sys_snprintf(s, sizeof(s), "SPRITES\376"); + draw_setfb(4, 4); + draw_tilesListImm(s); + for (i = 0; i < 8; i++) { + draw_setfb(0x08 + 0x20 + i * 0x20, 0x30 - 26); + draw_tile((i<10?0x30:'A'-10) + i); + draw_setfb(0x08 + 0x20 + i * 0x20, 0x30 - 16); + draw_tile((i+8<10?0x30:'A'-10) + i+8); + } + for (i = 0; i < 4; i++) { + k = pos + i * 8; + draw_setfb(0x20 - 16, 0x08 + 0x30 + i * 0x20); + j = k%16; + k /= 16; + draw_tile((j<10?0x30:'A'-10) + j); + draw_setfb(0x20 - 26, 0x08 + 0x30 + i * 0x20); + j = k%16; + draw_tile((j<10?0x30:'A'-10) + j); + } + k = pos; + for (i = 0; i < 4; i++) + for (j = 0; j < 8; j++) { + draw_sprite(k++, 0x20 + j * 0x20, 0x30 + i * 0x20); + } + seq = 30; + break; + case 30: /* wait for key pressed */ + if (control_test(Control_FIRE)) + seq = 98; + if (control_test(Control_UP)) + seq = 32; + if (control_test(Control_DOWN)) + seq = 33; + if (control_test(Control_LEFT)) + seq = 31; + if (control_test(Control_RIGHT)) + seq = 40; + break; + case 31: /* wait for key released */ + if (!(control_test(Control_LEFT))) { + pos = 0; + seq = 1; + } + break; + case 32: /* wait for key released */ + if (!(control_test(Control_UP))) { + if (pos < sprites_nbr_sprites - 32) pos += 32; + seq = 21; + } + break; + case 33: /* wait for key released */ + if (!(control_test(Control_DOWN))) { + if (pos > 0) pos -= 32; + seq = 21; + } + break; + case 40: + sysvid_clear(); +#ifdef GFXPC + if (pos2 == 0) pos2 = 2; +#endif +#ifdef GFXST + if (pos2 == 0) pos2 = 1; +#endif + sys_snprintf(s, sizeof(s), "BLOCKS@%#04X@TO@%#04X@WITH@BANK@%d\376", + pos, pos + 4*8-1, pos2); + draw_setfb(4, 4); + draw_tilesBank = 0; + draw_tilesListImm(s); + draw_tilesBank = pos2; + for (l = 0; l < 8; l++) + for (k = 0; k < 4; k++) + for (i = 0; i < 4; i++) + for (j = 0; j < 4; j++) { + draw_setfb(20 + j * 8 + l * 36, 30 + i * 8 + k * 36); + draw_tile(map_blocks[pos + l + k * 8][i * 4 + j]); + } + seq = 41; + break; + case 41: + if (control_test(Control_FIRE)) + seq = 98; + if (control_test(Control_UP)) + seq = 42; + if (control_test(Control_DOWN)) + seq = 43; + if (control_test(Control_LEFT)) + seq = 44; + if (control_test(Control_PAUSE)) + seq = 45; + break; + case 42: + if (!(control_test(Control_UP))) { + if (pos < map_nbr_blocks - 8*4) pos += 8 * 4; + seq = 40; + } + break; + case 43: + if (!(control_test(Control_DOWN))) { + if (pos > 0) pos -= 8 * 4; + seq = 40; + } + break; + case 44: + if (!(control_test(Control_LEFT))) { + pos = 0; + pos2 = 0; + seq = 21; + } + break; + case 45: + if (!(control_test(Control_PAUSE))) { +#ifdef GFXPC + if (pos2 == 2) pos2 = 3; + else pos2 = 2; +#endif +#ifdef GFXST + if (pos2 == 1) pos2 = 2; + else pos2 = 1; +#endif + seq = 40; + } + break; + case 98: /* wait for key released */ + if (!(control_test(Control_FIRE))) + seq = 99; + break; + } + + if (control_test(Control_EXIT)) /* check for exit request */ + return SCREEN_EXIT; + + if (seq == 99) { /* we're done */ + sysvid_clear(); + seq = 0; + return SCREEN_DONE; + } + + return SCREEN_RUNNING; +} + +#endif /* ENABLE_DEVTOOLS */ + +/* eof */ diff --git a/apps/plugins/xrick/devtools.h b/apps/plugins/xrick/devtools.h new file mode 100644 index 0000000000..e1021bfbcd --- /dev/null +++ b/apps/plugins/xrick/devtools.h @@ -0,0 +1,25 @@ +/* + * xrick/devtools.h + * + * Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net). + * Copyright (C) 2008-2014 Pierluigi Vicinanza. + * All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#ifndef _DEVTOOLS_H +#define _DEVTOOLS_H + +#include "xrick/system/basic_types.h" + +extern U8 devtools_run(void); + +#endif /* ndef _DEVTOOLS_H */ + +/* eof */ diff --git a/apps/plugins/xrick/draw.c b/apps/plugins/xrick/draw.c new file mode 100644 index 0000000000..a759ed5239 --- /dev/null +++ b/apps/plugins/xrick/draw.c @@ -0,0 +1,702 @@ +/* + * xrick/draw.c + * + * Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net). + * Copyright (C) 2008-2014 Pierluigi Vicinanza. + * All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +/* + * NOTES + * + * This is the only file which accesses the video. Anything calling d_* + * function should be video-independant. + * + * draw.c draws into a 320x200 or 0x0140x0xc8 8-bits depth frame buffer, + * using the CGA 2 bits color codes. It is up to the video to figure out + * how to display the frame buffer. Whatever draw.c does, does not show + * until the screen is explicitely refreshed. + * + * The "screen" is the whole 0x0140 by 0x00c8 screen, coordinates go from + * 0x0000,0x0000 to 0x013f,0x00c7. + * + * The "map" is a 0x0100 by 0x0140 rectangle that represents the active + * game area. + * + * Relative to the screen, the "map" is located at 0x0020,-0x0040 : the + * "map" is composed of two hidden 0x0100 by 0x0040 rectangles (one at the + * top and one at the bottom) and one visible 0x0100 by 0x00c0 rectangle (in + * the middle). + * + * The "map screen" is the visible rectangle ; it is a 0x0100 by 0xc0 + * rectangle located at 0x0020,0x00. + * + * Coordinates can be relative to the screen, the map, or the map screen. + * + * Coordinates can be expressed in pixels. When relative to the map or the + * map screen, they can also be expressed in tiles, the map being composed + * of rows of 0x20 tiles of 0x08 by 0x08 pixels. + */ + +#include "xrick/system/system.h" + +#include "xrick/game.h" +#include "xrick/draw.h" + +#include "xrick/data/sprites.h" +#include "xrick/data/tiles.h" + +#include "xrick/maps.h" +#include "xrick/rects.h" +#include "xrick/data/img.h" + + +/* + * counters positions (pixels, screen) + */ +#ifdef GFXPC +#define DRAW_STATUS_SCORE_X 0x28 +#define DRAW_STATUS_LIVES_X 0xE8 +#define DRAW_STATUS_Y 0x08 +#endif +#define DRAW_STATUS_BULLETS_X 0x68 +#define DRAW_STATUS_BOMBS_X 0xA8 +#ifdef GFXST +#define DRAW_STATUS_SCORE_X 0x20 +#define DRAW_STATUS_LIVES_X 0xF0 +#define DRAW_STATUS_Y 0 +#endif + + +/* + * public vars + */ +U8 *draw_tllst; /* pointer to tiles list */ +#ifdef GFXPC +U16 draw_filter; /* CGA colors filter */ +#endif +U8 draw_tilesBank; /* tile number offset */ + +rect_t draw_STATUSRECT = { + DRAW_STATUS_SCORE_X, DRAW_STATUS_Y, + DRAW_STATUS_LIVES_X + 6 * 8 - DRAW_STATUS_SCORE_X, 8, + NULL +}; +const rect_t draw_SCREENRECT = { 0, 0, SYSVID_WIDTH, SYSVID_HEIGHT, NULL }; + +size_t game_color_count = 0; +img_color_t *game_colors = NULL; + +/* + * private vars + */ +static U8 *fb; /* frame buffer pointer */ + + +/* + * Set the frame buffer pointer + * + * x, y: position (pixels, screen) + */ +void +draw_setfb(U16 x, U16 y) +{ + fb = sysvid_fb + x + y * SYSVID_WIDTH; +} + + +/* + * Clip to map screen + * + * x, y: position (pixels, map) CHANGED clipped + * width, height: dimension CHANGED clipped + * return: true if fully clipped, false if still (at least partly) visible + */ +bool +draw_clipms(S16 *x, S16 *y, U16 *width, U16 *height) +{ + if (*x < 0) { + if (*x + *width < 0) + return true; + else { + *width += *x; + *x = 0; + } + } + else { + if (*x > 0x0100) + return true; + else if (*x + *width > 0x0100) { + *width = 0x0100 - *x; + } + } + + if (*y < DRAW_XYMAP_SCRTOP) { + if ((*y + *height) < DRAW_XYMAP_SCRTOP) + return true; + else { + *height += *y - DRAW_XYMAP_SCRTOP; + *y = DRAW_XYMAP_SCRTOP; + } + } + else { + if (*y >= DRAW_XYMAP_HBTOP) + return true; + else if (*y + *height > DRAW_XYMAP_HBTOP) + *height = DRAW_XYMAP_HBTOP - *y; + } + + return false; +} + + +/* + * Draw a list of tiles onto the frame buffer + * start at position indicated by fb ; at the end of each (sub)list, + * perform a "carriage return + line feed" i.e. go back to the initial + * position then go down one tile row (8 pixels) + * + * ASM 1e33 + * fb: CHANGED (see above) + * draw_tllst: CHANGED points to the element following 0xfe/0xff end code + */ +void +draw_tilesList(void) +{ + U8 *t; + + t = fb; + while (draw_tilesSubList() != 0xFE) { /* draw sub-list */ + t += 8 * SYSVID_WIDTH; /* go down one tile i.e. 8 lines */ + fb = t; + } +} + + +/* + * Draw a list of tiles onto the frame buffer -- same as draw_tilesList, + * but accept an immediate string as parameter. Note that the string needs + * to be properly terminated with 0xfe (\376) and 0xff (\377) chars. + */ +void +draw_tilesListImm(U8 *list) +{ + draw_tllst = list; + draw_tilesList(); +} + + +/* + * Draw a sub-list of tiles onto the frame buffer + * start at position indicated by fb ; leave fb pointing to the next + * tile to the right of the last tile drawn + * + * ASM 1e41 + * fpb: CHANGED (see above) + * draw_tllst: CHANGED points to the element following 0xfe/0xff end code + * returns: end code (0xfe : end of list ; 0xff : end of sub-list) + */ +U8 +draw_tilesSubList() +{ + U8 i; + + i = *(draw_tllst++); + while (i != 0xFF && i != 0xFE) { /* while not end */ + draw_tile(i); /* draw tile */ + i = *(draw_tllst++); + } + return i; +} + + +/* + * Draw a tile + * at position indicated by fb ; leave fb pointing to the next tile + * to the right of the tile drawn + * + * ASM 1e6c + * tlnbr: tile number + * draw_filter: CGA colors filter + * fb: CHANGED (see above) + */ +void +draw_tile(U8 tileNumber) +{ + U8 i, k, *f; + +#ifdef GFXPC + U16 x; +#endif + +#ifdef GFXST + U32 x; +#endif + + f = fb; /* frame buffer */ + for (i = 0; i < TILES_NBR_LINES; i++) { /* for all 8 pixel lines */ + +#ifdef GFXPC + x = tiles_data[draw_tilesBank * TILES_NBR_TILES + tileNumber][i] & draw_filter; + /* + * tiles / perform the transformation from CGA 2 bits + * per pixel to frame buffer 8 bits per pixels + */ + for (k = 8; k--; x >>= 2) + f[k] = x & 3; + f += SYSVID_WIDTH; /* next line */ +#endif + +#ifdef GFXST + x = tiles_data[draw_tilesBank * TILES_NBR_TILES + tileNumber][i]; + /* + * tiles / perform the transformation from ST 4 bits + * per pixel to frame buffer 8 bits per pixels + */ + for (k = 8; k--; x >>= 4) + f[k] = x & 0x0F; + f += SYSVID_WIDTH; /* next line */ +#endif + + } + + fb += 8; /* next tile */ +} + +/* + * Draw a sprite + * + * ASM 1a09 + * nbr: sprite number + * x, y: sprite position (pixels, screen) + * fb: CHANGED + */ +#ifdef GFXPC +void +draw_sprite(U8 nbr, U16 x, U16 y) +{ + U8 i, j, k, *f; + U16 xm = 0, xp = 0; + + draw_setfb(x, y); + + for (i = 0; i < SPRITES_NBR_COLS; i++) { /* for each tile column */ + f = fb; /* frame buffer */ + for (j = 0; j < SPRITES_NBR_ROWS; j++) { /* for each pixel row */ + xm = sprites_data[nbr][i][j].mask; /* mask */ + xp = sprites_data[nbr][i][j].pict; /* picture */ + /* + * sprites / perform the transformation from CGA 2 bits + * per pixel to frame buffer 8 bits per pixels + */ + for (k = 8; k--; xm >>= 2, xp >>= 2) + f[k] = (f[k] & (xm & 3)) | (xp & 3); + f += SYSVID_WIDTH; + } + fb += 8; + } +} +#endif + + +/* + * Draw a sprite + * + * foobar + */ +#ifdef GFXST +void +draw_sprite(U8 number, U16 x, U16 y) +{ + U8 i, j, k, *f; + U16 g; + U32 d; + + draw_setfb(x, y); + g = 0; + for (i = 0; i < SPRITES_NBR_ROWS; i++) { /* rows */ + f = fb; + for (j = 0; j < SPRITES_NBR_COLS; j++) { /* cols */ + d = sprites_data[number][g++]; + for (k = 8; k--; d >>= 4) + if (d & 0x0F) f[k] = (f[k] & 0xF0) | (d & 0x0F); + f += 8; + } + fb += SYSVID_WIDTH; + } +} +#endif + + +/* + * Draw a sprite + * + * NOTE re-using original ST graphics format + */ +#ifdef GFXST +void +draw_sprite2(U8 number, U16 x, U16 y, bool front) +{ + U32 d = 0; /* sprite data */ + S16 x0, y0; /* clipped x, y */ + U16 w, h; /* width, height */ + S16 g, /* sprite data offset*/ + r, c, /* row, column */ + i, /* frame buffer shifter */ + im; /* tile flag shifter */ + U8 flg; /* tile flag */ + + x0 = x; + y0 = y; + w = SPRITES_NBR_COLS * 8; /* each tile column is 8 pixels */ + h = SPRITES_NBR_ROWS; + + if (draw_clipms(&x0, &y0, &w, &h)) /* return if not visible */ + return; + + g = 0; + draw_setfb(x0 - DRAW_XYMAP_SCRLEFT, y0 - DRAW_XYMAP_SCRTOP + 8); + + for (r = 0; r < SPRITES_NBR_ROWS; r++) { + if (r >= h || y + r < y0) continue; + + i = 0x1f; + im = x - (x & 0xfff8); + flg = map_eflg[map_map[(y + r) >> 3][(x + 0x1f)>> 3]]; + +#ifdef ENABLE_CHEATS +#define LOOP(N, C0, C1) \ + d = sprites_data[number][g + N]; \ + for (c = C0; c >= C1; c--, i--, d >>= 4, im--) { \ + if (im == 0) { \ + flg = map_eflg[map_map[(y + r) >> 3][(x + c) >> 3]]; \ + im = 8; \ + } \ + if (c >= w || x + c < x0) continue; \ + if (!front && !game_cheat3 && (flg & MAP_EFLG_FGND)) continue; \ + if (d & 0x0F) fb[i] = (fb[i] & 0xF0) | (d & 0x0F); \ + if (game_cheat3) fb[i] |= 0x10; \ + } +#else +#define LOOP(N, C0, C1) \ + d = sprites_data[number][g + N]; \ + for (c = C0; c >= C1; c--, i--, d >>= 4, im--) { \ + if (im == 0) { \ + flg = map_eflg[map_map[(y + r) >> 3][(x + c) >> 3]]; \ + im = 8; \ + } \ + if (!front && (flg & MAP_EFLG_FGND)) continue; \ + if (c >= w || x + c < x0) continue; \ + if (d & 0x0F) fb[i] = (fb[i] & 0xF0) | (d & 0x0F); \ + } +#endif + LOOP(3, 0x1f, 0x18); + LOOP(2, 0x17, 0x10); + LOOP(1, 0x0f, 0x08); + LOOP(0, 0x07, 0x00); + +#undef LOOP + + fb += SYSVID_WIDTH; + g += SPRITES_NBR_COLS; + } +} + +#endif + + +/* + * Draw a sprite + * align to tile column, determine plane automatically, and clip + * + * nbr: sprite number + * x, y: sprite position (pixels, map). + * fb: CHANGED + */ +#ifdef GFXPC +void +draw_sprite2(U8 number, U16 x, U16 y, bool front) +{ + U8 k, *f, c, r, dx; + U16 cmax, rmax; + U16 xm = 0, xp = 0; + S16 xmap, ymap; + + /* align to tile column, prepare map coordinate and clip */ + xmap = x & 0xFFF8; + ymap = y; + cmax = SPRITES_NBR_COLS * 8; /* width, 4 tile columns, 8 pixels each */ + rmax = SPRITES_NBR_ROWS; /* height, 15 pixels */ + dx = (x - xmap) * 2; + if (draw_clipms(&xmap, &ymap, &cmax, &rmax)) /* return if not visible */ + return; + + /* get back to screen */ + draw_setfb(xmap - DRAW_XYMAP_SCRLEFT, ymap - DRAW_XYMAP_SCRTOP); + xmap >>= 3; + cmax >>= 3; + + /* draw */ + for (c = 0; c < cmax; c++) { /* for each tile column */ + f = fb; + for (r = 0; r < rmax; r++) { /* for each pixel row */ + /* check that tile is not hidden behind foreground */ +#ifdef ENABLE_CHEATS + if (front || game_cheat3 || + !(map_eflg[map_map[(ymap + r) >> 3][xmap + c]] & MAP_EFLG_FGND)) { +#else + if (front || + !(map_eflg[map_map[(ymap + r) >> 3][xmap + c]] & MAP_EFLG_FGND)) { +#endif + xp = xm = 0; + if (c > 0) { + xm |= sprites_data[number][c - 1][r].mask << (16 - dx); + xp |= sprites_data[number][c - 1][r].pict << (16 - dx); + } + else + xm |= 0xFFFF << (16 - dx); + if (c < cmax) { + xm |= sprites_data[number][c][r].mask >> dx; + xp |= sprites_data[number][c][r].pict >> dx; + } + else + xm |= 0xFFFF >> dx; + /* + * sprites / perform the transformation from CGA 2 bits + * per pixel to frame buffer 8 bits per pixels + */ + for (k = 8; k--; xm >>= 2, xp >>= 2) { + f[k] = ((f[k] & (xm & 3)) | (xp & 3)); +#ifdef ENABLE_CHEATS + if (game_cheat3) f[k] |= 4; +#endif + } + } + f += SYSVID_WIDTH; + } + fb += 8; + } +} +#endif + + +/* + * Redraw the map behind a sprite + * align to tile column and row, and clip + * + * x, y: sprite position (pixels, map). + */ +void +draw_spriteBackground(U16 x, U16 y) +{ + U8 r, c; + U16 rmax, cmax; + S16 xmap, ymap; + U16 xs, ys; + + /* aligne to column and row, prepare map coordinate, and clip */ + xmap = x & 0xFFF8; + ymap = y & 0xFFF8; + cmax = (x - xmap == 0 ? 0x20 : 0x28); /* width, 4 tl cols, 8 pix each */ + rmax = (y & 0x04) ? 0x20 : 0x18; /* height, 3 or 4 tile rows */ + if (draw_clipms(&xmap, &ymap, &cmax, &rmax)) /* don't draw if fully clipped */ + return; + + /* get back to screen */ + xs = xmap - DRAW_XYMAP_SCRLEFT; + ys = ymap - DRAW_XYMAP_SCRTOP; + xmap >>= 3; + ymap >>= 3; + cmax >>= 3; + rmax >>= 3; + + /* draw */ + for (r = 0; r < rmax; r++) { /* for each row */ +#ifdef GFXPC + draw_setfb(xs, ys + r * 8); +#endif +#ifdef GFXST + draw_setfb(xs, 8 + ys + r * 8); +#endif + for (c = 0; c < cmax; c++) { /* for each column */ + draw_tile(map_map[ymap + r][xmap + c]); + } + } +} + + +/* + * Draw entire map screen background tiles onto frame buffer. + * + * ASM 0af5, 0a54 + */ +void +draw_map(void) +{ + U8 i, j; + + draw_tilesBank = map_tilesBank; + + for (i = 0; i < 0x18; i++) /* 0x18 rows */ + { +#ifdef GFXPC + draw_setfb(-DRAW_XYMAP_SCRLEFT, (i * 8)); +#endif +#ifdef GFXST + draw_setfb(-DRAW_XYMAP_SCRLEFT, 8 + (i * 8)); +#endif + for (j = 0; j < 0x20; j++) /* 0x20 tiles per row */ + { + draw_tile(map_map[i + 8][j]); + } + } +} + + +/* + * Draw status indicators + * + * ASM 0309 + */ +void +draw_drawStatus(void) +{ + S8 i; + U32 sv; + static U8 s[7] = {0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0xfe}; + + draw_tilesBank = 0; + + for (i = 5, sv = game_score; i >= 0; i--) { + s[i] = 0x30 + (U8)(sv % 10); + sv /= 10; + } + draw_tllst = s; + + draw_setfb(DRAW_STATUS_SCORE_X, DRAW_STATUS_Y); + draw_tilesList(); + + draw_setfb(DRAW_STATUS_BULLETS_X, DRAW_STATUS_Y); + for (i = 0; i < game_bullets; i++) + draw_tile(TILES_BULLET); + + draw_setfb(DRAW_STATUS_BOMBS_X, DRAW_STATUS_Y); + for (i = 0; i < game_bombs; i++) + draw_tile(TILES_BOMB); + + draw_setfb(DRAW_STATUS_LIVES_X, DRAW_STATUS_Y); + for (i = 0; i < game_lives; i++) + draw_tile(TILES_RICK); +} + + +/* + * Draw info indicators + */ +#ifdef ENABLE_CHEATS +void +draw_infos(void) +{ + draw_tilesBank = 0; + +#ifdef GFXPC + draw_filter = 0xffff; +#endif + + draw_setfb(0x00, DRAW_STATUS_Y); + draw_tile(game_cheat1 ? 'T' : '@'); + draw_setfb(0x08, DRAW_STATUS_Y); + draw_tile(game_cheat2 ? 'N' : '@'); + draw_setfb(0x10, DRAW_STATUS_Y); + draw_tile(game_cheat3 ? 'V' : '@'); +} +#endif + + +/* + * Clear status indicators + */ +void +draw_clearStatus(void) +{ + U8 i; + +#ifdef GFXPC + draw_tilesBank = map_tilesBank; +#endif +#ifdef GFXST + draw_tilesBank = 0; +#endif + draw_setfb(DRAW_STATUS_SCORE_X, DRAW_STATUS_Y); + for (i = 0; i < DRAW_STATUS_LIVES_X/8 + 6 - DRAW_STATUS_SCORE_X/8; i++) { +#ifdef GFXPC + draw_tile(map_map[MAP_ROW_SCRTOP + (DRAW_STATUS_Y / 8)][i]); +#endif +#ifdef GFXST + draw_tile('@'); +#endif + } +} + +/* + * Draw a picture + */ +#ifdef GFXST +void +draw_pic(const pic_t * picture) +{ + U8 *f; + U16 i, j, k, pp; + U32 v; + + draw_setfb(picture->xPos, picture->yPos); + pp = 0; + + for (i = 0; i < picture->height; i++) { /* rows */ + f = fb; + for (j = 0; j < picture->width; j += 8) { /* cols */ + v = picture->pixels[pp++]; + for (k = 8; k--; v >>= 4) + f[k] = v & 0x0F; + f += 8; + } + fb += SYSVID_WIDTH; + } +} +#endif + + +/* + * Draw a bitmap + */ +void +draw_img(img_t *image) +{ + U8 *f; + U16 i, j, pp; + + sysvid_setPalette(image->colors, image->ncolors); + + draw_setfb(image->xPos, image->yPos); + pp = 0; + + for (i = 0; i < image->height; i++) /* rows */ + { + f = fb; + for (j = 0; j < image->width; j++) /* cols */ + { + f[j] = image->pixels[pp++]; + } + fb += SYSVID_WIDTH; + } +} + + +/* eof */ diff --git a/apps/plugins/xrick/draw.h b/apps/plugins/xrick/draw.h new file mode 100644 index 0000000000..15520bd799 --- /dev/null +++ b/apps/plugins/xrick/draw.h @@ -0,0 +1,65 @@ +/* + * xrick/draw.h + * + * Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net). + * Copyright (C) 2008-2014 Pierluigi Vicinanza. + * All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#ifndef _DRAW_H +#define _DRAW_H + +#include "xrick/rects.h" +#include "xrick/data/img.h" +#ifdef GFXST +#include "xrick/data/pics.h" +#endif + +#include /* size_t */ + +/* map coordinates of the screen */ +#define DRAW_XYMAP_SCRLEFT (-0x0020) +#define DRAW_XYMAP_SCRTOP (0x0040) +/* map coordinates of the top of the hidden bottom of the map */ +#define DRAW_XYMAP_HBTOP (0x0100) + +extern U8 *draw_tllst; +#ifdef GFXPC +extern U16 draw_filter; +#endif +extern U8 draw_tilesBank; + +extern rect_t draw_STATUSRECT; +extern const rect_t draw_SCREENRECT; /* whole fb */ + +extern size_t game_color_count; +extern img_color_t *game_colors; + +extern void draw_setfb(U16, U16); +extern bool draw_clipms(S16 *, S16 *, U16 *, U16 *); +extern void draw_tilesList(void); +extern void draw_tilesListImm(U8 *); +extern U8 draw_tilesSubList(void); +extern void draw_tile(register U8); +extern void draw_sprite(U8, U16, U16); +extern void draw_sprite2(U8, U16, U16, bool); +extern void draw_spriteBackground(U16, U16); +extern void draw_map(void); +extern void draw_drawStatus(void); +extern void draw_clearStatus(void); +#ifdef GFXST +extern void draw_pic(const pic_t *); +#endif +extern void draw_infos(void); +extern void draw_img(img_t *); + +#endif /* ndef _DRAW_H */ + +/* eof */ diff --git a/apps/plugins/xrick/e_bomb.c b/apps/plugins/xrick/e_bomb.c new file mode 100644 index 0000000000..7b9f8cf309 --- /dev/null +++ b/apps/plugins/xrick/e_bomb.c @@ -0,0 +1,158 @@ +/* + * xrick/e_bomb.c + * + * Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net). + * Copyright (C) 2008-2014 Pierluigi Vicinanza. + * All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#include "xrick/e_bomb.h" + +#include "xrick/game.h" +#include "xrick/ents.h" +#include "xrick/e_rick.h" +#include "xrick/system/system.h" +#ifdef ENABLE_SOUND +#include "xrick/data/sounds.h" +#endif + +/* + * public vars (for performance reasons) + */ +bool e_bomb_lethal; +U8 e_bomb_xc; +U16 e_bomb_yc; + +/* + * private vars + */ +U8 e_bomb_ticker; + +/* + * Bomb hit test + * + * ASM 11CD + * returns: true/hit, false/not + */ +bool e_bomb_hit(U8 e) +{ + if (ent_ents[e].x > (E_BOMB_ENT.x >= 0xE0 ? 0xFF : E_BOMB_ENT.x + 0x20)) + return false; + if (ent_ents[e].x + ent_ents[e].w < (E_BOMB_ENT.x > 0x04 ? E_BOMB_ENT.x - 0x04 : 0)) + return false; + if (ent_ents[e].y > (E_BOMB_ENT.y + 0x1D)) + return false; + if (ent_ents[e].y + ent_ents[e].h < (E_BOMB_ENT.y > 0x0004 ? E_BOMB_ENT.y - 0x0004 : 0)) + return false; + return true; +} + +/* + * Initialize bomb + */ +void e_bomb_init(U16 x, U16 y) +{ + E_BOMB_ENT.n = 0x03; + E_BOMB_ENT.x = x; + E_BOMB_ENT.y = y; + e_bomb_ticker = E_BOMB_TICKER; + e_bomb_lethal = false; + + /* + * Atari ST dynamite sprites are not centered the + * way IBM PC sprites were ... need to adjust things a little bit + */ +#ifdef GFXST + E_BOMB_ENT.x += 4; + E_BOMB_ENT.y += 5; +#endif + +} + + +/* + * Entity action + * + * ASM 18CA + */ +void +e_bomb_action(U8 e/*unused*/) +{ + (void)e; + + /* tick */ + e_bomb_ticker--; + + if (e_bomb_ticker == 0) + { + /* + * end: deactivate + */ + E_BOMB_ENT.n = 0; + e_bomb_lethal = false; + } + else if (e_bomb_ticker >= 0x0A) + { + /* + * ticking + */ +#ifdef ENABLE_SOUND + if ((e_bomb_ticker & 0x03) == 0x02) + syssnd_play(soundBombshht, 1); +#endif +#ifdef GFXST + /* ST bomb sprites sequence is longer */ + if (e_bomb_ticker < 40) + E_BOMB_ENT.sprite = 0x99 + 19 - (e_bomb_ticker >> 1); + else +#endif + E_BOMB_ENT.sprite = (e_bomb_ticker & 0x01) ? 0x23 : 0x22; + } + else if (e_bomb_ticker == 0x09) + { + /* + * explode + */ +#ifdef ENABLE_SOUND + syssnd_play(soundExplode, 1); +#endif +#ifdef GFXPC + E_BOMB_ENT.sprite = 0x24 + 4 - (e_bomb_ticker >> 1); +#endif +#ifdef GFXST + /* See above: fixing alignment */ + E_BOMB_ENT.x -= 4; + E_BOMB_ENT.y -= 5; + E_BOMB_ENT.sprite = 0xa8 + 4 - (e_bomb_ticker >> 1); +#endif + e_bomb_xc = E_BOMB_ENT.x + 0x0C; + e_bomb_yc = E_BOMB_ENT.y + 0x000A; + e_bomb_lethal = true; + if (e_bomb_hit(E_RICK_NO)) + e_rick_gozombie(); + } + else + { + /* + * exploding + */ +#ifdef GFXPC + E_BOMB_ENT.sprite = 0x24 + 4 - (e_bomb_ticker >> 1); +#endif +#ifdef GFXST + E_BOMB_ENT.sprite = 0xa8 + 4 - (e_bomb_ticker >> 1); +#endif + /* exploding, hence lethal */ + if (e_bomb_hit(E_RICK_NO)) + e_rick_gozombie(); + } +} + +/* eof */ diff --git a/apps/plugins/xrick/e_bomb.h b/apps/plugins/xrick/e_bomb.h new file mode 100644 index 0000000000..93d66f7084 --- /dev/null +++ b/apps/plugins/xrick/e_bomb.h @@ -0,0 +1,36 @@ +/* + * xrick/e_bomb.h + * + * Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net). + * Copyright (C) 2008-2014 Pierluigi Vicinanza. + * All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#ifndef _E_BOMB_H +#define _E_BOMB_H + +#include "xrick/system/basic_types.h" + +#define E_BOMB_NO 3 +#define E_BOMB_ENT ent_ents[E_BOMB_NO] +#define E_BOMB_TICKER (0x2D) + +extern bool e_bomb_lethal; +extern U8 e_bomb_ticker; +extern U8 e_bomb_xc; +extern U16 e_bomb_yc; + +extern bool e_bomb_hit(U8); +extern void e_bomb_init(U16, U16); +extern void e_bomb_action(U8); + +#endif /* ndef _E_BOMB_H */ + +/* eof */ diff --git a/apps/plugins/xrick/e_bonus.c b/apps/plugins/xrick/e_bonus.c new file mode 100644 index 0000000000..cc45bbfc99 --- /dev/null +++ b/apps/plugins/xrick/e_bonus.c @@ -0,0 +1,60 @@ +/* + * xrick/e_bonus.c + * + * Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net). + * Copyright (C) 2008-2014 Pierluigi Vicinanza. + * All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#include "xrick/e_bonus.h" + +#include "xrick/game.h" +#include "xrick/ents.h" + +#include "xrick/e_rick.h" +#include "xrick/maps.h" + + +/* + * Entity action + * + * ASM 242C + */ +void +e_bonus_action(U8 e) +{ +#define seq c1 + + if (ent_ents[e].seq == 0) { + if (e_rick_boxtest(e)) { + game_score += 500; +#ifdef ENABLE_SOUND + syssnd_play(soundBonus, 1); +#endif + map_marks[ent_ents[e].mark].ent |= MAP_MARK_NACT; + ent_ents[e].seq = 1; + ent_ents[e].sprite = 0xad; + ent_ents[e].front = true; + ent_ents[e].y -= 0x08; + } + } + + else if (ent_ents[e].seq > 0 && ent_ents[e].seq < 10) { + ent_ents[e].seq++; + ent_ents[e].y -= 2; + } + + else { + ent_ents[e].n = 0; + } +} + + +/* eof */ diff --git a/apps/plugins/xrick/e_bonus.h b/apps/plugins/xrick/e_bonus.h new file mode 100644 index 0000000000..a2839e2a7a --- /dev/null +++ b/apps/plugins/xrick/e_bonus.h @@ -0,0 +1,25 @@ +/* + * xrick/e_bonus.h + * + * Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net). + * Copyright (C) 2008-2014 Pierluigi Vicinanza. + * All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#ifndef _E_BONUS_H +#define _E_BONUS_H + +#include "xrick/system/basic_types.h" + +extern void e_bonus_action(U8); + +#endif /* ndef _E_BONUS_H */ + +/* eof */ diff --git a/apps/plugins/xrick/e_box.c b/apps/plugins/xrick/e_box.c new file mode 100644 index 0000000000..25884b1a12 --- /dev/null +++ b/apps/plugins/xrick/e_box.c @@ -0,0 +1,109 @@ +/* + * xrick/e_box.c + * + * Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net). + * Copyright (C) 2008-2014 Pierluigi Vicinanza. + * All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#include "xrick/e_box.h" + +#include "xrick/game.h" +#include "xrick/ents.h" +#include "xrick/e_bullet.h" +#include "xrick/e_bomb.h" +#include "xrick/e_rick.h" +#include "xrick/maps.h" +#include "xrick/util.h" + +/* + * FIXME this is because the same structure is used + * for all entities. Need to replace this w/ an inheritance + * solution. + */ +#define cnt c1 + +/* + * Constants + */ +#define SEQ_INIT 0x0A + +/* + * Prototypes + */ +static void explode(U8); + +/* + * Entity action + * + * ASM 245A + */ +void +e_box_action(U8 e) +{ + static U8 sp[] = {0x24, 0x25, 0x26, 0x27, 0x28}; /* explosion sprites sequence */ + + if (ent_ents[e].n & ENT_LETHAL) { + /* + * box is lethal i.e. exploding + * play sprites sequence then stop + */ + ent_ents[e].sprite = sp[ent_ents[e].cnt >> 1]; + if (--ent_ents[e].cnt == 0) { + ent_ents[e].n = 0; + map_marks[ent_ents[e].mark].ent |= MAP_MARK_NACT; + } + } else { + /* + * not lethal: check to see if triggered + */ + if (e_rick_boxtest(e)) { + /* rick: collect bombs or bullets and stop */ +#ifdef ENABLE_SOUND + syssnd_play(soundBox, 1); +#endif + if (ent_ents[e].n == 0x10) + game_bombs = GAME_BOMBS_INIT; + else /* 0x11 */ + game_bullets = GAME_BULLETS_INIT; + ent_ents[e].n = 0; + map_marks[ent_ents[e].mark].ent |= MAP_MARK_NACT; + } + else if (e_rick_state_test(E_RICK_STSTOP) && + u_fboxtest(e, e_rick_stop_x, e_rick_stop_y)) { + /* rick's stick: explode */ + explode(e); + } + else if (E_BULLET_ENT.n && u_fboxtest(e, e_bullet_xc, e_bullet_yc)) { + /* bullet: explode (and stop bullet) */ + E_BULLET_ENT.n = 0; + explode(e); + } + else if (e_bomb_lethal && e_bomb_hit(e)) { + /* bomb: explode */ + explode(e); + } + } +} + + +/* + * Explode when + */ +static void explode(U8 e) +{ + ent_ents[e].cnt = SEQ_INIT; + ent_ents[e].n |= ENT_LETHAL; +#ifdef ENABLE_SOUND + syssnd_play(soundExplode, 1); +#endif +} + +/* eof */ diff --git a/apps/plugins/xrick/e_box.h b/apps/plugins/xrick/e_box.h new file mode 100644 index 0000000000..1271449bf5 --- /dev/null +++ b/apps/plugins/xrick/e_box.h @@ -0,0 +1,25 @@ +/* + * xrick/e_box.h + * + * Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net). + * Copyright (C) 2008-2014 Pierluigi Vicinanza. + * All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#ifndef _E_BOX_H +#define _E_BOX_H + +#include "xrick/system/basic_types.h" + +extern void e_box_action(U8); + +#endif /* ndef _E_BOX_H */ + +/* eof */ diff --git a/apps/plugins/xrick/e_bullet.c b/apps/plugins/xrick/e_bullet.c new file mode 100644 index 0000000000..86542256e8 --- /dev/null +++ b/apps/plugins/xrick/e_bullet.c @@ -0,0 +1,84 @@ +/* + * xrick/e_bullet.c + * + * Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net). + * Copyright (C) 2008-2014 Pierluigi Vicinanza. + * All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#include "xrick/e_bullet.h" + +#include "xrick/system/system.h" +#include "xrick/game.h" +#include "xrick/ents.h" +#include "xrick/maps.h" + +/* + * public vars (for performance reasons) + */ +S8 e_bullet_offsx; +S16 e_bullet_xc, e_bullet_yc; + +/* + * Initialize bullet + */ +void +e_bullet_init(U16 x, U16 y) +{ + E_BULLET_ENT.n = 0x02; + E_BULLET_ENT.x = x; + E_BULLET_ENT.y = y + 0x0006; + if (game_dir == LEFT) { + e_bullet_offsx = -0x08; + E_BULLET_ENT.sprite = 0x21; + } + else { + e_bullet_offsx = 0x08; + E_BULLET_ENT.sprite = 0x20; + } +#ifdef ENABLE_SOUND + syssnd_play(soundBullet, 1); +#endif +} + + +/* + * Entity action + * + * ASM 1883, 0F97 + */ +void +e_bullet_action(U8 e/*unused*/) +{ + (void)e; + + /* move bullet */ + E_BULLET_ENT.x += e_bullet_offsx; + + if (E_BULLET_ENT.x <= -0x10 || E_BULLET_ENT.x > 0xe8) + { + /* out: deactivate */ + E_BULLET_ENT.n = 0; + } + else + { + /* update bullet center coordinates */ + e_bullet_xc = E_BULLET_ENT.x + 0x0c; + e_bullet_yc = E_BULLET_ENT.y + 0x05; + if (map_eflg[map_map[e_bullet_yc >> 3][e_bullet_xc >> 3]] & MAP_EFLG_SOLID) + { + /* hit something: deactivate */ + E_BULLET_ENT.n = 0; + } + } +} + + +/* eof */ diff --git a/apps/plugins/xrick/e_bullet.h b/apps/plugins/xrick/e_bullet.h new file mode 100644 index 0000000000..5b8c78b709 --- /dev/null +++ b/apps/plugins/xrick/e_bullet.h @@ -0,0 +1,32 @@ +/* + * xrick/e_bullet.h + * + * Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net). + * Copyright (C) 2008-2014 Pierluigi Vicinanza. + * All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#ifndef _E_BULLET_H +#define _E_BULLET_H + +#include "xrick/system/basic_types.h" + +#define E_BULLET_NO 2 +#define E_BULLET_ENT ent_ents[E_BULLET_NO] + +extern S8 e_bullet_offsx; +extern S16 e_bullet_xc, e_bullet_yc; + +extern void e_bullet_init(U16, U16); +extern void e_bullet_action(U8); + +#endif /* ndef _E_BULLET_H */ + +/* eof */ diff --git a/apps/plugins/xrick/e_rick.c b/apps/plugins/xrick/e_rick.c new file mode 100644 index 0000000000..548a4f9681 --- /dev/null +++ b/apps/plugins/xrick/e_rick.c @@ -0,0 +1,606 @@ +/* + * xrick/e_rick.c + * + * Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net). + * Copyright (C) 2008-2014 Pierluigi Vicinanza. + * All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#include "xrick/e_rick.h" + +#include "xrick/system/system.h" +#include "xrick/config.h" +#include "xrick/game.h" +#include "xrick/ents.h" +#include "xrick/e_bullet.h" +#include "xrick/e_bomb.h" +#include "xrick/control.h" +#include "xrick/maps.h" +#include "xrick/util.h" + +/* + * public vars + */ +S16 e_rick_stop_x = 0; +S16 e_rick_stop_y = 0; +unsigned e_rick_state = 0; + +/* +* public functions +*/ +extern inline void e_rick_state_set(e_rick_state_t s); +extern inline void e_rick_state_clear(e_rick_state_t s); +extern inline bool e_rick_state_test(e_rick_state_t s); + + +/* + * local vars + */ +static U8 scrawl; + +static bool trigger = false; + +static S8 offsx; +static U8 ylow; +static S16 offsy; + +static U8 seq; + +static U8 save_crawl, save_direction; +static U16 save_x, save_y; + + +/* + * Box test + * + * ASM 113E (based on) + * + * e: entity to test against (corresponds to SI in asm code -- here DI + * is assumed to point to rick). + * ret: true/intersect, false/not. + */ +bool +e_rick_boxtest(U8 e) +{ + /* + * rick: x+0x05 to x+0x11, y+[0x08 if rick's crawling] to y+0x14 + * entity: x to x+w, y to y+h + */ + + if (E_RICK_ENT.x + 0x11 < ent_ents[e].x || + E_RICK_ENT.x + 0x05 > ent_ents[e].x + ent_ents[e].w || + E_RICK_ENT.y + 0x14 < ent_ents[e].y || + E_RICK_ENT.y + (e_rick_state_test(E_RICK_STCRAWL) ? 0x08 : 0x00) > ent_ents[e].y + ent_ents[e].h - 1) + return false; + else + return true; +} + + + + +/* + * Go zombie + * + * ASM 1851 + */ +void +e_rick_gozombie(void) +{ +#ifdef ENABLE_CHEATS + if (game_cheat2) return; +#endif + + /* already zombie? */ + if (e_rick_state_test(E_RICK_STZOMBIE)) return; + +#ifdef ENABLE_SOUND + syssnd_play(soundDie, 1); +#endif + + e_rick_state_set(E_RICK_STZOMBIE); + offsy = -0x0300; + offsx = (E_RICK_ENT.x > 0x80 ? -3 : +3); + ylow = 0; + E_RICK_ENT.front = true; +} + + +/* + * Action sub-function for e_rick when zombie + * + * ASM 17DC + */ +static void +e_rick_z_action(void) +{ + U32 i; + + /* sprite */ + E_RICK_ENT.sprite = (E_RICK_ENT.x & 0x04) ? 0x1A : 0x19; + + /* x */ + E_RICK_ENT.x += offsx; + + /* y */ + i = (E_RICK_ENT.y << 8) + offsy + ylow; + E_RICK_ENT.y = i >> 8; + offsy += 0x80; + ylow = i; + + /* dead when out of screen */ + if (E_RICK_ENT.y < 0 || E_RICK_ENT.y > 0x0140) + { + e_rick_state_set(E_RICK_STDEAD); + } +} + + +/* + * Action sub-function for e_rick. + * + * ASM 13BE + */ +void +e_rick_action2(void) +{ + U8 env0, env1; + S16 x, y; + U32 i; + + e_rick_state_clear(E_RICK_STSTOP | E_RICK_STSHOOT); + + /* if zombie, run dedicated function and return */ + if (e_rick_state_test(E_RICK_STZOMBIE)) + { + e_rick_z_action(); + return; + } + + /* climbing? */ + if (e_rick_state_test(E_RICK_STCLIMB)) + { + goto climbing; + } + /* + * NOT CLIMBING + */ + e_rick_state_clear(E_RICK_STJUMP); + /* calc y */ + i = (E_RICK_ENT.y << 8) + offsy + ylow; + y = i >> 8; + /* test environment */ + u_envtest(E_RICK_ENT.x, y, e_rick_state_test(E_RICK_STCRAWL), &env0, &env1); + /* stand up, if possible */ + if (e_rick_state_test(E_RICK_STCRAWL) && !env0) + { + e_rick_state_clear(E_RICK_STCRAWL); + } + /* can move vertically? */ + if (env1 & (offsy < 0 ? + MAP_EFLG_VERT|MAP_EFLG_SOLID|MAP_EFLG_SPAD : + MAP_EFLG_VERT|MAP_EFLG_SOLID|MAP_EFLG_SPAD|MAP_EFLG_WAYUP)) + goto vert_not; + + /* + * VERTICAL MOVE + */ + e_rick_state_set(E_RICK_STJUMP); + /* killed? */ + if (env1 & MAP_EFLG_LETHAL) { + e_rick_gozombie(); + return; + } + /* save */ + E_RICK_ENT.y = y; + ylow = i; + /* climb? */ + if ((env1 & MAP_EFLG_CLIMB) && (control_test(Control_UP | Control_DOWN))) + { + offsy = 0x0100; + e_rick_state_set(E_RICK_STCLIMB); + return; + } + /* fall */ + offsy += 0x0080; + if (offsy > 0x0800) { + offsy = 0x0800; + ylow = 0; + } + + /* + * HORIZONTAL MOVE + */ + horiz: + /* should move? */ + if (!(control_test(Control_LEFT | Control_RIGHT))) { + seq = 2; /* no: reset seq and return */ + return; + } + if (control_test(Control_LEFT)) { /* move left */ + x = E_RICK_ENT.x - 2; + game_dir = LEFT; + if (x < 0) { /* prev submap */ + game_chsm = true; + E_RICK_ENT.x = 0xe2; + return; + } + } else { /* move right */ + x = E_RICK_ENT.x + 2; + game_dir = RIGHT; + if (x >= 0xe8) { /* next submap */ + game_chsm = true; + E_RICK_ENT.x = 0x04; + return; + } + } + + /* still within this map: test environment */ + u_envtest(x, E_RICK_ENT.y, e_rick_state_test(E_RICK_STCRAWL), &env0, &env1); + + /* save x-position if it is possible to move */ + if (!(env1 & (MAP_EFLG_SOLID|MAP_EFLG_SPAD|MAP_EFLG_WAYUP))) { + E_RICK_ENT.x = x; + if (env1 & MAP_EFLG_LETHAL) e_rick_gozombie(); + } + + /* end */ + return; + + /* + * NO VERTICAL MOVE + */ + vert_not: + if (offsy < 0) { + /* not climbing + trying to go _up_ not possible -> hit the roof */ + e_rick_state_set(E_RICK_STJUMP); /* fall back to the ground */ + E_RICK_ENT.y &= 0xF8; + offsy = 0; + ylow = 0; + goto horiz; + } + /* else: not climbing + trying to go _down_ not possible -> standing */ + /* align to ground */ + E_RICK_ENT.y &= 0xF8; + E_RICK_ENT.y |= 0x03; + ylow = 0; + + /* standing on a super pad? */ + if ((env1 & MAP_EFLG_SPAD) && offsy >= 0X0200) { + offsy = (control_test(Control_UP)) ? 0xf800 : 0x00fe - offsy; +#ifdef ENABLE_SOUND + syssnd_play(soundPad, 1); +#endif + goto horiz; + } + + offsy = 0x0100; /* reset*/ + + /* standing. firing ? */ + if (scrawl || !(control_test(Control_FIRE))) + goto firing_not; + + /* + * FIRING + */ + if (control_test(Control_LEFT | Control_RIGHT)) { /* stop */ + if (control_test(Control_RIGHT)) + { + game_dir = RIGHT; + e_rick_stop_x = E_RICK_ENT.x + 0x17; + } else { + game_dir = LEFT; + e_rick_stop_x = E_RICK_ENT.x; + } + e_rick_stop_y = E_RICK_ENT.y + 0x000E; + e_rick_state_set(E_RICK_STSTOP); + return; + } + + if (control_test(Control_UP)) { /* bullet */ + e_rick_state_set(E_RICK_STSHOOT); + /* not an automatic gun: shoot once only */ + if (trigger) + return; + else + trigger = true; + /* already a bullet in the air ... that's enough */ + if (E_BULLET_ENT.n) + return; + /* else use a bullet, if any available */ + if (!game_bullets) + return; +#ifdef ENABLE_CHEATS + if (!game_cheat1) +#endif + { + game_bullets--; + } + + /* initialize bullet */ + e_bullet_init(E_RICK_ENT.x, E_RICK_ENT.y); + return; + } + + trigger = false; /* not shooting means trigger is released */ + seq = 0; /* reset */ + + if (control_test(Control_DOWN)) { /* bomb */ + /* already a bomb ticking ... that's enough */ + if (E_BOMB_ENT.n) + return; + /* else use a bomb, if any available */ + if (!game_bombs) + return; +#ifdef ENABLE_CHEATS + if (!game_cheat1) +#endif + { + game_bombs--; + } + + /* initialize bomb */ + e_bomb_init(E_RICK_ENT.x, E_RICK_ENT.y); + return; + } + + return; + + /* + * NOT FIRING + */ + firing_not: + if (control_test(Control_UP)) { /* jump or climb */ + if (env1 & MAP_EFLG_CLIMB) { /* climb */ + e_rick_state_set(E_RICK_STCLIMB); + return; + } + offsy = -0x0580; /* jump */ + ylow = 0; +#ifdef ENABLE_SOUND + syssnd_play(soundJump, 1); +#endif + goto horiz; + } + if (control_test(Control_DOWN)) { /* crawl or climb */ + if ((env1 & MAP_EFLG_VERT) && /* can go down */ + !(control_test(Control_LEFT | Control_RIGHT)) && /* + not moving horizontaly */ + (E_RICK_ENT.x & 0x1f) < 0x0a) { /* + aligned -> climb */ + E_RICK_ENT.x &= 0xf0; + E_RICK_ENT.x |= 0x04; + e_rick_state_set(E_RICK_STCLIMB); + } + else { /* crawl */ + e_rick_state_set(E_RICK_STCRAWL); + goto horiz; + } + + } + goto horiz; + + /* + * CLIMBING + */ + climbing: + /* should move? */ + if (!(control_test(Control_UP | Control_DOWN | Control_LEFT | Control_RIGHT))) { + seq = 0; /* no: reset seq and return */ + return; + } + + if (control_test(Control_UP | Control_DOWN)) { + /* up-down: calc new y and test environment */ + y = E_RICK_ENT.y + ((control_test(Control_UP)) ? -0x02 : 0x02); + u_envtest(E_RICK_ENT.x, y, e_rick_state_test(E_RICK_STCRAWL), &env0, &env1); + if (env1 & (MAP_EFLG_SOLID|MAP_EFLG_SPAD|MAP_EFLG_WAYUP) && + !(control_test(Control_UP))) { + /* FIXME what? */ + e_rick_state_clear(E_RICK_STCLIMB); + return; + } + if (!(env1 & (MAP_EFLG_SOLID|MAP_EFLG_SPAD|MAP_EFLG_WAYUP)) || + (env1 & MAP_EFLG_WAYUP)) { + /* ok to move, save */ + E_RICK_ENT.y = y; + if (env1 & MAP_EFLG_LETHAL) { + e_rick_gozombie(); + return; + } + if (!(env1 & (MAP_EFLG_VERT|MAP_EFLG_CLIMB))) { + /* reached end of climb zone */ + offsy = (control_test(Control_UP)) ? -0x0300 : 0x0100; +#ifdef ENABLE_SOUND + if (control_test(Control_UP)) + syssnd_play(soundJump, 1); +#endif + e_rick_state_clear(E_RICK_STCLIMB); + return; + } + } + } + if (control_test(Control_LEFT | Control_RIGHT)) { + /* left-right: calc new x and test environment */ + if (control_test(Control_LEFT)) { + x = E_RICK_ENT.x - 0x02; + if (x < 0) { /* (i.e. negative) prev submap */ + game_chsm = true; + /*6dbd = 0x00;*/ + E_RICK_ENT.x = 0xe2; + return; + } + } + else { + x = E_RICK_ENT.x + 0x02; + if (x >= 0xe8) { /* next submap */ + game_chsm = true; + /*6dbd = 0x01;*/ + E_RICK_ENT.x = 0x04; + return; + } + } + u_envtest(x, E_RICK_ENT.y, e_rick_state_test(E_RICK_STCRAWL), &env0, &env1); + if (env1 & (MAP_EFLG_SOLID|MAP_EFLG_SPAD)) return; + E_RICK_ENT.x = x; + if (env1 & MAP_EFLG_LETHAL) { + e_rick_gozombie(); + return; + } + + if (env1 & (MAP_EFLG_VERT|MAP_EFLG_CLIMB)) return; + e_rick_state_clear(E_RICK_STCLIMB); + if (control_test(Control_UP)) + offsy = -0x0300; + } +} + + +/* + * Action function for e_rick + * + * ASM 12CA + */ +void e_rick_action(U8 e/*unused*/) +{ + static U8 stopped = false; /* is this the most elegant way? */ + + (void)e; + + e_rick_action2(); + + scrawl = e_rick_state_test(E_RICK_STCRAWL); + + if (e_rick_state_test(E_RICK_STZOMBIE)) + { + return; + } + /* + * set sprite + */ + + if (e_rick_state_test(E_RICK_STSTOP)) + { + E_RICK_ENT.sprite = (game_dir ? 0x17 : 0x0B); +#ifdef ENABLE_SOUND + if (!stopped) + { + syssnd_play(soundStick, 1); + stopped = true; + } +#endif + return; + } + + stopped = false; + + if (e_rick_state_test(E_RICK_STSHOOT)) + { + E_RICK_ENT.sprite = (game_dir ? 0x16 : 0x0A); + return; + } + + if (e_rick_state_test(E_RICK_STCLIMB)) + { + E_RICK_ENT.sprite = (((E_RICK_ENT.x ^ E_RICK_ENT.y) & 0x04) ? 0x18 : 0x0c); +#ifdef ENABLE_SOUND + seq = (seq + 1) & 0x03; + if (seq == 0) syssnd_play(soundWalk, 1); +#endif + return; + } + + if (e_rick_state_test(E_RICK_STCRAWL)) + { + E_RICK_ENT.sprite = (game_dir ? 0x13 : 0x07); + if (E_RICK_ENT.x & 0x04) E_RICK_ENT.sprite++; +#ifdef ENABLE_SOUND + seq = (seq + 1) & 0x03; + if (seq == 0) syssnd_play(soundCrawl, 1); +#endif + return; + } + + if (e_rick_state_test(E_RICK_STJUMP)) + { + E_RICK_ENT.sprite = (game_dir ? 0x15 : 0x06); + return; + } + + seq++; + + if (seq >= 0x14) + { +#ifdef ENABLE_SOUND + syssnd_play(soundWalk, 1); +#endif + seq = 0x04; + } +#ifdef ENABLE_SOUND + else + { + if (seq == 0x0C) + { + syssnd_play(soundWalk, 1); + } + } +#endif + + E_RICK_ENT.sprite = (seq >> 2) + 1 + (game_dir ? 0x0c : 0x00); +} + + +/* + * Save status + * + * ASM part of 0x0BBB + */ +void e_rick_save(void) +{ + save_x = E_RICK_ENT.x; + save_y = E_RICK_ENT.y; + save_crawl = e_rick_state_test(E_RICK_STCRAWL); + save_direction = game_dir; + /* FIXME + * save_C0 = E_RICK_ENT.b0C; + * plus some 6DBC stuff? + */ +} + + +/* + * Restore status + * + * ASM part of 0x0BDC + */ +void e_rick_restore(void) +{ + E_RICK_ENT.x = save_x; + E_RICK_ENT.y = save_y; + if (save_crawl) + { + e_rick_state_set(E_RICK_STCRAWL); + } + else + { + e_rick_state_clear(E_RICK_STCRAWL); + } + game_dir = save_direction; + + E_RICK_ENT.front = false; + e_rick_state_clear(E_RICK_STCLIMB); /* should we clear other states? */ + /* FIXME + * E_RICK_ENT.b0C = save_C0; + * plus some 6DBC stuff? + */ +} + + + + +/* eof */ diff --git a/apps/plugins/xrick/e_rick.h b/apps/plugins/xrick/e_rick.h new file mode 100644 index 0000000000..57b45366d7 --- /dev/null +++ b/apps/plugins/xrick/e_rick.h @@ -0,0 +1,50 @@ +/* + * xrick/e_rick.h + * + * Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net). + * Copyright (C) 2008-2014 Pierluigi Vicinanza. + * All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#ifndef _E_RICK_H +#define _E_RICK_H + +#include "xrick/system/basic_types.h" + +#define E_RICK_NO 1 +#define E_RICK_ENT ent_ents[E_RICK_NO] + +typedef enum +{ + E_RICK_STSTOP = (1 << 0), + E_RICK_STSHOOT = (1 << 1), + E_RICK_STCLIMB = (1 << 2), + E_RICK_STJUMP = (1 << 3), + E_RICK_STZOMBIE = (1 << 4), + E_RICK_STDEAD = (1 << 5), + E_RICK_STCRAWL = (1 << 6), +} e_rick_state_t; + +extern unsigned e_rick_state; +inline void e_rick_state_set(e_rick_state_t s) { e_rick_state |= s; } +inline void e_rick_state_clear(e_rick_state_t s) { e_rick_state &= ~s; } +inline bool e_rick_state_test(e_rick_state_t s) { return e_rick_state & s; } + +extern S16 e_rick_stop_x, e_rick_stop_y; + +extern void e_rick_save(void); +extern void e_rick_restore(void); +extern void e_rick_action(U8); +extern void e_rick_gozombie(void); +extern bool e_rick_boxtest(U8); + +#endif /* ndef _E_RICK_H */ + +/* eof */ diff --git a/apps/plugins/xrick/e_sbonus.c b/apps/plugins/xrick/e_sbonus.c new file mode 100644 index 0000000000..1630d419aa --- /dev/null +++ b/apps/plugins/xrick/e_sbonus.c @@ -0,0 +1,88 @@ +/* + * xrick/e_sbonus.c + * + * Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net). + * Copyright (C) 2008-2014 Pierluigi Vicinanza. + * All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#include "xrick/e_sbonus.h" + +#include "xrick/game.h" +#include "xrick/ents.h" +#include "xrick/util.h" +#include "xrick/maps.h" +#include "xrick/e_rick.h" + + +/* + * public vars + */ +bool e_sbonus_counting = false; +U8 e_sbonus_counter = 0; +U16 e_sbonus_bonus = 0; + + +/* + * Entity action / start counting + * + * ASM 2182 + */ +void +e_sbonus_start(U8 e) +{ + ent_ents[e].sprite = 0; /* invisible */ + if (u_trigbox(e, ENT_XRICK.x + 0x0C, ENT_XRICK.y + 0x0A)) { + /* rick is within trigger box */ + ent_ents[e].n = 0; + e_sbonus_counting = true; /* 6DD5 */ + e_sbonus_counter = 0x1e; /* 6DDB */ + e_sbonus_bonus = 2000; /* 291A-291D */ +#ifdef ENABLE_SOUND + syssnd_play(soundSbonus1, 1); +#endif + } +} + + +/* + * Entity action / stop counting + * + * ASM 2143 + */ +void +e_sbonus_stop(U8 e) +{ + ent_ents[e].sprite = 0; /* invisible */ + + if (!e_sbonus_counting) + return; + + if (u_trigbox(e, ENT_XRICK.x + 0x0C, ENT_XRICK.y + 0x0A)) { + /* rick is within trigger box */ + e_sbonus_counting = false; /* stop counting */ + ent_ents[e].n = 0; /* deactivate entity */ + game_score += e_sbonus_bonus; /* add bonus to score */ +#ifdef ENABLE_SOUND + syssnd_play(soundSbonus2, 1); +#endif + /* make sure the entity won't be activated again */ + map_marks[ent_ents[e].mark].ent |= MAP_MARK_NACT; + } + else { + /* keep counting */ + if (--e_sbonus_counter == 0) { + e_sbonus_counter = 0x1e; + if (e_sbonus_bonus) e_sbonus_bonus--; + } + } +} + +/* eof */ diff --git a/apps/plugins/xrick/e_sbonus.h b/apps/plugins/xrick/e_sbonus.h new file mode 100644 index 0000000000..dbb29c9c99 --- /dev/null +++ b/apps/plugins/xrick/e_sbonus.h @@ -0,0 +1,30 @@ +/* + * xrick/e_sbonus.h + * + * Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net). + * Copyright (C) 2008-2014 Pierluigi Vicinanza. + * All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#ifndef _E_SBONUS_H +#define _E_SBONUS_H + +#include "xrick/system/basic_types.h" + +extern bool e_sbonus_counting; +extern U8 e_sbonus_counter; +extern U16 e_sbonus_bonus; + +extern void e_sbonus_start(U8); +extern void e_sbonus_stop(U8); + +#endif /* ndef _E_SBONUS_H */ + +/* eof */ diff --git a/apps/plugins/xrick/e_them.c b/apps/plugins/xrick/e_them.c new file mode 100644 index 0000000000..465325b652 --- /dev/null +++ b/apps/plugins/xrick/e_them.c @@ -0,0 +1,738 @@ +/* + * xrick/e_them.c + * + * Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net). + * Copyright (C) 2008-2014 Pierluigi Vicinanza. + * All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#include "xrick/e_them.h" + +#include "xrick/game.h" +#include "xrick/ents.h" +#include "xrick/e_rick.h" +#include "xrick/e_bomb.h" +#include "xrick/e_bullet.h" +#include "xrick/maps.h" +#include "xrick/util.h" + +#define TYPE_1A (0x00) +#define TYPE_1B (0xff) + +/* + * public vars + */ +U32 e_them_rndseed = 0; + +/* + * local vars + */ +static U16 e_them_rndnbr = 0; + +/* + * Check if entity boxtests with a lethal e_them i.e. something lethal + * in slot 0 and 4 to 8. + * + * ASM 122E + * + * e: entity slot number. + * ret: true/boxtests, false/not + */ +static bool +u_themtest(U8 e) +{ + U8 i; + + if ((ent_ents[0].n & ENT_LETHAL) && u_boxtest(e, 0)) + return true; + + for (i = 4; i < 9; i++) + if ((ent_ents[i].n & ENT_LETHAL) && u_boxtest(e, i)) + return true; + + return false; +} + + +/* + * Go zombie + * + * ASM 237B + */ +void +e_them_gozombie(U8 e) +{ +#define offsx c1 + ent_ents[e].n = 0x47; /* zombie entity */ + ent_ents[e].front = true; + ent_ents[e].offsy = -0x0400; +#ifdef ENABLE_SOUND + syssnd_play(soundDie, 1); +#endif + game_score += 50; + if (ent_ents[e].flags & ENT_FLG_ONCE) { + /* make sure entity won't be activated again */ + map_marks[ent_ents[e].mark].ent |= MAP_MARK_NACT; + } + ent_ents[e].offsx = (ent_ents[e].x >= 0x80 ? -0x02 : 0x02); +#undef offsx +} + + +/* + * Action sub-function for e_them _t1a and _t1b + * + * Those two types move horizontally, and fall if they have to. + * Type 1a moves horizontally over a given distance and then + * u-turns and repeats; type 1b is more subtle as it does u-turns + * in order to move horizontally towards rick. + * + * ASM 2242 + */ +void +e_them_t1_action2(U8 e, U8 type) +{ +#define offsx c1 +#define step_count c2 + U32 i; + S16 x, y; + U8 env0, env1; + + /* by default, try vertical move. calculate new y */ + i = (ent_ents[e].y << 8) + ent_ents[e].offsy + ent_ents[e].ylow; + y = i >> 8; + + /* deactivate if outside vertical boundaries */ + /* no need to test zero since e_them _t1a/b don't go up */ + /* FIXME what if they got scrolled out ? */ + if (y > 0x140) { + ent_ents[e].n = 0; + return; + } + + /* test environment */ + u_envtest(ent_ents[e].x, y, false, &env0, &env1); + + if (!(env1 & (MAP_EFLG_VERT|MAP_EFLG_SOLID|MAP_EFLG_SPAD|MAP_EFLG_WAYUP))) { + /* vertical move possible: falling */ + if (env1 & MAP_EFLG_LETHAL) { + /* lethal entities kill e_them */ + e_them_gozombie(e); + return; + } + /* save, cleanup and return */ + ent_ents[e].y = y; + ent_ents[e].ylow = i; + ent_ents[e].offsy += 0x0080; + if (ent_ents[e].offsy > 0x0800) + ent_ents[e].offsy = 0x0800; + return; + } + + /* vertical move not possible. calculate new sprite */ + ent_ents[e].sprite = ent_ents[e].sprbase + + ent_sprseq[(ent_ents[e].x & 0x1c) >> 3] + + (ent_ents[e].offsx < 0 ? 0x03 : 0x00); + + /* reset offsy */ + ent_ents[e].offsy = 0x0080; + + /* align to ground */ + ent_ents[e].y &= 0xfff8; + ent_ents[e].y |= 0x0003; + + /* latency: if not zero then decrease and return */ + if (ent_ents[e].latency > 0) { + ent_ents[e].latency--; + return; + } + + /* horizontal move. calculate new x */ + if (ent_ents[e].offsx == 0) /* not supposed to move -> don't */ + return; + + x = ent_ents[e].x + ent_ents[e].offsx; + if (ent_ents[e].x < 0 || ent_ents[e].x > 0xe8) { + /* U-turn and return if reaching horizontal boundaries */ + ent_ents[e].step_count = 0; + ent_ents[e].offsx = -ent_ents[e].offsx; + return; + } + + /* test environment */ + u_envtest(x, ent_ents[e].y, false, &env0, &env1); + + if (env1 & (MAP_EFLG_VERT|MAP_EFLG_SOLID|MAP_EFLG_SPAD|MAP_EFLG_WAYUP)) { + /* horizontal move not possible: u-turn and return */ + ent_ents[e].step_count = 0; + ent_ents[e].offsx = -ent_ents[e].offsx; + return; + } + + /* horizontal move possible */ + if (env1 & MAP_EFLG_LETHAL) { + /* lethal entities kill e_them */ + e_them_gozombie(e); + return; + } + + /* save */ + ent_ents[e].x = x; + + /* depending on type, */ + if (type == TYPE_1B) { + /* set direction to move horizontally towards rick */ + if ((ent_ents[e].x & 0x1e) != 0x10) /* prevents too frequent u-turns */ + return; + ent_ents[e].offsx = (ent_ents[e].x < E_RICK_ENT.x) ? 0x02 : -0x02; + return; + } + else { + /* set direction according to step counter */ + ent_ents[e].step_count++; + /* FIXME why trig_x (b16) ?? */ + if ((ent_ents[e].trig_x >> 1) > ent_ents[e].step_count) + return; + } + + /* type is 1A and step counter reached its limit: u-turn */ + ent_ents[e].step_count = 0; + ent_ents[e].offsx = -ent_ents[e].offsx; +#undef offsx +#undef step_count +} + + +/* + * ASM 21CF + */ +void +e_them_t1_action(U8 e, U8 type) +{ + e_them_t1_action2(e, type); + + /* lethal entities kill them */ + if (u_themtest(e)) { + e_them_gozombie(e); + return; + } + + /* bullet kills them */ + if (E_BULLET_ENT.n && + u_fboxtest(e, E_BULLET_ENT.x + (e_bullet_offsx < 0 ? 0 : 0x18), + E_BULLET_ENT.y)) { + E_BULLET_ENT.n = 0; + e_them_gozombie(e); + return; + } + + /* bomb kills them */ + if (e_bomb_lethal && e_bomb_hit(e)) { + e_them_gozombie(e); + return; + } + + /* rick stops them */ + if (e_rick_state_test(E_RICK_STSTOP) && + u_fboxtest(e, e_rick_stop_x, e_rick_stop_y)) + ent_ents[e].latency = 0x14; + + /* they kill rick */ + if (e_rick_boxtest(e)) + e_rick_gozombie(); +} + + +/* + * Action function for e_them _t1a type (stays within boundaries) + * + * ASM 2452 + */ +void +e_them_t1a_action(U8 e) +{ + e_them_t1_action(e, TYPE_1A); +} + + +/* + * Action function for e_them _t1b type (runs for rick) + * + * ASM 21CA + */ +void +e_them_t1b_action(U8 e) +{ + e_them_t1_action(e, TYPE_1B); +} + + +/* + * Action function for e_them _z (zombie) type + * + * ASM 23B8 + */ +void +e_them_z_action(U8 e) +{ +#define offsx c1 + U32 i; + + /* calc new sprite */ + ent_ents[e].sprite = ent_ents[e].sprbase + + ((ent_ents[e].x & 0x04) ? 0x07 : 0x06); + + /* calc new y */ + i = (ent_ents[e].y << 8) + ent_ents[e].offsy + ent_ents[e].ylow; + + /* deactivate if out of vertical boundaries */ + if (ent_ents[e].y < 0 || ent_ents[e].y > 0x0140) { + ent_ents[e].n = 0; + return; + } + + /* save */ + ent_ents[e].offsy += 0x0080; + ent_ents[e].ylow = i; + ent_ents[e].y = i >> 8; + + /* calc new x */ + ent_ents[e].x += ent_ents[e].offsx; + + /* must stay within horizontal boundaries */ + if (ent_ents[e].x < 0) + ent_ents[e].x = 0; + if (ent_ents[e].x > 0xe8) + ent_ents[e].x = 0xe8; +#undef offsx +} + + +/* + * Action sub-function for e_them _t2. + * + * Must document what it does. + * + * ASM 2792 + */ +void +e_them_t2_action2(U8 e) +{ +#define flgclmb c1 +#define offsx c2 + U32 i; + S16 x, y, yd; + U8 env0, env1; + + /* + * vars required by the Black Magic (tm) performance at the + * end of this function. + */ + static U16 bx; + static U8 *bl = (U8 *)&bx; + static U8 *bh = (U8 *)&bx + 1; + static U16 cx; + static U8 *cl = (U8 *)&cx; + static U8 *ch = (U8 *)&cx + 1; + static U16 *sl = (U16 *)&e_them_rndseed; + static U16 *sh = (U16 *)&e_them_rndseed + 2; + + /*sys_printf("e_them_t2 ------------------------------\n");*/ + + /* latency: if not zero then decrease */ + if (ent_ents[e].latency > 0) ent_ents[e].latency--; + + /* climbing? */ + if (!ent_ents[e].flgclmb) goto climbing_not; + + /* CLIMBING */ + + /*sys_printf("e_them_t2 climbing\n");*/ + + /* latency: if not zero then return */ + if (ent_ents[e].latency > 0) return; + + /* calc new sprite */ + ent_ents[e].sprite = ent_ents[e].sprbase + 0x08 + + (((ent_ents[e].x ^ ent_ents[e].y) & 0x04) ? 1 : 0); + + /* reached rick's level? */ + if ((ent_ents[e].y & 0xfe) != (E_RICK_ENT.y & 0xfe)) goto ymove; + + xmove: + /* calc new x and test environment */ + ent_ents[e].offsx = (ent_ents[e].x < E_RICK_ENT.x) ? 0x02 : -0x02; + x = ent_ents[e].x + ent_ents[e].offsx; + u_envtest(x, ent_ents[e].y, false, &env0, &env1); + if (env1 & (MAP_EFLG_SOLID|MAP_EFLG_SPAD|MAP_EFLG_WAYUP)) + return; + if (env1 & MAP_EFLG_LETHAL) { + e_them_gozombie(e); + return; + } + ent_ents[e].x = x; + if (env1 & (MAP_EFLG_VERT|MAP_EFLG_CLIMB)) /* still climbing */ + return; + goto climbing_not; /* not climbing anymore */ + + ymove: + /* calc new y and test environment */ + yd = ent_ents[e].y < E_RICK_ENT.y ? 0x02 : -0x02; + y = ent_ents[e].y + yd; + if (y < 0 || y > 0x0140) { + ent_ents[e].n = 0; + return; + } + u_envtest(ent_ents[e].x, y, false, &env0, &env1); + if (env1 & (MAP_EFLG_SOLID|MAP_EFLG_SPAD|MAP_EFLG_WAYUP)) { + if (yd < 0) + goto xmove; /* can't go up */ + else + goto climbing_not; /* can't go down */ + } + /* can move */ + ent_ents[e].y = y; + if (env1 & (MAP_EFLG_VERT|MAP_EFLG_CLIMB)) /* still climbing */ + return; + + /* NOT CLIMBING */ + + climbing_not: + /*sys_printf("e_them_t2 climbing NOT\n");*/ + + ent_ents[e].flgclmb = false; /* not climbing */ + + /* calc new y (falling) and test environment */ + i = (ent_ents[e].y << 8) + ent_ents[e].offsy + ent_ents[e].ylow; + y = i >> 8; + u_envtest(ent_ents[e].x, y, false, &env0, &env1); + if (!(env1 & (MAP_EFLG_SOLID|MAP_EFLG_SPAD|MAP_EFLG_WAYUP))) { + /*sys_printf("e_them_t2 y move OK\n");*/ + /* can go there */ + if (env1 & MAP_EFLG_LETHAL) { + e_them_gozombie(e); + return; + } + if (y > 0x0140) { /* deactivate if outside */ + ent_ents[e].n = 0; + return; + } + if (!(env1 & MAP_EFLG_VERT)) { + /* save */ + ent_ents[e].y = y; + ent_ents[e].ylow = i; + ent_ents[e].offsy += 0x0080; + if (ent_ents[e].offsy > 0x0800) + ent_ents[e].offsy = 0x0800; + return; + } + if (((ent_ents[e].x & 0x07) == 0x04) && (y < E_RICK_ENT.y)) { + /*sys_printf("e_them_t2 climbing00\n");*/ + ent_ents[e].flgclmb = true; /* climbing */ + return; + } + } + + /*sys_printf("e_them_t2 ymove nok or ...\n");*/ + /* can't go there, or ... */ + ent_ents[e].y = (ent_ents[e].y & 0xf8) | 0x03; /* align to ground */ + ent_ents[e].offsy = 0x0100; + if (ent_ents[e].latency != 00) + return; + + if ((env1 & MAP_EFLG_CLIMB) && + ((ent_ents[e].x & 0x0e) == 0x04) && + (ent_ents[e].y > E_RICK_ENT.y)) { + /*sys_printf("e_them_t2 climbing01\n");*/ + ent_ents[e].flgclmb = true; /* climbing */ + return; + } + + /* calc new sprite */ + ent_ents[e].sprite = ent_ents[e].sprbase + + ent_sprseq[(ent_ents[e].offsx < 0 ? 4 : 0) + + ((ent_ents[e].x & 0x0e) >> 3)]; + /*sys_printf("e_them_t2 sprite %02x\n", ent_ents[e].sprite);*/ + + + /* */ + if (ent_ents[e].offsx == 0) + ent_ents[e].offsx = 2; + x = ent_ents[e].x + ent_ents[e].offsx; + /*sys_printf("e_them_t2 xmove x=%02x\n", x);*/ + if (x < 0xe8) { + u_envtest(x, ent_ents[e].y, false, &env0, &env1); + if (!(env1 & (MAP_EFLG_VERT|MAP_EFLG_SOLID|MAP_EFLG_SPAD|MAP_EFLG_WAYUP))) { + ent_ents[e].x = x; + if ((x & 0x1e) != 0x08) + return; + + /* + * Black Magic (tm) + * + * this is obviously some sort of randomizer to define a direction + * for the entity. it is an exact copy of what the assembler code + * does but I can't explain. + */ + bx = e_them_rndnbr + *sh + *sl + 0x0d; + cx = *sh; + *bl ^= *ch; + *bl ^= *cl; + *bl ^= *bh; + e_them_rndnbr = bx; + + ent_ents[e].offsx = (*bl & 0x01) ? -0x02 : 0x02; + + /* back to normal */ + + return; + + } + } + + /* U-turn */ + /*sys_printf("e_them_t2 u-turn\n");*/ + if (ent_ents[e].offsx == 0) + ent_ents[e].offsx = 2; + else + ent_ents[e].offsx = -ent_ents[e].offsx; +#undef offsx +} + +/* + * Action function for e_them _t2 type + * + * ASM 2718 + */ +void +e_them_t2_action(U8 e) +{ + e_them_t2_action2(e); + + /* they kill rick */ + if (e_rick_boxtest(e)) + e_rick_gozombie(); + + /* lethal entities kill them */ + if (u_themtest(e)) { + e_them_gozombie(e); + return; + } + + /* bullet kills them */ + if (E_BULLET_ENT.n && + u_fboxtest(e, E_BULLET_ENT.x + (e_bullet_offsx < 0 ? 00 : 0x18), + E_BULLET_ENT.y)) { + E_BULLET_ENT.n = 0; + e_them_gozombie(e); + return; + } + + /* bomb kills them */ + if (e_bomb_lethal && e_bomb_hit(e)) { + e_them_gozombie(e); + return; + } + + /* rick stops them */ + if (e_rick_state_test(E_RICK_STSTOP) && + u_fboxtest(e, e_rick_stop_x, e_rick_stop_y)) + ent_ents[e].latency = 0x14; +} + + +/* + * Action sub-function for e_them _t3 + * + * FIXME always starts asleep?? + * + * Waits until triggered by something, then execute move steps from + * ent_mvstep with sprite from ent_sprseq. When done, either restart + * or disappear. + * + * Not always lethal ... but if lethal, kills rick. + * + * ASM: 255A + */ +void +e_them_t3_action2(U8 e) +{ +#define sproffs c1 +#define step_count c2 + U8 i; + S16 x, y; + int wav_index; + + while (1) { + + /* calc new sprite */ + i = ent_sprseq[ent_ents[e].sprbase + ent_ents[e].sproffs]; + if (i == 0xff) + i = ent_sprseq[ent_ents[e].sprbase]; + ent_ents[e].sprite = i; + + if (ent_ents[e].sproffs != 0) { /* awake */ + + /* rotate sprseq */ + if (ent_sprseq[ent_ents[e].sprbase + ent_ents[e].sproffs] != 0xff) + ent_ents[e].sproffs++; + if (ent_sprseq[ent_ents[e].sprbase + ent_ents[e].sproffs] == 0xff) + ent_ents[e].sproffs = 1; + + if (ent_ents[e].step_count < ent_mvstep[ent_ents[e].step_no].count) { + /* + * still running this step: try to increment x and y while + * checking that they remain within boudaries. if so, return. + * else switch to next step. + */ + ent_ents[e].step_count++; + x = ent_ents[e].x + ent_mvstep[ent_ents[e].step_no].dx; + + /* check'n save */ + if (x > 0 && x < 0xe8) { + ent_ents[e].x = x; + /*FIXME*/ + /* + y = ent_mvstep[ent_ents[e].step_no].dy; + if (y < 0) + y += 0xff00; + y += ent_ents[e].y; + */ + y = ent_ents[e].y + ent_mvstep[ent_ents[e].step_no].dy; + if (y > 0 && y < 0x0140) { + ent_ents[e].y = y; + return; + } + } + } + + /* + * step is done, or x or y is outside boundaries. try to + * switch to next step + */ + ent_ents[e].step_no++; + if (ent_mvstep[ent_ents[e].step_no].count != 0xff) { + /* there is a next step: init and loop */ + ent_ents[e].step_count = 0; + } + else { + /* there is no next step: restart or deactivate */ + if (!e_rick_state_test(E_RICK_STZOMBIE) && + !(ent_ents[e].flags & ENT_FLG_ONCE)) { + /* loop this entity */ + ent_ents[e].sproffs = 0; + ent_ents[e].n &= ~ENT_LETHAL; + if (ent_ents[e].flags & ENT_FLG_LETHALR) + ent_ents[e].n |= ENT_LETHAL; + ent_ents[e].x = ent_ents[e].xsave; + ent_ents[e].y = ent_ents[e].ysave; + if (ent_ents[e].y < 0 || ent_ents[e].y > 0x140) { + ent_ents[e].n = 0; + return; + } + } + else { + /* deactivate this entity */ + ent_ents[e].n = 0; + return; + } + } + } + else { /* ent_ents[e].sprseq1 == 0 -- waiting */ + + /* ugly GOTOs */ + + if (ent_ents[e].flags & ENT_FLG_TRIGRICK) { /* reacts to rick */ + /* wake up if triggered by rick */ + if (u_trigbox(e, E_RICK_ENT.x + 0x0C, E_RICK_ENT.y + 0x0A)) + goto wakeup; + } + + if (ent_ents[e].flags & ENT_FLG_TRIGSTOP) { /* reacts to rick "stop" */ + /* wake up if triggered by rick "stop" */ + if (e_rick_state_test(E_RICK_STSTOP) && + u_trigbox(e, e_rick_stop_x, e_rick_stop_y)) + goto wakeup; + } + + if (ent_ents[e].flags & ENT_FLG_TRIGBULLET) { /* reacts to bullets */ + /* wake up if triggered by bullet */ + if (E_BULLET_ENT.n && u_trigbox(e, e_bullet_xc, e_bullet_yc)) { + E_BULLET_ENT.n = 0; + goto wakeup; + } + } + + if (ent_ents[e].flags & ENT_FLG_TRIGBOMB) { /* reacts to bombs */ + /* wake up if triggered by bomb */ + if (e_bomb_lethal && u_trigbox(e, e_bomb_xc, e_bomb_yc)) + goto wakeup; + } + + /* not triggered: keep waiting */ + return; + + /* something triggered the entity: wake up */ + /* initialize step counter */ + wakeup: + if (e_rick_state_test(E_RICK_STZOMBIE)) + { + return; + } +#ifdef ENABLE_SOUND + /* + * FIXME the sound should come from a table, there are 10 of them + * but I dont have the table yet. must rip the data off the game... + * FIXME is it 8 of them, not 10? + * FIXME testing below... + */ + + /* FIXME this is defensive, need to figure out whether there + is simply missing sound (and possibly rip it) + or wrong data in sumbmap 47 (when making the switch explode) + and submap 13 (when touching jewel) */ + wav_index = (ent_ents[e].trigsnd & 0x1F) - 0x14; + if((0 <= wav_index) && (wav_index < SOUNDS_NBR_ENTITIES - 1)) + { + syssnd_play(soundEntity[wav_index], 1); + } + /*syssnd_play(WAV_ENTITY[0], 1);*/ +#endif /* ENABLE_SOUND */ + ent_ents[e].n &= ~ENT_LETHAL; + if (ent_ents[e].flags & ENT_FLG_LETHALI) + ent_ents[e].n |= ENT_LETHAL; + ent_ents[e].sproffs = 1; + ent_ents[e].step_count = 0; + ent_ents[e].step_no = ent_ents[e].step_no_i; + return; + } + } +#undef step_count +} + + +/* + * Action function for e_them _t3 type + * + * ASM 2546 + */ +void +e_them_t3_action(U8 e) +{ + e_them_t3_action2(e); + + /* if lethal, can kill rick */ + if ((ent_ents[e].n & ENT_LETHAL) && + !e_rick_state_test(E_RICK_STZOMBIE) && e_rick_boxtest(e)) { /* CALL 1130 */ + e_rick_gozombie(); + } +} + +/* eof */ diff --git a/apps/plugins/xrick/e_them.h b/apps/plugins/xrick/e_them.h new file mode 100644 index 0000000000..7b524142f6 --- /dev/null +++ b/apps/plugins/xrick/e_them.h @@ -0,0 +1,31 @@ +/* + * xrick/e_them.h + * + * Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net). + * Copyright (C) 2008-2014 Pierluigi Vicinanza. + * All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#ifndef _E_THEM_H +#define _E_THEM_H + +#include "xrick/system/basic_types.h" + +extern U32 e_them_rndseed; + +extern void e_them_t1a_action(U8); +extern void e_them_t1b_action(U8); +extern void e_them_t2_action(U8); +extern void e_them_t3_action(U8); +extern void e_them_z_action(U8); + +#endif /* ndef _E_THEM_H */ + +/* eof */ diff --git a/apps/plugins/xrick/ents.c b/apps/plugins/xrick/ents.c new file mode 100644 index 0000000000..5e35f2bdd1 --- /dev/null +++ b/apps/plugins/xrick/ents.c @@ -0,0 +1,540 @@ +/* + * xrick/ents.c + * + * Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net). + * Copyright (C) 2008-2014 Pierluigi Vicinanza. + * All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#include "xrick/ents.h" + +#include "xrick/config.h" +#include "xrick/control.h" +#include "xrick/game.h" +#include "xrick/debug.h" +#include "xrick/e_bullet.h" +#include "xrick/e_bomb.h" +#include "xrick/e_rick.h" +#include "xrick/e_them.h" +#include "xrick/e_bonus.h" +#include "xrick/e_box.h" +#include "xrick/e_sbonus.h" +#include "xrick/rects.h" +#include "xrick/maps.h" +#include "xrick/draw.h" + +#include /* abs */ + +/* + * global vars + */ +ent_t ent_ents[ENT_ENTSNUM + 1]; + +size_t ent_nbr_entdata = 0; +entdata_t *ent_entdata = NULL; + +rect_t *ent_rects = NULL; + +size_t ent_nbr_sprseq = 0; +U8 *ent_sprseq = NULL; + +size_t ent_nbr_mvstep = 0; +mvstep_t *ent_mvstep = NULL; + +/* + * prototypes + */ +static void ent_addrect(S16, S16, U16, U16); +static bool ent_creat1(U8 *); +static bool ent_creat2(U8 *, U16); + + +/* + * Reset entities + * + * ASM 2520 + */ +void +ent_reset(void) +{ + U8 i; + + e_rick_state_clear(E_RICK_STSTOP); + e_bomb_lethal = false; + + ent_ents[0].n = 0; + for (i = 2; ent_ents[i].n != 0xff; i++) + ent_ents[i].n = 0; +} + + +/* + * Create an entity on slots 4 to 8 by using the first slot available. + * Entities of type e_them on slots 4 to 8, when lethal, can kill + * other e_them (on slots 4 to C) as well as rick. + * + * ASM 209C + * + * e: anything, CHANGED to the allocated entity number. + * return: true/OK false/not + */ +static bool +ent_creat1(U8 *e) +{ + /* look for a slot */ + for (*e = 0x04; *e < 0x09; (*e)++) + if (ent_ents[*e].n == 0) { /* if slot available, use it */ + ent_ents[*e].c1 = 0; + return true; + } + + return false; +} + + +/* + * Create an entity on slots 9 to C by using the first slot available. + * Entities of type e_them on slots 9 to C can kill rick when lethal, + * but they can never kill other e_them. + * + * ASM 20BC + * + * e: anything, CHANGED to the allocated entity number. + * m: number of the mark triggering the creation of the entity. + * ret: true/OK false/not + */ +static bool +ent_creat2(U8 *e, U16 m) +{ + /* make sure the entity created by this mark is not active already */ + for (*e = 0x09; *e < 0x0c; (*e)++) + if (ent_ents[*e].n != 0 && ent_ents[*e].mark == m) + return false; + + /* look for a slot */ + for (*e = 0x09; *e < 0x0c; (*e)++) + if (ent_ents[*e].n == 0) { /* if slot available, use it */ + ent_ents[*e].c1 = 2; + return true; + } + + return false; +} + + +/* + * Process marks that are within the visible portion of the map, + * and create the corresponding entities. + * + * absolute map coordinate means that they are not relative to + * map_frow, as any other coordinates are. + * + * ASM 1F40 + * + * frow: first visible row of the map -- absolute map coordinate + * lrow: last visible row of the map -- absolute map coordinate + */ +void +ent_actvis(U8 frow, U8 lrow) +{ + U16 m; + U8 e; + U16 y; + + /* + * go through the list and find the first mark that + * is visible, i.e. which has a row greater than the + * first row (marks being ordered by row number). + */ + for (m = map_submaps[game_submap].mark; + map_marks[m].row != 0xff && map_marks[m].row < frow; + m++); + + if (map_marks[m].row == 0xff) /* none found */ + return; + + /* + * go through the list and process all marks that are + * visible, i.e. which have a row lower than the last + * row (marks still being ordered by row number). + */ + for (; + map_marks[m].row != 0xff && map_marks[m].row < lrow; + m++) { + + /* ignore marks that are not active */ + if (map_marks[m].ent & MAP_MARK_NACT) + continue; + + /* + * allocate a slot to the new entity + * + * slot type + * 0 available for e_them (lethal to other e_them, and stops entities + * i.e. entities can't move over them. E.g. moving blocks. But they + * can move over entities and kill them!). + * 1 xrick + * 2 bullet + * 3 bomb + * 4-8 available for e_them, e_box, e_bonus or e_sbonus (lethal to + * other e_them, identified by their number being >= 0x10) + * 9-C available for e_them, e_box, e_bonus or e_sbonus (not lethal to + * other e_them, identified by their number being < 0x10) + * + * the type of an entity is determined by its .n as detailed below. + * + * 1 xrick + * 2 bullet + * 3 bomb + * 4, 7, a, d e_them, type 1a + * 5, 8, b, e e_them, type 1b + * 6, 9, c, f e_them, type 2 + * 10, 11 box + * 12, 13, 14, 15 bonus + * 16, 17 speed bonus + * >17 e_them, type 3 + * 47 zombie + */ + + if (!(map_marks[m].flags & ENT_FLG_STOPRICK)) { + if (map_marks[m].ent >= 0x10) { + /* boxes, bonuses and type 3 e_them go to slot 4-8 */ + /* (c1 set to 0 -> all type 3 e_them are sleeping) */ + if (!ent_creat1(&e)) continue; + } + else { + /* type 1 and 2 e_them go to slot 9-c */ + /* (c1 set to 2) */ + if (!ent_creat2(&e, m)) continue; + } + } + else { + /* entities stopping rick (e.g. blocks) go to slot 0 */ + if (ent_ents[0].n) continue; + e = 0; + ent_ents[0].c1 = 0; + } + + /* + * initialize the entity + */ + ent_ents[e].mark = m; + ent_ents[e].flags = map_marks[m].flags; + ent_ents[e].n = map_marks[m].ent; + + /* + * if entity is to be already running (i.e. not asleep and waiting + * for some trigger to move), then use LETHALR i.e. restart flag, right + * from the beginning + */ + if (ent_ents[e].flags & ENT_FLG_LETHALR) + ent_ents[e].n |= ENT_LETHAL; + + ent_ents[e].x = map_marks[m].xy & 0xf8; + + y = (map_marks[m].xy & 0x07) + (map_marks[m].row & 0xf8) - map_frow; + y <<= 3; + if (!(ent_ents[e].flags & ENT_FLG_STOPRICK)) + y += 3; + ent_ents[e].y = y; + + ent_ents[e].xsave = ent_ents[e].x; + ent_ents[e].ysave = ent_ents[e].y; + + /*ent_ents[e].w0C = 0;*/ /* in ASM code but never used */ + + ent_ents[e].w = ent_entdata[map_marks[m].ent].w; + ent_ents[e].h = ent_entdata[map_marks[m].ent].h; + ent_ents[e].sprbase = ent_entdata[map_marks[m].ent].spr; + ent_ents[e].step_no_i = ent_entdata[map_marks[m].ent].sni; + ent_ents[e].trigsnd = (U8)ent_entdata[map_marks[m].ent].snd; + + /* + * FIXME what is this? when all trigger flags are up, then + * use .sni for sprbase. Why? What is the point? (This is + * for type 1 and 2 e_them, ...) + * + * This also means that as long as sprite has not been + * recalculated, a wrong value is used. This is normal, see + * what happens to the falling guy on the right on submap 3: + * it changes when hitting the ground. + * + * Note: sprite recalculation has been fixed, refer to the commit log. + */ +#define ENT_FLG_TRIGGERS \ +(ENT_FLG_TRIGBOMB|ENT_FLG_TRIGBULLET|ENT_FLG_TRIGSTOP|ENT_FLG_TRIGRICK) + if ((ent_ents[e].flags & ENT_FLG_TRIGGERS) == ENT_FLG_TRIGGERS + && e >= 0x09) + ent_ents[e].sprbase = (U8)(ent_entdata[map_marks[m].ent].sni & 0x00ff); +#undef ENT_FLG_TRIGGERS + + ent_ents[e].sprite = (U8)ent_ents[e].sprbase; + ent_ents[e].trig_x = map_marks[m].lt & 0xf8; + ent_ents[e].latency = (map_marks[m].lt & 0x07) << 5; /* <<5 eq *32 */ + + ent_ents[e].trig_y = 3 + 8 * ((map_marks[m].row & 0xf8) - map_frow + + (map_marks[m].lt & 0x07)); + + ent_ents[e].c2 = 0; + ent_ents[e].offsy = 0; + ent_ents[e].ylow = 0; + + ent_ents[e].front = false; + + } +} + + +/* + * Add a tile-aligned rectangle containing the given rectangle (indicated + * by its MAP coordinates) to the list of rectangles. Clip the rectangle + * so it fits into the display zone. + */ +static void +ent_addrect(S16 x, S16 y, U16 width, U16 height) +{ + S16 x0, y0; + U16 w0, h0; + rect_t *r; + + /*sys_printf("rect %#04x,%#04x %#04x %#04x ", x, y, width, height);*/ + + /* align to tiles */ + x0 = x & 0xfff8; + y0 = y & 0xfff8; + w0 = width; + h0 = height; + if (x - x0) w0 = (w0 + (x - x0)) | 0x0007; + if (y - y0) h0 = (h0 + (y - y0)) | 0x0007; + + /* clip */ + if (draw_clipms(&x0, &y0, &w0, &h0)) { /* do not add if fully clipped */ + /*sys_printf("-> [clipped]\n");*/ + return; + } + + /*sys_printf("-> %#04x,%#04x %#04x %#04x\n", x0, y0, w0, h0);*/ + +#ifdef GFXST + y0 += 8; +#endif + + /* get to screen */ + x0 -= DRAW_XYMAP_SCRLEFT; + y0 -= DRAW_XYMAP_SCRTOP; + + /* add rectangle to the list */ + r = rects_new(x0, y0, w0, h0, ent_rects); + if (!r) + { + control_set(Control_EXIT); + return; + } + ent_rects = r; +} + + +/* + * Draw all entities onto the frame buffer. + * + * ASM 07a4 + * + * NOTE This may need to be part of draw.c. Also needs better comments, + * NOTE and probably better rectangles management. + */ +void +ent_draw(void) +{ + U8 i; +#ifdef ENABLE_CHEATS + static bool ch3 = false; +#endif + S16 dx, dy; + + draw_tilesBank = map_tilesBank; + + /* reset rectangles list */ + rects_free(ent_rects); + ent_rects = NULL; + + /*sys_printf("\n");*/ + + /* + * background loop : erase all entities that were visible + */ + for (i = 0; ent_ents[i].n != 0xff; i++) { +#ifdef ENABLE_CHEATS + if (ent_ents[i].prev_n && (ch3 || ent_ents[i].prev_s)) +#else + if (ent_ents[i].prev_n && ent_ents[i].prev_s) +#endif + /* if entity was active, then erase it (redraw the map) */ + draw_spriteBackground(ent_ents[i].prev_x, ent_ents[i].prev_y); + } + + /* + * foreground loop : draw all entities that are visible + */ + for (i = 0; ent_ents[i].n != 0xff; i++) { + /* + * If entity is active now, draw the sprite. If entity was + * not active before, add a rectangle for the sprite. + */ +#ifdef ENABLE_CHEATS + if (ent_ents[i].n && (game_cheat3 || ent_ents[i].sprite)) +#else + if (ent_ents[i].n && ent_ents[i].sprite) +#endif + /* If entitiy is active, draw the sprite. */ + draw_sprite2(ent_ents[i].sprite, + ent_ents[i].x, ent_ents[i].y, + ent_ents[i].front); + } + + /* + * rectangles loop : figure out which parts of the screen have been + * impacted and need to be refreshed, then save state + */ + for (i = 0; ent_ents[i].n != 0xff; i++) { +#ifdef ENABLE_CHEATS + if (ent_ents[i].prev_n && (ch3 || ent_ents[i].prev_s)) { +#else + if (ent_ents[i].prev_n && ent_ents[i].prev_s) { +#endif + /* (1) if entity was active and has been drawn ... */ +#ifdef ENABLE_CHEATS + if (ent_ents[i].n && (game_cheat3 || ent_ents[i].sprite)) { +#else + if (ent_ents[i].n && ent_ents[i].sprite) { +#endif + /* (1.1) ... and is still active now and still needs to be drawn, */ + /* then check if rectangles intersect */ + dx = abs(ent_ents[i].x - ent_ents[i].prev_x); + dy = abs(ent_ents[i].y - ent_ents[i].prev_y); + if (dx < 0x20 && dy < 0x16) { + /* (1.1.1) if they do, then create one rectangle */ + ent_addrect((ent_ents[i].prev_x < ent_ents[i].x) + ? ent_ents[i].prev_x : ent_ents[i].x, + (ent_ents[i].prev_y < ent_ents[i].y) + ? ent_ents[i].prev_y : ent_ents[i].y, + dx + 0x20, dy + 0x15); + } + else { + /* (1.1.2) else, create two rectangles */ + ent_addrect(ent_ents[i].x, ent_ents[i].y, 0x20, 0x15); + ent_addrect(ent_ents[i].prev_x, ent_ents[i].prev_y, 0x20, 0x15); + } + } + else + /* (1.2) ... and is not active anymore or does not need to be drawn */ + /* then create one single rectangle */ + ent_addrect(ent_ents[i].prev_x, ent_ents[i].prev_y, 0x20, 0x15); + } +#ifdef ENABLE_CHEATS + else if (ent_ents[i].n && (game_cheat3 || ent_ents[i].sprite)) { +#else + else if (ent_ents[i].n && ent_ents[i].sprite) { +#endif + /* (2) if entity is active and needs to be drawn, */ + /* then create one rectangle */ + ent_addrect(ent_ents[i].x, ent_ents[i].y, 0x20, 0x15); + } + + /* save state */ + ent_ents[i].prev_x = ent_ents[i].x; + ent_ents[i].prev_y = ent_ents[i].y; + ent_ents[i].prev_n = ent_ents[i].n; + ent_ents[i].prev_s = ent_ents[i].sprite; + } + +#ifdef ENABLE_CHEATS + ch3 = game_cheat3; +#endif +} + + +/* + * Clear entities previous state + * + */ +void +ent_clprev(void) +{ + U8 i; + + for (i = 0; ent_ents[i].n != 0xff; i++) + ent_ents[i].prev_n = 0; +} + +/* + * Table containing entity action function pointers. + */ +void (*ent_actf[])(U8) = { + NULL, /* 00 - zero means that the slot is free */ + e_rick_action, /* 01 - 12CA */ + e_bullet_action, /* 02 - 1883 */ + e_bomb_action, /* 03 - 18CA */ + e_them_t1a_action, /* 04 - 2452 */ + e_them_t1b_action, /* 05 - 21CA */ + e_them_t2_action, /* 06 - 2718 */ + e_them_t1a_action, /* 07 - 2452 */ + e_them_t1b_action, /* 08 - 21CA */ + e_them_t2_action, /* 09 - 2718 */ + e_them_t1a_action, /* 0A - 2452 */ + e_them_t1b_action, /* 0B - 21CA */ + e_them_t2_action, /* 0C - 2718 */ + e_them_t1a_action, /* 0D - 2452 */ + e_them_t1b_action, /* 0E - 21CA */ + e_them_t2_action, /* 0F - 2718 */ + e_box_action, /* 10 - 245A */ + e_box_action, /* 11 - 245A */ + e_bonus_action, /* 12 - 242C */ + e_bonus_action, /* 13 - 242C */ + e_bonus_action, /* 14 - 242C */ + e_bonus_action, /* 15 - 242C */ + e_sbonus_start, /* 16 - 2182 */ + e_sbonus_stop /* 17 - 2143 */ +}; + + +/* + * Run entities action function + * + */ +void +ent_action(void) +{ + U8 i, k; + + IFDEBUG_ENTS( + sys_printf("xrick/ents: --------- action ----------------\n"); + for (i = 0; ent_ents[i].n != 0xff; i++) + if (ent_ents[i].n) { + sys_printf("xrick/ents: slot %#04x, entity %#04x", i, ent_ents[i].n); + sys_printf(" (%#06x, %#06x), sprite %#04x.\n", + ent_ents[i].x, ent_ents[i].y, ent_ents[i].sprite); + } + ); + + for (i = 0; ent_ents[i].n != 0xff; i++) { + if (ent_ents[i].n) { + k = ent_ents[i].n & 0x7f; + if (k == 0x47) + e_them_z_action(i); + else if (k >= 0x18) + e_them_t3_action(i); + else + ent_actf[k](i); + } + } +} + + +/* eof */ diff --git a/apps/plugins/xrick/ents.h b/apps/plugins/xrick/ents.h new file mode 100644 index 0000000000..1014205035 --- /dev/null +++ b/apps/plugins/xrick/ents.h @@ -0,0 +1,118 @@ +/* + * xrick/ents.h + * + * Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net). + * Copyright (C) 2008-2014 Pierluigi Vicinanza. + * All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#ifndef _ENTS_H +#define _ENTS_H + +#include "xrick/rects.h" + +#include /* size_t */ + +#define ENT_XRICK ent_ents[1] + +/* + * flags for ent_ents[e].n ("yes" when set) + * + * ENT_LETHAL: is entity lethal? + */ +#define ENT_LETHAL 0x80 + +/* + * flags for ent_ents[e].flag ("yes" when set) + * + * ENT_FLG_ONCE: should the entity run once only? + * ENT_FLG_STOPRICK: does the entity stops rick (and goes to slot zero)? + * ENT_FLG_LETHALR: is entity lethal when restarting? + * ENT_FLG_LETHALI: is entity initially lethal? + * ENT_FLG_TRIGBOMB: can entity be triggered by a bomb? + * ENT_FLG_TRIGBULLET: can entity be triggered by a bullet? + * ENT_FLG_TRIGSTOP: can entity be triggered by rick stop? + * ENT_FLG_TRIGRICK: can entity be triggered by rick? + */ +#define ENT_FLG_ONCE 0x01 +#define ENT_FLG_STOPRICK 0x02 +#define ENT_FLG_LETHALR 0x04 +#define ENT_FLG_LETHALI 0x08 +#define ENT_FLG_TRIGBOMB 0x10 +#define ENT_FLG_TRIGBULLET 0x20 +#define ENT_FLG_TRIGSTOP 0x40 +#define ENT_FLG_TRIGRICK 0x80 + +typedef struct { + U8 n; /* b00 */ + /*U8 b01;*/ /* b01 in ASM code but never used */ + S16 x; /* b02 - position */ + S16 y; /* w04 - position */ + U8 sprite; /* b08 - sprite number */ + /*U16 w0C;*/ /* w0C in ASM code but never used */ + U8 w; /* b0E - width */ + U8 h; /* b10 - height */ + U16 mark; /* w12 - number of the mark that created the entity */ + U8 flags; /* b14 */ + S16 trig_x; /* b16 - position of trigger box */ + S16 trig_y; /* w18 - position of trigger box */ + S16 xsave; /* b1C */ + S16 ysave; /* w1E */ + U16 sprbase; /* w20 */ + U16 step_no_i; /* w22 */ + U16 step_no; /* w24 */ + S16 c1; /* b26 */ + S16 c2; /* b28 */ + U8 ylow; /* b2A */ + S16 offsy; /* w2C */ + U8 latency; /* b2E */ + U8 prev_n; /* new */ + S16 prev_x; /* new */ + S16 prev_y; /* new */ + U8 prev_s; /* new */ + bool front; /* new */ + U8 trigsnd; /* new */ +} ent_t; + +typedef struct { + U8 w, h; + U16 spr, sni; + U8 trig_w, trig_h; + U8 snd; +} entdata_t; + +typedef struct { + U8 count; + S8 dx, dy; +} mvstep_t; + +enum { ENT_ENTSNUM = 12 }; +extern ent_t ent_ents[ENT_ENTSNUM + 1]; + +extern size_t ent_nbr_entdata; +extern entdata_t *ent_entdata; + +extern rect_t *ent_rects; + +extern size_t ent_nbr_sprseq; +extern U8 *ent_sprseq; + +extern size_t ent_nbr_mvstep; +extern mvstep_t *ent_mvstep; + +extern void ent_reset(void); +extern void ent_actvis(U8, U8); +extern void ent_draw(void); +extern void ent_clprev(void); +extern void ent_action(void); + +#endif /* ndef _ENTS_H */ + +/* eof */ diff --git a/apps/plugins/xrick/game.c b/apps/plugins/xrick/game.c new file mode 100644 index 0000000000..ac99c1829e --- /dev/null +++ b/apps/plugins/xrick/game.c @@ -0,0 +1,722 @@ +/* + * xrick/game.c + * + * Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net). + * Copyright (C) 2008-2014 Pierluigi Vicinanza. + * All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#include "xrick/game.h" + +#include "xrick/draw.h" +#include "xrick/maps.h" +#include "xrick/ents.h" +#include "xrick/e_rick.h" +#include "xrick/e_sbonus.h" +#include "xrick/e_them.h" +#include "xrick/screens.h" +#include "xrick/rects.h" +#include "xrick/scroller.h" +#include "xrick/control.h" +#include "xrick/resources.h" + +#ifdef ENABLE_DEVTOOLS +#include "xrick/devtools.h" +#endif + + +/* + * local typedefs + */ +typedef enum { +#ifdef ENABLE_DEVTOOLS + DEVTOOLS, +#endif + XRICK, + INIT_GAME, INIT_BUFFER, + INTRO_MAIN, INTRO_MAP, + PAUSE_PRESSED1, PAUSE_PRESSED1B, PAUSED, PAUSE_PRESSED2, + PLAY0, PLAY1, PLAY2, PLAY3, + CHAIN_SUBMAP, CHAIN_MAP, CHAIN_END, + SCROLL_UP, SCROLL_DOWN, + RESTART, GAMEOVER, GETNAME, EXIT +} game_state_t; + + +/* + * global vars + */ +U8 game_period = 0; +bool game_waitevt = false; +const rect_t *game_rects = NULL; + +U8 game_lives = 0; +U8 game_bombs = 0; +U8 game_bullets = 0; +U32 game_score = 0; + +U16 game_map = 0; +U16 game_submap = 0; + +U8 game_dir = RIGHT; +bool game_chsm = false; + +bool game_cheat1 = false; +bool game_cheat2 = false; +bool game_cheat3 = false; + + +/* + * local vars + */ +static U8 isave_frow; +static game_state_t game_state; +#ifdef ENABLE_SOUND +static sound_t *currentMusic = NULL; +#endif + + +/* + * prototypes + */ +static void frame(void); +static void init(void); +static void play0(void); +static void play3(void); +static void restart(void); +static void isave(void); +static void irestore(void); + + +/* + * Cheats + */ +#ifdef ENABLE_CHEATS +void +game_toggleCheat(cheat_t cheat) +{ + if (game_state != INTRO_MAIN && game_state != INTRO_MAP && + game_state != GAMEOVER && game_state != GETNAME && +#ifdef ENABLE_DEVTOOLS + game_state != DEVTOOLS && +#endif + game_state != XRICK && game_state != EXIT) + { + switch (cheat) + { + case Cheat_UNLIMITED_ALL: + { + game_cheat1 = !game_cheat1; + game_lives = 6; + game_bombs = 6; + game_bullets = 6; + break; + } + case Cheat_NEVER_DIE: + { + game_cheat2 = !game_cheat2; + break; + } + case Cheat_EXPOSE: + { + game_cheat3 = !game_cheat3; + break; + } + } + draw_infos(); + /* FIXME this should probably only raise a flag ... */ + /* plus we only need to update INFORECT not the whole screen */ + sysvid_update(&draw_SCREENRECT); + } +} +#endif + +#ifdef ENABLE_SOUND +/* + * Music + */ +void +game_setmusic(sound_t * newMusic, S8 loop) +{ + if (!newMusic) + { + return; + } + + if (currentMusic) + { + game_stopmusic(); + } + + syssnd_play(newMusic, loop); + + currentMusic = newMusic; +} + +void +game_stopmusic(void) +{ + syssnd_stop(currentMusic); + currentMusic = NULL; +} +#endif /*ENABLE_SOUND */ + +/* + * Main loop + */ +void +game_run(void) +{ + U32 currentTime, +#ifdef ENABLE_SOUND + lastSoundTime = 0, +#endif + lastFrameTime = 0; + + if (!resources_load()) + { + resources_unload(); + return; + } + + if (!sys_cacheData()) + { + sys_uncacheData(); + return; + } + + game_period = sysarg_args_period ? sysarg_args_period : GAME_PERIOD; + game_state = XRICK; + + /* main loop */ + while (game_state != EXIT) + { + currentTime = sys_gettime(); + + if (currentTime - lastFrameTime >= game_period) + { + /* frame */ + frame(); + + /* video */ + /*DEBUG*//*game_rects=&draw_SCREENRECT;*//*DEBUG*/ + sysvid_update(game_rects); + + /* reset rectangles list */ + rects_free(ent_rects); + ent_rects = NULL; + draw_STATUSRECT.next = NULL; /* FIXME freerects should handle this */ + + /* events */ + if (game_waitevt) + { + sysevt_wait(); /* wait for an event */ + } + else + { + sysevt_poll(); /* process events (non-blocking) */ + } + + lastFrameTime = currentTime; + } + +#ifdef ENABLE_SOUND + if (currentTime - lastSoundTime >= syssnd_period) + { + /* sound */ + syssnd_update(); + + lastSoundTime = currentTime; + } +#endif /* ENABLE_SOUND */ + + sys_yield(); + } + +#ifdef ENABLE_SOUND + syssnd_stopAll(); +#endif + + sys_uncacheData(); + + resources_unload(); +} + +/* + * Prepare frame + * + * This function loops forever: use 'return' when a frame is ready. + * When returning, game_rects must contain every parts of the buffer + * that have been modified. + */ +static void +frame(void) +{ + while (1) { + + switch (game_state) { + + + +#ifdef ENABLE_DEVTOOLS + case DEVTOOLS: + switch (devtools_run()) { + case SCREEN_RUNNING: + return; + case SCREEN_DONE: + game_state = INIT_GAME; + break; + case SCREEN_EXIT: + game_state = EXIT; + return; + } + break; +#endif + + + + case XRICK: + switch(screen_xrick()) { + case SCREEN_RUNNING: + return; + case SCREEN_DONE: +#ifdef ENABLE_DEVTOOLS + game_state = DEVTOOLS; +#else + game_state = INIT_GAME; +#endif + break; + case SCREEN_EXIT: + game_state = EXIT; + return; + } + break; + + + + case INIT_GAME: + init(); + game_state = INTRO_MAIN; + break; + + + + case INTRO_MAIN: + switch (screen_introMain()) { + case SCREEN_RUNNING: + return; + case SCREEN_DONE: + game_state = INTRO_MAP; + break; + case SCREEN_EXIT: + game_state = EXIT; + return; + } + break; + + + + case INTRO_MAP: + switch (screen_introMap()) { + case SCREEN_RUNNING: + return; + case SCREEN_DONE: + game_waitevt = false; + game_state = INIT_BUFFER; + break; + case SCREEN_EXIT: + game_state = EXIT; + return; + } + break; + + + + case INIT_BUFFER: + sysvid_clear(); /* clear buffer */ + draw_map(); /* draw the map onto the buffer */ + draw_drawStatus(); /* draw the status bar onto the buffer */ +#ifdef ENABLE_CHEATS + draw_infos(); /* draw the info bar onto the buffer */ +#endif + game_rects = &draw_SCREENRECT; /* request full buffer refresh */ + game_state = PLAY0; + return; + + + + case PAUSE_PRESSED1: + screen_pause(true); + game_state = PAUSE_PRESSED1B; + break; + + + + case PAUSE_PRESSED1B: + if (control_test(Control_PAUSE)) + return; + game_state = PAUSED; + break; + + + + case PAUSED: + if (control_test(Control_PAUSE)) + game_state = PAUSE_PRESSED2; + if (control_test(Control_EXIT)) + game_state = EXIT; + return; + + + + case PAUSE_PRESSED2: + if (!(control_test(Control_PAUSE))) { + game_waitevt = false; + screen_pause(false); +#ifdef ENABLE_SOUND + syssnd_pauseAll(false); +#endif + game_state = PLAY2; + } + return; + + + + case PLAY0: + play0(); + break; + + + + case PLAY1: + if (control_test(Control_PAUSE)) { +#ifdef ENABLE_SOUND + syssnd_pauseAll(true); +#endif + game_waitevt = true; + game_state = PAUSE_PRESSED1; + } + else if (!control_active) { +#ifdef ENABLE_SOUND + syssnd_pauseAll(true); +#endif + game_waitevt = true; + screen_pause(true); + game_state = PAUSED; + } + else + game_state = PLAY2; + break; + + + + case PLAY2: + if (e_rick_state_test(E_RICK_STDEAD)) { /* rick is dead */ + if (game_cheat1 || --game_lives) { + game_state = RESTART; + } else { + game_state = GAMEOVER; + } + } + else if (game_chsm) /* request to chain to next submap */ + game_state = CHAIN_SUBMAP; + else + game_state = PLAY3; + break; + + + + case PLAY3: + play3(); + return; + + + + case CHAIN_SUBMAP: + if (map_chain()) + game_state = CHAIN_END; + else { + game_bullets = 0x06; + game_bombs = 0x06; + game_map++; + + if (game_map == map_nbr_maps - 1) { + /* reached end of game */ + /* FIXME @292?*/ + } + + game_state = CHAIN_MAP; + } + break; + + + + case CHAIN_MAP: /* CHAIN MAP */ + switch (screen_introMap()) { + case SCREEN_RUNNING: + return; + case SCREEN_DONE: + if (game_map >= map_nbr_maps - 1) { /* reached end of game */ + sysarg_args_map = 0; + sysarg_args_submap = 0; + game_state = GAMEOVER; + } + else { /* initialize game */ + ent_ents[1].x = map_maps[game_map].x; + ent_ents[1].y = map_maps[game_map].y; + map_frow = (U8)map_maps[game_map].row; + game_submap = map_maps[game_map].submap; + game_state = CHAIN_END; + } + break; + case SCREEN_EXIT: + game_state = EXIT; + return; + } + break; + + + + case CHAIN_END: + map_init(); /* initialize the map */ + isave(); /* save data in case of a restart */ + ent_clprev(); /* cleanup entities */ + draw_map(); /* draw the map onto the buffer */ + draw_drawStatus(); /* draw the status bar onto the buffer */ + game_rects = &draw_SCREENRECT; /* request full screen refresh */ + game_state = PLAY0; + return; + + + + case SCROLL_UP: + switch (scroll_up()) { + case SCROLL_RUNNING: + return; + case SCROLL_DONE: + game_state = PLAY0; + break; + } + break; + + + + case SCROLL_DOWN: + switch (scroll_down()) { + case SCROLL_RUNNING: + return; + case SCROLL_DONE: + game_state = PLAY0; + break; + } + break; + + + + case RESTART: + restart(); + game_state = PLAY0; + return; + + + + case GAMEOVER: + switch (screen_gameover()) { + case SCREEN_RUNNING: + return; + case SCREEN_DONE: + game_state = GETNAME; + break; + case SCREEN_EXIT: + game_state = EXIT; + break; + } + break; + + + + case GETNAME: + switch (screen_getname()) { + case SCREEN_RUNNING: + return; + case SCREEN_DONE: + game_state = INIT_GAME; + return; + case SCREEN_EXIT: + game_state = EXIT; + break; + } + break; + + + + case EXIT: + return; + + } + } +} + + +/* + * Initialize the game + */ +static void +init(void) +{ + U8 i; + + e_rick_state_clear(0xff); + + game_lives = 6; + game_bombs = 6; + game_bullets = 6; + game_score = 0; + + game_map = sysarg_args_map; + + if (sysarg_args_submap == 0) + { + game_submap = map_maps[game_map].submap; + map_frow = (U8)map_maps[game_map].row; + } + else + { + /* dirty hack to determine frow */ + game_submap = sysarg_args_submap; + i = 0; + while (i < map_nbr_connect && + (map_connect[i].submap != game_submap || + map_connect[i].dir != RIGHT)) + { + i++; + } + map_frow = map_connect[i].rowin - 0x10; + ent_ents[1].y = 0x10 << 3; + } + + ent_ents[1].x = map_maps[game_map].x; + ent_ents[1].y = map_maps[game_map].y; + ent_ents[1].w = 0x18; + ent_ents[1].h = 0x15; + ent_ents[1].n = 0x01; + ent_ents[1].sprite = 0x01; + ent_ents[1].front = false; + ent_ents[ENT_ENTSNUM].n = 0xFF; + + map_resetMarks(); + + map_init(); + isave(); +} + + +/* + * play0 + * + */ +static void +play0(void) +{ + if (control_test(Control_END)) { /* request to end the game */ + game_state = GAMEOVER; + return; + } + + if (control_test(Control_EXIT)) { /* request to exit the game */ + game_state = EXIT; + return; + } + + ent_action(); /* run entities */ + e_them_rndseed++; /* (0270) */ + + game_state = PLAY1; +} + + +/* + * play3 + * + */ +static void +play3(void) +{ + draw_clearStatus(); /* clear the status bar */ + ent_draw(); /* draw all entities onto the buffer */ + /* sound */ + draw_drawStatus(); /* draw the status bar onto the buffer*/ + + game_rects = &draw_STATUSRECT; /* refresh status bar too */ + draw_STATUSRECT.next = ent_rects; /* take care to cleanup draw_STATUSRECT->next later! */ + + if (!e_rick_state_test(E_RICK_STZOMBIE)) { /* need to scroll ? */ + if (ent_ents[1].y >= 0xCC) { + game_state = SCROLL_UP; + return; + } + if (ent_ents[1].y <= 0x60) { + game_state = SCROLL_DOWN; + return; + } + } + + game_state = PLAY0; +} + + +/* + * restart + * + */ +static void +restart(void) +{ + e_rick_state_clear(E_RICK_STDEAD|E_RICK_STZOMBIE); + + game_bullets = 6; + game_bombs = 6; + + ent_ents[1].n = 1; + + irestore(); + map_init(); + isave(); + ent_clprev(); + draw_map(); + draw_drawStatus(); + game_rects = &draw_SCREENRECT; +} + + +/* + * isave (0bbb) + * + */ +static void +isave(void) +{ + e_rick_save(); + isave_frow = map_frow; +} + + +/* + * irestore (0bdc) + * + */ +static void +irestore(void) +{ + e_rick_restore(); + map_frow = isave_frow; +} + +/* eof */ diff --git a/apps/plugins/xrick/game.h b/apps/plugins/xrick/game.h new file mode 100644 index 0000000000..025c3bdbe2 --- /dev/null +++ b/apps/plugins/xrick/game.h @@ -0,0 +1,73 @@ +/* + * xrick/game.h + * + * Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net). + * Copyright (C) 2008-2014 Pierluigi Vicinanza. + * All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#ifndef _GAME_H +#define _GAME_H + +#include "xrick/config.h" +#include "xrick/rects.h" +#ifdef ENABLE_SOUND +#include "xrick/data/sounds.h" +#endif + +#include /* NULL */ + +#define LEFT 1 +#define RIGHT 0 + +#define GAME_PERIOD 40 + +#define GAME_BOMBS_INIT 6 +#define GAME_BULLETS_INIT 6 + +extern U8 game_lives; /* lives counter */ +extern U8 game_bombs; /* bombs counter */ +extern U8 game_bullets; /* bullets counter */ + +extern U32 game_score; /* score */ + +extern U16 game_map; /* current map */ +extern U16 game_submap; /* current submap */ + +extern U8 game_dir; /* direction (LEFT, RIGHT) */ +extern bool game_chsm; /* change submap request (true, false) */ + +extern bool game_waitevt; /* wait for events (true, false) */ +extern U8 game_period; /* time between each frame, in millisecond */ + +extern const rect_t *game_rects; /* rectangles to redraw at each frame */ + +extern void game_run(void); +#ifdef ENABLE_SOUND +extern void game_setmusic(sound_t * sound, S8 loop); +extern void game_stopmusic(void); +#endif /* ENABLE_SOUND */ + +#ifdef ENABLE_CHEATS +typedef enum +{ + Cheat_UNLIMITED_ALL, + Cheat_NEVER_DIE, + Cheat_EXPOSE +} cheat_t; +extern bool game_cheat1; /* infinite lives, bombs and bullets */ +extern bool game_cheat2; /* never die */ +extern bool game_cheat3; /* highlight sprites */ +extern void game_toggleCheat(cheat_t); +#endif /* ENABLE_CHEATS */ + +#endif /* ndef _GAME_H */ + +/* eof */ diff --git a/apps/plugins/xrick/maps.c b/apps/plugins/xrick/maps.c new file mode 100644 index 0000000000..f85d0b9906 --- /dev/null +++ b/apps/plugins/xrick/maps.c @@ -0,0 +1,253 @@ +/* + * xrick/maps.c + * + * Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net). + * Copyright (C) 2008-2014 Pierluigi Vicinanza. + * All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +/* + * NOTES + * + * A map is composed of submaps, which in turn are composed of rows of + * 0x20 tiles. map_map contains the tiles for the current portion of the + * current submap, i.e. a little bit more than what appear on the screen, + * but not the whole submap. + * + * map_frow is map_map top row within the submap. + * + * Submaps are stored as arrays of blocks, each block being a 4x4 tile + * array. map_submaps[].bnum points to the first block of the array. + * + * Before a submap can be played, it needs to be expanded from blocks + * to map_map. + */ + +#include "xrick/maps.h" + +#include "xrick/game.h" +#include "xrick/debug.h" +#include "xrick/control.h" +#include "xrick/ents.h" +#include "xrick/draw.h" +#include "xrick/screens.h" +#include "xrick/e_sbonus.h" + +/* + * global vars + */ +U8 map_map[0x2C][0x20]; + +size_t map_nbr_maps = 0; +map_t *map_maps = NULL; + +size_t map_nbr_submaps = 0; +submap_t *map_submaps = NULL; + +size_t map_nbr_connect = 0; +connect_t *map_connect = NULL; + +size_t map_nbr_blocks = 0; +block_t *map_blocks = NULL; + +size_t map_nbr_marks = 0; +mark_t *map_marks = NULL; + +size_t map_nbr_bnums = 0; +U8 *map_bnums = NULL; + +size_t map_nbr_eflgc = 0; +U8 *map_eflg_c = NULL; +U8 map_eflg[0x100]; + +U8 map_frow; +U8 map_tilesBank; + + +/* + * prototypes + */ +static void map_eflg_expand(U8); + + +/* + * Fill in map_map with tile numbers by expanding blocks. + * + * add map_submaps[].bnum to map_frow to find out where to start from. + * We need to /4 map_frow to convert from tile rows to block rows, then + * we need to *8 to convert from block rows to block numbers (there + * are 8 blocks per block row). This is achieved by *2 then &0xfff8. + */ +void +map_expand(void) +{ + U8 i, j, k, l; + U8 row, col; + U16 pbnum; + + pbnum = map_submaps[game_submap].bnum + ((2 * map_frow) & 0xfff8); + row = col = 0; + + for (i = 0; i < 0x0b; i++) { /* 0x0b rows of blocks */ + for (j = 0; j < 0x08; j++) { /* 0x08 blocks per row */ + for (k = 0, l = 0; k < 0x04; k++) { /* expand one block */ + map_map[row][col++] = map_blocks[map_bnums[pbnum]][l++]; + map_map[row][col++] = map_blocks[map_bnums[pbnum]][l++]; + map_map[row][col++] = map_blocks[map_bnums[pbnum]][l++]; + map_map[row][col] = map_blocks[map_bnums[pbnum]][l++]; + row += 1; col -= 3; + } + row -= 4; col += 4; + pbnum++; + } + row += 4; col = 0; + } +} + + +/* + * Initialize a new submap + * + * ASM 0cc3 + */ +void +map_init(void) +{ + /*sys_printf("xrick/map_init: map=%#04x submap=%#04x\n", g_map, game_submap);*/ +#ifdef GFXPC + draw_filter = 0xffff; + map_tilesBank = 2 + map_submaps[game_submap].page; +#endif +#ifdef GFXST + map_tilesBank = 1 + map_submaps[game_submap].page; +#endif + map_eflg_expand(map_submaps[game_submap].page << 4); + map_expand(); + ent_reset(); + ent_actvis(map_frow + MAP_ROW_SCRTOP, map_frow + MAP_ROW_SCRBOT); + ent_actvis(map_frow + MAP_ROW_HTTOP, map_frow + MAP_ROW_HTBOT); + ent_actvis(map_frow + MAP_ROW_HBTOP, map_frow + MAP_ROW_HBBOT); +} + + +/* + * Expand entity flags for this map + * + * ASM 1117 + */ +void +map_eflg_expand(U8 offs) +{ + U8 i, j, k; + + for (i = 0, k = 0; i < 0x10; i++) { + j = map_eflg_c[offs + i++]; + while (j--) map_eflg[k++] = map_eflg_c[offs + i]; + } +} + + +/* + * Chain (sub)maps + * + * ASM 0c08 + * return: true/next submap OK, false/map finished + */ +bool +map_chain(void) +{ + U16 c, t; + + game_chsm = false; + e_sbonus_counting = false; + + /* find connection */ + c = map_submaps[game_submap].connect; + t = 3; + + IFDEBUG_MAPS( + sys_printf("xrick/maps: chain submap=%#04x frow=%#04x .connect=%#04x %s\n", + game_submap, map_frow, c, + (game_dir == LEFT ? "-> left" : "-> right")); + ); + + /* + * look for the first connector with compatible row number. if none + * found, then panic + */ + for (c = map_submaps[game_submap].connect ; ; c++) + { + if (map_connect[c].dir == 0xff) + { + sys_error("(map_chain) can not find connector\n"); + control_set(Control_EXIT); + return false; + } + if (map_connect[c].dir != game_dir) + { + continue; + } + t = (ent_ents[1].y >> 3) + map_frow - map_connect[c].rowout; + if (t < 3) + { + break; + } + } + + /* got it */ + IFDEBUG_MAPS( + sys_printf("xrick/maps: chain frow=%#04x y=%#06x\n", + map_frow, ent_ents[1].y); + sys_printf("xrick/maps: chain connect=%#04x rowout=%#04x - ", + c, map_connect[c].rowout); + ); + + if (map_connect[c].submap == 0xff) + { + /* no next submap - request next map */ + IFDEBUG_MAPS( + sys_printf("chain to next map\n"); + ); + return false; + } + else + { + /* next submap */ + IFDEBUG_MAPS( + sys_printf("chain to submap=%#04x rowin=%#04x\n", + map_connect[c].submap, map_connect[c].rowin); + ); + map_frow = map_frow - map_connect[c].rowout + map_connect[c].rowin; + game_submap = map_connect[c].submap; + IFDEBUG_MAPS( + sys_printf("xrick/maps: chain frow=%#04x\n", + map_frow); + ); + return true; + } +} + + +/* + * Reset all marks, i.e. make them all active again. + * + * ASM 0025 + * + */ +void +map_resetMarks(void) +{ + U16 i; + for (i = 0; i < map_nbr_marks; i++) + map_marks[i].ent &= ~MAP_MARK_NACT; +} + + +/* eof */ diff --git a/apps/plugins/xrick/maps.h b/apps/plugins/xrick/maps.h new file mode 100644 index 0000000000..716c6589ad --- /dev/null +++ b/apps/plugins/xrick/maps.h @@ -0,0 +1,159 @@ +/* + * xrick/maps.h + * + * Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net). + * Copyright (C) 2008-2014 Pierluigi Vicinanza. + * All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#ifndef _MAPS_H +#define _MAPS_H + +#include "xrick/system/basic_types.h" +#include "xrick/system/system.h" +#ifdef ENABLE_SOUND +#include "xrick/data/sounds.h" +#endif + +#include /* size_t */ + +/* + * map row definitions, for three zones : hidden top, screen, hidden bottom + * the three zones compose map_map, which contains the definition of the + * current portion of the submap. + */ +#define MAP_ROW_HTTOP 0x00 +#define MAP_ROW_HTBOT 0x07 +#define MAP_ROW_SCRTOP 0x08 +#define MAP_ROW_SCRBOT 0x1F +#define MAP_ROW_HBTOP 0x20 +#define MAP_ROW_HBBOT 0x27 + +extern U8 map_map[0x2c][0x20]; + +/* + * main maps + */ +typedef struct { + U16 x, y; /* initial position for rick */ + U16 row; /* initial map_map top row within the submap */ + U16 submap; /* initial submap */ +#ifdef ENABLE_SOUND + sound_t * tune; /* map tune */ +#endif +} map_t; + +extern size_t map_nbr_maps; +extern map_t *map_maps; + +/* + * sub maps + */ +typedef struct { + U16 page; /* tiles page */ + U16 bnum; /* first block number */ + U16 connect; /* first connection */ + U16 mark; /* first entity mark */ +} submap_t; + +extern size_t map_nbr_submaps; +extern submap_t *map_submaps; + +/* + * connections + */ +typedef struct { + U8 dir; + U8 rowout; + U8 submap; + U8 rowin; +} connect_t; + +extern size_t map_nbr_connect; +extern connect_t *map_connect; + +/* + * blocks - one block is 4 by 4 tiles. + */ +typedef U8 block_t[0x10]; + +extern size_t map_nbr_blocks; +extern block_t *map_blocks; + +/* + * flags for map_marks[].ent ("yes" when set) + * + * MAP_MARK_NACT: this mark is not active anymore. + */ +#define MAP_MARK_NACT (0x80) + +/* + * mark structure + */ +typedef struct { + U8 row; + U8 ent; + U8 flags; + U8 xy; /* bits XXXX XYYY (from b03) with X->x, Y->y */ + U8 lt; /* bits XXXX XNNN (from b04) with X->trig_x, NNN->lat & trig_y */ +} mark_t; + +extern size_t map_nbr_marks; +extern mark_t *map_marks; + +/* + * block numbers, i.e. array of rows of 8 blocks + */ +extern size_t map_nbr_bnums; +extern U8 *map_bnums; + +/* + * flags for map_eflg[map_map[row][col]] ("yes" when set) + * + * MAP_EFLG_VERT: vertical move only (usually on top of _CLIMB). + * MAP_EFLG_SOLID: solid block, can't go through. + * MAP_EFLG_SPAD: super pad. can't go through, but sends entities to the sky. + * MAP_EFLG_WAYUP: solid block, can't go through except when going up. + * MAP_EFLG_FGND: foreground (hides entities). + * MAP_EFLG_LETHAL: lethal (kill entities). + * MAP_EFLG_CLIMB: entities can climb here. + * MAP_EFLG_01: + */ +#define MAP_EFLG_VERT (0x80) +#define MAP_EFLG_SOLID (0x40) +#define MAP_EFLG_SPAD (0x20) +#define MAP_EFLG_WAYUP (0x10) +#define MAP_EFLG_FGND (0x08) +#define MAP_EFLG_LETHAL (0x04) +#define MAP_EFLG_CLIMB (0x02) +#define MAP_EFLG_01 (0x01) + +extern size_t map_nbr_eflgc; +extern U8 *map_eflg_c; /* compressed */ +extern U8 map_eflg[0x100]; /* current */ + +/* + * map_map top row within the submap + */ +extern U8 map_frow; + +/* + * tiles offset + */ +extern U8 map_tilesBank; + +extern void map_expand(void); +extern void map_init(void); +extern bool map_chain(void); +extern void map_resetMarks(void); + +#endif /* ndef _MAPS_H */ + +/* eof */ diff --git a/apps/plugins/xrick/rects.c b/apps/plugins/xrick/rects.c new file mode 100644 index 0000000000..9324426060 --- /dev/null +++ b/apps/plugins/xrick/rects.c @@ -0,0 +1,57 @@ +/* + * xrick/rects.c + * + * Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net). + * Copyright (C) 2008-2014 Pierluigi Vicinanza. + * All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#include "xrick/rects.h" +#include "xrick/system/system.h" + +/* + * Free a list of rectangles and set the pointer to NULL. + * + * p: rectangle list CHANGED to NULL + */ +void +rects_free(rect_t *r) +{ + while (r) + { + rect_t * next = r->next; + sysmem_pop(r); + r = next; + } +} + + +/* + * Add a rectangle to a list of rectangles + */ +rect_t * +rects_new(U16 x, U16 y, U16 width, U16 height, rect_t *next) +{ + rect_t *r; + + r = sysmem_push(sizeof(*r)); + if (!r) + { + return NULL; + } + r->x = x; + r->y = y; + r->width = width; + r->height = height; + r->next = next; + return r; +} + +/* eof */ diff --git a/apps/plugins/xrick/rects.h b/apps/plugins/xrick/rects.h new file mode 100644 index 0000000000..ed75f609aa --- /dev/null +++ b/apps/plugins/xrick/rects.h @@ -0,0 +1,32 @@ +/* + * xrick/rects.h + * + * Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net). + * Copyright (C) 2008-2014 Pierluigi Vicinanza. + * All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#ifndef _RECTS_H +#define _RECTS_H + +#include "xrick/system/basic_types.h" + +typedef struct rect_s { + U16 x, y; + U16 width, height; + struct rect_s *next; +} rect_t; + +extern void rects_free(rect_t *); +extern rect_t *rects_new(U16, U16, U16, U16, rect_t *); + +#endif /* ndef _RECTS_H */ + +/* eof */ diff --git a/apps/plugins/xrick/res_magic.c b/apps/plugins/xrick/res_magic.c new file mode 100644 index 0000000000..c3365bc816 --- /dev/null +++ b/apps/plugins/xrick/res_magic.c @@ -0,0 +1,18 @@ +/* + * xrick/res_magic.c + * + * Copyright (C) 2008-2014 Pierluigi Vicinanza. All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#include "xrick/resources.h" + +const U8 resource_magic[4] = { 0x52, 0x49, 0x43, 0x4B }; /* 'R','I','C','K' */ + +/* eof */ diff --git a/apps/plugins/xrick/resources.c b/apps/plugins/xrick/resources.c new file mode 100644 index 0000000000..d7b49e8f73 --- /dev/null +++ b/apps/plugins/xrick/resources.c @@ -0,0 +1,1297 @@ +/* + * xrick/resources.c + * + * Copyright (C) 2008-2014 Pierluigi Vicinanza. All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#include "xrick/resources.h" + +#include "xrick/draw.h" +#include "xrick/ents.h" +#include "xrick/maps.h" +#include "xrick/util.h" +#include "xrick/data/sprites.h" +#include "xrick/data/tiles.h" +#include "xrick/data/pics.h" +#include "xrick/system/basic_funcs.h" + +#include "xrick/system/miniz_config.h" +#include "miniz/miniz.c" + +/* + * prototypes + */ +static bool readFile(const unsigned id); +static bool checkCrc32(const unsigned id); +static bool readHeader(file_t fp, const unsigned id); +static bool loadString(file_t fp, char ** str, const char terminator); +static void unloadString(char ** buffer); +static bool loadResourceFilelist(file_t fp); +static void unloadResourceFilelist(void); +static bool loadResourceEntdata(file_t fp); +static void unloadResourceEntdata(void); +static bool loadRawData(file_t fp, void ** buffer, const size_t size, size_t * count); +static void unloadRawData(void ** buffer, size_t * count); +static bool loadResourceMaps(file_t fp); +static void unloadResourceMaps(void); +static bool loadResourceSubmaps(file_t fp); +static void unloadResourceSubmaps(void); +static bool loadResourceImapsteps(file_t fp); +static void unloadResourceImapsteps(void); +static bool loadResourceImaptext(file_t fp); +static void unloadResourceImaptext(void); +static bool loadResourceHighScores(file_t fp); +static void unloadResourceHighScores(void); +static bool loadResourceSpritesData(file_t fp); +static void unloadResourceSpritesData(void); +static bool loadResourceTilesData(file_t fp); +static void unloadResourceTilesData(void); +static bool loadImage(file_t fp, img_t ** image); +static void unloadImage(img_t ** image); +#ifdef GFXST +static bool loadPicture(file_t fp, pic_t ** picture); +static void unloadPicture(pic_t ** picture); +#endif /* GFXST */ +#ifdef ENABLE_SOUND +static bool fromResourceIdToSound(const unsigned id, sound_t *** sound); +static bool loadSound(const unsigned id); +static void unloadSound(const unsigned id); +#endif /* ENABLE_SOUND */ + +/* + * local vars + */ +static char * resourceFiles[Resource_MAX_COUNT] = +{ + BOOTSTRAP_RESOURCE_NAME, + /* the rest initialised to NULL by default */ +}; + +/* + * load 16b length + not-terminated string + */ +static bool loadString(file_t fp, char ** buffer, const char terminator) +{ + size_t length; + U16 u16Temp; + char * bufferTemp; + + if (sysfile_read(fp, &u16Temp, sizeof(u16Temp), 1) != 1) + { + return false; + } + length = letoh16(u16Temp); + + bufferTemp = sysmem_push(length + 1); + *buffer = bufferTemp; + if (!bufferTemp) + { + return false; + } + + if (length) + { + if (sysfile_read(fp, bufferTemp, length, 1) != 1) + { + return false; + } + } + + bufferTemp[length] = terminator; + + return true; +} + +/* + * + */ +static void unloadString(char ** buffer) +{ + sysmem_pop(*buffer); + *buffer = NULL; +} + +/* + * + */ +static bool loadResourceFilelist(file_t fp) +{ + unsigned id; + + for (id = Resource_PALETTE; id < Resource_MAX_COUNT; ++id) + { + if (!loadString(fp, &(resourceFiles[id]), 0x00)) + { + return false; + } + } + return true; +} + +/* + * + */ +static void unloadResourceFilelist() +{ + unsigned id; + + for (id = Resource_MAX_COUNT - 1; id >= Resource_PALETTE; --id) + { + unloadString(&(resourceFiles[id])); + } +} + +/* + * + */ +static bool loadResourceEntdata(file_t fp) +{ + size_t i; + U16 u16Temp; + resource_entdata_t dataTemp; + + if (sysfile_read(fp, &u16Temp, sizeof(u16Temp), 1) != 1) + { + return false; + } + ent_nbr_entdata = letoh16(u16Temp); + + ent_entdata = sysmem_push(ent_nbr_entdata * sizeof(*ent_entdata)); + if (!ent_entdata) + { + return false; + } + + for (i = 0; i < ent_nbr_entdata; ++i) + { + if (sysfile_read(fp, &dataTemp, sizeof(dataTemp), 1) != 1) + { + return false; + } + ent_entdata[i].w = dataTemp.w; + ent_entdata[i].h = dataTemp.h; + memcpy(&u16Temp, dataTemp.spr, sizeof(U16)); + ent_entdata[i].spr = letoh16(u16Temp); + memcpy(&u16Temp, dataTemp.sni, sizeof(U16)); + ent_entdata[i].sni = letoh16(u16Temp); + ent_entdata[i].trig_w = dataTemp.trig_w; + ent_entdata[i].trig_h = dataTemp.trig_h; + ent_entdata[i].snd = dataTemp.snd; + } + return true; +} + +/* + * + */ +static void unloadResourceEntdata() +{ + sysmem_pop(ent_entdata); + ent_entdata = NULL; + ent_nbr_entdata = 0; +} + +/* + * + */ +static bool loadRawData(file_t fp, void ** buffer, const size_t size, size_t * count) +{ + U16 u16Temp; + if (sysfile_read(fp, &u16Temp, sizeof(u16Temp), 1) != 1) + { + return false; + } + *count = letoh16(u16Temp); + + *buffer = sysmem_push((*count) * size); + if (!(*buffer)) + { + return false; + } + + if (sysfile_read(fp, *buffer, size, *count) != (int)(*count)) + { + return false; + } + return true; +} + +/* + * + */ +static void unloadRawData(void ** buffer, size_t * count) +{ + sysmem_pop(*buffer); + *buffer = NULL; + *count = 0; +} + +/* + * + */ +static bool loadResourceMaps(file_t fp) +{ + size_t i; + U16 u16Temp; + resource_map_t dataTemp; + + if (sysfile_read(fp, &u16Temp, sizeof(u16Temp), 1) != 1) + { + return false; + } + map_nbr_maps = letoh16(u16Temp); + + map_maps = sysmem_push(map_nbr_maps * sizeof(*map_maps)); + if (!map_maps) + { + return false; + } + + for (i = 0; i < map_nbr_maps; ++i) + { +#ifdef ENABLE_SOUND + sound_t **soundTemp; +#endif + if (sysfile_read(fp, &dataTemp, sizeof(dataTemp), 1) != 1) + { + return false; + } + memcpy(&u16Temp, dataTemp.x, sizeof(U16)); + map_maps[i].x = letoh16(u16Temp); + memcpy(&u16Temp, dataTemp.y, sizeof(U16)); + map_maps[i].y = letoh16(u16Temp); + memcpy(&u16Temp, dataTemp.row, sizeof(U16)); + map_maps[i].row = letoh16(u16Temp); + memcpy(&u16Temp, dataTemp.submap, sizeof(U16)); + map_maps[i].submap = letoh16(u16Temp); +#ifdef ENABLE_SOUND + memcpy(&u16Temp, dataTemp.tuneId, sizeof(U16)); + if (!fromResourceIdToSound(letoh16(u16Temp), &soundTemp)) + { + return false; + } + map_maps[i].tune = *soundTemp; +#endif /* ENABLE_SOUND */ + } + return true; +} + +/* + * + */ +static void unloadResourceMaps() +{ + sysmem_pop(map_maps); + map_maps = NULL; + map_nbr_maps = 0; +} + +/* + * + */ +static bool loadResourceSubmaps(file_t fp) +{ + size_t i; + U16 u16Temp; + resource_submap_t dataTemp; + + if (sysfile_read(fp, &u16Temp, sizeof(u16Temp), 1) != 1) + { + return false; + } + map_nbr_submaps = letoh16(u16Temp); + + map_submaps = sysmem_push(map_nbr_submaps * sizeof(*map_submaps)); + if (!map_submaps) + { + return false; + } + + for (i = 0; i < map_nbr_submaps; ++i) + { + if (sysfile_read(fp, &dataTemp, sizeof(dataTemp), 1) != 1) + { + return false; + } + memcpy(&u16Temp, dataTemp.page, sizeof(U16)); + map_submaps[i].page = letoh16(u16Temp); + memcpy(&u16Temp, dataTemp.bnum, sizeof(U16)); + map_submaps[i].bnum = letoh16(u16Temp); + memcpy(&u16Temp, dataTemp.connect, sizeof(U16)); + map_submaps[i].connect = letoh16(u16Temp); + memcpy(&u16Temp, dataTemp.mark, sizeof(U16)); + map_submaps[i].mark = letoh16(u16Temp); + } + return true; +} + +/* + * + */ +static void unloadResourceSubmaps() +{ + sysmem_pop(map_submaps); + map_submaps = NULL; + map_nbr_submaps = 0; +} + +/* + * + */ +static bool loadResourceImapsteps(file_t fp) +{ + size_t i; + U16 u16Temp; + resource_imapsteps_t dataTemp; + + if (sysfile_read(fp, &u16Temp, sizeof(u16Temp), 1) != 1) + { + return false; + } + screen_nbr_imapstesps = letoh16(u16Temp); + + screen_imapsteps = sysmem_push(screen_nbr_imapstesps * sizeof(*screen_imapsteps)); + if (!screen_imapsteps) + { + return false; + } + + for (i = 0; i < screen_nbr_imapstesps; ++i) + { + if (sysfile_read(fp, &dataTemp, sizeof(dataTemp), 1) != 1) + { + return false; + } + memcpy(&u16Temp, dataTemp.count, sizeof(U16)); + screen_imapsteps[i].count = letoh16(u16Temp); + memcpy(&u16Temp, dataTemp.dx, sizeof(U16)); + screen_imapsteps[i].dx = letoh16(u16Temp); + memcpy(&u16Temp, dataTemp.dy, sizeof(U16)); + screen_imapsteps[i].dy = letoh16(u16Temp); + memcpy(&u16Temp, dataTemp.base, sizeof(U16)); + screen_imapsteps[i].base = letoh16(u16Temp); + } + return true; +} + +/* + * + */ +static void unloadResourceImapsteps() +{ + sysmem_pop(screen_imapsteps); + screen_imapsteps = NULL; + screen_nbr_imapstesps = 0; +} + +/* + * + */ +static bool loadResourceImaptext(file_t fp) +{ + size_t i; + U16 u16Temp; + + if (sysfile_read(fp, &u16Temp, sizeof(u16Temp), 1) != 1) + { + return false; + } + screen_nbr_imaptext = letoh16(u16Temp); + + screen_imaptext = sysmem_push(screen_nbr_imaptext * sizeof(*screen_imaptext)); + if (!screen_imapsteps) + { + return false; + } + + for (i = 0; i < screen_nbr_imaptext; ++i) + { + if (!loadString(fp, (char **)(&(screen_imaptext[i])), 0xFE)) + { + return false; + } + } + return true; +} + +/* + * + */ +static void unloadResourceImaptext() +{ + int i; + + for (i = screen_nbr_imaptext - 1; i >= 0; --i) + { + unloadString((char **)(&(screen_imaptext[i]))); + } + + sysmem_pop(screen_imaptext); + screen_imaptext = NULL; + screen_nbr_imaptext = 0; +} + +/* + * + */ +static bool loadResourceHighScores(file_t fp) +{ + size_t i; + U16 u16Temp; + U32 u32Temp; + resource_hiscore_t dataTemp; + + if (sysfile_read(fp, &u16Temp, sizeof(u16Temp), 1) != 1) + { + return false; + } + screen_nbr_hiscores = letoh16(u16Temp); + + screen_highScores = sysmem_push(screen_nbr_hiscores * sizeof(*screen_highScores)); + if (!screen_highScores) + { + return false; + } + + for (i = 0; i < screen_nbr_hiscores; ++i) + { + if (sysfile_read(fp, &dataTemp, sizeof(dataTemp), 1) != 1) + { + return false; + } + memcpy(&u32Temp, dataTemp.score, sizeof(U32)); + screen_highScores[i].score = letoh32(u32Temp); + memcpy(screen_highScores[i].name, dataTemp.name, HISCORE_NAME_SIZE); + } + return true; +} + +/* + * + */ +static void unloadResourceHighScores() +{ + sysmem_pop(screen_highScores); + screen_highScores = NULL; + screen_nbr_hiscores = 0; +} + +/* + * + */ +static bool loadResourceSpritesData(file_t fp) +{ + size_t i, j; + U16 u16Temp; + + if (sysfile_read(fp, &u16Temp, sizeof(u16Temp), 1) != 1) + { + return false; + } + sprites_nbr_sprites = letoh16(u16Temp); + + sprites_data = sysmem_push(sprites_nbr_sprites * sizeof(*sprites_data)); + if (!sprites_data) + { + return false; + } + +#ifdef GFXST + for (i = 0; i < sprites_nbr_sprites; ++i) + { + for (j = 0; j < SPRITES_NBR_DATA; ++j) + { + U32 u32Temp; + if (sysfile_read(fp, &u32Temp, sizeof(u32Temp), 1) != 1) + { + return false; + } + sprites_data[i][j] = letoh32(u32Temp); + } + } +#endif /* GFXST */ + +#ifdef GFXPC + for (i = 0; i < sprites_nbr_sprites; ++i) + { + for (j = 0; j < SPRITES_NBR_COLS; ++j) + { + size_t k; + for (k = 0; k < SPRITES_NBR_ROWS; ++k) + { + resource_spriteX_t dataTemp; + if (sysfile_read(fp, &dataTemp, sizeof(dataTemp), 1) != 1) + { + return false; + } + memcpy(&u16Temp, dataTemp.mask, sizeof(U16)); + sprites_data[i][j][k].mask = letoh16(u16Temp); + memcpy(&u16Temp, dataTemp.pict, sizeof(U16)); + sprites_data[i][j][k].pict = letoh16(u16Temp); + } + } + } +#endif /* GFXPC */ + + return true; +} + +/* + * + */ +static void unloadResourceSpritesData() +{ + sysmem_pop(sprites_data); + sprites_data = NULL; + sprites_nbr_sprites = 0; +} + +/* + * + */ +static bool loadResourceTilesData(file_t fp) +{ + size_t i, j, k; + U16 u16Temp; + + if (sysfile_read(fp, &u16Temp, sizeof(u16Temp), 1) != 1) + { + return false; + } + tiles_nbr_banks = letoh16(u16Temp); + + tiles_data = sysmem_push(tiles_nbr_banks * TILES_NBR_TILES * sizeof(*tiles_data)); + if (!tiles_data) + { + return false; + } + + for (i = 0; i < tiles_nbr_banks ; ++i) + { + for (j = 0; j < TILES_NBR_TILES; ++j) + { + for (k = 0; k < TILES_NBR_LINES ; ++k) + { +#ifdef GFXPC + if (sysfile_read(fp, &u16Temp, sizeof(u16Temp), 1) != 1) + { + return false; + } + tiles_data[i * TILES_NBR_TILES + j][k] = letoh16(u16Temp); +#endif /* GFXPC */ +#ifdef GFXST + U32 u32Temp; + if (sysfile_read(fp, &u32Temp, sizeof(u32Temp), 1) != 1) + { + return false; + } + tiles_data[i * TILES_NBR_TILES + j][k] = letoh32(u32Temp); +#endif /* GFXST */ + } + } + } + return true; +} + +/* + * + */ +static void unloadResourceTilesData() +{ + sysmem_pop(tiles_data); + tiles_data = NULL; + tiles_nbr_banks = 0; +} + +/* + * + */ +static bool loadImage(file_t fp, img_t ** image) +{ + U16 u16Temp; + size_t pixelCount, colorCount; + resource_pic_t dataTemp; + img_t * imgTemp; + void * vp; + bool success; + + imgTemp = sysmem_push(sizeof(*imgTemp)); + *image = imgTemp; + if (!imgTemp) + { + return false; + } + + if (sysfile_read(fp, &dataTemp, sizeof(dataTemp), 1) != 1) + { + return false; + } + memcpy(&u16Temp, dataTemp.width, sizeof(U16)); + imgTemp->width = letoh16(u16Temp); + memcpy(&u16Temp, dataTemp.height, sizeof(U16)); + imgTemp->height = letoh16(u16Temp); + memcpy(&u16Temp, dataTemp.xPos, sizeof(U16)); + imgTemp->xPos = letoh16(u16Temp); + memcpy(&u16Temp, dataTemp.yPos, sizeof(U16)); + imgTemp->yPos = letoh16(u16Temp); + + vp = imgTemp->colors; + success = loadRawData(fp, &vp, sizeof(*imgTemp->colors), &colorCount); + imgTemp->ncolors = colorCount; + imgTemp->colors = vp; + if (!success) + { + return false; + } + + pixelCount = (imgTemp->width * imgTemp->height); /*we use 8b per pixel*/ + + imgTemp->pixels = sysmem_push(pixelCount * sizeof(U8)); + if (!imgTemp->pixels) + { + return false; + } + + if (sysfile_read(fp, imgTemp->pixels, sizeof(U8), pixelCount) != (int)pixelCount) + { + return false; + } + return true; +} + +/* + * + */ +static void unloadImage(img_t ** image) +{ + if (*image) + { + sysmem_pop((*image)->pixels); + sysmem_pop((*image)->colors); + } + sysmem_pop(*image); + *image = NULL; +} + +/* + * + */ +#ifdef GFXST +static bool loadPicture(file_t fp, pic_t ** picture) +{ + U16 u16Temp; + size_t i, pixelWords32b; + resource_pic_t dataTemp; + pic_t * picTemp; + + picTemp = sysmem_push(sizeof(*picTemp)); + *picture = picTemp; + if (!picTemp) + { + return false; + } + + if (sysfile_read(fp, &dataTemp, sizeof(dataTemp), 1) != 1) + { + return false; + } + memcpy(&u16Temp, dataTemp.width, sizeof(U16)); + picTemp->width = letoh16(u16Temp); + memcpy(&u16Temp, dataTemp.height, sizeof(U16)); + picTemp->height = letoh16(u16Temp); + memcpy(&u16Temp, dataTemp.xPos, sizeof(U16)); + picTemp->xPos = letoh16(u16Temp); + memcpy(&u16Temp, dataTemp.yPos, sizeof(U16)); + picTemp->yPos = letoh16(u16Temp); + + pixelWords32b = (picTemp->width * picTemp->height) / 8; /*we use 4b per pixel*/ + + picTemp->pixels = sysmem_push(pixelWords32b * sizeof(U32)); + if (!picTemp->pixels) + { + return false; + } + + for (i = 0; i < pixelWords32b; ++i) + { + U32 u32Temp; + if (sysfile_read(fp, &u32Temp, sizeof(u32Temp), 1) != 1) + { + return false; + } + picTemp->pixels[i] = letoh32(u32Temp); + } + return true; +} + +/* + * + */ +static void unloadPicture(pic_t ** picture) +{ + if (*picture) + { + sysmem_pop((*picture)->pixels); + } + sysmem_pop(*picture); + *picture = NULL; +} +#endif /* GFXST */ + +#ifdef ENABLE_SOUND + +/* + * + */ +static bool fromResourceIdToSound(const unsigned id, sound_t *** sound) +{ + switch (id) + { + case Resource_SOUNDBOMBSHHT: *sound = &soundBombshht; return true; + case Resource_SOUNDBONUS: *sound = &soundBonus; return true; + case Resource_SOUNDBOX: *sound = &soundBox; return true; + case Resource_SOUNDBULLET: *sound = &soundBullet; return true; + case Resource_SOUNDCRAWL: *sound = &soundCrawl; return true; + case Resource_SOUNDDIE: *sound = &soundDie; return true; + case Resource_SOUNDENTITY0: *sound = &(soundEntity[0]); return true; + case Resource_SOUNDENTITY1: *sound = &(soundEntity[1]); return true; + case Resource_SOUNDENTITY2: *sound = &(soundEntity[2]); return true; + case Resource_SOUNDENTITY3: *sound = &(soundEntity[3]); return true; + case Resource_SOUNDENTITY4: *sound = &(soundEntity[4]); return true; + case Resource_SOUNDENTITY5: *sound = &(soundEntity[5]); return true; + case Resource_SOUNDENTITY6: *sound = &(soundEntity[6]); return true; + case Resource_SOUNDENTITY7: *sound = &(soundEntity[7]); return true; + case Resource_SOUNDENTITY8: *sound = &(soundEntity[8]); return true; + case Resource_SOUNDEXPLODE: *sound = &soundExplode; return true; + case Resource_SOUNDGAMEOVER: *sound = &soundGameover; return true; + case Resource_SOUNDJUMP: *sound = &soundJump; return true; + case Resource_SOUNDPAD: *sound = &soundPad; return true; + case Resource_SOUNDSBONUS1: *sound = &soundSbonus1; return true; + case Resource_SOUNDSBONUS2: *sound = &soundSbonus2; return true; + case Resource_SOUNDSTICK: *sound = &soundStick; return true; + case Resource_SOUNDTUNE0: *sound = &soundTune0; return true; + case Resource_SOUNDTUNE1: *sound = &soundTune1; return true; + case Resource_SOUNDTUNE2: *sound = &soundTune2; return true; + case Resource_SOUNDTUNE3: *sound = &soundTune3; return true; + case Resource_SOUNDTUNE4: *sound = &soundTune4; return true; + case Resource_SOUNDTUNE5: *sound = &soundTune5; return true; + case Resource_SOUNDWALK: *sound = &soundWalk; return true; + default: + { + sys_error("(resources) no associated sound found for ID %d", id); + return false; + } + } +} + +/* + * + */ +static bool loadSound(const unsigned id) +{ + sound_t ** sound; + file_t fp; + wave_header_t header; + U16 u16Temp; + U32 u32Temp; + int bytesRead; + bool isHeaderValid; + + if (!fromResourceIdToSound(id, &sound)) + { + return false; + } + + *sound = sysmem_push(sizeof(**sound)); + if (!*sound) + { + return false; + } + + (*sound)->buf = NULL; + (*sound)->dispose = true; /* sounds are "fire and forget" by default */ + + (*sound)->name = u_strdup(resourceFiles[id]); + if (!(*sound)->name) + { + return false; + } + + fp = sysfile_open(resourceFiles[id]); + if (!fp) + { + sys_error("(resources) unable to open \"%s\"", resourceFiles[id]); + return false; + } + + bytesRead = sysfile_read(fp, &header, sizeof(header), 1); + sysfile_close(fp); + if (bytesRead != 1) + { + sys_error("(resources) unable to read WAVE header from \"%s\"", resourceFiles[id]); + return false; + } + + isHeaderValid = false; + for (;;) + { + if (memcmp(header.riffChunkId, "RIFF", 4) || + memcmp(header.riffType, "WAVE", 4) || + memcmp(header.formatChunkId, "fmt ", 4) || + memcmp(header.dataChunkId, "data", 4)) + { + break; + } + memcpy(&u16Temp, header.audioFormat, sizeof(u16Temp)); + if (letoh16(u16Temp) != Wave_AUDIO_FORMAT) + { + break; + } + memcpy(&u16Temp, header.channelCount, sizeof(u16Temp)); + if (letoh16(u16Temp) != Wave_CHANNEL_COUNT) + { + break; + } + memcpy(&u32Temp, header.sampleRate, sizeof(u32Temp)); + if (letoh32(u32Temp) != Wave_SAMPLE_RATE) + { + isHeaderValid = false; + break; + } + memcpy(&u16Temp, header.bitsPerSample, sizeof(u16Temp)); + if (letoh16(u16Temp) != Wave_BITS_PER_SAMPLE) + { + isHeaderValid = false; + break; + } + + memcpy(&u32Temp, header.dataChunkSize, sizeof(u32Temp)); + (*sound)->len = letoh32(u32Temp); + + isHeaderValid = true; + break; + } + if (!isHeaderValid) + { + sys_error("(resources) incompatible WAVE header for \"%s\"", resourceFiles[id]); + return false; + } + return true; +} + +/* + * + */ +static void unloadSound(const unsigned id) +{ + sound_t ** sound; + + if (!fromResourceIdToSound(id, &sound)) + { + return; + } + + if (!*sound) + { + return; + } + + sysmem_pop((*sound)->name); + sysmem_pop(*sound); + *sound = NULL; +} +#endif /* ENABLE_SOUND */ + + +/* + * + */ +static bool readHeader(file_t fp, const unsigned id) +{ + resource_header_t header; + U16 u16Temp; + + if (sysfile_read(fp, &header, sizeof(header), 1) != 1) + { + sys_error("(resources) unable to read header from \"%s\"", resourceFiles[id]); + return false; + } + + if (memcmp(header.magic, resource_magic, sizeof(header.magic)) != 0) + { + sys_error("(resources) wrong header for \"%s\"", resourceFiles[id]); + return false; + } + + memcpy(&u16Temp, header.version, sizeof(u16Temp)); + u16Temp = htole16(u16Temp); + if (u16Temp != DATA_VERSION) + { + sys_error("(resources) incompatible version for \"%s\"", resourceFiles[id]); + return false; + } + + memcpy(&u16Temp, header.resourceId, sizeof(u16Temp)); + u16Temp = htole16(u16Temp); + if (u16Temp != id) + { + sys_error("(resources) mismatching ID for \"%s\"", resourceFiles[id]); + return false; + } + return true; +} + +/* + * + */ +static bool checkCrc32(const unsigned id) +{ + int bytesRead; + U8 tempBuffer[1024]; + U32 expectedCrc32, calculatedCrc32 = MZ_CRC32_INIT; + + file_t fp = sysfile_open(resourceFiles[id]); + if (fp == NULL) + { + sys_error("(resources) unable to open \"%s\"", resourceFiles[id]); + return false; + } + + bytesRead = sysfile_read(fp, tempBuffer, sizeof(U32), 1); /* prepare beginning of buffer for the following loop */ + if (bytesRead != 1) + { + sys_error("(resources) not enough data for \"%s\"", resourceFiles[id]); + sysfile_close(fp); + return false; + } + do + { + bytesRead = sysfile_read(fp, tempBuffer + sizeof(U32), sizeof(U8), sizeof(tempBuffer) - sizeof(U32)); + + calculatedCrc32 = mz_crc32(calculatedCrc32, tempBuffer, bytesRead); + + memcpy(tempBuffer, tempBuffer + bytesRead, sizeof(U32)); + } while (bytesRead == sizeof(tempBuffer) - sizeof(U32)); + + sysfile_close(fp); + + memcpy(&expectedCrc32, tempBuffer, sizeof(U32)); + expectedCrc32 = letoh32(expectedCrc32); + if (expectedCrc32 != calculatedCrc32) + { + sys_error("(resources) crc check failed for \"%s\"", resourceFiles[id]); + return false; + } + return true; +} + +/* + * + */ +static bool readFile(const unsigned id) +{ + bool success; + file_t fp; + void * vp; + + switch (id) + { +#ifndef GFXST + case Resource_PICHAF: /* fallthrough */ + case Resource_PICCONGRATS: /* fallthrough */ + case Resource_PICSPLASH: return true; +#endif /* ndef GFXST */ +#ifndef GFXPC + case Resource_IMAINHOFT: /* fallthrough */ + case Resource_IMAINRDT: /* fallthrough */ + case Resource_IMAINCDC: /* fallthrough */ + case Resource_SCREENCONGRATS: return true; +#endif /* ndef GFXPC */ + default: break; + } + + if (resourceFiles[id] == NULL) + { + sys_error("(resources) resource ID %d not available", id); + return false; + } + + if (!checkCrc32(id)) + { + return false; + } + + fp = sysfile_open(resourceFiles[id]); + if (fp == NULL) + { + if (id == Resource_FILELIST) + sys_error("Please install resource files!"); + else + sys_error("(resources) unable to open \"%s\"", resourceFiles[id]); + return false; + } + + success = readHeader(fp, id); + + if (success) + { + switch (id) + { + case Resource_FILELIST: success = loadResourceFilelist(fp); break; + case Resource_PALETTE: + { + vp = game_colors; + success = loadRawData(fp, &vp, sizeof(*game_colors), &game_color_count); + game_colors = vp; + break; + } + case Resource_ENTDATA: success = loadResourceEntdata(fp); break; + case Resource_SPRSEQ: + { + vp = ent_sprseq; + success = loadRawData(fp, &vp, sizeof(*ent_sprseq), &ent_nbr_sprseq); + ent_sprseq = vp; + break; + } + case Resource_MVSTEP: + { + vp = ent_mvstep; + success = loadRawData(fp, &vp, sizeof(*ent_mvstep), &ent_nbr_mvstep); + ent_mvstep = vp; + break; + } + case Resource_MAPS: success = loadResourceMaps(fp); break; + case Resource_SUBMAPS: success = loadResourceSubmaps(fp); break; + case Resource_CONNECT: + { + vp = map_connect; + success = loadRawData(fp, &vp, sizeof(*map_connect), &map_nbr_connect); + map_connect = vp; + break; + } + case Resource_BNUMS: + { + vp = map_bnums; + success = loadRawData(fp, &vp, sizeof(*map_bnums), &map_nbr_bnums); + map_bnums = vp; + break; + } + case Resource_BLOCKS: + { + vp = map_blocks; + success = loadRawData(fp, &vp, sizeof(*map_blocks), &map_nbr_blocks); + map_blocks = vp; + break; + } + case Resource_MARKS: + { + vp = map_marks; + success = loadRawData(fp, &vp, sizeof(*map_marks), &map_nbr_marks); + map_marks = vp; + break; + } + case Resource_EFLGC: + { + vp = map_eflg_c; + success = loadRawData(fp, &vp, sizeof(*map_eflg_c), &map_nbr_eflgc); + map_eflg_c = vp; + break; + } + case Resource_IMAPSL: + { + vp = screen_imapsl; + success = loadRawData(fp, &vp, sizeof(*screen_imapsl), &screen_nbr_imapsl); + screen_imapsl = vp; + break; + } + case Resource_IMAPSTEPS: success = loadResourceImapsteps(fp); break; + case Resource_IMAPSOFS: + { + vp = screen_imapsofs; + success = loadRawData(fp, &vp, sizeof(*screen_imapsofs), &screen_nbr_imapsofs); + screen_imapsofs = vp; + break; + } + case Resource_IMAPTEXT: success = loadResourceImaptext(fp); break; + case Resource_GAMEOVERTXT: success = loadString(fp, (char **)(&screen_gameovertxt), 0xFE); break; + case Resource_PAUSEDTXT: success = loadString(fp, (char **)(&screen_pausedtxt), 0xFE); break; + case Resource_SPRITESDATA: success = loadResourceSpritesData(fp); break; + case Resource_TILESDATA: success = loadResourceTilesData(fp); break; + case Resource_HIGHSCORES: success = loadResourceHighScores(fp); break; + case Resource_IMGSPLASH: success = loadImage(fp, &img_splash); break; +#ifdef GFXST + case Resource_PICHAF: success = loadPicture(fp, &pic_haf); break; + case Resource_PICCONGRATS: success = loadPicture(fp, &pic_congrats); break; + case Resource_PICSPLASH: success = loadPicture(fp, &pic_splash); break; +#endif /* GFXST */ +#ifdef GFXPC + case Resource_IMAINHOFT: success = loadString(fp, (char **)(&screen_imainhoft), 0xFE); break; + case Resource_IMAINRDT: success = loadString(fp, (char **)(&screen_imainrdt), 0xFE); break; + case Resource_IMAINCDC: success = loadString(fp, (char **)(&screen_imaincdc), 0xFE); break; + case Resource_SCREENCONGRATS: success = loadString(fp, (char **)(&screen_congrats), 0xFE); break; +#endif /* GFXPC */ + default: success = false; break; + } + } + + if (!success) + { + sys_error("(resources) error when parsing \"%s\"", resourceFiles[id]); + } + + sysfile_close(fp); + return success; +} + +/* + * + */ +bool resources_load() +{ + bool success; + unsigned id; + + /* note: loading order is important: file list first, then sounds, then the rest */ + + success = readFile(Resource_FILELIST); + +#ifdef ENABLE_SOUND + for (id = Resource_SOUNDBOMBSHHT; (id <= Resource_SOUNDWALK) && success; ++id) + { + success = loadSound(id); + } +#endif /* ENABLE_SOUND */ + + for (id = Resource_PALETTE; (id <= Resource_SCREENCONGRATS) && success; ++id) + { + success = readFile(id); + } + return success; +} + +/* + * + */ +void resources_unload() +{ + int id; + void * vp; + + for (id = Resource_SCREENCONGRATS; id >= Resource_PALETTE; --id) + { + switch (id) + { + case Resource_PALETTE: + { + vp = game_colors; + unloadRawData(&vp, &game_color_count); + game_colors = vp; + break; + } + case Resource_ENTDATA: unloadResourceEntdata(); break; + case Resource_SPRSEQ: + { + vp = ent_sprseq; + unloadRawData(&vp, &ent_nbr_sprseq); + ent_sprseq = vp; + break; + } + case Resource_MVSTEP: + { + vp = ent_mvstep; + unloadRawData(&vp, &ent_nbr_mvstep); + ent_mvstep = vp; + break; + } + case Resource_MAPS: unloadResourceMaps(); break; + case Resource_SUBMAPS: unloadResourceSubmaps(); break; + case Resource_CONNECT: + { + vp = map_connect; + unloadRawData(&vp, &map_nbr_connect); + map_connect = vp; + break; + } + case Resource_BNUMS: + { + vp = map_bnums; + unloadRawData(&vp, &map_nbr_bnums); + map_bnums = vp; + break; + } + case Resource_BLOCKS: + { + vp = map_blocks; + unloadRawData(&vp, &map_nbr_blocks); + map_blocks = vp; + break; + } + case Resource_MARKS: + { + vp = map_marks; + unloadRawData(&vp, &map_nbr_marks); + map_marks = vp; + break; + } + case Resource_EFLGC: + { + vp = map_eflg_c; + unloadRawData(&vp, &map_nbr_eflgc); + map_eflg_c = vp; + break; + } + case Resource_IMAPSL: + { + vp = screen_imapsl; + unloadRawData(&vp, &screen_nbr_imapsl); + screen_imapsl = vp; + break; + } + case Resource_IMAPSTEPS: unloadResourceImapsteps(); break; + case Resource_IMAPSOFS: + { + vp = screen_imapsofs; + unloadRawData(&vp, &screen_nbr_imapsofs); + screen_imapsofs = vp; + break; + } + case Resource_IMAPTEXT: unloadResourceImaptext(); break; + case Resource_GAMEOVERTXT: unloadString((char **)(&screen_gameovertxt)); break; + case Resource_PAUSEDTXT: unloadString((char **)(&screen_pausedtxt)); break; + case Resource_SPRITESDATA: unloadResourceSpritesData(); break; + case Resource_TILESDATA: unloadResourceTilesData(); break; + case Resource_HIGHSCORES: unloadResourceHighScores(); break; + case Resource_IMGSPLASH: unloadImage(&img_splash); break; +#ifdef GFXST + case Resource_PICHAF: unloadPicture(&pic_haf); break; + case Resource_PICCONGRATS: unloadPicture(&pic_congrats); break; + case Resource_PICSPLASH: unloadPicture(&pic_splash); break; +#endif /* GFXST */ +#ifdef GFXPC + case Resource_IMAINHOFT: unloadString((char **)(&screen_imainhoft)); break; + case Resource_IMAINRDT: unloadString((char **)(&screen_imainrdt)); break; + case Resource_IMAINCDC: unloadString((char **)(&screen_imaincdc)); break; + case Resource_SCREENCONGRATS: unloadString((char **)(&screen_congrats)); break; +#endif /* GFXPC */ + default: break; + } + } + +#ifdef ENABLE_SOUND + for (id = Resource_SOUNDWALK; id >= Resource_SOUNDBOMBSHHT; --id) + { + unloadSound(id); + } +#endif /* ENABLE_SOUND */ + + unloadResourceFilelist(); +} + +/* eof */ diff --git a/apps/plugins/xrick/resources.h b/apps/plugins/xrick/resources.h new file mode 100644 index 0000000000..e919ed081a --- /dev/null +++ b/apps/plugins/xrick/resources.h @@ -0,0 +1,165 @@ +/* + * xrick/resources.h + * + * Copyright (C) 2008-2014 Pierluigi Vicinanza. All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#ifndef _RESOURCES_H +#define _RESOURCES_H + +#include "xrick/config.h" +#include "xrick/screens.h" +#include "xrick/system/basic_types.h" + +/* + * All data is assumed to be Little Endian + */ +typedef struct +{ + U8 magic[4]; + U8 version[2]; + U8 resourceId[2]; +} resource_header_t; + +typedef struct +{ + U8 w; + U8 h; + U8 spr[2]; + U8 sni[2]; + U8 trig_w; + U8 trig_h; + U8 snd; +} resource_entdata_t; + +typedef struct +{ + U8 x[2]; + U8 y[2]; + U8 row[2]; + U8 submap[2]; + U8 tuneId[2]; +} resource_map_t; + +typedef struct +{ + U8 page[2]; + U8 bnum[2]; + U8 connect[2]; + U8 mark[2]; +} resource_submap_t; + +typedef struct { + U8 count[2]; + U8 dx[2]; + U8 dy[2]; + U8 base[2]; +} resource_imapsteps_t; + +typedef struct { + U8 width[2]; + U8 height[2]; + U8 xPos[2]; + U8 yPos[2]; +} resource_pic_t; + +typedef struct { + U8 score[4]; + U8 name[HISCORE_NAME_SIZE]; +} resource_hiscore_t; + +#ifdef GFXPC +typedef struct { + U8 mask[2]; + U8 pict[2]; +} resource_spriteX_t; +#endif /* GFXPC */ + +extern const U8 resource_magic[4]; + +enum +{ + DATA_VERSION = 3, + + /* "bootstrap" file */ + Resource_FILELIST = 0, + + /* graphics, misc, texts */ + Resource_PALETTE, + Resource_ENTDATA, + Resource_SPRSEQ, + Resource_MVSTEP, + Resource_MAPS, + Resource_SUBMAPS, + Resource_CONNECT, + Resource_BNUMS, + Resource_BLOCKS, + Resource_MARKS, + Resource_EFLGC, + Resource_IMAPSL, + Resource_IMAPSTEPS, + Resource_IMAPSOFS, + Resource_IMAPTEXT, + Resource_GAMEOVERTXT, + Resource_PAUSEDTXT, + Resource_SPRITESDATA, + Resource_TILESDATA, + Resource_HIGHSCORES, + Resource_IMGSPLASH, + Resource_PICHAF, /* ST version only */ + Resource_PICCONGRATS, /* ST version only */ + Resource_PICSPLASH, /* ST version only */ + Resource_IMAINHOFT, /* PC version only */ + Resource_IMAINRDT, /* PC version only */ + Resource_IMAINCDC, /* PC version only */ + Resource_SCREENCONGRATS, /* PC version only */ + + /* sounds */ + Resource_SOUNDBOMBSHHT, + Resource_SOUNDBONUS, + Resource_SOUNDBOX, + Resource_SOUNDBULLET, + Resource_SOUNDCRAWL, + Resource_SOUNDDIE, + Resource_SOUNDENTITY0, + Resource_SOUNDENTITY1, + Resource_SOUNDENTITY2, + Resource_SOUNDENTITY3, + Resource_SOUNDENTITY4, + Resource_SOUNDENTITY5, + Resource_SOUNDENTITY6, + Resource_SOUNDENTITY7, + Resource_SOUNDENTITY8, + Resource_SOUNDEXPLODE, + Resource_SOUNDGAMEOVER, + Resource_SOUNDJUMP, + Resource_SOUNDPAD, + Resource_SOUNDSBONUS1, + Resource_SOUNDSBONUS2, + Resource_SOUNDSTICK, + Resource_SOUNDTUNE0, + Resource_SOUNDTUNE1, + Resource_SOUNDTUNE2, + Resource_SOUNDTUNE3, + Resource_SOUNDTUNE4, + Resource_SOUNDTUNE5, + Resource_SOUNDWALK, + + Resource_MAX_COUNT, +}; + +#define BOOTSTRAP_RESOURCE_NAME "filelist.dat" + +bool resources_load(void); +void resources_unload(void); + +#endif /* ndef _RESOURCES_H */ + +/* eof */ diff --git a/apps/plugins/xrick/scr_gameover.c b/apps/plugins/xrick/scr_gameover.c new file mode 100644 index 0000000000..7467ce3cbe --- /dev/null +++ b/apps/plugins/xrick/scr_gameover.c @@ -0,0 +1,92 @@ +/* + * xrick/scr_gameover.c + * + * Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net). + * Copyright (C) 2008-2014 Pierluigi Vicinanza. + * All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#include "xrick/screens.h" + +#include "xrick/game.h" +#include "xrick/draw.h" +#include "xrick/control.h" +#include "xrick/system/system.h" + +/* + * Display the game over screen + * + * return: SCREEN_RUNNING, SCREEN_DONE, SCREEN_EXIT + */ +U8 +screen_gameover(void) +{ + static U8 seq = 0; + static U8 period = 0; +#ifdef GFXST + static U32 tm = 0; +#endif + if (seq == 0) { + draw_tilesBank = 0; + seq = 1; + period = game_period; /* save period, */ + game_period = 50; /* and use our own */ +#ifdef ENABLE_SOUND + game_setmusic(soundGameover, 1); +#endif + } + + switch (seq) { + case 1: /* display banner */ +#ifdef GFXST + sysvid_clear(); + tm = sys_gettime(); +#endif + draw_tllst = screen_gameovertxt; + draw_setfb(120, 80); +#ifdef GFXPC + draw_filter = 0xAAAA; +#endif + draw_tilesList(); + draw_drawStatus(); + + game_rects = &draw_SCREENRECT; + seq = 2; + break; + + case 2: /* wait for key pressed */ + if (control_test(Control_FIRE)) + seq = 3; +#ifdef GFXST + else if (sys_gettime() - tm > SCREEN_TIMEOUT) + seq = 4; +#endif + break; + + case 3: /* wait for key released */ + if (!(control_test(Control_FIRE))) + seq = 4; + break; + } + + if (control_test(Control_EXIT)) /* check for exit request */ + return SCREEN_EXIT; + + if (seq == 4) { /* we're done */ + sysvid_clear(); + seq = 0; + game_period = period; + return SCREEN_DONE; + } + + return SCREEN_RUNNING; +} + +/* eof */ diff --git a/apps/plugins/xrick/scr_getname.c b/apps/plugins/xrick/scr_getname.c new file mode 100644 index 0000000000..eb1afffde9 --- /dev/null +++ b/apps/plugins/xrick/scr_getname.c @@ -0,0 +1,290 @@ +/* + * xrick/scr_getname.c + * + * Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net). + * Copyright (C) 2008-2014 Pierluigi Vicinanza. + * All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#include "xrick/screens.h" + +#include "xrick/game.h" +#include "xrick/draw.h" +#include "xrick/control.h" +#include "xrick/data/pics.h" +#include "xrick/system/system.h" + +/* + * local vars + */ +static U8 seq = 0; +static U8 x, y, p; +static U8 player_name[HISCORE_NAME_SIZE]; + +#define TILE_POINTER '\072' +#define TILE_CURSOR '\073' +#define TOPLEFT_X 116 +#define TOPLEFT_Y 64 +#define NAMEPOS_X 120 +#define NAMEPOS_Y 160 +#define AUTOREPEAT_TMOUT 100 + + +/* + * prototypes + */ +static void pointer_show(bool); +static void name_update(void); +static void name_draw(void); + + +/* + * Get name + * + * return: 0 while running, 1 when finished. + */ +U8 +screen_getname(void) +{ + static U32 tm = 0; + U8 i, j; + + if (seq == 0) + { + /* figure out if this is a high score */ + if (game_score < screen_highScores[screen_nbr_hiscores - 1].score) + return SCREEN_DONE; + + /* prepare */ + draw_tilesBank = 0; +#ifdef GFXPC + draw_filter = 0xffff; +#endif + for (i = 0; i < HISCORE_NAME_SIZE; i++) + { + player_name[i] = '@'; + } + x = 5, y = 4, p = 0; + game_rects = &draw_SCREENRECT; + seq = 1; + } + + switch (seq) + { + case 1: /* prepare screen */ + { + sysvid_clear(); +#ifdef GFXPC + draw_setfb(32, 8); + draw_filter = 0xaaaa; /* red */ + draw_tilesListImm(screen_congrats); +#endif +#ifdef GFXST + draw_pic(pic_congrats); +#endif + draw_setfb(72, 40); +#ifdef GFXPC + draw_filter = 0xffff; /* yellow */ +#endif + draw_tilesListImm((U8 *)"PLEASE@ENTER@YOUR@NAME\376"); +#ifdef GFXPC + draw_filter = 0x5555; /* green */ +#endif + for (i = 0; i < 6; i++) + { + for (j = 0; j < 4; j++) + { + draw_setfb(TOPLEFT_X + i * 8 * 2, TOPLEFT_Y + j * 8 * 2); + draw_tile('A' + i + j * 6); + } + } + draw_setfb(TOPLEFT_X, TOPLEFT_Y + 64); +#ifdef GFXST + draw_tilesListImm((U8 *)"Y@Z@.@@@\074\373\374\375\376"); +#endif +#ifdef GFXPC + draw_tilesListImm((U8 *)"Y@Z@.@@@\074@\075@\376"); +#endif + name_draw(); + pointer_show(true); + seq = 2; + break; + } + case 2: /* wait for key pressed */ + { + if (control_test(Control_FIRE)) + seq = 3; + if (control_test(Control_UP)) { + if (y > 0) { + pointer_show(false); + y--; + pointer_show(true); + tm = sys_gettime(); + } + seq = 4; + } + if (control_test(Control_DOWN)) { + if (y < 4) { + pointer_show(false); + y++; + pointer_show(true); + tm = sys_gettime(); + } + seq = 5; + } + if (control_test(Control_LEFT)) { + if (x > 0) { + pointer_show(false); + x--; + pointer_show(true); + tm = sys_gettime(); + } + seq = 6; + } + if (control_test(Control_RIGHT)) { + if (x < 5) { + pointer_show(false); + x++; + pointer_show(true); + tm = sys_gettime(); + } + seq = 7; + } + break; + } + case 3: /* wait for FIRE released */ + { + if (!(control_test(Control_FIRE))) + { + if (x == 5 && y == 4) + { /* end */ + i = 0; + while (game_score < screen_highScores[i].score) i++; + j = 7; + while (j > i) + { + screen_highScores[j].score = screen_highScores[j - 1].score; + for (x = 0; x < HISCORE_NAME_SIZE; x++) + { + screen_highScores[j].name[x] = screen_highScores[j - 1].name[x]; + } + j--; + } + screen_highScores[i].score = game_score; + for (x = 0; x < HISCORE_NAME_SIZE; x++) + { + screen_highScores[i].name[x] = player_name[x]; + } + seq = 99; + } + else + { + name_update(); + name_draw(); + seq = 2; + } + } + break; + } + case 4: /* wait for UP released */ + { + if (!(control_test(Control_UP)) || + sys_gettime() - tm > AUTOREPEAT_TMOUT) + seq = 2; + break; + } + case 5: /* wait for DOWN released */ + { + if (!(control_test(Control_DOWN)) || + sys_gettime() - tm > AUTOREPEAT_TMOUT) + seq = 2; + break; + } + case 6: /* wait for LEFT released */ + { + if (!(control_test(Control_LEFT)) || + sys_gettime() - tm > AUTOREPEAT_TMOUT) + seq = 2; + break; + } + case 7: /* wait for RIGHT released */ + { + if (!(control_test(Control_RIGHT)) || + sys_gettime() - tm > AUTOREPEAT_TMOUT) + seq = 2; + break; + } + } + + if (control_test(Control_EXIT)) /* check for exit request */ + return SCREEN_EXIT; + + if (seq == 99) { /* seq 99, we're done */ + sysvid_clear(); + seq = 0; + return SCREEN_DONE; + } + else + return SCREEN_RUNNING; +} + + +static void +pointer_show(bool show) +{ + draw_setfb(TOPLEFT_X + x * 8 * 2, TOPLEFT_Y + y * 8 * 2 + 8); +#ifdef GFXPC + draw_filter = 0xaaaa; /* red */ +#endif + draw_tile(show? TILE_POINTER:'@'); +} + +static void +name_update(void) +{ + U8 i; + + i = x + y * 6; + if (i < 26 && p < 10) + player_name[p++] = 'A' + i; + if (i == 26 && p < 10) + player_name[p++] = '.'; + if (i == 27 && p < 10) + player_name[p++] = '@'; + if (i == 28 && p > 0) { + p--; + } +} + +static void +name_draw(void) +{ + U8 i; + + draw_setfb(NAMEPOS_X, NAMEPOS_Y); +#ifdef GFXPC + draw_filter = 0xaaaa; /* red */ +#endif + for (i = 0; i < p; i++) + draw_tile(player_name[i]); + for (i = p; i < 10; i++) + draw_tile(TILE_CURSOR); + +#ifdef GFXST + draw_setfb(NAMEPOS_X, NAMEPOS_Y + 8); + for (i = 0; i < 10; i++) + draw_tile('@'); + draw_setfb(NAMEPOS_X + 8 * (p < 9 ? p : 9), NAMEPOS_Y + 8); + draw_tile(TILE_POINTER); +#endif +} + + +/* eof */ diff --git a/apps/plugins/xrick/scr_imain.c b/apps/plugins/xrick/scr_imain.c new file mode 100644 index 0000000000..6851cd0cca --- /dev/null +++ b/apps/plugins/xrick/scr_imain.c @@ -0,0 +1,170 @@ +/* + * xrick/scr_imain.c + * + * Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net). + * Copyright (C) 2008-2014 Pierluigi Vicinanza. + * All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#include "xrick/screens.h" + +#include "xrick/game.h" +#include "xrick/draw.h" +#include "xrick/control.h" +#ifdef GFXST +#include "xrick/data/pics.h" +#endif +#include "xrick/system/system.h" + +/* + * Main introduction + * + * return: SCREEN_RUNNING, SCREEN_DONE, SCREEN_EXIT + */ +U8 +screen_introMain(void) +{ + static U8 seq = 0; + static U8 seen = 0; + static bool first = true; + static U8 period = 0; + static U32 tm = 0; + + if (seq == 0) { + draw_tilesBank = 0; + if (first) + seq = 1; + else + seq = 4; + period = game_period; + game_period = 50; + game_rects = &draw_SCREENRECT; +#ifdef ENABLE_SOUND + game_setmusic(soundTune5, -1); +#endif + } + + switch (seq) + { + case 1: /* display Rick Dangerous title and Core Design copyright */ + { + sysvid_clear(); + tm = sys_gettime(); +#ifdef GFXPC + /* Rick Dangerous title */ + draw_tllst = (U8 *)screen_imainrdt; + draw_setfb(32, 16); + draw_filter = 0xaaaa; + draw_tilesList(); + + /* Core Design copyright + press space to start */ + draw_tllst = (U8 *)screen_imaincdc; + draw_setfb(64, 80); + draw_filter = 0x5555; + draw_tilesList(); +#endif +#ifdef GFXST + draw_pic(pic_splash); +#endif + seq = 2; + break; + } + case 2: /* wait for key pressed or timeout */ + { + if (control_test(Control_FIRE)) + seq = 3; + else if (sys_gettime() - tm > SCREEN_TIMEOUT) { + seen++; + seq = 4; + } + break; + } + case 3: /* wait for key released */ + { + if (!(control_test(Control_FIRE))) { + if (seen++ == 0) + seq = 4; + else + seq = 7; + } + break; + } + case 4: /* dispay hall of fame */ + { + U8 s[32]; + size_t i; + + sysvid_clear(); + tm = sys_gettime(); + /* hall of fame title */ +#ifdef GFXPC + draw_tllst = (U8 *)screen_imainhoft; + draw_setfb(32, 0); + draw_filter = 0xaaaa; + draw_tilesList(); +#endif +#ifdef GFXST + draw_pic(pic_haf); +#endif + /* hall of fame content */ + draw_setfb(56, 48); +#ifdef GFXPC + draw_filter = 0x5555; +#endif + for (i = 0; i < screen_nbr_hiscores; i++) { + sys_snprintf((char *)s, sizeof(s), "%06d@@@====@@@%s", + screen_highScores[i].score, screen_highScores[i].name); + s[26] = (U8)'\377'; + s[27] = (U8)'\377'; + s[28] = (U8)'\376'; + draw_tllst = s; + draw_tilesList(); + } + seq = 5; + break; + } + case 5: /* wait for key pressed or timeout */ + { + if (control_test(Control_FIRE)) + seq = 6; + else if (sys_gettime() - tm > SCREEN_TIMEOUT) { + seen++; + seq = 1; + } + break; + } + case 6: /* wait for key released */ + { + if (!(control_test(Control_FIRE))) { + if (seen++ == 0) + seq = 1; + else + seq = 7; + } + break; + } + } + + if (control_test(Control_EXIT)) /* check for exit request */ + return SCREEN_EXIT; + + if (seq == 7) { /* we're done */ + sysvid_clear(); + seq = 0; + seen = 0; + first = false; + game_period = period; + return SCREEN_DONE; + } + else + return SCREEN_RUNNING; +} + +/* eof */ diff --git a/apps/plugins/xrick/scr_imap.c b/apps/plugins/xrick/scr_imap.c new file mode 100644 index 0000000000..5be80a24e4 --- /dev/null +++ b/apps/plugins/xrick/scr_imap.c @@ -0,0 +1,293 @@ +/* + * xrick/scr_imap.c + * + * Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net). + * Copyright (C) 2008-2014 Pierluigi Vicinanza. + * All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#include "xrick/screens.h" + +#include "xrick/game.h" +#include "xrick/rects.h" +#include "xrick/draw.h" +#include "xrick/control.h" +#include "xrick/maps.h" + +/* + * local vars + */ +static U16 step; /* current step */ +static U16 count; /* number of loops for current step */ +static U16 run; /* 1 = run, 0 = no more step */ +static U8 flipflop; /* flipflop for top, bottom, left, right */ +static U8 spnum; /* sprite number */ +static U16 spx, spdx; /* sprite x position and delta */ +static U16 spy, spdy; /* sprite y position and delta */ +static U16 spbase, spoffs; /* base, offset for sprite numbers table */ +static U8 seq = 0; /* anim sequence */ + +static rect_t anim_rect = { 128, 16 + 16, 64, 64, NULL }; /* anim rectangle */ + +/* + * prototypes + */ +static void drawtb(void); +static void drawlr(void); +static void drawsprite(void); +static void drawcenter(void); +static void nextstep(void); +static void anim(void); +static void init(void); + +/* + * Map introduction + * + * ASM: 1948 + * + * return: SCREEN_RUNNING, SCREEN_DONE, SCREEN_EXIT + */ +U8 +screen_introMap(void) +{ + switch (seq) { + case 0: + sysvid_clear(); + +#ifdef GFXPC + draw_tilesBank = 1; + draw_filter = 0xAAAA; +#endif +#ifdef GFXST + draw_tilesBank = 0; +#endif + draw_tllst = screen_imaptext[game_map]; + draw_setfb(40, 16); + draw_tilesSubList(); + + draw_setfb(40, 104); +#ifdef GFXPC + draw_filter = 0x5555; +#endif + draw_tilesList(); + + game_rects = NULL; + +#ifdef GFXPC + draw_filter = 0xFFFF; +#endif + + init(); + nextstep(); + drawcenter(); + drawtb(); + drawlr(); + drawsprite(); + draw_drawStatus(); + + game_rects = &draw_SCREENRECT; + +#ifdef ENABLE_SOUND + game_setmusic(map_maps[game_map].tune, 1); +#endif + + seq = 1; + break; + case 1: /* top and bottom borders */ + drawtb(); + game_rects = &anim_rect; + seq = 2; + break; + case 2: /* background and sprite */ + anim(); + drawcenter(); + drawsprite(); + game_rects = &anim_rect; + seq = 3; + break; + case 3: /* all borders */ + drawtb(); + drawlr(); + game_rects = &anim_rect; + seq = 1; + break; + case 4: /* wait for key release */ + if (!(control_test(Control_FIRE))) + seq = 5; + break; + } + + if (control_test(Control_FIRE)) { /* end as soon as key pressed */ + seq = 4; + } + + if (control_test(Control_EXIT)) /* check for exit request */ + return SCREEN_EXIT; + + if (seq == 5) { /* end as soon as key pressed */ + sysvid_clear(); + seq = 0; + return SCREEN_DONE; + } + else + return SCREEN_RUNNING; +} + + +/* + * Display top and bottom borders (0x1B1F) + * + */ +static void +drawtb(void) +{ + U8 i; + + flipflop++; + if (flipflop & 0x01) { + draw_setfb(136, 16 + 16); + for (i = 0; i < 6; i++) + draw_tile(0x40); + draw_setfb(136, 72 + 16); + for (i = 0; i < 6; i++) + draw_tile(0x06); + } + else { + draw_setfb(136, 16 + 16); + for (i = 0; i < 6; i++) + draw_tile(0x05); + draw_setfb(136, 72 + 16); + for (i = 0; i < 6; i++) + draw_tile(0x40); + } +} + + +/* + * Display left and right borders (0x1B7C) + * + */ +static void +drawlr(void) +{ + U8 i; + + if (flipflop & 0x02) { + for (i = 0; i < 8; i++) { + draw_setfb(128, 16 + i * 8 + 16); + draw_tile(0x04); + draw_setfb(184, 16 + i * 8 + 16); + draw_tile(0x04); + } + } + else { + for (i = 0; i < 8; i++) { + draw_setfb(128, 16 + i * 8 + 16); + draw_tile(0x2B); + draw_setfb(184, 16 + i * 8 + 16); + draw_tile(0x2B); + } + } +} + + +/* + * Draw the sprite (0x19C6) + * + */ +static void +drawsprite(void) +{ + draw_sprite(spnum, 136 + ((spx << 1) & 0x1C), 24 + (spy << 1) + 16); +} + + +/* + * Draw the background (0x1AF1) + * + */ +static void +drawcenter(void) +{ + static U8 tn0[] = { 0x07, 0x5B, 0x7F, 0xA3, 0xC7 }; + U8 i, j, tn; + + tn = tn0[game_map]; + for (i = 0; i < 6; i++) { + draw_setfb(136, (24 + 8 * i) + 16); + for (j = 0; j < 6; j++) + draw_tile(tn++); + } +} + + +/* + * Next Step (0x1A74) + * + */ +static void +nextstep(void) +{ + if (screen_imapsteps[step].count) { + count = screen_imapsteps[step].count; + spdx = screen_imapsteps[step].dx; + spdy = screen_imapsteps[step].dy; + spbase = screen_imapsteps[step].base; + spoffs = 0; + step++; + } + else { + run = 0; + } +} + + +/* + * Anim (0x1AA8) + * + */ +static void +anim(void) +{ + U8 i; + + if (run) { + i = screen_imapsl[spbase + spoffs]; + if (i == 0) { + spoffs = 0; + i = screen_imapsl[spbase]; + } + spnum = i; + spoffs++; + spx += spdx; + spy += spdy; + count--; + if (count == 0) + nextstep(); + } +} + + +/* + * Initialize (0x1A43) + * + */ +static void +init(void) +{ + run = 0; run--; + step = screen_imapsofs[game_map]; + spx = screen_imapsteps[step].dx; + spy = screen_imapsteps[step].dy; + step++; + spnum = 0; /* NOTE spnum in [8728] is never initialized ? */ +} + +/* eof */ diff --git a/apps/plugins/xrick/scr_pause.c b/apps/plugins/xrick/scr_pause.c new file mode 100644 index 0000000000..04c3368d21 --- /dev/null +++ b/apps/plugins/xrick/scr_pause.c @@ -0,0 +1,50 @@ +/* + * xrick/scr_pause.c + * + * Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net). + * Copyright (C) 2008-2014 Pierluigi Vicinanza. + * All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#include "xrick/screens.h" + +#include "xrick/game.h" +#include "xrick/draw.h" +#include "xrick/control.h" +#include "xrick/ents.h" + +/* + * Display the pause indicator + */ +void +screen_pause(bool pause) +{ + if (pause) { + draw_tilesBank = 0; + draw_tllst = screen_pausedtxt; + draw_setfb(120, 80); +#ifdef GFXPC + draw_filter = 0xAAAA; +#endif + draw_tilesList(); + } + else { +#ifdef GFXPC + draw_filter = 0xFFFF; +#endif + draw_map(); + ent_draw(); + draw_drawStatus(); + } + game_rects = &draw_SCREENRECT; +} + + +/* eof */ diff --git a/apps/plugins/xrick/scr_xrick.c b/apps/plugins/xrick/scr_xrick.c new file mode 100644 index 0000000000..00798ec123 --- /dev/null +++ b/apps/plugins/xrick/scr_xrick.c @@ -0,0 +1,101 @@ +/* + * xrick/scr_xrick.c + * + * Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net). + * Copyright (C) 2008-2014 Pierluigi Vicinanza. + * All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#include "xrick/screens.h" + +#include "xrick/game.h" +#include "xrick/draw.h" +#include "xrick/control.h" +#include "xrick/data/img.h" +#include "xrick/system/system.h" + +/* + * global vars + */ +size_t screen_nbr_imapsl = 0; +U8 *screen_imapsl = NULL; + +size_t screen_nbr_imapstesps = 0; +screen_imapsteps_t *screen_imapsteps = NULL; + +size_t screen_nbr_imapsofs = 0; +U8 *screen_imapsofs = NULL; + +size_t screen_nbr_imaptext = 0; +U8 **screen_imaptext = NULL; + +size_t screen_nbr_hiscores = 0; +hiscore_t *screen_highScores = NULL; + +#ifdef GFXPC +U8 *screen_imainhoft = NULL; +U8 *screen_imainrdt = NULL; +U8 *screen_imaincdc = NULL; +U8 *screen_congrats = NULL; +#endif +U8 *screen_gameovertxt = NULL; +U8 *screen_pausedtxt = NULL; + + +/* + * Display XRICK splash screen + * + * return: SCREEN_RUNNING, SCREEN_DONE, SCREEN_EXIT + */ +U8 +screen_xrick(void) +{ + static U8 seq = 0; + static U8 wait = 0; + + if (seq == 0) { + sysvid_clear(); + draw_img(img_splash); + game_rects = &draw_SCREENRECT; + seq = 1; + } + + switch (seq) { + case 1: /* wait */ + if (wait++ > 0x2) { +#ifdef ENABLE_SOUND + game_setmusic(soundBullet, 1); +#endif + seq = 2; + wait = 0; + } + break; + + case 2: /* wait */ + if (wait++ > 0x20) { + seq = 99; + wait = 0; + } + } + + if (control_test(Control_EXIT)) /* check for exit request */ + return SCREEN_EXIT; + + if (seq == 99) { /* we're done */ + sysvid_clear(); + sysvid_setGamePalette(); + seq = 0; + return SCREEN_DONE; + } + + return SCREEN_RUNNING; +} + +/* eof */ diff --git a/apps/plugins/xrick/screens.h b/apps/plugins/xrick/screens.h new file mode 100644 index 0000000000..60564a99d2 --- /dev/null +++ b/apps/plugins/xrick/screens.h @@ -0,0 +1,74 @@ +/* + * xrick/screens.h + * + * Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net). + * Copyright (C) 2008-2014 Pierluigi Vicinanza. + * All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#ifndef _SCREENS_H +#define _SCREENS_H + +#include "xrick/system/basic_types.h" +#include "xrick/config.h" + +#include /* size_t */ + +#define SCREEN_TIMEOUT 4000 +#define SCREEN_RUNNING 0 +#define SCREEN_DONE 1 +#define SCREEN_EXIT 2 + +typedef struct { + U16 count; /* number of loops */ + U16 dx, dy; /* sprite x and y deltas */ + U16 base; /* base for sprite numbers table */ +} screen_imapsteps_t; /* description of one step */ + +enum { HISCORE_NAME_SIZE = 10 }; +typedef struct { + U32 score; + U8 name[HISCORE_NAME_SIZE]; +} hiscore_t; + +extern size_t screen_nbr_imapsl; +extern U8 *screen_imapsl; /* sprite lists */ + +extern size_t screen_nbr_imapstesps; +extern screen_imapsteps_t *screen_imapsteps; /* map intro steps */ + +extern size_t screen_nbr_imapsofs; +extern U8 *screen_imapsofs; /* first step for each map */ + +extern size_t screen_nbr_imaptext; +extern U8 **screen_imaptext; /* map intro texts */ + +extern size_t screen_nbr_hiscores; +extern hiscore_t *screen_highScores; /* highest scores (hall of fame) */ + +#ifdef GFXPC +extern U8 *screen_imainhoft; /* hall of fame title */ +extern U8 *screen_imainrdt; /* rick dangerous title */ +extern U8 *screen_imaincdc; /* core design copyright text */ +extern U8 *screen_congrats; /* congratulations */ +#endif /* GFXPC */ +extern U8 *screen_gameovertxt; /* game over */ +extern U8 *screen_pausedtxt; /* paused */ + +extern U8 screen_xrick(void); /* splash */ +extern U8 screen_introMain(void); /* main intro */ +extern U8 screen_introMap(void); /* map intro */ +extern U8 screen_gameover(void); /* gameover */ +extern U8 screen_getname(void); /* enter you name */ +extern void screen_pause(bool); /* pause indicator */ + +#endif /* ndef _SCREENS_H */ + +/* eof */ diff --git a/apps/plugins/xrick/scroller.c b/apps/plugins/xrick/scroller.c new file mode 100644 index 0000000000..824fe9a6a9 --- /dev/null +++ b/apps/plugins/xrick/scroller.c @@ -0,0 +1,165 @@ +/* + * xrick/scroller.c + * + * Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net). + * Copyright (C) 2008-2014 Pierluigi Vicinanza. + * All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#include "xrick/scroller.h" + +#include "xrick/game.h" +#include "xrick/debug.h" +#include "xrick/draw.h" +#include "xrick/maps.h" +#include "xrick/ents.h" + +/* + * Local variables + */ +static U8 period; + +/* + * Scroll up + * + */ +U8 +scroll_up(void) +{ + U8 i, j; + static U8 n = 0; + + /* last call: restore */ + if (n == 8) { + n = 0; + game_period = period; + return SCROLL_DONE; + } + + /* first call: prepare */ + if (n == 0) { + period = game_period; + game_period = SCROLL_PERIOD; + } + + /* translate map */ + for (i = MAP_ROW_SCRTOP; i < MAP_ROW_HBBOT; i++) + for (j = 0x00; j < 0x20; j++) + map_map[i][j] = map_map[i + 1][j]; + + /* translate entities */ + for (i = 0; ent_ents[i].n != 0xFF; i++) { + if (ent_ents[i].n) { + ent_ents[i].ysave -= 8; + ent_ents[i].trig_y -= 8; + ent_ents[i].y -= 8; + if (ent_ents[i].y & 0x8000) { /* map coord. from 0x0000 to 0x0140 */ + IFDEBUG_SCROLLER( + sys_printf("xrick/scroller: entity %#04X is gone\n", i); + ); + ent_ents[i].n = 0; + } + } + } + + /* display */ + draw_map(); + ent_draw(); + draw_drawStatus(); + map_frow++; + + /* loop */ + if (n++ == 7) { + /* activate visible entities */ + ent_actvis(map_frow + MAP_ROW_HBTOP, map_frow + MAP_ROW_HBBOT); + + /* prepare map */ + map_expand(); + + /* display */ + draw_map(); + ent_draw(); + draw_drawStatus(); + } + + game_rects = &draw_SCREENRECT; + + return SCROLL_RUNNING; +} + +/* + * Scroll down + * + */ +U8 +scroll_down(void) +{ + U8 i, j; + static U8 n = 0; + + /* last call: restore */ + if (n == 8) { + n = 0; + game_period = period; + return SCROLL_DONE; + } + + /* first call: prepare */ + if (n == 0) { + period = game_period; + game_period = SCROLL_PERIOD; + } + + /* translate map */ + for (i = MAP_ROW_SCRBOT; i > MAP_ROW_HTTOP; i--) + for (j = 0x00; j < 0x20; j++) + map_map[i][j] = map_map[i - 1][j]; + + /* translate entities */ + for (i = 0; ent_ents[i].n != 0xFF; i++) { + if (ent_ents[i].n) { + ent_ents[i].ysave += 8; + ent_ents[i].trig_y += 8; + ent_ents[i].y += 8; + if (ent_ents[i].y > 0x0140) { /* map coord. from 0x0000 to 0x0140 */ + IFDEBUG_SCROLLER( + sys_printf("xrick/scroller: entity %#04X is gone\n", i); + ); + ent_ents[i].n = 0; + } + } + } + + /* display */ + draw_map(); + ent_draw(); + draw_drawStatus(); + map_frow--; + + /* loop */ + if (n++ == 7) { + /* activate visible entities */ + ent_actvis(map_frow + MAP_ROW_HTTOP, map_frow + MAP_ROW_HTBOT); + + /* prepare map */ + map_expand(); + + /* display */ + draw_map(); + ent_draw(); + draw_drawStatus(); + } + + game_rects = &draw_SCREENRECT; + + return SCROLL_RUNNING; +} + +/* eof */ diff --git a/apps/plugins/xrick/scroller.h b/apps/plugins/xrick/scroller.h new file mode 100644 index 0000000000..50c2190547 --- /dev/null +++ b/apps/plugins/xrick/scroller.h @@ -0,0 +1,31 @@ +/* + * xrick/scroller.h + * + * Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net). + * Copyright (C) 2008-2014 Pierluigi Vicinanza. + * All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#ifndef _SCROLLER_H +#define _SCROLLER_H + +#define SCROLL_RUNNING 1 +#define SCROLL_DONE 0 + +#define SCROLL_PERIOD 24 + +#include "xrick/system/basic_types.h" + +extern U8 scroll_up(void); +extern U8 scroll_down(void); + +#endif /* ndef _SCROLLER_H */ + +/* eof */ diff --git a/apps/plugins/xrick/system/basic_funcs.c b/apps/plugins/xrick/system/basic_funcs.c new file mode 100644 index 0000000000..fbc025a6ef --- /dev/null +++ b/apps/plugins/xrick/system/basic_funcs.c @@ -0,0 +1,33 @@ +/* + * xrick/system/basic_funcs.c + * + * Copyright (C) 2008-2014 Pierluigi Vicinanza. All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#include "xrick/system/basic_funcs.h" + +#ifdef USE_DEFAULT_ENDIANNESS_FUNCTIONS + +extern inline uint16_t swap16(uint16_t x); +extern inline uint32_t swap32(uint32_t x); + +extern inline uint16_t htobe16(uint16_t host); +extern inline uint16_t htole16(uint16_t host); +extern inline uint16_t betoh16(uint16_t big_endian); +extern inline uint16_t letoh16(uint16_t little_endian); + +extern inline uint32_t htobe32(uint32_t host); +extern inline uint32_t htole32(uint32_t host); +extern inline uint32_t betoh32(uint32_t big_endian); +extern inline uint32_t letoh32(uint32_t little_endian); + +#endif /* USE_DEFAULT_ENDIANNESS_FUNCTIONS */ + +/* eof */ diff --git a/apps/plugins/xrick/system/basic_funcs.h b/apps/plugins/xrick/system/basic_funcs.h new file mode 100644 index 0000000000..1ac5c58d32 --- /dev/null +++ b/apps/plugins/xrick/system/basic_funcs.h @@ -0,0 +1,141 @@ +/* + * xrick/system/basic_funcs.h + * + * Copyright (C) 2008-2014 Pierluigi Vicinanza. All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#ifndef _BASIC_FUNCS_H +#define _BASIC_FUNCS_H + +#include "xrick/system/basic_types.h" +#include "xrick/system/system.h" + +#ifdef __WIN32__ +/* Windows is little endian only */ +# define __ORDER_LITTLE_ENDIAN__ 1234 +# define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__ +# define USE_DEFAULT_ENDIANNESS_FUNCTIONS +# include /* _byteswap_XXX */ + +#elif defined(ROCKBOX) +/* Rockbox*/ +# include "plugin.h" +# define __ORDER_LITTLE_ENDIAN__ 1234 +# define __ORDER_BIG_ENDIAN__ 4321 +# ifdef ROCKBOX_BIG_ENDIAN +# define __BYTE_ORDER__ __ORDER_BIG_ENDIAN__ +# else +# define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__ +# endif + +#elif (defined(__FreeBSD__) && __FreeBSD_version >= 470000) || defined(__OpenBSD__) || defined(__NetBSD__) +/* *BSD */ +# include +# define __ORDER_BIG_ENDIAN__ BIG_ENDIAN +# define __ORDER_LITTLE_ENDIAN__ LITTLE_ENDIAN +# define __BYTE_ORDER__ BYTE_ORDER + +#elif (defined(BSD) && (BSD >= 199103)) || defined(__MacOSX__) +/* more BSD */ +# include +# define __ORDER_BIG_ENDIAN__ BIG_ENDIAN +# define __ORDER_LITTLE_ENDIAN__ LITTLE_ENDIAN +# define __BYTE_ORDER__ BYTE_ORDER + +#elif defined(__linux__) /*|| defined (__BEOS__)*/ +/* Linux, BeOS */ +# include +# define betoh16(x) be16toh(x) +# define letoh16(x) le16toh(x) +# define betoh32(x) be32toh(x) +# define letoh32(x) le32toh(x) + +#else +/* shall we just '#include '? */ +# define USE_DEFAULT_ENDIANNESS_FUNCTIONS + +#endif /* __WIN32__ */ + +/* define default endianness */ +#ifndef __ORDER_LITTLE_ENDIAN__ +# define __ORDER_LITTLE_ENDIAN__ 1234 +#endif + +#ifndef __ORDER_BIG_ENDIAN__ +# define __ORDER_BIG_ENDIAN__ 4321 +#endif + +#ifndef __BYTE_ORDER__ +# warning "Byte order not defined on your system, assuming little endian!" +# define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__ +#endif + +/* provide default endianness functions */ +#ifdef USE_DEFAULT_ENDIANNESS_FUNCTIONS + +# define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) + +inline uint32_t swap32(uint32_t x) +{ +# ifdef _MSC_VER + return _byteswap_ulong(x); +# elif (GCC_VERSION > 40300) || defined(__clang__) + return __builtin_bswap32(x); +# else + return (x >> 24) | + ((x >> 8) & 0x0000FF00) | + ((x << 8) & 0x00FF0000) | + (x << 24); +# endif /* _MSC_VER */ +} + +inline uint16_t swap16(uint16_t x) +{ +# ifdef _MSC_VER + return _byteswap_ushort(x); +# elif (GCC_VERSION > 40800) || defined(__clang__) + return __builtin_bswap16(x); +# else + return (x << 8)|(x >> 8); +# endif /* _MSC_VER */ +} + +# if (__BYTE_ORDER__==__ORDER_LITTLE_ENDIAN__) +inline uint16_t htobe16(uint16_t host) { return swap16(host); } +inline uint16_t htole16(uint16_t host) { return host; } +inline uint16_t betoh16(uint16_t big_endian) { return swap16(big_endian); } +inline uint16_t letoh16(uint16_t little_endian) { return little_endian; } + +inline uint32_t htobe32(uint32_t host) { return swap32(host); } +inline uint32_t htole32(uint32_t host) { return host; } +inline uint32_t betoh32(uint32_t big_endian) { return swap32(big_endian); } +inline uint32_t letoh32(uint32_t little_endian) { return little_endian; } + +# elif (__BYTE_ORDER__==__ORDER_BIG_ENDIAN__) +inline uint16_t htobe16(uint16_t host) { return host; } +inline uint16_t htole16(uint16_t host) { return swap16(host); } +inline uint16_t betoh16(uint16_t big_endian) { return big_endian; } +inline uint16_t letoh16(uint16_t little_endian) { return swap16(little_endian); } + +inline uint32_t htobe32(uint32_t host) { return host; } +inline uint32_t htole32(uint32_t host) { return swap32(host); } +inline uint32_t betoh32(uint32_t big_endian) { return big_endian; } +inline uint32_t letoh32(uint32_t little_endian) { return swap32(little_endian); } + +# else +# error "Unknown/unsupported byte order!" + +# endif + +#endif /* USE_DEFAULT_ENDIANNESS_FUNCTIONS */ + +#endif /* ndef _BASIC_FUNCS_H */ + +/* eof */ diff --git a/apps/plugins/xrick/system/basic_types.h b/apps/plugins/xrick/system/basic_types.h new file mode 100644 index 0000000000..e05fd477f3 --- /dev/null +++ b/apps/plugins/xrick/system/basic_types.h @@ -0,0 +1,48 @@ +/* + * xrick/system/basic_types.h + * + * Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net). + * Copyright (C) 2008-2014 Pierluigi Vicinanza. + * All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#ifndef _BASIC_TYPES_H +#define _BASIC_TYPES_H + +#ifdef _MSC_VER + +typedef enum { false, true } bool; + +#define inline __inline + +typedef unsigned __int8 uint8_t; +typedef unsigned __int16 uint16_t; +typedef unsigned __int32 uint32_t; +typedef __int8 int8_t; +typedef __int16 int16_t; +typedef __int32 int32_t; + +#else /* ndef _MSC_VER */ + +#include +#include + +#endif /* _MSC_VER */ + +typedef uint8_t U8; /* 8 bits unsigned */ +typedef uint16_t U16; /* 16 bits unsigned */ +typedef uint32_t U32; /* 32 bits unsigned */ +typedef int8_t S8; /* 8 bits signed */ +typedef int16_t S16; /* 16 bits signed */ +typedef int32_t S32; /* 32 bits signed */ + +#endif /* ndef _BASIC_TYPES_H */ + +/* eof */ diff --git a/apps/plugins/xrick/system/main_rockbox.c b/apps/plugins/xrick/system/main_rockbox.c new file mode 100644 index 0000000000..e273e1dc8d --- /dev/null +++ b/apps/plugins/xrick/system/main_rockbox.c @@ -0,0 +1,43 @@ + /*************************************************************************** + * __________ __ ___. + * Open \______ \ ____ ____ | | _\_ |__ _______ ___ + * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ / + * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < < + * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \ + * \/ \/ \/ \/ \/ + * $Id$ + * + * Port of xrick, a Rick Dangerous clone, to Rockbox. + * See http://www.bigorno.net/xrick/ + * + * Copyright (C) 2008-2014 Pierluigi Vicinanza + * + * 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 software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ****************************************************************************/ + +#include "xrick/system/system.h" +#include "xrick/game.h" + +#include "plugin.h" + +/* Plug-in entry point */ +enum plugin_status plugin_start(const void* parameter) +{ + char *filename = (char*)parameter; + bool success = sys_init(1, &filename); + if (success) + { + game_run(); + } + sys_shutdown(); + return (success? PLUGIN_OK : PLUGIN_ERROR); +} + +/* eof */ diff --git a/apps/plugins/xrick/system/miniz_config.h b/apps/plugins/xrick/system/miniz_config.h new file mode 100644 index 0000000000..65899b0c23 --- /dev/null +++ b/apps/plugins/xrick/system/miniz_config.h @@ -0,0 +1,38 @@ +/* + * xrick/system/miniz_config.h + * + * Copyright (C) 2008-2014 Pierluigi Vicinanza. All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#ifndef _MINIZ_CONFIG_H +#define _MINIZ_CONFIG_H + +/* + * miniz used only for crc32 calculation + */ +#define MINIZ_NO_STDIO +#define MINIZ_NO_TIME +#define MINIZ_NO_ARCHIVE_APIS +#define MINIZ_NO_ARCHIVE_WRITING_APIS +#define MINIZ_NO_ZLIB_APIS +#define MINIZ_NO_MALLOC +#ifdef ROCKBOX +# define MINIZ_NO_ASSERT +# ifndef SIMULATOR +# define MINIZ_X86_OR_X64_CPU 0 +# define MINIZ_HAS_64BIT_REGISTERS 0 +# define TINFL_USE_64BIT_BITBUF 0 +# define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 0 +# endif /* ndef SIMULATOR */ +#endif + +#endif /* ndef _MINIZ_CONFIG_H */ + +/* eof */ diff --git a/apps/plugins/xrick/system/rockboxcodes.h b/apps/plugins/xrick/system/rockboxcodes.h new file mode 100644 index 0000000000..ca56c338b6 --- /dev/null +++ b/apps/plugins/xrick/system/rockboxcodes.h @@ -0,0 +1,110 @@ + /*************************************************************************** + * __________ __ ___. + * Open \______ \ ____ ____ | | _\_ |__ _______ ___ + * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ / + * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < < + * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \ + * \/ \/ \/ \/ \/ + * $Id$ + * + * Port of xrick, a Rick Dangerous clone, to Rockbox. + * See http://www.bigorno.net/xrick/ + * + * Copyright (C) 2008-2014 Pierluigi Vicinanza + * + * 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 software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ****************************************************************************/ + +#ifndef _ROCKBOXCODES_H +#define _ROCKBOXCODES_H + +/* keypad mappings */ +#include "plugin.h" + +#if (CONFIG_KEYPAD == IRIVER_H100_PAD) || \ + (CONFIG_KEYPAD == IRIVER_H300_PAD) +#define XRICK_BTN_UP BUTTON_UP | BUTTON_REC +#define XRICK_BTN_DOWN BUTTON_DOWN | BUTTON_MODE +#define XRICK_BTN_LEFT BUTTON_LEFT +#define XRICK_BTN_RIGHT BUTTON_RIGHT +#define XRICK_BTN_FIRE BUTTON_ON +#define XRICK_BTN_PAUSE BUTTON_SELECT +#define XRICK_BTN_MENU BUTTON_OFF + +#elif (CONFIG_KEYPAD == IRIVER_H10_PAD) +#define XRICK_BTN_MENU BUTTON_POWER +#define XRICK_BTN_FIRE BUTTON_PLAY +#define XRICK_BTN_PAUSE BUTTON_REW +#define XRICK_BTN_UP BUTTON_SCROLL_UP +#define XRICK_BTN_DOWN BUTTON_SCROLL_DOWN +#define XRICK_BTN_LEFT BUTTON_LEFT +#define XRICK_BTN_RIGHT BUTTON_RIGHT + +#elif (CONFIG_KEYPAD == IPOD_4G_PAD) || \ + (CONFIG_KEYPAD == IPOD_3G_PAD) || \ + (CONFIG_KEYPAD == IPOD_1G2G_PAD) +#define XRICK_BTN_UP BUTTON_MENU +#define XRICK_BTN_DOWN BUTTON_PLAY +#define XRICK_BTN_LEFT BUTTON_LEFT +#define XRICK_BTN_RIGHT BUTTON_RIGHT +#define XRICK_BTN_FIRE BUTTON_SELECT +#define XRICK_BTN_PAUSE BUTTON_SCROLL_BACK +#define XRICK_BTN_MENU BUTTON_SCROLL_FWD + +#elif (CONFIG_KEYPAD == SANSA_FUZEPLUS_PAD) +#define XRICK_BTN_UP BUTTON_UP +#define XRICK_BTN_UPLEFT BUTTON_BACK +#define XRICK_BTN_UPRIGHT BUTTON_PLAYPAUSE +#define XRICK_BTN_DOWN BUTTON_DOWN +#define XRICK_BTN_DOWNLEFT BUTTON_BOTTOMLEFT +#define XRICK_BTN_DOWNRIGHT BUTTON_BOTTOMRIGHT +#define XRICK_BTN_LEFT BUTTON_LEFT +#define XRICK_BTN_RIGHT BUTTON_RIGHT +#define XRICK_BTN_FIRE BUTTON_VOL_DOWN +#define XRICK_BTN_PAUSE BUTTON_VOL_UP +#define XRICK_BTN_MENU BUTTON_POWER + +#elif (CONFIG_KEYPAD == SAMSUNG_YH92X_PAD) +#define XRICK_BTN_UP BUTTON_UP +#define XRICK_BTN_DOWN BUTTON_DOWN +#define XRICK_BTN_LEFT BUTTON_LEFT +#define XRICK_BTN_RIGHT BUTTON_RIGHT +#define XRICK_BTN_FIRE BUTTON_PLAY +#define XRICK_BTN_PAUSE BUTTON_FFWD +#define XRICK_BTN_MENU BUTTON_REW + +#elif (CONFIG_KEYPAD == SAMSUNG_YH820_PAD) +#define XRICK_BTN_UP BUTTON_UP +#define XRICK_BTN_DOWN BUTTON_DOWN +#define XRICK_BTN_LEFT BUTTON_LEFT +#define XRICK_BTN_RIGHT BUTTON_RIGHT +#define XRICK_BTN_FIRE BUTTON_PLAY +#define XRICK_BTN_PAUSE BUTTON_FFWD +#define XRICK_BTN_MENU BUTTON_REW + +/* place other keypad mappings here +#elif CONFIG_KEYPAD ==... +#define XRICK_BTN... +*/ + +#else +# include "lib/pluginlib_actions.h" +#define XRICK_BTN_UP PLA_UP +#define XRICK_BTN_DOWN PLA_DOWN +#define XRICK_BTN_LEFT PLA_LEFT +#define XRICK_BTN_RIGHT PLA_RIGHT +#define XRICK_BTN_FIRE PLA_SELECT +#define XRICK_BTN_PAUSE PLA_CANCEL +#define XRICK_BTN_MENU PLA_EXIT +#endif + +#endif /* ndef _ROCKBOXCODES_H */ + +/* eof */ diff --git a/apps/plugins/xrick/system/sysarg_rockbox.c b/apps/plugins/xrick/system/sysarg_rockbox.c new file mode 100644 index 0000000000..fa502ff4b0 --- /dev/null +++ b/apps/plugins/xrick/system/sysarg_rockbox.c @@ -0,0 +1,49 @@ + /*************************************************************************** + * __________ __ ___. + * Open \______ \ ____ ____ | | _\_ |__ _______ ___ + * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ / + * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < < + * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \ + * \/ \/ \/ \/ \/ + * $Id$ + * + * Port of xrick, a Rick Dangerous clone, to Rockbox. + * See http://www.bigorno.net/xrick/ + * + * Copyright (C) 2008-2014 Pierluigi Vicinanza + * + * 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 software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ****************************************************************************/ + +#include "xrick/system/system.h" + +/* + * globals + */ +int sysarg_args_period = 0; /* time between each frame, in milliseconds. The default is 40. */ +int sysarg_args_map = 0; +int sysarg_args_submap = 0; +bool sysarg_args_nosound = false; +const char *sysarg_args_data = NULL; + +/* + * Read and process arguments + */ +bool sysarg_init(int argc/*unused*/, char **argv) +{ + (void)argc; + + /* note: "*argv" is truly a "const *" */ + sysarg_args_data = *argv; + + return true; +} + +/* eof */ diff --git a/apps/plugins/xrick/system/sysevt_rockbox.c b/apps/plugins/xrick/system/sysevt_rockbox.c new file mode 100644 index 0000000000..f5314712e8 --- /dev/null +++ b/apps/plugins/xrick/system/sysevt_rockbox.c @@ -0,0 +1,156 @@ + /*************************************************************************** + * __________ __ ___. + * Open \______ \ ____ ____ | | _\_ |__ _______ ___ + * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ / + * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < < + * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \ + * \/ \/ \/ \/ \/ + * $Id$ + * + * Port of xrick, a Rick Dangerous clone, to Rockbox. + * See http://www.bigorno.net/xrick/ + * + * Copyright (C) 2008-2014 Pierluigi Vicinanza + * + * 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 software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ****************************************************************************/ + +#include "xrick/system/system.h" + +#include "xrick/config.h" +#include "xrick/control.h" +#include "xrick/game.h" +#include "xrick/system/sysmenu_rockbox.h" +#include "xrick/system/rockboxcodes.h" + +/* + * Helper function to set/clear controls according to key press + */ +static inline void checkKey(int key, unsigned button, control_t control) +{ + if (key & button) + { + control_set(control); + } + else + { + control_clear(control); + } +} + +/* + * Process events, if any, then return + */ +void sysevt_poll(void) +{ + static int previousKey, currentKey; + + /* this is because "Restart Game" is handled via menu */ + if (control_test(Control_END)) + { + control_clear(Control_END); + } + + for (;;) + { + /* check for USB connection */ + if ((rb->default_event_handler(rb->button_get(false)) == SYS_USB_CONNECTED) +#if defined(HAS_BUTTON_HOLD) + || rb->button_hold() +#endif + ) + { + sysmenu_exec(); + } + + currentKey = rb->button_status(); + if (currentKey != previousKey) + { + break; + } + else if (game_waitevt) + { + rb->yield(); + } + else /* (currentKey == previousKey) && !game_waitevt */ + { + return; + } + } + +#ifdef XRICK_BTN_MENU + if (currentKey & XRICK_BTN_MENU) + { + sysmenu_exec(); + } +#endif + +#ifdef XRICK_BTN_PAUSE + checkKey(currentKey, XRICK_BTN_PAUSE, Control_PAUSE); +#endif + + checkKey(currentKey, XRICK_BTN_UP, Control_UP); + + checkKey(currentKey, XRICK_BTN_DOWN, Control_DOWN); + + checkKey(currentKey, XRICK_BTN_LEFT, Control_LEFT); + + checkKey(currentKey, XRICK_BTN_RIGHT, Control_RIGHT); + + checkKey(currentKey, XRICK_BTN_FIRE, Control_FIRE); + +#ifdef XRICK_BTN_UPLEFT + if (!control_test(Control_UP | Control_LEFT)) + { + checkKey(currentKey, XRICK_BTN_UPLEFT, Control_UP | Control_LEFT); + } +#endif /* XRICK_BTN_UPLEFT */ + +#ifdef XRICK_BTN_UPRIGHT + if (!control_test(Control_UP | Control_RIGHT)) + { + checkKey(currentKey, XRICK_BTN_UPRIGHT, Control_UP | Control_RIGHT); + } +#endif /* XRICK_BTN_UPRIGHT */ + +#ifdef XRICK_BTN_DOWNLEFT + if (!control_test(Control_DOWN | Control_LEFT)) + { + checkKey(currentKey, XRICK_BTN_DOWNLEFT, Control_DOWN | Control_LEFT); + } +#endif /* XRICK_BTN_DOWNLEFT */ + +#ifdef XRICK_BTN_DOWNRIGHT + if (!control_test(Control_DOWN | Control_RIGHT)) + { + checkKey(currentKey, XRICK_BTN_DOWNRIGHT, Control_DOWN | Control_RIGHT); + } +#endif /* XRICK_BTN_DOWNRIGHT */ + + previousKey = currentKey; +} + +/* + * Wait for an event, then process it and return + */ +void sysevt_wait(void) +{ +#ifdef HAVE_ADJUSTABLE_CPU_FREQ + rb->cpu_boost(false); +#endif + + sysevt_poll(); /* sysevt_poll deals with blocking case as well */ + +#ifdef HAVE_ADJUSTABLE_CPU_FREQ + rb->cpu_boost(true); +#endif +} + +/* eof */ diff --git a/apps/plugins/xrick/system/sysfile_rockbox.c b/apps/plugins/xrick/system/sysfile_rockbox.c new file mode 100644 index 0000000000..72227d5301 --- /dev/null +++ b/apps/plugins/xrick/system/sysfile_rockbox.c @@ -0,0 +1,122 @@ + /*************************************************************************** + * __________ __ ___. + * Open \______ \ ____ ____ | | _\_ |__ _______ ___ + * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ / + * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < < + * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \ + * \/ \/ \/ \/ \/ + * $Id$ + * + * Port of xrick, a Rick Dangerous clone, to Rockbox. + * See http://www.bigorno.net/xrick/ + * + * Copyright (C) 2008-2014 Pierluigi Vicinanza + * + * 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 software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ****************************************************************************/ + +#include "xrick/system/system.h" + +#include "xrick/config.h" +#include "xrick/util.h" + +#include "plugin.h" + +#define XRICK_GAME_DIR ROCKBOX_DIR "/xrick/" + +/* + * Global variables + */ +const char *sysfile_defaultPath = XRICK_GAME_DIR; + +/* + * Local variables + */ +static char *rootPath = NULL; + +/* + * + */ +bool sysfile_setRootPath(const char *name) +{ + rootPath = u_strdup(name); + return (rootPath != NULL); +} + +/* + * + */ +void sysfile_clearRootPath() +{ + sysmem_pop(rootPath); + rootPath = NULL; +} + +/* + * Open a data file. + */ +file_t sysfile_open(const char *name) +{ + int fd; + + size_t fullPathLength = rb->strlen(rootPath) + rb->strlen(name) + 2; + char *fullPath = sysmem_push(fullPathLength); + if (!fullPath) + { + return NULL; + } + rb->snprintf(fullPath, fullPathLength, "%s/%s", rootPath, name); + fd = rb->open(fullPath, O_RDONLY); + sysmem_pop(fullPath); + + /* + * note: I've never seen zero/NULL being used as a file descriptor under Rockbox. + * Putting a check here in case this will ever happen (will need a fix). + */ + if (fd == 0) + { + sys_error("(file) unsupported file descriptor (zero/NULL) being used"); + } + if (fd < 0) + { + return NULL; + } + + return (file_t)fd; +} + +/* + * Read a file within a data archive. + */ +int sysfile_read(file_t file, void *buf, size_t size, size_t count) +{ + int fd = (int)file; + return (rb->read(fd, buf, size * count) / size); +} + +/* + * Seek. + */ +int sysfile_seek(file_t file, long offset, int origin) +{ + int fd = (int)file; + return rb->lseek(fd, offset, origin); +} + +/* + * Close a file within a data archive. + */ +void sysfile_close(file_t file) +{ + int fd = (int)file; + rb->close(fd); +} + +/* eof */ diff --git a/apps/plugins/xrick/system/sysmem_rockbox.c b/apps/plugins/xrick/system/sysmem_rockbox.c new file mode 100644 index 0000000000..06a683a463 --- /dev/null +++ b/apps/plugins/xrick/system/sysmem_rockbox.c @@ -0,0 +1,156 @@ + /*************************************************************************** + * __________ __ ___. + * Open \______ \ ____ ____ | | _\_ |__ _______ ___ + * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ / + * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < < + * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \ + * \/ \/ \/ \/ \/ + * $Id$ + * + * Port of xrick, a Rick Dangerous clone, to Rockbox. + * See http://www.bigorno.net/xrick/ + * + * Copyright (C) 2008-2014 Pierluigi Vicinanza + * + * 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 software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ****************************************************************************/ + +#include "xrick/system/system.h" + +#include "xrick/debug.h" + +#include "plugin.h" + +/* + * Local variables + */ +enum +{ + ALIGNMENT = sizeof(void*) /* this is more of an educated guess; might want to adjust for your specific architecture */ +}; +static U8 * stackBuffer; +static U8 * stackTop; +static size_t stackSize; +static size_t stackMaxSize; +static bool isMemoryInitialised = false; +IFDEBUG_MEMORY( static size_t maxUsedMemory = 0; ); + +/* + * Initialise memory stack + */ +bool sysmem_init(void) +{ + if (isMemoryInitialised) + { + return true; + } + + if (rb->audio_status()) + { + /* Playback must be stopped the entire time the sound buffer is used.*/ + rb->audio_stop(); + } + + stackBuffer = rb->plugin_get_audio_buffer(&stackMaxSize); + stackTop = stackBuffer; + stackSize = 0; + isMemoryInitialised = true; + return true; +} + +/* + * Cleanup memory stack + */ +void sysmem_shutdown(void) +{ + if (!isMemoryInitialised) + { + return; + } + + if (stackTop != stackBuffer || stackSize != 0) + { + sys_error("(memory) improper deallocation detected"); + } + + IFDEBUG_MEMORY( + sys_printf("xrick/memory: max memory usage was %u bytes\n", maxUsedMemory); + ); + + isMemoryInitialised = false; +} + +/* + * Allocate a memory-aligned block on top of the memory stack + */ +void *sysmem_push(size_t size) +{ + uintptr_t alignedPtr; + size_t * allocatedSizePtr; + + size_t neededSize = sizeof(size_t) + size + (ALIGNMENT - 1); + if (stackSize + neededSize > stackMaxSize) + { + sys_error("(memory) tried to allocate a block when memory full"); + return NULL; + } + + alignedPtr = (((uintptr_t)stackTop) + sizeof(size_t) + ALIGNMENT) & ~((uintptr_t)(ALIGNMENT - 1)); + + allocatedSizePtr = (size_t *)(alignedPtr); + allocatedSizePtr[-1] = neededSize; + + stackTop += neededSize; + stackSize += neededSize; + + IFDEBUG_MEMORY( + sys_printf("xrick/memory: allocated %u bytes\n", neededSize); + if (stackSize > maxUsedMemory) maxUsedMemory = stackSize; + ); + + return (void *)alignedPtr; +} + +/* + * Release block from the top of the memory stack + */ +void sysmem_pop(void * alignedPtr) +{ + size_t allocatedSize; + + if (!alignedPtr) + { + return; + } + + if (stackSize == 0) + { + sys_error("(memory) tried to release a block when memory empty"); + return; + } + + allocatedSize = ((size_t *)(alignedPtr))[-1]; + stackTop -= allocatedSize; + stackSize -= allocatedSize; + + IFDEBUG_MEMORY( + if ((uintptr_t)alignedPtr != ((((uintptr_t)stackTop) + sizeof(size_t) + ALIGNMENT) & ~((uintptr_t)(ALIGNMENT - 1)))) + { + sys_error("(memory) tried to release a wrong block"); + return; + } + ); + + IFDEBUG_MEMORY( + sys_printf("xrick/memory: released %u bytes\n", allocatedSize); + ); +} + +/* eof */ diff --git a/apps/plugins/xrick/system/sysmenu_rockbox.c b/apps/plugins/xrick/system/sysmenu_rockbox.c new file mode 100644 index 0000000000..fb80881749 --- /dev/null +++ b/apps/plugins/xrick/system/sysmenu_rockbox.c @@ -0,0 +1,200 @@ + /*************************************************************************** + * __________ __ ___. + * Open \______ \ ____ ____ | | _\_ |__ _______ ___ + * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ / + * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < < + * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \ + * \/ \/ \/ \/ \/ + * $Id$ + * + * Port of xrick, a Rick Dangerous clone, to Rockbox. + * See http://www.bigorno.net/xrick/ + * + * Copyright (C) 2008-2014 Pierluigi Vicinanza + * + * 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 software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ****************************************************************************/ + +#include "xrick/system/sysmenu_rockbox.h" + +#include "xrick/config.h" +#include "xrick/control.h" +#include "xrick/draw.h" +#include "xrick/game.h" +#include "xrick/system/system.h" +#include "xrick/system/syssnd_rockbox.h" + +#include "plugin.h" +#ifndef HAVE_LCD_COLOR +#include "lib/grey.h" +#endif + +#ifdef HAVE_LCD_COLOR +static fb_data *lcd_fb=NULL; +#endif + +#ifdef ENABLE_CHEATS +/* + * Cheat settings menu + */ +static char * sysmenu_cheatItemText(int selected_item, void *data, char *buffer, size_t buffer_len) +{ + (void)selected_item; + cheat_t cheat = (cheat_t)data; + (void)buffer; + (void)buffer_len; + char * messages[] = + { + "Disable Unlimited Lives/Ammo Mode", + "Enable Unlimited Lives/Ammo Mode", + "Disable Never Die Mode", + "Enable Never Die Mode", + "Disable Expose Mode", + "Enable Expose Mode" + }; + + switch (cheat) + { + case Cheat_UNLIMITED_ALL: + { + return game_cheat1? messages[0] : messages[1]; + } + case Cheat_NEVER_DIE: + { + return game_cheat2? messages[2] : messages[3]; + } + case Cheat_EXPOSE: + { + return game_cheat3? messages[4] : messages[5]; + } + default: break; + } + return ""; +} + +/* + * Callback invoked by cheat menu item + */ +static int sysmenu_doToggleCheat(void *param) +{ + cheat_t cheat = (cheat_t)param; + game_toggleCheat(cheat); + return 0; +} + +MENUITEM_FUNCTION_DYNTEXT(sysmenu_unlimitedAllItem, MENU_FUNC_USEPARAM, sysmenu_doToggleCheat, + sysmenu_cheatItemText, NULL, (void *)Cheat_UNLIMITED_ALL, + NULL, Icon_NOICON); + +MENUITEM_FUNCTION_DYNTEXT(sysmenu_neverDieItem, MENU_FUNC_USEPARAM, sysmenu_doToggleCheat, + sysmenu_cheatItemText, NULL, (void *)Cheat_NEVER_DIE, + NULL, Icon_NOICON); + +MENUITEM_FUNCTION_DYNTEXT(sysmenu_exposeItem, MENU_FUNC_USEPARAM, sysmenu_doToggleCheat, + sysmenu_cheatItemText, NULL, (void *)Cheat_EXPOSE, + NULL, Icon_NOICON); + +MAKE_MENU(sysmenu_cheatItems, "Cheat Settings", NULL, Icon_NOICON, + &sysmenu_unlimitedAllItem, &sysmenu_neverDieItem, &sysmenu_exposeItem); + +#endif /* ENABLE_CHEATS */ + +/* + * Display main menu + */ +void sysmenu_exec(void) +{ + int result; + bool done; + + enum + { + Menu_RESUME, + Menu_RESTART, +#ifdef ENABLE_CHEATS + Menu_CHEAT_SETTINGS, +#endif + Menu_QUIT + }; + + MENUITEM_STRINGLIST(sysmenu_mainItems, "xrick Menu", NULL, + "Resume Game", + "Restart Game", +#ifdef ENABLE_CHEATS + "Cheat Settings", +#endif + ID2P(LANG_MENU_QUIT)); + +#ifdef ENABLE_SOUND + syssnd_pauseAll(true); +#endif + +#ifndef HAVE_LCD_COLOR + grey_show(false); +#endif + + done = false; + do + { + rb->button_clear_queue(); + + result = rb->do_menu(&sysmenu_mainItems, NULL, NULL, false); + switch(result) + { + case Menu_RESUME: + { + done = true; + break; + } + case Menu_RESTART: + { + control_set(Control_END); + done = true; + break; + } +#ifdef ENABLE_CHEATS + case Menu_CHEAT_SETTINGS: + { + rb->do_menu(&sysmenu_cheatItems, NULL, NULL, false); + break; + } +#endif + case Menu_QUIT: + { + control_set(Control_EXIT); + done = true; + break; + } + default: break; + } + } while (!done); + +#ifdef HAVE_LCD_COLOR + if (!(control_test(Control_EXIT))) + { + if(!lcd_fb) + { + struct viewport *vp_main = rb->lcd_set_viewport(NULL); + lcd_fb = vp_main->buffer->fb_ptr; + } + rb->memset(lcd_fb, 0, sizeof(fb_data) * LCD_WIDTH * LCD_HEIGHT); + sysvid_update(&draw_SCREENRECT); + rb->lcd_update(); + } +#else + grey_show(true); +#endif + +#ifdef ENABLE_SOUND + syssnd_pauseAll(false); +#endif +} + +/* eof */ diff --git a/apps/plugins/xrick/system/sysmenu_rockbox.h b/apps/plugins/xrick/system/sysmenu_rockbox.h new file mode 100644 index 0000000000..fcd13606fa --- /dev/null +++ b/apps/plugins/xrick/system/sysmenu_rockbox.h @@ -0,0 +1,32 @@ + /*************************************************************************** + * __________ __ ___. + * Open \______ \ ____ ____ | | _\_ |__ _______ ___ + * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ / + * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < < + * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \ + * \/ \/ \/ \/ \/ + * $Id$ + * + * Port of xrick, a Rick Dangerous clone, to Rockbox. + * See http://www.bigorno.net/xrick/ + * + * Copyright (C) 2008-2014 Pierluigi Vicinanza + * + * 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 software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ****************************************************************************/ + +#ifndef _SYSMENU_ROCKBOX_H +#define _SYSMENU_ROCKBOX_H + +extern void sysmenu_exec(void); + +#endif /* ndef _SYSMENU_ROCKBOX_H */ + +/* eof */ diff --git a/apps/plugins/xrick/system/syssnd_rockbox.c b/apps/plugins/xrick/system/syssnd_rockbox.c new file mode 100644 index 0000000000..97ed5474f1 --- /dev/null +++ b/apps/plugins/xrick/system/syssnd_rockbox.c @@ -0,0 +1,483 @@ + /*************************************************************************** + * __________ __ ___. + * Open \______ \ ____ ____ | | _\_ |__ _______ ___ + * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ / + * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < < + * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \ + * \/ \/ \/ \/ \/ + * $Id$ + * + * Port of xrick, a Rick Dangerous clone, to Rockbox. + * See http://www.bigorno.net/xrick/ + * + * Copyright (C) 2008-2014 Pierluigi Vicinanza + * + * 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 software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ****************************************************************************/ + +#include "xrick/config.h" + +#ifdef ENABLE_SOUND + +#include "xrick/system/system.h" + +#include "xrick/game.h" +#include "xrick/debug.h" +#include "xrick/system/syssnd_rockbox.h" + +#include "plugin.h" + +/* + * Global variables + */ +const U8 syssnd_period = 20; + +/* + * Local variables + */ +enum +{ + SYSSND_MIX_CHANNELS = 5, + SYSSND_MIX_SAMPLES = 1024, /* try changing this value if sound mixing is too slow or choppy */ + SYSSND_SOURCE_SAMPLES = SYSSND_MIX_SAMPLES / 2 +}; + +/* channels to be mixed */ +static channel_t channels[SYSSND_MIX_CHANNELS]; +/* buffer used to mix sounds sent to pcm playback, stores 16b stereo 44Khz audio samples */ +enum { AUDIO_BUFFER_COUNT = 4 }; +typedef struct +{ + U32 data[SYSSND_MIX_SAMPLES]; + size_t length; /* in 8 bit mono samples */ +} mix_buffer_t; +static mix_buffer_t mixBuffers[AUDIO_BUFFER_COUNT]; +static size_t writeIndex; +static size_t readIndex; +static size_t fillCount; +static bool isAudioPlaying; +static bool isAudioInitialised = false; + +/* + * Prototypes + */ +static void endChannel(size_t c); +static void get_more(const void **start, size_t *size); + +/* + * Deactivate channel + */ +static void endChannel(size_t c) +{ + channels[c].loop = 0; + channels[c].sound = NULL; +} + +/* + * Audio callback + */ +static void get_more(const void **start, size_t *size) +{ + if (fillCount > 0) + { + /* Store output data address and size. */ + *start = mixBuffers[readIndex].data; + *size = mixBuffers[readIndex].length * 8; + + /* Free this part of output buffer. */ + mixBuffers[readIndex].length = 0; + + /* Advance to the next part of output buffer. */ + readIndex = (readIndex + 1) & (AUDIO_BUFFER_COUNT - 1); + fillCount--; + } + else + { + /* Nothing to play. */ + isAudioPlaying = false; + } +} + +/* + * Mix audio samples and fill playback buffer + */ +void syssnd_update(void) +{ + if (!isAudioInitialised) + { + return; + } + + for (;;) + { + size_t c; + size_t sampleOffset; + size_t maxSampleCount; + bool isFirstSound; + U8 *sourceBuf, *sourceBufEnd; + U32 *destBuf; + + /* Cancel if whole buffer filled. */ + if (fillCount >= (AUDIO_BUFFER_COUNT - 1)) + { + return; + } + + maxSampleCount = 0; + + sampleOffset = mixBuffers[writeIndex].length; + destBuf = mixBuffers[writeIndex].data + sampleOffset * 2; + + isFirstSound = true; + for (c = 0; c < SYSSND_MIX_CHANNELS ; ++c) + { + U32 * mixBuffer; + size_t sampleCount; + channel_t * channel = &channels[c]; + + if (!channel->sound /* no sound to play on this channel */ + || (channel->loop == 0)) /* channel is inactive */ + { + continue; + } + + if (isFirstSound) + { + /* clear mixing buffer */ + rb->memset(destBuf, 0, (SYSSND_MIX_SAMPLES - (sampleOffset * 2)) * sizeof(U32)); + isFirstSound = false; + } + + sampleCount = MIN(SYSSND_SOURCE_SAMPLES - sampleOffset, channel->len); + if (maxSampleCount < sampleCount) + { + maxSampleCount = sampleCount; + } + + /* mix sound samples */ + mixBuffer = destBuf; + sourceBuf = channel->buf; + sourceBufEnd = channel->buf + sampleCount; + while (sourceBuf < sourceBufEnd) + { + /* Convert from unsigned 8 bit mono 22khz to signed 16 bit stereo 44khz */ + const int sourceSample = *sourceBuf++; + int monoSample = (sourceSample - 0x80) << 8; + U32 stereoSample = *mixBuffer; + monoSample += (S32)(stereoSample) >> 16; + if (monoSample >= 0x8000) + { + monoSample = 0x7FFF; + } + else if (monoSample < -0x8000) + { + monoSample = -0x8000; + } + stereoSample = (U16)monoSample | ((U16)monoSample << 16); + *mixBuffer++ = stereoSample; + *mixBuffer++ = stereoSample; + } + channel->buf = sourceBufEnd; + + channel->len -= sampleCount; + if (channel->len == 0) /* ending ? */ + { + if (channel->loop > 0) + { + channel->loop--; + } + if (channel->loop) + { + /* just loop */ + IFDEBUG_AUDIO2(sys_printf("xrick/audio: channel %d - loop\n", c);); + channel->buf = channel->sound->buf; + channel->len = channel->sound->len; + } + else + { + /* end for real */ + IFDEBUG_AUDIO2(sys_printf("xrick/audio: channel %d - end\n", c);); + endChannel(c); + } + } + } + + if (maxSampleCount == 0) + { + return; + } + + mixBuffers[writeIndex].length += maxSampleCount; + + /* Advance one part of audio buffer. */ + writeIndex = (writeIndex + 1) & (AUDIO_BUFFER_COUNT - 1); + fillCount++; + + if (!isAudioPlaying && fillCount > 0) + { + rb->pcm_play_data(&get_more, NULL, NULL, 0); + isAudioPlaying = true; + } + } +} + +/* + * Initialise audio + */ +bool syssnd_init(void) +{ + if (isAudioInitialised) + { + return true; + } + + IFDEBUG_AUDIO(sys_printf("xrick/audio: start\n");); + + rb->talk_disable(true); + + /* Stop playback to reconfigure audio settings and acquire audio buffer */ + rb->mixer_channel_stop(PCM_MIXER_CHAN_PLAYBACK); + +#if INPUT_SRC_CAPS != 0 + /* Select playback */ + rb->audio_set_input_source(AUDIO_SRC_PLAYBACK, SRCF_PLAYBACK); + rb->audio_set_output_source(AUDIO_SRC_PLAYBACK); +#endif + + rb->pcm_set_frequency(HW_FREQ_44); + rb->pcm_apply_settings(); + + rb->memset(channels, 0, sizeof(channels)); + rb->memset(mixBuffers, 0, sizeof(mixBuffers)); + + writeIndex = 0; + readIndex = 0; + fillCount = 0; + isAudioPlaying = false; + + isAudioInitialised = true; + IFDEBUG_AUDIO(sys_printf("xrick/audio: ready\n");); + return true; +} + +/* + * Shutdown + */ +void syssnd_shutdown(void) +{ + if (!isAudioInitialised) + { + return; + } + + /* Stop playback. */ + rb->pcm_play_stop(); + + /* Reset playing status. */ + isAudioPlaying = false; + + /* Restore default sampling rate. */ + rb->pcm_set_frequency(HW_SAMPR_DEFAULT); + rb->pcm_apply_settings(); + + rb->talk_disable(false); + + isAudioInitialised = false; + IFDEBUG_AUDIO(sys_printf("xrick/audio: stop\n");); +} + +/* + * Play a sound + * + * loop: number of times the sound should be played, -1 to loop forever + * + * NOTE if sound is already playing, simply reset it (i.e. can not have + * twice the same sound playing -- tends to become noisy when too many + * bad guys die at the same time). + */ +void syssnd_play(sound_t *sound, S8 loop) +{ + size_t c; + + if (!isAudioInitialised || !sound) + { + return; + } + + c = 0; + while (channels[c].sound != sound && + channels[c].loop != 0 && + c < SYSSND_MIX_CHANNELS) + { + c++; + } + if (c >= SYSSND_MIX_CHANNELS) + { + return; + } + + if (!sound->buf) + { + syssnd_load(sound); + if (!sound->buf) + { + sys_error("(audio) can not load %s", sound->name); + return; + } + } + + IFDEBUG_AUDIO( + if (channels[c].sound == sound) + { + sys_printf("xrick/audio: already playing %s on channel %d - resetting\n", + sound->name, c); + } + else + { + sys_printf("xrick/audio: playing %s on channel %d\n", sound->name, c); + } + ); + + channels[c].loop = loop; + channels[c].sound = sound; + channels[c].buf = sound->buf; + channels[c].len = sound->len; +} + +/* + * Pause all sounds + */ +void syssnd_pauseAll(bool pause) +{ + if (!isAudioInitialised) + { + return; + } + + rb->pcm_play_lock(); + rb->mixer_channel_play_pause(PCM_MIXER_CHAN_PLAYBACK, !pause); + rb->pcm_play_unlock(); +} + +/* + * Stop a sound + */ +void syssnd_stop(sound_t *sound) +{ + size_t c; + + if (!isAudioInitialised || !sound) + { + return; + } + + for (c = 0; c < SYSSND_MIX_CHANNELS; c++) + { + if (channels[c].sound == sound) + { + endChannel(c); + } + } +} + +/* + * Stops all channels. + */ +void syssnd_stopAll(void) +{ + size_t c; + + if (!isAudioInitialised) + { + return; + } + + for (c = 0; c < SYSSND_MIX_CHANNELS; c++) + { + if (channels[c].sound) + { + endChannel(c); + } + } +} + +/* + * Load a sound. + */ +void syssnd_load(sound_t *sound) +{ + int bytesRead; + file_t fp; + bool success; + + if (!isAudioInitialised || !sound) + { + return; + } + + success = false; + do + { + sound->buf = sysmem_push(sound->len); + if (!sound->buf) + { + sys_error("(audio) not enough memory for \"%s\", %d bytes needed", sound->name, sound->len); + break; + } + + fp = sysfile_open(sound->name); + if (!fp) + { + sys_error("(audio) unable to open \"%s\"", sound->name); + break; + } + + sysfile_seek(fp, sizeof(wave_header_t), SEEK_SET); /* skip WAVE header */ + + bytesRead = sysfile_read(fp, sound->buf, sound->len, 1); + sysfile_close(fp); + if (bytesRead != 1) + { + sys_error("(audio) unable to read from \"%s\"", sound->name); + break; + } + + success = true; + } while (false); + + if (!success) + { + sysmem_pop(sound->buf); + sound->buf = NULL; + sound->len = 0; + return; + } + + IFDEBUG_AUDIO(sys_printf("xrick/audio: successfully loaded \"%s\"\n", sound->name);); +} + +/* + * Unload a sound. + */ +void syssnd_unload(sound_t *sound) +{ + if (!isAudioInitialised || !sound || !sound->buf) + { + return; + } + + sysmem_pop(sound->buf); + sound->buf = NULL; + sound->len = 0; +} + +#endif /* ENABLE_SOUND */ + +/* eof */ diff --git a/apps/plugins/xrick/system/syssnd_rockbox.h b/apps/plugins/xrick/system/syssnd_rockbox.h new file mode 100644 index 0000000000..41bd7d8454 --- /dev/null +++ b/apps/plugins/xrick/system/syssnd_rockbox.h @@ -0,0 +1,48 @@ + /*************************************************************************** + * __________ __ ___. + * Open \______ \ ____ ____ | | _\_ |__ _______ ___ + * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ / + * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < < + * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \ + * \/ \/ \/ \/ \/ + * $Id$ + * + * Port of xrick, a Rick Dangerous clone, to Rockbox. + * See http://www.bigorno.net/xrick/ + * + * Copyright (C) 2008-2014 Pierluigi Vicinanza + * + * 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 software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ****************************************************************************/ + +#ifndef _SYSSND_ROCKBOX_H +#define _SYSSND_ROCKBOX_H + +#include "xrick/config.h" + +#ifdef ENABLE_SOUND + +#include "xrick/system/system.h" + +typedef struct { + sound_t *sound; + U8 *buf; + U32 len; + S8 loop; +} channel_t; + +extern void syssnd_load(sound_t *); +extern void syssnd_unload(sound_t *); + +#endif /* ENABLE_SOUND */ + +#endif /* ndef _SYSSND_ROCKBOX_H */ + +/* eof */ diff --git a/apps/plugins/xrick/system/system.h b/apps/plugins/xrick/system/system.h new file mode 100644 index 0000000000..d4dda3d5d4 --- /dev/null +++ b/apps/plugins/xrick/system/system.h @@ -0,0 +1,178 @@ +/* + * xrick/system/system.h + * + * Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net). + * Copyright (C) 2008-2014 Pierluigi Vicinanza. + * All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#ifndef _SYSTEM_H +#define _SYSTEM_H + +/* + * Detect GCC + */ +#ifdef __GNUC__ +/* + * make POSIX functions available + */ +# ifndef _POSIX_SOURCE +# define _POSIX_SOURCE +# endif +#endif + +/* + * Detect Microsoft Visual C + */ +#ifdef _MSC_VER +/* + * FIXME disable "integral size mismatch in argument; conversion supplied" warning + * as long as the code has not been cleared -- there are so many of them... + */ +#pragma warning( disable : 4761 ) +#endif + +/* + * Detect Microsoft Windows + */ +#if !defined( __WIN32__ ) && ( defined( WIN32 ) || defined( _WIN32 ) ) +#define __WIN32__ +#endif + +#include "xrick/config.h" +#include "xrick/rects.h" +#include "xrick/data/img.h" +#ifdef ENABLE_SOUND +#include "xrick/data/sounds.h" +#endif + +#include /* size_t */ +#include /* off_t */ + +/* + * main section + */ +extern bool sys_init(int, char **); +extern void sys_shutdown(void); +extern void sys_error(const char *, ...); +extern void sys_printf(const char *, ...); +extern void sys_snprintf(char *, size_t, const char *, ...); +extern size_t sys_strlen(const char *); +extern U32 sys_gettime(void); +extern void sys_yield(void); +extern bool sys_cacheData(void); +extern void sys_uncacheData(void); + +/* + * memory section + */ +extern bool sysmem_init(void); +extern void sysmem_shutdown(void); +extern void *sysmem_push(size_t); +extern void sysmem_pop(void *); + +/* + * video section + */ +#define SYSVID_ZOOM 2 +#define SYSVID_MAXZOOM 4 +#define SYSVID_WIDTH 320 +#define SYSVID_HEIGHT 200 + +extern U8 *sysvid_fb; /* frame buffer */ + +extern bool sysvid_init(void); +extern void sysvid_shutdown(void); +extern void sysvid_update(const rect_t *); +extern void sysvid_clear(void); +extern void sysvid_zoom(S8); +extern void sysvid_toggleFullscreen(void); +extern void sysvid_setGamePalette(void); +extern void sysvid_setPalette(img_color_t *, U16); + +/* + * file management section + */ +typedef void *file_t; + +extern const char *sysfile_defaultPath; + +extern bool sysfile_setRootPath(const char *); +extern void sysfile_clearRootPath(void); + +extern file_t sysfile_open(const char *); +extern int sysfile_seek(file_t file, long offset, int origin); +extern int sysfile_tell(file_t); +extern off_t sysfile_size(file_t); +extern int sysfile_read(file_t, void *, size_t, size_t); +extern void sysfile_close(file_t); + +/* + * events section + */ +extern void sysevt_poll(void); +extern void sysevt_wait(void); + +/* + * keyboard section + */ +extern U8 syskbd_up; +extern U8 syskbd_down; +extern U8 syskbd_left; +extern U8 syskbd_right; +extern U8 syskbd_pause; +extern U8 syskbd_end; +extern U8 syskbd_xtra; +extern U8 syskbd_fire; + +/* + * sound section + */ +#ifdef ENABLE_SOUND +extern const U8 syssnd_period; /* time between each sound update, in millisecond */ + +extern bool syssnd_init(void); +extern void syssnd_shutdown(void); +extern void syssnd_update(void); +extern void syssnd_vol(S8); +extern void syssnd_toggleMute(void); +extern void syssnd_play(sound_t *, S8); +extern void syssnd_pauseAll(bool); +extern void syssnd_stop(sound_t *); +extern void syssnd_stopAll(void); +#endif /* ENABLE_ SOUND */ + +/* + * args section + */ +extern int sysarg_args_period; +extern int sysarg_args_map; +extern int sysarg_args_submap; +extern int sysarg_args_fullscreen; +extern int sysarg_args_zoom; +#ifdef ENABLE_SOUND +extern bool sysarg_args_nosound; +extern int sysarg_args_vol; +#endif /* ENABLE_ SOUND */ +extern const char *sysarg_args_data; + +extern bool sysarg_init(int, char **); + +/* + * joystick section + */ +#ifdef ENABLE_JOYSTICK +extern bool sysjoy_init(void); +extern void sysjoy_shutdown(void); +#endif + +#endif /* ndef _SYSTEM_H */ + +/* eof */ diff --git a/apps/plugins/xrick/system/system_rockbox.c b/apps/plugins/xrick/system/system_rockbox.c new file mode 100644 index 0000000000..3b5f96a4ed --- /dev/null +++ b/apps/plugins/xrick/system/system_rockbox.c @@ -0,0 +1,262 @@ + /*************************************************************************** + * __________ __ ___. + * Open \______ \ ____ ____ | | _\_ |__ _______ ___ + * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ / + * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < < + * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \ + * \/ \/ \/ \/ \/ + * $Id$ + * + * Port of xrick, a Rick Dangerous clone, to Rockbox. + * See http://www.bigorno.net/xrick/ + * + * Copyright (C) 2008-2014 Pierluigi Vicinanza + * + * 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 software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ****************************************************************************/ + +#include "xrick/system/system.h" + +#include "xrick/config.h" +#ifdef ENABLE_SOUND +#include "xrick/system/syssnd_rockbox.h" +#endif + +#include "plugin.h" + +enum { LINE_LENGTH = 80 }; + +/* +* Error +*/ +void sys_error(const char *err, ...) +{ + va_list argptr; + char s[LINE_LENGTH]; + + /* prepare message */ + va_start(argptr, err); + rb->vsnprintf(s, sizeof(s), err, argptr); + va_end(argptr); + + /* print error message */ + rb->splashf(HZ*3, ID2P(LANG_ERROR_FORMATSTR), s); + DEBUGF("Error: %s\n", s); +} + +/* +* Print a message to standard output +*/ +void sys_printf(const char *msg, ...) +{ + va_list argptr; + char s[LINE_LENGTH]; + + /* prepare message */ + va_start(argptr, msg); + rb->vsnprintf(s, sizeof(s), msg, argptr); + va_end(argptr); + + /* print message */ + DEBUGF("%s",s); + +#ifdef ENABLE_SYSPRINTF_TO_SCREEN + { + static int currentYPos = 0; + size_t i; + + /* Device LCDs display newlines funny. */ + for(i = 0; s[i] != '\0'; ++i) + { + if(s[i] == '\n') + { + s[i] = ' '; + } + } + + rb->lcd_putsxy(1, currentYPos, (unsigned char *)s); + rb->lcd_update(); + + currentYPos += 12; + if(currentYPos > LCD_HEIGHT-12) + { + currentYPos = 0; + rb->lcd_clear_display(); + } + } +#endif /* ENABLE_SYSPRINTF_TO_SCREEN */ +} + +/* +* Print a message to string buffer +*/ +void sys_snprintf(char *buf, size_t size, const char *msg, ...) +{ + va_list argptr; + + va_start(argptr, msg); + rb->vsnprintf(buf, size, msg, argptr); + va_end(argptr); +} + +/* +* Returns string length +*/ +size_t sys_strlen(const char * str) +{ + return rb->strlen(str); +} + +/* +* Return number of milliseconds elapsed since first call +*/ +U32 sys_gettime(void) +{ + long ticks = *(rb->current_tick); + return (U32)((ticks * 1000) / HZ); +} + +/* +* Yield execution to another thread +*/ +void sys_yield(void) +{ + rb->yield(); +} + +/* +* Initialize system +*/ +bool sys_init(int argc, char **argv) +{ +#ifdef HAVE_ADJUSTABLE_CPU_FREQ + rb->cpu_boost(true); +#endif + + if (!sysarg_init(argc, argv)) + { + return false; + } + if (!sysmem_init()) + { + return false; + } + if (!sysvid_init()) + { + return false; + } +#ifdef ENABLE_SOUND + if (!sysarg_args_nosound && !syssnd_init()) + { + return false; + } +#endif + if (!sysfile_setRootPath(sysarg_args_data? sysarg_args_data : sysfile_defaultPath)) + { + return false; + } + return true; +} + +/* +* Shutdown system +*/ +void sys_shutdown(void) +{ + sysfile_clearRootPath(); +#ifdef ENABLE_SOUND + syssnd_shutdown(); +#endif + sysvid_shutdown(); + sysmem_shutdown(); + +#ifdef HAVE_ADJUSTABLE_CPU_FREQ + rb->cpu_boost(false); +#endif +} + +/* +* Preload data before entering main loop +*/ +bool sys_cacheData(void) +{ +#ifdef ENABLE_SOUND + syssnd_load(soundGameover); + syssnd_load(soundSbonus2); + syssnd_load(soundBullet); + syssnd_load(soundBombshht); + syssnd_load(soundExplode); + syssnd_load(soundStick); + syssnd_load(soundWalk); + syssnd_load(soundCrawl); + syssnd_load(soundJump); + syssnd_load(soundPad); + syssnd_load(soundBox); + syssnd_load(soundBonus); + syssnd_load(soundSbonus1); + syssnd_load(soundDie); + syssnd_load(soundEntity[0]); + syssnd_load(soundEntity[1]); + syssnd_load(soundEntity[2]); + syssnd_load(soundEntity[3]); + syssnd_load(soundEntity[4]); + syssnd_load(soundEntity[5]); + syssnd_load(soundEntity[6]); + syssnd_load(soundEntity[7]); + syssnd_load(soundEntity[8]); + syssnd_load(soundTune0); + syssnd_load(soundTune1); + syssnd_load(soundTune2); + syssnd_load(soundTune3); + syssnd_load(soundTune4); + syssnd_load(soundTune5); +#endif /* ENABLE_SOUND */ + return true; +} + +/* +* Clear preloaded data before shutdown +*/ +void sys_uncacheData(void) +{ +#ifdef ENABLE_SOUND + syssnd_unload(soundTune5); + syssnd_unload(soundTune4); + syssnd_unload(soundTune3); + syssnd_unload(soundTune2); + syssnd_unload(soundTune1); + syssnd_unload(soundTune0); + syssnd_unload(soundEntity[8]); + syssnd_unload(soundEntity[7]); + syssnd_unload(soundEntity[6]); + syssnd_unload(soundEntity[5]); + syssnd_unload(soundEntity[4]); + syssnd_unload(soundEntity[3]); + syssnd_unload(soundEntity[2]); + syssnd_unload(soundEntity[1]); + syssnd_unload(soundEntity[0]); + syssnd_unload(soundDie); + syssnd_unload(soundSbonus1); + syssnd_unload(soundBonus); + syssnd_unload(soundBox); + syssnd_unload(soundPad); + syssnd_unload(soundJump); + syssnd_unload(soundCrawl); + syssnd_unload(soundWalk); + syssnd_unload(soundStick); + syssnd_unload(soundExplode); + syssnd_unload(soundBombshht); + syssnd_unload(soundBullet); + syssnd_unload(soundSbonus2); + syssnd_unload(soundGameover); +#endif /* ENABLE_SOUND */ +} + +/* eof */ diff --git a/apps/plugins/xrick/system/sysvid_rockbox.c b/apps/plugins/xrick/system/sysvid_rockbox.c new file mode 100644 index 0000000000..236bc87616 --- /dev/null +++ b/apps/plugins/xrick/system/sysvid_rockbox.c @@ -0,0 +1,402 @@ + /*************************************************************************** + * __________ __ ___. + * Open \______ \ ____ ____ | | _\_ |__ _______ ___ + * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ / + * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < < + * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \ + * \/ \/ \/ \/ \/ + * $Id$ + * + * Port of xrick, a Rick Dangerous clone, to Rockbox. + * See http://www.bigorno.net/xrick/ + * + * Copyright (C) 2008-2014 Pierluigi Vicinanza + * + * 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 software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ****************************************************************************/ + +#include "xrick/system/system.h" + +#include "xrick/config.h" +#include "xrick/draw.h" +#include "xrick/game.h" +#include "xrick/data/img.h" +#include "xrick/debug.h" + +#include "plugin.h" +#include "lib/helper.h" + +/* + * Global variables + */ +U8 *sysvid_fb = NULL; /* xRick generic 320x200 8bpp frame buffer */ + +/* + * Local variables + */ +static fb_data palette[256] IBSS_ATTR; +static bool isVideoInitialised = false; +#ifndef HAVE_LCD_COLOR +# include "lib/grey.h" +GREY_INFO_STRUCT_IRAM +static unsigned char greybuffer[LCD_HEIGHT * LCD_WIDTH] IBSS_ATTR; /* off screen buffer */ +static unsigned char *gbuf; +# if LCD_PIXELFORMAT == HORIZONTAL_PACKING +enum { GREYBUFSIZE = (((LCD_WIDTH+7)/8)*LCD_HEIGHT*16+200) }; +# else +enum { GREYBUFSIZE = (LCD_WIDTH*((LCD_HEIGHT+7)/8)*16+200) }; +# endif +#endif /* ndef HAVE_LCD_COLOR */ + +static fb_data *lcd_fb = NULL; + +#if (LCD_HEIGHT < SYSVID_HEIGHT) +enum { ROW_RESIZE_STEP = (LCD_HEIGHT << 16) / SYSVID_HEIGHT }; + +static bool rowsToSkip[SYSVID_HEIGHT]; + +/* + * + */ +static void calculateRowsToSkip(void) +{ + U32 currentRow, prevResizedRow; + + prevResizedRow = 0; + rowsToSkip[0] = false; + + for (currentRow = 1; currentRow < SYSVID_HEIGHT; ++currentRow) + { + U32 resizedRow = (currentRow * ROW_RESIZE_STEP) >> 16; + if (resizedRow == prevResizedRow) + { + rowsToSkip[currentRow] = true; + } + prevResizedRow = resizedRow; + } +} +#endif /* (LCD_HEIGHT < SYSVID_HEIGHT) */ + +#if (LCD_WIDTH < SYSVID_WIDTH) +enum { COLUMN_RESIZE_STEP = (LCD_WIDTH << 16) / (SYSVID_WIDTH + (DRAW_XYMAP_SCRLEFT*2)) }; + +static bool columnsToSkip[SYSVID_WIDTH + (DRAW_XYMAP_SCRLEFT*2)]; + +/* + * + */ +static void calculateColumnsToSkip(void) +{ + U32 currentColumn, prevResizedColumn; + + prevResizedColumn = 0; + columnsToSkip[0] = false; + + for (currentColumn = 1; currentColumn < (SYSVID_WIDTH + (DRAW_XYMAP_SCRLEFT*2)); ++currentColumn) + { + U32 resizedColumn = (currentColumn * COLUMN_RESIZE_STEP) >> 16; + if (resizedColumn == prevResizedColumn) + { + columnsToSkip[currentColumn] = true; + } + prevResizedColumn = resizedColumn; + } +} +#endif /* (LCD_WIDTH < SYSVID_WIDTH) */ + +/* + * + */ +void sysvid_setPalette(img_color_t *pal, U16 n) +{ + U16 i; + + for (i = 0; i < n; i++) + { +#ifdef HAVE_LCD_COLOR + palette[i] = LCD_RGBPACK(pal[i].r, pal[i].g, pal[i].b); +#else + palette[i] = ((3 * pal[i].r) + (6 * pal[i].g) + pal[i].b) / 10; +#endif + } +} + +/* + * + */ +void sysvid_setGamePalette() +{ + sysvid_setPalette(game_colors, game_color_count); +} + +/* + * Update screen + */ +void sysvid_update(const rect_t *rects) +{ + unsigned sourceRow, sourceLastRow; + unsigned sourceColumn, sourceLastColumn; + unsigned resizedRow, resizedColumn; + unsigned resizedWidth, resizedHeight; + unsigned x, y; + U8 *sourceBuf, *sourceTemp; + fb_data *destBuf, *destTemp; + + if (!rects) + { + return; + } + + while (rects) + { + sourceRow = rects->y; + sourceLastRow = sourceRow + rects->height; + sourceColumn = rects->x; + sourceLastColumn = sourceColumn + rects->width; + +#if (LCD_WIDTH < SYSVID_WIDTH) + /* skip black borders */ + if (sourceColumn < -DRAW_XYMAP_SCRLEFT) + { + sourceColumn = -DRAW_XYMAP_SCRLEFT; + } + if (sourceLastColumn > (SYSVID_WIDTH + DRAW_XYMAP_SCRLEFT)) + { + sourceLastColumn = SYSVID_WIDTH + DRAW_XYMAP_SCRLEFT; + } + + /* skip unwanted columns */ + while (columnsToSkip[sourceColumn + DRAW_XYMAP_SCRLEFT] /* && sourceColumn < (SYSVID_WIDTH + DRAW_XYMAP_SCRLEFT) */) + { + ++sourceColumn; + } + + resizedColumn = ((sourceColumn + DRAW_XYMAP_SCRLEFT) * COLUMN_RESIZE_STEP) >> 16; + resizedWidth = 0; +#else + resizedColumn = sourceColumn; + resizedWidth = rects->width; +#endif /* (LCD_WIDTH < SYSVID_WIDTH) */ + +#if (LCD_HEIGHT < SYSVID_HEIGHT) + /* skip unwanted rows */ + while (rowsToSkip[sourceRow] /* && sourceRow < SYSVID_HEIGHT */) + { + ++sourceRow; + } + + resizedRow = (sourceRow * ROW_RESIZE_STEP) >> 16; + resizedHeight = 0; +#else + resizedRow = sourceRow; + resizedHeight = rects->height; +#endif /* (LCD_HEIGHT < SYSVID_HEIGHT) */ + + sourceBuf = sysvid_fb; + sourceBuf += sourceColumn + sourceRow * SYSVID_WIDTH; + +#ifdef HAVE_LCD_COLOR + if(!lcd_fb) + { + struct viewport *vp_main = rb->lcd_set_viewport(NULL); + lcd_fb = vp_main->buffer->fb_ptr; + } + destBuf = lcd_fb; +#else + destBuf = greybuffer; +#endif /* HAVE_LCD_COLOR */ + destBuf += resizedColumn + resizedRow * LCD_WIDTH; + +#if (LCD_WIDTH < SYSVID_WIDTH) + sourceColumn += DRAW_XYMAP_SCRLEFT; + sourceLastColumn += DRAW_XYMAP_SCRLEFT; +#endif /* (LCD_WIDTH < SYSVID_WIDTH) */ + + for (y = sourceRow; y < sourceLastRow; ++y) + { +#if (LCD_HEIGHT < SYSVID_HEIGHT) + if (rowsToSkip[y]) + { + sourceBuf += SYSVID_WIDTH; + continue; + } + + ++resizedHeight; +#endif /* (LCD_HEIGHT < SYSVID_HEIGHT) */ + + sourceTemp = sourceBuf; + destTemp = destBuf; + for (x = sourceColumn; x < sourceLastColumn; ++x) + { +#if (LCD_WIDTH < SYSVID_WIDTH) + if (columnsToSkip[x]) + { + ++sourceTemp; + continue; + } + + if (y == sourceRow) + { + ++resizedWidth; + } +#endif /* (LCD_WIDTH < SYSVID_WIDTH) */ + + *destTemp = palette[*sourceTemp]; + + ++sourceTemp; + ++destTemp; + } + + sourceBuf += SYSVID_WIDTH; + destBuf += LCD_WIDTH; + } + +#ifdef HAVE_LCD_COLOR + IFDEBUG_VIDEO2( + for (y = resizedRow; y < resizedRow + resizedHeight; ++y) + { + destBuf = lcd_fb + resizedColumn + y * LCD_WIDTH; + *destBuf = palette[0x01]; + *(destBuf + resizedWidth - 1) = palette[0x01]; + } + + for (x = resizedColumn; x < resizedColumn + resizedWidth; ++x) + { + destBuf = rb->lcd_fb + x + resizedRow * LCD_WIDTH; + *destBuf = palette[0x01]; + *(destBuf + (resizedHeight - 1) * LCD_WIDTH) = palette[0x01]; + } + ); + + rb->lcd_update_rect(resizedColumn, resizedRow, resizedWidth, resizedHeight); +#else + grey_ub_gray_bitmap_part(greybuffer, resizedColumn, resizedRow, LCD_WIDTH, resizedColumn, resizedRow, resizedWidth, resizedHeight); +#endif /* HAVE_LCD_COLOR */ + + rects = rects->next; + } +} + +/* + * Clear screen + * (077C) + */ +void sysvid_clear(void) +{ + rb->memset(sysvid_fb, 0, sizeof(U8) * SYSVID_WIDTH * SYSVID_HEIGHT); +} + +/* + * Initialise video + */ +bool sysvid_init() +{ + bool success; + + if (isVideoInitialised) + { + return true; + } + + IFDEBUG_VIDEO(sys_printf("xrick/video: start\n");); + + success = false; + do + { + /* allocate xRick generic frame buffer into memory */ + sysvid_fb = sysmem_push(sizeof(U8) * SYSVID_WIDTH * SYSVID_HEIGHT); + if (!sysvid_fb) + { + sys_error("(video) unable to allocate frame buffer"); + break; + } + +#ifndef HAVE_LCD_COLOR + gbuf = sysmem_push(GREYBUFSIZE); + if (!gbuf) + { + sys_error("(video) unable to allocate buffer for greyscale functions"); + break; + } + + if (!grey_init(gbuf, GREYBUFSIZE, GREY_ON_COP, LCD_WIDTH, LCD_HEIGHT, NULL)) + { + sys_error("(video) not enough memory to initialise greyscale functions"); + break; + } +#endif /* ndef HAVE_LCD_COLOR */ + + success = true; + } while (false); + + if (!success) + { +#ifndef HAVE_LCD_COLOR + sysmem_pop(gbuf); +#endif + sysmem_pop(sysvid_fb); + return false; + } + +#if (LCD_HEIGHT < SYSVID_HEIGHT) + calculateRowsToSkip(); +#endif +#if (LCD_WIDTH < SYSVID_WIDTH) + calculateColumnsToSkip(); +#endif + +#if LCD_DEPTH > 1 + rb->lcd_set_backdrop(NULL); +#endif + /* Turn off backlight timeout */ + backlight_ignore_timeout(); + + rb->lcd_set_foreground(LCD_WHITE); + rb->lcd_set_background(LCD_BLACK); + rb->lcd_clear_display(); + +#ifdef HAVE_LCD_COLOR + rb->lcd_update(); +#else + /* switch on greyscale overlay */ + grey_show(true); +#endif /* HAVE_LCD_COLOR */ + + isVideoInitialised = true; + IFDEBUG_VIDEO(sys_printf("xrick/video: ready\n");); + return true; +} + +/* + * Shutdown video + */ +void sysvid_shutdown(void) +{ + if (!isVideoInitialised) + { + return; + } + +#ifndef HAVE_LCD_COLOR + grey_show(false); + grey_release(); + + sysmem_pop(gbuf); +#endif /* ndef HAVE_LCD_COLOR */ + sysmem_pop(sysvid_fb); + + /* Turn on backlight timeout (revert to settings) */ + backlight_use_settings(); + + isVideoInitialised = false; + IFDEBUG_VIDEO(sys_printf("xrick/video: stop\n");); +} + +/* eof */ diff --git a/apps/plugins/xrick/util.c b/apps/plugins/xrick/util.c new file mode 100644 index 0000000000..8926a00e5d --- /dev/null +++ b/apps/plugins/xrick/util.c @@ -0,0 +1,230 @@ +/* + * xrick/util.c + * + * Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net). + * Copyright (C) 2008-2014 Pierluigi Vicinanza. + * All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#include "xrick/util.h" + +#include "xrick/config.h" +#include "xrick/game.h" +#include "xrick/ents.h" +#include "xrick/e_rick.h" +#include "xrick/maps.h" +#include "xrick/system/system.h" + +#include /* memcpy */ + +/* + * Full box test. + * + * ASM 1199 + * + * e: entity to test against. + * x,y: coordinates to test. + * ret: true/(x,y) is within e's space, false/not. + */ +bool +u_fboxtest(U8 e, S16 x, S16 y) +{ + if (ent_ents[e].x >= x || + ent_ents[e].x + ent_ents[e].w < x || + ent_ents[e].y >= y || + ent_ents[e].y + ent_ents[e].h < y) + return false; + else + return true; +} + + + + +/* + * Box test (then whole e2 is checked agains the center of e1). + * + * ASM 113E + * + * e1: entity to test against (corresponds to DI in asm code). + * e2: entity to test (corresponds to SI in asm code). + * ret: true/intersect, false/not. + */ +bool +u_boxtest(U8 e1, U8 e2) +{ + /* rick is special (may be crawling) */ + if (e1 == E_RICK_NO) + return e_rick_boxtest(e2); + + /* + * entity 1: x+0x05 to x+0x011, y to y+0x14 + * entity 2: x to x+ .w, y to y+ .h + */ + if (ent_ents[e1].x + 0x11 < ent_ents[e2].x || + ent_ents[e1].x + 0x05 > ent_ents[e2].x + ent_ents[e2].w || + ent_ents[e1].y + 0x14 < ent_ents[e2].y || + ent_ents[e1].y > ent_ents[e2].y + ent_ents[e2].h - 1) + return false; + else + return true; +} + + +/* + * Compute the environment flag. + * + * ASM 0FBC if !crawl, else 103E + * + * x, y: coordinates where to compute the environment flag + * crawl: is rick crawling? + * rc0: anything CHANGED to the environment flag for crawling (6DBA) + * rc1: anything CHANGED to the environment flag (6DAD) + */ +void +u_envtest(S16 x, S16 y, bool crawl, U8 *rc0, U8 *rc1) +{ + U8 i, xx; + + /* prepare for ent #0 test */ + ent_ents[ENT_ENTSNUM].x = x; + ent_ents[ENT_ENTSNUM].y = y; + + i = 1; + if (!crawl) i++; + if (y & 0x0004) i++; + + x += 4; + xx = (U8)x; /* FIXME? */ + + x = x >> 3; /* from pixels to tiles */ + y = y >> 3; /* from pixels to tiles */ + + *rc0 = *rc1 = 0; + + if (xx & 0x07) { /* tiles columns alignment */ + if (crawl) { + *rc0 |= (map_eflg[map_map[y][x]] & + (MAP_EFLG_VERT|MAP_EFLG_SOLID|MAP_EFLG_SPAD|MAP_EFLG_WAYUP)); + *rc0 |= (map_eflg[map_map[y][x + 1]] & + (MAP_EFLG_VERT|MAP_EFLG_SOLID|MAP_EFLG_SPAD|MAP_EFLG_WAYUP)); + *rc0 |= (map_eflg[map_map[y][x + 2]] & + (MAP_EFLG_VERT|MAP_EFLG_SOLID|MAP_EFLG_SPAD|MAP_EFLG_WAYUP)); + y++; + } + do { + *rc1 |= (map_eflg[map_map[y][x]] & + (MAP_EFLG_SOLID|MAP_EFLG_SPAD|MAP_EFLG_FGND| + MAP_EFLG_LETHAL|MAP_EFLG_01)); + *rc1 |= (map_eflg[map_map[y][x + 1]] & + (MAP_EFLG_SOLID|MAP_EFLG_SPAD|MAP_EFLG_FGND| + MAP_EFLG_LETHAL|MAP_EFLG_CLIMB|MAP_EFLG_01)); + *rc1 |= (map_eflg[map_map[y][x + 2]] & + (MAP_EFLG_SOLID|MAP_EFLG_SPAD|MAP_EFLG_FGND| + MAP_EFLG_LETHAL|MAP_EFLG_01)); + y++; + } while (--i > 0); + + *rc1 |= (map_eflg[map_map[y][x]] & + (MAP_EFLG_SOLID|MAP_EFLG_SPAD|MAP_EFLG_WAYUP|MAP_EFLG_FGND| + MAP_EFLG_LETHAL|MAP_EFLG_01)); + *rc1 |= (map_eflg[map_map[y][x + 1]]); + *rc1 |= (map_eflg[map_map[y][x + 2]] & + (MAP_EFLG_SOLID|MAP_EFLG_SPAD|MAP_EFLG_WAYUP|MAP_EFLG_FGND| + MAP_EFLG_LETHAL|MAP_EFLG_01)); + } + else { + if (crawl) { + *rc0 |= (map_eflg[map_map[y][x]] & + (MAP_EFLG_VERT|MAP_EFLG_SOLID|MAP_EFLG_SPAD|MAP_EFLG_WAYUP)); + *rc0 |= (map_eflg[map_map[y][x + 1]] & + (MAP_EFLG_VERT|MAP_EFLG_SOLID|MAP_EFLG_SPAD|MAP_EFLG_WAYUP)); + y++; + } + do { + *rc1 |= (map_eflg[map_map[y][x]] & + (MAP_EFLG_SOLID|MAP_EFLG_SPAD|MAP_EFLG_FGND| + MAP_EFLG_LETHAL|MAP_EFLG_CLIMB|MAP_EFLG_01)); + *rc1 |= (map_eflg[map_map[y][x + 1]] & + (MAP_EFLG_SOLID|MAP_EFLG_SPAD|MAP_EFLG_FGND| + MAP_EFLG_LETHAL|MAP_EFLG_CLIMB|MAP_EFLG_01)); + y++; + } while (--i > 0); + + *rc1 |= (map_eflg[map_map[y][x]]); + *rc1 |= (map_eflg[map_map[y][x + 1]]); + } + + /* + * If not lethal yet, and there's an entity on slot zero, and (x,y) + * boxtests this entity, then raise SOLID flag. This is how we make + * sure that no entity can move over the entity that is on slot zero. + * + * Beware! When game_cheat2 is set, this means that a block can + * move over rick without killing him -- but then rick is trapped + * because the block is solid. + */ + if (!(*rc1 & MAP_EFLG_LETHAL) + && ent_ents[0].n + && u_boxtest(ENT_ENTSNUM, 0)) { + *rc1 |= MAP_EFLG_SOLID; + } + + /* When game_cheat2 is set, the environment can not be lethal. */ +#ifdef ENABLE_CHEATS + if (game_cheat2) *rc1 &= ~MAP_EFLG_LETHAL; +#endif +} + + +/* + * Check if x,y is within e trigger box. + * + * ASM 126F + * return: false if not in box, true if in box. + */ +bool +u_trigbox(U8 e, S16 x, S16 y) +{ + U16 xmax, ymax; + + xmax = ent_ents[e].trig_x + (ent_entdata[ent_ents[e].n & 0x7F].trig_w << 3); + ymax = ent_ents[e].trig_y + (ent_entdata[ent_ents[e].n & 0x7F].trig_h << 3); + + if (xmax > 0xFF) xmax = 0xFF; + + if (x <= ent_ents[e].trig_x || x > xmax || + y <= ent_ents[e].trig_y || y > ymax) + return false; + else + return true; +} + +/* + * Custom implementation of strdup function + */ +char * +u_strdup(const char *sourceStr) +{ + char *destStr; + size_t length; + + length = sys_strlen(sourceStr) + 1; + destStr = sysmem_push(length); + if (!destStr) + { + return NULL; + } + memcpy(destStr, sourceStr, length); + return destStr; +} + + +/* eof */ diff --git a/apps/plugins/xrick/util.h b/apps/plugins/xrick/util.h new file mode 100644 index 0000000000..6a455ba0f6 --- /dev/null +++ b/apps/plugins/xrick/util.h @@ -0,0 +1,29 @@ +/* + * xrick/util.h + * + * Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net). + * Copyright (C) 2008-2014 Pierluigi Vicinanza. + * All rights reserved. + * + * The use and distribution terms for this software are contained in the file + * named README, which can be found in the root of this distribution. By + * using this software in any fashion, you are agreeing to be bound by the + * terms of this license. + * + * You must not remove this notice, or any other, from this software. + */ + +#ifndef _UTIL_H +#define _UTIL_H + +#include "xrick/system/basic_types.h" + +extern void u_envtest(S16, S16, bool, U8 *, U8 *); +extern bool u_boxtest(U8, U8); +extern bool u_fboxtest(U8, S16, S16); +extern bool u_trigbox(U8, S16, S16); +extern char * u_strdup(const char *); + +#endif /* ndef _UTIL_H */ + +/* eof */ diff --git a/apps/plugins/xrick/xrick.make b/apps/plugins/xrick/xrick.make new file mode 100644 index 0000000000..26406a957d --- /dev/null +++ b/apps/plugins/xrick/xrick.make @@ -0,0 +1,31 @@ +# __________ __ ___. +# Open \______ \ ____ ____ | | _\_ |__ _______ ___ +# Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ / +# Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < < +# Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \ +# \/ \/ \/ \/ \/ +# $Id$ +# + +XRICKSRCDIR := $(APPSDIR)/plugins/xrick +XRICKBUILDDIR := $(BUILDDIR)/apps/plugins/xrick + +INCLUDES += -I$(XRICKSRCDIR)../ \ + -I$(XRICKSRCDIR)/3rd_party + +ROCKS += $(XRICKBUILDDIR)/xrick.rock + +XRICK_SRC := $(call preprocess, $(XRICKSRCDIR)/SOURCES) +XRICK_OBJ := $(call c2obj, $(XRICK_SRC)) + +# add source files to OTHER_SRC to get automatic dependencies +OTHER_SRC += $(XRICK_SRC) + +XRICKCFLAGS = $(PLUGINFLAGS) -std=gnu99 -O2 + +$(XRICKBUILDDIR)/xrick.rock: $(XRICK_OBJ) + +# new rule needed to use extra compile flags +$(XRICKBUILDDIR)/%.o: $(XRICKSRCDIR)/%.c + $(SILENT)mkdir -p $(dir $@) + $(call PRINTS,CC $(subst $(ROOTDIR)/,,$<))$(CC) $(XRICKCFLAGS) -c $< -o $@ diff --git a/docs/CREDITS b/docs/CREDITS index fba9aed0d3..2fd7b35537 100644 --- a/docs/CREDITS +++ b/docs/CREDITS @@ -8,7 +8,7 @@ People that have contributed to the project, one way or another. Friends! -Björn Stenberg +Bjrn Stenberg Linus Nielsen Feltzing Andy Choi Andrew Jamieson @@ -20,17 +20,17 @@ Gary Czvitkovicz Stuart Martin Felix Arends Ulf Ralberg -David Härdeman +David Hrdeman Thomas Saeys Grant Wier -Julien Labruyére +Julien Labruyre Nicolas Sauzede Robert Hak Dave Chapman Stefan Meyer Eric Linenberg Tom Cvitan -Magnus Öman +Magnus man Jerome Kuptz Julien Boissinot Nuutti Kotivuori @@ -59,14 +59,14 @@ Kjell Ericson Jim Hagani Ludovic Lange Mike Holden -Simon Elén +Simon Eln Matthew P. O'Reilly -Christian Schönberger +Christian Schnberger Henrik Backe Craig Sather -José Maria Garcia-Valdecasas Bernal +Jos Maria Garcia-Valdecasas Bernal Stevie Oh -Jörg Hohensohn +Jrg Hohensohn Dave Jones Thomas Paul Diffenbach Roland Kletzing @@ -96,7 +96,7 @@ Jiri Jurecek Jacob Erlbeck Jean-Philippe Bernardy Dave Hooper -Jonas Häggqvist +Jonas Hggqvist Thom Johansen Rinat Zakirov Manuel Dejonghe @@ -105,12 +105,12 @@ Michiel van der Kolk Tony Motakis Andy Young Alexandre Bourget -Richard S. La Charité III +Richard S. La Charit III Christian Gmeiner Tomas Salfischberger Miika Pekkarinen Tapio Karppinen -Richard Ottó O'Brien +Richard Ott O'Brien Luca Burelli Alessio Lenzi David Bryant @@ -126,9 +126,9 @@ Hristo Kovachev Sander Sweers Antonius Hellman Ryan Jackson -Per Holmäng +Per Holmng Frederic Devernay -José M. Fandiño +Jos M. Fandio Gadi Cohen Naftali Goldstein David Dent @@ -171,19 +171,19 @@ Mikael Magnusson Dominik Wenger Henrico Witvliet Andrew Scott -Miguel A. Arévalo +Miguel A. Arvalo Aaron F. Gonzalez Aleksey Kozyulin Jani Kinnunen Rui Marinho Alun Thomas -Nils Wallménius +Nils Wallmnius Naoaki Okazaki Will Dyson Matthias Mohr Christian Marg Eli Sherer -Fredrik Öhrn +Fredrik hrn Nicolas Pennequin Ralf Herz Michael DiFebbo @@ -204,18 +204,18 @@ Frederik Vestre Wenbin Leo Tom Evans Ewan Davies -Frédéric François -Marc-André Moreau +Frdric Franois +Marc-Andr Moreau Ioannis Koutoulakis Alistair Marshall Karl Ove Hufthammer -Víctor Zabalza +Vctor Zabalza Ulrich Pegelow Andreas Mattsson Daniel Ankers Paul Louden Rainer Sinsch -Plácido Revilla +Plcido Revilla Michael Sevakis Lukas Sabota Emanuel Zephir @@ -243,13 +243,13 @@ Robert Kukla David Quesada Jared Stafford Martin Hensel -Stéphane Doyon +Stphane Doyon Austin Appel Andre Smith Travis Hyyppa Ian Webber Pavel Gnelitsa -Lutz Böhne +Lutz Bhne Will Robertson Robert Carboneau Ye Wei @@ -259,13 +259,13 @@ Chris Taylor Tobias Langhoff Steve Gotthardt Greg White -Mattieu Favréaux +Mattieu Favraux Malcolm Tyrrell Piotr Jafiszow Gary Allen John BouAntoun Tomasz Mon -Jakub Matoušek +Jakub Matou?ek Albert Veli Chris Dohan Takashi Obara @@ -276,7 +276,7 @@ Sean Morrisey Shay Green Nick Vanderweit Simon Menzel -Timo Horstschäfer +Timo Horstschfer Jacco Koning Chris Ham Jose Ramon Garcia @@ -335,7 +335,7 @@ Alexander Eickhoff Ken Fazzone David Bishop Hein-Pieter van Braam -Przemysław Hołubowski +Przemys?aw Ho?ubowski Stepan Moskovchenko John S. Gwynne Brian J. Morey @@ -343,12 +343,12 @@ Stijn Hisken Bertrik Sikken Karim Boucher James Espinoza -Franz Rühmland +Franz Rhmland Jordan Anderson Maurus Cuelenaere Chris Allegretta Alastair S -Martin Crkovský +Martin Crkovsk Ariya Hidayat Jonas Hurrelmann Lee Kang Hyuk @@ -356,7 +356,7 @@ Clemens Werther Robert Menes Henri Valta Melba Sitjar -Mehmet Ş. Çatalbaş +Mehmet ?. atalba? Scott Tinman Alexander Kuzmenkov Thomas Martitz @@ -366,7 +366,7 @@ Apoorva Mahajan Vuong Minh Hiep Mateusz Kubica Frank Gevaerts -Chelo Sacristán +Chelo Sacristn Sascha Wolf Nickolay Jordanov Johannes Voggenthaler @@ -380,7 +380,7 @@ Ivan Pesic Marcel Barbulescu Phil Light Rob Purchase -Andreas Müller +Andreas Mller Christopher Williams Martin Ritter Justin Hannigan @@ -409,39 +409,39 @@ Shunsuke Shimizu Tadayuki Nishizono Jun Gu Daniel Weck -Clément Pit-Claudel +Clment Pit-Claudel Jelle Geerts -Tadeusz Pyś +Tadeusz Py? Rostislav Chekan Florin Popescu Volker Mische Vitja Makarov Francisco Vila Christian Lees -Rafaël Carré +Rafal Carr Denes Balatoni Roy Wallace Eric Lassauge -François Dinel +Franois Dinel Francesco Rigoni -Joël Puik +Jol Puik Klaas Bosteels Teruaki Kawashima -Marcin Łukasik +Marcin ?ukasik Le Jin Alex Bennee -Stéphane Quertinmont +Stphane Quertinmont Bartosz Fabianowski Adam Hogan Andrew Mahone Anton Veretenenko Vicente Ibarra -Rui Araújo +Rui Arajo Brian Cloutier Olivier Barbut Yoshihisa Uchida Sanggon Lee -Kaspar Rothenfußer +Kaspar Rothenfuer Ryan Press Craig Elliott Kenderes Tamas @@ -453,7 +453,7 @@ Gareth Schakel Brian Sutherland Sam Bouwer Johannes Linke -Michaël Burtin +Michal Burtin Sasha Khamkov Kai Posadowsky Jack Halpin @@ -504,14 +504,14 @@ Yann Muller Sascha Wilde Fred Bauer Simon Rothen -Pavel Rzehák +Pavel Rzehk Diego Herranz Viktor Varga Juliusz Chroboczek Christian Beier Giovanni Zilli Shiloh Hawley -Peter Lecký +Peter Leck Wilfred Hughes Laurent Gautier Simon Zhukovsky @@ -528,36 +528,36 @@ Mark Borgerding Tobias Diedrich Andrew Engelbrecht Kevin Schoedel -Jens Theeß +Jens Thee Alexey Nemtsev Pascal Below Danny Attar Philipp Stephani -Tore Johnny Bråtveit +Tore Johnny Brtveit Marcin Bukat Andrew Rodland Luca Leonardo Scorcia Gerhard Zintel -Adrián Cereto Massagué +Adrin Cereto Massagu Chris Savery -Raphaël Jakse +Raphal Jakse Wincent Balin Aaron Rothbaum Nejc Lotric -Hinrik Örn Sigurðsson +Hinrik rn Sigursson Stephen Carroll Joe Balough -Jérôme Heil +Jrme Heil Tim Graf -Martin Sägmüller +Martin Sgmller Joshua Hulst Pierre-Yves Roosens Hayden Pearce Rodrigo Barretto Daniel Rigby Alexey Polkhirev -István Nagy -Wojciech Leśniak +Istvn Nagy +Wojciech Le?niak Tuomas Airaksinen Calvin Walden Michael Gentry @@ -572,12 +572,12 @@ Craig Mann William Peters Li Jie Cristina Talpiga -Ştefan Moisei +?tefan Moisei Alexander Meshcheryakov Ryan Sawhill Thomas Jarosch Will Sowerbutts -Łukasz Stelmach +?ukasz Stelmach Gabriel Maia Robert Horn Ante Maretic @@ -586,12 +586,12 @@ Uwe Wiebach Mikhail Titov Dave Slusher Jean-Marie Moraux -Ismael Castiñeira Álvarez -Mārtiņš Šimis +Ismael Castieira lvarez +M?rti?? ?imis Huan Zhang Leif Andersen Sergiu Rotaru -Noé Lojkine +No Lojkine Ophir Lojkine Stephan Grossklass John Morris @@ -616,7 +616,7 @@ Artur Juraszek Wieland Hoffmann Nathan Korth Igor Petelin -Cástor Muñoz +Cstor Muoz Albert Barca Fukuda Takafumi Dimitar Dimitrov @@ -649,8 +649,8 @@ Semyon Zhukovsky Kostadin Kolev Jordi Prenafeta Tiago Medeiros -Udo Schläpfer -Åka Sikrom +Udo Schlpfer +ka Sikrom Thomas White Karl Huber Adam Sampson @@ -685,15 +685,16 @@ Martin Buck Stefan Ott David Chionne Wilfried Winkler -Johannes König +Johannes Knig Alexander Drammen Kei Miyamoto James D. Smith Howard Richardson +Aurlien Coudurier Sylvain Saubier Adrián Tinoco Boris Kovačević -Stéphane Moutard-Martin +Stphane Moutard-Martin Rune Pade Michael Rey Yuxuan Shui @@ -720,6 +721,7 @@ JJ Style Jerry Chapman Leander Lismond Eren Akpolat +Pierluigi Vicinanza The libmad team The wavpack team @@ -761,3 +763,4 @@ The bsdiff team The libtomcrypt team The microtar team (rxi and others) The UnifontEX and GNU Unifont teams +The XRick team diff --git a/manual/plugins/images/ss-xrick-220x176x16.png b/manual/plugins/images/ss-xrick-220x176x16.png new file mode 100755 index 0000000000..5fb3a74a2f Binary files /dev/null and b/manual/plugins/images/ss-xrick-220x176x16.png differ diff --git a/manual/plugins/images/ss-xrick-240x320x16.png b/manual/plugins/images/ss-xrick-240x320x16.png new file mode 100755 index 0000000000..2d86387b15 Binary files /dev/null and b/manual/plugins/images/ss-xrick-240x320x16.png differ diff --git a/manual/plugins/images/ss-xrick-320x240x16.png b/manual/plugins/images/ss-xrick-320x240x16.png new file mode 100755 index 0000000000..7739445c35 Binary files /dev/null and b/manual/plugins/images/ss-xrick-320x240x16.png differ diff --git a/manual/plugins/main.tex b/manual/plugins/main.tex index c04299ca49..b2274f18af 100644 --- a/manual/plugins/main.tex +++ b/manual/plugins/main.tex @@ -111,8 +111,13 @@ text files% \input{plugins/xobox.tex} +\opt{lcd_non-mono}{\input{plugins/xrick.tex}} + \opt{lcd_color}{\input{plugins/xworld.tex}} + + + \section{Demos} \input{plugins/bounce.tex} diff --git a/manual/plugins/xrick.tex b/manual/plugins/xrick.tex new file mode 100755 index 0000000000..3aac6e08c8 --- /dev/null +++ b/manual/plugins/xrick.tex @@ -0,0 +1,107 @@ +% $Id$ % +\subsection{xrick} +\screenshot{plugins/images/ss-xrick}{xrick}{img:xrick} +xrick is a clone of the platform game +\emph{'Rick Dangerous'} +(\url{http://en.wikipedia.org/wiki/Rick_Dangerous}), +originally written by 'BigOrno' +(\url{http://www.bigorno.net/xrick/}), +modified and ported to Rockbox by Pierluigi Vicinanza +(\url{https://github.com/pierluigi-vicinanza/xrick}). + +Walk through the maps, avoid traps, kill the Bad Guys... and +try to stay alive long enough to accomplish your mission! + +Rick can fire bullets, lay sticks of dynamite, walk, crawl, +climb, and also poke walls or Bad Guys with his stick. +Poking walls can trigger traps, open doors, etc. although +sometimes a dynamite stick or a bullet is needed. +Go figure. + +\subsubsection{Getting started} +For the game to run you need \fname{.dat} game files located in +\fname{/.rockbox/xrick} on your \dap. +Create the directory and extract xrick \fname{data.zip} archive into it. +The needed files can be found at +\url{https://github.com/pierluigi-vicinanza/xrick/blob/master/game/data.zip}. + +\subsubsection{Controls} +By holding down \emph{Fire} and pressing \emph{Left} or \emph{Right}, +you can poke a wall (or anything else) with your stick. +By holding down \emph{Fire} and pressing \emph{Down}, you can lay a stick of dynamite. +By holding down \emph{Fire} and pressing \emph{Up}, you can fire a bullet. + +Throughout the game, use these buttons to control Rick: + +\begin{btnmap} +% + \opt{iriverh300}{\ButtonUp/\ButtonRec} + \opt{fuzeplus}{\ButtonUp} + \opt{ipodvideo}{\ButtonMenu} + \nopt{iriverh300,fuzeplus,ipodvideo}{\PluginUp} + \opt{HAVEREMOTEKEYMAP}{& } + & Jump or Climb Up\\ +% + \opt{fuzeplus}{\ButtonPlay & Jump Right or Climb Up and Right\\} +% + \opt{fuzeplus}{\ButtonBack & Jump Left or Climb Up and Left\\} +% + \opt{iriverh300}{\ButtonDown/\ButtonMode} + \opt{fuzeplus}{\ButtonDown} + \opt{ipodvideo}{\ButtonPlay} + \nopt{iriverh300,fuzeplus,ipodvideo}{\PluginDown} + \opt{HAVEREMOTEKEYMAP}{& } + & Crouch or Climb Down\\ +% + \opt{fuzeplus}{\ButtonBottomRight & Crouch and Move Right or Climb Down and Right\\} +% + \opt{fuzeplus}{\ButtonBottomLeft & Crouch and Move Left or Climb Down and Left\\} +% + \opt{iriverh300,fuzeplus,ipodvideo}{\ButtonLeft} + \nopt{iriverh300,fuzeplus,ipodvideo}{\PluginLeft} + \opt{HAVEREMOTEKEYMAP}{& } + & Move Left\\ +% + \opt{iriverh300,fuzeplus,ipodvideo}{\ButtonRight} + \nopt{iriverh300,fuzeplus,ipodvideo}{\PluginRight} + \opt{HAVEREMOTEKEYMAP}{& } + & Move Right\\ +% + \opt{iriverh300}{\ButtonOn} + \opt{fuzeplus}{\ButtonVolDown} + \opt{ipodvideo}{\ButtonSelect} + \nopt{iriverh300,fuzeplus,ipodvideo}{\PluginSelect} + + \opt{HAVEREMOTEKEYMAP}{& } + & Fire\\ +% + \opt{iriverh300}{\ButtonSelect} + \opt{fuzeplus}{\ButtonVolUp} + \opt{ipodvideo}{\ButtonScrollBack} + \nopt{iriverh300,fuzeplus,ipodvideo}{\PluginCancel} + \opt{HAVEREMOTEKEYMAP}{& } + & Pause\\ +% + \opt{iriverh300}{\ButtonOff} + \opt{fuzeplus}{\ButtonPower} + \opt{ipodvideo}{\ButtonScrollFwd} + \nopt{iriverh300,fuzeplus,ipodvideo}{\PluginExit} + \opt{hold_button}{/\ButtonHold} + \opt{HAVEREMOTEKEYMAP}{& } + & Menu\\ +% +\end{btnmap} + +\subsubsection{Menu} +\begin{description} + \item[Resume Game. ] Resume the game + \item[Restart Game. ] Restart the game + \item[Cheat Settings. ] This menu has the following options: + + \emph{Enable Unlimited Lives/Ammo Mode. } Toggle trainer mode (always six bullets, six sticks, six Rick).\\ + \emph{Enable Never Die Mode. } Toggle 'never die' mode (nothing can kill Rick). Use with care. + Although it lets you walk through Bad Guys unharmed, it can produce strange results.\\ + \emph{Enable Expose Mode. } Toggle 'expose' mode (see all entities).%\\ + + \item[Quit. ] Quit the game +\end{description} diff --git a/utils/rbutilqt/base/playerbuildinfo.cpp b/utils/rbutilqt/base/playerbuildinfo.cpp index c76abc4ffe..7edb7f750c 100644 --- a/utils/rbutilqt/base/playerbuildinfo.cpp +++ b/utils/rbutilqt/base/playerbuildinfo.cpp @@ -49,6 +49,7 @@ const static struct { { PlayerBuildInfo::PuzzFontsUrl, "other/puzzfonts_url" }, { PlayerBuildInfo::QuakeUrl, "other/quake_url" }, { PlayerBuildInfo::Wolf3DUrl, "other/wolf3d_url" }, + { PlayerBuildInfo::XRickUrl, "other/xrick_url" }, { PlayerBuildInfo::XWorldUrl, "other/xworld_url" }, { PlayerBuildInfo::MidiPatchsetUrl, "other/patcheset_url" }, }; diff --git a/utils/rbutilqt/base/playerbuildinfo.h b/utils/rbutilqt/base/playerbuildinfo.h index 85fc2ac6dc..38f6662e09 100644 --- a/utils/rbutilqt/base/playerbuildinfo.h +++ b/utils/rbutilqt/base/playerbuildinfo.h @@ -53,6 +53,7 @@ public: QuakeUrl, Wolf3DUrl, XWorldUrl, + XRickUrl, MidiPatchsetUrl, }; enum DeviceInfo { diff --git a/utils/rbutilqt/gui/selectiveinstallwidget.cpp b/utils/rbutilqt/gui/selectiveinstallwidget.cpp index 28dd50d482..639e03308a 100644 --- a/utils/rbutilqt/gui/selectiveinstallwidget.cpp +++ b/utils/rbutilqt/gui/selectiveinstallwidget.cpp @@ -610,6 +610,7 @@ static const struct { { "Quake", "games/quake.rock", PlayerBuildInfo::QuakeUrl }, { "Puzzles fonts", "games/sgt-blackbox.rock", PlayerBuildInfo::PuzzFontsUrl }, { "Wolf3D", "games/wolf3d.rock", PlayerBuildInfo::Wolf3DUrl }, + { "XRick", "games/xrick.rock", PlayerBuildInfo::XRickUrl }, { "XWorld", "games/xworld.rock", PlayerBuildInfo::XWorldUrl }, { "MIDI Patchset", "viewers/midi.rock", PlayerBuildInfo::MidiPatchsetUrl }, }; diff --git a/utils/rbutilqt/rbutil.ini b/utils/rbutilqt/rbutil.ini index f75cfe015e..bc41ff48b0 100644 --- a/utils/rbutilqt/rbutil.ini +++ b/utils/rbutilqt/rbutil.ini @@ -14,6 +14,7 @@ quake_url=https://download.rockbox.org/useful/quake.zip puzzfonts_url=https://download.rockbox.org/useful/sgt-fonts.zip wolf3d_url=https://download.rockbox.org/useful/wolf3d.zip xworld_url=https://download.rockbox.org/useful/xworld.zip +xrick_url=https://download.rockbox.org/useful/xrick-data.zip rbutil_url=https://download.rockbox.org/rbutil/ [bootloader] -- cgit v1.2.3