mirror of
https://github.com/zeldaret/mm.git
synced 2024-11-22 20:39:49 +00:00
Build Sync (#1600)
* Rename outputs * Makefile target renames * Add run target * yeet z64compress * venv * baserom_uncompressed -> baserom-decompressed * input rom name to baserom.z64 * Add BUILD_DIR makefile variable * Move built roms to build dir * Move baserom to baseroms folder * Add version to map file name * Makefile cleanup * Rename ldscript to include version * Multiversion build * n64-us version name * Remove venv as dependency of setup * Readme wording * extract_baserom.py suggestion * Readd checksums * Make .venv work with windows * missed an endif * Cleaner windows venv implementation * Remove duplciate process * Build process steps * Move make_options back * Fix schedule build directory * Fix schedule includes * Makefile NON_MATCHING check -> != 0 * OOT 1704 changes * Small cleanups * Missed 1 thing * UNSET -> SYMS * Update extract_baserom.py * dmadata.py * Small cleanup * dmadata_start * Format * dmadata files * Fix makefile comment * Jenkins report fix * extracted dir * Python dependencies order in readme
This commit is contained in:
parent
45ae63ccc5
commit
471d86f530
3
.gitignore
vendored
3
.gitignore
vendored
@ -10,6 +10,7 @@ __pycache__/
|
||||
CMakeLists.txt
|
||||
cmake-build-debug
|
||||
venv/
|
||||
.venv/
|
||||
tags
|
||||
|
||||
# Project-specific ignores
|
||||
@ -19,12 +20,14 @@ tags
|
||||
*.sra
|
||||
*.bin
|
||||
*.elf
|
||||
*.flash
|
||||
archive/
|
||||
build/
|
||||
baserom/
|
||||
decomp/
|
||||
asm/
|
||||
data/
|
||||
extracted/
|
||||
expected/
|
||||
nonmatchings/
|
||||
|
||||
|
41
Jenkinsfile
vendored
41
Jenkinsfile
vendored
@ -22,25 +22,18 @@ pipeline {
|
||||
}
|
||||
stage('Install Python dependencies') {
|
||||
steps {
|
||||
echo 'Installing Python dependencies'
|
||||
sh 'python3 -m venv .venv'
|
||||
sh '''. .venv/bin/activate
|
||||
python3 -m pip install -U -r requirements.txt
|
||||
python3 -m pip install -U GitPython
|
||||
'''
|
||||
sh 'bash -c "make -j venv"'
|
||||
}
|
||||
}
|
||||
stage('Copy ROM') {
|
||||
steps {
|
||||
echo 'Setting up ROM...'
|
||||
sh 'cp /usr/local/etc/roms/mm.us.rev1.z64 baserom.mm.us.rev1.z64'
|
||||
sh 'cp /usr/local/etc/roms/mm.us.rev1.z64 baseroms/n64-us/baserom.z64'
|
||||
}
|
||||
}
|
||||
stage('Setup') {
|
||||
steps {
|
||||
sh '''. .venv/bin/activate
|
||||
bash -c "make -j setup 2> >(tee tools/warnings_count/warnings_setup_new.txt)"
|
||||
'''
|
||||
sh 'bash -c "make -j setup 2> >(tee tools/warnings_count/warnings_setup_new.txt)"'
|
||||
}
|
||||
}
|
||||
stage('Check setup warnings') {
|
||||
@ -50,9 +43,7 @@ pipeline {
|
||||
}
|
||||
stage('Assets') {
|
||||
steps {
|
||||
sh '''. .venv/bin/activate
|
||||
bash -c "make -j assets 2> >(tee tools/warnings_count/warnings_assets_new.txt)"
|
||||
'''
|
||||
sh 'bash -c "make -j assets 2> >(tee tools/warnings_count/warnings_assets_new.txt)"'
|
||||
}
|
||||
}
|
||||
stage('Check assets warnings') {
|
||||
@ -62,9 +53,7 @@ pipeline {
|
||||
}
|
||||
stage('Disasm') {
|
||||
steps {
|
||||
sh '''. .venv/bin/activate
|
||||
bash -c "make -j disasm 2> >(tee tools/warnings_count/warnings_disasm_new.txt)"
|
||||
'''
|
||||
sh 'bash -c "make -j disasm 2> >(tee tools/warnings_count/warnings_disasm_new.txt)"'
|
||||
}
|
||||
}
|
||||
stage('Check disasm warnings') {
|
||||
@ -74,9 +63,7 @@ pipeline {
|
||||
}
|
||||
stage('Build') {
|
||||
steps {
|
||||
sh '''. .venv/bin/activate
|
||||
bash -c "make -j uncompressed 2> >(tee tools/warnings_count/warnings_build_new.txt)"
|
||||
'''
|
||||
sh 'bash -c "make -j rom 2> >(tee tools/warnings_count/warnings_build_new.txt)"'
|
||||
}
|
||||
}
|
||||
stage('Check build warnings') {
|
||||
@ -86,9 +73,7 @@ pipeline {
|
||||
}
|
||||
stage('Compress') {
|
||||
steps {
|
||||
sh '''. .venv/bin/activate
|
||||
bash -c "make -j compressed 2> >(tee tools/warnings_count/warnings_compress_new.txt)"
|
||||
'''
|
||||
sh 'bash -c "make -j compress 2> >(tee tools/warnings_count/warnings_compress_new.txt)"'
|
||||
}
|
||||
}
|
||||
stage('Check compress warnings') {
|
||||
@ -102,15 +87,9 @@ pipeline {
|
||||
}
|
||||
steps {
|
||||
sh 'mkdir reports'
|
||||
sh '''. .venv/bin/activate
|
||||
python3 ./tools/progress.py csv >> reports/progress-mm-nonmatching.csv
|
||||
'''
|
||||
sh '''. .venv/bin/activate
|
||||
python3 ./tools/progress.py csv -m >> reports/progress-mm-matching.csv
|
||||
'''
|
||||
sh '''. .venv/bin/activate
|
||||
python3 ./tools/progress.py shield-json > reports/progress-mm-shield.json
|
||||
'''
|
||||
sh '.venv/bin/python3 ./tools/progress.py csv >> reports/progress-mm-nonmatching.csv'
|
||||
sh '.venv/bin/python3 ./tools/progress.py csv -m >> reports/progress-mm-matching.csv'
|
||||
sh '.venv/bin/python3 ./tools/progress.py shield-json > reports/progress-mm-shield.json'
|
||||
stash includes: 'reports/*', name: 'reports'
|
||||
}
|
||||
}
|
||||
|
344
Makefile
344
Makefile
@ -5,8 +5,35 @@
|
||||
|
||||
MAKEFLAGS += --no-builtin-rules
|
||||
|
||||
# Ensure the build fails if a piped command fails
|
||||
SHELL = /bin/bash
|
||||
.SHELLFLAGS = -o pipefail -c
|
||||
|
||||
# OS Detection
|
||||
ifeq ($(OS),Windows_NT)
|
||||
DETECTED_OS = windows
|
||||
MAKE = make
|
||||
VENV_BIN_DIR = Scripts
|
||||
else
|
||||
UNAME_S := $(shell uname -s)
|
||||
ifeq ($(UNAME_S),Linux)
|
||||
DETECTED_OS = linux
|
||||
MAKE = make
|
||||
VENV_BIN_DIR = bin
|
||||
endif
|
||||
ifeq ($(UNAME_S),Darwin)
|
||||
DETECTED_OS = macos
|
||||
MAKE = gmake
|
||||
VENV_BIN_DIR = bin
|
||||
endif
|
||||
endif
|
||||
|
||||
|
||||
#### Defaults ####
|
||||
|
||||
# Target game version. Currently only the following version is supported:
|
||||
# n64-us N64 USA (default)
|
||||
VERSION ?= n64-us
|
||||
# If COMPARE is 1, check the output md5sum after building
|
||||
COMPARE ?= 1
|
||||
# If NON_MATCHING is 1, define the NON_MATCHING C flag when building
|
||||
@ -29,15 +56,20 @@ ASM_PROC_FORCE ?= 0
|
||||
N_THREADS ?= $(shell nproc)
|
||||
# MIPS toolchain prefix
|
||||
MIPS_BINUTILS_PREFIX ?= mips-linux-gnu-
|
||||
# Python virtual environment
|
||||
VENV ?= .venv
|
||||
# Python interpreter
|
||||
PYTHON ?= python3
|
||||
PYTHON ?= $(VENV)/$(VENV_BIN_DIR)/python3
|
||||
# Emulator w/ flags
|
||||
N64_EMULATOR ?=
|
||||
|
||||
|
||||
#### Setup ####
|
||||
|
||||
# Ensure the map file being created using English localization
|
||||
export LANG := C
|
||||
|
||||
ifeq ($(NON_MATCHING),1)
|
||||
ifneq ($(NON_MATCHING),0)
|
||||
CFLAGS := -DNON_MATCHING
|
||||
CPPFLAGS := -DNON_MATCHING
|
||||
COMPARE := 0
|
||||
@ -48,25 +80,19 @@ ifneq ($(FULL_DISASM), 0)
|
||||
DISASM_FLAGS += --all
|
||||
endif
|
||||
|
||||
PROJECT_DIR := $(dir $(realpath $(firstword $(MAKEFILE_LIST))))
|
||||
PROJECT_DIR := $(dir $(realpath $(firstword $(MAKEFILE_LIST))))
|
||||
|
||||
BASEROM_DIR := baseroms/$(VERSION)
|
||||
BUILD_DIR := build/$(VERSION)
|
||||
EXTRACTED_DIR := extracted/$(VERSION)
|
||||
|
||||
MAKE = make
|
||||
CPPFLAGS += -P
|
||||
|
||||
ifeq ($(OS),Windows_NT)
|
||||
DETECTED_OS=windows
|
||||
else
|
||||
UNAME_S := $(shell uname -s)
|
||||
ifeq ($(UNAME_S),Linux)
|
||||
DETECTED_OS=linux
|
||||
endif
|
||||
ifeq ($(UNAME_S),Darwin)
|
||||
DETECTED_OS=macos
|
||||
MAKE=gmake
|
||||
CPPFLAGS += -xc++
|
||||
endif
|
||||
ifeq ($(DETECTED_OS), macos)
|
||||
CPPFLAGS += -xc++
|
||||
endif
|
||||
|
||||
|
||||
#### Tools ####
|
||||
ifneq ($(shell type $(MIPS_BINUTILS_PREFIX)ld >/dev/null 2>/dev/null; echo $$?), 0)
|
||||
$(error Unable to find $(MIPS_BINUTILS_PREFIX)ld. Please install or build MIPS binutils, commonly mips-linux-gnu. (or set MIPS_BINUTILS_PREFIX if your MIPS binutils install uses another prefix))
|
||||
@ -87,19 +113,20 @@ ifeq ($(ORIG_COMPILER),1)
|
||||
CC_OLD = $(QEMU_IRIX) -L tools/ido5.3_compiler tools/ido5.3_compiler/usr/bin/cc
|
||||
endif
|
||||
|
||||
AS := $(MIPS_BINUTILS_PREFIX)as
|
||||
LD := $(MIPS_BINUTILS_PREFIX)ld
|
||||
OBJCOPY := $(MIPS_BINUTILS_PREFIX)objcopy
|
||||
OBJDUMP := $(MIPS_BINUTILS_PREFIX)objdump
|
||||
ASM_PROC := $(PYTHON) tools/asm-processor/build.py
|
||||
AS := $(MIPS_BINUTILS_PREFIX)as
|
||||
LD := $(MIPS_BINUTILS_PREFIX)ld
|
||||
NM := $(MIPS_BINUTILS_PREFIX)nm
|
||||
OBJCOPY := $(MIPS_BINUTILS_PREFIX)objcopy
|
||||
OBJDUMP := $(MIPS_BINUTILS_PREFIX)objdump
|
||||
|
||||
ASM_PROC := $(PYTHON) tools/asm-processor/build.py
|
||||
ASM_PROC_FLAGS := --input-enc=utf-8 --output-enc=euc-jp --convert-statics=global-with-filename
|
||||
|
||||
ifneq ($(ASM_PROC_FORCE), 0)
|
||||
ASM_PROC_FLAGS += --force
|
||||
ASM_PROC_FLAGS += --force
|
||||
endif
|
||||
|
||||
IINC := -Iinclude -Isrc -Iassets -Ibuild -I.
|
||||
IINC := -Iinclude -Isrc -Iassets -I$(BUILD_DIR) -I.
|
||||
|
||||
ifeq ($(KEEP_MDEBUG),0)
|
||||
RM_MDEBUG = $(OBJCOPY) --remove-section .mdebug $@
|
||||
@ -125,11 +152,15 @@ ZAPD := tools/ZAPD/ZAPD.out
|
||||
FADO := tools/fado/fado.elf
|
||||
MAKEYAR := $(PYTHON) tools/buildtools/makeyar.py
|
||||
CHECKSUMMER := $(PYTHON) tools/buildtools/checksummer.py
|
||||
SHIFTJIS_CONV := $(PYTHON) tools/shiftjis_conv.py
|
||||
SHIFTJIS_CONV := $(PYTHON) tools/buildtools/shiftjis_conv.py
|
||||
SCHC := $(PYTHON) tools/buildtools/schc.py
|
||||
|
||||
SCHC_FLAGS :=
|
||||
|
||||
# Command to replace path variables in the spec file. We can't use the C
|
||||
# preprocessor for this because it won't substitute inside string literals.
|
||||
SPEC_REPLACE_VARS := sed -e 's|$$(BUILD_DIR)|$(BUILD_DIR)|g'
|
||||
|
||||
OPTFLAGS := -O2 -g3
|
||||
ASFLAGS := -march=vr4300 -32 -Iinclude
|
||||
MIPS_VERSION := -mips2
|
||||
@ -156,23 +187,20 @@ else ifneq ($(RUN_CC_CHECK),0)
|
||||
CC_CHECK += -m32
|
||||
endif
|
||||
|
||||
# rom compression flags
|
||||
COMPFLAGS := --threads $(N_THREADS)
|
||||
ifneq ($(NON_MATCHING),1)
|
||||
COMPFLAGS += --matching
|
||||
endif
|
||||
|
||||
#### Files ####
|
||||
|
||||
# ROM image
|
||||
ROMC := mm.us.rev1.rom.z64
|
||||
ROM := $(ROMC:.rom.z64=.rom_uncompressed.z64)
|
||||
ELF := $(ROM:.z64=.elf)
|
||||
ROM := $(BUILD_DIR)/mm-$(VERSION).z64
|
||||
ROMC := $(ROM:.z64=-compressed.z64)
|
||||
ELF := $(ROM:.z64=.elf)
|
||||
MAP := $(ROM:.z64=.map)
|
||||
LDSCRIPT := $(ROM:.z64=.ld)
|
||||
# description of ROM segments
|
||||
SPEC := spec
|
||||
|
||||
# create asm directories
|
||||
$(shell mkdir -p asm data)
|
||||
$(shell mkdir -p asm data extracted)
|
||||
|
||||
SRC_DIRS := $(shell find src -type d)
|
||||
ASM_DIRS := $(shell find asm -type d -not -path "asm/non_matchings*") $(shell find data -type d)
|
||||
@ -183,117 +211,116 @@ ASSET_BIN_DIRS := $(shell find assets/* -type d -not -path "assets/xml*" -not -p
|
||||
ASSET_BIN_DIRS_C_FILES := $(shell find assets/* -type d -not -path "assets/xml*" -not -path "assets/code*" -not -path "assets/overlays*")
|
||||
|
||||
ASSET_FILES_BIN := $(foreach dir,$(ASSET_BIN_DIRS),$(wildcard $(dir)/*.bin))
|
||||
ASSET_FILES_OUT := $(foreach f,$(ASSET_FILES_BIN:.bin=.bin.inc.c),build/$f)
|
||||
ASSET_FILES_OUT := $(foreach f,$(ASSET_FILES_BIN:.bin=.bin.inc.c),$(BUILD_DIR)/$f)
|
||||
|
||||
TEXTURE_FILES_PNG := $(foreach dir,$(ASSET_BIN_DIRS),$(wildcard $(dir)/*.png))
|
||||
TEXTURE_FILES_JPG := $(foreach dir,$(ASSET_BIN_DIRS),$(wildcard $(dir)/*.jpg))
|
||||
TEXTURE_FILES_OUT := $(foreach f,$(TEXTURE_FILES_PNG:.png=.inc.c),build/$f) \
|
||||
$(foreach f,$(TEXTURE_FILES_JPG:.jpg=.jpg.inc.c),build/$f) \
|
||||
TEXTURE_FILES_OUT := $(foreach f,$(TEXTURE_FILES_PNG:.png=.inc.c),$(BUILD_DIR)/$f) \
|
||||
$(foreach f,$(TEXTURE_FILES_JPG:.jpg=.jpg.inc.c),$(BUILD_DIR)/$f) \
|
||||
|
||||
C_FILES := $(foreach dir,$(SRC_DIRS) $(ASSET_BIN_DIRS_C_FILES),$(wildcard $(dir)/*.c))
|
||||
S_FILES := $(shell grep -F "build/asm" spec | sed 's/.*build\/// ; s/\.o\".*/.s/') \
|
||||
$(shell grep -F "build/data" spec | sed 's/.*build\/// ; s/\.o\".*/.s/')
|
||||
S_FILES := $(shell grep -F "\$$(BUILD_DIR)/asm" spec | sed 's/.*$$(BUILD_DIR)\/// ; s/\.o\".*/.s/') \
|
||||
$(shell grep -F "\$$(BUILD_DIR)/data" spec | sed 's/.*$$(BUILD_DIR)\/// ; s/\.o\".*/.s/')
|
||||
SCHEDULE_FILES:= $(foreach dir,$(SRC_DIRS),$(wildcard $(dir)/*.schl))
|
||||
BASEROM_FILES := $(shell grep -F "build/baserom" spec | sed 's/.*build\/// ; s/\.o\".*//')
|
||||
ARCHIVES_O := $(shell grep -F ".yar.o" spec | sed 's/.*include "// ; s/\.o\".*/.o/')
|
||||
O_FILES := $(foreach f,$(S_FILES:.s=.o),build/$f) \
|
||||
$(foreach f,$(C_FILES:.c=.o),build/$f) \
|
||||
$(foreach f,$(BASEROM_FILES),build/$f.o) \
|
||||
$(ARCHIVES_O)
|
||||
BASEROM_FILES := $(shell grep -F "\$$(BUILD_DIR)/baserom" spec | sed 's/.*$$(BUILD_DIR)\/// ; s/\.o\".*//')
|
||||
ARCHIVES_O := $(shell grep -F ".yar.o" spec | sed 's/.*include "// ; s/.*$$(BUILD_DIR)\/// ; s/\.o\".*/.o/')
|
||||
O_FILES := $(foreach f,$(S_FILES:.s=.o),$(BUILD_DIR)/$f) \
|
||||
$(foreach f,$(C_FILES:.c=.o),$(BUILD_DIR)/$f) \
|
||||
$(foreach f,$(BASEROM_FILES),$(BUILD_DIR)/$f.o) \
|
||||
$(foreach f,$(ARCHIVES_O),$(BUILD_DIR)/$f)
|
||||
|
||||
SHIFTJIS_C_FILES := src/libultra/voice/voicecheckword.c src/audio/voice_external.c src/code/z_message.c src/code/z_message_nes.c
|
||||
SHIFTJIS_O_FILES := $(foreach f,$(SHIFTJIS_C_FILES:.c=.o),build/$f)
|
||||
SHIFTJIS_O_FILES := $(foreach f,$(SHIFTJIS_C_FILES:.c=.o),$(BUILD_DIR)/$f)
|
||||
|
||||
OVL_RELOC_FILES := $(shell $(CPP) $(CPPFLAGS) $(SPEC) | grep -o '[^"]*_reloc.o' )
|
||||
OVL_RELOC_FILES := $(shell $(CPP) $(CPPFLAGS) $(SPEC) | $(SPEC_REPLACE_VARS) | grep -o '[^"]*_reloc.o' )
|
||||
|
||||
SCHEDULE_INC_FILES := $(foreach f,$(SCHEDULE_FILES:.schl=.schl.inc),build/$f)
|
||||
SCHEDULE_INC_FILES := $(foreach f,$(SCHEDULE_FILES:.schl=.schl.inc),$(BUILD_DIR)/$f)
|
||||
|
||||
# Automatic dependency files
|
||||
# (Only asm_processor dependencies and reloc dependencies are handled for now)
|
||||
DEP_FILES := $(O_FILES:.o=.asmproc.d) $(OVL_RELOC_FILES:.o=.d)
|
||||
|
||||
# create build directories
|
||||
$(shell mkdir -p build/baserom $(foreach dir,$(SRC_DIRS) $(ASM_DIRS) $(ASSET_BIN_DIRS) $(ASSET_BIN_DIRS_C_FILES),build/$(dir)))
|
||||
$(shell mkdir -p $(BUILD_DIR)/baserom $(foreach dir,$(SRC_DIRS) $(ASM_DIRS) $(ASSET_BIN_DIRS) $(ASSET_BIN_DIRS_C_FILES),$(BUILD_DIR)/$(dir)))
|
||||
|
||||
# directory flags
|
||||
build/src/boot/O2/%.o: OPTFLAGS := -O2
|
||||
$(BUILD_DIR)/src/libultra/os/%.o: OPTFLAGS := -O1
|
||||
$(BUILD_DIR)/src/libultra/voice/%.o: OPTFLAGS := -O2
|
||||
$(BUILD_DIR)/src/libultra/io/%.o: OPTFLAGS := -O2
|
||||
$(BUILD_DIR)/src/libultra/libc/%.o: OPTFLAGS := -O2
|
||||
$(BUILD_DIR)/src/libultra/gu/%.o: OPTFLAGS := -O2
|
||||
$(BUILD_DIR)/src/libultra/rmon/%.o: OPTFLAGS := -O2
|
||||
|
||||
build/src/boot/libc/%.o: OPTFLAGS := -O2
|
||||
build/src/boot/libm/%.o: OPTFLAGS := -O2
|
||||
build/src/boot/libc64/%.o: OPTFLAGS := -O2
|
||||
$(BUILD_DIR)/src/boot/O2/%.o: OPTFLAGS := -O2
|
||||
|
||||
build/src/libultra/os/%.o: OPTFLAGS := -O1
|
||||
build/src/libultra/voice/%.o: OPTFLAGS := -O2
|
||||
build/src/libultra/io/%.o: OPTFLAGS := -O2
|
||||
build/src/libultra/libc/%.o: OPTFLAGS := -O2
|
||||
build/src/libultra/gu/%.o: OPTFLAGS := -O2
|
||||
build/src/libultra/rmon/%.o: OPTFLAGS := -O2
|
||||
$(BUILD_DIR)/src/boot/libc/%.o: OPTFLAGS := -O2
|
||||
$(BUILD_DIR)/src/boot/libm/%.o: OPTFLAGS := -O2
|
||||
$(BUILD_DIR)/src/boot/libc64/%.o: OPTFLAGS := -O2
|
||||
|
||||
build/src/audio/%.o: OPTFLAGS := -O2
|
||||
$(BUILD_DIR)/src/audio/%.o: OPTFLAGS := -O2
|
||||
|
||||
build/assets/%.o: OPTFLAGS := -O1
|
||||
build/assets/%.o: ASM_PROC_FLAGS :=
|
||||
$(BUILD_DIR)/assets/%.o: OPTFLAGS := -O1
|
||||
$(BUILD_DIR)/assets/%.o: ASM_PROC_FLAGS :=
|
||||
|
||||
# file flags
|
||||
build/src/boot/fault.o: CFLAGS += -trapuv
|
||||
build/src/boot/fault_drawer.o: CFLAGS += -trapuv
|
||||
$(BUILD_DIR)/src/libultra/libc/ll.o: OPTFLAGS := -O1
|
||||
$(BUILD_DIR)/src/libultra/libc/ll.o: MIPS_VERSION := -mips3 -32
|
||||
$(BUILD_DIR)/src/libultra/libc/llcvt.o: OPTFLAGS := -O1
|
||||
$(BUILD_DIR)/src/libultra/libc/llcvt.o: MIPS_VERSION := -mips3 -32
|
||||
|
||||
build/src/code/jpegutils.o: OPTFLAGS := -O2
|
||||
build/src/code/jpegdecoder.o: OPTFLAGS := -O2
|
||||
build/src/code/jpegutils.o: CC := $(CC_OLD)
|
||||
build/src/code/jpegdecoder.o: CC := $(CC_OLD)
|
||||
$(BUILD_DIR)/src/boot/fault.o: CFLAGS += -trapuv
|
||||
$(BUILD_DIR)/src/boot/fault_drawer.o: CFLAGS += -trapuv
|
||||
|
||||
build/src/code/osFlash.o: OPTFLAGS := -g
|
||||
build/src/code/osFlash.o: MIPS_VERSION := -mips1
|
||||
build/src/code/osFlash.o: CC := $(CC_OLD)
|
||||
$(BUILD_DIR)/src/code/jpegdecoder.o: CC := $(CC_OLD)
|
||||
$(BUILD_DIR)/src/code/jpegdecoder.o: OPTFLAGS := -O2
|
||||
$(BUILD_DIR)/src/code/jpegutils.o: CC := $(CC_OLD)
|
||||
$(BUILD_DIR)/src/code/jpegutils.o: OPTFLAGS := -O2
|
||||
|
||||
build/src/libultra/libc/ll.o: OPTFLAGS := -O1
|
||||
build/src/libultra/libc/ll.o: MIPS_VERSION := -mips3 -32
|
||||
build/src/libultra/libc/llcvt.o: OPTFLAGS := -O1
|
||||
build/src/libultra/libc/llcvt.o: MIPS_VERSION := -mips3 -32
|
||||
$(BUILD_DIR)/src/code/osFlash.o: CC := $(CC_OLD)
|
||||
$(BUILD_DIR)/src/code/osFlash.o: OPTFLAGS := -g
|
||||
$(BUILD_DIR)/src/code/osFlash.o: MIPS_VERSION := -mips1
|
||||
|
||||
# cc & asm-processor
|
||||
build/src/boot/%.o: CC := $(ASM_PROC) $(ASM_PROC_FLAGS) $(CC) -- $(AS) $(ASFLAGS) --
|
||||
build/src/boot/O2/%.o: CC := $(ASM_PROC) $(ASM_PROC_FLAGS) $(CC) -- $(AS) $(ASFLAGS) --
|
||||
$(BUILD_DIR)/src/libultra/%.o: CC := $(CC_OLD)
|
||||
|
||||
build/src/libultra/%.o: CC := $(CC_OLD)
|
||||
$(BUILD_DIR)/src/boot/%.o: CC := $(ASM_PROC) $(ASM_PROC_FLAGS) $(CC) -- $(AS) $(ASFLAGS) --
|
||||
$(BUILD_DIR)/src/boot/O2/%.o: CC := $(ASM_PROC) $(ASM_PROC_FLAGS) $(CC) -- $(AS) $(ASFLAGS) --
|
||||
|
||||
build/src/code/%.o: CC := $(ASM_PROC) $(ASM_PROC_FLAGS) $(CC) -- $(AS) $(ASFLAGS) --
|
||||
build/src/audio/%.o: CC := $(ASM_PROC) $(ASM_PROC_FLAGS) $(CC) -- $(AS) $(ASFLAGS) --
|
||||
$(BUILD_DIR)/src/code/%.o: CC := $(ASM_PROC) $(ASM_PROC_FLAGS) $(CC) -- $(AS) $(ASFLAGS) --
|
||||
$(BUILD_DIR)/src/audio/%.o: CC := $(ASM_PROC) $(ASM_PROC_FLAGS) $(CC) -- $(AS) $(ASFLAGS) --
|
||||
|
||||
build/src/overlays/%.o: CC := $(ASM_PROC) $(ASM_PROC_FLAGS) $(CC) -- $(AS) $(ASFLAGS) --
|
||||
$(BUILD_DIR)/src/overlays/%.o: CC := $(ASM_PROC) $(ASM_PROC_FLAGS) $(CC) -- $(AS) $(ASFLAGS) --
|
||||
|
||||
$(BUILD_DIR)/assets/%.o: CC := $(ASM_PROC) $(ASM_PROC_FLAGS) $(CC) -- $(AS) $(ASFLAGS) --
|
||||
|
||||
build/assets/%.o: CC := $(ASM_PROC) $(ASM_PROC_FLAGS) $(CC) -- $(AS) $(ASFLAGS) --
|
||||
|
||||
$(SHIFTJIS_O_FILES): CC_CHECK += -Wno-multichar -Wno-type-limits -Wno-overflow
|
||||
|
||||
#### Main Targets ###
|
||||
|
||||
uncompressed: $(ROM)
|
||||
ifeq ($(COMPARE),1)
|
||||
rom: $(ROM)
|
||||
ifneq ($(COMPARE),0)
|
||||
@md5sum $(ROM)
|
||||
@md5sum -c checksum_uncompressed.md5
|
||||
@md5sum -c $(BASEROM_DIR)/checksum.md5
|
||||
endif
|
||||
|
||||
compressed: $(ROMC)
|
||||
ifeq ($(COMPARE),1)
|
||||
compress: $(ROMC)
|
||||
ifneq ($(COMPARE),0)
|
||||
@md5sum $(ROMC)
|
||||
@md5sum -c checksum.md5
|
||||
@md5sum -c $(BASEROM_DIR)/checksum-compressed.md5
|
||||
endif
|
||||
|
||||
.PHONY: all uncompressed compressed clean assetclean distclean assets disasm init setup
|
||||
.DEFAULT_GOAL := uncompressed
|
||||
all: uncompressed compressed
|
||||
|
||||
$(ROM): $(ELF)
|
||||
$(OBJCOPY) --gap-fill=0x00 -O binary $< $@
|
||||
$(CHECKSUMMER) $@
|
||||
|
||||
$(ROMC): $(ROM)
|
||||
$(PYTHON) tools/z64compress_wrapper.py $(COMPFLAGS) $(ROM) $@ $(ELF) build/$(SPEC)
|
||||
$(ROMC): $(ROM) $(ELF) $(BUILD_DIR)/compress_ranges.txt
|
||||
$(PYTHON) tools/buildtools/compress.py --in $(ROM) --out $@ --dma-start `tools/buildtools/dmadata_start.sh $(NM) $(ELF)` --compress `cat $(BUILD_DIR)/compress_ranges.txt` --threads $(N_THREADS)
|
||||
$(PYTHON) -m ipl3checksum sum --cic 6105 --update $@
|
||||
|
||||
$(ELF): $(TEXTURE_FILES_OUT) $(ASSET_FILES_OUT) $(O_FILES) $(OVL_RELOC_FILES) build/ldscript.txt build/undefined_syms.txt
|
||||
$(LD) -T build/undefined_syms.txt -T build/ldscript.txt --no-check-sections --accept-unknown-input-arch --emit-relocs -Map build/mm.map -o $@
|
||||
$(ELF): $(TEXTURE_FILES_OUT) $(ASSET_FILES_OUT) $(O_FILES) $(OVL_RELOC_FILES) $(LDSCRIPT) $(BUILD_DIR)/undefined_syms.txt
|
||||
$(LD) -T $(LDSCRIPT) -T $(BUILD_DIR)/undefined_syms.txt --no-check-sections --accept-unknown-input-arch --emit-relocs -Map $(MAP) -o $@
|
||||
|
||||
## Order-only prerequisites
|
||||
# These ensure e.g. the O_FILES are built before the OVL_RELOC_FILES.
|
||||
@ -310,127 +337,144 @@ $(O_FILES): | schedule_inc_files
|
||||
|
||||
.PHONY: o_files asset_files schedule_inc_files
|
||||
|
||||
|
||||
#### Main commands ####
|
||||
|
||||
## Cleaning ##
|
||||
clean:
|
||||
$(RM) -rf $(ROMC) $(ROM) $(ELF) build
|
||||
$(RM) -r $(BUILD_DIR)
|
||||
|
||||
assetclean:
|
||||
$(RM) -rf $(ASSET_BIN_DIRS)
|
||||
$(RM) -rf assets/text/*.h
|
||||
$(RM) -rf build/assets
|
||||
$(RM) -rf .extracted-assets.json
|
||||
$(RM) -r $(ASSET_BIN_DIRS)
|
||||
$(RM) -r $(BUILD_DIR)/assets
|
||||
$(RM) -r assets/text/*.h
|
||||
$(RM) -r .extracted-assets.json
|
||||
|
||||
distclean: assetclean clean
|
||||
$(RM) -rf asm baserom data
|
||||
$(RM) -r asm data extracted
|
||||
$(MAKE) -C tools clean
|
||||
|
||||
venv:
|
||||
test -d $(VENV) || python3 -m venv $(VENV)
|
||||
$(PYTHON) -m pip install -U pip
|
||||
$(PYTHON) -m pip install -U -r requirements.txt
|
||||
|
||||
## Extraction step
|
||||
setup:
|
||||
$(MAKE) -C tools
|
||||
$(PYTHON) tools/fixbaserom.py
|
||||
$(PYTHON) tools/extract_baserom.py
|
||||
$(PYTHON) tools/decompress_yars.py
|
||||
$(PYTHON) tools/buildtools/decompress_baserom.py $(VERSION)
|
||||
$(PYTHON) tools/buildtools/extract_baserom.py $(BASEROM_DIR)/baserom-decompressed.z64 -o $(EXTRACTED_DIR)/baserom --dmadata-start `cat $(BASEROM_DIR)/dmadata_start.txt` --dmadata-names $(BASEROM_DIR)/dmadata_names.txt
|
||||
$(PYTHON) tools/buildtools/extract_yars.py $(VERSION)
|
||||
|
||||
assets:
|
||||
$(PYTHON) extract_assets.py -j $(N_THREADS) -Z Wno-hardcoded-pointer
|
||||
|
||||
## Assembly generation
|
||||
disasm:
|
||||
$(RM) -rf asm data
|
||||
$(RM) -r asm data
|
||||
$(PYTHON) tools/disasm/disasm.py -j $(N_THREADS) $(DISASM_FLAGS)
|
||||
|
||||
diff-init: uncompressed
|
||||
$(RM) -rf expected/
|
||||
diff-init: rom
|
||||
$(RM) -r expected/
|
||||
mkdir -p expected/
|
||||
cp -r build expected/build
|
||||
|
||||
init:
|
||||
$(MAKE) distclean
|
||||
init: distclean
|
||||
$(MAKE) venv
|
||||
$(MAKE) setup
|
||||
$(MAKE) assets
|
||||
$(MAKE) disasm
|
||||
$(MAKE) all
|
||||
$(MAKE) diff-init
|
||||
|
||||
run: $(ROM)
|
||||
ifeq ($(N64_EMULATOR),)
|
||||
$(error Emulator path not set. Set N64_EMULATOR in the Makefile, .make_options, or define it as an environment variable)
|
||||
endif
|
||||
$(N64_EMULATOR) $<
|
||||
|
||||
.PHONY: all rom compress clean assetclean distclean assets disasm init venv setup run
|
||||
.DEFAULT_GOAL := rom
|
||||
all: rom compress
|
||||
|
||||
|
||||
#### Various Recipes ####
|
||||
|
||||
build/undefined_syms.txt: undefined_syms.txt
|
||||
$(CPP) $(CPPFLAGS) $< > build/undefined_syms.txt
|
||||
$(BUILD_DIR)/undefined_syms.txt: undefined_syms.txt
|
||||
$(CPP) $(CPPFLAGS) $< > $(BUILD_DIR)/undefined_syms.txt
|
||||
|
||||
build/$(SPEC): $(SPEC)
|
||||
$(CPP) $(CPPFLAGS) $< > $@
|
||||
$(BUILD_DIR)/$(SPEC): $(SPEC)
|
||||
$(CPP) $(CPPFLAGS) $< | $(SPEC_REPLACE_VARS) > $@
|
||||
|
||||
build/ldscript.txt: build/$(SPEC)
|
||||
$(LDSCRIPT): $(BUILD_DIR)/$(SPEC)
|
||||
$(MKLDSCRIPT) $< $@
|
||||
|
||||
build/dmadata_table_spec.h: build/$(SPEC)
|
||||
$(MKDMADATA) $< $@
|
||||
$(BUILD_DIR)/dmadata_table_spec.h $(BUILD_DIR)/compress_ranges.txt: $(BUILD_DIR)/$(SPEC)
|
||||
$(MKDMADATA) $< $(BUILD_DIR)/dmadata_table_spec.h $(BUILD_DIR)/compress_ranges.txt
|
||||
|
||||
# Dependencies for files that may include the dmadata header automatically generated from the spec file
|
||||
build/src/boot/z_std_dma.o: build/dmadata_table_spec.h
|
||||
build/src/dmadata/dmadata.o: build/dmadata_table_spec.h
|
||||
$(BUILD_DIR)/src/boot/z_std_dma.o: $(BUILD_DIR)/dmadata_table_spec.h
|
||||
$(BUILD_DIR)/src/dmadata/dmadata.o: $(BUILD_DIR)/dmadata_table_spec.h
|
||||
|
||||
build/asm/%.o: asm/%.s
|
||||
$(BUILD_DIR)/asm/%.o: asm/%.s
|
||||
$(AS) $(ASFLAGS) $< -o $@
|
||||
|
||||
build/assets/%.o: assets/%.c
|
||||
$(BUILD_DIR)/assets/%.o: assets/%.c
|
||||
$(CC) -c $(CFLAGS) $(MIPS_VERSION) $(OPTFLAGS) -o $@ $<
|
||||
$(OBJCOPY_BIN)
|
||||
$(RM_MDEBUG)
|
||||
|
||||
build/%.yar.o: build/%.o
|
||||
$(BUILD_DIR)/%.yar.o: $(BUILD_DIR)/%.o
|
||||
$(MAKEYAR) $< $(@:.yar.o=.yar.bin) $(@:.yar.o=.symbols.o)
|
||||
$(OBJCOPY) -I binary -O elf32-big $(@:.yar.o=.yar.bin) $@
|
||||
|
||||
build/baserom/%.o: baserom/%
|
||||
$(BUILD_DIR)/baserom/%.o: $(EXTRACTED_DIR)/baserom/%
|
||||
$(OBJCOPY) -I binary -O elf32-big $< $@
|
||||
|
||||
build/data/%.o: data/%.s
|
||||
$(BUILD_DIR)/data/%.o: data/%.s
|
||||
$(AS) $(ASFLAGS) $< -o $@
|
||||
|
||||
build/assets/text/message_data.enc.h: assets/text/message_data.h
|
||||
$(BUILD_DIR)/assets/text/message_data.enc.h: assets/text/message_data.h
|
||||
python3 tools/msg/nes/msgencNES.py -o $@ $<
|
||||
|
||||
build/assets/text/staff_message_data.enc.h: assets/text/staff_message_data.h
|
||||
$(BUILD_DIR)/assets/text/staff_message_data.enc.h: assets/text/staff_message_data.h
|
||||
python3 tools/msg/staff/msgencStaff.py -o $@ $<
|
||||
|
||||
build/assets/text/message_data_static.o: build/assets/text/message_data.enc.h
|
||||
build/assets/text/staff_message_data_static.o: build/assets/text/staff_message_data.enc.h
|
||||
build/src/code/z_message.o: build/assets/text/message_data.enc.h build/assets/text/staff_message_data.enc.h
|
||||
$(BUILD_DIR)/assets/text/message_data_static.o: $(BUILD_DIR)/assets/text/message_data.enc.h
|
||||
$(BUILD_DIR)/assets/text/staff_message_data_static.o: $(BUILD_DIR)/assets/text/staff_message_data.enc.h
|
||||
$(BUILD_DIR)/src/code/z_message.o: $(BUILD_DIR)/assets/text/message_data.enc.h $(BUILD_DIR)/assets/text/staff_message_data.enc.h
|
||||
|
||||
build/src/overlays/%.o: src/overlays/%.c
|
||||
$(CC_CHECK) $<
|
||||
$(CC) -c $(CFLAGS) $(MIPS_VERSION) $(OPTFLAGS) -o $@ $<
|
||||
@$(OBJDUMP) -d $@ > $(@:.o=.s)
|
||||
$(RM_MDEBUG)
|
||||
|
||||
build/src/overlays/%_reloc.o: build/$(SPEC)
|
||||
$(FADO) $$(tools/buildtools/reloc_prereq $< $(notdir $*)) -n $(notdir $*) -o $(@:.o=.s) -M $(@:.o=.d)
|
||||
$(AS) $(ASFLAGS) $(@:.o=.s) -o $@
|
||||
|
||||
build/src/%.o: src/%.c
|
||||
$(CC_CHECK) $<
|
||||
$(CC) -c $(CFLAGS) $(MIPS_VERSION) $(OPTFLAGS) -o $@ $<
|
||||
$(OBJDUMP_CMD)
|
||||
$(RM_MDEBUG)
|
||||
|
||||
$(SHIFTJIS_O_FILES): build/src/%.o: src/%.c
|
||||
$(SHIFTJIS_O_FILES): $(BUILD_DIR)/src/%.o: src/%.c
|
||||
$(SHIFTJIS_CONV) -o $(@:.o=.enc.c) $<
|
||||
$(CC_CHECK) $(@:.o=.enc.c)
|
||||
$(CC) -c $(CFLAGS) $(MIPS_VERSION) $(OPTFLAGS) -o $@ $(@:.o=.enc.c)
|
||||
$(OBJDUMP_CMD)
|
||||
$(RM_MDEBUG)
|
||||
|
||||
build/src/libultra/libc/ll.o: src/libultra/libc/ll.c
|
||||
$(BUILD_DIR)/src/overlays/%.o: src/overlays/%.c
|
||||
$(CC_CHECK) $<
|
||||
$(CC) -c $(CFLAGS) $(MIPS_VERSION) $(OPTFLAGS) -o $@ $<
|
||||
$(OBJDUMP_CMD)
|
||||
$(RM_MDEBUG)
|
||||
|
||||
$(BUILD_DIR)/src/overlays/%_reloc.o: $(BUILD_DIR)/$(SPEC)
|
||||
$(FADO) $$(tools/buildtools/reloc_prereq $< $(notdir $*)) -n $(notdir $*) -o $(@:.o=.s) -M $(@:.o=.d)
|
||||
$(AS) $(ASFLAGS) $(@:.o=.s) -o $@
|
||||
|
||||
$(BUILD_DIR)/src/%.o: src/%.c
|
||||
$(CC_CHECK) $<
|
||||
$(CC) -c $(CFLAGS) $(MIPS_VERSION) $(OPTFLAGS) -o $@ $<
|
||||
$(OBJDUMP_CMD)
|
||||
$(RM_MDEBUG)
|
||||
|
||||
$(BUILD_DIR)/src/libultra/libc/ll.o: src/libultra/libc/ll.c
|
||||
$(CC_CHECK) $<
|
||||
$(CC) -c $(CFLAGS) $(MIPS_VERSION) $(OPTFLAGS) -o $@ $<
|
||||
$(PYTHON) tools/set_o32abi_bit.py $@
|
||||
$(OBJDUMP_CMD)
|
||||
$(RM_MDEBUG)
|
||||
|
||||
build/src/libultra/libc/llcvt.o: src/libultra/libc/llcvt.c
|
||||
$(BUILD_DIR)/src/libultra/libc/llcvt.o: src/libultra/libc/llcvt.c
|
||||
$(CC_CHECK) $<
|
||||
$(CC) -c $(CFLAGS) $(MIPS_VERSION) $(OPTFLAGS) -o $@ $<
|
||||
$(PYTHON) tools/set_o32abi_bit.py $@
|
||||
@ -439,16 +483,16 @@ build/src/libultra/libc/llcvt.o: src/libultra/libc/llcvt.c
|
||||
|
||||
# Build C files from assets
|
||||
|
||||
build/%.inc.c: %.png
|
||||
$(BUILD_DIR)/%.inc.c: %.png
|
||||
$(ZAPD) btex -eh -tt $(subst .,,$(suffix $*)) -i $< -o $@
|
||||
|
||||
build/assets/%.bin.inc.c: assets/%.bin
|
||||
$(BUILD_DIR)/assets/%.bin.inc.c: assets/%.bin
|
||||
$(ZAPD) bblb -eh -i $< -o $@
|
||||
|
||||
build/assets/%.jpg.inc.c: assets/%.jpg
|
||||
$(BUILD_DIR)/assets/%.jpg.inc.c: assets/%.jpg
|
||||
$(ZAPD) bren -eh -i $< -o $@
|
||||
|
||||
build/%.schl.inc: %.schl
|
||||
$(BUILD_DIR)/%.schl.inc: %.schl
|
||||
$(SCHC) $(SCHC_FLAGS) -o $@ $<
|
||||
|
||||
-include $(DEP_FILES)
|
||||
|
75
README.md
75
README.md
@ -27,9 +27,10 @@ This is a WIP **decompilation** of ***The Legend of Zelda: Majora's Mask***. The
|
||||
|
||||
The only version currently supported is N64 US, but we intend to eventually support every retail version of the original game (i.e. not versions of MM3D, which is a totally different game).
|
||||
|
||||
It currently builds the following ROM:
|
||||
It currently builds the following ROM and compressed ROM:
|
||||
|
||||
* mm.us.rev1.rom.z64 `md5: 2a0a8acb61538235bc1094d297fb6556`
|
||||
* mm-n64-us.z64 `md5: f46493eaa0628827dbd6ad3ecd8d65d6`
|
||||
* mm-n64-us-compressed.z64 `md5: 2a0a8acb61538235bc1094d297fb6556`
|
||||
|
||||
**This repo does not include any assets or assembly code necessary for compiling the ROM. A prior copy of the game is required to extract the required assets.**
|
||||
|
||||
@ -66,15 +67,15 @@ The build process has the following package requirements:
|
||||
* build-essential
|
||||
* binutils-mips-linux-gnu
|
||||
* python3
|
||||
* pip3
|
||||
* libpng-dev
|
||||
* python3-pip
|
||||
* python3-venv
|
||||
* libpng-dev
|
||||
|
||||
Under Debian / Ubuntu (which we recommend using), you can install them with the following commands:
|
||||
|
||||
```bash
|
||||
sudo apt update
|
||||
sudo apt install make git build-essential binutils-mips-linux-gnu python3 python3-pip libpng-dev python3-venv
|
||||
sudo apt install make git build-essential binutils-mips-linux-gnu python3 python3-pip python3-venv libpng-dev
|
||||
```
|
||||
|
||||
#### 2. Clone the repository
|
||||
@ -91,36 +92,13 @@ This will copy the GitHub repository contents into a new folder in the current d
|
||||
cd mm
|
||||
```
|
||||
|
||||
#### 3. Install python dependencies
|
||||
#### 3. Prepare a base ROM
|
||||
|
||||
The build process has a few python packages required that are located in `requirements.txt`.
|
||||
Place a copy of the US ROM inside the `baseroms/n64-us/` folder.
|
||||
|
||||
It is recommend to setup a virtual environment for python to localize all dependencies. To create a virtual environment:
|
||||
Rename the file to `baserom.z64`, `baserom.n64` or `baserom.v64`, depending on the original extension.
|
||||
|
||||
```bash
|
||||
python3 -m venv .mm-env
|
||||
```
|
||||
|
||||
To activate or deactivate the virtual environment run either:
|
||||
```bash
|
||||
# Activates the mm-env virtual environment
|
||||
source .mm-env/bin/activate
|
||||
# Deactivates the active virtual environment
|
||||
deactivate
|
||||
```
|
||||
|
||||
Once activated you can install the required dependencies:
|
||||
```bash
|
||||
pip install -r requirements.txt # or python3 -m pip if you want
|
||||
```
|
||||
|
||||
**Important:** This virtual environment will need to be activated everytime you enter the repo.
|
||||
|
||||
#### 4. Prepare a base ROM
|
||||
|
||||
Copy your ROM to inside the root of this new project directory, and rename the file of the baserom to reflect the version of ROM you are using. ex: `baserom.mm.us.rev1.z64`
|
||||
|
||||
#### 5. Make and Build the ROM
|
||||
#### 4. Make and Build the ROM
|
||||
|
||||
To start the extraction/build process, run the following command:
|
||||
|
||||
@ -128,18 +106,43 @@ To start the extraction/build process, run the following command:
|
||||
make init
|
||||
```
|
||||
|
||||
This will extract all the individual files in the ROM into a newly created baserom folder, as well as decompress the compressed files in a newly created decomp folder. This will create the build folders as well as a new folder with the ASM as well as containing the disassemblies of nearly all the files containing code.
|
||||
The extraction/build process:
|
||||
1. Prepares build environment:
|
||||
- Creates a Python virtual environment
|
||||
- Downloads necessary tools from pip
|
||||
- Compiles tools for the build process
|
||||
2. Extracts ROM contents:
|
||||
- Decompresses the ROM
|
||||
- Extracts individual files
|
||||
- Extracts archive files
|
||||
3. Extracts assets:
|
||||
- Extracts assets based on the XML files found in `assets/xml`
|
||||
4. Disassembles code:
|
||||
- Disassembles code-containing files
|
||||
- Disassembles data (data, rodata, and bss)
|
||||
5. Builds the ROM:
|
||||
- Compiles the code and assets into a new ROM
|
||||
- Generates a compressed version of the ROM
|
||||
|
||||
This make target will also build the ROM. If all goes well, a new ROM called "mm.us.rev1.rom.z64" should be built and the following text should be printed:
|
||||
If all goes well, the new ROM should be built at `build/n64-us/mm-n64-us.z64`, a compressed version generated at `build/n64-us/mm-n64-us-compressed.z64`, and the following text printed:
|
||||
|
||||
```bash
|
||||
mm.us.rev1.rom.z64: OK
|
||||
build/n64-us/mm-n64-us.z64: OK
|
||||
```
|
||||
and
|
||||
```bash
|
||||
build/n64-us/mm-n64-us-compressed.z64: OK
|
||||
```
|
||||
|
||||
If you instead see the following:
|
||||
|
||||
```bash
|
||||
mm.us.rev1.rom.z64: FAILED
|
||||
build/n64-us/mm-n64-us.z64: FAILED
|
||||
md5sum: WARNING: 1 computed checksum did NOT match
|
||||
```
|
||||
or
|
||||
```bash
|
||||
build/n64-us/mm-n64-us-compressed.z64: FAILED
|
||||
md5sum: WARNING: 1 computed checksum did NOT match
|
||||
```
|
||||
|
||||
|
1
baseroms/n64-us/checksum-compressed.md5
Normal file
1
baseroms/n64-us/checksum-compressed.md5
Normal file
@ -0,0 +1 @@
|
||||
2a0a8acb61538235bc1094d297fb6556 build/n64-us/mm-n64-us-compressed.z64
|
1
baseroms/n64-us/checksum.md5
Normal file
1
baseroms/n64-us/checksum.md5
Normal file
@ -0,0 +1 @@
|
||||
f46493eaa0628827dbd6ad3ecd8d65d6 build/n64-us/mm-n64-us.z64
|
1552
baseroms/n64-us/dmadata_names.txt
Normal file
1552
baseroms/n64-us/dmadata_names.txt
Normal file
File diff suppressed because it is too large
Load Diff
1
baseroms/n64-us/dmadata_start.txt
Normal file
1
baseroms/n64-us/dmadata_start.txt
Normal file
@ -0,0 +1 @@
|
||||
0x1A500
|
@ -1 +0,0 @@
|
||||
2a0a8acb61538235bc1094d297fb6556 mm.us.rev1.rom.z64
|
@ -1 +0,0 @@
|
||||
F46493EAA0628827DBD6AD3ECD8D65D6 mm.us.rev1.rom_uncompressed.z64
|
@ -1,9 +1,9 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
def apply(config, args):
|
||||
config['baseimg'] = 'baserom_uncompressed.z64'
|
||||
config['myimg'] = 'mm.us.rev1.rom_uncompressed.z64'
|
||||
config['mapfile'] = 'build/mm.map'
|
||||
config['baseimg'] = 'baseroms/n64-us/baserom-decompressed.z64'
|
||||
config['myimg'] = 'build/n64-us/mm-n64-us.z64'
|
||||
config['mapfile'] = 'build/n64-us/mm-n64-us.map'
|
||||
config['source_directories'] = ['./src','./include']
|
||||
config['objdump_flags'] = ['-M','reg-names=32']
|
||||
config['makeflags'] = ['KEEP_MDEBUG=1']
|
||||
|
@ -279,7 +279,7 @@ static ScheduleScript D_80BD3DB0[] = {
|
||||
In the actor's C code:
|
||||
|
||||
```c
|
||||
#include "build/src/overlays/actors/ovl_En_Ah/scheduleScripts.schl.inc"
|
||||
#include "src/overlays/actors/ovl_En_Ah/scheduleScripts.schl.inc"
|
||||
```
|
||||
|
||||
## Commands
|
||||
|
@ -42,6 +42,22 @@
|
||||
|
||||
There are a variety of tools that are used to assist in the decompilation process. This guide is an introduction to some of the tools that are used. Most of these tools are located in the `mm/tools` directory, others are either in the project root, or are separate programs entirely. Almost all of these programs have more information available via running them with `-h`.
|
||||
|
||||
**Important:** Many tools require activating a Python virtual environment that contains Python dependencies. This virtual environment is automatically installed into the `.venv` directory by `make setup`, but you need to **activate** it in your current terminal session in order to run Python tools. To start using the virtual environment in your current terminal run:
|
||||
|
||||
```bash
|
||||
source .venv/bin/activate
|
||||
```
|
||||
|
||||
Keep in mind that for each new terminal session, you will need to activate the Python virtual environment again. That is, run the above `source .venv/bin/activate` command.
|
||||
|
||||
To deactivate the virtual environment, run
|
||||
|
||||
```bash
|
||||
deactivate
|
||||
```
|
||||
|
||||
and your terminal session state will be restored to what it was before.
|
||||
|
||||
## In the repository
|
||||
|
||||
### `diff.py`
|
||||
@ -56,7 +72,7 @@ To use `diff.py`, you need a copy of a matching build folder to diff against. In
|
||||
./diff.py <flags> ObjTree_Init
|
||||
```
|
||||
|
||||
`diff.py` reads the respective `mm.map` files to find the function. If the function has been renamed, it will not be able to find it. You should not edit map files yourself, but instead rerun `make diff-init` (it is possible to copy the build folder manually, but it's better not to, since `make diff-init` guarantees an OK `expected` folder).
|
||||
`diff.py` reads the respective `mm-n64-us.map` file to find the function. If the function has been renamed, it will not be able to find it. You should not edit map files yourself, but instead rerun `make diff-init` (it is possible to copy the build folder manually, but it's better not to, since `make diff-init` guarantees an OK `expected` folder).
|
||||
|
||||
The recommended flags used are `-mwo`, `-mwo3`, or `-mwob`:
|
||||
|
||||
@ -102,7 +118,7 @@ Can be given a symbol (function or variable name, for example), and will find it
|
||||
|
||||
```bash
|
||||
$ ./sym_info.py ObjTree_Init
|
||||
Symbol ObjTree_Init (RAM: 0x80B9A0B0, ROM: 0xFFF210, build/src/overlays/actors/ovl_Obj_Tree/z_obj_tree.o)
|
||||
Symbol ObjTree_Init (RAM: 0x80B9A0B0, ROM: 0xFFF210, build/n64-us/src/overlays/actors/ovl_Obj_Tree/z_obj_tree.o)
|
||||
```
|
||||
|
||||
### `extract_assets.py`
|
||||
|
@ -78,9 +78,9 @@ First, we tell the compiler to ignore the original data file. To do this, open t
|
||||
beginseg
|
||||
name "ovl_En_Recepgirl"
|
||||
compress
|
||||
include "build/src/overlays/actors/ovl_En_Recepgirl/z_en_recepgirl.o"
|
||||
include "build/data/ovl_En_Recepgirl/ovl_En_Recepgirl.data.o"
|
||||
include "build/data/ovl_En_Recepgirl/ovl_En_Recepgirl.reloc.o"
|
||||
include "$(BUILD_DIR)/src/overlays/actors/ovl_En_Recepgirl/z_en_recepgirl.o"
|
||||
include "$(BUILD_DIR)/data/ovl_En_Recepgirl/ovl_En_Recepgirl.data.o"
|
||||
include "$(BUILD_DIR)/data/ovl_En_Recepgirl/ovl_En_Recepgirl.reloc.o"
|
||||
endseg
|
||||
```
|
||||
|
||||
@ -90,9 +90,9 @@ We will eventually remove both of the bottom two lines and replace them with our
|
||||
beginseg
|
||||
name "ovl_En_Recepgirl"
|
||||
compress
|
||||
include "build/src/overlays/actors/ovl_En_Recepgirl/z_en_recepgirl.o"
|
||||
//include "build/data/ovl_En_Recepgirl/ovl_En_Recepgirl.data.o"
|
||||
include "build/data/ovl_En_Recepgirl/ovl_En_Recepgirl.reloc.o"
|
||||
include "$(BUILD_DIR)/src/overlays/actors/ovl_En_Recepgirl/z_en_recepgirl.o"
|
||||
//include "$(BUILD_DIR)/data/ovl_En_Recepgirl/ovl_En_Recepgirl.data.o"
|
||||
include "$(BUILD_DIR)/data/ovl_En_Recepgirl/ovl_En_Recepgirl.reloc.o"
|
||||
endseg
|
||||
```
|
||||
|
||||
@ -131,7 +131,7 @@ The game has a convenient system that allows it to sometimes effectively use off
|
||||
There is an obvious problem here, which is that is that these symbols have to be defined *somewhere*, or the linker will complain (indeed, if we change the ones in the array to `D_...`, even if we extern them, we get
|
||||
|
||||
```
|
||||
mips-linux-gnu-ld: build/src/overlays/actors/ovl_En_Recepgirl/z_en_recepgirl.o:(.data+0x20): undefined reference to `D_0600F8F0'
|
||||
mips-linux-gnu-ld: build/n64-us/src/overlays/actors/ovl_En_Recepgirl/z_en_recepgirl.o:(.data+0x20): undefined reference to `D_0600F8F0'
|
||||
```
|
||||
|
||||
As we'd expect, of course: we didn't fulfil our promise that they were defined elsewhere.)
|
||||
|
@ -12,9 +12,9 @@ Specifically, to use the automatically generated reloc, rather than the original
|
||||
```
|
||||
beginseg
|
||||
name "ovl_En_Recepgirl"
|
||||
include "build/src/overlays/actors/ovl_En_Recepgirl/z_en_recepgirl.o"
|
||||
//include "build/data/overlays/actors/ovl_En_Recepgirl.data.o"
|
||||
include "build/data/overlays/actors/ovl_En_Recepgirl.reloc.o"
|
||||
include "$(BUILD_DIR)/src/overlays/actors/ovl_En_Recepgirl/z_en_recepgirl.o"
|
||||
//include "$(BUILD_DIR)/data/overlays/actors/ovl_En_Recepgirl.data.o"
|
||||
include "$(BUILD_DIR)/data/overlays/actors/ovl_En_Recepgirl.reloc.o"
|
||||
endseg
|
||||
```
|
||||
|
||||
@ -23,8 +23,8 @@ and change to use our reloc:
|
||||
```
|
||||
beginseg
|
||||
name "ovl_En_Recepgirl"
|
||||
include "build/src/overlays/actors/ovl_En_Recepgirl/z_en_recepgirl.o"
|
||||
include "build/src/overlays/actors/ovl_En_Recepgirl/ovl_En_Recepgirl_reloc.o"
|
||||
include "$(BUILD_DIR)/src/overlays/actors/ovl_En_Recepgirl/z_en_recepgirl.o"
|
||||
include "$(BUILD_DIR)/src/overlays/actors/ovl_En_Recepgirl/ovl_En_Recepgirl_reloc.o"
|
||||
endseg
|
||||
```
|
||||
|
||||
@ -51,11 +51,11 @@ in the C file. Also, due to the way `GLOBAL_ASM` works, we also cannot use gener
|
||||
beginseg
|
||||
name "ovl_En_Recepgirl"
|
||||
compress
|
||||
include "build/src/overlays/actors/ovl_En_Recepgirl/z_en_recepgirl.o"
|
||||
include "$(BUILD_DIR)/src/overlays/actors/ovl_En_Recepgirl/z_en_recepgirl.o"
|
||||
#ifdef NON_MATCHING
|
||||
include "build/src/overlays/actors/ovl_En_Recepgirl/ovl_En_Recepgirl_reloc.o"
|
||||
include "$(BUILD_DIR)/src/overlays/actors/ovl_En_Recepgirl/ovl_En_Recepgirl_reloc.o"
|
||||
#else
|
||||
include "build/data/overlays/actors/ovl_En_Recepgirl.reloc.o"
|
||||
include "$(BUILD_DIR)/data/overlays/actors/ovl_En_Recepgirl.reloc.o"
|
||||
#endif
|
||||
endseg
|
||||
```
|
||||
|
@ -39,18 +39,18 @@ You can create a `.vscode/c_cpp_properties.json` file with `C/C++: Edit Configur
|
||||
{
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Linux",
|
||||
"name": "n64-us",
|
||||
"compilerPath": "${default}", // Needs to not be "" for -m32 to work
|
||||
"compilerArgs": [
|
||||
"-m32" // Removes integer truncation warnings with gbi macros
|
||||
],
|
||||
"intelliSenseMode": "${default}", // Shouldn't matter
|
||||
"includePath": [ // Matches makefile's includes
|
||||
"${workspaceFolder}/**",
|
||||
"include",
|
||||
"src",
|
||||
"assets",
|
||||
"build",
|
||||
"include"
|
||||
"build/n64-us/",
|
||||
"${workspaceFolder}",
|
||||
],
|
||||
"defines": [
|
||||
"_LANGUAGE_C" // For gbi.h
|
||||
@ -72,10 +72,11 @@ Add the following to (or create) the `.vscode/settings.json` file for VSCode to
|
||||
"search.useIgnoreFiles": false,
|
||||
"search.exclude": {
|
||||
"**/.git": true,
|
||||
"baserom/**": true,
|
||||
"baseroms/**": true,
|
||||
"build/**": true,
|
||||
"expected/**": true,
|
||||
"nonmatchings/**": true,
|
||||
".venv/**": true
|
||||
},
|
||||
}
|
||||
```
|
||||
|
@ -27,7 +27,7 @@ def ExtractFile(xmlPath, outputPath, outputSourcePath):
|
||||
generateSourceFile = "0"
|
||||
break
|
||||
|
||||
execStr = f"tools/ZAPD/ZAPD.out e -eh -i {xmlPath} -b baserom/ -o {outputPath} -osf {outputSourcePath} -gsf {generateSourceFile} -rconf tools/ZAPDConfigs/MM/Config.xml {ZAPDArgs}"
|
||||
execStr = f"tools/ZAPD/ZAPD.out e -eh -i {xmlPath} -b extracted/n64-us/baserom -o {outputPath} -osf {outputSourcePath} -gsf {generateSourceFile} -rconf tools/ZAPDConfigs/MM/Config.xml {ZAPDArgs}"
|
||||
|
||||
if globalUnaccounted:
|
||||
execStr += " -Wunaccounted"
|
||||
|
@ -39,17 +39,17 @@ def firstDiffMain():
|
||||
parser = argparse.ArgumentParser(description="Find the first difference(s) between the built ROM and the base ROM.")
|
||||
|
||||
parser.add_argument("-c", "--count", type=int, default=5, help="find up to this many instruction difference(s)")
|
||||
parser.add_argument("-v", "--version", help="Which version should be processed", default="us.rev1")
|
||||
parser.add_argument("-v", "--version", help="Which version should be processed", default="n64-us")
|
||||
parser.add_argument("-a", "--add-colons", action='store_true', help="Add colon between bytes" )
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
buildFolder = Path("build")
|
||||
buildFolder = Path(f"build/{args.version}")
|
||||
|
||||
BUILTROM = Path(f"mm.{args.version}.rom_uncompressed.z64")
|
||||
BUILTMAP = buildFolder / f"mm.map"
|
||||
BUILTROM = buildFolder / f"mm-{args.version}.z64"
|
||||
BUILTMAP = buildFolder / f"mm-{args.version}.map"
|
||||
|
||||
EXPECTEDROM = Path("baserom_uncompressed.z64")
|
||||
EXPECTEDROM = Path(f"baseroms/{args.version}/baserom-decompressed.z64")
|
||||
EXPECTEDMAP = "expected" / BUILTMAP
|
||||
|
||||
mapfile_parser.frontends.first_diff.doFirstDiff(BUILTMAP, EXPECTEDMAP, BUILTROM, EXPECTEDROM, args.count, mismatchSize=True, addColons=args.add_colons, bytesConverterCallback=decodeInstruction)
|
||||
|
@ -29,7 +29,7 @@ APPLY_OPTS = ""
|
||||
|
||||
# Compiler options used with Clang-Tidy
|
||||
# Normal warnings are disabled with -Wno-everything to focus only on tidying
|
||||
INCLUDES = "-Iinclude -Isrc -Ibuild -I."
|
||||
INCLUDES = "-Iinclude -Isrc -Ibuild/n64-us -I."
|
||||
DEFINES = "-D_LANGUAGE_C -DNON_MATCHING"
|
||||
COMPILER_OPTS = f"-fno-builtin -std=gnu90 -m32 -Wno-everything {INCLUDES} {DEFINES}"
|
||||
|
||||
|
@ -5,7 +5,7 @@
|
||||
* - Argument 1: Name of the segment
|
||||
* - Argument 2: String matching the original name of the segment
|
||||
*
|
||||
* DEFINE_DMA_ENTRY_UNSET should be used for empty dmadata entries
|
||||
* DEFINE_DMA_ENTRY_SYMS should be used for empty dmadata entries that are used to keep track of symbols
|
||||
* - Argument 1: Name of the segment
|
||||
* - Argument 2: String matching the original name of the segment
|
||||
*/
|
||||
@ -17,8 +17,8 @@ DEFINE_DMA_ENTRY(Audioseq, "Audioseq")
|
||||
DEFINE_DMA_ENTRY(Audiotable, "Audiotable")
|
||||
DEFINE_DMA_ENTRY(kanji, "kanji")
|
||||
DEFINE_DMA_ENTRY(link_animetion, "link_animetion")
|
||||
DEFINE_DMA_ENTRY_UNSET(icon_item_static_syms, "icon_item_static_syms")
|
||||
DEFINE_DMA_ENTRY_UNSET(icon_item_24_static_syms, "icon_item_24_static_syms")
|
||||
DEFINE_DMA_ENTRY_SYMS(icon_item_static_syms, "icon_item_static_syms")
|
||||
DEFINE_DMA_ENTRY_SYMS(icon_item_24_static_syms, "icon_item_24_static_syms")
|
||||
DEFINE_DMA_ENTRY(icon_item_field_static, "icon_item_field_static")
|
||||
DEFINE_DMA_ENTRY(icon_item_dungeon_static, "icon_item_dungeon_static")
|
||||
DEFINE_DMA_ENTRY(icon_item_gameover_static, "icon_item_gameover_static")
|
||||
@ -30,7 +30,7 @@ DEFINE_DMA_ENTRY(item_name_static, "item_name_static")
|
||||
DEFINE_DMA_ENTRY(map_name_static, "map_name_static")
|
||||
DEFINE_DMA_ENTRY(icon_item_static_yar, "icon_item_static_yar")
|
||||
DEFINE_DMA_ENTRY(icon_item_24_static_yar, "icon_item_24_static_yar")
|
||||
DEFINE_DMA_ENTRY_UNSET(schedule_dma_static_syms, "schedule_dma_static_syms")
|
||||
DEFINE_DMA_ENTRY_SYMS(schedule_dma_static_syms, "schedule_dma_static_syms")
|
||||
DEFINE_DMA_ENTRY(schedule_dma_static_yar, "schedule_dma_static_yar")
|
||||
DEFINE_DMA_ENTRY(schedule_static, "schedule_static")
|
||||
DEFINE_DMA_ENTRY(story_static, "story_static")
|
||||
@ -661,7 +661,7 @@ DEFINE_DMA_ENTRY(ovl_En_Rsn, "ovl_En_Rsn")
|
||||
DEFINE_DMA_ENTRY(gameplay_keep, "gameplay_keep")
|
||||
DEFINE_DMA_ENTRY(gameplay_field_keep, "gameplay_field_keep")
|
||||
DEFINE_DMA_ENTRY(gameplay_dangeon_keep, "gameplay_dangeon_keep")
|
||||
DEFINE_DMA_ENTRY_UNSET(gameplay_object_exchange_static, "gameplay_object_exchange_static")
|
||||
DEFINE_DMA_ENTRY_SYMS(gameplay_object_exchange_static, "gameplay_object_exchange_static")
|
||||
DEFINE_DMA_ENTRY(object_link_boy, "object_link_boy")
|
||||
DEFINE_DMA_ENTRY(object_link_child, "object_link_child")
|
||||
DEFINE_DMA_ENTRY(object_link_goron, "object_link_goron")
|
||||
@ -1548,16 +1548,16 @@ DEFINE_DMA_ENTRY(KAKUSIANA_room_12, "KAKUSIANA_room_12")
|
||||
DEFINE_DMA_ENTRY(KAKUSIANA_room_13, "KAKUSIANA_room_13")
|
||||
DEFINE_DMA_ENTRY(KAKUSIANA_room_14, "KAKUSIANA_room_14")
|
||||
DEFINE_DMA_ENTRY(bump_texture_static, "bump_texture_static")
|
||||
DEFINE_DMA_ENTRY_UNSET(anime_model_1_static, "anime_model_1_static")
|
||||
DEFINE_DMA_ENTRY_UNSET(anime_model_2_static, "anime_model_2_static")
|
||||
DEFINE_DMA_ENTRY_UNSET(anime_model_3_static, "anime_model_3_static")
|
||||
DEFINE_DMA_ENTRY_UNSET(anime_model_4_static, "anime_model_4_static")
|
||||
DEFINE_DMA_ENTRY_UNSET(anime_model_5_static, "anime_model_5_static")
|
||||
DEFINE_DMA_ENTRY_UNSET(anime_model_6_static, "anime_model_6_static")
|
||||
DEFINE_DMA_ENTRY_UNSET(anime_texture_1_static, "anime_texture_1_static")
|
||||
DEFINE_DMA_ENTRY_UNSET(anime_texture_2_static, "anime_texture_2_static")
|
||||
DEFINE_DMA_ENTRY_UNSET(anime_texture_3_static, "anime_texture_3_static")
|
||||
DEFINE_DMA_ENTRY_UNSET(anime_texture_4_static, "anime_texture_4_static")
|
||||
DEFINE_DMA_ENTRY_UNSET(anime_texture_5_static, "anime_texture_5_static")
|
||||
DEFINE_DMA_ENTRY_UNSET(anime_texture_6_static, "anime_texture_6_static")
|
||||
DEFINE_DMA_ENTRY_UNSET(softsprite_matrix_static, "softsprite_matrix_static")
|
||||
DEFINE_DMA_ENTRY_SYMS(anime_model_1_static, "anime_model_1_static")
|
||||
DEFINE_DMA_ENTRY_SYMS(anime_model_2_static, "anime_model_2_static")
|
||||
DEFINE_DMA_ENTRY_SYMS(anime_model_3_static, "anime_model_3_static")
|
||||
DEFINE_DMA_ENTRY_SYMS(anime_model_4_static, "anime_model_4_static")
|
||||
DEFINE_DMA_ENTRY_SYMS(anime_model_5_static, "anime_model_5_static")
|
||||
DEFINE_DMA_ENTRY_SYMS(anime_model_6_static, "anime_model_6_static")
|
||||
DEFINE_DMA_ENTRY_SYMS(anime_texture_1_static, "anime_texture_1_static")
|
||||
DEFINE_DMA_ENTRY_SYMS(anime_texture_2_static, "anime_texture_2_static")
|
||||
DEFINE_DMA_ENTRY_SYMS(anime_texture_3_static, "anime_texture_3_static")
|
||||
DEFINE_DMA_ENTRY_SYMS(anime_texture_4_static, "anime_texture_4_static")
|
||||
DEFINE_DMA_ENTRY_SYMS(anime_texture_5_static, "anime_texture_5_static")
|
||||
DEFINE_DMA_ENTRY_SYMS(anime_texture_6_static, "anime_texture_6_static")
|
||||
DEFINE_DMA_ENTRY_SYMS(softsprite_matrix_static, "softsprite_matrix_static")
|
||||
|
@ -1,4 +1,4 @@
|
||||
# Setup
|
||||
# setup
|
||||
colorama>=0.4.3
|
||||
crunch64>=0.3.1,<1.0.0
|
||||
ipl3checksum>=1.2.0,<2.0.0
|
||||
@ -6,7 +6,7 @@ ipl3checksum>=1.2.0,<2.0.0
|
||||
# disasm
|
||||
rabbitizer>=1.3.0,<2.0.0
|
||||
|
||||
# Compression
|
||||
# yars
|
||||
pyelftools>=0.26
|
||||
|
||||
# diff
|
||||
@ -15,5 +15,9 @@ argcomplete
|
||||
python-Levenshtein
|
||||
cxxfilt
|
||||
|
||||
# permuter
|
||||
pycparser
|
||||
toml
|
||||
|
||||
# map parsing
|
||||
mapfile-parser>=1.2.1,<2.0.0
|
||||
|
@ -3,17 +3,17 @@
|
||||
|
||||
// Linker symbol declarations (used in the table below)
|
||||
#define DEFINE_DMA_ENTRY(name, _nameString) DECLARE_ROM_SEGMENT(name)
|
||||
#define DEFINE_DMA_ENTRY_UNSET(name, _nameString) DECLARE_ROM_SEGMENT(name)
|
||||
#define DEFINE_DMA_ENTRY_SYMS(name, _nameString) DECLARE_ROM_SEGMENT(name)
|
||||
|
||||
#include "tables/dmadata_table.h"
|
||||
|
||||
#undef DEFINE_DMA_ENTRY
|
||||
#undef DEFINE_DMA_ENTRY_UNSET
|
||||
#undef DEFINE_DMA_ENTRY_SYMS
|
||||
|
||||
// dmadata Table definition
|
||||
#define DEFINE_DMA_ENTRY(name, _nameString) \
|
||||
{ SEGMENT_ROM_START(name), SEGMENT_ROM_END(name), SEGMENT_ROM_START(name), 0 },
|
||||
#define DEFINE_DMA_ENTRY_UNSET(name, _nameString) \
|
||||
#define DEFINE_DMA_ENTRY_SYMS(name, _nameString) \
|
||||
{ SEGMENT_ROM_START(name), SEGMENT_ROM_END(name), 0xFFFFFFFF, 0xFFFFFFFF },
|
||||
|
||||
DmaEntry gDmaDataTable[] = {
|
||||
@ -22,7 +22,7 @@ DmaEntry gDmaDataTable[] = {
|
||||
};
|
||||
|
||||
#undef DEFINE_DMA_ENTRY
|
||||
#undef DEFINE_DMA_ENTRY_UNSET
|
||||
#undef DEFINE_DMA_ENTRY_SYMS
|
||||
|
||||
u8 sDmaDataPadding[0xF0] = { 0 };
|
||||
static s32 sBssPad;
|
||||
|
@ -18,7 +18,7 @@ void EnAh_Draw(Actor* thisx, PlayState* play);
|
||||
|
||||
void func_80BD3768(EnAh* this, PlayState* play);
|
||||
|
||||
#include "build/src/overlays/actors/ovl_En_Ah/scheduleScripts.schl.inc"
|
||||
#include "src/overlays/actors/ovl_En_Ah/scheduleScripts.schl.inc"
|
||||
|
||||
s32 D_80BD3DE8[] = { 0x0E28FF0C, 0x10000000 };
|
||||
|
||||
|
@ -17,7 +17,7 @@ void EnAl_Draw(Actor* thisx, PlayState* play);
|
||||
|
||||
void func_80BDF6C4(EnAl* this, PlayState* play);
|
||||
|
||||
#include "build/src/overlays/actors/ovl_En_Al/scheduleScripts.schl.inc"
|
||||
#include "src/overlays/actors/ovl_En_Al/scheduleScripts.schl.inc"
|
||||
|
||||
s32 D_80BDFCBC[] = {
|
||||
0x09000017, 0x0E27A50C, 0x09000018, 0x0E27A60C, 0x09000017, 0x0E27A70C, 0x09000018, 0x0E27A80C,
|
||||
|
@ -158,7 +158,7 @@ typedef enum AnjuScheduleResult {
|
||||
/* 64 */ ANJU_SCH_MAX
|
||||
} AnjuScheduleResult;
|
||||
|
||||
#include "build/src/overlays/actors/ovl_En_An/scheduleScripts.schl.inc"
|
||||
#include "src/overlays/actors/ovl_En_An/scheduleScripts.schl.inc"
|
||||
|
||||
static s32 sSearchTimePathLimit[ANJU_SCH_MAX] = {
|
||||
-1, // ANJU_SCH_NONE
|
||||
|
@ -129,7 +129,7 @@ static DamageTable sDamageTable = {
|
||||
/* Powder Keg */ DMG_ENTRY(1, 0x0),
|
||||
};
|
||||
|
||||
#include "build/src/overlays/actors/ovl_En_Baba/scheduleScripts.schl.inc"
|
||||
#include "src/overlays/actors/ovl_En_Baba/scheduleScripts.schl.inc"
|
||||
|
||||
static s32 sSearchTimePathLimit[] = { -1, -1, 0 };
|
||||
|
||||
|
@ -29,7 +29,7 @@ typedef enum {
|
||||
/* 1 */ TOILET_HAND_SCH_AVAILABLE
|
||||
} ToiletHandScheduleResult;
|
||||
|
||||
#include "build/src/overlays/actors/ovl_En_Bjt/scheduleScripts.schl.inc"
|
||||
#include "src/overlays/actors/ovl_En_Bjt/scheduleScripts.schl.inc"
|
||||
|
||||
static u8 sMsgEventScript[] = {
|
||||
0x0E, 0x29, 0x48, 0x0C, 0x0E, 0x00, 0xFF, 0x2B, 0x00, 0x00, 0x00, 0x52, 0x00, 0x5F, 0x2C, 0x29, 0x4A, 0x0C, 0x2F,
|
||||
|
@ -36,7 +36,7 @@ void func_80867144(EnDoor* this, PlayState* play);
|
||||
void func_808670F0(EnDoor* this, PlayState* play);
|
||||
void func_80866A5C(EnDoor* this, PlayState* play);
|
||||
|
||||
#include "build/src/overlays/actors/ovl_En_Door/scheduleScripts.schl.inc"
|
||||
#include "src/overlays/actors/ovl_En_Door/scheduleScripts.schl.inc"
|
||||
|
||||
ScheduleScript* D_8086778C[] = {
|
||||
D_808675D0, D_808675E4, D_80867634, D_80867640, D_8086764C, D_80867658, D_80867684, D_80867688,
|
||||
|
@ -19,7 +19,7 @@ void EnGm_Draw(Actor* thisx, PlayState* play);
|
||||
void func_80950CDC(EnGm* this, PlayState* play);
|
||||
void func_80950DB8(EnGm* this, PlayState* play);
|
||||
|
||||
#include "build/src/overlays/actors/ovl_En_Gm/scheduleScripts.schl.inc"
|
||||
#include "src/overlays/actors/ovl_En_Gm/scheduleScripts.schl.inc"
|
||||
|
||||
static s32 D_80951A0C[] = {
|
||||
-1, 1, 4, 1, -1, 1, -1, -1, -1, 0, 2, 3, 5, 6, 8, 1, 0, 8, 3, 6, 0, 1, 4, 7, 0, 1, 2, 4, 5, 7, 1,
|
||||
|
@ -19,7 +19,7 @@ void EnIg_Draw(Actor* thisx, PlayState* play);
|
||||
void func_80BF2AF8(EnIg* this, PlayState* play);
|
||||
void func_80BF2BD4(EnIg* this, PlayState* play);
|
||||
|
||||
#include "build/src/overlays/actors/ovl_En_Ig/scheduleScripts.schl.inc"
|
||||
#include "src/overlays/actors/ovl_En_Ig/scheduleScripts.schl.inc"
|
||||
|
||||
static s32 D_80BF3318[] = { -1, -1, 3, 1, 3, 1, 2, 0, 3, 5, 0, 3, 1, 2, 4 };
|
||||
|
||||
|
@ -21,7 +21,7 @@ void func_80BC2EA4(EnJa* this);
|
||||
void func_80BC32D8(EnJa* this, PlayState* play);
|
||||
void func_80BC3594(EnJa* this, PlayState* play);
|
||||
|
||||
#include "build/src/overlays/actors/ovl_En_Ja/scheduleScripts.schl.inc"
|
||||
#include "src/overlays/actors/ovl_En_Ja/scheduleScripts.schl.inc"
|
||||
|
||||
s32 D_80BC360C[] = {
|
||||
0x0E29370C, 0x170E2938, 0x0C180E29, 0x390C170E, 0x293A0C09, 0x0000180E, 0x293B0C09, 0x00001000,
|
||||
|
@ -36,7 +36,7 @@ typedef enum EnNbScheduleResult {
|
||||
/* 4 */ EN_NB_SCH_4
|
||||
} EnNbScheduleResult;
|
||||
|
||||
#include "build/src/overlays/actors/ovl_En_Nb/scheduleScripts.schl.inc"
|
||||
#include "src/overlays/actors/ovl_En_Nb/scheduleScripts.schl.inc"
|
||||
|
||||
u8 D_80BC1464[] = {
|
||||
0x1B, 0x04, 0x08, 0x00, 0x6A, 0x0A, 0x00, 0x10, 0x00, 0x08, 0x00, 0x10, 0x00, 0x08, 0x00, 0x00, 0x00, 0x08, 0x0E,
|
||||
|
@ -20,7 +20,7 @@ void EnPm_Draw(Actor* thisx, PlayState* play);
|
||||
void func_80AFA4D0(EnPm* this, PlayState* play);
|
||||
void func_80AFA5FC(EnPm* this, PlayState* play);
|
||||
|
||||
#include "build/src/overlays/actors/ovl_En_Pm/scheduleScripts.schl.inc"
|
||||
#include "src/overlays/actors/ovl_En_Pm/scheduleScripts.schl.inc"
|
||||
|
||||
static s32 D_80AFB430[] = {
|
||||
-1, 0, 4, 1, 0, 0, 1, 4, -1, -1, 15, 5, 0, 3, -1, -1, 1, 2, 11, 3, -1, -1, -1, 0, 0, 0, 0, 0, 1, 12, -1,
|
||||
|
@ -28,7 +28,7 @@ typedef enum {
|
||||
/* 1 */ POSTBOX_BEHAVIOUR_TAKE_ITEM
|
||||
} PostboxBehaviour;
|
||||
|
||||
#include "build/src/overlays/actors/ovl_En_Pst/scheduleScripts.schl.inc"
|
||||
#include "src/overlays/actors/ovl_En_Pst/scheduleScripts.schl.inc"
|
||||
|
||||
s32 D_80B2C23C[] = {
|
||||
0x0E27840C, 0x0E00FF2B, 0x00000031, 0x00392800, 0x0A122C27, 0xA40C2F00, 0x000C1012,
|
||||
|
@ -142,7 +142,7 @@ static TrackOptionsSet sTrackOptions = {
|
||||
{ 0x1770, 4, 1, 6 },
|
||||
};
|
||||
|
||||
#include "build/src/overlays/actors/ovl_En_Suttari/scheduleScripts.schl.inc"
|
||||
#include "src/overlays/actors/ovl_En_Suttari/scheduleScripts.schl.inc"
|
||||
|
||||
static s32 D_80BAE8F8[] = {
|
||||
-1, -1, -1, -1, -1, -1, 1, 2, 0, 3, 1, 2, 0, 0, 3, 0,
|
||||
|
@ -20,7 +20,7 @@ void EnTab_Draw(Actor* thisx, PlayState* play);
|
||||
void func_80BE127C(EnTab* this, PlayState* play);
|
||||
void func_80BE1348(EnTab* this, PlayState* play);
|
||||
|
||||
#include "build/src/overlays/actors/ovl_En_Tab/scheduleScripts.schl.inc"
|
||||
#include "src/overlays/actors/ovl_En_Tab/scheduleScripts.schl.inc"
|
||||
|
||||
s32 D_80BE1914[] = {
|
||||
0x003A0200, 0x080E2AF9, 0x0C113A02, 0x100E2AFA, 0x0C150900, 0x000E2AFB,
|
||||
|
@ -82,7 +82,7 @@ void func_80A4084C(EnTest3* this, PlayState* play);
|
||||
void func_80A40908(EnTest3* this, PlayState* play);
|
||||
void func_80A40A6C(EnTest3* this, PlayState* play);
|
||||
|
||||
#include "build/src/overlays/actors/ovl_En_Test3/scheduleScripts.schl.inc"
|
||||
#include "src/overlays/actors/ovl_En_Test3/scheduleScripts.schl.inc"
|
||||
|
||||
ActorInit En_Test3_InitVars = {
|
||||
/**/ ACTOR_EN_TEST3,
|
||||
|
@ -62,7 +62,7 @@ void func_80AEF5F4(Actor* thisx, PlayState* play);
|
||||
|
||||
static s32 D_80AF0050;
|
||||
|
||||
#include "build/src/overlays/actors/ovl_En_Tk/scheduleScripts.schl.inc"
|
||||
#include "src/overlays/actors/ovl_En_Tk/scheduleScripts.schl.inc"
|
||||
|
||||
ActorInit En_Tk_InitVars = {
|
||||
/**/ ACTOR_EN_TK,
|
||||
|
@ -34,7 +34,7 @@ void ObjShutter_Init(Actor* thisx, PlayState* play) {
|
||||
void ObjShutter_Destroy(Actor* thisx, PlayState* play) {
|
||||
}
|
||||
|
||||
#include "build/src/overlays/actors/ovl_Obj_Shutter/scheduleScripts.schl.inc"
|
||||
#include "src/overlays/actors/ovl_Obj_Shutter/scheduleScripts.schl.inc"
|
||||
|
||||
void ObjShutter_Update(Actor* thisx, PlayState* play2) {
|
||||
ObjShutter* this = THIS;
|
||||
|
@ -14,10 +14,11 @@ def symInfoMain():
|
||||
parser = argparse.ArgumentParser(description="Display various information about a symbol or address.")
|
||||
parser.add_argument("symname", help="symbol name or VROM/VRAM address to lookup")
|
||||
parser.add_argument("-e", "--expected", dest="use_expected", action="store_true", help="use the map file in expected/build/ instead of build/")
|
||||
parser.add_argument("-v", "--version", help="Which version should be processed", default="n64-us")
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
BUILTMAP = Path(f"build") / f"mm.map"
|
||||
BUILTMAP = Path(f"build/{args.version}/mm-{args.version}.map")
|
||||
|
||||
mapPath = BUILTMAP
|
||||
if args.use_expected:
|
||||
|
@ -6,15 +6,12 @@ all: $(PROGRAMS)
|
||||
$(MAKE) -C ZAPD
|
||||
$(MAKE) -C fado
|
||||
$(MAKE) -C buildtools
|
||||
# Some gcc versions give a warning about the -flto flag with no parameters. So we override the CFLAGS as a workaround
|
||||
$(MAKE) -C z64compress CFLAGS="-Os -flto=auto"
|
||||
|
||||
clean:
|
||||
$(RM) $(PROGRAMS)
|
||||
$(MAKE) -C ZAPD clean
|
||||
$(MAKE) -C fado clean
|
||||
$(MAKE) -C buildtools clean
|
||||
$(MAKE) -C z64compress clean
|
||||
|
||||
vtxdis_SOURCES := vtxdis.c
|
||||
|
||||
|
@ -10,10 +10,10 @@ gAddressWidth = 18 # if your ld >= 2.40 change this to 10
|
||||
script_dir = os.path.dirname(os.path.realpath(__file__))
|
||||
root_dir = script_dir + "/../"
|
||||
asm_dir = root_dir + "asm/non_matchings/overlays"
|
||||
build_dir = root_dir + "build/"
|
||||
build_dir = root_dir + "build/n64-us/"
|
||||
|
||||
def read_rom():
|
||||
with open("baserom_uncompressed.z64", "rb") as f:
|
||||
with open("baseroms/n64-us/baserom-decompressed.z64", "rb") as f:
|
||||
return f.read()
|
||||
|
||||
|
||||
@ -162,7 +162,7 @@ parser.add_argument("--num-out", help="number of functions to display", type=int
|
||||
args = parser.parse_args()
|
||||
|
||||
rom_bytes = read_rom()
|
||||
map_syms = parse_map(build_dir + "mm.map")
|
||||
map_syms = parse_map(build_dir + "mm-n64-us.map")
|
||||
map_offsets = get_map_offsets(map_syms)
|
||||
|
||||
s_files = get_all_s_files()
|
||||
|
284
tools/buildtools/compress.py
Normal file
284
tools/buildtools/compress.py
Normal file
@ -0,0 +1,284 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
# SPDX-FileCopyrightText: 2024 zeldaret
|
||||
# SPDX-License-Identifier: CC0-1.0
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
import dataclasses
|
||||
import time
|
||||
import multiprocessing
|
||||
import multiprocessing.pool
|
||||
|
||||
import crunch64
|
||||
|
||||
import dmadata
|
||||
|
||||
|
||||
def align(v: int):
|
||||
v += 0xF
|
||||
return v // 0x10 * 0x10
|
||||
|
||||
|
||||
@dataclasses.dataclass
|
||||
class RomSegment:
|
||||
vrom_start: int
|
||||
vrom_end: int
|
||||
is_compressed: bool
|
||||
is_syms: bool
|
||||
data: memoryview | None
|
||||
data_async: multiprocessing.pool.AsyncResult | None
|
||||
|
||||
@property
|
||||
def uncompressed_size(self):
|
||||
return self.vrom_end - self.vrom_start
|
||||
|
||||
|
||||
# Make interrupting the compression with ^C less jank
|
||||
# https://stackoverflow.com/questions/72967793/keyboardinterrupt-with-python-multiprocessing-pool
|
||||
def set_sigint_ignored():
|
||||
import signal
|
||||
|
||||
signal.signal(signal.SIGINT, signal.SIG_IGN)
|
||||
|
||||
|
||||
def compress_rom(
|
||||
rom_data: memoryview,
|
||||
dmadata_start: int,
|
||||
compress_entries_indices: set[int],
|
||||
n_threads: int = None,
|
||||
):
|
||||
"""
|
||||
rom_data: the uncompressed rom data
|
||||
dmadata_start: the offset in the rom where the dmadata starts
|
||||
compress_entries_indices: the indices in the dmadata of the segments that should be compressed
|
||||
n_threads: how many cores to use for compression
|
||||
"""
|
||||
|
||||
# Segments of the compressed rom (not all are compressed)
|
||||
compressed_rom_segments: list[RomSegment] = []
|
||||
dma_entries = dmadata.read_dmadata(rom_data, dmadata_start)
|
||||
# We sort the DMA entries by ROM start because `compress_entries_indices`
|
||||
# refers to indices in ROM order, but the uncompressed dmadata might not be
|
||||
# in ROM order.
|
||||
dma_entries.sort(key=lambda dma_entry: dma_entry.vrom_start)
|
||||
|
||||
with multiprocessing.Pool(n_threads, initializer=set_sigint_ignored) as p:
|
||||
# Extract each segment from the input rom
|
||||
for entry_index, dma_entry in enumerate(dma_entries):
|
||||
segment_rom_start = dma_entry.rom_start
|
||||
segment_rom_end = dma_entry.rom_start + (
|
||||
dma_entry.vrom_end - dma_entry.vrom_start
|
||||
)
|
||||
segment_data_uncompressed = rom_data[segment_rom_start:segment_rom_end]
|
||||
|
||||
is_compressed = entry_index in compress_entries_indices
|
||||
|
||||
if is_compressed:
|
||||
segment_data = None
|
||||
segment_data_async = p.apply_async(
|
||||
crunch64.yaz0.compress,
|
||||
(bytes(segment_data_uncompressed),),
|
||||
)
|
||||
else:
|
||||
segment_data = segment_data_uncompressed
|
||||
segment_data_async = None
|
||||
|
||||
compressed_rom_segments.append(
|
||||
RomSegment(
|
||||
dma_entry.vrom_start,
|
||||
dma_entry.vrom_end,
|
||||
is_compressed,
|
||||
dma_entry.is_syms(),
|
||||
segment_data,
|
||||
segment_data_async,
|
||||
)
|
||||
)
|
||||
|
||||
# Wait on compression of all compressed segments
|
||||
waiting_on_segments = [
|
||||
segment for segment in compressed_rom_segments if segment.is_compressed
|
||||
]
|
||||
total_uncompressed_size_of_data_to_compress = sum(
|
||||
segment.uncompressed_size for segment in waiting_on_segments
|
||||
)
|
||||
uncompressed_size_of_data_compressed_so_far = 0
|
||||
while waiting_on_segments:
|
||||
# Show progress
|
||||
progress = (
|
||||
uncompressed_size_of_data_compressed_so_far
|
||||
/ total_uncompressed_size_of_data_to_compress
|
||||
)
|
||||
print(f"Compressing... {progress * 100:.1f}%", end="\r")
|
||||
|
||||
# The segments for which the compression is not finished yet are
|
||||
# added to this list
|
||||
still_waiting_on_segments = []
|
||||
got_some_results = False
|
||||
for segment in waiting_on_segments:
|
||||
assert segment.data is None
|
||||
assert segment.data_async is not None
|
||||
|
||||
try:
|
||||
compressed_data = segment.data_async.get(0)
|
||||
except multiprocessing.TimeoutError:
|
||||
# Compression not finished yet
|
||||
still_waiting_on_segments.append(segment)
|
||||
else:
|
||||
# Compression finished!
|
||||
assert isinstance(compressed_data, bytes)
|
||||
segment.data = memoryview(compressed_data)
|
||||
uncompressed_size_of_data_compressed_so_far += (
|
||||
segment.uncompressed_size
|
||||
)
|
||||
got_some_results = True
|
||||
segment.data_async = None
|
||||
|
||||
if not got_some_results and still_waiting_on_segments:
|
||||
# Nothing happened this wait iteration, idle a bit
|
||||
time.sleep(0.010)
|
||||
|
||||
waiting_on_segments = still_waiting_on_segments
|
||||
|
||||
print("Putting together the compressed rom...")
|
||||
|
||||
# Put together the compressed rom
|
||||
compressed_rom_size = sum(
|
||||
align(len(segment.data)) for segment in compressed_rom_segments
|
||||
)
|
||||
pad_to_multiple_of = 8 * 2**20 # 8 MiB
|
||||
compressed_rom_size_padded = (
|
||||
(compressed_rom_size + pad_to_multiple_of - 1)
|
||||
// pad_to_multiple_of
|
||||
* pad_to_multiple_of
|
||||
)
|
||||
compressed_rom_data = memoryview(bytearray(compressed_rom_size_padded))
|
||||
compressed_rom_dma_entries: list[dmadata.DmaEntry] = []
|
||||
rom_offset = 0
|
||||
for segment in compressed_rom_segments:
|
||||
assert segment.data is not None
|
||||
|
||||
segment_rom_start = rom_offset
|
||||
segment_rom_end = align(segment_rom_start + len(segment.data))
|
||||
|
||||
i = segment_rom_start + len(segment.data)
|
||||
assert i <= len(compressed_rom_data)
|
||||
compressed_rom_data[segment_rom_start:i] = segment.data
|
||||
|
||||
rom_offset = segment_rom_end
|
||||
|
||||
if segment.is_syms:
|
||||
segment_rom_start = 0xFFFFFFFF
|
||||
segment_rom_end = 0xFFFFFFFF
|
||||
elif not segment.is_compressed:
|
||||
segment_rom_end = 0
|
||||
|
||||
compressed_rom_dma_entries.append(
|
||||
dmadata.DmaEntry(
|
||||
segment.vrom_start,
|
||||
segment.vrom_end,
|
||||
segment_rom_start,
|
||||
segment_rom_end,
|
||||
)
|
||||
)
|
||||
|
||||
assert rom_offset == compressed_rom_size
|
||||
# Pad the compressed rom with the pattern matching the baseroms
|
||||
for i in range(compressed_rom_size, compressed_rom_size_padded):
|
||||
compressed_rom_data[i] = i % 256
|
||||
|
||||
# Write the new dmadata
|
||||
offset = dmadata_start
|
||||
for dma_entry in compressed_rom_dma_entries:
|
||||
dma_entry.to_bin(compressed_rom_data[offset:])
|
||||
offset += dmadata.DmaEntry.SIZE_BYTES
|
||||
|
||||
return compressed_rom_data
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument(
|
||||
"--in",
|
||||
dest="in_rom",
|
||||
required=True,
|
||||
help="path to an uncompressed rom to be compressed",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--out",
|
||||
dest="out_rom",
|
||||
required=True,
|
||||
help="path of the compressed rom to write out",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--dma-start",
|
||||
dest="dma_start",
|
||||
type=lambda s: int(s, 16),
|
||||
required=True,
|
||||
help=(
|
||||
"The dmadata location in the rom, as a hexadecimal offset (e.g. 0x12f70)."
|
||||
),
|
||||
)
|
||||
parser.add_argument(
|
||||
"--compress",
|
||||
dest="compress_ranges",
|
||||
required=True,
|
||||
help=(
|
||||
"The indices in the dmadata of the entries to be compressed,"
|
||||
" where 0 is the first entry."
|
||||
" It is a comma-separated list of individual indices and inclusive ranges."
|
||||
" e.g. '0-1,3,5,6-9' is all indices from 0 to 9 (included) except 2 and 4."
|
||||
),
|
||||
)
|
||||
parser.add_argument(
|
||||
"--threads",
|
||||
dest="n_threads",
|
||||
type=int,
|
||||
default=1,
|
||||
help="how many cores to use for parallel compression",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
in_rom_p = Path(args.in_rom)
|
||||
if not in_rom_p.exists():
|
||||
parser.error(f"Input rom file {in_rom_p} doesn't exist.")
|
||||
|
||||
out_rom_p = Path(args.out_rom)
|
||||
|
||||
dmadata_start = args.dma_start
|
||||
|
||||
compress_ranges_str: str = args.compress_ranges
|
||||
compress_entries_indices = set()
|
||||
for compress_range_str in compress_ranges_str.split(","):
|
||||
compress_range_ends_str = compress_range_str.split("-")
|
||||
assert len(compress_range_ends_str) <= 2, (
|
||||
compress_range_ends_str,
|
||||
compress_range_str,
|
||||
compress_ranges_str,
|
||||
)
|
||||
compress_range_ends = [int(v_str) for v_str in compress_range_ends_str]
|
||||
if len(compress_range_ends) == 1:
|
||||
compress_entries_indices.add(compress_range_ends[0])
|
||||
else:
|
||||
assert len(compress_range_ends) == 2
|
||||
compress_range_first, compress_range_last = compress_range_ends
|
||||
compress_entries_indices.update(
|
||||
range(compress_range_first, compress_range_last + 1)
|
||||
)
|
||||
|
||||
n_threads = args.n_threads
|
||||
|
||||
in_rom_data = in_rom_p.read_bytes()
|
||||
out_rom_data = compress_rom(
|
||||
memoryview(in_rom_data),
|
||||
dmadata_start,
|
||||
compress_entries_indices,
|
||||
n_threads,
|
||||
)
|
||||
out_rom_p.write_bytes(out_rom_data)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
242
tools/buildtools/decompress_baserom.py
Executable file
242
tools/buildtools/decompress_baserom.py
Executable file
@ -0,0 +1,242 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
# SPDX-FileCopyrightText: © 2024 ZeldaRET
|
||||
# SPDX-License-Identifier: CC0-1.0
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import io
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import sys
|
||||
|
||||
import crunch64
|
||||
import ipl3checksum
|
||||
import zlib
|
||||
|
||||
import dmadata
|
||||
|
||||
|
||||
def decompress_zlib(data: bytes) -> bytes:
|
||||
decomp = zlib.decompressobj(-zlib.MAX_WBITS)
|
||||
output = bytearray()
|
||||
output.extend(decomp.decompress(data))
|
||||
while decomp.unconsumed_tail:
|
||||
output.extend(decomp.decompress(decomp.unconsumed_tail))
|
||||
output.extend(decomp.flush())
|
||||
return bytes(output)
|
||||
|
||||
|
||||
def decompress(data: bytes, is_zlib_compressed: bool) -> bytes:
|
||||
if is_zlib_compressed:
|
||||
return decompress_zlib(data)
|
||||
return crunch64.yaz0.decompress(data)
|
||||
|
||||
|
||||
def round_up(n, shift):
|
||||
mod = 1 << shift
|
||||
return (n + mod - 1) >> shift << shift
|
||||
|
||||
|
||||
def update_crc(decompressed: io.BytesIO) -> io.BytesIO:
|
||||
print("Recalculating crc...")
|
||||
calculated_checksum = ipl3checksum.CICKind.CIC_X105.calculateChecksum(
|
||||
bytes(decompressed.getbuffer())
|
||||
)
|
||||
new_crc = struct.pack(f">II", calculated_checksum[0], calculated_checksum[1])
|
||||
|
||||
decompressed.seek(0x10)
|
||||
decompressed.write(new_crc)
|
||||
return decompressed
|
||||
|
||||
|
||||
def decompress_rom(
|
||||
file_content: bytearray,
|
||||
dmadata_start: int,
|
||||
dma_entries: list[dmadata.DmaEntry],
|
||||
is_zlib_compressed: bool,
|
||||
) -> bytearray:
|
||||
rom_segments = {} # vrom start : data s.t. len(data) == vrom_end - vrom_start
|
||||
new_dmadata = [] # new dmadata: list[dmadata.Entry]
|
||||
|
||||
decompressed = io.BytesIO(b"")
|
||||
|
||||
for dma_entry in dma_entries:
|
||||
v_start = dma_entry.vrom_start
|
||||
v_end = dma_entry.vrom_end
|
||||
p_start = dma_entry.rom_start
|
||||
p_end = dma_entry.rom_end
|
||||
if dma_entry.is_syms():
|
||||
new_dmadata.append(dma_entry)
|
||||
continue
|
||||
if dma_entry.is_compressed():
|
||||
new_contents = decompress(file_content[p_start:p_end], is_zlib_compressed)
|
||||
rom_segments[v_start] = new_contents
|
||||
else:
|
||||
rom_segments[v_start] = file_content[p_start : p_start + v_end - v_start]
|
||||
new_dmadata.append(dmadata.DmaEntry(v_start, v_end, v_start, 0))
|
||||
|
||||
# write rom segments to vaddrs
|
||||
for vrom_st, data in rom_segments.items():
|
||||
decompressed.seek(vrom_st)
|
||||
decompressed.write(data)
|
||||
# write new dmadata
|
||||
decompressed.seek(dmadata_start)
|
||||
for dma_entry in new_dmadata:
|
||||
entry_data = bytearray(dmadata.DmaEntry.SIZE_BYTES)
|
||||
dma_entry.to_bin(entry_data)
|
||||
decompressed.write(entry_data)
|
||||
# pad to size
|
||||
padding_end = round_up(dma_entries[-1].vrom_end, 17)
|
||||
decompressed.seek(padding_end - 1)
|
||||
decompressed.write(bytearray([0]))
|
||||
# re-calculate crc
|
||||
return bytearray(update_crc(decompressed).getbuffer())
|
||||
|
||||
|
||||
def get_str_hash(byte_array):
|
||||
return str(hashlib.md5(byte_array).hexdigest())
|
||||
|
||||
|
||||
def check_existing_rom(rom_path: Path, correct_str_hash: str):
|
||||
# If the baserom exists and is correct, we don't need to change anything
|
||||
if rom_path.exists():
|
||||
if get_str_hash(rom_path.read_bytes()) == correct_str_hash:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def word_swap(file_content: bytearray) -> bytearray:
|
||||
words = str(int(len(file_content) / 4))
|
||||
little_byte_format = "<" + words + "I"
|
||||
big_byte_format = ">" + words + "I"
|
||||
tmp = struct.unpack_from(little_byte_format, file_content, 0)
|
||||
struct.pack_into(big_byte_format, file_content, 0, *tmp)
|
||||
return file_content
|
||||
|
||||
|
||||
def byte_swap(file_content: bytearray) -> bytearray:
|
||||
halfwords = str(int(len(file_content) / 2))
|
||||
little_byte_format = "<" + halfwords + "H"
|
||||
big_byte_format = ">" + halfwords + "H"
|
||||
tmp = struct.unpack_from(little_byte_format, file_content, 0)
|
||||
struct.pack_into(big_byte_format, file_content, 0, *tmp)
|
||||
return file_content
|
||||
|
||||
|
||||
def per_version_fixes(file_content: bytearray, version: str) -> bytearray:
|
||||
return file_content
|
||||
|
||||
|
||||
def pad_rom(file_content: bytearray, dma_entries: list[dmadata.DmaEntry]) -> bytearray:
|
||||
padding_start = round_up(dma_entries[-1].vrom_end, 12)
|
||||
padding_end = round_up(dma_entries[-1].vrom_end, 17)
|
||||
print(f"Padding from {padding_start:X} to {padding_end:X}...")
|
||||
for i in range(padding_start, padding_end):
|
||||
file_content[i] = 0xFF
|
||||
return file_content
|
||||
|
||||
|
||||
# Determine if we have a ROM file
|
||||
ROM_FILE_EXTENSIONS = ["z64", "n64", "v64"]
|
||||
|
||||
|
||||
def find_baserom(version: str) -> Path | None:
|
||||
for rom_file_ext_lower in ROM_FILE_EXTENSIONS:
|
||||
for rom_file_ext in (rom_file_ext_lower, rom_file_ext_lower.upper()):
|
||||
rom_file_name_candidate = Path(f"baseroms/{version}/baserom.{rom_file_ext}")
|
||||
if rom_file_name_candidate.exists():
|
||||
return rom_file_name_candidate
|
||||
return None
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Convert a rom that uses dmadata to an uncompressed one."
|
||||
)
|
||||
parser.add_argument(
|
||||
"version",
|
||||
help="Version of the game to decompress.",
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
version = args.version
|
||||
|
||||
baserom_dir = Path(f"baseroms/{version}")
|
||||
if not baserom_dir.exists():
|
||||
print(f"Error: Unknown version '{version}'.", file=sys.stderr)
|
||||
exit(1)
|
||||
|
||||
uncompressed_path = baserom_dir / "baserom-decompressed.z64"
|
||||
|
||||
dmadata_start = int((baserom_dir / "dmadata_start.txt").read_text(), 16)
|
||||
correct_str_hash = (baserom_dir / "checksum.md5").read_text().split()[0]
|
||||
|
||||
if check_existing_rom(uncompressed_path, correct_str_hash):
|
||||
print("Found valid baserom - exiting early")
|
||||
return
|
||||
|
||||
rom_file_name = find_baserom(version)
|
||||
|
||||
if rom_file_name is None:
|
||||
path_list = [
|
||||
f"baseroms/{version}/baserom.{rom_file_ext}"
|
||||
for rom_file_ext in ROM_FILE_EXTENSIONS
|
||||
]
|
||||
print(f"Error: Could not find {','.join(path_list)}.", file=sys.stderr)
|
||||
exit(1)
|
||||
|
||||
# Read in the original ROM
|
||||
print(f"File '{rom_file_name}' found.")
|
||||
|
||||
file_content = bytearray(rom_file_name.read_bytes())
|
||||
|
||||
# Check if ROM needs to be byte/word swapped
|
||||
# Little-endian
|
||||
if file_content[0] == 0x40:
|
||||
# Word Swap ROM
|
||||
print("ROM needs to be word swapped...")
|
||||
file_content = word_swap(file_content)
|
||||
print("Word swapping done.")
|
||||
|
||||
# Byte-swapped
|
||||
elif file_content[0] == 0x37:
|
||||
# Byte Swap ROM
|
||||
print("ROM needs to be byte swapped...")
|
||||
file_content = byte_swap(file_content)
|
||||
print("Byte swapping done.")
|
||||
|
||||
file_content = per_version_fixes(file_content, version)
|
||||
|
||||
dma_entries = dmadata.read_dmadata(file_content, dmadata_start)
|
||||
# Decompress
|
||||
if any(dma_entry.is_compressed() for dma_entry in dma_entries):
|
||||
print("Decompressing rom...")
|
||||
is_zlib_compressed = version in {"ique-cn", "ique-zh"}
|
||||
file_content = decompress_rom(
|
||||
file_content, dmadata_start, dma_entries, is_zlib_compressed
|
||||
)
|
||||
|
||||
file_content = pad_rom(file_content, dma_entries)
|
||||
|
||||
# Check to see if the ROM is a "vanilla" ROM
|
||||
str_hash = get_str_hash(file_content)
|
||||
if str_hash != correct_str_hash:
|
||||
print(
|
||||
f"Error: Expected a hash of {correct_str_hash} but got {str_hash}. The baserom has probably been tampered, find a new one",
|
||||
file=sys.stderr,
|
||||
)
|
||||
exit(1)
|
||||
|
||||
# Write out our new ROM
|
||||
print(f"Writing new ROM {uncompressed_path}...")
|
||||
uncompressed_path.write_bytes(file_content)
|
||||
|
||||
print("Done!")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
83
tools/buildtools/dmadata.py
Normal file
83
tools/buildtools/dmadata.py
Normal file
@ -0,0 +1,83 @@
|
||||
# SPDX-FileCopyrightText: © 2024 ZeldaRET
|
||||
# SPDX-License-Identifier: CC0-1.0
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import dataclasses
|
||||
import struct
|
||||
|
||||
|
||||
STRUCT_IIII = struct.Struct(">IIII")
|
||||
|
||||
|
||||
@dataclasses.dataclass
|
||||
class DmaEntry:
|
||||
"""
|
||||
A Python counterpart to the dmadata entry struct:
|
||||
```c
|
||||
typedef struct {
|
||||
/* 0x00 */ uintptr_t vromStart;
|
||||
/* 0x04 */ uintptr_t vromEnd;
|
||||
/* 0x08 */ uintptr_t romStart;
|
||||
/* 0x0C */ uintptr_t romEnd;
|
||||
} DmaEntry;
|
||||
```
|
||||
"""
|
||||
|
||||
vrom_start: int
|
||||
vrom_end: int
|
||||
rom_start: int
|
||||
rom_end: int
|
||||
|
||||
def __repr__(self):
|
||||
return (
|
||||
"DmaEntry("
|
||||
f"vrom_start=0x{self.vrom_start:08X}, "
|
||||
f"vrom_end=0x{self.vrom_end:08X}, "
|
||||
f"rom_start=0x{self.rom_start:08X}, "
|
||||
f"rom_end=0x{self.rom_end:08X}"
|
||||
")"
|
||||
)
|
||||
|
||||
SIZE_BYTES = STRUCT_IIII.size
|
||||
|
||||
def to_bin(self, data: memoryview):
|
||||
STRUCT_IIII.pack_into(
|
||||
data,
|
||||
0,
|
||||
self.vrom_start,
|
||||
self.vrom_end,
|
||||
self.rom_start,
|
||||
self.rom_end,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def from_bin(data: memoryview):
|
||||
return DmaEntry(*STRUCT_IIII.unpack_from(data))
|
||||
|
||||
def is_compressed(self) -> bool:
|
||||
return self.rom_end != 0
|
||||
|
||||
def is_syms(self) -> bool:
|
||||
"""
|
||||
"SYMS" DMA entries describe segments that are always filled with 0's in the ROM.
|
||||
The DMA entry has both rom_start and rom_end set to 0xFFFFFFFF, where the actual rom start and end is given by vrom_start and vrom_end instead.
|
||||
These zeroed segments are used to record the offsets/sizes of subfiles in compressed yaz0 archive files but are not used by the game directly.
|
||||
"""
|
||||
return self.rom_start == 0xFFFFFFFF and self.rom_end == 0xFFFFFFFF
|
||||
|
||||
|
||||
DMA_ENTRY_END = DmaEntry(0, 0, 0, 0)
|
||||
|
||||
|
||||
def read_dmadata(rom_data: memoryview, start_offset: int) -> list[DmaEntry]:
|
||||
result = []
|
||||
|
||||
offset = start_offset
|
||||
while (
|
||||
entry := DmaEntry.from_bin(rom_data[offset : offset + DmaEntry.SIZE_BYTES])
|
||||
) != DMA_ENTRY_END:
|
||||
result.append(entry)
|
||||
offset += DmaEntry.SIZE_BYTES
|
||||
|
||||
return result
|
15
tools/buildtools/dmadata_start.sh
Executable file
15
tools/buildtools/dmadata_start.sh
Executable file
@ -0,0 +1,15 @@
|
||||
#!/bin/sh
|
||||
|
||||
NM=$1
|
||||
ELF=$2
|
||||
|
||||
# dmadata_syms contents look like:
|
||||
# ffffffff80015850 T _dmadataSegmentTextStart
|
||||
# 00000000 A _dmadataSegmentTextSize
|
||||
# 00011a40 A _dmadataSegmentRomStart
|
||||
# ffffffff8001b920 T _dmadataSegmentRoDataEnd
|
||||
dmadata_syms=`$NM $ELF --no-sort --radix=x --format=bsd | grep dmadata`
|
||||
|
||||
_dmadataSegmentRomStart=`echo "$dmadata_syms" | grep '\b_dmadataSegmentRomStart\b' | cut -d' ' -f1`
|
||||
|
||||
echo 0x"$_dmadataSegmentRomStart"
|
79
tools/buildtools/extract_baserom.py
Executable file
79
tools/buildtools/extract_baserom.py
Executable file
@ -0,0 +1,79 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
# SPDX-FileCopyrightText: © 2024 ZeldaRET
|
||||
# SPDX-License-Identifier: CC0-1.0
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
import dmadata
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Extract segments from an uncompressed ROM, based on its dmadata."
|
||||
)
|
||||
parser.add_argument(
|
||||
"rom", metavar="ROM", type=Path, help="Path to uncompressed ROM"
|
||||
)
|
||||
parser.add_argument(
|
||||
"-o",
|
||||
"--output-dir",
|
||||
type=Path,
|
||||
required=True,
|
||||
help="Output directory for segments",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--dmadata-start",
|
||||
type=lambda s: int(s, 16),
|
||||
required=True,
|
||||
help=(
|
||||
"The dmadata location in the rom, as a hexadecimal offset (e.g. 0x12f70)"
|
||||
),
|
||||
)
|
||||
parser.add_argument(
|
||||
"--dmadata-names",
|
||||
type=Path,
|
||||
required=True,
|
||||
help="Path to file containing segment names",
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
rom_data = memoryview(args.rom.read_bytes())
|
||||
|
||||
dma_names = args.dmadata_names.read_text().splitlines()
|
||||
dma_entries = dmadata.read_dmadata(rom_data, args.dmadata_start)
|
||||
if len(dma_names) != len(dma_entries):
|
||||
print(
|
||||
f"Error: expected {len(dma_names)} DMA entries but found {len(dma_entries)} in ROM",
|
||||
file=sys.stderr,
|
||||
)
|
||||
exit(1)
|
||||
|
||||
args.output_dir.mkdir(parents=True, exist_ok=True)
|
||||
for dma_name, dma_entry in zip(dma_names, dma_entries):
|
||||
if dma_entry.is_syms():
|
||||
segment_rom_start = dma_entry.vrom_start
|
||||
elif not dma_entry.is_compressed():
|
||||
segment_rom_start = dma_entry.rom_start
|
||||
else: # Segment compressed
|
||||
print(f"Error: segment {dma_name} is compressed", file=sys.stderr)
|
||||
exit(1)
|
||||
|
||||
segment_rom_end = segment_rom_start + (
|
||||
dma_entry.vrom_end - dma_entry.vrom_start
|
||||
)
|
||||
|
||||
segment_data = rom_data[segment_rom_start:segment_rom_end]
|
||||
segment_path = args.output_dir / dma_name
|
||||
segment_path.write_bytes(segment_data)
|
||||
|
||||
print(f"Extracted {len(dma_entries)} segments to {args.output_dir}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
@ -7,7 +7,7 @@
|
||||
#
|
||||
# This program decompresses every raw yar binary file listed in
|
||||
# `tools/filelists/{version}/archives.csv` to a corresponding
|
||||
# `baserom/{file}.unarchive` raw file.
|
||||
# `extracted/{version}/baserom/{file}.unarchive` raw file.
|
||||
#
|
||||
# It works by decompressing every Yaz0 block and appending them one by one into
|
||||
# a new raw binary file so it can be processed normally by other tools.
|
||||
@ -24,6 +24,7 @@ import struct
|
||||
|
||||
PRINT_XML = False
|
||||
|
||||
|
||||
@dataclasses.dataclass
|
||||
class ArchiveMeta:
|
||||
start: int
|
||||
@ -45,7 +46,9 @@ def getOffsetsList(archiveBytes: bytearray) -> list[ArchiveMeta]:
|
||||
firstEntryOffset = readBytesAsWord(archiveBytes, 0)
|
||||
firstEntrySize = readBytesAsWord(archiveBytes, 4)
|
||||
|
||||
archivesOffsets.append(ArchiveMeta(firstEntryOffset, firstEntryOffset + firstEntrySize))
|
||||
archivesOffsets.append(
|
||||
ArchiveMeta(firstEntryOffset, firstEntryOffset + firstEntrySize)
|
||||
)
|
||||
|
||||
offset = 4
|
||||
while offset < firstEntryOffset - 4:
|
||||
@ -71,29 +74,33 @@ def extractArchive(archivePath: Path, outPath: Path):
|
||||
archivesOffsets = getOffsetsList(archiveBytes)
|
||||
|
||||
if PRINT_XML:
|
||||
print('<Root>')
|
||||
print("<Root>")
|
||||
print(f' <File Name="{outPath.stem}">')
|
||||
|
||||
with outPath.open("wb") as out:
|
||||
currentOffset = 0
|
||||
for meta in archivesOffsets:
|
||||
decompressedBytes = crunch64.yaz0.decompress(archiveBytes[meta.start:meta.end])
|
||||
decompressedBytes = crunch64.yaz0.decompress(
|
||||
archiveBytes[meta.start : meta.end]
|
||||
)
|
||||
decompressedSize = len(decompressedBytes)
|
||||
out.write(decompressedBytes)
|
||||
|
||||
if PRINT_XML:
|
||||
print(f' <Blob Name="{archivePath.stem}_Blob_{currentOffset:06X}" Size="0x{decompressedSize:04X}" Offset="0x{currentOffset:X}" />')
|
||||
print(
|
||||
f' <Blob Name="{archivePath.stem}_Blob_{currentOffset:06X}" Size="0x{decompressedSize:04X}" Offset="0x{currentOffset:X}" />'
|
||||
)
|
||||
|
||||
currentOffset += decompressedSize
|
||||
|
||||
if PRINT_XML:
|
||||
print(f' </File>')
|
||||
print('</Root>')
|
||||
print(f" </File>")
|
||||
print("</Root>")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="MM archives extractor")
|
||||
parser.add_argument("-v", "--version", help="version to process", default="mm.us.rev1")
|
||||
parser.add_argument("version", help="version to process", default="n64-us")
|
||||
parser.add_argument("--xml", help="Generate xml to stdout", action="store_true")
|
||||
|
||||
args = parser.parse_args()
|
||||
@ -106,10 +113,11 @@ def main():
|
||||
with archivesCsvPath.open() as f:
|
||||
for line in f:
|
||||
archiveName = line.strip().split(",")[1]
|
||||
archivePath = Path(f"baserom/{archiveName}")
|
||||
archivePath = Path(f"extracted/{args.version}/baserom/{archiveName}")
|
||||
|
||||
extractedPath = Path(str(archivePath) + ".unarchive")
|
||||
extractArchive(archivePath, extractedPath)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
@ -23,30 +23,70 @@ static void write_dmadata_table(FILE *fout)
|
||||
}
|
||||
|
||||
if (g_segments[i].flags & FLAG_SYMS) {
|
||||
// For segments set with SYMS, unset in the dma table
|
||||
fprintf(fout, "DEFINE_DMA_ENTRY_UNSET(%s, \"%s\")\n", g_segments[i].name, g_segments[i].name);
|
||||
fprintf(fout, "DEFINE_DMA_ENTRY_SYMS(%s, \"%s\")\n", g_segments[i].name, g_segments[i].name);
|
||||
} else {
|
||||
fprintf(fout, "DEFINE_DMA_ENTRY(%s, \"%s\")\n", g_segments[i].name, g_segments[i].name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void write_compress_ranges(FILE *fout)
|
||||
{
|
||||
int i;
|
||||
int rom_index = 0;
|
||||
bool continue_list = false;
|
||||
int stride_first = -1;
|
||||
|
||||
for (i = 0; i < g_segmentsCount; i++) {
|
||||
bool compress = g_segments[i].compress;
|
||||
|
||||
// Don't consider segments set with NOLOAD when calculating indices
|
||||
if (g_segments[i].flags & FLAG_NOLOAD) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (compress) {
|
||||
if (stride_first == -1)
|
||||
stride_first = rom_index;
|
||||
}
|
||||
if (!compress || i == g_segmentsCount - 1) {
|
||||
if (stride_first != -1) {
|
||||
int stride_last = compress ? rom_index : rom_index - 1;
|
||||
if (continue_list) {
|
||||
fprintf(fout, ",");
|
||||
}
|
||||
if (stride_first == stride_last) {
|
||||
fprintf(fout, "%d", stride_first);
|
||||
} else {
|
||||
fprintf(fout, "%d-%d", stride_first, stride_last);
|
||||
}
|
||||
continue_list = true;
|
||||
stride_first = -1;
|
||||
}
|
||||
}
|
||||
|
||||
rom_index++;
|
||||
}
|
||||
}
|
||||
|
||||
static void usage(const char *execname)
|
||||
{
|
||||
fprintf(stderr, "zelda64 dmadata generation tool v0.01\n"
|
||||
"usage: %s SPEC_FILE DMADATA_TABLE\n"
|
||||
"SPEC_FILE file describing the organization of object files into segments\n"
|
||||
"DMADATA_TABLE filename of output dmadata table header\n",
|
||||
"usage: %s SPEC_FILE DMADATA_TABLE COMPRESS_RANGES\n"
|
||||
"SPEC_FILE file describing the organization of object files into segments\n"
|
||||
"DMADATA_TABLE filename of output dmadata table header\n"
|
||||
"COMPRESS_RANGES filename to write which files are compressed (e.g. 0-5,7,10-20)\n",
|
||||
execname);
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
FILE *dmaout;
|
||||
FILE *compress_ranges_out;
|
||||
void *spec;
|
||||
size_t size;
|
||||
|
||||
if (argc != 3)
|
||||
if (argc != 4)
|
||||
{
|
||||
usage(argv[0]);
|
||||
return 1;
|
||||
@ -60,6 +100,13 @@ int main(int argc, char **argv)
|
||||
util_fatal_error("failed to open file '%s' for writing", argv[2]);
|
||||
write_dmadata_table(dmaout);
|
||||
fclose(dmaout);
|
||||
|
||||
compress_ranges_out = fopen(argv[3], "w");
|
||||
if (compress_ranges_out == NULL)
|
||||
util_fatal_error("failed to open file '%s' for writing", argv[3]);
|
||||
write_compress_ranges(compress_ranges_out);
|
||||
fclose(compress_ranges_out);
|
||||
|
||||
free_rom_spec(g_segments, g_segmentsCount);
|
||||
free(spec);
|
||||
|
||||
|
@ -152,7 +152,6 @@ bool parse_segment_statement(struct Segment* currSeg, STMTId stmt, char* args, i
|
||||
util_fatal_error("line %i: duplicate '%s' statement", lineNum, stmtNames[stmt]);
|
||||
|
||||
currSeg->fields |= 1 << stmt;
|
||||
currSeg->compress = false;
|
||||
|
||||
// statements valid within a segment definition
|
||||
switch (stmt) {
|
||||
|
@ -34,7 +34,7 @@ echo "char measurement;" >> $TEMPC
|
||||
|
||||
$(pwd)/tools/ido_recomp/linux/7.1/cc -G 0 -non_shared \
|
||||
-Xfullwarn -Xcpluscomm -O2 -g3 -Xcpluscomm -mips2 \
|
||||
-I $(pwd)/ -I $(pwd)/include/ -I $(pwd)/src/ -I $(pwd)/assets/ -I $(pwd)/build/ \
|
||||
-I $(pwd)/ -I $(pwd)/include/ -I $(pwd)/src/ -I $(pwd)/assets/ -I $(pwd)/build/n64-us/ \
|
||||
-Wab,-r4300_mul -woff 624,649,838,712 -c $TEMPC -o $TEMPO
|
||||
|
||||
LINE=$(${CROSS}objdump -t $TEMPO | grep measurement | cut -d' ' -f1)
|
||||
|
@ -73,8 +73,8 @@ def discard_decomped_files(files_spec, include_files):
|
||||
i += 1
|
||||
|
||||
# For every file within this segment, look through the seg for lines with this file's name
|
||||
# if found, check whether it's still in build/asm/ or build/data/, in which case it's not decomped
|
||||
# if all references to it are in build/src/ then it should be ok to skip, some code/boot files are a bit different
|
||||
# if found, check whether it's still in $(BUILD_DIR)/asm/ or $(BUILD_DIR)/data/, in which case it's not decomped
|
||||
# if all references to it are in $(BUILD_DIR)/src/ then it should be ok to skip, some code/boot files are a bit different
|
||||
|
||||
seg_start = i
|
||||
new_files = {}
|
||||
@ -99,20 +99,20 @@ def discard_decomped_files(files_spec, include_files):
|
||||
if f"/{file}." in spec[i]:
|
||||
if spec[i].count(".") == 1:
|
||||
last_line = spec[i]
|
||||
if "build/asm/" in spec[i] or "build/data/" in spec[i]:
|
||||
if "$(BUILD_DIR)/asm/" in spec[i] or "$(BUILD_DIR)/data/" in spec[i]:
|
||||
include = True
|
||||
break
|
||||
i += 1
|
||||
else:
|
||||
# Many code/boot files only have a single section (i.e .text)
|
||||
# In that case it will be inside build/src/ and pragma in the asm
|
||||
# In that case it will be inside $(BUILD_DIR)/src/ and pragma in the asm
|
||||
# For these files, open the source and look for the pragmas to be sure
|
||||
# Overlays always have at least a data section we can check in the spec, so it's not needed for them
|
||||
if type != "overlay" and last_line != "":
|
||||
assert last_line.count(".") == 1
|
||||
last_line = (
|
||||
last_line.strip()
|
||||
.split("build/", 1)[1]
|
||||
.split("$(BUILD_DIR)/", 1)[1]
|
||||
.replace(".o", ".c")[:-1]
|
||||
)
|
||||
with open(root_path / last_line, "r") as f2:
|
||||
@ -1802,7 +1802,7 @@ def disassemble_makerom(section):
|
||||
|
||||
elif section[-1]["type"] == "ipl3":
|
||||
# TODO disassemble this eventually, low priority
|
||||
out = f"{asm_header('.text')}\n.incbin \"baserom/makerom\", 0x40, 0xFC0\n"
|
||||
out = f"{asm_header('.text')}\n.incbin \"extracted/n64-us/baserom/makerom\", 0x40, 0xFC0\n"
|
||||
|
||||
with open(ASM_OUT + "/makerom/ipl3.s", "w") as outfile:
|
||||
outfile.write(out)
|
||||
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@ -1,156 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import hashlib, io, struct, sys
|
||||
from os import path
|
||||
|
||||
import crunch64
|
||||
import ipl3checksum
|
||||
|
||||
UNCOMPRESSED_SIZE = 0x2F00000
|
||||
|
||||
def as_word_list(b):
|
||||
return [i[0] for i in struct.iter_unpack(">I", b)]
|
||||
|
||||
def read_dmadata_entry(addr):
|
||||
return as_word_list(fileContent[addr:addr+0x10])
|
||||
|
||||
def read_dmadata(start):
|
||||
dmadata = []
|
||||
addr = start
|
||||
entry = read_dmadata_entry(addr)
|
||||
i = 0
|
||||
while any([e != 0 for e in entry]):
|
||||
# print(f"0x{addr:08X} " + str([f"{e:08X}" for e in entry]))
|
||||
dmadata.append(entry)
|
||||
addr += 0x10
|
||||
i += 1
|
||||
entry = read_dmadata_entry(addr)
|
||||
# print(f"0x{addr:08X} " + str([f"{e:08X}" for e in entry]))
|
||||
return dmadata
|
||||
|
||||
def update_crc(decompressed):
|
||||
print("Recalculating crc...")
|
||||
calculated_checksum = ipl3checksum.CICKind.CIC_X105.calculateChecksum(bytes(decompressed.getbuffer()))
|
||||
new_crc = struct.pack(f">II", calculated_checksum[0], calculated_checksum[1])
|
||||
|
||||
decompressed.seek(0x10)
|
||||
decompressed.write(new_crc)
|
||||
return decompressed
|
||||
|
||||
def decompress_rom(dmadata_addr, dmadata):
|
||||
rom_segments = {} # vrom start : data s.t. len(data) == vrom_end - vrom_start
|
||||
new_dmadata = bytearray() # new dmadata: {vrom start , vrom end , vrom start , 0}
|
||||
|
||||
decompressed = io.BytesIO(b"")
|
||||
|
||||
for v_start, v_end, p_start, p_end in dmadata:
|
||||
if p_start == 0xFFFFFFFF and p_end == 0xFFFFFFFF:
|
||||
new_dmadata.extend(struct.pack(">IIII", v_start, v_end, p_start, p_end))
|
||||
continue
|
||||
if p_end == 0: # uncompressed
|
||||
rom_segments.update({v_start : fileContent[p_start:p_start + v_end - v_start]})
|
||||
else: # compressed
|
||||
rom_segments.update({v_start : crunch64.yaz0.decompress(fileContent[p_start:p_end])})
|
||||
new_dmadata.extend(struct.pack(">IIII", v_start, v_end, v_start, 0))
|
||||
|
||||
# write rom segments to vaddrs
|
||||
for vrom_st,data in rom_segments.items():
|
||||
decompressed.seek(vrom_st)
|
||||
decompressed.write(data)
|
||||
# write new dmadata
|
||||
decompressed.seek(dmadata_addr)
|
||||
decompressed.write(new_dmadata)
|
||||
# pad to size
|
||||
decompressed.seek(UNCOMPRESSED_SIZE-1)
|
||||
decompressed.write(bytearray([0]))
|
||||
# re-calculate crc
|
||||
return update_crc(decompressed)
|
||||
|
||||
correct_compressed_str_hash = "2a0a8acb61538235bc1094d297fb6556"
|
||||
correct_str_hash = "f46493eaa0628827dbd6ad3ecd8d65d6"
|
||||
|
||||
def get_str_hash(byte_array):
|
||||
return str(hashlib.md5(byte_array).hexdigest())
|
||||
|
||||
# If the baserom exists and is correct, we don't need to change anything
|
||||
if path.exists("baserom_uncompressed.z64"):
|
||||
with open("baserom_uncompressed.z64", mode="rb") as file:
|
||||
fileContent = bytearray(file.read())
|
||||
if get_str_hash(fileContent) == correct_str_hash:
|
||||
print("Found valid baserom - exiting early")
|
||||
sys.exit(0)
|
||||
|
||||
# Determine if we have a ROM file
|
||||
romFileName = ""
|
||||
if path.exists("baserom.mm.us.rev1.z64"):
|
||||
romFileName = "baserom.mm.us.rev1.z64"
|
||||
elif path.exists("baserom.mm.us.rev1.n64"):
|
||||
romFileName = "baserom.mm.us.rev1.n64"
|
||||
elif path.exists("baserom.mm.us.rev1.v64"):
|
||||
romFileName = "baserom.mm.us.rev1.v64"
|
||||
else:
|
||||
print("Error: Could not find baserom.mm.us.rev1.z64/baserom.mm.us.rev1.n64/baserom.mm.us.rev1.v64.")
|
||||
sys.exit(1)
|
||||
|
||||
# Read in the original ROM
|
||||
print("File '" + romFileName + "' found.")
|
||||
with open(romFileName, mode="rb") as file:
|
||||
fileContent = bytearray(file.read())
|
||||
|
||||
fileContentLen = len(fileContent)
|
||||
|
||||
# Check if ROM needs to be byte/word swapped
|
||||
# Little-endian
|
||||
if fileContent[0] == 0x40:
|
||||
# Word Swap ROM
|
||||
print("ROM needs to be word swapped...")
|
||||
words = str(int(fileContentLen/4))
|
||||
little_byte_format = "<" + words + "I"
|
||||
big_byte_format = ">" + words + "I"
|
||||
tmp = struct.unpack_from(little_byte_format, fileContent, 0)
|
||||
struct.pack_into(big_byte_format, fileContent, 0, *tmp)
|
||||
|
||||
print("Word swapping done.")
|
||||
|
||||
# Byte-swapped
|
||||
elif fileContent[0] == 0x37:
|
||||
# Byte Swap ROM
|
||||
print("ROM needs to be byte swapped...")
|
||||
halfwords = str(int(fileContentLen/2))
|
||||
little_byte_format = "<" + halfwords + "H"
|
||||
big_byte_format = ">" + halfwords + "H"
|
||||
tmp = struct.unpack_from(little_byte_format, fileContent, 0)
|
||||
struct.pack_into(big_byte_format, fileContent, 0, *tmp)
|
||||
|
||||
print("Byte swapping done.")
|
||||
|
||||
# Check to see if the ROM is a compressed "vanilla" ROM
|
||||
compressed_str_hash = get_str_hash(bytearray(fileContent))
|
||||
if compressed_str_hash != correct_compressed_str_hash:
|
||||
print("Error: Expected a hash of " + correct_compressed_str_hash + " but got " + compressed_str_hash + ". " +
|
||||
"The baserom has probably been tampered, find a new one")
|
||||
sys.exit(1)
|
||||
|
||||
# Decompress
|
||||
FILE_TABLE_OFFSET = 0x1A500 # 0x1C110 for JP1.0, 0x1C050 for JP1.1, 0x24F60 for debug
|
||||
if any([b != 0 for b in fileContent[FILE_TABLE_OFFSET + 0x9C:FILE_TABLE_OFFSET + 0x9C + 0x4]]):
|
||||
print("Decompressing rom...")
|
||||
fileContent = decompress_rom(FILE_TABLE_OFFSET, read_dmadata(FILE_TABLE_OFFSET)).getbuffer()
|
||||
|
||||
# FF Padding (TODO is there an automatic way we can find where to start padding from? Largest dmadata file end maybe?)
|
||||
for i in range(0x2EE8000,UNCOMPRESSED_SIZE):
|
||||
fileContent[i] = 0xFF
|
||||
|
||||
# Check to see if the ROM is a "vanilla" ROM
|
||||
str_hash = get_str_hash(bytearray(fileContent))
|
||||
if str_hash != correct_str_hash:
|
||||
print("Error: Expected a hash of " + correct_str_hash + " but got " + str_hash + ". " +
|
||||
"The baserom has probably been tampered, find a new one")
|
||||
sys.exit(1)
|
||||
|
||||
# Write out our new ROM
|
||||
print("Writing new ROM 'baserom_uncompressed.z64'.")
|
||||
with open("baserom_uncompressed.z64", "wb") as file:
|
||||
file.write(bytes(fileContent))
|
||||
|
||||
print("Done!")
|
@ -5,7 +5,7 @@ import argparse, math, os, re
|
||||
script_dir = os.path.dirname(os.path.realpath(__file__))
|
||||
root_dir = script_dir + "/../"
|
||||
asm_dir = root_dir + "asm/non_matchings/overlays/actors"
|
||||
build_dir = root_dir + "build/src/overlays/actors"
|
||||
build_dir = root_dir + "build/n64-us/src/overlays/actors"
|
||||
|
||||
|
||||
def get_num_instructions(f_path):
|
||||
|
@ -252,7 +252,7 @@ class MessageNES:
|
||||
|
||||
def parseTable(start):
|
||||
table = {}
|
||||
with open("baserom/code","rb") as f:
|
||||
with open("extracted/n64-us/baserom/code","rb") as f:
|
||||
f.seek(start)
|
||||
buf = f.read(8)
|
||||
textId, typePos, segment = struct.unpack(">HBxI", buf)
|
||||
@ -263,14 +263,14 @@ def parseTable(start):
|
||||
|
||||
return table
|
||||
|
||||
NES_MESSAGE_TABLE_ADDR = 0x1210D8 # Location of NES message table in baserom/code
|
||||
NES_MESSAGE_TABLE_ADDR = 0x1210D8 # Location of NES message table in extracted/n64-us/baserom/code
|
||||
NES_SEGMENT_ADDR = 0x08000000
|
||||
|
||||
def main(outfile):
|
||||
msgTable = parseTable(NES_MESSAGE_TABLE_ADDR)
|
||||
|
||||
buf = []
|
||||
with open("baserom/message_data_static", "rb") as f:
|
||||
with open("extracted/n64-us/baserom/message_data_static", "rb") as f:
|
||||
buf = f.read()
|
||||
|
||||
bufLen = len(buf)
|
||||
|
@ -172,7 +172,7 @@ class MessageCredits:
|
||||
|
||||
def parseTable(start):
|
||||
table = {}
|
||||
with open("baserom/code","rb") as f:
|
||||
with open("extracted/n64-us/baserom/code","rb") as f:
|
||||
f.seek(start)
|
||||
buf = f.read(8)
|
||||
textId, typePos, segment = struct.unpack(">HBxI", buf)
|
||||
@ -183,14 +183,14 @@ def parseTable(start):
|
||||
|
||||
return table
|
||||
|
||||
STAFF_MESSAGE_TABLE_ADDR = 0x12A048 # Location of Staff message table in baserom/code
|
||||
STAFF_MESSAGE_TABLE_ADDR = 0x12A048 # Location of Staff message table in extracted/n64-us/baserom/code
|
||||
STAFF_SEGMENT_ADDR = 0x07000000
|
||||
|
||||
def main(outfile):
|
||||
msgTable = parseTable(STAFF_MESSAGE_TABLE_ADDR)
|
||||
|
||||
buf = []
|
||||
with open("baserom/staff_message_data_static", "rb") as f:
|
||||
with open("extracted/n64-us/baserom/staff_message_data_static", "rb") as f:
|
||||
buf = f.read()
|
||||
|
||||
bufLen = len(buf)
|
||||
|
@ -710,7 +710,7 @@ def null_or_ptr(w):
|
||||
# (name, vrom_st, vrom_end, vram_st, vram_end)
|
||||
def read_actor_ovl_tbl():
|
||||
actortbl = []
|
||||
with open(repo + "baserom/code","rb") as codefile:
|
||||
with open(repo + "baseroms/n64-us/code","rb") as codefile:
|
||||
codefile.seek(0x109510) # actor overlay table offset into code
|
||||
entry = as_word_list(codefile.read(0x20))
|
||||
i = 0
|
||||
|
@ -19,7 +19,7 @@ AUTOGENERATED_ASSET_NAME = re.compile(r".+0[0-9A-Fa-f]{5}")
|
||||
ASM_JMP_LABEL = re.compile(r"^(?P<name>L[0-9A-F]{8})$")
|
||||
|
||||
# TODO: consider making this a parameter of this script
|
||||
GAME_VERSION = "mm.us.rev1"
|
||||
GAME_VERSION = "n64-us"
|
||||
|
||||
def eprint(*args, **kwargs):
|
||||
print(*args, file=sys.stderr, **kwargs)
|
||||
@ -105,13 +105,13 @@ def CalculateNonNamedAssets(mapFileList, assetsTracker):
|
||||
for mapFile in mapFileList:
|
||||
if mapFile["section"] != ".data" and mapFile["section"] != ".rodata":
|
||||
continue
|
||||
if not mapFile["name"].startswith("build/assets/"):
|
||||
if not mapFile["name"].startswith("build/n64-us/assets/"):
|
||||
continue
|
||||
|
||||
if mapFile["name"].startswith("build/assets/c"):
|
||||
assetCat = mapFile["name"].split("/")[3]
|
||||
if mapFile["name"].startswith("build/n64-us/assets/c"):
|
||||
assetCat = mapFile["name"].split("/")[4]
|
||||
else:
|
||||
assetCat = mapFile["name"].split("/")[2]
|
||||
assetCat = mapFile["name"].split("/")[3]
|
||||
|
||||
|
||||
for symbol in mapFile["symbols"]:
|
||||
@ -122,7 +122,7 @@ def CalculateNonNamedAssets(mapFileList, assetsTracker):
|
||||
return assetsTracker
|
||||
|
||||
|
||||
map_file = ReadAllLines('build/mm.map')
|
||||
map_file = ReadAllLines('build/n64-us/mm-n64-us.map')
|
||||
|
||||
# Get list of Non-Matchings
|
||||
all_files = GetFiles("src", ".c")
|
||||
@ -217,7 +217,7 @@ for line in map_file:
|
||||
mapFileList.append(fileData)
|
||||
|
||||
if (section == ".text"):
|
||||
srcCat = obj_file.split("/")[2]
|
||||
srcCat = obj_file.split("/")[3]
|
||||
if srcCat in srcCategoriesFixer:
|
||||
srcCat = srcCategoriesFixer[srcCat]
|
||||
|
||||
@ -225,19 +225,19 @@ for line in map_file:
|
||||
correctSection = fileSectionFixer[objFileName]
|
||||
if correctSection in srcTracker:
|
||||
srcTracker[correctSection]["totalSize"] += file_size
|
||||
elif obj_file.startswith("build/src"):
|
||||
elif obj_file.startswith("build/n64-us/src"):
|
||||
if srcCat in srcTracker:
|
||||
srcTracker[srcCat]["totalSize"] += file_size
|
||||
elif (obj_file.startswith("build/asm")):
|
||||
elif (obj_file.startswith("build/n64-us/asm")):
|
||||
if srcCat in asmTracker:
|
||||
asmTracker[srcCat]["totalSize"] += file_size
|
||||
|
||||
if section == ".data" or section == ".rodata":
|
||||
if obj_file.startswith("build/assets/"):
|
||||
if obj_file.startswith("build/assets/c"):
|
||||
assetCat = obj_file.split("/")[3]
|
||||
if obj_file.startswith("build/n64-us/assets/"):
|
||||
if obj_file.startswith("build/n64-us/assets/c"):
|
||||
assetCat = obj_file.split("/")[4]
|
||||
else:
|
||||
assetCat = obj_file.split("/")[2]
|
||||
assetCat = obj_file.split("/")[3]
|
||||
if assetCat in assetsTracker:
|
||||
assetsTracker[assetCat]["currentSize"] += file_size
|
||||
elif assetCat in ignoredAssets:
|
||||
@ -318,7 +318,7 @@ for srcCat in asmTracker:
|
||||
# Calculate size of all assets
|
||||
for assetCat in assetsTracker:
|
||||
for index, f in assetsTracker[assetCat]["files"]:
|
||||
assetsTracker[assetCat]["totalSize"] += os.stat(os.path.join("baserom", f)).st_size
|
||||
assetsTracker[assetCat]["totalSize"] += os.stat(os.path.join("baseroms", "n64-us", "segments", f)).st_size
|
||||
|
||||
if args.matching:
|
||||
for assetCat in assetsTracker:
|
||||
|
@ -17,7 +17,7 @@ if "/overlays/actors/" not in str(file_path):
|
||||
exit()
|
||||
|
||||
map_path = file_path.parent.parent.parent.parent.parent
|
||||
map_lines = (map_path / "build" / "mm.map").read_text().splitlines()[10000:]
|
||||
map_lines = (map_path / "build" / "n64-us" / "mm-n64-us.map").read_text().splitlines()[10000:]
|
||||
|
||||
i = 0
|
||||
while not f"{file_path.stem}.o(.text)" in map_lines[i]:
|
||||
|
@ -10,5 +10,5 @@ make distclean
|
||||
make setup 2> tools/warnings_count/warnings_setup_current.txt
|
||||
make assets 2> tools/warnings_count/warnings_assets_current.txt
|
||||
make disasm 2> tools/warnings_count/warnings_disasm_current.txt
|
||||
make uncompressed 2> tools/warnings_count/warnings_build_current.txt
|
||||
make compressed 2> tools/warnings_count/warnings_compress_current.txt
|
||||
make rom 2> tools/warnings_count/warnings_build_current.txt
|
||||
make compress 2> tools/warnings_count/warnings_compress_current.txt
|
||||
|
@ -1,15 +0,0 @@
|
||||
root = true
|
||||
|
||||
[*]
|
||||
end_of_line = lf
|
||||
insert_final_newline = true
|
||||
|
||||
# Matches multiple files with brace expansion notation
|
||||
[*.{c,h,ch}]
|
||||
charset = utf-8
|
||||
indent_style = tab
|
||||
indent_size = 3
|
||||
trim_trailing_whitespace = false
|
||||
|
||||
[*.md]
|
||||
trim_trailing_whitespace = false
|
3
tools/z64compress/.gitignore
vendored
3
tools/z64compress/.gitignore
vendored
@ -1,3 +0,0 @@
|
||||
bin/
|
||||
o/
|
||||
z64compress
|
@ -1,12 +0,0 @@
|
||||
; DO NOT EDIT (unless you know what you are doing)
|
||||
;
|
||||
; This subdirectory is a git "subrepo", and this file is maintained by the
|
||||
; git-subrepo command. See https://github.com/git-commands/git-subrepo#readme
|
||||
;
|
||||
[subrepo]
|
||||
remote = https://github.com/z64me/z64compress.git
|
||||
branch = main
|
||||
commit = 5da3132606e4fd427a8d72b8428e4f921cd6e56f
|
||||
parent = 837eb1c80687fe9b57a3c7b841547c33feeed6c7
|
||||
method = merge
|
||||
cmdver = 0.4.3
|
@ -1,674 +0,0 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
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 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
@ -1,47 +0,0 @@
|
||||
CC := gcc
|
||||
CFLAGS := -DNDEBUG -s -Os -flto -Wall -Wextra
|
||||
|
||||
# Target platform, specify with TARGET= on the command line, linux64 is default.
|
||||
# Currently supported: linux64, linux32, win32
|
||||
TARGET ?= linux64
|
||||
|
||||
ifeq ($(TARGET),linux32)
|
||||
TARGET_CFLAGS := -m32
|
||||
else ifeq ($(TARGET),win32)
|
||||
# If using a cross compiler, specify the compiler executable on the command line.
|
||||
# make TARGET=win32 CC=~/c/mxe/usr/bin/i686-w64-mingw32.static-gcc
|
||||
TARGET_LIBS := -mconsole -municode
|
||||
else ifneq ($(TARGET),linux64)
|
||||
$(error Supported targets: linux64, linux32, win32)
|
||||
endif
|
||||
|
||||
# Whether to use native optimizations, specify with NATIVE_OPT=0/1 on the command line, default is 0.
|
||||
# This is not supported by all compilers which is particularly an issue on Mac, and may inhibit tests.
|
||||
NATIVE_OPT ?= 0
|
||||
ifeq ($(NATIVE_OPT),1)
|
||||
TARGET_CFLAGS += -march=native -mtune=native
|
||||
endif
|
||||
|
||||
OBJ_DIR := o/$(TARGET)
|
||||
|
||||
$(OBJ_DIR)/src/enc/%.o: CFLAGS := -DNDEBUG -s -Ofast -flto -Wall
|
||||
|
||||
SRC_DIRS := $(shell find src -type d)
|
||||
C_FILES := $(foreach dir,$(SRC_DIRS),$(wildcard $(dir)/*.c))
|
||||
O_FILES := $(foreach f,$(C_FILES:.c=.o),$(OBJ_DIR)/$f)
|
||||
|
||||
# Make build directories
|
||||
$(shell mkdir -p $(foreach dir,$(SRC_DIRS),$(OBJ_DIR)/$(dir)))
|
||||
|
||||
.PHONY: all clean
|
||||
|
||||
all: z64compress
|
||||
|
||||
z64compress: $(O_FILES)
|
||||
$(CC) $(TARGET_CFLAGS) $(CFLAGS) $(O_FILES) -lm -lpthread $(TARGET_LIBS) -o z64compress
|
||||
|
||||
$(OBJ_DIR)/%.o: %.c
|
||||
$(CC) -c $(TARGET_CFLAGS) $(CFLAGS) $< -o $@
|
||||
|
||||
clean:
|
||||
$(RM) -rf z64compress bin o
|
@ -1,94 +0,0 @@
|
||||
# z64compress
|
||||
|
||||
`z64compress` is a program for compressing Zelda 64 roms: be they retail, hacked traditionally, or custom-built from the [`Ocarina of Time`](https://github.com/zeldaret/oot) or [`Majora's Mask`](https://github.com/zeldaret/mm) reverse engineering projects. It is written in highly efficient C and leverages the power of multithreading to make compression as fast as possible. To reduce overhead on subsequent compressions, an optional cache directory can be specified.
|
||||
|
||||
In addition to the default `yaz`, it supports some faster and more compact algorithms such as `lzo`, `ucl`, and `aplib`. In order to use these, grab patches or code from my [`z64enc` repository](https://github.com/z64me/z64enc).
|
||||
|
||||
If you add an algorithm, please make sure `valgrind` reports no memory leaks or other errors before making a pull request. Thank you!
|
||||
|
||||
(By the way, `valgrind` works better without the `-march=native -mtune=native` optimizations, so turn those off when testing `valgrind`.)
|
||||
|
||||
## Usage
|
||||
This is a command line application. Learn from these common examples and adapt the arguments to your needs:
|
||||
```
|
||||
compressing oot debug
|
||||
--in "path/to/in.z64"
|
||||
--out "path/to/out.z64"
|
||||
--mb 32
|
||||
--codec yaz
|
||||
--cache "path/to/cache"
|
||||
--dma "0x12F70,1548"
|
||||
--compress "9-14,28-END"
|
||||
--threads 4
|
||||
|
||||
compressing oot ntsc 1.0
|
||||
--in "path/to/in.z64"
|
||||
--out "path/to/out.z64"
|
||||
--mb 32
|
||||
--codec yaz
|
||||
--cache "path/to/cache"
|
||||
--dma "0x7430,1526"
|
||||
--compress "10-14,27-END"
|
||||
--threads 4
|
||||
|
||||
compressing mm usa
|
||||
--in "path/to/in.z64"
|
||||
--out "path/to/out.z64"
|
||||
--mb 32
|
||||
--codec yaz
|
||||
--cache "path/to/cache"
|
||||
--dma "0x1A500,1568"
|
||||
--compress "10-14,23,24,31-END"
|
||||
--skip "1127"
|
||||
--repack "15-20,22"
|
||||
--threads 4
|
||||
```
|
||||
|
||||
## Arguments
|
||||
```
|
||||
--in uncompressed input rom
|
||||
|
||||
--out compressed output rom
|
||||
|
||||
--matching attempt matching compression at the cost of
|
||||
some optimizations and reduced performance
|
||||
|
||||
--mb how many mb the compressed rom should be
|
||||
|
||||
--codec currently supported codecs
|
||||
yaz
|
||||
ucl
|
||||
lzo
|
||||
aplib
|
||||
* to use non-yaz codecs, find patches
|
||||
and code on my z64enc repo
|
||||
|
||||
--cache is optional and won't be created if
|
||||
no path is specified (having a cache
|
||||
makes subsequent compressions faster)
|
||||
* pro-tip: linux users who don't want a
|
||||
cache to persist across power cycles
|
||||
can use the path "/tmp/z64compress"
|
||||
|
||||
--dma specify dmadata address and count
|
||||
|
||||
--compress enable compression on specified files
|
||||
|
||||
--skip disable compression on specified files
|
||||
|
||||
--repack handles Majora's Mask archives
|
||||
|
||||
--threads optional multithreading;
|
||||
exclude this argument to disable it
|
||||
|
||||
--only-stdout reserve stderr for errors and print
|
||||
everything else to stdout
|
||||
|
||||
arguments are executed as they
|
||||
are parsed, so order matters!
|
||||
```
|
||||
|
||||
## Building
|
||||
I have included shell scripts for building Linux and Windows binaries. Windows binaries are built using a cross compiler ([I recommend `MXE`](https://mxe.cc/)).
|
||||
|
||||
Alternatively, a Makefile-based build system is provided. Choose the target platform with `make TARGET=linux64|linux32|win32`, default is linux64. If building for windows with a cross compiler, specify the compiler executable with `make TARGET=win32 CC=/path/to/executable`.
|
@ -1,14 +0,0 @@
|
||||
# build compression functions (slow)
|
||||
gcc -DNDEBUG -s -Ofast -flto -lm -c -Wall -march=native -mtune=native src/enc/*.c src/enc/lzo/*.c src/enc/ucl/comp/*.c src/enc/apultra/*.c
|
||||
mkdir -p o
|
||||
mv *.o o
|
||||
|
||||
# build everything else
|
||||
gcc -o z64compress -DNDEBUG src/*.c o/*.o -Wall -Wextra -s -Os -flto -lpthread -march=native -mtune=native
|
||||
|
||||
# move to bin directory
|
||||
mkdir -p bin/linux64
|
||||
mv z64compress bin/linux64
|
||||
|
||||
|
||||
|
@ -1,14 +0,0 @@
|
||||
# build compression functions (slow)
|
||||
gcc -m32 -DNDEBUG -s -Ofast -flto -lm -c -Wall -march=native -mtune=native src/enc/*.c src/enc/lzo/*.c src/enc/ucl/comp/*.c src/enc/apultra/*.c
|
||||
mkdir -p o
|
||||
mv *.o o
|
||||
|
||||
# build everything else
|
||||
gcc -m32 -o z64compress -DNDEBUG src/*.c o/*.o -Wall -Wextra -s -Os -flto -lpthread -march=native -mtune=native
|
||||
|
||||
# move to bin directory
|
||||
mkdir -p bin/linux32
|
||||
mv z64compress bin/linux32
|
||||
|
||||
|
||||
|
@ -1,12 +0,0 @@
|
||||
# build compression functions (slow)
|
||||
~/c/mxe/usr/bin/i686-w64-mingw32.static-gcc -DNDEBUG -s -Ofast -flto -lm -c -Wall src/enc/*.c src/enc/lzo/*.c src/enc/ucl/comp/*.c src/enc/apultra/*.c
|
||||
mkdir -p o
|
||||
mv *.o o
|
||||
|
||||
# build everything else
|
||||
~/c/mxe/usr/bin/i686-w64-mingw32.static-gcc -o z64compress.exe -DNDEBUG src/*.c o/*.o -Wall -Wextra -s -Os -flto -lpthread -mconsole -municode
|
||||
|
||||
# move to bin directory
|
||||
mkdir -p bin/win32
|
||||
mv z64compress.exe bin/win32
|
||||
|
@ -1,48 +0,0 @@
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
#include "apultra/libapultra.h"
|
||||
|
||||
static void compression_progress(long long nOriginalSize, long long nCompressedSize) {
|
||||
/* do nothing */
|
||||
}
|
||||
|
||||
int
|
||||
aplenc(
|
||||
void *_src
|
||||
, unsigned src_sz
|
||||
, void *_dst
|
||||
, unsigned *dst_sz
|
||||
, void *_ctx
|
||||
)
|
||||
{
|
||||
unsigned char *src = _src;
|
||||
unsigned char *dst = _dst;
|
||||
int nMaxCompressedSize = apultra_get_max_compressed_size(src_sz);
|
||||
apultra_stats stats;
|
||||
|
||||
int hlen = 8; /* header length; required due to MM's archives */
|
||||
memset(dst, 0, hlen);
|
||||
memcpy(dst, "APL0", 4);
|
||||
dst[4] = (src_sz >> 24);
|
||||
dst[5] = (src_sz >> 16);
|
||||
dst[6] = (src_sz >> 8);
|
||||
dst[7] = (src_sz >> 0);
|
||||
|
||||
*dst_sz = apultra_compress(
|
||||
src
|
||||
, dst + hlen
|
||||
, src_sz
|
||||
, nMaxCompressedSize
|
||||
, 0 /* flags */
|
||||
, 0 /* nMaxWindowSize */
|
||||
, 0 /* nDictionarySize */
|
||||
, compression_progress
|
||||
, &stats
|
||||
);
|
||||
|
||||
*dst_sz = *dst_sz + hlen;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
File diff suppressed because it is too large
Load Diff
@ -1,460 +0,0 @@
|
||||
/*
|
||||
* divsufsort.c for libdivsufsort
|
||||
* Copyright (c) 2003-2008 Yuta Mori All Rights Reserved.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person
|
||||
* obtaining a copy of this software and associated documentation
|
||||
* files (the "Software"), to deal in the Software without
|
||||
* restriction, including without limitation the rights to use,
|
||||
* copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the
|
||||
* Software is furnished to do so, subject to the following
|
||||
* conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* 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 OR COPYRIGHT
|
||||
* HOLDERS 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.
|
||||
*/
|
||||
|
||||
#include "divsufsort_private.h"
|
||||
#ifdef _OPENMP
|
||||
# include <omp.h>
|
||||
#endif
|
||||
|
||||
|
||||
/*- Private Functions -*/
|
||||
|
||||
/* Sorts suffixes of type B*. */
|
||||
static
|
||||
saidx_t
|
||||
sort_typeBstar(const sauchar_t *T, saidx_t *SA,
|
||||
saidx_t *bucket_A, saidx_t *bucket_B,
|
||||
saidx_t n) {
|
||||
saidx_t *PAb, *ISAb, *buf;
|
||||
#ifdef _OPENMP
|
||||
saidx_t *curbuf;
|
||||
saidx_t l;
|
||||
#endif
|
||||
saidx_t i, j, k, t, m, bufsize;
|
||||
saint_t c0, c1;
|
||||
#ifdef _OPENMP
|
||||
saint_t d0, d1;
|
||||
int tmp;
|
||||
#endif
|
||||
|
||||
/* Initialize bucket arrays. */
|
||||
for(i = 0; i < BUCKET_A_SIZE; ++i) { bucket_A[i] = 0; }
|
||||
for(i = 0; i < BUCKET_B_SIZE; ++i) { bucket_B[i] = 0; }
|
||||
|
||||
/* Count the number of occurrences of the first one or two characters of each
|
||||
type A, B and B* suffix. Moreover, store the beginning position of all
|
||||
type B* suffixes into the array SA. */
|
||||
for(i = n - 1, m = n, c0 = T[n - 1]; 0 <= i;) {
|
||||
/* type A suffix. */
|
||||
do { ++BUCKET_A(c1 = c0); } while((0 <= --i) && ((c0 = T[i]) >= c1));
|
||||
if(0 <= i) {
|
||||
/* type B* suffix. */
|
||||
++BUCKET_BSTAR(c0, c1);
|
||||
SA[--m] = i;
|
||||
/* type B suffix. */
|
||||
for(--i, c1 = c0; (0 <= i) && ((c0 = T[i]) <= c1); --i, c1 = c0) {
|
||||
++BUCKET_B(c0, c1);
|
||||
}
|
||||
}
|
||||
}
|
||||
m = n - m;
|
||||
/*
|
||||
note:
|
||||
A type B* suffix is lexicographically smaller than a type B suffix that
|
||||
begins with the same first two characters.
|
||||
*/
|
||||
|
||||
/* Calculate the index of start/end point of each bucket. */
|
||||
for(c0 = 0, i = 0, j = 0; c0 < ALPHABET_SIZE; ++c0) {
|
||||
t = i + BUCKET_A(c0);
|
||||
BUCKET_A(c0) = i + j; /* start point */
|
||||
i = t + BUCKET_B(c0, c0);
|
||||
for(c1 = c0 + 1; c1 < ALPHABET_SIZE; ++c1) {
|
||||
j += BUCKET_BSTAR(c0, c1);
|
||||
BUCKET_BSTAR(c0, c1) = j; /* end point */
|
||||
i += BUCKET_B(c0, c1);
|
||||
}
|
||||
}
|
||||
|
||||
if(0 < m) {
|
||||
/* Sort the type B* suffixes by their first two characters. */
|
||||
PAb = SA + n - m; ISAb = SA + m;
|
||||
for(i = m - 2; 0 <= i; --i) {
|
||||
t = PAb[i], c0 = T[t], c1 = T[t + 1];
|
||||
SA[--BUCKET_BSTAR(c0, c1)] = i;
|
||||
}
|
||||
t = PAb[m - 1], c0 = T[t], c1 = T[t + 1];
|
||||
SA[--BUCKET_BSTAR(c0, c1)] = m - 1;
|
||||
|
||||
/* Sort the type B* substrings using sssort. */
|
||||
#ifdef _OPENMP
|
||||
tmp = omp_get_max_threads();
|
||||
buf = SA + m, bufsize = (n - (2 * m)) / tmp;
|
||||
c0 = ALPHABET_SIZE - 2, c1 = ALPHABET_SIZE - 1, j = m;
|
||||
#pragma omp parallel default(shared) private(curbuf, k, l, d0, d1, tmp)
|
||||
{
|
||||
tmp = omp_get_thread_num();
|
||||
curbuf = buf + tmp * bufsize;
|
||||
k = 0;
|
||||
for(;;) {
|
||||
#pragma omp critical(sssort_lock)
|
||||
{
|
||||
if(0 < (l = j)) {
|
||||
d0 = c0, d1 = c1;
|
||||
do {
|
||||
k = BUCKET_BSTAR(d0, d1);
|
||||
if(--d1 <= d0) {
|
||||
d1 = ALPHABET_SIZE - 1;
|
||||
if(--d0 < 0) { break; }
|
||||
}
|
||||
} while(((l - k) <= 1) && (0 < (l = k)));
|
||||
c0 = d0, c1 = d1, j = k;
|
||||
}
|
||||
}
|
||||
if(l == 0) { break; }
|
||||
sssort(T, PAb, SA + k, SA + l,
|
||||
curbuf, bufsize, 2, n, *(SA + k) == (m - 1));
|
||||
}
|
||||
}
|
||||
#else
|
||||
buf = SA + m, bufsize = n - (2 * m);
|
||||
for(c0 = ALPHABET_SIZE - 2, j = m; 0 < j; --c0) {
|
||||
for(c1 = ALPHABET_SIZE - 1; c0 < c1; j = i, --c1) {
|
||||
i = BUCKET_BSTAR(c0, c1);
|
||||
if(1 < (j - i)) {
|
||||
sssort(T, PAb, SA + i, SA + j,
|
||||
buf, bufsize, 2, n, *(SA + i) == (m - 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/* Compute ranks of type B* substrings. */
|
||||
for(i = m - 1; 0 <= i; --i) {
|
||||
if(0 <= SA[i]) {
|
||||
j = i;
|
||||
do { ISAb[SA[i]] = i; } while((0 <= --i) && (0 <= SA[i]));
|
||||
SA[i + 1] = i - j;
|
||||
if(i <= 0) { break; }
|
||||
}
|
||||
j = i;
|
||||
do { ISAb[SA[i] = ~SA[i]] = j; } while(SA[--i] < 0);
|
||||
ISAb[SA[i]] = j;
|
||||
}
|
||||
|
||||
/* Construct the inverse suffix array of type B* suffixes using trsort. */
|
||||
trsort(ISAb, SA, m, 1);
|
||||
|
||||
/* Set the sorted order of tyoe B* suffixes. */
|
||||
for(i = n - 1, j = m, c0 = T[n - 1]; 0 <= i;) {
|
||||
for(--i, c1 = c0; (0 <= i) && ((c0 = T[i]) >= c1); --i, c1 = c0) { }
|
||||
if(0 <= i) {
|
||||
t = i;
|
||||
for(--i, c1 = c0; (0 <= i) && ((c0 = T[i]) <= c1); --i, c1 = c0) { }
|
||||
SA[ISAb[--j]] = ((t == 0) || (1 < (t - i))) ? t : ~t;
|
||||
}
|
||||
}
|
||||
|
||||
/* Calculate the index of start/end point of each bucket. */
|
||||
BUCKET_B(ALPHABET_SIZE - 1, ALPHABET_SIZE - 1) = n; /* end point */
|
||||
for(c0 = ALPHABET_SIZE - 2, k = m - 1; 0 <= c0; --c0) {
|
||||
i = BUCKET_A(c0 + 1) - 1;
|
||||
for(c1 = ALPHABET_SIZE - 1; c0 < c1; --c1) {
|
||||
t = i - BUCKET_B(c0, c1);
|
||||
BUCKET_B(c0, c1) = i; /* end point */
|
||||
|
||||
/* Move all type B* suffixes to the correct position. */
|
||||
for(i = t, j = BUCKET_BSTAR(c0, c1);
|
||||
j <= k;
|
||||
--i, --k) { SA[i] = SA[k]; }
|
||||
}
|
||||
BUCKET_BSTAR(c0, c0 + 1) = i - BUCKET_B(c0, c0) + 1; /* start point */
|
||||
BUCKET_B(c0, c0) = i; /* end point */
|
||||
}
|
||||
}
|
||||
|
||||
return m;
|
||||
}
|
||||
|
||||
/* Constructs the suffix array by using the sorted order of type B* suffixes. */
|
||||
static
|
||||
void
|
||||
construct_SA(const sauchar_t *T, saidx_t *SA,
|
||||
saidx_t *bucket_A, saidx_t *bucket_B,
|
||||
saidx_t n, saidx_t m) {
|
||||
saidx_t *i, *j, *k;
|
||||
saidx_t s;
|
||||
saint_t c0, c1, c2;
|
||||
|
||||
if(0 < m) {
|
||||
/* Construct the sorted order of type B suffixes by using
|
||||
the sorted order of type B* suffixes. */
|
||||
for(c1 = ALPHABET_SIZE - 2; 0 <= c1; --c1) {
|
||||
/* Scan the suffix array from right to left. */
|
||||
for(i = SA + BUCKET_BSTAR(c1, c1 + 1),
|
||||
j = SA + BUCKET_A(c1 + 1) - 1, k = NULL, c2 = -1;
|
||||
i <= j;
|
||||
--j) {
|
||||
if(0 < (s = *j)) {
|
||||
assert(T[s] == c1);
|
||||
assert(((s + 1) < n) && (T[s] <= T[s + 1]));
|
||||
assert(T[s - 1] <= T[s]);
|
||||
*j = ~s;
|
||||
c0 = T[--s];
|
||||
if((0 < s) && (T[s - 1] > c0)) { s = ~s; }
|
||||
if(c0 != c2) {
|
||||
if(0 <= c2) { BUCKET_B(c2, c1) = k - SA; }
|
||||
k = SA + BUCKET_B(c2 = c0, c1);
|
||||
}
|
||||
assert(k < j);
|
||||
*k-- = s;
|
||||
} else {
|
||||
assert(((s == 0) && (T[s] == c1)) || (s < 0));
|
||||
*j = ~s;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Construct the suffix array by using
|
||||
the sorted order of type B suffixes. */
|
||||
k = SA + BUCKET_A(c2 = T[n - 1]);
|
||||
*k++ = (T[n - 2] < c2) ? ~(n - 1) : (n - 1);
|
||||
/* Scan the suffix array from left to right. */
|
||||
for(i = SA, j = SA + n; i < j; ++i) {
|
||||
if(0 < (s = *i)) {
|
||||
assert(T[s - 1] >= T[s]);
|
||||
c0 = T[--s];
|
||||
if((s == 0) || (T[s - 1] < c0)) { s = ~s; }
|
||||
if(c0 != c2) {
|
||||
BUCKET_A(c2) = k - SA;
|
||||
k = SA + BUCKET_A(c2 = c0);
|
||||
}
|
||||
assert(i < k);
|
||||
*k++ = s;
|
||||
} else {
|
||||
assert(s < 0);
|
||||
*i = ~s;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if 0
|
||||
/* Constructs the burrows-wheeler transformed string directly
|
||||
by using the sorted order of type B* suffixes. */
|
||||
static
|
||||
saidx_t
|
||||
construct_BWT(const sauchar_t *T, saidx_t *SA,
|
||||
saidx_t *bucket_A, saidx_t *bucket_B,
|
||||
saidx_t n, saidx_t m) {
|
||||
saidx_t *i, *j, *k, *orig;
|
||||
saidx_t s;
|
||||
saint_t c0, c1, c2;
|
||||
|
||||
if(0 < m) {
|
||||
/* Construct the sorted order of type B suffixes by using
|
||||
the sorted order of type B* suffixes. */
|
||||
for(c1 = ALPHABET_SIZE - 2; 0 <= c1; --c1) {
|
||||
/* Scan the suffix array from right to left. */
|
||||
for(i = SA + BUCKET_BSTAR(c1, c1 + 1),
|
||||
j = SA + BUCKET_A(c1 + 1) - 1, k = NULL, c2 = -1;
|
||||
i <= j;
|
||||
--j) {
|
||||
if(0 < (s = *j)) {
|
||||
assert(T[s] == c1);
|
||||
assert(((s + 1) < n) && (T[s] <= T[s + 1]));
|
||||
assert(T[s - 1] <= T[s]);
|
||||
c0 = T[--s];
|
||||
*j = ~((saidx_t)c0);
|
||||
if((0 < s) && (T[s - 1] > c0)) { s = ~s; }
|
||||
if(c0 != c2) {
|
||||
if(0 <= c2) { BUCKET_B(c2, c1) = k - SA; }
|
||||
k = SA + BUCKET_B(c2 = c0, c1);
|
||||
}
|
||||
assert(k < j);
|
||||
*k-- = s;
|
||||
} else if(s != 0) {
|
||||
*j = ~s;
|
||||
#ifndef NDEBUG
|
||||
} else {
|
||||
assert(T[s] == c1);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Construct the BWTed string by using
|
||||
the sorted order of type B suffixes. */
|
||||
k = SA + BUCKET_A(c2 = T[n - 1]);
|
||||
*k++ = (T[n - 2] < c2) ? ~((saidx_t)T[n - 2]) : (n - 1);
|
||||
/* Scan the suffix array from left to right. */
|
||||
for(i = SA, j = SA + n, orig = SA; i < j; ++i) {
|
||||
if(0 < (s = *i)) {
|
||||
assert(T[s - 1] >= T[s]);
|
||||
c0 = T[--s];
|
||||
*i = c0;
|
||||
if((0 < s) && (T[s - 1] < c0)) { s = ~((saidx_t)T[s - 1]); }
|
||||
if(c0 != c2) {
|
||||
BUCKET_A(c2) = k - SA;
|
||||
k = SA + BUCKET_A(c2 = c0);
|
||||
}
|
||||
assert(i < k);
|
||||
*k++ = s;
|
||||
} else if(s != 0) {
|
||||
*i = ~s;
|
||||
} else {
|
||||
orig = i;
|
||||
}
|
||||
}
|
||||
|
||||
return orig - SA;
|
||||
}
|
||||
#endif
|
||||
|
||||
/*---------------------------------------------------------------------------*/
|
||||
|
||||
/**
|
||||
* Initialize suffix array context
|
||||
*
|
||||
* @return 0 for success, or non-zero in case of an error
|
||||
*/
|
||||
int divsufsort_init(divsufsort_ctx_t *ctx) {
|
||||
ctx->bucket_A = (saidx_t *)malloc(BUCKET_A_SIZE * sizeof(saidx_t));
|
||||
ctx->bucket_B = NULL;
|
||||
|
||||
if (ctx->bucket_A) {
|
||||
ctx->bucket_B = (saidx_t *)malloc(BUCKET_B_SIZE * sizeof(saidx_t));
|
||||
|
||||
if (ctx->bucket_B)
|
||||
return 0;
|
||||
}
|
||||
|
||||
divsufsort_destroy(ctx);
|
||||
return -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Destroy suffix array context
|
||||
*
|
||||
* @param ctx suffix array context to destroy
|
||||
*/
|
||||
void divsufsort_destroy(divsufsort_ctx_t *ctx) {
|
||||
if (ctx->bucket_B) {
|
||||
free(ctx->bucket_B);
|
||||
ctx->bucket_B = NULL;
|
||||
}
|
||||
|
||||
if (ctx->bucket_A) {
|
||||
free(ctx->bucket_A);
|
||||
ctx->bucket_A = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
/*- Function -*/
|
||||
|
||||
saint_t
|
||||
divsufsort_build_array(divsufsort_ctx_t *ctx, const sauchar_t *T, saidx_t *SA, saidx_t n) {
|
||||
saidx_t m;
|
||||
saint_t err = 0;
|
||||
|
||||
/* Check arguments. */
|
||||
if((T == NULL) || (SA == NULL) || (n < 0)) { return -1; }
|
||||
else if(n == 0) { return 0; }
|
||||
else if(n == 1) { SA[0] = 0; return 0; }
|
||||
else if(n == 2) { m = (T[0] < T[1]); SA[m ^ 1] = 0, SA[m] = 1; return 0; }
|
||||
|
||||
/* Suffixsort. */
|
||||
if((ctx->bucket_A != NULL) && (ctx->bucket_B != NULL)) {
|
||||
m = sort_typeBstar(T, SA, ctx->bucket_A, ctx->bucket_B, n);
|
||||
construct_SA(T, SA, ctx->bucket_A, ctx->bucket_B, n, m);
|
||||
} else {
|
||||
err = -2;
|
||||
}
|
||||
|
||||
return err;
|
||||
}
|
||||
|
||||
#if 0
|
||||
saidx_t
|
||||
divbwt(const sauchar_t *T, sauchar_t *U, saidx_t *A, saidx_t n) {
|
||||
saidx_t *B;
|
||||
saidx_t *bucket_A, *bucket_B;
|
||||
saidx_t m, pidx, i;
|
||||
|
||||
/* Check arguments. */
|
||||
if((T == NULL) || (U == NULL) || (n < 0)) { return -1; }
|
||||
else if(n <= 1) { if(n == 1) { U[0] = T[0]; } return n; }
|
||||
|
||||
if((B = A) == NULL) { B = (saidx_t *)malloc((size_t)(n + 1) * sizeof(saidx_t)); }
|
||||
bucket_A = (saidx_t *)malloc(BUCKET_A_SIZE * sizeof(saidx_t));
|
||||
bucket_B = (saidx_t *)malloc(BUCKET_B_SIZE * sizeof(saidx_t));
|
||||
|
||||
/* Burrows-Wheeler Transform. */
|
||||
if((B != NULL) && (bucket_A != NULL) && (bucket_B != NULL)) {
|
||||
m = sort_typeBstar(T, B, bucket_A, bucket_B, n);
|
||||
pidx = construct_BWT(T, B, bucket_A, bucket_B, n, m);
|
||||
|
||||
/* Copy to output string. */
|
||||
U[0] = T[n - 1];
|
||||
for(i = 0; i < pidx; ++i) { U[i + 1] = (sauchar_t)B[i]; }
|
||||
for(i += 1; i < n; ++i) { U[i] = (sauchar_t)B[i]; }
|
||||
pidx += 1;
|
||||
} else {
|
||||
pidx = -2;
|
||||
}
|
||||
|
||||
free(bucket_B);
|
||||
free(bucket_A);
|
||||
if(A == NULL) { free(B); }
|
||||
|
||||
return pidx;
|
||||
}
|
||||
|
||||
const char *
|
||||
divsufsort_version(void) {
|
||||
return PROJECT_VERSION_FULL;
|
||||
}
|
||||
#endif
|
||||
|
||||
saint_t
|
||||
divsufsort(const sauchar_t *T, saidx_t *SA, saidx_t n) {
|
||||
saidx_t *bucket_A, *bucket_B;
|
||||
saidx_t m;
|
||||
saint_t err = 0;
|
||||
|
||||
/* Check arguments. */
|
||||
if((T == NULL) || (SA == NULL) || (n < 0)) { return -1; }
|
||||
else if(n == 0) { return 0; }
|
||||
else if(n == 1) { SA[0] = 0; return 0; }
|
||||
else if(n == 2) { m = (T[0] < T[1]); SA[m ^ 1] = 0, SA[m] = 1; return 0; }
|
||||
|
||||
bucket_A = (saidx_t *)malloc(BUCKET_A_SIZE * sizeof(saidx_t));
|
||||
bucket_B = (saidx_t *)malloc(BUCKET_B_SIZE * sizeof(saidx_t));
|
||||
|
||||
/* Suffixsort. */
|
||||
if((bucket_A != NULL) && (bucket_B != NULL)) {
|
||||
m = sort_typeBstar(T, SA, bucket_A, bucket_B, n);
|
||||
construct_SA(T, SA, bucket_A, bucket_B, n, m);
|
||||
} else {
|
||||
err = -2;
|
||||
}
|
||||
|
||||
free(bucket_B);
|
||||
free(bucket_A);
|
||||
|
||||
return err;
|
||||
}
|
@ -1,192 +0,0 @@
|
||||
/*
|
||||
* divsufsort.h for libdivsufsort
|
||||
* Copyright (c) 2003-2008 Yuta Mori All Rights Reserved.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person
|
||||
* obtaining a copy of this software and associated documentation
|
||||
* files (the "Software"), to deal in the Software without
|
||||
* restriction, including without limitation the rights to use,
|
||||
* copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the
|
||||
* Software is furnished to do so, subject to the following
|
||||
* conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* 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 OR COPYRIGHT
|
||||
* HOLDERS 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.
|
||||
*/
|
||||
|
||||
#ifndef _DIVSUFSORT_H
|
||||
#define _DIVSUFSORT_H 1
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif /* __cplusplus */
|
||||
|
||||
#define DIVSUFSORT_API
|
||||
|
||||
/*- Datatypes -*/
|
||||
#ifndef SAUCHAR_T
|
||||
#define SAUCHAR_T
|
||||
typedef unsigned char sauchar_t;
|
||||
#endif /* SAUCHAR_T */
|
||||
#ifndef SAINT_T
|
||||
#define SAINT_T
|
||||
typedef int saint_t;
|
||||
#endif /* SAINT_T */
|
||||
#ifndef SAIDX_T
|
||||
#define SAIDX_T
|
||||
typedef int saidx_t;
|
||||
#endif /* SAIDX_T */
|
||||
#ifndef PRIdSAIDX_T
|
||||
#define PRIdSAIDX_T "d"
|
||||
#endif
|
||||
|
||||
/*- divsufsort context */
|
||||
typedef struct _divsufsort_ctx_t {
|
||||
saidx_t *bucket_A;
|
||||
saidx_t *bucket_B;
|
||||
} divsufsort_ctx_t;
|
||||
|
||||
/*- Prototypes -*/
|
||||
|
||||
/**
|
||||
* Initialize suffix array context
|
||||
*
|
||||
* @return 0 for success, or non-zero in case of an error
|
||||
*/
|
||||
int divsufsort_init(divsufsort_ctx_t *ctx);
|
||||
|
||||
/**
|
||||
* Destroy suffix array context
|
||||
*
|
||||
* @param ctx suffix array context to destroy
|
||||
*/
|
||||
void divsufsort_destroy(divsufsort_ctx_t *ctx);
|
||||
|
||||
/**
|
||||
* Constructs the suffix array of a given string.
|
||||
* @param ctx suffix array context
|
||||
* @param T[0..n-1] The input string.
|
||||
* @param SA[0..n-1] The output array of suffixes.
|
||||
* @param n The length of the given string.
|
||||
* @return 0 if no error occurred, -1 or -2 otherwise.
|
||||
*/
|
||||
DIVSUFSORT_API
|
||||
saint_t divsufsort_build_array(divsufsort_ctx_t *ctx, const sauchar_t *T, saidx_t *SA, saidx_t n);
|
||||
|
||||
#if 0
|
||||
/**
|
||||
* Constructs the burrows-wheeler transformed string of a given string.
|
||||
* @param T[0..n-1] The input string.
|
||||
* @param U[0..n-1] The output string. (can be T)
|
||||
* @param A[0..n-1] The temporary array. (can be NULL)
|
||||
* @param n The length of the given string.
|
||||
* @return The primary index if no error occurred, -1 or -2 otherwise.
|
||||
*/
|
||||
DIVSUFSORT_API
|
||||
saidx_t
|
||||
divbwt(const sauchar_t *T, sauchar_t *U, saidx_t *A, saidx_t n);
|
||||
|
||||
/**
|
||||
* Returns the version of the divsufsort library.
|
||||
* @return The version number string.
|
||||
*/
|
||||
DIVSUFSORT_API
|
||||
const char *
|
||||
divsufsort_version(void);
|
||||
|
||||
|
||||
/**
|
||||
* Constructs the burrows-wheeler transformed string of a given string and suffix array.
|
||||
* @param T[0..n-1] The input string.
|
||||
* @param U[0..n-1] The output string. (can be T)
|
||||
* @param SA[0..n-1] The suffix array. (can be NULL)
|
||||
* @param n The length of the given string.
|
||||
* @param idx The output primary index.
|
||||
* @return 0 if no error occurred, -1 or -2 otherwise.
|
||||
*/
|
||||
DIVSUFSORT_API
|
||||
saint_t
|
||||
bw_transform(const sauchar_t *T, sauchar_t *U,
|
||||
saidx_t *SA /* can NULL */,
|
||||
saidx_t n, saidx_t *idx);
|
||||
|
||||
/**
|
||||
* Inverse BW-transforms a given BWTed string.
|
||||
* @param T[0..n-1] The input string.
|
||||
* @param U[0..n-1] The output string. (can be T)
|
||||
* @param A[0..n-1] The temporary array. (can be NULL)
|
||||
* @param n The length of the given string.
|
||||
* @param idx The primary index.
|
||||
* @return 0 if no error occurred, -1 or -2 otherwise.
|
||||
*/
|
||||
DIVSUFSORT_API
|
||||
saint_t
|
||||
inverse_bw_transform(const sauchar_t *T, sauchar_t *U,
|
||||
saidx_t *A /* can NULL */,
|
||||
saidx_t n, saidx_t idx);
|
||||
|
||||
/**
|
||||
* Checks the correctness of a given suffix array.
|
||||
* @param T[0..n-1] The input string.
|
||||
* @param SA[0..n-1] The input suffix array.
|
||||
* @param n The length of the given string.
|
||||
* @param verbose The verbose mode.
|
||||
* @return 0 if no error occurred.
|
||||
*/
|
||||
DIVSUFSORT_API
|
||||
saint_t
|
||||
sufcheck(const sauchar_t *T, const saidx_t *SA, saidx_t n, saint_t verbose);
|
||||
|
||||
/**
|
||||
* Search for the pattern P in the string T.
|
||||
* @param T[0..Tsize-1] The input string.
|
||||
* @param Tsize The length of the given string.
|
||||
* @param P[0..Psize-1] The input pattern string.
|
||||
* @param Psize The length of the given pattern string.
|
||||
* @param SA[0..SAsize-1] The input suffix array.
|
||||
* @param SAsize The length of the given suffix array.
|
||||
* @param idx The output index.
|
||||
* @return The count of matches if no error occurred, -1 otherwise.
|
||||
*/
|
||||
DIVSUFSORT_API
|
||||
saidx_t
|
||||
sa_search(const sauchar_t *T, saidx_t Tsize,
|
||||
const sauchar_t *P, saidx_t Psize,
|
||||
const saidx_t *SA, saidx_t SAsize,
|
||||
saidx_t *left);
|
||||
|
||||
/**
|
||||
* Search for the character c in the string T.
|
||||
* @param T[0..Tsize-1] The input string.
|
||||
* @param Tsize The length of the given string.
|
||||
* @param SA[0..SAsize-1] The input suffix array.
|
||||
* @param SAsize The length of the given suffix array.
|
||||
* @param c The input character.
|
||||
* @param idx The output index.
|
||||
* @return The count of matches if no error occurred, -1 otherwise.
|
||||
*/
|
||||
DIVSUFSORT_API
|
||||
saidx_t
|
||||
sa_simplesearch(const sauchar_t *T, saidx_t Tsize,
|
||||
const saidx_t *SA, saidx_t SAsize,
|
||||
saint_t c, saidx_t *left);
|
||||
#endif
|
||||
|
||||
saint_t
|
||||
divsufsort(const sauchar_t *T, saidx_t *SA, saidx_t n);
|
||||
|
||||
#ifdef __cplusplus
|
||||
} /* extern "C" */
|
||||
#endif /* __cplusplus */
|
||||
|
||||
#endif /* _DIVSUFSORT_H */
|
@ -1,9 +0,0 @@
|
||||
#define HAVE_STRING_H 1
|
||||
#define HAVE_STDLIB_H 1
|
||||
#define HAVE_MEMORY_H 1
|
||||
#define HAVE_STDINT_H 1
|
||||
#define INLINE inline
|
||||
|
||||
#ifdef _MSC_VER
|
||||
#pragma warning( disable : 4244 )
|
||||
#endif /* _MSC_VER */
|
@ -1,205 +0,0 @@
|
||||
/*
|
||||
* divsufsort_private.h for libdivsufsort
|
||||
* Copyright (c) 2003-2008 Yuta Mori All Rights Reserved.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person
|
||||
* obtaining a copy of this software and associated documentation
|
||||
* files (the "Software"), to deal in the Software without
|
||||
* restriction, including without limitation the rights to use,
|
||||
* copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the
|
||||
* Software is furnished to do so, subject to the following
|
||||
* conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* 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 OR COPYRIGHT
|
||||
* HOLDERS 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.
|
||||
*/
|
||||
|
||||
#ifndef _DIVSUFSORT_PRIVATE_H
|
||||
#define _DIVSUFSORT_PRIVATE_H 1
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif /* __cplusplus */
|
||||
|
||||
#include "divsufsort_config.h"
|
||||
#include <assert.h>
|
||||
#include <stdio.h>
|
||||
#if HAVE_STRING_H
|
||||
# include <string.h>
|
||||
#endif
|
||||
#if HAVE_STDLIB_H
|
||||
# include <stdlib.h>
|
||||
#endif
|
||||
#if HAVE_MEMORY_H
|
||||
# include <memory.h>
|
||||
#endif
|
||||
#if HAVE_STDDEF_H
|
||||
# include <stddef.h>
|
||||
#endif
|
||||
#if HAVE_STRINGS_H
|
||||
# include <strings.h>
|
||||
#endif
|
||||
#if HAVE_INTTYPES_H
|
||||
# include <inttypes.h>
|
||||
#else
|
||||
# if HAVE_STDINT_H
|
||||
# include <stdint.h>
|
||||
# endif
|
||||
#endif
|
||||
#if defined(BUILD_DIVSUFSORT64)
|
||||
# include "divsufsort64.h"
|
||||
# ifndef SAIDX_T
|
||||
# define SAIDX_T
|
||||
# define saidx_t saidx64_t
|
||||
# endif /* SAIDX_T */
|
||||
# ifndef PRIdSAIDX_T
|
||||
# define PRIdSAIDX_T PRIdSAIDX64_T
|
||||
# endif /* PRIdSAIDX_T */
|
||||
# define divsufsort divsufsort64
|
||||
# define divbwt divbwt64
|
||||
# define divsufsort_version divsufsort64_version
|
||||
# define bw_transform bw_transform64
|
||||
# define inverse_bw_transform inverse_bw_transform64
|
||||
# define sufcheck sufcheck64
|
||||
# define sa_search sa_search64
|
||||
# define sa_simplesearch sa_simplesearch64
|
||||
# define sssort sssort64
|
||||
# define trsort trsort64
|
||||
#else
|
||||
# include "divsufsort.h"
|
||||
#endif
|
||||
|
||||
|
||||
/*- Constants -*/
|
||||
#if !defined(UINT8_MAX)
|
||||
# define UINT8_MAX (255)
|
||||
#endif /* UINT8_MAX */
|
||||
#if defined(ALPHABET_SIZE) && (ALPHABET_SIZE < 1)
|
||||
# undef ALPHABET_SIZE
|
||||
#endif
|
||||
#if !defined(ALPHABET_SIZE)
|
||||
# define ALPHABET_SIZE (UINT8_MAX + 1)
|
||||
#endif
|
||||
/* for divsufsort.c */
|
||||
#define BUCKET_A_SIZE (ALPHABET_SIZE)
|
||||
#define BUCKET_B_SIZE (ALPHABET_SIZE * ALPHABET_SIZE)
|
||||
/* for sssort.c */
|
||||
#if defined(SS_INSERTIONSORT_THRESHOLD)
|
||||
# if SS_INSERTIONSORT_THRESHOLD < 1
|
||||
# undef SS_INSERTIONSORT_THRESHOLD
|
||||
# define SS_INSERTIONSORT_THRESHOLD (1)
|
||||
# endif
|
||||
#else
|
||||
# define SS_INSERTIONSORT_THRESHOLD (8)
|
||||
#endif
|
||||
#if defined(SS_BLOCKSIZE)
|
||||
# if SS_BLOCKSIZE < 0
|
||||
# undef SS_BLOCKSIZE
|
||||
# define SS_BLOCKSIZE (0)
|
||||
# elif 32768 <= SS_BLOCKSIZE
|
||||
# undef SS_BLOCKSIZE
|
||||
# define SS_BLOCKSIZE (32767)
|
||||
# endif
|
||||
#else
|
||||
# define SS_BLOCKSIZE (1024)
|
||||
#endif
|
||||
/* minstacksize = log(SS_BLOCKSIZE) / log(3) * 2 */
|
||||
#if SS_BLOCKSIZE == 0
|
||||
# if defined(BUILD_DIVSUFSORT64)
|
||||
# define SS_MISORT_STACKSIZE (96)
|
||||
# else
|
||||
# define SS_MISORT_STACKSIZE (64)
|
||||
# endif
|
||||
#elif SS_BLOCKSIZE <= 4096
|
||||
# define SS_MISORT_STACKSIZE (16)
|
||||
#else
|
||||
# define SS_MISORT_STACKSIZE (24)
|
||||
#endif
|
||||
#if defined(BUILD_DIVSUFSORT64)
|
||||
# define SS_SMERGE_STACKSIZE (64)
|
||||
#else
|
||||
# define SS_SMERGE_STACKSIZE (32)
|
||||
#endif
|
||||
/* for trsort.c */
|
||||
#define TR_INSERTIONSORT_THRESHOLD (8)
|
||||
#if defined(BUILD_DIVSUFSORT64)
|
||||
# define TR_STACKSIZE (96)
|
||||
#else
|
||||
# define TR_STACKSIZE (64)
|
||||
#endif
|
||||
|
||||
|
||||
/*- Macros -*/
|
||||
#ifndef SWAP
|
||||
# define SWAP(_a, _b) do { t = (_a); (_a) = (_b); (_b) = t; } while(0)
|
||||
#endif /* SWAP */
|
||||
#ifndef MIN
|
||||
# define MIN(_a, _b) (((_a) < (_b)) ? (_a) : (_b))
|
||||
#endif /* MIN */
|
||||
#ifndef MAX
|
||||
# define MAX(_a, _b) (((_a) > (_b)) ? (_a) : (_b))
|
||||
#endif /* MAX */
|
||||
#define STACK_PUSH(_a, _b, _c, _d)\
|
||||
do {\
|
||||
assert(ssize < STACK_SIZE);\
|
||||
stack[ssize].a = (_a), stack[ssize].b = (_b),\
|
||||
stack[ssize].c = (_c), stack[ssize++].d = (_d);\
|
||||
} while(0)
|
||||
#define STACK_PUSH5(_a, _b, _c, _d, _e)\
|
||||
do {\
|
||||
assert(ssize < STACK_SIZE);\
|
||||
stack[ssize].a = (_a), stack[ssize].b = (_b),\
|
||||
stack[ssize].c = (_c), stack[ssize].d = (_d), stack[ssize++].e = (_e);\
|
||||
} while(0)
|
||||
#define STACK_POP(_a, _b, _c, _d)\
|
||||
do {\
|
||||
assert(0 <= ssize);\
|
||||
if(ssize == 0) { return; }\
|
||||
(_a) = stack[--ssize].a, (_b) = stack[ssize].b,\
|
||||
(_c) = stack[ssize].c, (_d) = stack[ssize].d;\
|
||||
} while(0)
|
||||
#define STACK_POP5(_a, _b, _c, _d, _e)\
|
||||
do {\
|
||||
assert(0 <= ssize);\
|
||||
if(ssize == 0) { return; }\
|
||||
(_a) = stack[--ssize].a, (_b) = stack[ssize].b,\
|
||||
(_c) = stack[ssize].c, (_d) = stack[ssize].d, (_e) = stack[ssize].e;\
|
||||
} while(0)
|
||||
/* for divsufsort.c */
|
||||
#define BUCKET_A(_c0) bucket_A[(_c0)]
|
||||
#if ALPHABET_SIZE == 256
|
||||
#define BUCKET_B(_c0, _c1) (bucket_B[((_c1) << 8) | (_c0)])
|
||||
#define BUCKET_BSTAR(_c0, _c1) (bucket_B[((_c0) << 8) | (_c1)])
|
||||
#else
|
||||
#define BUCKET_B(_c0, _c1) (bucket_B[(_c1) * ALPHABET_SIZE + (_c0)])
|
||||
#define BUCKET_BSTAR(_c0, _c1) (bucket_B[(_c0) * ALPHABET_SIZE + (_c1)])
|
||||
#endif
|
||||
|
||||
|
||||
/*- Private Prototypes -*/
|
||||
/* sssort.c */
|
||||
void
|
||||
sssort(const sauchar_t *Td, const saidx_t *PA,
|
||||
saidx_t *first, saidx_t *last,
|
||||
saidx_t *buf, saidx_t bufsize,
|
||||
saidx_t depth, saidx_t n, saint_t lastsuffix);
|
||||
/* trsort.c */
|
||||
void
|
||||
trsort(saidx_t *ISA, saidx_t *SA, saidx_t n, saidx_t depth);
|
||||
|
||||
|
||||
#ifdef __cplusplus
|
||||
} /* extern "C" */
|
||||
#endif /* __cplusplus */
|
||||
|
||||
#endif /* _DIVSUFSORT_PRIVATE_H */
|
@ -1,396 +0,0 @@
|
||||
/*
|
||||
* expand.c - decompressor implementation
|
||||
*
|
||||
* Copyright (C) 2019 Emmanuel Marty
|
||||
*
|
||||
* This software is provided 'as-is', without any express or implied
|
||||
* warranty. In no event will the authors be held liable for any damages
|
||||
* arising from the use of this software.
|
||||
*
|
||||
* Permission is granted to anyone to use this software for any purpose,
|
||||
* including commercial applications, and to alter it and redistribute it
|
||||
* freely, subject to the following restrictions:
|
||||
*
|
||||
* 1. The origin of this software must not be misrepresented; you must not
|
||||
* claim that you wrote the original software. If you use this software
|
||||
* in a product, an acknowledgment in the product documentation would be
|
||||
* appreciated but is not required.
|
||||
* 2. Altered source versions must be plainly marked as such, and must not be
|
||||
* misrepresented as being the original software.
|
||||
* 3. This notice may not be removed or altered from any source distribution.
|
||||
*/
|
||||
|
||||
/*
|
||||
* Uses the libdivsufsort library Copyright (c) 2003-2008 Yuta Mori
|
||||
*
|
||||
* Inspired by cap by Sven-Åke Dahl. https://github.com/svendahl/cap
|
||||
* Also inspired by Charles Bloom's compression blog. http://cbloomrants.blogspot.com/
|
||||
* With ideas from LZ4 by Yann Collet. https://github.com/lz4/lz4
|
||||
* With help and support from spke <zxintrospec@gmail.com>
|
||||
*
|
||||
*/
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include "format.h"
|
||||
#include "expand.h"
|
||||
#include "libapultra.h"
|
||||
|
||||
#ifdef _MSC_VER
|
||||
#define FORCE_INLINE __forceinline
|
||||
#else /* _MSC_VER */
|
||||
#define FORCE_INLINE __attribute__((always_inline))
|
||||
#endif /* _MSC_VER */
|
||||
|
||||
static inline FORCE_INLINE int apultra_read_bit(const unsigned char **ppInBlock, const unsigned char *pDataEnd, int *nCurBitMask, unsigned char *bits) {
|
||||
const unsigned char *pInBlock = *ppInBlock;
|
||||
int nBit;
|
||||
|
||||
if ((*nCurBitMask) == 0) {
|
||||
if (pInBlock >= pDataEnd) return -1;
|
||||
(*bits) = *pInBlock++;
|
||||
(*nCurBitMask) = 128;
|
||||
}
|
||||
|
||||
nBit = ((*bits) & 128) ? 1 : 0;
|
||||
|
||||
(*bits) <<= 1;
|
||||
(*nCurBitMask) >>= 1;
|
||||
|
||||
*ppInBlock = pInBlock;
|
||||
return nBit;
|
||||
}
|
||||
|
||||
static inline FORCE_INLINE int apultra_read_gamma2(const unsigned char **ppInBlock, const unsigned char *pDataEnd, int *nCurBitMask, unsigned char *bits) {
|
||||
int bit;
|
||||
unsigned int v = 1;
|
||||
|
||||
do {
|
||||
v = (v << 1) + apultra_read_bit(ppInBlock, pDataEnd, nCurBitMask, bits);
|
||||
bit = apultra_read_bit(ppInBlock, pDataEnd, nCurBitMask, bits);
|
||||
if (bit < 0) return bit;
|
||||
} while (bit);
|
||||
|
||||
return v;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get maximum decompressed size of compressed data
|
||||
*
|
||||
* @param pInputData compressed data
|
||||
* @param nInputSize compressed size in bytes
|
||||
* @param nFlags compression flags (set to 0)
|
||||
*
|
||||
* @return maximum decompressed size
|
||||
*/
|
||||
size_t apultra_get_max_decompressed_size(const unsigned char *pInputData, size_t nInputSize, const unsigned int nFlags) {
|
||||
const unsigned char *pInputDataEnd = pInputData + nInputSize;
|
||||
int nCurBitMask = 0;
|
||||
unsigned char bits = 0;
|
||||
int nMatchOffset = -1;
|
||||
int nFollowsLiteral = 3;
|
||||
size_t nDecompressedSize = 0;
|
||||
|
||||
if (pInputData >= pInputDataEnd)
|
||||
return -1;
|
||||
pInputData++;
|
||||
nDecompressedSize++;
|
||||
|
||||
while (1) {
|
||||
int nResult;
|
||||
|
||||
nResult = apultra_read_bit(&pInputData, pInputDataEnd, &nCurBitMask, &bits);
|
||||
if (nResult < 0) return -1;
|
||||
|
||||
if (!nResult) {
|
||||
/* '0': literal */
|
||||
if (pInputData < pInputDataEnd) {
|
||||
pInputData++;
|
||||
nDecompressedSize++;
|
||||
nFollowsLiteral = 3;
|
||||
}
|
||||
else {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
else {
|
||||
nResult = apultra_read_bit(&pInputData, pInputDataEnd, &nCurBitMask, &bits);
|
||||
if (nResult < 0) return -1;
|
||||
|
||||
if (nResult == 0) {
|
||||
unsigned int nMatchLen;
|
||||
|
||||
/* '10': 8+n bits offset */
|
||||
int nMatchOffsetHi = apultra_read_gamma2(&pInputData, pInputDataEnd, &nCurBitMask, &bits);
|
||||
nMatchOffsetHi -= nFollowsLiteral;
|
||||
if (nMatchOffsetHi >= 0) {
|
||||
nMatchOffset = ((unsigned int) nMatchOffsetHi) << 8;
|
||||
nMatchOffset |= (unsigned int)(*pInputData++);
|
||||
|
||||
nMatchLen = apultra_read_gamma2(&pInputData, pInputDataEnd, &nCurBitMask, &bits);
|
||||
|
||||
if (nMatchOffset < 128 || nMatchOffset >= MINMATCH4_OFFSET)
|
||||
nMatchLen += 2;
|
||||
else if (nMatchOffset >= MINMATCH3_OFFSET)
|
||||
nMatchLen++;
|
||||
}
|
||||
else {
|
||||
/* else rep-match */
|
||||
nMatchLen = apultra_read_gamma2(&pInputData, pInputDataEnd, &nCurBitMask, &bits);
|
||||
}
|
||||
|
||||
nFollowsLiteral = 2;
|
||||
|
||||
nDecompressedSize += nMatchLen;
|
||||
}
|
||||
else {
|
||||
nResult = apultra_read_bit(&pInputData, pInputDataEnd, &nCurBitMask, &bits);
|
||||
if (nResult < 0) return -1;
|
||||
|
||||
if (nResult == 0) {
|
||||
unsigned int nCommand;
|
||||
unsigned int nMatchLen;
|
||||
|
||||
/* '110': 7 bits offset + 1 bit length */
|
||||
nCommand = (unsigned int)(*pInputData++);
|
||||
if (nCommand == 0x00) {
|
||||
/* EOD. No match len follows. */
|
||||
break;
|
||||
}
|
||||
|
||||
/* Bits 7-1: offset; bit 0: length */
|
||||
nMatchOffset = (nCommand >> 1);
|
||||
nMatchLen = (nCommand & 1) + 2;
|
||||
|
||||
nFollowsLiteral = 2;
|
||||
nDecompressedSize += nMatchLen;
|
||||
}
|
||||
else {
|
||||
unsigned int nShortMatchOffset;
|
||||
|
||||
/* '111': 4 bit offset */
|
||||
nResult = apultra_read_bit(&pInputData, pInputDataEnd, &nCurBitMask, &bits);
|
||||
if (nResult < 0) return -1;
|
||||
nShortMatchOffset = nResult << 3;
|
||||
|
||||
nResult = apultra_read_bit(&pInputData, pInputDataEnd, &nCurBitMask, &bits);
|
||||
if (nResult < 0) return -1;
|
||||
nShortMatchOffset |= nResult << 2;
|
||||
|
||||
nResult = apultra_read_bit(&pInputData, pInputDataEnd, &nCurBitMask, &bits);
|
||||
if (nResult < 0) return -1;
|
||||
nShortMatchOffset |= nResult << 1;
|
||||
|
||||
nResult = apultra_read_bit(&pInputData, pInputDataEnd, &nCurBitMask, &bits);
|
||||
if (nResult < 0) return -1;
|
||||
nShortMatchOffset |= nResult << 0;
|
||||
|
||||
nFollowsLiteral = 3;
|
||||
nDecompressedSize++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nDecompressedSize;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decompress data in memory
|
||||
*
|
||||
* @param pInputData compressed data
|
||||
* @param pOutBuffer buffer for decompressed data
|
||||
* @param nInputSize compressed size in bytes
|
||||
* @param nMaxOutBufferSize maximum capacity of decompression buffer
|
||||
* @param nDictionarySize size of dictionary in front of input data (0 for none)
|
||||
* @param nFlags compression flags (set to 0)
|
||||
*
|
||||
* @return actual decompressed size, or -1 for error
|
||||
*/
|
||||
size_t apultra_decompress(const unsigned char *pInputData, unsigned char *pOutData, size_t nInputSize, size_t nMaxOutBufferSize, size_t nDictionarySize, const unsigned int nFlags) {
|
||||
const unsigned char *pInputDataEnd = pInputData + nInputSize;
|
||||
unsigned char *pCurOutData = pOutData + nDictionarySize;
|
||||
const unsigned char *pOutDataEnd = pCurOutData + nMaxOutBufferSize;
|
||||
const unsigned char *pOutDataFastEnd = pOutDataEnd - 20;
|
||||
int nCurBitMask = 0;
|
||||
unsigned char bits = 0;
|
||||
int nMatchOffset = -1;
|
||||
int nFollowsLiteral = 3;
|
||||
|
||||
if (pInputData >= pInputDataEnd && pCurOutData < pOutDataEnd)
|
||||
return -1;
|
||||
*pCurOutData++ = *pInputData++;
|
||||
|
||||
while (1) {
|
||||
int nResult;
|
||||
|
||||
nResult = apultra_read_bit(&pInputData, pInputDataEnd, &nCurBitMask, &bits);
|
||||
if (nResult < 0) return -1;
|
||||
|
||||
if (!nResult) {
|
||||
/* '0': literal */
|
||||
if (pInputData < pInputDataEnd && pCurOutData < pOutDataEnd) {
|
||||
*pCurOutData++ = *pInputData++;
|
||||
nFollowsLiteral = 3;
|
||||
}
|
||||
else {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
else {
|
||||
nResult = apultra_read_bit(&pInputData, pInputDataEnd, &nCurBitMask, &bits);
|
||||
if (nResult < 0) return -1;
|
||||
|
||||
if (nResult == 0) {
|
||||
unsigned int nMatchLen;
|
||||
|
||||
/* '10': 8+n bits offset */
|
||||
int nMatchOffsetHi = apultra_read_gamma2(&pInputData, pInputDataEnd, &nCurBitMask, &bits);
|
||||
nMatchOffsetHi -= nFollowsLiteral;
|
||||
if (nMatchOffsetHi >= 0) {
|
||||
nMatchOffset = ((unsigned int) nMatchOffsetHi) << 8;
|
||||
nMatchOffset |= (unsigned int)(*pInputData++);
|
||||
|
||||
nMatchLen = apultra_read_gamma2(&pInputData, pInputDataEnd, &nCurBitMask, &bits);
|
||||
|
||||
if (nMatchOffset < 128 || nMatchOffset >= MINMATCH4_OFFSET)
|
||||
nMatchLen += 2;
|
||||
else if (nMatchOffset >= MINMATCH3_OFFSET)
|
||||
nMatchLen++;
|
||||
}
|
||||
else {
|
||||
/* else rep-match */
|
||||
nMatchLen = apultra_read_gamma2(&pInputData, pInputDataEnd, &nCurBitMask, &bits);
|
||||
}
|
||||
|
||||
nFollowsLiteral = 2;
|
||||
const unsigned char *pSrc = pCurOutData - nMatchOffset;
|
||||
if (pSrc >= pOutData && (pSrc + nMatchLen) <= pOutDataEnd) {
|
||||
if (nMatchLen < 11 && nMatchOffset >= 8 && pCurOutData < pOutDataFastEnd) {
|
||||
memcpy(pCurOutData, pSrc, 8);
|
||||
memcpy(pCurOutData + 8, pSrc + 8, 2);
|
||||
pCurOutData += nMatchLen;
|
||||
}
|
||||
else {
|
||||
if ((pCurOutData + nMatchLen) <= pOutDataEnd) {
|
||||
/* Do a deterministic, left to right byte copy instead of memcpy() so as to handle overlaps */
|
||||
|
||||
if (nMatchOffset >= 16 && (pCurOutData + nMatchLen) < (pOutDataFastEnd - 15)) {
|
||||
const unsigned char *pCopySrc = pSrc;
|
||||
unsigned char *pCopyDst = pCurOutData;
|
||||
const unsigned char *pCopyEndDst = pCurOutData + nMatchLen;
|
||||
|
||||
do {
|
||||
memcpy(pCopyDst, pCopySrc, 16);
|
||||
pCopySrc += 16;
|
||||
pCopyDst += 16;
|
||||
} while (pCopyDst < pCopyEndDst);
|
||||
|
||||
pCurOutData += nMatchLen;
|
||||
}
|
||||
else {
|
||||
while (nMatchLen) {
|
||||
*pCurOutData++ = *pSrc++;
|
||||
nMatchLen--;
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
else {
|
||||
nResult = apultra_read_bit(&pInputData, pInputDataEnd, &nCurBitMask, &bits);
|
||||
if (nResult < 0) return -1;
|
||||
|
||||
if (nResult == 0) {
|
||||
unsigned int nCommand;
|
||||
unsigned int nMatchLen;
|
||||
|
||||
/* '110': 7 bits offset + 1 bit length */
|
||||
nCommand = (unsigned int)(*pInputData++);
|
||||
if (nCommand == 0x00) {
|
||||
/* EOD. No match len follows. */
|
||||
break;
|
||||
}
|
||||
|
||||
/* Bits 7-1: offset; bit 0: length */
|
||||
nMatchOffset = (nCommand >> 1);
|
||||
nMatchLen = (nCommand & 1) + 2;
|
||||
|
||||
nFollowsLiteral = 2;
|
||||
const unsigned char *pSrc = pCurOutData - nMatchOffset;
|
||||
if (pSrc >= pOutData && (pSrc + nMatchLen) <= pOutDataEnd) {
|
||||
if (nMatchOffset >= 8 && pCurOutData < pOutDataFastEnd) {
|
||||
memcpy(pCurOutData, pSrc, 8);
|
||||
memcpy(pCurOutData + 8, pSrc + 8, 2);
|
||||
pCurOutData += nMatchLen;
|
||||
}
|
||||
else {
|
||||
if ((pCurOutData + nMatchLen) <= pOutDataEnd) {
|
||||
while (nMatchLen) {
|
||||
*pCurOutData++ = *pSrc++;
|
||||
nMatchLen--;
|
||||
}
|
||||
}
|
||||
else {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
else {
|
||||
unsigned int nShortMatchOffset;
|
||||
|
||||
/* '111': 4 bit offset */
|
||||
nResult = apultra_read_bit(&pInputData, pInputDataEnd, &nCurBitMask, &bits);
|
||||
if (nResult < 0) return -1;
|
||||
nShortMatchOffset = nResult << 3;
|
||||
|
||||
nResult = apultra_read_bit(&pInputData, pInputDataEnd, &nCurBitMask, &bits);
|
||||
if (nResult < 0) return -1;
|
||||
nShortMatchOffset |= nResult << 2;
|
||||
|
||||
nResult = apultra_read_bit(&pInputData, pInputDataEnd, &nCurBitMask, &bits);
|
||||
if (nResult < 0) return -1;
|
||||
nShortMatchOffset |= nResult << 1;
|
||||
|
||||
nResult = apultra_read_bit(&pInputData, pInputDataEnd, &nCurBitMask, &bits);
|
||||
if (nResult < 0) return -1;
|
||||
nShortMatchOffset |= nResult << 0;
|
||||
|
||||
nFollowsLiteral = 3;
|
||||
if (nShortMatchOffset) {
|
||||
/* Short offset, 1-15 */
|
||||
const unsigned char *pSrc = pCurOutData - nShortMatchOffset;
|
||||
if (pSrc >= pOutData && (pCurOutData + 1) <= pOutDataEnd && (pSrc + 1) <= pOutDataEnd) {
|
||||
*pCurOutData++ = *pSrc++;
|
||||
}
|
||||
else {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
else {
|
||||
/* Write zero */
|
||||
if ((pCurOutData + 1) <= pOutDataEnd) {
|
||||
*pCurOutData++ = 0;
|
||||
}
|
||||
else {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (size_t)(pCurOutData - pOutData) - nDictionarySize;
|
||||
}
|
@ -1,71 +0,0 @@
|
||||
/*
|
||||
* expand.h - decompressor definitions
|
||||
*
|
||||
* Copyright (C) 2019 Emmanuel Marty
|
||||
*
|
||||
* This software is provided 'as-is', without any express or implied
|
||||
* warranty. In no event will the authors be held liable for any damages
|
||||
* arising from the use of this software.
|
||||
*
|
||||
* Permission is granted to anyone to use this software for any purpose,
|
||||
* including commercial applications, and to alter it and redistribute it
|
||||
* freely, subject to the following restrictions:
|
||||
*
|
||||
* 1. The origin of this software must not be misrepresented; you must not
|
||||
* claim that you wrote the original software. If you use this software
|
||||
* in a product, an acknowledgment in the product documentation would be
|
||||
* appreciated but is not required.
|
||||
* 2. Altered source versions must be plainly marked as such, and must not be
|
||||
* misrepresented as being the original software.
|
||||
* 3. This notice may not be removed or altered from any source distribution.
|
||||
*/
|
||||
|
||||
/*
|
||||
* Uses the libdivsufsort library Copyright (c) 2003-2008 Yuta Mori
|
||||
*
|
||||
* Inspired by cap by Sven-Åke Dahl. https://github.com/svendahl/cap
|
||||
* Also inspired by Charles Bloom's compression blog. http://cbloomrants.blogspot.com/
|
||||
* With ideas from LZ4 by Yann Collet. https://github.com/lz4/lz4
|
||||
* With help and support from spke <zxintrospec@gmail.com>
|
||||
*
|
||||
*/
|
||||
|
||||
#ifndef _EXPAND_H
|
||||
#define _EXPAND_H
|
||||
|
||||
#include <stdlib.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/**
|
||||
* Get maximum decompressed size of compressed data
|
||||
*
|
||||
* @param pInputData compressed data
|
||||
* @param nInputSize compressed size in bytes
|
||||
* @param nFlags compression flags (set to 0)
|
||||
*
|
||||
* @return maximum decompressed size
|
||||
*/
|
||||
size_t apultra_get_max_decompressed_size(const unsigned char *pInputData, size_t nInputSize, const unsigned int nFlags);
|
||||
|
||||
/**
|
||||
* Decompress data in memory
|
||||
*
|
||||
* @param pInputData compressed data
|
||||
* @param pOutBuffer buffer for decompressed data
|
||||
* @param nInputSize compressed size in bytes
|
||||
* @param nMaxOutBufferSize maximum capacity of decompression buffer
|
||||
* @param nDictionarySize size of dictionary in front of input data (0 for none)
|
||||
* @param nFlags compression flags (set to 0)
|
||||
*
|
||||
* @return actual decompressed size, or -1 for error
|
||||
*/
|
||||
size_t apultra_decompress(const unsigned char *pInputData, unsigned char *pOutBuffer, size_t nInputSize, size_t nMaxOutBufferSize, size_t nDictionarySize, const unsigned int nFlags);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* _EXPAND_H */
|
@ -1,47 +0,0 @@
|
||||
/*
|
||||
* format.h - byte stream format definitions
|
||||
*
|
||||
* Copyright (C) 2019 Emmanuel Marty
|
||||
*
|
||||
* This software is provided 'as-is', without any express or implied
|
||||
* warranty. In no event will the authors be held liable for any damages
|
||||
* arising from the use of this software.
|
||||
*
|
||||
* Permission is granted to anyone to use this software for any purpose,
|
||||
* including commercial applications, and to alter it and redistribute it
|
||||
* freely, subject to the following restrictions:
|
||||
*
|
||||
* 1. The origin of this software must not be misrepresented; you must not
|
||||
* claim that you wrote the original software. If you use this software
|
||||
* in a product, an acknowledgment in the product documentation would be
|
||||
* appreciated but is not required.
|
||||
* 2. Altered source versions must be plainly marked as such, and must not be
|
||||
* misrepresented as being the original software.
|
||||
* 3. This notice may not be removed or altered from any source distribution.
|
||||
*/
|
||||
|
||||
/*
|
||||
* Uses the libdivsufsort library Copyright (c) 2003-2008 Yuta Mori
|
||||
*
|
||||
* Inspired by cap by Sven-Åke Dahl. https://github.com/svendahl/cap
|
||||
* Also inspired by Charles Bloom's compression blog. http://cbloomrants.blogspot.com/
|
||||
* With ideas from LZ4 by Yann Collet. https://github.com/lz4/lz4
|
||||
* With help and support from spke <zxintrospec@gmail.com>
|
||||
*
|
||||
*/
|
||||
|
||||
#ifndef _FORMAT_H
|
||||
#define _FORMAT_H
|
||||
|
||||
#define MIN_OFFSET 1
|
||||
#define MAX_OFFSET 0x1fffff
|
||||
|
||||
#define MAX_VARLEN 0x1fffff
|
||||
|
||||
#define BLOCK_SIZE 0x100000
|
||||
|
||||
#define MIN_MATCH_SIZE 1
|
||||
#define MINMATCH3_OFFSET 1280
|
||||
#define MINMATCH4_OFFSET 32000
|
||||
|
||||
#endif /* _FORMAT_H */
|
@ -1,40 +0,0 @@
|
||||
/*
|
||||
* libapultra.h - library definitions
|
||||
*
|
||||
* Copyright (C) 2019 Emmanuel Marty
|
||||
*
|
||||
* This software is provided 'as-is', without any express or implied
|
||||
* warranty. In no event will the authors be held liable for any damages
|
||||
* arising from the use of this software.
|
||||
*
|
||||
* Permission is granted to anyone to use this software for any purpose,
|
||||
* including commercial applications, and to alter it and redistribute it
|
||||
* freely, subject to the following restrictions:
|
||||
*
|
||||
* 1. The origin of this software must not be misrepresented; you must not
|
||||
* claim that you wrote the original software. If you use this software
|
||||
* in a product, an acknowledgment in the product documentation would be
|
||||
* appreciated but is not required.
|
||||
* 2. Altered source versions must be plainly marked as such, and must not be
|
||||
* misrepresented as being the original software.
|
||||
* 3. This notice may not be removed or altered from any source distribution.
|
||||
*/
|
||||
|
||||
/*
|
||||
* Uses the libdivsufsort library Copyright (c) 2003-2008 Yuta Mori
|
||||
*
|
||||
* Inspired by cap by Sven-Åke Dahl. https://github.com/svendahl/cap
|
||||
* Also inspired by Charles Bloom's compression blog. http://cbloomrants.blogspot.com/
|
||||
* With ideas from LZ4 by Yann Collet. https://github.com/lz4/lz4
|
||||
* With help and support from spke <zxintrospec@gmail.com>
|
||||
*
|
||||
*/
|
||||
|
||||
#ifndef _LIB_APULTRA_H
|
||||
#define _LIB_APULTRA_H
|
||||
|
||||
#include "format.h"
|
||||
#include "shrink.h"
|
||||
#include "expand.h"
|
||||
|
||||
#endif /* _LIB_APULTRA_H */
|
@ -1,449 +0,0 @@
|
||||
/*
|
||||
* matchfinder.c - LZ match finder implementation
|
||||
*
|
||||
* The following copying information applies to this specific source code file:
|
||||
*
|
||||
* Written in 2019 by Emmanuel Marty <marty.emmanuel@gmail.com>
|
||||
* Portions written in 2014-2015 by Eric Biggers <ebiggers3@gmail.com>
|
||||
*
|
||||
* To the extent possible under law, the author(s) have dedicated all copyright
|
||||
* and related and neighboring rights to this software to the public domain
|
||||
* worldwide via the Creative Commons Zero 1.0 Universal Public Domain
|
||||
* Dedication (the "CC0").
|
||||
*
|
||||
* This software is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||
* FOR A PARTICULAR PURPOSE. See the CC0 for more details.
|
||||
*
|
||||
* You should have received a copy of the CC0 along with this software; if not
|
||||
* see <http://creativecommons.org/publicdomain/zero/1.0/>.
|
||||
*/
|
||||
|
||||
/*
|
||||
* Uses the libdivsufsort library Copyright (c) 2003-2008 Yuta Mori
|
||||
*
|
||||
* Inspired by cap by Sven-Åke Dahl. https://github.com/svendahl/cap
|
||||
* Also inspired by Charles Bloom's compression blog. http://cbloomrants.blogspot.com/
|
||||
* With ideas from LZ4 by Yann Collet. https://github.com/lz4/lz4
|
||||
* With help and support from spke <zxintrospec@gmail.com>
|
||||
*
|
||||
*/
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include "matchfinder.h"
|
||||
#include "format.h"
|
||||
#include "libapultra.h"
|
||||
|
||||
/**
|
||||
* Hash index into TAG_BITS
|
||||
*
|
||||
* @param nIndex index value
|
||||
*
|
||||
* @return hash
|
||||
*/
|
||||
static inline int apultra_get_index_tag(unsigned int nIndex) {
|
||||
return (int)(((unsigned long long)nIndex * 11400714819323198485ULL) >> (64ULL - TAG_BITS));
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse input data, build suffix array and overlaid data structures to speed up match finding
|
||||
*
|
||||
* @param pCompressor compression context
|
||||
* @param pInWindow pointer to input data window (previously compressed bytes + bytes to compress)
|
||||
* @param nInWindowSize total input size in bytes (previously compressed bytes + bytes to compress)
|
||||
*
|
||||
* @return 0 for success, non-zero for failure
|
||||
*/
|
||||
int apultra_build_suffix_array(apultra_compressor *pCompressor, const unsigned char *pInWindow, const int nInWindowSize) {
|
||||
unsigned long long *intervals = pCompressor->intervals;
|
||||
|
||||
/* Build suffix array from input data */
|
||||
saidx_t *suffixArray = (saidx_t*)intervals;
|
||||
if (divsufsort_build_array(&pCompressor->divsufsort_context, pInWindow, suffixArray, nInWindowSize) != 0) {
|
||||
return 100;
|
||||
}
|
||||
|
||||
int i, r;
|
||||
|
||||
for (i = nInWindowSize - 1; i >= 0; i--) {
|
||||
intervals[i] = suffixArray[i];
|
||||
}
|
||||
|
||||
int *PLCP = (int*)pCompressor->pos_data; /* Use temporarily */
|
||||
int *Phi = PLCP;
|
||||
int nCurLen = 0;
|
||||
|
||||
/* Compute the permuted LCP first (Kärkkäinen method) */
|
||||
Phi[intervals[0]] = -1;
|
||||
for (i = 1; i < nInWindowSize; i++)
|
||||
Phi[intervals[i]] = (unsigned int)intervals[i - 1];
|
||||
for (i = 0; i < nInWindowSize; i++) {
|
||||
if (Phi[i] == -1) {
|
||||
PLCP[i] = 0;
|
||||
continue;
|
||||
}
|
||||
int nMaxLen = (i > Phi[i]) ? (nInWindowSize - i) : (nInWindowSize - Phi[i]);
|
||||
while (nCurLen < nMaxLen && pInWindow[i + nCurLen] == pInWindow[Phi[i] + nCurLen]) nCurLen++;
|
||||
PLCP[i] = nCurLen;
|
||||
if (nCurLen > 0)
|
||||
nCurLen--;
|
||||
}
|
||||
|
||||
/* Rotate permuted LCP into the LCP. This has better cache locality than the direct Kasai LCP method. This also
|
||||
* saves us from having to build the inverse suffix array index, as the LCP is calculated without it using this method,
|
||||
* and the interval builder below doesn't need it either. */
|
||||
intervals[0] &= POS_MASK;
|
||||
|
||||
for (i = 1; i < nInWindowSize; i++) {
|
||||
int nIndex = (int)(intervals[i] & POS_MASK);
|
||||
int nLen = PLCP[nIndex];
|
||||
if (nLen < MIN_MATCH_SIZE)
|
||||
nLen = 0;
|
||||
if (nLen > LCP_MAX)
|
||||
nLen = LCP_MAX;
|
||||
int nTaggedLen = 0;
|
||||
if (nLen)
|
||||
nTaggedLen = (nLen << TAG_BITS) | (apultra_get_index_tag((unsigned int)nIndex) & ((1 << TAG_BITS) - 1));
|
||||
intervals[i] = ((unsigned long long)nIndex) | (((unsigned long long)nTaggedLen) << LCP_SHIFT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build intervals for finding matches
|
||||
*
|
||||
* Methodology and code fragment taken from wimlib (CC0 license):
|
||||
* https://wimlib.net/git/?p=wimlib;a=blob_plain;f=src/lcpit_matchfinder.c;h=a2d6a1e0cd95200d1f3a5464d8359d5736b14cbe;hb=HEAD
|
||||
*/
|
||||
unsigned long long * const SA_and_LCP = intervals;
|
||||
unsigned long long *pos_data = pCompressor->pos_data;
|
||||
unsigned long long next_interval_idx;
|
||||
unsigned long long *top = pCompressor->open_intervals;
|
||||
unsigned long long prev_pos = SA_and_LCP[0] & POS_MASK;
|
||||
|
||||
*top = 0;
|
||||
intervals[0] = 0;
|
||||
next_interval_idx = 1;
|
||||
|
||||
for (r = 1; r < nInWindowSize; r++) {
|
||||
const unsigned long long next_pos = SA_and_LCP[r] & POS_MASK;
|
||||
const unsigned long long next_lcp = SA_and_LCP[r] & LCP_MASK;
|
||||
const unsigned long long top_lcp = *top & LCP_MASK;
|
||||
|
||||
if (next_lcp == top_lcp) {
|
||||
/* Continuing the deepest open interval */
|
||||
pos_data[prev_pos] = *top;
|
||||
}
|
||||
else if (next_lcp > top_lcp) {
|
||||
/* Opening a new interval */
|
||||
*++top = next_lcp | next_interval_idx++;
|
||||
pos_data[prev_pos] = *top;
|
||||
}
|
||||
else {
|
||||
/* Closing the deepest open interval */
|
||||
pos_data[prev_pos] = *top;
|
||||
for (;;) {
|
||||
const unsigned long long closed_interval_idx = *top-- & POS_MASK;
|
||||
const unsigned long long superinterval_lcp = *top & LCP_MASK;
|
||||
|
||||
if (next_lcp == superinterval_lcp) {
|
||||
/* Continuing the superinterval */
|
||||
intervals[closed_interval_idx] = *top;
|
||||
break;
|
||||
}
|
||||
else if (next_lcp > superinterval_lcp) {
|
||||
/* Creating a new interval that is a
|
||||
* superinterval of the one being
|
||||
* closed, but still a subinterval of
|
||||
* its superinterval */
|
||||
*++top = next_lcp | next_interval_idx++;
|
||||
intervals[closed_interval_idx] = *top;
|
||||
break;
|
||||
}
|
||||
else {
|
||||
/* Also closing the superinterval */
|
||||
intervals[closed_interval_idx] = *top;
|
||||
}
|
||||
}
|
||||
}
|
||||
prev_pos = next_pos;
|
||||
}
|
||||
|
||||
/* Close any still-open intervals. */
|
||||
pos_data[prev_pos] = *top;
|
||||
for (; top > pCompressor->open_intervals; top--)
|
||||
intervals[*top & POS_MASK] = *(top - 1);
|
||||
|
||||
/* Success */
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find matches at the specified offset in the input window
|
||||
*
|
||||
* @param pCompressor compression context
|
||||
* @param nOffset offset to find matches at, in the input window
|
||||
* @param pMatches pointer to returned matches
|
||||
* @param pMatchDepth pointer to returned match depths
|
||||
* @param pMatch1 pointer to 1-byte length, 4 bit offset match
|
||||
* @param nMaxMatches maximum number of matches to return (0 for none)
|
||||
* @param nBlockFlags bit 0: 1 for first block, 0 otherwise; bit 1: 1 for last block, 0 otherwise
|
||||
*
|
||||
* @return number of matches
|
||||
*/
|
||||
int apultra_find_matches_at(apultra_compressor *pCompressor, const int nOffset, apultra_match *pMatches, unsigned short *pMatchDepth, unsigned char *pMatch1, const int nMaxMatches, const int nBlockFlags) {
|
||||
unsigned long long *intervals = pCompressor->intervals;
|
||||
unsigned long long *pos_data = pCompressor->pos_data;
|
||||
unsigned long long ref;
|
||||
unsigned long long super_ref;
|
||||
unsigned long long match_pos;
|
||||
apultra_match *matchptr;
|
||||
unsigned short *depthptr;
|
||||
const int nMaxOffset = pCompressor->max_offset;
|
||||
|
||||
*pMatch1 = 0;
|
||||
|
||||
/**
|
||||
* Find matches using intervals
|
||||
*
|
||||
* Taken from wimlib (CC0 license):
|
||||
* https://wimlib.net/git/?p=wimlib;a=blob_plain;f=src/lcpit_matchfinder.c;h=a2d6a1e0cd95200d1f3a5464d8359d5736b14cbe;hb=HEAD
|
||||
*/
|
||||
|
||||
/* Get the deepest lcp-interval containing the current suffix. */
|
||||
ref = pos_data[nOffset];
|
||||
|
||||
pos_data[nOffset] = 0;
|
||||
|
||||
/* Ascend until we reach a visited interval, the root, or a child of the
|
||||
* root. Link unvisited intervals to the current suffix as we go. */
|
||||
while ((super_ref = intervals[ref & POS_MASK]) & LCP_MASK) {
|
||||
intervals[ref & POS_MASK] = nOffset | VISITED_FLAG;
|
||||
ref = super_ref;
|
||||
}
|
||||
|
||||
if (super_ref == 0) {
|
||||
/* In this case, the current interval may be any of:
|
||||
* (1) the root;
|
||||
* (2) an unvisited child of the root */
|
||||
|
||||
if (ref != 0) /* Not the root? */
|
||||
intervals[ref & POS_MASK] = nOffset | VISITED_FLAG;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Ascend indirectly via pos_data[] links. */
|
||||
match_pos = super_ref & EXCL_VISITED_MASK;
|
||||
matchptr = pMatches;
|
||||
depthptr = pMatchDepth;
|
||||
int nPrevOffset = 0;
|
||||
int nPrevLen = 0;
|
||||
int nCurDepth = 0;
|
||||
unsigned short *cur_depth = NULL;
|
||||
|
||||
if (nOffset >= match_pos && (nBlockFlags & 3) == 3) {
|
||||
int nMatchOffset = (int)(nOffset - match_pos);
|
||||
int nMatchLen = (int)(ref >> (LCP_SHIFT + TAG_BITS));
|
||||
|
||||
if ((matchptr - pMatches) < nMaxMatches) {
|
||||
if (nMatchOffset <= nMaxOffset) {
|
||||
if (nPrevOffset && nPrevLen > 2 && nMatchOffset == (nPrevOffset - 1) && nMatchLen == (nPrevLen - 1) && cur_depth && nCurDepth < LCP_MAX) {
|
||||
nCurDepth++;
|
||||
*cur_depth = nCurDepth;
|
||||
}
|
||||
else {
|
||||
nCurDepth = 0;
|
||||
|
||||
cur_depth = depthptr;
|
||||
matchptr->length = nMatchLen;
|
||||
matchptr->offset = nMatchOffset;
|
||||
*depthptr = 0;
|
||||
matchptr++;
|
||||
depthptr++;
|
||||
}
|
||||
|
||||
nPrevLen = nMatchLen;
|
||||
nPrevOffset = nMatchOffset;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (;;) {
|
||||
if ((super_ref = pos_data[match_pos]) > ref) {
|
||||
match_pos = intervals[super_ref & POS_MASK] & EXCL_VISITED_MASK;
|
||||
|
||||
if (nOffset >= match_pos && (nBlockFlags & 3) == 3) {
|
||||
int nMatchOffset = (int)(nOffset - match_pos);
|
||||
int nMatchLen = (int)(ref >> (LCP_SHIFT + TAG_BITS));
|
||||
|
||||
if ((matchptr - pMatches) < nMaxMatches) {
|
||||
if (nMatchOffset <= nMaxOffset && abs(nMatchOffset - nPrevOffset) >= 128) {
|
||||
if (nPrevOffset && nPrevLen > 2 && nMatchOffset == (nPrevOffset - 1) && nMatchLen == (nPrevLen - 1) && cur_depth && nCurDepth < LCP_MAX) {
|
||||
nCurDepth++;
|
||||
*cur_depth = nCurDepth | 0x8000;
|
||||
}
|
||||
else {
|
||||
nCurDepth = 0;
|
||||
|
||||
cur_depth = depthptr;
|
||||
matchptr->length = nMatchLen;
|
||||
matchptr->offset = nMatchOffset;
|
||||
*depthptr = 0x8000;
|
||||
matchptr++;
|
||||
depthptr++;
|
||||
}
|
||||
|
||||
nPrevLen = nMatchLen;
|
||||
nPrevOffset = nMatchOffset;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
while ((super_ref = pos_data[match_pos]) > ref) {
|
||||
match_pos = intervals[super_ref & POS_MASK] & EXCL_VISITED_MASK;
|
||||
|
||||
if (nOffset > match_pos && (nBlockFlags & 3) == 3) {
|
||||
int nMatchOffset = (int)(nOffset - match_pos);
|
||||
int nMatchLen = (int)(ref >> (LCP_SHIFT + TAG_BITS));
|
||||
|
||||
if ((matchptr - pMatches) < nMaxMatches) {
|
||||
if (nMatchOffset <= nMaxOffset && (nMatchLen >= 3 || (nMatchLen >= 2 && (matchptr - pMatches) < (nMaxMatches - 1))) && nMatchLen < 1280 && abs(nMatchOffset - nPrevOffset) >= 128) {
|
||||
if (nPrevOffset && nPrevLen > 2 && nMatchOffset == (nPrevOffset - 1) && nMatchLen == (nPrevLen - 1) && cur_depth && nCurDepth < LCP_MAX) {
|
||||
nCurDepth++;
|
||||
*cur_depth = nCurDepth | 0x8000;
|
||||
}
|
||||
else {
|
||||
nCurDepth = 0;
|
||||
|
||||
cur_depth = depthptr;
|
||||
matchptr->length = nMatchLen;
|
||||
matchptr->offset = nMatchOffset;
|
||||
*depthptr = 0x8000;
|
||||
matchptr++;
|
||||
depthptr++;
|
||||
}
|
||||
|
||||
nPrevLen = nMatchLen;
|
||||
nPrevOffset = nMatchOffset;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
intervals[ref & POS_MASK] = nOffset | VISITED_FLAG;
|
||||
pos_data[match_pos] = (unsigned long long)ref;
|
||||
|
||||
int nMatchOffset = (int)(nOffset - match_pos);
|
||||
int nMatchLen = (int)(ref >> (LCP_SHIFT + TAG_BITS));
|
||||
|
||||
if ((matchptr - pMatches) < nMaxMatches) {
|
||||
if (nMatchOffset <= nMaxOffset && nMatchOffset != nPrevOffset) {
|
||||
if (nPrevOffset && nPrevLen > 2 && nMatchOffset == (nPrevOffset - 1) && nMatchLen == (nPrevLen - 1) && cur_depth && nCurDepth < LCP_MAX) {
|
||||
nCurDepth++;
|
||||
*cur_depth = nCurDepth;
|
||||
}
|
||||
else {
|
||||
nCurDepth = 0;
|
||||
|
||||
cur_depth = depthptr;
|
||||
matchptr->length = nMatchLen;
|
||||
matchptr->offset = nMatchOffset;
|
||||
*depthptr = 0;
|
||||
matchptr++;
|
||||
depthptr++;
|
||||
}
|
||||
|
||||
nPrevLen = nMatchLen;
|
||||
nPrevOffset = nMatchOffset;
|
||||
}
|
||||
}
|
||||
|
||||
if (nMatchOffset && nMatchOffset < 16 && nMatchLen)
|
||||
*pMatch1 = nMatchOffset;
|
||||
|
||||
if (super_ref == 0)
|
||||
break;
|
||||
ref = super_ref;
|
||||
match_pos = intervals[ref & POS_MASK] & EXCL_VISITED_MASK;
|
||||
|
||||
if (nOffset > match_pos && (nBlockFlags & 3) == 3) {
|
||||
int nMatchOffset = (int)(nOffset - match_pos);
|
||||
int nMatchLen = (int)(ref >> (LCP_SHIFT + TAG_BITS));
|
||||
|
||||
if ((matchptr - pMatches) < nMaxMatches) {
|
||||
if (nMatchOffset <= nMaxOffset && nMatchLen >= 2 && abs(nMatchOffset - nPrevOffset) >= 128) {
|
||||
if (nPrevOffset && nPrevLen > 2 && nMatchOffset == (nPrevOffset - 1) && nMatchLen == (nPrevLen - 1) && cur_depth && nCurDepth < LCP_MAX) {
|
||||
nCurDepth++;
|
||||
*cur_depth = nCurDepth | 0x8000;
|
||||
}
|
||||
else {
|
||||
nCurDepth = 0;
|
||||
|
||||
cur_depth = depthptr;
|
||||
matchptr->length = nMatchLen;
|
||||
matchptr->offset = nMatchOffset;
|
||||
*depthptr = 0x8000;
|
||||
matchptr++;
|
||||
depthptr++;
|
||||
}
|
||||
|
||||
nPrevLen = nMatchLen;
|
||||
nPrevOffset = nMatchOffset;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (int)(matchptr - pMatches);
|
||||
}
|
||||
|
||||
/**
|
||||
* Skip previously compressed bytes
|
||||
*
|
||||
* @param pCompressor compression context
|
||||
* @param nStartOffset current offset in input window (typically 0)
|
||||
* @param nEndOffset offset to skip to in input window (typically the number of previously compressed bytes)
|
||||
*/
|
||||
void apultra_skip_matches(apultra_compressor *pCompressor, const int nStartOffset, const int nEndOffset) {
|
||||
apultra_match match;
|
||||
unsigned short depth;
|
||||
unsigned char match1;
|
||||
int i;
|
||||
|
||||
/* Skipping still requires scanning for matches, as this also performs a lazy update of the intervals. However,
|
||||
* we don't store the matches. */
|
||||
for (i = nStartOffset; i < nEndOffset; i++) {
|
||||
apultra_find_matches_at(pCompressor, i, &match, &depth, &match1, 0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Find all matches for the data to be compressed
|
||||
*
|
||||
* @param pCompressor compression context
|
||||
* @param nMatchesPerOffset maximum number of matches to store for each offset
|
||||
* @param nStartOffset current offset in input window (typically the number of previously compressed bytes)
|
||||
* @param nEndOffset offset to end finding matches at (typically the size of the total input window in bytes
|
||||
* @param nBlockFlags bit 0: 1 for first block, 0 otherwise; bit 1: 1 for last block, 0 otherwise
|
||||
*/
|
||||
void apultra_find_all_matches(apultra_compressor *pCompressor, const int nMatchesPerOffset, const int nStartOffset, const int nEndOffset, const int nBlockFlags) {
|
||||
apultra_match *pMatch = pCompressor->match;
|
||||
unsigned short *pMatchDepth = pCompressor->match_depth;
|
||||
unsigned char *pMatch1 = pCompressor->match1;
|
||||
int i;
|
||||
|
||||
for (i = nStartOffset; i < nEndOffset; i++) {
|
||||
int nMatches = apultra_find_matches_at(pCompressor, i, pMatch, pMatchDepth, pMatch1, nMatchesPerOffset, nBlockFlags);
|
||||
|
||||
while (nMatches < nMatchesPerOffset) {
|
||||
pMatch[nMatches].length = 0;
|
||||
pMatch[nMatches].offset = 0;
|
||||
pMatchDepth[nMatches] = 0;
|
||||
nMatches++;
|
||||
}
|
||||
|
||||
pMatch += nMatchesPerOffset;
|
||||
pMatchDepth += nMatchesPerOffset;
|
||||
pMatch1++;
|
||||
}
|
||||
}
|
@ -1,94 +0,0 @@
|
||||
/*
|
||||
* matchfinder.h - LZ match finder definitions
|
||||
*
|
||||
* Copyright (C) 2019 Emmanuel Marty
|
||||
*
|
||||
* This software is provided 'as-is', without any express or implied
|
||||
* warranty. In no event will the authors be held liable for any damages
|
||||
* arising from the use of this software.
|
||||
*
|
||||
* Permission is granted to anyone to use this software for any purpose,
|
||||
* including commercial applications, and to alter it and redistribute it
|
||||
* freely, subject to the following restrictions:
|
||||
*
|
||||
* 1. The origin of this software must not be misrepresented; you must not
|
||||
* claim that you wrote the original software. If you use this software
|
||||
* in a product, an acknowledgment in the product documentation would be
|
||||
* appreciated but is not required.
|
||||
* 2. Altered source versions must be plainly marked as such, and must not be
|
||||
* misrepresented as being the original software.
|
||||
* 3. This notice may not be removed or altered from any source distribution.
|
||||
*/
|
||||
|
||||
/*
|
||||
* Uses the libdivsufsort library Copyright (c) 2003-2008 Yuta Mori
|
||||
*
|
||||
* Inspired by cap by Sven-Åke Dahl. https://github.com/svendahl/cap
|
||||
* Also inspired by Charles Bloom's compression blog. http://cbloomrants.blogspot.com/
|
||||
* With ideas from LZ4 by Yann Collet. https://github.com/lz4/lz4
|
||||
* With help and support from spke <zxintrospec@gmail.com>
|
||||
*
|
||||
*/
|
||||
|
||||
#ifndef _MATCHFINDER_H
|
||||
#define _MATCHFINDER_H
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* Forward declarations */
|
||||
typedef struct _apultra_match apultra_match;
|
||||
typedef struct _apultra_compressor apultra_compressor;
|
||||
|
||||
/**
|
||||
* Parse input data, build suffix array and overlaid data structures to speed up match finding
|
||||
*
|
||||
* @param pCompressor compression context
|
||||
* @param pInWindow pointer to input data window (previously compressed bytes + bytes to compress)
|
||||
* @param nInWindowSize total input size in bytes (previously compressed bytes + bytes to compress)
|
||||
*
|
||||
* @return 0 for success, non-zero for failure
|
||||
*/
|
||||
int apultra_build_suffix_array(apultra_compressor *pCompressor, const unsigned char *pInWindow, const int nInWindowSize);
|
||||
|
||||
/**
|
||||
* Find matches at the specified offset in the input window
|
||||
*
|
||||
* @param pCompressor compression context
|
||||
* @param nOffset offset to find matches at, in the input window
|
||||
* @param pMatches pointer to returned matches
|
||||
* @param pMatchDepth pointer to returned match depths
|
||||
* @param pMatch1 pointer to 1-byte length, 4 bit offset match
|
||||
* @param nMaxMatches maximum number of matches to return (0 for none)
|
||||
* @param nBlockFlags bit 0: 1 for first block, 0 otherwise; bit 1: 1 for last block, 0 otherwise
|
||||
*
|
||||
* @return number of matches
|
||||
*/
|
||||
int apultra_find_matches_at(apultra_compressor *pCompressor, const int nOffset, apultra_match *pMatches, unsigned short *pMatchDepth, unsigned char *pMatch1, const int nMaxMatches, const int nBlockFlags);
|
||||
|
||||
/**
|
||||
* Skip previously compressed bytes
|
||||
*
|
||||
* @param pCompressor compression context
|
||||
* @param nStartOffset current offset in input window (typically 0)
|
||||
* @param nEndOffset offset to skip to in input window (typically the number of previously compressed bytes)
|
||||
*/
|
||||
void apultra_skip_matches(apultra_compressor *pCompressor, const int nStartOffset, const int nEndOffset);
|
||||
|
||||
/**
|
||||
* Find all matches for the data to be compressed
|
||||
*
|
||||
* @param pCompressor compression context
|
||||
* @param nMatchesPerOffset maximum number of matches to store for each offset
|
||||
* @param nStartOffset current offset in input window (typically the number of previously compressed bytes)
|
||||
* @param nEndOffset offset to end finding matches at (typically the size of the total input window in bytes
|
||||
* @param nBlockFlags bit 0: 1 for first block, 0 otherwise; bit 1: 1 for last block, 0 otherwise
|
||||
*/
|
||||
void apultra_find_all_matches(apultra_compressor *pCompressor, const int nMatchesPerOffset, const int nStartOffset, const int nEndOffset, const int nBlockFlags);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* _MATCHFINDER_H */
|
File diff suppressed because it is too large
Load Diff
@ -1,174 +0,0 @@
|
||||
/*
|
||||
* shrink.h - compressor definitions
|
||||
*
|
||||
* Copyright (C) 2019 Emmanuel Marty
|
||||
*
|
||||
* This software is provided 'as-is', without any express or implied
|
||||
* warranty. In no event will the authors be held liable for any damages
|
||||
* arising from the use of this software.
|
||||
*
|
||||
* Permission is granted to anyone to use this software for any purpose,
|
||||
* including commercial applications, and to alter it and redistribute it
|
||||
* freely, subject to the following restrictions:
|
||||
*
|
||||
* 1. The origin of this software must not be misrepresented; you must not
|
||||
* claim that you wrote the original software. If you use this software
|
||||
* in a product, an acknowledgment in the product documentation would be
|
||||
* appreciated but is not required.
|
||||
* 2. Altered source versions must be plainly marked as such, and must not be
|
||||
* misrepresented as being the original software.
|
||||
* 3. This notice may not be removed or altered from any source distribution.
|
||||
*/
|
||||
|
||||
/*
|
||||
* Uses the libdivsufsort library Copyright (c) 2003-2008 Yuta Mori
|
||||
*
|
||||
* Inspired by cap by Sven-Åke Dahl. https://github.com/svendahl/cap
|
||||
* Also inspired by Charles Bloom's compression blog. http://cbloomrants.blogspot.com/
|
||||
* With ideas from LZ4 by Yann Collet. https://github.com/lz4/lz4
|
||||
* With help and support from spke <zxintrospec@gmail.com>
|
||||
*
|
||||
*/
|
||||
|
||||
#ifndef _SHRINK_H
|
||||
#define _SHRINK_H
|
||||
|
||||
#include "divsufsort.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#define LCP_BITS 15
|
||||
#define TAG_BITS 4
|
||||
#define LCP_MAX ((1U<<(LCP_BITS - TAG_BITS)) - 1)
|
||||
#define LCP_AND_TAG_MAX ((1U<<LCP_BITS) - 1)
|
||||
#define LCP_SHIFT (63-LCP_BITS)
|
||||
#define LCP_MASK (((1ULL<<LCP_BITS) - 1) << LCP_SHIFT)
|
||||
#define POS_MASK ((1ULL<<LCP_SHIFT) - 1)
|
||||
#define VISITED_FLAG 0x8000000000000000ULL
|
||||
#define EXCL_VISITED_MASK 0x7fffffffffffffffULL
|
||||
|
||||
#define NARRIVALS_PER_POSITION_MAX 62
|
||||
#define NARRIVALS_PER_POSITION_NORMAL 46
|
||||
#define NARRIVALS_PER_POSITION_SMALL 9
|
||||
|
||||
#define NMATCHES_PER_INDEX 64
|
||||
#define MATCHES_PER_INDEX_SHIFT 6
|
||||
|
||||
#define LEAVE_ALONE_MATCH_SIZE 120
|
||||
|
||||
/** One match option */
|
||||
typedef struct _apultra_match {
|
||||
unsigned int length:11;
|
||||
unsigned int offset:21;
|
||||
} apultra_match;
|
||||
|
||||
/** One finalized match */
|
||||
typedef struct _apultra_final_match {
|
||||
int length;
|
||||
int offset;
|
||||
} apultra_final_match;
|
||||
|
||||
/** Forward arrival slot */
|
||||
typedef struct {
|
||||
int cost;
|
||||
|
||||
unsigned int from_pos:21;
|
||||
int from_slot:7;
|
||||
unsigned int follows_literal:1;
|
||||
|
||||
unsigned int rep_offset:21;
|
||||
unsigned int short_offset:4;
|
||||
unsigned int rep_pos:21;
|
||||
unsigned int match_len:11;
|
||||
|
||||
int score;
|
||||
} apultra_arrival;
|
||||
|
||||
/** Compression statistics */
|
||||
typedef struct _apultra_stats {
|
||||
int num_literals;
|
||||
int num_4bit_matches;
|
||||
int num_7bit_matches;
|
||||
int num_variable_matches;
|
||||
int num_rep_matches;
|
||||
int num_eod;
|
||||
|
||||
int safe_dist;
|
||||
|
||||
int min_offset;
|
||||
int max_offset;
|
||||
long long total_offsets;
|
||||
|
||||
int min_match_len;
|
||||
int max_match_len;
|
||||
int total_match_lens;
|
||||
|
||||
int min_rle1_len;
|
||||
int max_rle1_len;
|
||||
int total_rle1_lens;
|
||||
|
||||
int min_rle2_len;
|
||||
int max_rle2_len;
|
||||
int total_rle2_lens;
|
||||
|
||||
int commands_divisor;
|
||||
int match_divisor;
|
||||
int rle1_divisor;
|
||||
int rle2_divisor;
|
||||
} apultra_stats;
|
||||
|
||||
/** Compression context */
|
||||
typedef struct _apultra_compressor {
|
||||
divsufsort_ctx_t divsufsort_context;
|
||||
unsigned long long *intervals;
|
||||
unsigned long long *pos_data;
|
||||
unsigned long long *open_intervals;
|
||||
apultra_match *match;
|
||||
unsigned short *match_depth;
|
||||
unsigned char *match1;
|
||||
apultra_final_match *best_match;
|
||||
apultra_arrival *arrival;
|
||||
int *first_offset_for_byte;
|
||||
int *next_offset_for_pos;
|
||||
int *offset_cache;
|
||||
int flags;
|
||||
int block_size;
|
||||
int max_offset;
|
||||
int max_arrivals;
|
||||
apultra_stats stats;
|
||||
} apultra_compressor;
|
||||
|
||||
/**
|
||||
* Get maximum compressed size of input(source) data
|
||||
*
|
||||
* @param nInputSize input(source) size in bytes
|
||||
*
|
||||
* @return maximum compressed size
|
||||
*/
|
||||
size_t apultra_get_max_compressed_size(size_t nInputSize);
|
||||
|
||||
/**
|
||||
* Compress memory
|
||||
*
|
||||
* @param pInputData pointer to input(source) data to compress
|
||||
* @param pOutBuffer buffer for compressed data
|
||||
* @param nInputSize input(source) size in bytes
|
||||
* @param nMaxOutBufferSize maximum capacity of compression buffer
|
||||
* @param nFlags compression flags (set to 0)
|
||||
* @param nMaxWindowSize maximum window size to use (0 for default)
|
||||
* @param nDictionarySize size of dictionary in front of input data (0 for none)
|
||||
* @param progress progress function, called after compressing each block, or NULL for none
|
||||
* @param pStats pointer to compression stats that are filled if this function is successful, or NULL
|
||||
*
|
||||
* @return actual compressed size, or -1 for error
|
||||
*/
|
||||
size_t apultra_compress(const unsigned char *pInputData, unsigned char *pOutBuffer, size_t nInputSize, size_t nMaxOutBufferSize,
|
||||
const unsigned int nFlags, size_t nMaxWindowSize, size_t nDictionarySize, void(*progress)(long long nOriginalSize, long long nCompressedSize), apultra_stats *pStats);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* _SHRINK_H */
|
@ -1,39 +0,0 @@
|
||||
/*
|
||||
* shrink_context.c - compression context implementation
|
||||
*
|
||||
* Copyright (C) 2019 Emmanuel Marty
|
||||
*
|
||||
* This software is provided 'as-is', without any express or implied
|
||||
* warranty. In no event will the authors be held liable for any damages
|
||||
* arising from the use of this software.
|
||||
*
|
||||
* Permission is granted to anyone to use this software for any purpose,
|
||||
* including commercial applications, and to alter it and redistribute it
|
||||
* freely, subject to the following restrictions:
|
||||
*
|
||||
* 1. The origin of this software must not be misrepresented; you must not
|
||||
* claim that you wrote the original software. If you use this software
|
||||
* in a product, an acknowledgment in the product documentation would be
|
||||
* appreciated but is not required.
|
||||
* 2. Altered source versions must be plainly marked as such, and must not be
|
||||
* misrepresented as being the original software.
|
||||
* 3. This notice may not be removed or altered from any source distribution.
|
||||
*/
|
||||
|
||||
/*
|
||||
* Uses the libdivsufsort library Copyright (c) 2003-2008 Yuta Mori
|
||||
*
|
||||
* Inspired by LZ4 by Yann Collet. https://github.com/lz4/lz4
|
||||
* With help, ideas, optimizations and speed measurements by spke <zxintrospec@gmail.com>
|
||||
* With ideas from Lizard by Przemyslaw Skibinski and Yann Collet. https://github.com/inikep/lizard
|
||||
* Also with ideas from smallz4 by Stephan Brumme. https://create.stephan-brumme.com/smallz4/
|
||||
*
|
||||
*/
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
//#include "shrink_context.h"
|
||||
//#include "shrink_block.h"
|
||||
#include "format.h"
|
||||
#include "matchfinder.h"
|
||||
//#include "lib.h"
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user