├── requirements.txt ├── duke3d-shareware.grp.zip ├── GUI ├── launcher.py ├── __init__.py └── gui.py ├── .editorconfig ├── .github ├── run-tests │ └── action.yml ├── workflows │ ├── commit.yml │ └── release.yml └── release_template.md ├── README.md ├── .gitignore ├── BuildLibs ├── confile.py ├── __init__.py ├── SpoilerLog.py ├── grp.py ├── buildmap.py ├── grpbase.py └── buildmapbase.py ├── BuildGames ├── PowerSlave.py ├── OtherGames.py ├── ShadowWarrior.py ├── __init__.py ├── IonFury.py ├── Blood.py └── Duke3d.py ├── tests.py └── LICENSE /requirements.txt: -------------------------------------------------------------------------------- 1 | pyinstaller 2 | tk 3 | typeguard>=3.0.0 4 | -------------------------------------------------------------------------------- /duke3d-shareware.grp.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Die4Ever/build-engine-randomizer/HEAD/duke3d-shareware.grp.zip -------------------------------------------------------------------------------- /GUI/launcher.py: -------------------------------------------------------------------------------- 1 | # keep a config of recently randomized games, how to launch them, what setttings they used... 2 | # buttons to launch, rerandomize with new settings, quick rerandomize with same settings and play? 3 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | [*] 2 | indent_style = space 3 | indent_size = 4 4 | trim_trailing_whitespace = true 5 | insert_final_newline = true 6 | vc_generate_documentation_comments = doxygen_slash_star 7 | end_of_line = lf 8 | 9 | [*.yml] 10 | indent_size = 2 11 | -------------------------------------------------------------------------------- /.github/run-tests/action.yml: -------------------------------------------------------------------------------- 1 | runs: 2 | using: "composite" 3 | steps: 4 | - uses: actions/setup-python@v5 5 | with: 6 | python-version: '3.11' 7 | cache: 'pip' # caching pip dependencies 8 | 9 | - run: pip3 install -r requirements.txt 2>&1 10 | shell: bash 11 | 12 | - run: python3 -m compileall -q . 2>&1 13 | shell: bash 14 | - run: python3 tests.py 2>&1 15 | shell: bash 16 | - run: echo "🍏 This job's status is ${{ job.status }}." 17 | shell: bash 18 | 19 | - name: Build 20 | run: pyinstaller buildrandomizer.py --onefile --noconsole --name build-engine-randomizer 21 | shell: bash 22 | - run: ls -lah dist 23 | shell: bash 24 | 25 | # make sure we don't need the .app folder, specifically for MacOS 26 | - run: rm -rf dist/build-engine-randomizer.app 27 | shell: bash 28 | - run: ./dist/build-engine-randomizer --version 2>&1 29 | shell: bash 30 | -------------------------------------------------------------------------------- /.github/workflows/commit.yml: -------------------------------------------------------------------------------- 1 | name: Commit 2 | on: [push] 3 | 4 | jobs: 5 | Windows-Commit: 6 | runs-on: windows-latest 7 | steps: 8 | - run: echo "🔎 The name of your branch is ${{ github.ref }} and your repository is ${{ github.repository }}." 9 | - name: Check out repository code 10 | uses: actions/checkout@v4 11 | - run: cd ${{ github.workspace }} 12 | 13 | - uses: ./.github/run-tests 14 | 15 | - name: Upload artifacts 16 | uses: actions/upload-artifact@v4 17 | with: 18 | name: build-engine-randomizer.exe 19 | path: dist/build-engine-randomizer.exe 20 | 21 | Linux-Commit: 22 | runs-on: ubuntu-latest 23 | defaults: 24 | run: 25 | # Must be explicit for proper pipefail support 26 | shell: bash 27 | steps: 28 | - run: echo "🔎 The name of your branch is ${{ github.ref }} and your repository is ${{ github.repository }}." 29 | - name: Check out repository code 30 | uses: actions/checkout@v4 31 | - run: cd ${{ github.workspace }} 32 | 33 | - run: sudo apt-get update -y 34 | - run: sudo apt-get install -y python3-tk idle3 35 | 36 | - uses: ./.github/run-tests 37 | 38 | - name: Upload artifacts 39 | uses: actions/upload-artifact@v4 40 | with: 41 | name: build-engine-randomizer-linux 42 | path: dist/build-engine-randomizer 43 | 44 | 45 | MacOS-Commit: 46 | runs-on: macos-latest 47 | defaults: 48 | run: 49 | # Must be explicit for proper pipefail support 50 | shell: bash 51 | steps: 52 | - run: echo "🔎 The name of your branch is ${{ github.ref }} and your repository is ${{ github.repository }}." 53 | - name: Check out repository code 54 | uses: actions/checkout@v4 55 | - run: cd ${{ github.workspace }} 56 | 57 | - run: brew install python-tk 58 | 59 | - uses: ./.github/run-tests 60 | 61 | - name: Upload artifacts 62 | uses: actions/upload-artifact@v4 63 | with: 64 | name: build-engine-randomizer-macos 65 | path: dist/build-engine-randomizer 66 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Build Engine Randomizer 2 | Build Engine Randomizer currently supports: Duke Nukem 3D, Ion Fury, Shadow Warrior (1997), Blood, and PowerSlave/Exhumed (and maybe more in the future!) 3 | 4 | # Trailer 5 | 6 | 7 | Build Engine Randomizer Trailer 8 | 9 | Download build-engine-randomizer.exe from [the Assets section on the Releases page](https://github.com/Die4Ever/build-engine-randomizer/releases). Put eduke32.exe/nblood.exe/etc into the game's folder. Run the Randomizer it, point it to the game's GRP file, choose your settings, and click Randomize! Make sure you have a backup of your game files first just in case. On Windows the Randomizer will generate a bat file for you to play, and then you can just play the game as normal, choose which episode and which difficulty, and it will automatically use the new map files. You do NOT select "USER MAP" in the game menus. If you don't get a bat file, then [see the wiki](https://github.com/Die4Ever/build-engine-randomizer/wiki#how-to-use) for how to play. 10 | 11 | For info on where to get the games and how to run them, [check out our wiki here](https://github.com/Die4Ever/build-engine-randomizer/wiki). 12 | 13 | Damn, I'm lookin' good! 14 | 15 | "Damn, I'm lookin' good!" 16 | 17 | GUI 18 | 19 | Randomizes enemies and items. For games that use CON files (Duke Nukem 3D and Ion Fury so far) it also randomizes values like maximum health and ammo values, and enemy strengths. Also supports randomizing the map order. Be warned that putting every setting to maximum will make the game nearly impossible. I suggest you start with the default settings. Also check out the Randomizer.html file that gets created in the output directory to see what's changed. 20 | 21 | [Join our Discord here!](https://discord.gg/QwjnYWhKsY) 22 | 23 | Also check out [our new website, Mods4Ever.com](https://Mods4Ever.com/) 24 | -------------------------------------------------------------------------------- /.github/release_template.md: -------------------------------------------------------------------------------- 1 | Build Engine Randomizer currently supports: Duke Nukem 3D, Ion Fury, Shadow Warrior (1997), Blood, and PowerSlave/Exhumed (and maybe more in the future!) 2 | 3 | # Trailer 4 | 5 | 6 | Build Engine Randomizer Trailer 7 | 8 | Download build-engine-randomizer.exe from the Assets section below. Put eduke32.exe/nblood.exe/etc into the game's folder. Run the Randomizer it, point it to the game's GRP file, choose your settings, and click Randomize! Make sure you have a backup of your game files first just in case. On Windows the Randomizer will generate a bat file for you to play, and then you can just play the game as normal, choose which episode and which difficulty, and it will automatically use the new map files. You do NOT select "USER MAP" in the game menus. If you don't get a bat file, then [see the wiki](https://github.com/Die4Ever/build-engine-randomizer/wiki#how-to-use) for how to play. 9 | 10 | For info on where to get the games and how to run them, [check out our wiki here](https://github.com/Die4Ever/build-engine-randomizer/wiki). 11 | 12 |
13 | Screenshots 14 | Damn, I'm lookin' good! 15 | 16 | "Damn, I'm lookin' good!" 17 | 18 | GUI 19 |
20 | 21 | Randomizes enemies and items. For games that use CON files (Duke Nukem 3D and Ion Fury so far) it also randomizes values like maximum health and ammo values, and enemy strengths. Also supports randomizing the map order. Be warned that putting every setting to maximum will make the game nearly impossible. I suggest you start with the default settings. Also check out the Randomizer.html file that gets created in the output directory to see what's changed. 22 | 23 | ## Changes 24 | 25 | * 26 | 27 | [Join our Discord here!](https://discord.gg/QwjnYWhKsY) 28 | 29 | Also check out [our new website, Mods4Ever.com](https://Mods4Ever.com/) 30 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | temp/ 2 | dist/ 3 | build/ 4 | errorlog.txt 5 | othertests/ 6 | combine/ 7 | 8 | # Byte-compiled / optimized / DLL files 9 | __pycache__/ 10 | *.py[cod] 11 | *$py.class 12 | *.py.profile 13 | 14 | # C extensions 15 | *.so 16 | 17 | # Distribution / packaging 18 | .Python 19 | build/ 20 | develop-eggs/ 21 | dist/ 22 | downloads/ 23 | eggs/ 24 | .eggs/ 25 | lib/ 26 | lib64/ 27 | parts/ 28 | sdist/ 29 | var/ 30 | wheels/ 31 | pip-wheel-metadata/ 32 | share/python-wheels/ 33 | *.egg-info/ 34 | .installed.cfg 35 | *.egg 36 | MANIFEST 37 | 38 | # PyInstaller 39 | # Usually these files are written by a python script from a template 40 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 41 | *.manifest 42 | *.spec 43 | 44 | # Installer logs 45 | pip-log.txt 46 | pip-delete-this-directory.txt 47 | 48 | # Unit test / coverage reports 49 | htmlcov/ 50 | .tox/ 51 | .nox/ 52 | .coverage 53 | .coverage.* 54 | .cache 55 | nosetests.xml 56 | coverage.xml 57 | *.cover 58 | *.py,cover 59 | .hypothesis/ 60 | .pytest_cache/ 61 | 62 | # Translations 63 | *.mo 64 | *.pot 65 | 66 | # Django stuff: 67 | *.log 68 | local_settings.py 69 | db.sqlite3 70 | db.sqlite3-journal 71 | 72 | # Flask stuff: 73 | instance/ 74 | .webassets-cache 75 | 76 | # Scrapy stuff: 77 | .scrapy 78 | 79 | # Sphinx documentation 80 | docs/_build/ 81 | 82 | # PyBuilder 83 | target/ 84 | 85 | # Jupyter Notebook 86 | .ipynb_checkpoints 87 | 88 | # IPython 89 | profile_default/ 90 | ipython_config.py 91 | 92 | # pyenv 93 | .python-version 94 | 95 | # pipenv 96 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 97 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 98 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 99 | # install all needed dependencies. 100 | #Pipfile.lock 101 | 102 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 103 | __pypackages__/ 104 | 105 | # Celery stuff 106 | celerybeat-schedule 107 | celerybeat.pid 108 | 109 | # SageMath parsed files 110 | *.sage.py 111 | 112 | # Environments 113 | .env 114 | .venv 115 | env/ 116 | venv/ 117 | ENV/ 118 | env.bak/ 119 | venv.bak/ 120 | 121 | # Spyder project settings 122 | .spyderproject 123 | .spyproject 124 | 125 | # Rope project settings 126 | .ropeproject 127 | 128 | # mkdocs documentation 129 | /site 130 | 131 | # mypy 132 | .mypy_cache/ 133 | .dmypy.json 134 | dmypy.json 135 | 136 | # Pyre type checker 137 | .pyre/ 138 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: release 2 | on: 3 | release: 4 | types: [published] 5 | 6 | jobs: 7 | Windows-Release: 8 | runs-on: windows-latest 9 | steps: 10 | - run: echo "🔎 The name of your branch is ${{ github.ref }} and your repository is ${{ github.repository }}." 11 | - name: Check out repository code 12 | uses: actions/checkout@v4 13 | - run: cd ${{ github.workspace }} 14 | 15 | - uses: ./.github/run-tests 16 | 17 | - name: Upload Release Asset 18 | id: upload-release-asset 19 | uses: svenstaro/upload-release-action@v2 20 | with: 21 | repo_token: ${{ secrets.GITHUB_TOKEN }} 22 | file: dist/build-engine-randomizer.exe 23 | asset_name: build-engine-randomizer.exe 24 | tag: ${{ github.ref }} 25 | overwrite: true 26 | 27 | Linux-Release: 28 | runs-on: ubuntu-latest 29 | defaults: 30 | run: 31 | # Must be explicit for proper pipefail support 32 | shell: bash 33 | steps: 34 | - run: echo "🔎 The name of your branch is ${{ github.ref }} and your repository is ${{ github.repository }}." 35 | - name: Check out repository code 36 | uses: actions/checkout@v4 37 | - run: cd ${{ github.workspace }} 38 | 39 | - run: sudo apt-get update -y 40 | - run: sudo apt-get install -y python3-tk idle3 41 | 42 | - uses: ./.github/run-tests 43 | 44 | - name: Upload Release Asset 45 | id: upload-release-asset 46 | uses: svenstaro/upload-release-action@v2 47 | with: 48 | repo_token: ${{ secrets.GITHUB_TOKEN }} 49 | file: dist/build-engine-randomizer 50 | asset_name: build-engine-randomizer-linux 51 | tag: ${{ github.ref }} 52 | overwrite: true 53 | 54 | MacOS-Release: 55 | runs-on: macos-latest 56 | defaults: 57 | run: 58 | # Must be explicit for proper pipefail support 59 | shell: bash 60 | steps: 61 | - run: echo "🔎 The name of your branch is ${{ github.ref }} and your repository is ${{ github.repository }}." 62 | - name: Check out repository code 63 | uses: actions/checkout@v4 64 | - run: cd ${{ github.workspace }} 65 | 66 | - run: brew install python-tk 67 | 68 | - uses: ./.github/run-tests 69 | 70 | - name: Upload Release Asset 71 | id: upload-release-asset 72 | uses: svenstaro/upload-release-action@v2 73 | with: 74 | repo_token: ${{ secrets.GITHUB_TOKEN }} 75 | file: dist/build-engine-randomizer 76 | asset_name: build-engine-randomizer-macos 77 | tag: ${{ github.ref }} 78 | overwrite: true 79 | -------------------------------------------------------------------------------- /BuildLibs/confile.py: -------------------------------------------------------------------------------- 1 | from BuildLibs import * 2 | import BuildGames 3 | from pathlib import Path 4 | import re 5 | 6 | defineregex = re.compile('^define\s+([^\s]+)\s+(\d+)(.*)$') 7 | 8 | class ConFile: 9 | def __init__(self, game, conSettings, name, text): 10 | info('\n', name, len(text)) 11 | self.game = game 12 | self.conSettings:dict = conSettings 13 | self.name:str = name 14 | self.text:str = text 15 | for v in self.conSettings: 16 | r = re.compile('^'+v['regexstr']+'$') 17 | v['regex'] = r 18 | 19 | def GetVarSettings(self, name) -> dict|None: 20 | for v in self.conSettings: 21 | if v['regex'].match(name): 22 | return v 23 | return None 24 | 25 | def RandomizeLine(self, l:str, seed:int, range:float, balance_scale:float, difficulty:float) -> str: 26 | m = defineregex.match(l) 27 | if not m: 28 | return l 29 | name = m.group(1) 30 | oldval = int(m.group(2)) 31 | theRest = m.group(3) 32 | 33 | var_settings:dict|None = self.GetVarSettings(name) 34 | if var_settings is None: 35 | return l 36 | var_difficulty = var_settings.get('difficulty', 0) 37 | 38 | rng = random.Random(crc32('define', name, seed)) 39 | range *= var_settings.get('range', 1) 40 | r = rng.random() * range + 1 41 | 42 | if var_difficulty < 0: 43 | recip_chance = difficulty 44 | elif var_difficulty > 0: 45 | recip_chance = 1 - difficulty 46 | else: 47 | recip_chance = 0.5 48 | 49 | if rng.random() < recip_chance: 50 | r = 1/r 51 | r *= balance_scale * var_settings.get('balance', 1) 52 | newval = round(oldval * r) 53 | self.spoilerlog.Change(name, oldval, newval) 54 | return 'define '+name+' '+str(newval)+theRest 55 | 56 | def Randomize(self, seed:int, settings:dict, spoilerlog): 57 | try: 58 | spoilerlog.SetFilename(Path(self.name)) 59 | self.spoilerlog = spoilerlog 60 | self._Randomize(seed, settings) 61 | finally: 62 | self.spoilerlog = None 63 | spoilerlog.FinishRandomizingFile() 64 | 65 | def _Randomize(self, seed:int, settings:dict): 66 | # split lines 67 | range:float = settings['conFile.range'] 68 | scale:float = settings['conFile.scale'] 69 | difficulty:float = settings['conFile.difficulty'] 70 | if range == 0 or difficulty is None: 71 | return 72 | out = '' 73 | for l in self.text.splitlines(): 74 | l = l.strip() 75 | if l.startswith('define '): 76 | l = self.RandomizeLine(l, seed, range, scale, difficulty) 77 | out += l + '\r\n' 78 | self.text = out 79 | info('\n') 80 | 81 | def GetText(self) -> str: 82 | return self.text 83 | -------------------------------------------------------------------------------- /BuildGames/PowerSlave.py: -------------------------------------------------------------------------------- 1 | from BuildGames import * 2 | 3 | AddGame('PowerSlave', 'PowerSlave', 26904012, 'AC80ECB6', '4ae5cbe10396147ae042463b7df8010f', '548751e10f5c25f80d95321565b13f4664434981', canUseGrpFile=True) # STUFF.DAT 4 | AddGame('PowerSlave', 'PowerSlave', 27108170, 'E3B172F1', 'b51391e08a17e5c46e25f6cf46f892eb', 'b84fd656be67271910e5eba4caf69bc81192c174', canUseGrpFile=True) # STUFF.DAT 5 | AddGame('PowerSlave Demo', 'PowerSlave', 15904838, '1D8C7645', '61f5b2871e57e757932f338adefbc878', '6bb4b2974da3d90e70c6b4dc56b296f907c180f0', canUseGrpFile=True) # STUFF.DAT shareware 6 | AddGame('Exhumed Demo', 'PowerSlave', 16481687, '1A6E27FA', 'e368de92d99e4fb85ebe5f188eb175e3', '2062fec5d513850b3c3dc66c7d44c4b0f91296db', canUseGrpFile=True) # STUFF.DAT shareware 7 | 8 | AddMapSettings('PowerSlave', minMapVersion=6, maxMapVersion=6, 9 | swappableItems={ 10 | **SpriteRange(326, 331, SpriteInfo('Life Blood')), 11 | **SpriteRange(332, 337, SpriteInfo('Cobra Venom Bowl')), 12 | 782: SpriteInfo('Still Beating Heart'), 13 | 488: SpriteInfo('Pistol'), 14 | 490: SpriteInfo('Machine Gun'), 15 | 491: SpriteInfo('Fancy Gun'), 16 | 877: SpriteInfo('Quick Loader'), 17 | 878: SpriteInfo('Grenade'), 18 | 879: SpriteInfo('Fuel Canister'), 19 | 881: SpriteInfo('Machine Gun Ammo'), 20 | 882: SpriteInfo('Machine Gun Ammo'), 21 | **SpriteRange(899, 901, SpriteInfo('Cobra Staff')), 22 | 983: SpriteInfo('Extra Life'), 23 | 3457: SpriteInfo('Golden Cobra'), 24 | **SpriteRange(3502, 3507, SpriteInfo('Magical Essence')), 25 | **SpriteRange(3516, 3520, SpriteInfo('Raw Energy')), 26 | 3602: SpriteInfo('Grenade'), 27 | }, 28 | swappableEnemies={ 29 | **SpriteRange(861, 875, SpriteInfo('Spider')), 30 | **SpriteRange(1526, 1531, SpriteInfo('Mummy')), 31 | **SpriteRange(1664, 1746, SpriteInfo('Mummy')), 32 | **SpriteRange(1949, 1963, SpriteInfo('Mummy')), 33 | **SpriteRange(2311, 2373, SpriteInfo('Anubis Zombie')), 34 | **SpriteRange(2432, 2497, SpriteInfo('Omenwasp')), 35 | 2552: SpriteInfo('Omenwasp'), 36 | **SpriteRange(2498, 2548, SpriteInfo('Am-mit')), 37 | **SpriteRange(2751, 2816, SpriteInfo('Bastet')), 38 | **SpriteRange(3038, 3049, SpriteInfo('Bastet')), 39 | **SpriteRange(3137, 3147, SpriteInfo('Mouth')), 40 | **SpriteRange(3200, 3250, SpriteInfo('Grasshopper')), 41 | }, 42 | triggers={}, 43 | additions={}, 44 | keyItems={ 45 | **SpriteRange(3320, 3347, SpriteInfo('Key')), 46 | }, 47 | bosses={ 48 | **SpriteRange(2559, 2642, SpriteInfo('Set')), 49 | 2687: SpriteInfo('Set'), 50 | **SpriteRange(2643, 2675, SpriteInfo('Magmantis')), 51 | **SpriteRange(2698, 2750, SpriteInfo('Selkis')), 52 | **SpriteRange(3072, 3136, SpriteInfo('Kilmaatikahn')), 53 | **SpriteRange(3151, 3181, SpriteInfo('Kilmaatikahn')), 54 | } 55 | ) 56 | 57 | AddGameSettings('PowerSlave', 58 | commands= dict( 59 | grp={'pcexhumed': '-nosetup -g'}, 60 | folder={'pcexhumed': '-nosetup -j '} 61 | ) 62 | ) 63 | -------------------------------------------------------------------------------- /BuildGames/OtherGames.py: -------------------------------------------------------------------------------- 1 | from BuildGames import * 2 | 3 | AddGame('Platoon Leader', 'WWII GI', 37852572, 'D1ED8C0C') # PLATOONL_CRC 4 | 5 | AddGame('NAPALM.GRP', 'Napalm', 44365728, '3DE1589A', 'D926E362839949AA6EBA5BDF35A5F2D6', '9C42E7268A45D57E4B7961E6F1D3414D9DE12323') # NAPALM.GRP 6 | #AddGame('NAPALM.RTS', 'Napalm', 564926, '12505172', 'D571897B4E3D43B3757A98C856869ED7', 'C90B050192030FFBD0137C03A4181CB1705B95D3') # NAPALM.RTS 7 | #AddGame('NAPALM.CON (GAME.CON)', 'Napalm', 142803, '75EF92BD', 'CCBBB146C094F490242FD922293DD5F9', '46F3AE2B37983660835F220AECEEA6060C89F2A7') # NAPALM.CON (GAME.CON) 8 | AddGame('NAM.GRP', 'NAM', 43448927, '75C1F07B', '6C910A5438E230F85804353AC54D77B9', '2FD12F94246FBD3014223B76301B812EE8341D05') # NAM.GRP 9 | #AddGame('NAM.RTS', 'NAM', 564926, '12505172', 'D571897B4E3D43B3757A98C856869ED7', 'C90B050192030FFBD0137C03A4181CB1705B95D3') # NAM.RTS 10 | #AddGame('NAM.CON (GAME.CON)', 'NAM', 142803, '75EF92BD', 'CCBBB146C094F490242FD922293DD5F9', '46F3AE2B37983660835F220AECEEA6060C89F2A7') # NAM.CON (GAME.CON) 11 | AddGame('WW2GI.GRP', 'WWII GI', 77939508, '907B82BF', '27E927BEBA43447DB3951EAADEDB4709', 'FD0208A55EAEF3937C126E1FFF474FB4DFBDA6F5') # WW2GI.GRP 12 | #AddGame('WW2GI.RTS', 'WWII GI', 259214, '79D16760', '759F66C9F3C70AEDCAE29473AADE9966', 'CE352EF4C22F85869FDCB060A64EBC263ACEA6B0') # WW2GI.RTS 13 | 14 | AddGame('A.W.O.L. v0.91', 'AWOL', 252384950, '894F0199', '0161F85CEE80E1A60A28F40643BF02B2', 'C797F9D3BED6BADAD62C4C9C14D78F34058D97A8', canUseRandomizerFolder=False) # AWOL.GRP 15 | AddGame('A.W.O.L.', 'AWOL', 244458025, 'DA99945F', '11812e4a50f6151c14df64bf0caae33a', '44393A5DC91BFC59533C679575A5ECD977B416C2', canUseRandomizerFolder=False) # AWOL.GRP r9597-bb01a1394 16 | 17 | 18 | AddMapSettings('AWOL', minMapVersion=7, maxMapVersion=9, 19 | swappableItems = { 20 | }, 21 | swappableEnemies = { 22 | }, 23 | addableEnemies = [], 24 | triggers={} 25 | ) 26 | # ['awol.con', 'data/awol_aibot.con', 'data/awol_astar.con', 'data/awol_choreo.con', 'data/awol_choreo_scripts.con', 'data/awol_common.con', 'data/awol_customize.con', 'data/awol_cutscene_script1.con', 'data/awol_cutscene_script10.con', 'data/awol_cutscene_script11.con', 'data/awol_cutscene_script2.con', 'data/awol_cutscene_script3.con', 'data/awol_cutscene_script4.con', 'data/awol_cutscene_script5.con', 'data/awol_cutscene_script6.con', 'data/awol_cutscene_script7.con', 'data/awol_cutscene_script8.con', 'data/awol_cutscene_script9.con', 'data/awol_cutscenes.con', 'data/awol_env.con', 'data/awol_ghost.con', 'data/awol_interactables.con', 'data/awol_inventory.con', 'data/awol_levels.con', 'data/awol_main.con', 'data/awol_materials.con', 'data/awol_materials_defs.con', 'data/awol_materials_init.con', 'data/awol_names.con', 'data/awol_nodegraph.con', 'data/awol_objective_scripts.con', 'data/awol_pickups.con', 'data/awol_player.con', 'data/awol_scripted.con', 'data/awol_sounds.con', 'data/awol_subtitles.con', 'data/awol_text.con', 'data/awol_tokens.con', 'data/awol_ui.con', 'data/awol_vfx.con', 'data/awol_weapons.con', 'data/awol_weather.con', 'data/enemy_arctic.con', 'data/enemy_arena.con', 'data/enemy_flyers.con', 'data/enemy_guerrilla.con', 'data/enemy_insurgent.con', 'data/enemy_jungle.con', 'data/enemy_legacy.con', 'data/enemy_security.con', 'data/enemy_shared.con', 'data/mikko.con'] 27 | AddGameSettings('AWOL', conFiles = { 28 | }) 29 | -------------------------------------------------------------------------------- /GUI/__init__.py: -------------------------------------------------------------------------------- 1 | from tkinter import * 2 | from tkinter import filedialog 3 | from tkinter import font 4 | from tkinter import messagebox 5 | import traceback 6 | from idlelib.tooltip import Hovertip 7 | from BuildLibs import * 8 | 9 | # probably some stuff for easy layouts and config handling, and maybe a dialog class, a class for a progress bar window 10 | 11 | class GUIBase: 12 | def __init__(self): 13 | self.width=480 14 | self.height=500 15 | self.initWindow() 16 | #self.ChooseFile() 17 | if self.root: 18 | self.root.mainloop() 19 | 20 | def closeWindow(self): 21 | self.root.destroy() 22 | self.root=None 23 | 24 | def isWindowOpen(self) -> bool: 25 | return self.root!=None 26 | 27 | def resize(self,event): 28 | if event.widget == self.root: 29 | try: 30 | trace('resize', event.width, event.height) 31 | self.width = event.width 32 | self.height = event.height 33 | except Exception as e: 34 | error('ERROR: in resize:', e) 35 | 36 | def newInput(self, cls, label:str, tooltip:str, row:int, *args, **kargs): 37 | label = Label(self.win,text=label,width=22,height=2,font=self.font, anchor='e', justify='left') 38 | label.grid(column=0,row=row, sticky='E') 39 | if cls == OptionMenu: 40 | entry = cls(self.win, *args, **kargs) 41 | else: 42 | entry = cls(self.win, *args, width=18,font=self.font, **kargs) 43 | entry.grid(column=1,row=row, sticky='W') 44 | 45 | myTip = Hovertip(label, tooltip) 46 | myTip = Hovertip(entry, tooltip) 47 | return entry 48 | 49 | 50 | # from https://stackoverflow.com/a/68701602 51 | class ScrollableFrame: 52 | """ 53 | # How to use class 54 | from tkinter import * 55 | obj = ScrollableFrame(master,height=300 # Total required height of canvas,width=400 # Total width of master) 56 | objframe = obj.frame 57 | # use objframe as the main window to make widget 58 | """ 59 | def __init__ (self,master,width,height,mousescroll=0): 60 | self.mousescroll = mousescroll 61 | self.master = master 62 | self.height = height 63 | self.width = width 64 | self.main_frame = Frame(self.master) 65 | self.main_frame.pack(fill=BOTH,expand=1) 66 | 67 | self.scrollbar = Scrollbar(self.main_frame, orient=VERTICAL) 68 | self.scrollbar.pack(side=RIGHT,fill=Y) 69 | 70 | self.canvas = Canvas(self.main_frame,yscrollcommand=self.scrollbar.set) 71 | self.canvas.pack(expand=True,fill=BOTH) 72 | 73 | self.scrollbar.config(command=self.canvas.yview) 74 | 75 | self.canvas.bind('', lambda e: self.canvas.configure(scrollregion = self.canvas.bbox("all"))) 76 | 77 | self.frame = Frame(self.canvas,width=self.width,height=self.height) 78 | self.frame.pack(expand=True,fill=BOTH) 79 | self.canvas.create_window((0,0), window=self.frame, anchor="nw") 80 | 81 | self.frame.bind("", self.entered) 82 | self.frame.bind("", self.left) 83 | 84 | def _on_mouse_wheel(self,event): 85 | self.canvas.yview_scroll(-1 * int((event.delta / 120)), "units") 86 | 87 | def entered(self,event): 88 | if self.mousescroll: 89 | self.canvas.bind_all("", self._on_mouse_wheel) 90 | 91 | def left(self,event): 92 | if self.mousescroll: 93 | self.canvas.unbind_all("") 94 | 95 | 96 | def errordialog(title, msg, e=None): 97 | if e: 98 | msg += '\n' + str(e) + '\n\n' + traceback.format_exc() 99 | error(title, '\n', msg) 100 | messagebox.showerror(title, msg) 101 | -------------------------------------------------------------------------------- /BuildGames/ShadowWarrior.py: -------------------------------------------------------------------------------- 1 | from BuildGames import * 2 | 3 | AddGame('Shadow Warrior', 'Shadow Warrior', 47536148, '7545319F', '9d200b5fb4ace8797e7f8638c4f96af2', '4863226c01d0850c65ac0a3e20831e072b285425', canUseGrpFile=True) # Steam "Classic" version https://store.steampowered.com/app/238070/Shadow_Warrior_Classic_1997/ 4 | 5 | # https://forums.duke4.net/topic/11406-shadow-warrior-scriptset-for-mapster32/ 6 | # using find and replace regex on duke3d.def from the above link 7 | # voxel "([^"]+)"\s+\{\s+tile\s+(\d+)\s+\} 8 | # $2: '$1', 9 | AddMapSettings('Shadow Warrior', minMapVersion=7, maxMapVersion=7, 10 | swappableItems = { 11 | 1802: SpriteInfo('medpak'), 12 | 1803: SpriteInfo('medkit'), 13 | 1797: SpriteInfo('uzi'), 14 | 1817: SpriteInfo('grenade'), 15 | 764: SpriteInfo('gunbarl'), 16 | 765: SpriteInfo('camera'), 17 | 1831: SpriteInfo('40mmbox'), 18 | 1842: SpriteInfo('mines'), 19 | 1794: SpriteInfo('shotgun'), 20 | 1818: SpriteInfo('rocket'), 21 | 1823: SpriteInfo('shtgammo'), 22 | 1800: SpriteInfo('rcktammo'), 23 | 1813: SpriteInfo('tools'), 24 | 1799: SpriteInfo('uziclip'), 25 | 3031: SpriteInfo('nitevis'), 26 | 1811: SpriteInfo('railgun'), 27 | 1812: SpriteInfo('railpak'), 28 | 3030: SpriteInfo('armor'), 29 | 1793: SpriteInfo('star'), 30 | 1819: SpriteInfo('heat'), 31 | 1792: SpriteInfo('coin'), 32 | 1824: SpriteInfo('heart'), 33 | 1825: SpriteInfo('heart2'), 34 | 1807: SpriteInfo('uziside'), 35 | 1809: SpriteInfo('bomb'), 36 | 1808: SpriteInfo('smoke'), 37 | 1805: SpriteInfo('flash'), 38 | 1814: SpriteInfo('gorohead'), 39 | 1804: SpriteInfo('shadow'), 40 | 1829: SpriteInfo('caltrop'), 41 | 1810: SpriteInfo('cookie'), 42 | #1766: SpriteInfo('techkey'), 43 | #1765: SpriteInfo('oldkey'), 44 | # 2520: SpriteInfo('flag1'), 45 | # 2521: SpriteInfo('flag2'), 46 | # 2522: SpriteInfo('flag3'), 47 | # 1767: SpriteInfo('keycard'), 48 | # 1846: SpriteInfo('oldlock'), 49 | # 1847: SpriteInfo('oldlock2'), 50 | # 1850: SpriteInfo('kcrdlck1'), 51 | # 1851: SpriteInfo('kcrdlck2'), 52 | # 1852: SpriteInfo('tchklck1'), 53 | # 1853: SpriteInfo('tchklck2'), 54 | # 1854: SpriteInfo('tchklck3'), 55 | # 1765: SpriteInfo('MASTER_KEY1'),# gold 56 | # 1769: SpriteInfo('oldkey'),# silver 57 | # 1773: SpriteInfo('oldkey'),# bronze 58 | # 1777: SpriteInfo('oldkey'),# red 59 | # 1770: SpriteInfo('techkey'), 60 | # 1774: SpriteInfo('techkey'), 61 | # 1778: SpriteInfo('techkey'), 62 | # 1771: SpriteInfo('keycard'), 63 | # 1775: SpriteInfo('keycard'), 64 | # 1779: SpriteInfo('keycard'), 65 | 817: SpriteInfo('mine'), 66 | 818: SpriteInfo('mine2'), 67 | 819: SpriteInfo('mine3'), 68 | #2470: 'EXIT_SWITCH' 69 | }, 70 | swappableEnemies = { 71 | 4096: SpriteInfo('EVIL_NINJA'), 72 | 4162: SpriteInfo('EVIL_NINJA_CROUCHING'), 73 | 4320: SpriteInfo('BIG_RIPPER'), 74 | 1400: SpriteInfo('COOLIE'), 75 | 1441: SpriteInfo('COOLIE_GHOST'), 76 | 1469: SpriteInfo('GREEN_GUARDIAN'), 77 | 5162: SpriteInfo('FEMALE_WARRIOR'), 78 | 1580: SpriteInfo('LITTLE_RIPPER'), 79 | #3780: SpriteInfo('FISH'), 80 | 800: SpriteInfo('HORNET'), 81 | }, 82 | addableEnemies = [4096, 4320, 1400, 1441, 1469, 5162, 1580, 800,], 83 | triggers={}, 84 | bosses={ 85 | 1210: SpriteInfo('SUMO_BOSS'), 86 | 1300: SpriteInfo('SERPENT_BOSS'), 87 | 5426: SpriteInfo('ZILLA_BOSS') 88 | } 89 | ) 90 | # Keys (picnums 1765-1779) 91 | # Locks 1846-1854 92 | 93 | AddGameSettings('Shadow Warrior', 94 | commands = dict( # https://voidpoint.io/terminx/eduke32/-/blob/master/source/duke3d/src/cmdline.cpp#L39 95 | grp={'voidsw': '-nosetup -g'}, 96 | folder={'voidsw': '-nosetup -j '}, 97 | simple={} 98 | )) 99 | -------------------------------------------------------------------------------- /BuildLibs/__init__.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | if sys.version_info[0] < 3: 4 | raise ImportError('Python < 3 is unsupported.') 5 | if sys.version_info[0] == 3 and sys.version_info[1] < 6: 6 | raise ImportError('Python < 3.6 is unsupported.') 7 | 8 | import os 9 | from typing import OrderedDict, Union 10 | import struct 11 | import binascii 12 | from collections import namedtuple 13 | import random 14 | import pathlib 15 | from datetime import datetime 16 | import re 17 | 18 | def GetVersion() -> str: 19 | return 'v0.9.6 Beta' 20 | 21 | packLengthRegex = re.compile('^(.*?)(\d+)(\w)(.*?)$') 22 | class FancyPacker: 23 | 24 | def __init__(self, endianness: str, mappings: OrderedDict): 25 | self.format = endianness 26 | self.keys = {} 27 | self.total_len = 0 28 | for k, v in mappings.items(): 29 | self.format += v 30 | m = packLengthRegex.match(v) 31 | if m: 32 | self.keys[k] = len(m.group(1)) + 1 + len(m.group(4)) 33 | else: 34 | self.keys[k] = len(v) 35 | self.total_len += self.keys[k] 36 | 37 | def unpack(self, data: bytes) -> dict: 38 | t = struct.unpack(self.format, data) 39 | dict = {} 40 | i = 0 41 | for k, L in self.keys.items(): 42 | if L == 1: 43 | dict[k] = t[i] 44 | i+=1 45 | continue 46 | dict[k] = list(t[i:i+L]) 47 | i+=L 48 | return dict 49 | 50 | def pack(self, dict: dict) -> bytes: 51 | values = [None] * self.total_len 52 | i = 0 53 | for k, L in self.keys.items(): 54 | v = dict[k] 55 | if L > 1: 56 | values[i:i+L] = v 57 | else: 58 | values[i] = v 59 | i+=L 60 | return struct.pack(self.format, *values) 61 | 62 | def calcsize(self) -> int: 63 | return struct.calcsize(self.format) 64 | 65 | 66 | def crc32(*args): 67 | s = ' '.join(map(str, args)) 68 | return binascii.crc32(s.encode('utf8')) 69 | 70 | def swapdictkey(a, b, key): 71 | a[key], b[key] = b[key], a[key] 72 | 73 | def swapobjkey(a, b, key): 74 | a.__dict__[key], b.__dict__[key] = b.__dict__[key], a.__dict__[key] 75 | 76 | # 1-level deep copy, usually enough 77 | def copyobj(obj): 78 | d = obj.__dict__.copy() 79 | for k in d.keys(): 80 | if type(d[k]) not in [int, str, bool, type(None)]: 81 | d[k] = d[k].copy() 82 | obj = type(obj)() 83 | obj.__dict__ = d 84 | return obj 85 | 86 | verbose = 1 87 | 88 | def checkCleanupErrorLog(): 89 | if getattr(checkCleanupErrorLog, "checked", False): 90 | return 91 | checkCleanupErrorLog.checked = True 92 | doCleanup = True 93 | 94 | try: 95 | if os.path.isfile("errorlog.txt"): 96 | with open("errorlog.txt") as file: 97 | doCleanup = False 98 | firstLine = file.readline() 99 | end = file.seek(0, 2) 100 | if firstLine.strip() != GetVersion(): 101 | doCleanup = True 102 | elif end > 1024 * 1024 * 10:# max of 10 MB 103 | doCleanup = True 104 | 105 | if doCleanup: 106 | with open("errorlog.txt", 'w') as file: 107 | print(GetVersion() +'\n', file=file) 108 | else: 109 | with open("errorlog.txt", "a") as file: 110 | print('\n\n', file=file) 111 | except Exception as e: 112 | # the checked property means this function won't be called recursively 113 | error('checkCleanupErrorLog:', e) 114 | 115 | 116 | def error(*args, **kargs): 117 | print('ERROR:', *args, **kargs) 118 | checkCleanupErrorLog() 119 | with open("errorlog.txt", "a") as file: 120 | print(datetime.now().strftime('%c') + ': ERROR:', *args, **kargs, file=file) 121 | 122 | def warning(*args, **kargs): 123 | print('WARNING:', *args, **kargs) 124 | checkCleanupErrorLog() 125 | with open("errorlog.txt", "a") as file: 126 | print(datetime.now().strftime('%c') + ': WARNING:', *args, **kargs, file=file) 127 | 128 | def info(*args, **kargs): 129 | if verbose > -1: 130 | print('INFO:', *args, **kargs) 131 | 132 | def debug(*args, **kargs): 133 | if verbose > 0: 134 | print('DEBUG:', *args, **kargs) 135 | 136 | def trace(*args, **kargs): 137 | if verbose > 1: 138 | print('TRACE:', *args, **kargs) 139 | 140 | 141 | def setVerbose(v: int): 142 | global verbose 143 | verbose = v 144 | -------------------------------------------------------------------------------- /BuildLibs/SpoilerLog.py: -------------------------------------------------------------------------------- 1 | import traceback 2 | from BuildLibs import * 3 | from pathlib import Path 4 | 5 | class SpoilerLog: 6 | def __init__(self, filename:Path): 7 | self.filename = filename 8 | self.file = None 9 | self.currentFile = '' 10 | self.FinishRandomizingFile() 11 | 12 | def __enter__(self): 13 | assert not self.filename.exists() 14 | self.file = open(self.filename, 'w', encoding='utf-8') 15 | self.WriteHeader() 16 | return self 17 | 18 | def __exit__(self, exc_type, exc_value, tb): 19 | if exc_value: 20 | text = "".join(traceback.format_exception(exc_type, exc_value, tb)) 21 | self._WriteHtml('error', text) 22 | self.WriteFooter() 23 | self.file.close() 24 | 25 | def WriteHeader(self): 26 | html = """ 27 | 28 | 29 | 30 | Build Engine Randomizer Spoiler Log 31 | 58 | 59 | 78 | 79 | \n""" 80 | self.file.write(html) 81 | 82 | def WriteFooter(self): 83 | html = '\n' 84 | self.file.write(html) 85 | 86 | def write(self, text:str): 87 | info(text) 88 | self._WriteHtml('write', text) 89 | 90 | def _WriteHtml(self, classname:str, text:str): 91 | self.file.write('
' + text.replace('\n', '
') + '
\n') 92 | 93 | def Change(self, var, old, new): 94 | text = ' ' + var + ' changed from ' + str(old) + ' to ' + str(new) 95 | trace(text) 96 | self._WriteHtml('Change', text) 97 | 98 | def AddSprite(self, type, sprite): 99 | text = ' added ' + type + ' ' + self.DescribeSprite(sprite) 100 | trace(text) 101 | #self._WriteHtml('AddSprite', text) 102 | 103 | def DelSprite(self, type, sprite): 104 | text = ' deleted ' + type + ' ' + self.DescribeSprite(sprite) 105 | trace(text) 106 | #self._WriteHtml('DelSprite', text) 107 | 108 | def GetPicnumName(self, picnum: int) -> str: 109 | valname = None 110 | if self.gameMapSettings and picnum in self.gameMapSettings.swappableItems: 111 | valname = self.gameMapSettings.swappableItems[picnum]['name'] 112 | elif self.gameMapSettings and picnum in self.gameMapSettings.swappableEnemies: 113 | valname = self.gameMapSettings.swappableEnemies[picnum]['name'] 114 | if valname: 115 | return valname + ' ('+str(picnum)+')' 116 | return str(picnum) 117 | 118 | def DescribeSprite(self, sprite) -> str: 119 | name = self.GetPicnumName(sprite.picnum) 120 | # tuple gives parens so it looks better than a list 121 | pos = tuple(sprite.pos) 122 | return name + ' ' + str(pos) 123 | 124 | def SwapSprites(self, spritetype, s1, s2): 125 | text = ' swapping ' + spritetype + ' ' + self.DescribeSprite(s1) + ' with ' + self.DescribeSprite(s2) 126 | trace(text) 127 | #self._WriteHtml('SwapSprites', text) 128 | 129 | def ListSprites(self, spritetype, sprites): 130 | for sprite in sprites: 131 | text = ' ' + spritetype + ' ' + self.DescribeSprite(sprite) 132 | self._WriteHtml('ListSprites', text) 133 | 134 | def SpriteChangedTag(self, tagname:str, sprite, tagval): 135 | # tuple gives parens so it looks better than a list 136 | pos = str(tuple(sprite.pos)) 137 | tagval = self.GetPicnumName(tagval) 138 | text = ' set ' + tagname + ' to ' + tagval + ' on trigger (' + str(sprite.picnum) + ') at ' + pos 139 | trace(text) 140 | self._WriteHtml('SpriteChangedTag', text) 141 | 142 | # which file is currently being randomized 143 | def SetFilename(self, filename:Path): 144 | self.currentFile = filename 145 | text = 'Starting randomizing file: ' + str(filename) 146 | debug(text) 147 | self.file.write( 148 | '\n
\n' 160 | ) 161 | self.currentFile = None 162 | self.gameMapSettings = {} 163 | 164 | def SetGameMapSettings(self, gameMapSettings): 165 | self.gameMapSettings = gameMapSettings 166 | 167 | -------------------------------------------------------------------------------- /BuildGames/__init__.py: -------------------------------------------------------------------------------- 1 | import binascii 2 | import os 3 | from hashlib import md5, sha1 4 | from mmap import mmap, ACCESS_READ 5 | from BuildLibs import * 6 | from pathlib import Path 7 | 8 | gamesList = {} 9 | gamesMapSettings = {} 10 | gamesSettings = {} 11 | 12 | class GameInfo(): 13 | def __init__(self, name='', type='', size:int=0, crc:str='', md5:str='', sha1:str='', externalFiles:bool=False, canUseRandomizerFolder=True, canUseGrpFile=False, **kargs): 14 | self.name = name 15 | self.type = type 16 | self.size = size 17 | self.md5 = md5.lower() 18 | self.crc = 0 19 | if crc: 20 | self.crc = int(crc, 16) 21 | self.sha1 = sha1.lower() 22 | self.externalFiles = externalFiles 23 | self.canUseRandomizerFolder = canUseRandomizerFolder 24 | self.canUseGrpFile = canUseGrpFile 25 | # can't use external files without also using the randomizer folder, otherwise we're reading from the same files we're writing to 26 | assert not (self.externalFiles and not self.canUseRandomizerFolder) 27 | 28 | def __repr__(self): 29 | return repr(self.__dict__) 30 | 31 | def copy(self) -> 'GameInfo': 32 | return copyobj(self) 33 | 34 | 35 | def AddGame(*args, **kargs) -> GameInfo: 36 | """ 37 | def __init__(self, name='', type='', size:int=0, crc:str='', md5:str='', sha1:str='', externalFiles:bool=False, canUseRandomizerFolder=True, canUseGrpFile=False, **kargs): 38 | """ 39 | """ 40 | https://wiki.eduke32.com/wiki/Frequently_Asked_Questions 41 | ^(.*?)\t(.*?)\t(.*?)\t(.*?)\t(.*?)\t(.*?)$ 42 | AddGame('$1', '', $2, '$4', '$5', '$6') # $1 43 | (\d),(\d) 44 | $1$2 45 | idk what an SSI file is, but their sizes seem comparable to the GRP files 46 | """ 47 | 48 | global gamesList 49 | game = GameInfo(*args, **kargs) 50 | if 'allowOverwrite' not in {**kargs}: 51 | assert game.crc not in gamesList, repr(game.__dict__) 52 | gamesList[game.crc] = game 53 | return game 54 | 55 | class GameMapSettings: 56 | def __init__(self, gameName=None, minMapVersion=7, maxMapVersion=9, idType:str='picnum', 57 | swappableItems:list|dict={}, swappableEnemies:list|dict={}, addableEnemies:list=[], 58 | triggers:dict={}, additions:dict={}, reorderMapsBlacklist:list=[], **kargs): 59 | self.gameName = gameName 60 | self.minMapVersion = minMapVersion 61 | self.maxMapVersion = maxMapVersion 62 | self.idType = idType 63 | 64 | if idType == 'lowtag': 65 | assert isinstance(swappableEnemies, list) 66 | assert isinstance(swappableItems, list) 67 | for v in [*swappableEnemies, *swappableItems]: 68 | assert 'picnum' in v, 'picnum is in '+repr(v) 69 | 70 | self.swappableItems = {v[idType]: v for v in swappableItems} 71 | self.swappableEnemies = {v[idType]: v for v in swappableEnemies} 72 | elif idType == 'picnum': 73 | # TODO: only dict is supported here for now, but these should all be converted to lists later 74 | assert isinstance(swappableEnemies, dict) 75 | assert isinstance(swappableItems, dict) 76 | self.swappableItems = swappableItems 77 | self.swappableEnemies = swappableEnemies 78 | else: 79 | raise Exception('unknown idType: '+repr(idType)) 80 | 81 | assert len(self.swappableItems) == len(swappableItems) 82 | assert len(self.swappableEnemies) == len(swappableEnemies) 83 | 84 | self.addableEnemies = addableEnemies 85 | self.triggers = triggers 86 | self.additions = additions 87 | self.reorderMapsBlacklist = reorderMapsBlacklist 88 | self.__dict__.update(kargs) 89 | 90 | def __repr__(self): 91 | return repr(self.__dict__) 92 | 93 | def copy(self) -> 'GameMapSettings': 94 | return copyobj(self) 95 | 96 | def AddMapSettings(*args, **kargs) -> GameMapSettings: 97 | """ 98 | build GameMapSettings using this regex find/replace 99 | define ([\w_]+) (\d+) 100 | $2: '$1', 101 | """ 102 | global gamesMapSettings 103 | gms: GameMapSettings = GameMapSettings(*args, **kargs) 104 | assert gms.gameName not in gamesMapSettings, repr(gms.__dict__) 105 | gamesMapSettings[gms.gameName] = gms 106 | return gms 107 | 108 | class GameSettings: 109 | def __init__(self, gameName: Union[None,str]=None, mainScript: Union[None,str]=None, flags: int=0, defName: Union[None,str]=None, commands: dict={}, conFiles: dict={}): 110 | self.gameName = gameName 111 | self.mainScript = mainScript 112 | self.flags = flags 113 | self.defName = defName 114 | self.commands = commands 115 | self.conFiles = conFiles 116 | 117 | def __repr__(self): 118 | return repr(self.__dict__) 119 | 120 | def copy(self) -> 'GameSettings': 121 | return copyobj(self) 122 | 123 | # difficulty > 0 means higher number makes the game harder 124 | def AddGameSettings(*args, **kargs) -> GameSettings: 125 | global gamesSettings 126 | gs: GameSettings = GameSettings(*args, **kargs) 127 | assert gs.gameName not in gamesSettings, repr(gs.__dict__) 128 | gamesSettings[gs.gameName] = gs 129 | return gs 130 | 131 | def GetGame(grppath:Path) -> GameInfo: 132 | global gamesList 133 | size = os.path.getsize(grppath) 134 | with open(grppath) as file, mmap(file.fileno(), 0, access=ACCESS_READ) as file: 135 | crc:int = binascii.crc32(file) 136 | g:Union[GameInfo,None] = gamesList.get(crc) 137 | if g: 138 | if not g.size: 139 | g.size = size 140 | if not g.md5: 141 | g.md5 = md5(file).hexdigest() 142 | if not g.sha1: 143 | g.sha1 = sha1(file).hexdigest() 144 | info('matched game:', repr(g)) 145 | return g.copy() 146 | md5sum:str = md5(file).hexdigest() 147 | sha:str = sha1(file).hexdigest() 148 | error('ERROR: in GetGame, unknown game', grppath, 'size:', size, 'crc32:', "0x{:X}".format(crc), 'md5:', md5sum, 'sha1:', sha, sep=', ') 149 | # TODO support for unknown games with default settings, for now return dummy game 150 | return GameInfo('Unknown Game') 151 | raise Exception('error in GetGame', grppath) 152 | 153 | def GetGameMapSettings(game: GameInfo) -> GameMapSettings: 154 | global gamesMapSettings 155 | g:GameMapSettings = gamesMapSettings[game.type] 156 | return g.copy() 157 | 158 | def GetGameSettings(game: GameInfo) -> GameSettings: 159 | global gamesSettings 160 | g:GameSettings = gamesSettings.get(game.type) 161 | if not g: 162 | raise KeyError('GetGameSettings cannot find game', game.type) 163 | return g.copy() 164 | 165 | def SpriteInfo(name:str, category:str='', lowtag:int=0, xrepeat:int=0, yrepeat:int=0, palettes=None, picnum:int=0) -> dict: 166 | d = dict(name=name, category=category) 167 | if lowtag: 168 | d['lowtag'] = lowtag 169 | if xrepeat: 170 | d['xrepeat'] = xrepeat 171 | d['yrepeat'] = yrepeat 172 | if palettes: 173 | d['palettes'] = palettes 174 | if picnum: 175 | d['picnum'] = picnum 176 | return d 177 | 178 | def SpriteRange(min:int, max:int, value:dict): 179 | d={} 180 | for i in range(min,max+1): 181 | d[i] = value 182 | return d 183 | 184 | def ConVar(regex:str, difficulty:float=0, range:float=1, balance:float=1) -> dict: 185 | return { 'regexstr': regex, 'difficulty': difficulty, 'range': range, 'balance': balance } 186 | 187 | from BuildGames import Blood, Duke3d, IonFury, OtherGames, PowerSlave, ShadowWarrior 188 | -------------------------------------------------------------------------------- /BuildGames/IonFury.py: -------------------------------------------------------------------------------- 1 | from BuildGames import * 2 | 3 | AddGame('Ion Fury', 'Ion Fury', 92644120, '960B3686', 'd834055f0c9a60f8f23163b67d086546', '2cec5ab769ae27c6685d517defa766191c5e66c1', canUseRandomizerFolder=False, canUseGrpFile=True) # Steam version 4 | AddGame('Ion Fury', 'Ion Fury', 92644105, 'F3A52423', '2f2a861001ab446bd32a78667f91db40', '9b763ff2caf112d9aa9e4f5ed7a9a26c98af6eaa', canUseRandomizerFolder=False, canUseGrpFile=True) # Steam version version v2.0.01.10459 5 | 6 | AddGame('Ion Fury Aftershock', 'Ion Fury Aftershock', 163939122, '2D7CAC72', 'a326052d456a9c9a80ca13cb90270d5b', '720b17e4110448e33129504918feea3dc23fe900', canUseRandomizerFolder=False, canUseGrpFile=True) # Steam Aftershock version 7 | AddGame('Ion Fury Aftershock', 'Ion Fury Aftershock', 163948283, 'AE68B9E7', '7bfcea0b46d3afb206cbc5f4a2e3282c', '8177341cd8691b6a8667fd51d0ed9837ce74d523', canUseRandomizerFolder=False, canUseGrpFile=True) # Steam Aftershock version v3.0.03.104182 8 | AddGame('Ion Fury Aftershock', 'Ion Fury Aftershock', 160826590, 'E175FB41', 'cbd077bb55dd4f776a937a104807797f', '78c142276411ebfef7ece2133ed5c4f0b428dc65', canUseRandomizerFolder=False, canUseGrpFile=True) # Steam Aftershock version v3.0.0.9.10514 9 | 10 | ion_fury_map_settings = dict(minMapVersion=7, maxMapVersion=9, 11 | swappableItems = { 12 | 209: SpriteInfo('I_BATON'), 13 | 210: SpriteInfo('I_LOVERBOY'), 14 | 211: SpriteInfo('I_LOVERBOY_AMMO'), 15 | 212: SpriteInfo('I_MEDPACK'), 16 | 213: SpriteInfo('I_MEDICOMP'), 17 | 214: SpriteInfo('I_MEDKIT'), 18 | 215: SpriteInfo('I_BULLETVEST'), 19 | 216: SpriteInfo('I_ARMORVEST'), 20 | #217: SpriteInfo('I_ACCESSCARD'), 21 | 218: SpriteInfo('I_MINIGUN_AMMO'), 22 | 219: SpriteInfo('I_PLASMACROSSBOW_AMMO'), 23 | 220: SpriteInfo('I_PLASMACROSSBOW'), 24 | 221: SpriteInfo('I_MINIGUN'), 25 | 222: SpriteInfo('I_CLUSTERPUCK'), 26 | 223: SpriteInfo('I_TECHVEST'), 27 | 224: SpriteInfo('I_SHOTGUN'), 28 | 225: SpriteInfo('I_SHOTGUN_AMMO'), 29 | 226: SpriteInfo('I_GRENADELAUNCHER_AMMO'), 30 | 227: SpriteInfo('I_SMG_AMMO'), 31 | 228: SpriteInfo('I_ARMOR_SHARD'), 32 | 229: SpriteInfo('I_LOVERBOY_AMMO2'), 33 | 230: SpriteInfo('I_SMG'), 34 | 231: SpriteInfo('I_GRENADELAUNCHER'), 35 | 232: SpriteInfo('I_BOWLINGBOMB_PICKUP'), 36 | 233: SpriteInfo('I_SYRINGE'), 37 | 240: SpriteInfo('I_HAZARDSUIT'), 38 | 241: SpriteInfo('I_BOMBRUSH'), 39 | 242: SpriteInfo('I_RADAR'), 40 | 243: SpriteInfo('I_DKSHOES'), 41 | 244: SpriteInfo('I_DAMAGEBOOSTER'), 42 | 6800: SpriteInfo('I_BOWLINGBOMB'), 43 | 9930: SpriteInfo('I_PIZZA_6'), 44 | 9931: SpriteInfo('I_PIZZA_5'), 45 | 9932: SpriteInfo('I_PIZZA_4'), 46 | 9933: SpriteInfo('I_PIZZA_3'), 47 | 9934: SpriteInfo('I_PIZZA_2'), 48 | 9935: SpriteInfo('I_PIZZA_1'), 49 | 9003: SpriteInfo('I_SODA'), 50 | 9002: SpriteInfo('I_SODA_STAND'), 51 | 320: SpriteInfo('I_AMMOCRATE'), 52 | 53 | # Aftershock 54 | # define I_BANSHEE 16083 55 | # define I_COLLECTIBLE 17200 56 | 17201: SpriteInfo('I_WRECKER'), 57 | 17202: SpriteInfo('I_GRENADELAUNCHER_GAS'), 58 | 17203: SpriteInfo('I_SHOTGUN_CLUSTER'), 59 | 17204: SpriteInfo('I_GASGRENADE_AMMO'), 60 | 17205: SpriteInfo('I_CLUSTER_AMMO'), 61 | 17211: SpriteInfo('I_WRECKER_AMMO'), 62 | 17212: SpriteInfo('I_WRECKER_AMMO_SIXPACK'), 63 | 17206: SpriteInfo('I_BOOM_BAG'), 64 | 17207: SpriteInfo('I_INVULNERABILITY'), 65 | 17208: SpriteInfo('I_POCKET_PARASITE'), 66 | 17209: SpriteInfo('I_AGILITY_SURGE'), 67 | 17210: SpriteInfo('I_GOLDEN_GUN'), 68 | 17213: SpriteInfo('I_FLAMETRAP'), 69 | 17214: SpriteInfo('I_INFLATABLE_CHAIR'), 70 | }, 71 | swappableEnemies = { 72 | # 7259: SpriteInfo('A_TURRET_BOTTOM'), 73 | # 7260: SpriteInfo('A_TURRET'), 74 | # 7281: SpriteInfo('A_TURRETDEAD'), 75 | 7300: SpriteInfo('A_MECHSECT'), 76 | # 7301: SpriteInfo('A_MECHSECT_HANG'), 77 | # 7349: SpriteInfo('A_MECHSECT_DEAD1'), 78 | # 7356: SpriteInfo('A_MECHSECT_DEAD2'), 79 | 12096: SpriteInfo('A_CULTIST'), 80 | 12097: SpriteInfo('A_CULTIST_STAYPUT'), 81 | 12192: SpriteInfo('A_CULTIST_CROUCH'), 82 | # 12227: SpriteInfo('A_CULTIST_DEAD'), 83 | # 12255: SpriteInfo('A_CULTIST_DEADHEAD'), 84 | # 12249: SpriteInfo('A_CULTIST_GIBBED'), 85 | 12288: SpriteInfo('A_GREATER'), 86 | 12289: SpriteInfo('A_GREATER_STAYPUT'), 87 | 12384: SpriteInfo('A_GREATER_CROUCH'), 88 | # 12426: SpriteInfo('A_GREATER_DEAD1'), 89 | # 12437: SpriteInfo('A_GREATER_DEAD2'), 90 | # 12459: SpriteInfo('A_GREATER_GIBBED'), 91 | 11796: SpriteInfo('A_SHOTGUNNER'), 92 | 11797: SpriteInfo('A_SHOTGUNNER_STAYPUT'), 93 | 11892: SpriteInfo('A_SHOTGUNNER_CROUCH'), 94 | # 11927: SpriteInfo('A_SHOTGUNNER_DEAD'), 95 | # 11949: SpriteInfo('A_SHOTGUNNER_GIBBED'), 96 | # 11913: SpriteInfo('A_SHOTGUNNER_DEADHEAD'), 97 | 12925: SpriteInfo('A_BRUTE'), 98 | 12930: SpriteInfo('A_BRUTE_BOTTOM'), 99 | # 12923: SpriteInfo('A_BRUTE_BOTTOM_DEAD'), 100 | 12960: SpriteInfo('A_BRUTE_TOP'), 101 | # 13094: SpriteInfo('A_BRUTE_TOP_DEAD'), 102 | 11600: SpriteInfo('A_DRONE'), 103 | 11540: SpriteInfo('A_DIOPEDE_HEAD'), 104 | 11570: SpriteInfo('A_DIOPEDE_BUTT'), 105 | 11450: SpriteInfo('A_DEACON'), 106 | # 11512: SpriteInfo('A_DEACON_DEAD'), 107 | 13175: SpriteInfo('A_ARCHANGEL'), 108 | # 13301: SpriteInfo('A_ARCHANGEL_DEAD'), 109 | 13350: SpriteInfo('A_WENTEKO'), 110 | # 13498: SpriteInfo('A_WENTEKO_DEAD1'), 111 | # 13486: SpriteInfo('A_WENTEKO_DEAD2'), 112 | 13600: SpriteInfo('A_NUKEMUTANT'), 113 | 13685: SpriteInfo('A_NUKEMUTANT_RISE'), 114 | # 13707: SpriteInfo('A_NUKEMUTANT_DEAD'), 115 | # 13698: SpriteInfo('A_NUKEMUTANT_DEADHEAD'), 116 | # 13717: SpriteInfo('A_NUKEMUTANT_GIBBED'), 117 | 13720: SpriteInfo('A_NUKEMUTANT_GDF'), 118 | 13785: SpriteInfo('A_NUKEMUTANT_GDF_RISE'), 119 | # 13807: SpriteInfo('A_NUKEMUTANT_GDF_DEAD'), 120 | # 13830: SpriteInfo('A_NUKEMUTANT_GDF_GIBBED'), 121 | # 13837: SpriteInfo('A_NUKEMUTANT_GDF_DEADHEAD'), 122 | 11392: SpriteInfo('A_PSEUDO_ENEMY'), 123 | 13850: SpriteInfo('A_HESKEL_BOT'), 124 | 12496: SpriteInfo('A_MECHBOSS_BOTTOM'), 125 | 12488: SpriteInfo('A_MECHBOSS_TOP'), 126 | }, 127 | addableEnemies = [7300, 12096, 12288, 11796, 12925, 11600, 11450, 13175, 13350, 13600, 13685, 13720, 13785, 11392, 13850], 128 | triggers={} 129 | ) 130 | 131 | AddMapSettings('Ion Fury', **ion_fury_map_settings) 132 | AddMapSettings('Ion Fury Aftershock', **ion_fury_map_settings) 133 | 134 | ion_fury_game_settings = dict( 135 | mainScript='scripts/main.con', defName='fury.def', flags=128, 136 | commands = dict(# https://voidpoint.io/terminx/eduke32/-/blob/master/source/duke3d/src/cmdline.cpp#L39 137 | grp=OrderedDict(eduke32='-nosetup -g', fury='-nosetup -g'), 138 | folder=OrderedDict(eduke32='-nosetup -j '), 139 | simple={} 140 | ), 141 | conFiles = { 142 | 'scripts/customize.con': [ 143 | ConVar('.*\wHEALTH', -1, range=0.5), 144 | ConVar('MEDKIT_HEALTHAMOUNT', -1, range=0.5), 145 | ConVar('.*MAXAMMO', -1), 146 | ConVar('.*AMOUNT', -1), 147 | 148 | ConVar('.*_DMG', 0), # not sure if this affects enemies too or just the player? 149 | 150 | ConVar('.*_HEALTH', 1), 151 | ] 152 | } 153 | ) 154 | 155 | aftershock_game_settings = {**ion_fury_game_settings, 'defName':'ashock.def'} 156 | 157 | AddGameSettings('Ion Fury', **ion_fury_game_settings) 158 | AddGameSettings('Ion Fury Aftershock', **aftershock_game_settings) 159 | -------------------------------------------------------------------------------- /BuildLibs/grp.py: -------------------------------------------------------------------------------- 1 | from BuildLibs.grpbase import * 2 | from zipfile import ZipFile 3 | import binascii 4 | from mmap import mmap, ACCESS_READ 5 | 6 | def LoadGrpFile(filepath:Path) -> 'GrpBase': 7 | info(filepath) 8 | game:BuildGames.GameInfo = BuildGames.GetGame(filepath) 9 | filesize = os.path.getsize(filepath) 10 | with open(filepath, mode='rb') as f: 11 | sig = f.read(12) 12 | 13 | trace(sig) 14 | if sig[:4] == b'PK\x03\x04': 15 | debug('is a zip file') 16 | return GrpZipFile(filepath, filesize, game) 17 | elif sig[:12] == b'KenSilverman': 18 | debug('is a GRP file') 19 | return GrpFile(filepath, filesize, game) 20 | elif sig[:4] == b'RFF\x1a': 21 | debug('is an RFF file') 22 | return RffFile(filepath, filesize, game) 23 | else: 24 | raise Exception(filepath + ' is an unknown type, size: ', filesize, game) 25 | 26 | 27 | # https://moddingwiki.shikadi.net/wiki/GRP_Format 28 | class GrpFile(GrpBase): 29 | def GetFilesInfo(self) -> None: 30 | with open(self.filepath, 'rb') as f: 31 | f.seek(12) 32 | data = f.read(4) 33 | (numFiles,) = struct.unpack(' bytes: 48 | info = self.files.get(name) 49 | if not info: 50 | raise Exception('file not found in GRP', name, len(self.files)) 51 | 52 | if filehandle: 53 | filehandle.seek(info['offset']) 54 | return filehandle.read(info['size']) 55 | 56 | with open(self.filepath, 'rb') as f: 57 | f.seek(info['offset']) 58 | return f.read(info['size']) 59 | 60 | def getFileHandle(self): 61 | return open(self.filepath, 'rb') 62 | 63 | def GetGrpOutput(self, basepath: Path, num_files: int, seed: int, full: bool): 64 | p = Path(basepath, self.game.type + ' Randomizer.grp') 65 | extraname = str(seed) 66 | scriptname = None 67 | defName = None 68 | flags = 0 69 | if self.gameSettings: 70 | scriptname = self.gameSettings.mainScript 71 | defName = self.gameSettings.defName 72 | flags = self.gameSettings.flags 73 | depend = 0 if full else self.game.crc 74 | return GrpOutput(p, self.game.type, num_files, extraname, scriptname, defName, flags, depend) 75 | 76 | 77 | # idk what to call these, but Ion Fury uses one 78 | class GrpZipFile(GrpBase): 79 | def GetFilesInfo(self) -> None: 80 | with ZipFile(self.filepath, 'r') as zip: 81 | for f in zip.infolist(): 82 | self.files[f.filename] = { 'size': f.file_size } 83 | 84 | def _getfile(self, name, filehandle) -> bytes: 85 | if name not in self.files: 86 | raise Exception('file not found in GRP/ZIP', name, len(self.files)) 87 | 88 | if filehandle: 89 | with filehandle.open(name) as f: 90 | return f.read() 91 | 92 | with ZipFile(self.filepath, 'r') as zip: 93 | with zip.open(name) as file: 94 | return file.read() 95 | 96 | def getFileHandle(self): 97 | return ZipFile(self.filepath, 'r') 98 | 99 | def GetGrpOutput(self, basepath: Path, num_files: int, seed: int, full: bool): 100 | p = Path(basepath, self.game.type + ' Randomizer.grp') 101 | extraname = str(seed) 102 | scriptname = None 103 | defName = None 104 | flags = 0 105 | if self.gameSettings: 106 | scriptname = self.gameSettings.mainScript 107 | defName = self.gameSettings.defName 108 | flags = self.gameSettings.flags 109 | depend = 0 if full else self.game.crc 110 | return GrpZipOutput(p, self.game.type, num_files, extraname, scriptname, defName, flags, depend) 111 | 112 | 113 | # used by Blood https://github.com/Die4Ever/build-engine-randomizer/issues/21 114 | class RffFile(GrpBase): 115 | def GetFilesInfo(self) -> None: 116 | headerPack = FancyPacker('<', OrderedDict(sign='4s', version='h', pad1='h', offset='I', filenum='I')) 117 | directoryPack = FancyPacker('<', OrderedDict(unused1='16s', offset='I', size='I', unused2='8s', flags='B', type='3s', name='8s', id='i')) 118 | itemSize = 48 119 | 120 | with open(self.filepath, 'rb') as file: 121 | data = file.read(16) 122 | header = headerPack.unpack(data) 123 | trace(header) 124 | self.offset = header['offset'] 125 | self.fileNum = header['filenum'] 126 | file.seek(self.offset, os.SEEK_SET) 127 | data = bytearray(file.read(itemSize * self.fileNum)) 128 | 129 | self.version = header['version'] 130 | self.versionClass = header['version'] & 0xff00 131 | if self.versionClass == 0x200: 132 | self.crypt = 0 133 | elif self.versionClass == 0x300: 134 | self.crypt = 1 135 | else: 136 | raise NotImplementedError(self.filepath + ' ' + repr(header)) 137 | 138 | if self.crypt: 139 | data = RffCrypt(data, self.offset + (self.version & 0xff) * self.offset) 140 | 141 | for i in range(self.fileNum): 142 | d = directoryPack.unpack(data[i*itemSize:(i+1)*itemSize]) 143 | d['type'] = d['type'].decode() 144 | name = d['name'].decode().replace('\x00', '') 145 | filename = name + '.' + d['type'] 146 | d['name'] = filename 147 | del d['unused1'] 148 | del d['unused2'] 149 | self.files[filename] = d 150 | 151 | 152 | def _getfile(self, name, filehandle) -> bytes: 153 | info = self.files.get(name) 154 | if not info: 155 | raise Exception('file not found in RFF', name, len(self.files)) 156 | 157 | if filehandle: 158 | filehandle.seek(info['offset'], os.SEEK_SET) 159 | data = filehandle.read(info['size']) 160 | else: 161 | with open(self.filepath, 'rb') as f: 162 | f.seek(info['offset'], os.SEEK_SET) 163 | data = f.read(info['size']) 164 | 165 | DICT_CRYPT = 16 166 | if info['flags'] & DICT_CRYPT: 167 | data = bytearray(data) 168 | decryptSize = min(info['size'], 0x100) 169 | data[:decryptSize] = RffCrypt(data[:decryptSize], 0) 170 | return data 171 | 172 | 173 | def getFileHandle(self): 174 | return open(self.filepath, 'rb') 175 | 176 | def GetGrpOutput(self, basepath: Path, num_files: int, seed: int, full: bool): 177 | p = Path(basepath, self.game.type + ' Randomizer.rff') 178 | extraname = str(seed) 179 | scriptname = None 180 | defName = None 181 | flags = 0 182 | if self.gameSettings: 183 | scriptname = self.gameSettings.mainScript 184 | defName = self.gameSettings.defName 185 | flags = self.gameSettings.flags 186 | depend = 0 if full else self.game.crc 187 | return RffOutput(p, self.game.type, num_files, extraname, scriptname, defName, flags, depend) 188 | 189 | 190 | class GrpOutput(GrpOutputBase): 191 | def open(self): 192 | filepath = self.outpath 193 | filepath.parent.mkdir(parents=True, exist_ok=True) 194 | assert not filepath.exists() 195 | self.outfile = open(filepath, 'w+b') 196 | self.outfile.write(b'KenSilverman') 197 | self.outfile.write(struct.pack(' bytearray: 255 | for i in range(len(data)): 256 | data[i] = data[i] ^ ((key>>1) & 0xff) 257 | key += 1 258 | return data 259 | -------------------------------------------------------------------------------- /BuildLibs/buildmap.py: -------------------------------------------------------------------------------- 1 | import binascii 2 | import struct 3 | from typing import OrderedDict, Union 4 | from BuildLibs import crc32, error, info, swapobjkey, trace, warning, FancyPacker 5 | from BuildLibs.buildmapbase import CStat, Sector, Wall, Sprite, MapFileBase, MapCrypt 6 | 7 | 8 | class MapFile(MapFileBase): 9 | """ https://moddingwiki.shikadi.net/wiki/MAP_Format_(Build) """ 10 | HEADER_SIZE = 20 11 | SECTOR_SIZE = 40 12 | WALL_SIZE = 32 13 | SPRITE_SIZE = 44 14 | 15 | def CreateHeaderPacker(self): 16 | self.headerPacker = FancyPacker( 17 | '<', 18 | OrderedDict( 19 | version='i', 20 | startPos='iii', 21 | startAngle='h', 22 | startSect='h', 23 | ) 24 | ) 25 | 26 | def CreateSectorPacker(self): 27 | # keep AddSector up to date with this 28 | self.sectorPacker = FancyPacker( 29 | '<', 30 | OrderedDict( 31 | wallptr='h', 32 | wallnum='h', 33 | ceilingz='i', 34 | floorz='i', 35 | ceilingstat='h', 36 | floorstat='h', 37 | ceilingpicnum='h', 38 | ceilingheinum='h', 39 | ceilingshade='b', 40 | ceiling_palette='B', 41 | ceiling_texcoords='BB', 42 | floorpicnum='h', 43 | floorheinum='h', 44 | floorshade='b', 45 | floor_palette='B', 46 | floor_texcoords='BB', 47 | visibility='B', 48 | filler='B', 49 | lowtag='h', 50 | hightag='h', 51 | extra='h', 52 | ) 53 | ) 54 | 55 | def CreateWallPacker(self): 56 | # keep AddWall up to date with this 57 | self.wallPacker = FancyPacker( 58 | '<', 59 | OrderedDict( 60 | pos='ii', 61 | next_wall='h', 62 | next_sector_wall='h', 63 | next_sector='h', 64 | cstat='h', 65 | picnum='h', 66 | overpicnum='h', 67 | shade='b', 68 | palette='B', 69 | texcoords='BBBB', 70 | lowtag='h', 71 | hightag='h', 72 | extra='h', 73 | ) 74 | ) 75 | 76 | def CreateSpritePacker(self): 77 | # keep AddSprite up to date with this 78 | self.spritePacker = FancyPacker( 79 | '<', 80 | OrderedDict( 81 | pos='iii', 82 | cstat='h', 83 | picnum='h', 84 | shade='b', 85 | palette='B', 86 | clipdist='B', 87 | filler='B', 88 | texcoords='BBbb', 89 | sectnum='h', 90 | statnum='h', 91 | angle='h', 92 | owner='h', 93 | velocity='hhh', 94 | lowtag='h', 95 | hightag='h', 96 | extra='h', 97 | ) 98 | ) 99 | 100 | def ReadData(self): 101 | pos: int = self.ReadHeaders() 102 | if self.version < self.gameSettings.minMapVersion or self.version > self.gameSettings.maxMapVersion: 103 | warning('unexpected map version', self.version, self.name, self.gameSettings.minMapVersion, self.gameSettings.maxMapVersion) 104 | pos = self.ReadNumSectors(pos) 105 | pos = self.ReadSectors(pos) 106 | pos = self.ReadNumWalls(pos) 107 | pos = self.ReadWalls(pos) 108 | self.start_num_sprites = pos 109 | pos = self.ReadNumSprites(pos) 110 | self.ReadSprites(pos) 111 | 112 | def WriteData(self): 113 | pos: int 114 | if self.full_rewrite: 115 | self.data = bytearray() 116 | pos = self.WriteHeaders() 117 | pos = self.WriteNumSectors(pos) 118 | pos = self.WriteSectors(pos) 119 | pos = self.WriteNumWalls(pos) 120 | pos = self.WriteWalls(pos) 121 | else: 122 | pos = self.start_num_sprites 123 | self.data = self.data[:pos] 124 | pos = self.WriteNumSprites(pos) 125 | self.WriteSprites(pos) 126 | 127 | 128 | class MapV6(MapFile): 129 | """ https://moddingwiki.shikadi.net/wiki/MAP_Format_(Build)#Version_6 """ 130 | SECTOR_SIZE = 37 131 | SPRITE_SIZE = 43 132 | 133 | def CreateSectorPacker(self): 134 | # keep AddSector up to date with this 135 | self.sectorPacker = FancyPacker( 136 | '<', 137 | OrderedDict( 138 | wallptr='h', 139 | wallnum='h', 140 | ceilingpicnum='h', 141 | floorpicnum='h', 142 | ceilingheinum='h', 143 | floorheinum='h', 144 | ceilingz='i', 145 | floorz='i', 146 | ceilingshade='b', 147 | floorshade='b', 148 | ceilingxpanning='B', 149 | floorxpanning='B', 150 | ceilingypanning='B', 151 | floorypanning='B', 152 | ceilingstat='B', 153 | floorstat='B', 154 | ceiling_palette='B', 155 | floor_palette='B', 156 | visibility='B', 157 | lowtag='h', 158 | hightag='h', 159 | extra='h', 160 | ) 161 | ) 162 | 163 | def CreateWallPacker(self): 164 | # keep AddWall up to date with this 165 | self.wallPacker = FancyPacker( 166 | '<', 167 | OrderedDict( 168 | pos='ii', 169 | next_wall='h', 170 | next_sector='h', 171 | next_sector_wall='h', 172 | picnum='h', 173 | overpicnum='h', 174 | shade='b', 175 | palette='B', 176 | cstat='h', 177 | texcoords='BBBB', 178 | lowtag='h', 179 | hightag='h', 180 | extra='h', 181 | ) 182 | ) 183 | 184 | def CreateSpritePacker(self): 185 | # keep AddSprite up to date with this 186 | self.spritePacker = FancyPacker( 187 | '<', 188 | OrderedDict( 189 | pos='iii', 190 | cstat='h', 191 | shade='b', 192 | palette='B', 193 | clipdist='B', 194 | texcoords='BBbb', 195 | picnum='h', 196 | angle='h', 197 | velocity='hhh', 198 | owner='h', 199 | sectnum='h', 200 | statnum='h', 201 | lowtag='h', 202 | hightag='h', 203 | extra='h', 204 | ) 205 | ) 206 | 207 | 208 | class BloodMap(MapFile): 209 | """ https://github.com/nukeykt/NBlood/blob/master/source/blood/src/resource.cpp#L85 """ 210 | HEADER_SIZE = 43 211 | 212 | def CreateHeaderPacker(self): 213 | self.headerPacker = FancyPacker( 214 | '<', 215 | OrderedDict( 216 | sig='4s', 217 | version='h', 218 | startPos='iii', 219 | startAngle='h', 220 | startSect='h', 221 | pskybits='h', 222 | visibility='i', 223 | songid='i', 224 | parallaxtype='c', 225 | mapRevision='i', 226 | num_sectors='H', 227 | num_walls='H', 228 | num_sprites='H', 229 | ) 230 | ) 231 | self.header2Packer = FancyPacker('<', OrderedDict(x_sprite_size='i', x_wall_size='i', x_sector_size='i')) 232 | 233 | 234 | def ReadHeaders(self) -> int: 235 | super().ReadHeaders() 236 | 237 | if self.songid != 0 and self.songid != 0x7474614d and self.songid != 0x4d617474: 238 | header = self.data[:self.HEADER_SIZE] 239 | header[6:self.HEADER_SIZE] = MapCrypt(header[6:self.HEADER_SIZE], 0x7474614d) 240 | self.crypt = 1 241 | self.__dict__.update(self.headerPacker.unpack(header[:self.HEADER_SIZE])) 242 | 243 | self.exactVersion = self.version 244 | self.version = self.exactVersion >> 8 245 | 246 | if self.version == 7: # if (byte_1A76C8) 247 | self.header2Len = 128 248 | header2Start = self.HEADER_SIZE 249 | header2data = self.data[header2Start:header2Start + self.header2Len] 250 | self.header2data = header2data.copy() 251 | if self.crypt: 252 | header2data = MapCrypt(header2data, self.num_walls) 253 | 254 | header2 = self.header2Packer.unpack(header2data[64:76]) # skip the 64 bytes starting padding 255 | self.__dict__.update(header2) 256 | else: 257 | self.header2Len = 0 258 | self.x_sector_size = 60 259 | self.x_sprite_size = 56 260 | self.x_wall_size = 24 261 | 262 | self.hash = self.data[-4:] 263 | self.sky_start = self.HEADER_SIZE + self.header2Len 264 | self.sky_length = (1 << self.pskybits) * 2 265 | self.sky_data = self.data[self.sky_start:self.sky_start + self.sky_length] 266 | return self.sky_start + self.sky_length 267 | 268 | def WriteHeaders(self): 269 | # get the version ready for writing 270 | version = self.version 271 | self.version = self.exactVersion 272 | 273 | self.num_sprites = len(self.sprites) 274 | header = self.headerPacker.pack(self.__dict__) 275 | if self.crypt: 276 | header = bytearray(header) 277 | header[6:self.HEADER_SIZE] = MapCrypt(header[6:self.HEADER_SIZE], 0x7474614d) 278 | self.data.extend(header) 279 | if self.header2Len: 280 | self.data.extend(self.header2data) 281 | self.data.extend(self.sky_data) 282 | 283 | # put the version back to how we use it internally 284 | self.version = version 285 | return len(self.data) 286 | 287 | def ReadData(self): 288 | pos: int = self.ReadHeaders() 289 | pos = self.ReadSectors(pos) 290 | pos = self.ReadWalls(pos) 291 | self.start_sprites = pos 292 | self.ReadSprites(pos) 293 | 294 | def WriteData(self): 295 | old_data = self.data 296 | self.data = bytearray() 297 | pos:int = self.WriteHeaders() 298 | if self.full_rewrite: 299 | pos = self.WriteSectors(pos) 300 | pos = self.WriteWalls(pos) 301 | else: 302 | self.data.extend(old_data[pos:self.start_sprites]) 303 | pos = self.start_sprites 304 | self.WriteSprites(pos) 305 | 306 | def WriteSprites(self, pos): 307 | super().WriteSprites(pos) 308 | crc: int = binascii.crc32(self.data) 309 | self.hash = struct.pack(' 'MapFile': 314 | # Blood has a signature at the front of map files 315 | if data[:4] == b'BLM\x1a': 316 | return BloodMap(gameName, name, data) 317 | else: 318 | (version,) = struct.unpack(' bool: 125 | outputMethod = settings['outputMethod'] 126 | deleting = self.grp.GetDeletes(None, outputMethod) 127 | deletingstrs = [] 128 | d : Path 129 | maps = {} 130 | for d in deleting: 131 | s = str(d.absolute()) 132 | if s.lower().endswith('.map'): 133 | key = str(Path(d.absolute().parent, '*.map')) 134 | maps[key] = maps.get(key, 0) + 1 135 | else: 136 | deletingstrs.append(s) 137 | for (k,v) in maps.items(): 138 | deletingstrs.append(k + ' (' + str(v) + ' map files)') 139 | 140 | return messagebox.askokcancel( 141 | title='Will DELETE files!', 142 | message='This may take a minute.\nWILL DELETE/OVERWRITE THE FOLLOWING:\n\n' 143 | + '\n\n'.join(deletingstrs) 144 | ) 145 | 146 | def Randomize(self): 147 | try: 148 | self.randoButton["state"]='disabled' 149 | self.update() 150 | settings = self.ReadSettings() 151 | 152 | if not self.WarnOverwrites(settings): 153 | info('Declined overwrite warning, not randomizing') 154 | if self.isWindowOpen(): 155 | self.randoButton["state"]='normal' 156 | return 157 | 158 | self._Randomize(settings) 159 | except Exception as e: 160 | errordialog('Error Randomizing', self.grppath, e) 161 | if self.isWindowOpen(): 162 | self.randoButton["state"]='normal' 163 | raise 164 | 165 | 166 | def initWindow(self): 167 | self.root = Tk() 168 | self.root.protocol("WM_DELETE_WINDOW",self.closeWindow) 169 | self.root.bind("",self.resize) 170 | self.root.title('Build Engine Randomizer ' + GetVersion()+' Settings') 171 | self.root.geometry(str(self.width)+"x"+str(self.height)) 172 | 173 | scroll = ScrollableFrame(self.root, width=self.width, height=self.height, mousescroll=1) 174 | self.win = scroll.frame 175 | #self.win.config() 176 | self.font = font.Font(size=14) 177 | self.linkfont = font.Font(size=12, underline=True) 178 | 179 | row=0 180 | infoLabel = Label(self.win, 181 | text='Make sure you have a backup of your game files!\nRandomizer might overwrite files\ninside the game directory.', 182 | width=40,height=4,font=self.font 183 | ) 184 | infoLabel.grid(column=0,row=row,columnspan=2,rowspan=1) 185 | row+=1 186 | 187 | self.seedVar = StringVar(self.win, random.randint(1, 999999)) 188 | self.seedEntry:Entry = self.newInput(Entry, 'Seed: ', 189 | 'RNG Seed. Each seed is a different game!\nLeave blank for a random seed.', 190 | row, textvariable=self.seedVar 191 | ) 192 | row+=1 193 | 194 | # items add/reduce? maybe combine them into presets so it's simpler to understand 195 | self.itemsVar = StringVar(self.win, 'Some') 196 | items:OptionMenu = self.newInput(OptionMenu, 'Items: ', 'How many items.\n"Some" is a similar amount to vanilla.', 197 | row, self.itemsVar, *OptionsList(chanceDupeItem) 198 | ) 199 | row+=1 200 | 201 | # enemies add/reduce? 202 | self.enemiesVar = StringVar(self.win, 'Some') 203 | enemies:OptionMenu = self.newInput(OptionMenu, 'Enemies: ', 'How many enemies.\n"Some" is a similar amount to vanilla.', 204 | row, self.enemiesVar, *OptionsList(chanceDupeEnemy) 205 | ) 206 | row+=1 207 | 208 | # values range 209 | self.rangeVar = StringVar(self.win, 'Medium') 210 | self.range:OptionMenu = self.newInput(OptionMenu, 'Randomization Range: ', 211 | 'How wide the range of values can be randomized.\nThis affects the values in CON files such as health and damage values.', 212 | row, self.rangeVar, *OptionsList(rangeOptions) 213 | ) 214 | row+=1 215 | 216 | # difficulty? values difficulty? 217 | self.difficultyVar = StringVar(self.win, 'Medium') 218 | self.difficulty:OptionMenu = self.newInput(OptionMenu, 'Difficulty: ', 219 | 'Increase the difficulty for more challenge.\nThis affects the values in CON files such as health and damage values.', 220 | row, self.difficultyVar, *OptionsList(difficultyOptions) 221 | ) 222 | row+=1 223 | 224 | self.itemVarietyVar = StringVar(self.win, 'Increased') 225 | self.itemVariety:OptionMenu = self.newInput(OptionMenu, 'Item Variety: ', 226 | 'Chance to add items that shouldn\'t be on the map.', 227 | row, self.itemVarietyVar, *OptionsList(spriteVariety) 228 | ) 229 | row+=1 230 | 231 | self.enemyVarietyVar = StringVar(self.win, 'Increased') 232 | self.enemyVariety:OptionMenu = self.newInput(OptionMenu, 'Enemy Variety: ', 233 | 'Chance to add enemies that shouldn\'t be on the map.\nThis can create difficult situations.', 234 | row, self.enemyVarietyVar, *OptionsList(spriteVariety) 235 | ) 236 | row+=1 237 | 238 | self.reorderMapsVar = StringVar(self.win, 'Disabled') 239 | reorderMaps:OptionMenu = self.newInput(OptionMenu, 'Reorder Maps: ', 240 | 'Shuffle the order of the maps.', 241 | row, self.reorderMapsVar, *OptionsList(reorderMapsOptions) 242 | ) 243 | row+=1 244 | 245 | # TODO: option to enable/disable loading external files? 246 | 247 | self.outputMethodVar = StringVar(self.win, 'GRP File') 248 | self.randomizerFolder:OptionMenu = self.newInput(OptionMenu, 'Output Method: ', 249 | 'Usually just use the default setting. See the wiki on GitHub for more info.', 250 | row, self.outputMethodVar, *OptionsList(outputMethodOptions) 251 | ) 252 | row+=1 253 | 254 | #self.progressbar = Progressbar(self.win, maximum=1) 255 | #self.progressbar.grid(column=0,row=row,columnspan=2) 256 | #row+=1 257 | 258 | link = Label(self.win,text='Mods4Ever.com',width=22,height=2,font=self.linkfont, fg="Blue", cursor="hand2") 259 | link.bind('', lambda *args: webbrowser.open_new('https://Mods4Ever.com')) 260 | link.grid(column=0,row=100) 261 | myTip = Hovertip(link, 'Check out our website and join our Discord!') 262 | 263 | self.randoButton = Button(self.win,text='Randomize!',width=18,height=2,font=self.font, command=self.Randomize) 264 | self.randoButton.grid(column=1,row=100, sticky='SE') 265 | Hovertip(self.randoButton, 'Dew it!') 266 | 267 | self.ChooseFile() 268 | 269 | def update(self): 270 | self.root.update() 271 | 272 | def main(): 273 | settings = RandoSettings() 274 | 275 | def chooseFile(root): 276 | filetype = (("All Supported Files",("*.grp","STUFF.DAT",'*.rff')), ("GRP Files","*.grp"), ('RFF Files','*.rff'), ('DAT Files', '*.DAT'), ("All Files","*.*")) 277 | target = filedialog.askopenfilename(title="Choose a GRP file",filetypes=filetype) 278 | return target 279 | -------------------------------------------------------------------------------- /BuildGames/Duke3d.py: -------------------------------------------------------------------------------- 1 | from BuildGames import * 2 | 3 | #AddGame('DUKE.RTS v0.99', 'Duke Nukem 3D', 175567, '6148685E', '7ECAF2753AA9CC924F746B3D0F36E7C2', 'A9356036AEA01583C85B71410F066285AFE3AF2B', canUseGrpFile=True) # DUKE.RTS v0.99 4 | AddGame('Shareware DUKE3D.GRP v0.99', 'Duke Nukem 3D', 9690241, '02F18900', '56B35E575EBA7F16C0E19628BD6BD934', 'A6341C16BC1170B43BE7F28B5A91C080F9CE3409', canUseGrpFile=True) # Shareware DUKE3D.GRP v0.99 5 | AddGame('Shareware DUKE3D.GRP v1.0', 'Duke Nukem 3D', 10429258, 'A28AA589', '1E57CF6272E8BE0E746666700CC0EE96', '7D2FDF1E9F1BBCE327650B3AECDAF78E6BBD6211', canUseGrpFile=True) # Shareware DUKE3D.GRP v1.0 6 | AddGame('Shareware DUKE3D.GRP v1.1', 'Duke Nukem 3D', 10442980, '912E1E8D', '9B0683A74C8BF36BF85631616385BEC8', '5166D6E4DBBA2B8ABB2FDA48257F0FCBDBF17626', canUseGrpFile=True) # Shareware DUKE3D.GRP v1.1 7 | AddGame('Shareware DUKE3D.GRP v1.3D', 'Duke Nukem 3D', 11035779, '983AD923', 'C03558E3A78D1C5356DC69B6134C5B55', 'A58BDBFAF28416528A0D9A4452F896F46774A806', canUseGrpFile=True) # Shareware DUKE3D.GRP v1.3D 8 | AddGame('Shareware DUKE3D.GRP v1.5 Mac', 'Duke Nukem 3D', 10444391, 'C5F71561', 'B9CAC374477E09459A313CEA457971EA', 'F035E9F0615E3DB23D2DB4C90232D8A95B5B9585', canUseGrpFile=True) # Shareware DUKE3D.GRP v1.5 Mac 9 | 10 | AddGame('DUKE3D.GRP v1.3D', 'Duke Nukem 3D', 26524524, 'BBC9CE44', '981125CB9237C19AA0237109958D2B50', '3D508EAF3360605B0204301C259BD898717CF468', canUseGrpFile=True) # DUKE3D.GRP v1.3D 11 | #AddGame('DUKE.RTS v1.0/1.1/1.3D/1.4/1.5', 'Duke Nukem 3D', 188954, '504086C1', '9D29F9673BBDB56068ACF7645C13749C', '738C7F5FD0C8B57EE2E87AE7A97BF8E21A821D07', canUseGrpFile=True) # DUKE.RTS v1.0/1.1/1.3D/1.4/1.5 12 | AddGame('DUKE3D.GRP v1.4 (Plutonium Pak)', 'Duke Nukem 3D', 44348015, 'F514A6AC', 'C904FFB6A4F3C6080DD1DAC31218B25A', '61E70F883DF9552395406BF3D64F887F3C709438', canUseGrpFile=True) # DUKE3D.GRP v1.4 (Plutonium Pak) 13 | AddGame('DUKE3D.GRP v1.5 (Atomic Edition)', 'Duke Nukem 3D', 44356548, 'FD3DCFF1', '22B6938FE767E5CC57D1FE13080CD522', '4FDEF8559E2D35B1727FE92F021DF9C148CF696C', canUseGrpFile=True) # DUKE3D.GRP v1.5 (Atomic Edition) 14 | 15 | AddGame('Duke Nukem 3D: Atomic Edition (WT)', 'Duke Nukem 3D', 44356548, '982AFE4A', externalFiles=True) # DUKEWT_CRC 16 | AddGame('Duke Nukem 3D: World Tour', 'Duke Nukem 3D', 37, '5BD05463', '756a398d7d684f55785005833b4dd67c', '7a9afeb6bb1ad7dd097487cad3c8775debddc730', externalFiles=True) # DUKE3D.GRP v1.5 (Atomic Edition) 17 | 18 | AddGame('Duke Nukem 3D (South Korean Censored)', 'Duke Nukem 3D', 26385383, 'AA4F6A40', canUseGrpFile=True) # DUKEKR_CRC 19 | AddGame('Duke Nukem 3D MacUser Demo', 'Duke Nukem 3D', 10628573, '73A15EE7', canUseGrpFile=True) # DUKEMD2_CRC 20 | 21 | AddGame('Duke it out in D.C.', 'Duke it out in D.C.', 8410187, '39A692BF') # { "Duke it out in D.C.", (int32_t) 0x39A692BF, 8410187, GAMEFLAG_DUKE|GAMEFLAG_ADDON, DUKE15_CRC, "DUKEDC.CON", NULL} 22 | AddGame('Duke Caribbean: Life\'s a Beach', 'Duke Caribbean: Life\'s a Beach', 22397273, '65B5F690') # { "Duke Caribbean: Life's a Beach", (int32_t) 0x65B5F690, 22397273, GAMEFLAG_DUKE|GAMEFLAG_ADDON, DUKE15_CRC, "VACATION.CON", NULL} 23 | AddGame('Duke: Nuclear Winter Demo', 'Duke: Nuclear Winter', 10965909, 'C7EFBFA9') # { "Duke: Nuclear Winter Demo", (int32_t) 0xC7EFBFA9, 10965909, GAMEFLAG_DUKE|GAMEFLAG_ADDON, DUKE15_CRC, "NWINTER.CON", NULL} 24 | AddGame('Duke!ZONE II', 'Duke!ZONE II', 3186656, '1E9516F1') # { "Duke!ZONE II", (int32_t) 0x1E9516F1, 3186656, GAMEFLAG_DUKE|GAMEFLAG_ADDON, DUKE15_CRC, "DZ-GAME.CON", NULL} 25 | AddGame('Duke Nukem\'s Penthouse Paradise', 'Duke Nukem\'s Penthouse Paradise', 2112419, '7CD82A3B') # { "Duke Nukem's Penthouse Paradise", (int32_t) 0x7CD82A3B, 2112419, GAMEFLAG_DUKE|GAMEFLAG_ADDON, DUKE15_CRC, "ppakgame.con", NULL}, // original .zip release 26 | AddGame('Duke Nukem\'s Penthouse Paradise', 'Duke Nukem\'s Penthouse Paradise', 4247491, 'CF928A58') # { "Duke Nukem's Penthouse Paradise", (int32_t) 0xCF928A58, 4247491, GAMEFLAG_DUKE|GAMEFLAG_ADDON, DUKE15_CRC, "PPAKGAME.CON", NULL}, // ZOOM Platform repacked .grp 27 | 28 | AddGame('DUKE!ZON.GRP v1.3D', 'Duke!ZONE II', 26135388, '82C1B47F', 'C960FE3CC6920369EB43A8B00AC4E4EE', '169E9E2BEAB2E9FF6E0660FA3CE93C85B4B56884') # DUKE!ZON.GRP v1.3D 29 | #AddGame('DZ-GAME.CON v1.3D', 'Duke!ZONE II', 99967, 'F3DCF89D', '65C72C2550049D7456D5F983E0051E7B', '8D05E4646DFBD201877036F5379534D06E6A6DDC') # DZ-GAME.CON v1.3D 30 | #AddGame('DZ-DEFS.CON v1.3D', 'Duke!ZONE II', 28959, 'F2FE1424', '45DDEB920FF7AF450CD6A19CDFF6EE7E', '7BA88D2B12F5F193DA96822E59E5B7EE9DABFD5C') # DZ-DEFS.CON v1.3D 31 | #AddGame('DZ-USER.CON v1.3D', 'Duke!ZONE II', 36237, '93401EA4', 'A81793173C384F025768ED853A060F3A', '1E37C7EB9EAB03C938B18B3712DAEF97BA9B9B13') # DZ-USER.CON v1.3D 32 | AddGame('DUKE!ZON.GRP v1.4', 'Duke!ZONE II', 44100411, '7FB6117C', '031C271C689DD76F9E40241B10B8EBA9', '86A58754A2F2D95271B389FA2B8FAC9AA34CCFCE') # DUKE!ZON.GRP v1.4 33 | #AddGame('DZ-GAME.CON v1.4', 'Duke!ZONE II', 151198, '5C0E6CC7', '8EF020D2F63C0EE1CC391F00FEEE895D', 'D6DC4C24EC5986C7AC8FB3F4DA85D97E06D72F2E') # DZ-GAME.CON v1.4 34 | #AddGame('DZ-DEFS.CON v1.4', 'Duke!ZONE II', 36038, '85847E24', '8C7A4622A71F580B57954CA129B0474B', 'D23A2E9CC0FF30B02911AC9D7EC49D55CE856EE0') # DZ-DEFS.CON v1.4 35 | #AddGame('DZ-USER.CON v1.4', 'Duke!ZONE II', 45037, '739BE376', '1862C4CD17B6C95942B75F72CEAC7AEA', '31E39D7BB9E7E77E468CC67684F41AA58238179A') # DZ-USER.CON v1.4 36 | 37 | AddGame('DUKEDC13.SSI v1.3D', 'Duke it out in D.C.', 7926624, 'A9242158', 'D085D538A6BF40EBB041D964787A5D20', '66A96327EC514710D3526D87259CF5C0ABBBB841') # DUKEDC13.SSI v1.3D 38 | AddGame('DUKEDCPP.SSI v1.4', 'Duke it out in D.C.', 8225517, 'B79D997F', 'F0BFA5B956C8E3DBCBA1042118C1F456', '30D6AA2A44E936D09D6B423CFAB7C0595E2376F9') # DUKEDCPP.SSI v1.4 39 | AddGame('DUKEDC.GRP (Atomic Edition)', 'Duke it out in D.C.', 8410183, 'A8CF80DA', '8AB2E7328DB4153E4158C850DE82D7C0', '1B66C3AD9A65556044946DD1CA97A839FCFEDC3B') # DUKEDC.GRP (Atomic Edition) 40 | AddGame('NWINTER.GRP', 'Duke: Nuclear Winter', 16169365, 'F1CAE8E4', '1250F83DCC3588293F0CE5C6FC701B43', 'A6728F621F121F9DB02EE67C39EFDBB5EEA95711') # NWINTER.GRP 41 | 42 | AddGame('VACA13.SSI v1.3D', 'Duke Caribbean: Life\'s a Beach', 23559381, '4A2DBB62', '974616FC968D188C984E4F9A60F3C4BE', '2B7779AB211FB21CD2D7DEF93E2B9BBF948E406F') # VACA13.SSI v1.3D 43 | AddGame('VACAPP.SSI v1.4', 'Duke Caribbean: Life\'s a Beach', 22551333, '2F4FCCEE', '540AFD010435450D73FA3463437FCFC9', '58FD872BE376957D63D9F5C3BD169D5FCDF28664') # VACAPP.SSI v1.4 44 | AddGame('VACA15.SSI v1.5', 'Duke Caribbean: Life\'s a Beach', 22521880, 'B62B42FD', '22C8CD6235FC2B7ECEFEFC2442570D68', '84945D64E246E91840A872F332494D8509B66DD9') # VACA15.SSI v1.5 45 | AddGame('VACATION.GRP (Atomic Edition)', 'Duke Caribbean: Life\'s a Beach', 22213819, '18F01C5B', '1C105CED73B776C172593764E9D0D93E', '65B8B787616ED637F86CFCAA90DE24C8E65B3DCC') # VACATION.GRP (Atomic Edition) 46 | 47 | AddMapSettings('Duke Nukem 3D', minMapVersion=7, maxMapVersion=9, 48 | swappableItems = { 49 | 21: SpriteInfo('FIRSTGUNSPRITE'), 50 | 22: SpriteInfo('CHAINGUNSPRITE'), 51 | 23: SpriteInfo('RPGSPRITE'), 52 | 24: SpriteInfo('FREEZESPRITE'), 53 | 25: SpriteInfo('SHRINKERSPRITE'), 54 | 26: SpriteInfo('HEAVYHBOMB'), 55 | 27: SpriteInfo('TRIPBOMBSPRITE'), 56 | 28: SpriteInfo('SHOTGUNSPRITE'), 57 | 29: SpriteInfo('DEVISTATORSPRITE'), 58 | #30: SpriteInfo('HEALTHBOX'), 59 | #31: SpriteInfo('AMMOBOX'), 60 | 37: SpriteInfo('FREEZEAMMO'), 61 | 40: SpriteInfo('AMMO'), 62 | 41: SpriteInfo('BATTERYAMMO'), 63 | 42: SpriteInfo('DEVISTATORAMMO'), 64 | 44: SpriteInfo('RPGAMMO'), 65 | 45: SpriteInfo('GROWAMMO'), 66 | 46: SpriteInfo('CRYSTALAMMO'), 67 | 47: SpriteInfo('HBOMBAMMO'), 68 | #48: SpriteInfo('AMMOLOTS'), 69 | 49: SpriteInfo('SHOTGUNAMMO'), 70 | 51: SpriteInfo('COLA'), 71 | 52: SpriteInfo('SIXPAK'), 72 | 53: SpriteInfo('FIRSTAID'), 73 | 54: SpriteInfo('SHIELD'), 74 | 55: SpriteInfo('STEROIDS'), 75 | 56: SpriteInfo('AIRTANK'), 76 | 57: SpriteInfo('JETPACK'), 77 | 59: SpriteInfo('HEATSENSOR'), 78 | # 60: SpriteInfo('ACCESSCARD'), 79 | 61: SpriteInfo('BOOTS'), 80 | 100: SpriteInfo('ATOMICHEALTH'), 81 | #142: SpriteInfo('NUKEBUTTON'), 82 | 1348: SpriteInfo('HOLODUKE'), 83 | }, 84 | swappableEnemies = { 85 | 675: SpriteInfo('EGG'), 86 | #1550: SpriteInfo('SHARK'), 87 | 1680: SpriteInfo('LIZTROOP'), 88 | 1681: SpriteInfo('LIZTROOPRUNNING'), 89 | 1682: SpriteInfo('LIZTROOPSTAYPUT'), 90 | 1705: SpriteInfo('LIZTOP'), 91 | 1715: SpriteInfo('LIZTROOPSHOOT'), 92 | 1725: SpriteInfo('LIZTROOPJETPACK'), 93 | #1734: SpriteInfo('LIZTROOPDSPRITE'), 94 | 1741: SpriteInfo('LIZTROOPONTOILET'), 95 | 1742: SpriteInfo('LIZTROOPJUSTSIT'), 96 | 1744: SpriteInfo('LIZTROOPDUCKING'), 97 | 1820: SpriteInfo('OCTABRAIN'), 98 | 1821: SpriteInfo('OCTABRAINSTAYPUT'), 99 | 1845: SpriteInfo('OCTATOP'), 100 | 1880: SpriteInfo('DRONE'), 101 | 1920: SpriteInfo('COMMANDER'), 102 | 1921: SpriteInfo('COMMANDERSTAYPUT'), 103 | 1960: SpriteInfo('RECON'), 104 | 1975: SpriteInfo('TANK'), 105 | 2000: SpriteInfo('PIGCOP'), 106 | 2001: SpriteInfo('PIGCOPSTAYPUT'), 107 | 2045: SpriteInfo('PIGCOPDIVE'), 108 | #2060: SpriteInfo('PIGCOPDEADSPRITE'), 109 | 2061: SpriteInfo('PIGTOP'), 110 | 2120: SpriteInfo('LIZMAN'), 111 | 2121: SpriteInfo('LIZMANSTAYPUT'), 112 | 2150: SpriteInfo('LIZMANSPITTING'), 113 | 2160: SpriteInfo('LIZMANFEEDING'), 114 | 2165: SpriteInfo('LIZMANJUMP'), 115 | #2219: SpriteInfo('EXPLOSION2BOT'), 116 | 2370: SpriteInfo('GREENSLIME'), 117 | 2371: SpriteInfo('GREENSLIME2'), 118 | # 2630: SpriteInfo('BOSS1'), 119 | # 2631: SpriteInfo('BOSS1STAYPUT'), 120 | # 2660: SpriteInfo('BOSS1SHOOT'), 121 | # 2670: SpriteInfo('BOSS1LOB'), 122 | # 2696: SpriteInfo('BOSSTOP'), 123 | # 2710: SpriteInfo('BOSS2'), 124 | # 2760: SpriteInfo('BOSS3'), 125 | 4610: SpriteInfo('NEWBEAST'), 126 | 4611: SpriteInfo('NEWBEASTSTAYPUT'), 127 | 4690: SpriteInfo('NEWBEASTJUMP'), 128 | 4670: SpriteInfo('NEWBEASTHANG'), 129 | 4671: SpriteInfo('NEWBEASTHANGDEAD'), 130 | # 4740: SpriteInfo('BOSS4'), 131 | # 4741: SpriteInfo('BOSS4STAYPUT'), 132 | }, 133 | addableEnemies = [675, 1680, 1820, 1880, 1920, 1960, 1975, 2000, 2120, 2370, 4610,], 134 | triggers = { 135 | # 675 EGG doesn't work for spawning? 136 | 9: dict(name='RESPAWN', hightags=[1680, 1820, 1960, 2000, 2120, 2370], lowtags=[], not_hightags=[2630, 2631, 2660, 2670, 2696, 2710, 2760, 4740, 4741]), 137 | }, 138 | additions = { 139 | # lower case because python doesn't have case-insensitive dicts, maybe I should create these with a function 140 | 'e1l2.map': [ 141 | dict(pos=[-658, 37872, -12166], sectnum=214, choices=[57]), 142 | ], 143 | 'e1l3.map': [ # ensure the player gets weapons to start with 144 | dict(pos=[24160, 52032, 45056], sectnum=296, choices=[21,22,23,24,25,26,27,28,29]), # under the chair 145 | dict(pos=[28096, 50688, 22528], sectnum=297, choices=[21,22,23,24,25,26,27,28,29]), # in the locker 146 | dict(pos=[47864, 29653, 20480], sectnum=265, choices=[23,47]), # explosives near the end of the map 147 | dict(pos=[47270, 25876, 34370], sectnum=272, texcoords=[8, 8, 0, 0], choices=[26]), # single pipe bomb near the end of the map 148 | ] 149 | }, 150 | reorderMapsBlacklist = [ 'E1L7.MAP', 'E1L8.MAP', 'E3L10.MAP' ] 151 | ) 152 | 153 | AddGameSettings('Duke Nukem 3D', mainScript='GAME.CON', flags=0, 154 | commands = dict( # https://voidpoint.io/terminx/eduke32/-/blob/master/source/duke3d/src/cmdline.cpp#L39 155 | grp={'eduke32': '-nosetup -g'}, 156 | folder={'eduke32': '-nosetup -j '}, 157 | simple={} 158 | ), 159 | conFiles = { 160 | 'USER.CON': [ 161 | # more specific things first 162 | ConVar('STEROID_AMOUNT', 0, range=0), # STEROID_AMOUNT less than 400 causes it to be used immediately, greater than 400 causes it to be unusable 163 | ConVar('BOSS.*STRENGTH', 1, range=0.5, balance=0.9), # prevent bosses from being crazy strong 164 | ConVar('TRIPBOMB_STRENGTH', -1, balance=1.5), 165 | ConVar('HANDBOMB_WEAPON_STRENGTH', -1, balance=1.5), 166 | ConVar('YELLHURTSOUNDSTRENGTH', 0, range=0), 167 | ConVar('SWEARFREQUENCY', 0), 168 | ConVar('PIG_SHIELD_AMOUNT\d', 1), 169 | 170 | ConVar('.*HEALTH', -1, range=0.5), 171 | ConVar('MAX.*AMMO', -1), 172 | ConVar('.*AMMOAMOUNT', -1), 173 | ConVar('.*_AMOUNT', -1), 174 | ConVar('HANDBOMBBOX', -1), 175 | ConVar('.*_WEAPON_STRENGTH', -1), 176 | 177 | ConVar('.*\wSTRENGTH', 1), 178 | 179 | # idk what these do 180 | ConVar('OCTASCRATCHINGPLAYER', 0), 181 | ConVar('LIZGETTINGDAZEDAT', 0), 182 | ConVar('LIZEATINGPLAYER', 0), 183 | ConVar('NEWBEASTSCRATCHAMOUNT', 0), 184 | ] 185 | }) 186 | -------------------------------------------------------------------------------- /BuildLibs/grpbase.py: -------------------------------------------------------------------------------- 1 | import abc 2 | import glob 3 | import locale 4 | import os 5 | import random 6 | import re 7 | import shutil 8 | import traceback 9 | import ctypes 10 | from datetime import datetime 11 | from pathlib import Path 12 | from typing import List, OrderedDict, Callable, Optional 13 | 14 | from BuildLibs import debug, error, info, trace, warning 15 | from BuildLibs.buildmap import * 16 | from BuildLibs.confile import ConFile 17 | from BuildLibs.SpoilerLog import SpoilerLog 18 | import BuildGames 19 | 20 | 21 | try: 22 | locale.setlocale(locale.LC_ALL, '') 23 | except Exception as e: 24 | error('Failed to set locale', e, '\n', traceback.format_exc()) 25 | 26 | 27 | # game's main resource file, either GRP, ZIP, or RFF 28 | class GrpBase(metaclass=abc.ABCMeta): 29 | @abc.abstractmethod 30 | def GetFilesInfo(self) -> None: 31 | return 32 | 33 | @abc.abstractmethod 34 | def getFileHandle(self): 35 | return 36 | 37 | @abc.abstractmethod 38 | def _getfile(self, name, filehandle) -> bytes: 39 | return 40 | 41 | def __init__(self, filepath:Path, filesize, game): 42 | self.filepath = filepath 43 | info(filepath) 44 | self.files = {} 45 | self.game:BuildGames.GameInfo = game 46 | self.filesize = filesize 47 | self.deletes = None 48 | self.spoilerlogpath = None 49 | self.batpath = None 50 | 51 | self.GetFilesInfo() 52 | self.GetExternalFiles() 53 | cons = self.GetAllFilesEndsWith('.con') 54 | if not self.game.type: 55 | info(repr(cons)) 56 | raise Exception('unidentified game') 57 | 58 | self.gameSettings = BuildGames.GetGameSettings(self.game) 59 | if not self.gameSettings: 60 | raise Exception('missing GameSettings', self.game, filepath) 61 | elif not self.gameSettings.conFiles: 62 | warning("This game is missing CON file randomization", self.game, filepath) 63 | for con in cons: 64 | warning(con) 65 | # self.ExtractFile('temp/', con) 66 | else: 67 | for con in self.gameSettings.conFiles: 68 | if con not in cons: 69 | warning('file not found', con) 70 | 71 | self.mapSettings = BuildGames.GetGameMapSettings(self.game) 72 | if not self.mapSettings.swappableItems: 73 | warning("This game doesn't have any swappableItems", self.game, filepath) 74 | if not self.mapSettings.swappableEnemies: 75 | warning("This game doesn't have any swappableEnemies", self.game, filepath) 76 | 77 | def GetExternalFiles(self): 78 | if not self.game.externalFiles: 79 | return 80 | gamedir = os.path.dirname(self.filepath) 81 | searchdir = Path(gamedir, '**') 82 | trace(searchdir) 83 | files = glob.glob(str(searchdir), recursive=True) 84 | trace(files) 85 | for f in files: 86 | p = Path(f) 87 | rel = p.relative_to(gamedir) 88 | if 'backup' in f.lower(): # TODO: maybe move old files to backup instead of deleting? but then have to delete the previous files in backup? 89 | continue 90 | if 'addons' in f.lower(): # TODO: support addons 91 | continue 92 | if 'Randomizer' in rel.parts: 93 | continue 94 | if not p.is_file(): 95 | continue 96 | 97 | f = str(rel) 98 | self.files[f] = { 99 | 'location': p, 100 | #'parts': p.parts 101 | } 102 | 103 | def GetAllFilesEndsWith(self, postfix) -> list: 104 | matches = [] 105 | postfix = postfix.lower() 106 | for f in self.files.keys(): 107 | if f.lower().endswith(postfix): 108 | matches.append(f) 109 | matches.sort() 110 | return matches 111 | 112 | def getfile(self, name, filehandle=None) -> bytes: 113 | overridepath = self.files[name].get('location') 114 | if overridepath: 115 | with open(overridepath, 'rb') as file: 116 | return file.read() 117 | return self._getfile(name, filehandle) 118 | 119 | def getmap(self, name, file) -> MapFile: 120 | data = bytearray(self.getfile(name, file)) 121 | return LoadMap(self.game, name, data) 122 | 123 | def GetOutputPath(self, basepath:Path, outputMethod) -> Path: 124 | gamedir = os.path.dirname(self.filepath) 125 | if not basepath: 126 | basepath = gamedir 127 | if outputMethod=='folder': 128 | basepath = Path(basepath, 'Randomizer') 129 | return Path(basepath) 130 | 131 | def GetDeletes(self, basepath:Path, outputMethod) -> List[Path]: 132 | if self.deletes: 133 | return self.deletes 134 | 135 | outpath:Path = self.GetOutputPath(basepath, outputMethod) 136 | maybedeletes = self._GetDeletes(outpath, outputMethod) 137 | self.deletes = [] 138 | for f in maybedeletes: 139 | if f.exists(): 140 | self.deletes.append(f) 141 | return self.deletes 142 | 143 | 144 | def _GetDeletes(self, outpath:Path, outputMethod) -> List[Path]: 145 | ret = [] 146 | if outputMethod=='folder': 147 | ret += [outpath] 148 | # let's clean up the plain files in the parent folder too 149 | outpath = outpath.parent 150 | else: 151 | ret += [Path(outpath, 'Randomizer')] 152 | 153 | #if outputMethod=='grp': # we check if these exist anyways, might as well always add them to the list and have safer cleanups 154 | ret += [ 155 | Path(outpath, self.game.type + ' Randomizer.html'), 156 | Path(outpath, self.game.type + ' Randomizer.grp'), 157 | Path(outpath, self.game.type + ' Randomizer.grpinfo'), 158 | ] 159 | 160 | cons = self.gameSettings.conFiles 161 | maps = self.GetAllFilesEndsWith('.map') 162 | paths = set([self.game.type + ' Randomizer.html', 'Randomizer.html', self.game.type + ' Randomizer.bat']) 163 | f:str 164 | for f in self.files: 165 | if f in cons or f in maps: 166 | part:str = Path(f).parts[0] 167 | paths.add(part) 168 | paths = list(paths) 169 | paths.sort(key=str.casefold) 170 | for f in paths: 171 | p:Path = Path(outpath, f) 172 | if p not in ret: 173 | ret.append(p) 174 | return ret 175 | 176 | def ShuffleMaps(self, seed, restricted, maps) -> dict: 177 | maps = maps.copy() 178 | for m in self.mapSettings.reorderMapsBlacklist: 179 | if m in maps: 180 | maps.remove(m) 181 | if len(maps) == 0: 182 | return {} 183 | 184 | if not restricted: 185 | rng = random.Random(crc32('grp reorder maps', seed)) 186 | return dict(zip(maps, rng.sample(maps, k=len(maps)))) 187 | 188 | episodes = {} 189 | mapRenames = {} 190 | # categorize the maps 191 | for map in maps: 192 | match = re.match('\w(\d+)\w(\d+)\.MAP$', map, flags=re.IGNORECASE) 193 | episode = 'other' 194 | if match: 195 | episode = match.group(1) 196 | if episode not in episodes: 197 | episodes[episode] = [map] 198 | else: 199 | episodes[episode].append(map) 200 | # shuffle each episode 201 | for k,v in episodes.items(): 202 | rng = random.Random(crc32('grp reorder maps', k, seed)) 203 | d = dict(zip(v, rng.sample(v, k=len(v)))) 204 | mapRenames.update(d) 205 | return mapRenames 206 | 207 | @abc.abstractmethod 208 | def GetGrpOutput(self, basepath: Path, num_files: int, full: bool): 209 | raise NotImplementedError() 210 | 211 | # basepath is only used by tests 212 | def _Randomize(self, seed:int, settings:dict, basepath:Path, spoilerlog, filehandle, progressCallback:Optional[Callable]) -> None: 213 | spoilerlog.write(datetime.now().strftime('%c') + ': Randomizing with seed: ' + str(seed) + ', settings:\n ' + repr(settings) + '\n') 214 | spoilerlog.write(str(self.filepath)) 215 | spoilerlog.write(repr(self.game) + '\n\n') 216 | 217 | maps = self.GetAllFilesEndsWith('.map') 218 | cons = self.gameSettings.conFiles 219 | 220 | outputMethod = settings['outputMethod'] 221 | grpOut = None 222 | full = False 223 | if outputMethod in ('grp', 'grpfull'): 224 | num_files = len(maps) + len(cons) 225 | if outputMethod == 'grpfull': 226 | num_files = len(self.files) 227 | full = True 228 | grpOut = self.GetGrpOutput(basepath, num_files, seed, full) 229 | grpOut.open() 230 | 231 | # randomize CON files 232 | for (conName,conSettings) in cons.items(): 233 | data = self.getfile(conName, filehandle) 234 | text = data.decode('iso_8859_1') 235 | con:ConFile = ConFile(self.game, conSettings, conName, text) 236 | con.Randomize(seed, settings, spoilerlog) 237 | 238 | out = Path(basepath, conName) 239 | text = con.GetText() 240 | size = locale.format_string('%d bytes', len(text), grouping=True) 241 | spoilerlog.write(str(out) + ' is ' + size) 242 | 243 | if grpOut: 244 | grpOut.write(conName, text.encode('iso_8859_1')) 245 | else: 246 | out.parent.mkdir(parents=True, exist_ok=True) 247 | assert not out.exists() 248 | with open(out, 'wb') as f: 249 | f.write(text.encode('iso_8859_1')) 250 | 251 | # MAP shuffling 252 | mapRenames = {} 253 | if settings.get('grp.reorderMaps'): 254 | restricted = settings['grp.reorderMaps'] == 'restricted' 255 | mapRenames = self.ShuffleMaps(seed, restricted, maps) 256 | 257 | # randomize MAP files 258 | for mapname in maps: 259 | if progressCallback: 260 | progressCallback(mapname, maps, 0) 261 | map:MapFile = self.getmap(mapname, filehandle) 262 | map.Randomize(seed, settings, spoilerlog) 263 | 264 | writename = mapRenames.get(mapname, mapname) 265 | out = Path(basepath, writename) 266 | size = locale.format_string('%d bytes', len(map.data), grouping=True) 267 | spoilerlog.write(str(mapname) + ' writing to ' + str(out) + ', is ' + size) 268 | 269 | if grpOut: 270 | grpOut.write(writename, map.data) 271 | else: 272 | out.parent.mkdir(parents=True, exist_ok=True) 273 | assert not out.exists() 274 | with open(out, 'wb') as f: 275 | f.write(map.data) 276 | 277 | # write the remaining files to the GRP 278 | if grpOut and full: 279 | for f in self.files.keys(): 280 | if f in cons or f in maps: 281 | continue 282 | grpOut.write(f, self.getfile(f, filehandle)) 283 | if grpOut: 284 | grpOut.close() 285 | 286 | spoilerlog.write('\n') 287 | spoilerlog.write(repr(self.gameSettings)) 288 | spoilerlog.write('\n') 289 | spoilerlog.write(repr(self.mapSettings)) 290 | 291 | 292 | def Randomize(self, seed:int, settings:dict={}, basepath:Path='', progressCallback:Optional[Callable]=None) -> None: 293 | outputMethod = settings['outputMethod'] 294 | outpath:Path = self.GetOutputPath(basepath, outputMethod) 295 | deletes:List[Path] = self.GetDeletes(basepath, outputMethod) 296 | for f in deletes: 297 | info('Deleting: ', f) 298 | if f.is_dir(): 299 | shutil.rmtree(f) 300 | elif f.is_file(): 301 | os.remove(f) 302 | 303 | out = Path(outpath, self.game.type + ' Randomizer.html') 304 | out.parent.mkdir(parents=True, exist_ok=True) 305 | self.spoilerlogpath = out 306 | assert not out.exists() 307 | with self.getFileHandle() as filehandle, SpoilerLog(out) as spoilerlog: 308 | try: 309 | self._Randomize(seed, settings, outpath, spoilerlog, filehandle, progressCallback) 310 | self.WriteBat(outpath, outputMethod) 311 | except: 312 | error(str(self.filepath)) 313 | error(self.game, ', seed: ', seed, ', settings: ', settings, ', outpath: ', outpath) 314 | error('\n == files: ', self.files, ' == end of files listing ==\n') 315 | raise 316 | 317 | 318 | def WriteBat(self, outpath:Path, outputMethod:str): 319 | if os.name != 'nt': 320 | return None 321 | basepath = outpath 322 | if outputMethod=='folder': 323 | basepath = outpath.parent 324 | 325 | commands = self.gameSettings.commands.get(outputMethod) 326 | if not commands: 327 | return 328 | for (k,v) in commands.items(): 329 | exe = Path(basepath, k+'.exe') 330 | if not exe.exists(): 331 | continue 332 | bat = Path(basepath, self.game.type + ' Randomizer.bat') 333 | cmd = k+' '+v 334 | if outputMethod in ['grp', 'grpfull']: 335 | cmd += '"' + self.game.type + ' Randomizer.grp"' 336 | elif outputMethod == 'folder': 337 | cmd += 'Randomizer' 338 | assert not bat.exists() 339 | with open(bat, 'w') as file: 340 | file.write(cmd) 341 | self.batpath = bat 342 | return cmd 343 | self.batpath = None 344 | warning('Unable to create bat file, unrecognized source port') 345 | 346 | def ExtractFile(self, outpath:Path, name, filehandle=None) -> None: 347 | outfile = Path(outpath, name) 348 | outfile.parent.mkdir(parents=True, exist_ok=True) 349 | data = self.getfile(name, filehandle) 350 | print(name, len(data), outfile) 351 | if not data: 352 | return 353 | with open(outfile, 'wb') as o: 354 | o.write(data) 355 | 356 | def ExtractAll(self, outpath:Path) -> None: 357 | with self.getFileHandle() as filehandle: 358 | for name in self.files.keys(): 359 | self.ExtractFile(outpath, name, filehandle) 360 | 361 | 362 | class GrpOutputBase(metaclass=abc.ABCMeta): 363 | def __init__(self, outpath: Path, gamename: str, num_files: int, extraname: str, scriptname: Union[None,str], defName: Union[None,str], flags: int, depend: int): 364 | self.num_files = num_files 365 | self.outpath = outpath 366 | self.gamename = gamename 367 | self.num_saved_files = 0 368 | self.files = dict() 369 | self.extraname = extraname 370 | self.scriptname = scriptname 371 | self.defName = defName 372 | self.flags = flags 373 | self.depend = depend 374 | 375 | def __enter__(self): 376 | return self.open() 377 | 378 | def __exit__(self, *args): 379 | self.close() 380 | 381 | @abc.abstractmethod 382 | def open(self): 383 | return self 384 | 385 | @abc.abstractmethod 386 | def write(self, name: str, data: bytes): 387 | return 388 | 389 | @abc.abstractmethod 390 | def close(self): 391 | return 392 | 393 | def write_info(self, size: int, crc: int): 394 | # grpinfo file so eDuke32 knows what to do with it 395 | crc = ctypes.c_int32(crc).value 396 | depend = ctypes.c_int32(self.depend).value 397 | if self.extraname: 398 | self.extraname = ' ' + self.extraname 399 | grpinfo_path = Path(self.outpath.parent, self.outpath.name + 'info') 400 | info = "grpinfo\n{\n" 401 | info += ' name "' + self.gamename + ' Randomizer' + self.extraname + '"\n' 402 | if self.scriptname: 403 | info += ' scriptname "' + self.scriptname + '"\n' 404 | if self.defName: 405 | info += ' defname "' + self.defName + '"\n' 406 | info += ' size ' + str(size) + '\n' 407 | info += " crc " + str(crc) + "\n" 408 | info += ' flags ' + str(self.flags) + '\n' 409 | info += ' dependency ' + str(depend) + '\n' 410 | info += "}\n" 411 | grpinfo_path.parent.mkdir(parents=True, exist_ok=True) 412 | assert not grpinfo_path.exists() 413 | with open(grpinfo_path, 'wb') as i: 414 | i.write(info.encode('ascii')) 415 | -------------------------------------------------------------------------------- /tests.py: -------------------------------------------------------------------------------- 1 | import cProfile 2 | import glob 3 | import os 4 | import sys 5 | import random 6 | import shutil 7 | import unittest 8 | from typing import OrderedDict, Union 9 | from hashlib import md5 10 | from mmap import mmap, ACCESS_READ 11 | from pathlib import Path 12 | from typeguard import typechecked, install_import_hook 13 | from unittest import case 14 | 15 | profiling = False 16 | typechecks = not profiling 17 | if typechecks: 18 | install_import_hook('BuildLibs') 19 | install_import_hook('BuildGames') 20 | install_import_hook('GUI') 21 | from BuildLibs import buildmapbase, buildmap, crc32, trace, setVerbose, GetVersion, warning 22 | from BuildLibs.grpbase import GrpBase 23 | from BuildLibs.grp import GrpZipFile, LoadGrpFile, RffCrypt, GrpOutput 24 | import BuildGames 25 | from GUI import gui, launcher 26 | 27 | unittest.TestLoader.sortTestMethodsUsing = None 28 | temp:Path = Path('temp/') 29 | zippath:Path = Path('duke3d-shareware.grp.zip') 30 | tempgrp:Path = Path('temp/testing.grp') 31 | 32 | settings = { 33 | 'MapFile.chanceDupeItem': 0.5, 34 | 'MapFile.chanceDeleteItem': 0.5, 35 | 'MapFile.chanceDupeEnemy': 0.5, 36 | 'MapFile.chanceDeleteEnemy': 0.5, 37 | 'MapFile.itemVariety': 0, 38 | 'MapFile.enemyVariety': 0, 39 | 'conFile.range': 1, 40 | 'conFile.scale': 1, 41 | 'conFile.difficulty': 0.5, 42 | 'outputMethod': 'folder', 43 | } 44 | 45 | different_settings = { 46 | 'MapFile.chanceDupeItem': 0.75, 47 | 'MapFile.chanceDeleteItem': 0.25, 48 | 'MapFile.chanceDupeEnemy': 0.75, 49 | 'MapFile.chanceDeleteEnemy': 0.25, 50 | 'MapFile.itemVariety': 0, 51 | 'MapFile.enemyVariety': 0, 52 | 'conFile.range': 1.5, 53 | 'conFile.scale': 0.8, 54 | 'conFile.difficulty': 0.7, 55 | 'outputMethod': 'folder', 56 | } 57 | 58 | # zipped for tests 59 | BuildGames.AddGame('ZIPPED Shareware DUKE3D.GRP v1.3D', 'Duke Nukem 3D', 4570468, 'BFC91225', '9eacbb74e107fa0b136f189217ce41c7', '4bdf21e32ec6a3fc43092a50a51fce3e4ad6600d') # ZIPPED Shareware DUKE3D.GRP v1.3D for tests 60 | 61 | # we need the correct file order so we can match the md5 62 | original_order = [ 63 | 'DEFS.CON', 'GAME.CON', 'USER.CON', 'D3DTIMBR.TMB', 'DUKESW.BIN', 'LOOKUP.DAT', 'PALETTE.DAT', 64 | 'TABLES.DAT', 'SECRET.VOC', 'BLANK.VOC', 'ROAM06.VOC', 'ROAM58.VOC', 'PREDRG.VOC', 'GBLASR01.VOC', 65 | 'PREDPN.VOC', 'PREDDY.VOC', 'CHOKN12.VOC', 'PREDRM.VOC', 'LIZSPIT.VOC', 'PIGRM.VOC', 'ROAM29.VOC', 66 | 'ROAM67.VOC', 'PIGRG.VOC', 'PIGPN.VOC', 'PIGDY.VOC', 'PIGWRN.VOC', 'OCTARM.VOC', 'OCTARG.VOC', 'OCTAAT1.VOC', 67 | 'OCTAAT2.VOC', 'OCTAPN.VOC', 'OCTADY.VOC', 'BOS1RM.VOC', 'BOS1RG.VOC', 'BOS1PN.VOC', 'BOS1DY.VOC', 'KICKHIT.VOC', 68 | 'RICOCHET.VOC', 'BULITHIT.VOC', 'PISTOL.VOC', 'CLIPOUT.VOC', 'CLIPIN.VOC', 'CHAINGUN.VOC', 'SHOTGNCK.VOC', 69 | 'RPGFIRE.VOC', 'BOMBEXPL.VOC', 'PBOMBBNC.VOC', 'WPNSEL21.VOC', 'SHRINK.VOC', 'LSRBMBPT.VOC', 'LSRBMBWN.VOC', 70 | 'SHRINKER.VOC', 'VENTBUST.VOC', 'GLASS.VOC', 'GLASHEVY.VOC', 'SHORTED.VOC', 'SPLASH.VOC', 'ALERT.VOC', 'REACTOR.VOC', 71 | 'SUBWAY.VOC', 'GEARGRND.VOC', 'GASP.VOC', 'GASPS07.VOC', 'PISSING.VOC', 'KNUCKLE.VOC', 'DRINK18.VOC', 'EXERT.VOC', 72 | 'HARTBEAT.VOC', 'PAIN13.VOC', 'PAIN28.VOC', 'PAIN39.VOC', 'PAIN87.VOC', 'WETFEET.VOC', 'LAND02.VOC', 'DUCTWLK.VOC', 73 | 'PAIN54.VOC', 'PAIN75.VOC', 'PAIN93.VOC', 'PAIN68.VOC', 'DAMN03.VOC', 'DAMNIT04.VOC', 'COMEON02.VOC', 'WAITIN03.VOC', 74 | 'COOL01.VOC', 'AHMUCH03.VOC', 'DANCE01.VOC', 'LETSRK03.VOC', 'READY2A.VOC', 'RIPEM08.VOC', 'ROCKIN02.VOC', 75 | 'AHH04.VOC', 'GULP01.VOC', 'PAY02.VOC', 'AMESS06.VOC', 'BITCHN04.VOC', 'DOOMED16.VOC', 'HOLYCW01.VOC', 76 | 'HOLYSH02.VOC', 'IMGOOD12.VOC', 'ONLYON03.VOC', 'PIECE02.VOC', 'RIDES09.VOC', '2RIDE06.VOC', 'THSUK13A.VOC', 77 | 'WANSOM4A.VOC', 'MYSELF3A.VOC', 'NEEDED03.VOC', 'SHAKE2A.VOC', 'DUKNUK14.VOC', 'GETSOM1A.VOC', 'GOTHRT01.VOC', 78 | 'GROOVY02.VOC', 'WHRSIT05.VOC', 'BOOBY04.VOC', 'DIESOB03.VOC', 'DSCREM04.VOC', 'LOOKIN01.VOC', 'PISSIN01.VOC', 79 | 'GETITM19.VOC', 'SCUBA.VOC', 'JETPAKON.VOC', 'JETPAKI.VOC', 'JETPAKOF.VOC', 'GOGGLE12.VOC', 'THUD.VOC', 80 | 'SQUISH.VOC', 'TELEPORT.VOC', 'GBELEV01.VOC', 'GBELEV02.VOC', 'SWITCH.VOC', 'FLUSH.VOC', 'QUAKE.VOC', 81 | 'MONITOR.VOC', 'POOLBAL1.VOC', 'ONBOARD.VOC', 'BUBBLAMB.VOC', 'MACHAMB.VOC', 'WIND54.VOC', 'STEAMHIS.VOC', 82 | 'BARMUSIC.VOC', 'WARAMB13.VOC', 'WARAMB21.VOC', 'WARAMB23.VOC', 'WARAMB29.VOC', 'COMPAMB.VOC', 'SLIDOOR.VOC', 83 | 'OPENDOOR.VOC', 'EDOOR10.VOC', 'EDOOR11.VOC', 'FSCRM10.VOC', 'H2OGRGL2.VOC', 'GRIND.VOC', 'ENGHUM.VOC', 84 | 'LAVA06.VOC', 'PHONBUSY.VOC', 'ROAM22.VOC', 'AMB81B.VOC', 'ROAM98B.VOC', 'H2ORUSH2.VOC', 'PROJRUN.VOC', 85 | 'FIRE09.VOC', '!PRISON.VOC', '!PIG.VOC', '!BOSS.VOC', 'MICE3.VOC', 'DRIP3.VOC', 'ITEM15.VOC', 'BONUS.VOC', 86 | 'CATFIRE.VOC', 'KILLME.VOC', 'SHOTGUN7.VOC', 'DMDEATH.VOC', 'HAPPEN01.VOC', 'DSCREM15.VOC', 'DSCREM16.VOC', 87 | 'DSCREM17.VOC', 'DSCREM18.VOC', 'DSCREM38.VOC', 'RIP01.VOC', 'NOBODY01.VOC', 'CHEW05.VOC', 'LETGOD01.VOC', 88 | 'HAIL01.VOC', 'BLOWIT01.VOC', 'EATSHT01.VOC', 'FACE01.VOC', 'INHELL01.VOC', 'SUKIT01.VOC', 'PISSES01.VOC', 89 | 'GRABBAG.MID', 'STALKER.MID', 'DETHTOLL.MID', 'STREETS.MID', 'WATRWLD1.MID', 'SNAKE1.MID', 'THECALL.MID', 90 | 'TILES000.ART', 'TILES001.ART', 'TILES002.ART', 'TILES003.ART', 'TILES004.ART', 'TILES005.ART', 'TILES006.ART', 91 | 'TILES007.ART', 'TILES008.ART', 'TILES009.ART', 'TILES010.ART', 'TILES011.ART', 'TILES012.ART', 'E1L1.MAP', 92 | 'E1L2.MAP', 'E1L3.MAP', 'E1L4.MAP', 'E1L5.MAP', 'E1L6.MAP' 93 | ] 94 | 95 | @typechecked 96 | class BERandoTestCase(unittest.TestCase): 97 | def subTest(self, msg=case._subtest_msg_sentinel, **params): 98 | print('\n----------------------------------\nstarting subTest', msg, '\n----------------------------------') 99 | return super().subTest(msg, **params) 100 | 101 | @classmethod 102 | def tearDownClass(cls): 103 | # GitHub Actions doesn't show STDERR 104 | print('Finished '+ str(cls.__name__)) 105 | super().tearDownClass() 106 | 107 | def test_get_version(self): 108 | print(GetVersion()) 109 | print('Python version:', sys.version_info) 110 | 111 | d = OrderedDict(zero=0, one=1, two=2, three=3, four=4, five=5, six=6, seven=7, eight=8, nine=9, ten=10) 112 | l = list(d.values()) 113 | self.assertListEqual(l, list(range(0, 11)), 'OrderedDict kargs init ordering') 114 | 115 | d = OrderedDict({'zero':0, 'one':1, 'two':2, 'three':3, 'four':4, 'five':5, 'six':6, 'seven':7, 'eight':8, 'nine':9, 'ten':10}) 116 | l = list(d.values()) 117 | self.assertListEqual(l, list(range(0, 11)), 'OrderedDict dict init ordering') 118 | 119 | def test_1_extract_zipgrp(self): 120 | # I zipped the GRP file to save space in the repo 121 | # but also Ion Fury uses ZIP format anyways so we do need to test it 122 | grp: GrpBase|None = None 123 | with self.subTest('ExtractAll'): 124 | grp = LoadGrpFile(zippath) 125 | self.assertEqual(len(grp.files), len(original_order)) 126 | grp.ExtractAll(temp) 127 | 128 | with self.subTest('CreateGrpFile'): 129 | CreateGrpFile(temp, tempgrp, original_order) 130 | 131 | grp = None 132 | with self.subTest('Verify new GRP File'): 133 | grp = LoadGrpFile(tempgrp) 134 | self.assertEqual(grp.game.type, 'Duke Nukem 3D') 135 | 136 | def test_rng(self): 137 | # ensure the rng is OS indepedent 138 | rng = random.Random('0451') 139 | self.assertEqual(rng.randint(1, 10), 8) 140 | self.assertEqual(rng.choice(range(10)), 2) 141 | self.assertEqual(int(rng.random()*1000), 433) 142 | 143 | def test_rando(self): 144 | # first get vanilla MD5s 145 | with self.subTest('Open GRP File'): 146 | grp: GrpBase = LoadGrpFile(tempgrp) 147 | vanilla = self.Md5GameFiles('Vanilla', grp, temp) 148 | self.assertIsNotNone(vanilla, 'Vanilla MD5s') 149 | self.assertGreater(len(vanilla), 0, 'Vanilla MD5s') 150 | 151 | # now test randomizing with different seeds and settings, comparing MD5s each time 152 | grp0451 = self.TestRandomize(tempgrp, 451, vanilla, False) 153 | print(repr(grp0451)) 154 | # update these when making behavioral changes, but otherwise they should stay the same 155 | self.assertDictEqual( 156 | { 157 | 'E1L1.MAP': '92d3555d92495f1d158844def24d3653', 158 | 'E1L2.MAP': 'f58855a55af234be8d1de4f145dc07fa', 159 | 'E1L3.MAP': '9fb5450bd3781d70fa3e95d70aa50b1a', 160 | 'E1L4.MAP': 'f3fd61103fe07e90afbf19f2b99a83fb', 161 | 'E1L5.MAP': '8affa9fe8ddb2ecc5951a87788629417', 162 | 'E1L6.MAP': 'c8d921798945faa9a9321ad018fc80d2', 163 | 'USER.CON': '24e6c7ce98064e633528d92380002d55' 164 | }, 165 | grp0451 166 | ) 167 | self.TestRandomize(zippath, 2052, grp0451, False) 168 | self.TestRandomize(tempgrp, 451, grp0451, True) 169 | self.TestRandomize(tempgrp, 451, grp0451, False, settings=different_settings) 170 | 171 | def test_grp_output(self): 172 | settings_grp = settings.copy() 173 | settings_grp['outputMethod'] = 'grp' 174 | grp:GrpBase = LoadGrpFile(tempgrp) 175 | grp.Randomize(451, settings=settings_grp, basepath=Path(tempgrp.parent, 'test_grp_output')) 176 | 177 | 178 | def test_external_files(self): 179 | try: 180 | with self.subTest('Create External File'): 181 | testdata = 'Damn, I\'m lookin good!' 182 | extname = 'external_file.txt' 183 | gamedir = Path(tempgrp).parent 184 | extpath = Path(gamedir, extname) 185 | with open(extpath, 'w') as file: 186 | file.write(testdata) 187 | 188 | with self.subTest('Open GRP File'): 189 | BuildGames.AddGame('Shareware DUKE3D.GRP v1.3D', 'Duke Nukem 3D', 11035779, '983AD923', 'C03558E3A78D1C5356DC69B6134C5B55', 'A58BDBFAF28416528A0D9A4452F896F46774A806', externalFiles=True, allowOverwrite=True) # Shareware DUKE3D.GRP v1.3D 190 | grp: GrpBase = LoadGrpFile(tempgrp) 191 | 192 | with self.subTest('Read External File'): 193 | t = grp.getfile(extname).decode() 194 | self.assertEqual(t, testdata, 'Got external file path override') 195 | finally: 196 | BuildGames.AddGame('Shareware DUKE3D.GRP v1.3D', 'Duke Nukem 3D', 11035779, '983AD923', 'C03558E3A78D1C5356DC69B6134C5B55', 'A58BDBFAF28416528A0D9A4452F896F46774A806', externalFiles=False, allowOverwrite=True) # Shareware DUKE3D.GRP v1.3D 197 | 198 | def test_game_settings(self): 199 | for game in BuildGames.gamesList.values(): 200 | self.CheckGame(game) 201 | 202 | def CheckGame(self, game: BuildGames.GameInfo): 203 | try: 204 | mapSettings: BuildGames.GameMapSettings = BuildGames.GetGameMapSettings(game) 205 | except Exception as e: 206 | warning(e) 207 | return 208 | for e in mapSettings.addableEnemies: 209 | self.assertIn(e, mapSettings.swappableEnemies) 210 | for map in mapSettings.additions.values(): 211 | for addition in map: 212 | for sprite in addition['choices']: 213 | self.assertIn(sprite, mapSettings.swappableItems) 214 | 215 | #@unittest.skip 216 | def test_other_grps(self): 217 | # optionally use the othertests folder for testing your own collection of games that aren't freeware 218 | files = glob.glob('othertests/*', recursive=True) 219 | for f in files: 220 | if 'skip' in f: 221 | continue 222 | with self.subTest(f): 223 | f = Path(f) 224 | self.TestRandomize(f, 451, {}, False) 225 | #grp = LoadGrpFile(f) 226 | #grp.ExtractAll(Path(temp,str(f)+'-extracted')) 227 | 228 | def test_combine(self): 229 | # optionally make a new grp file 230 | globfiles = glob.glob('combine/*', recursive=True) 231 | files = [] 232 | for f in globfiles: 233 | f = Path(f) 234 | if f.is_file(): 235 | files.append(f) 236 | if files: 237 | CreateGrpFile(Path(''), Path('temp/combined.grp'), files) 238 | 239 | 240 | def TestRandomize(self, grppath:Path, seed:int, oldMd5s:dict, shouldMatch:bool, settings:dict=settings) -> dict: 241 | self.maxDiff = None 242 | testname = str(grppath) + ' Seed ' + ('0451' if seed==451 else str(seed)) 243 | foldername = grppath.name + '-' + str(crc32(testname+repr(settings))) 244 | basepath = Path(temp, foldername) 245 | newMd5s = None 246 | with self.subTest('Randomize '+testname): 247 | grp:GrpBase = LoadGrpFile(grppath) 248 | grp.Randomize(seed, settings=settings, basepath=basepath) 249 | gametype = grp.game.type 250 | 251 | if settings['outputMethod'] == 'folder': 252 | basepath = Path(basepath, 'Randomizer') 253 | newMd5s = self.Md5GameFiles(testname, grp, basepath) 254 | self.assertIsNotNone(newMd5s, 'New MD5s') 255 | self.assertGreater(len(newMd5s), 0, 'New MD5s') 256 | 257 | if oldMd5s: 258 | self.assertIsNotNone(oldMd5s, 'Old MD5s') 259 | self.assertGreater(len(oldMd5s), 0, 'Old MD5s') 260 | if shouldMatch: 261 | self.assertDictEqual(oldMd5s, newMd5s) 262 | else: 263 | self.assertEqual(len(oldMd5s), len(newMd5s), 'Same number of files') 264 | for k in oldMd5s.keys(): 265 | self.assertNotEqual(oldMd5s[k], newMd5s[k], k) 266 | 267 | with open(Path(basepath, gametype + ' Randomizer.html')) as spoilerlog: 268 | logs = spoilerlog.read() 269 | self.assertGreater(len(logs), 10, 'found spoiler logs') 270 | self.assertInLogs('Randomizing with seed: '+str(seed), logs) 271 | for con in grp.gameSettings.conFiles.keys(): 272 | con = str(Path(con)) 273 | self.assertInLogs('Finished randomizing file: '+con, logs) 274 | for map in grp.GetAllFilesEndsWith('.map'): 275 | map = str(Path(map)) 276 | self.assertInLogs('Finished randomizing file: '+map, logs) 277 | self.assertInLogs('
', logs) 278 | if grp.mapSettings.triggers: 279 | self.assertInLogs('set hightag to ', logs) 280 | self.assertInLogs('
', logs) 281 | return newMd5s 282 | 283 | def assertInLogs(self, text, logs): 284 | if text.lower() not in logs.lower(): 285 | self.fail(text + ' not found in logs') 286 | 287 | def Md5GameFiles(self, testname:str, grp:GrpBase, basepath:Path) -> dict: 288 | with self.subTest('MD5 '+testname): 289 | maps = grp.GetAllFilesEndsWith('.map') 290 | cons = list(grp.gameSettings.conFiles.keys()) 291 | return self.Md5Files(basepath, (maps+cons)) 292 | 293 | def Md5Files(self, basepath: Path, filenames: list) -> dict: 294 | md5s = {} 295 | for f in filenames: 296 | t = self.Md5File(Path(basepath, f)) 297 | md5s[f] = t 298 | trace('Md5Files ', basepath, ': ', md5s) 299 | return md5s 300 | 301 | def Md5File(self, filename:Path): 302 | with open(filename) as file, mmap(file.fileno(), 0, access=ACCESS_READ) as file: 303 | md5sum = md5(file).hexdigest() 304 | return md5sum 305 | 306 | def test_walls(self): 307 | with self.subTest('test PointIsInShape'): 308 | walls = [(0,0), (10,0), (10,10), (0,10)] 309 | self.assertEqual(buildmapbase.PointIsInShape(walls, (5,5), 0) % 2, 1) 310 | self.assertEqual(buildmapbase.PointIsInShape(walls, (15,15), 0) % 2, 0) 311 | 312 | def test_blood_crypt(self): 313 | # ensure it's reversible 314 | data = bytearray(b'123456') 315 | d2 = buildmap.MapCrypt(data, 451) 316 | d2 = buildmap.MapCrypt(d2, 451) 317 | d2 = RffCrypt(d2, 451) 318 | d2 = RffCrypt(d2, 451) 319 | self.assertEqual(data, d2) 320 | 321 | data = bytearray(b'dfgdfghcvbngertguhyrtujityr3456436fdghsdfgxcvb') 322 | d2 = buildmap.MapCrypt(data, 0x7474614d) 323 | d2 = buildmap.MapCrypt(d2, 0x7474614d) 324 | d2 = RffCrypt(d2, 451) 325 | d2 = RffCrypt(d2, 451) 326 | self.assertEqual(data, d2) 327 | 328 | def test_mirror(self): 329 | orig = [12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] # verticies are counter-clockwise, right? 330 | desired = [12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] 331 | result = buildmapbase.MirrorList(orig) 332 | self.assertListEqual(result, desired, 'mirror') 333 | 334 | 335 | 336 | def CreateGrpFile(frompath: Path, outpath: Path, filenames: list) -> None: 337 | with GrpOutput(outpath, 'test', len(filenames), '', 'GAME.CON', None, 0, 0) as out: 338 | for name in filenames: 339 | with open(Path(frompath, name), 'rb') as f: 340 | d = f.read() 341 | out.write(str(name), d) 342 | 343 | def runtests(): 344 | unittest.main(verbosity=9, warnings="error", failfast=True) 345 | 346 | 347 | if __name__ == "__main__": 348 | try: 349 | if os.path.isdir(temp): 350 | shutil.rmtree(temp) 351 | if profiling: 352 | setVerbose(-10) 353 | cProfile.run("runtests()", sort="cumtime") 354 | else: 355 | runtests() 356 | finally: 357 | # if os.path.isdir(temp): 358 | # shutil.rmtree(temp) 359 | pass 360 | -------------------------------------------------------------------------------- /BuildLibs/buildmapbase.py: -------------------------------------------------------------------------------- 1 | import abc 2 | import binascii 3 | import copy 4 | import random 5 | import struct 6 | from pathlib import Path 7 | from typing import OrderedDict, Union 8 | 9 | from BuildLibs import crc32, error, info, swapobjkey, trace, warning, FancyPacker 10 | import BuildGames 11 | 12 | class CStat: 13 | 14 | def __init__(self, cstat): 15 | self.blocking = bool(cstat & 1) 16 | self.facing = cstat & 0x30 17 | self.onesided = cstat & 0x40 18 | self.blockingHitscan = bool(cstat & 0x800) 19 | self.invisible = bool(cstat & 0x8000) 20 | 21 | 22 | class Sector: 23 | 24 | def __init__(self, data:dict): 25 | self.__dict__ = data 26 | 27 | def defaults(self, data:dict): 28 | self.wallptr: int = data.get('wallptr', 0) 29 | self.wallnum: int = data.get('wallnum', 0) 30 | self.ceilingz: int = data.get('ceilingz', 0) 31 | self.floorz: int = data.get('floorz', 0) 32 | self.ceilingstat: int = data.get('ceilingstat', 0) 33 | self.floorstat: int = data.get('floorstat', 0) 34 | self.ceilingpicnum: int = data.get('ceilingpicnum', 0) 35 | self.ceilingheinum: int = data.get('ceilingheinum', 0) 36 | self.ceilingshade: int = data.get('ceilingshade', 0) 37 | self.ceiling_palette: int = data.get('ceiling_palette', 0) 38 | self.ceiling_texcoords: list = data.get('ceiling_texcoords', [0, 0]) 39 | self.floorpicnum: int = data.get('floorpicnum', 0) 40 | self.floorheinum: int = data.get('floorheinum', 0) 41 | self.floorshade: int = data.get('floorshade', 0) 42 | self.floor_palette: int = data.get('floor_palette', 0) 43 | self.floor_texcoords: list = data.get('floor_texcoords', [0, 0]) 44 | self.visibility: int = data.get('visibility', 0) 45 | self.filler: int = data.get('filler', 0) 46 | self.lowtag: int = data.get('lowtag', 0) 47 | self.hightag: int = data.get('hightag', 0) 48 | self.extra: int = data.get('extra', -1) 49 | self.length: int = data.get('length', 0) 50 | self.ceilingxpanning: int = data.get('ceilingxpanning', 0) 51 | self.floorxpanning: int = data.get('floorxpanning', 0) 52 | self.ceilingypanning: int = data.get('ceilingypanning', 0) 53 | self.floorypanning: int = data.get('floorypanning', 0) 54 | 55 | self.walls: Union[list, None] = data.get('walls', None) 56 | self.nearbySectors: Union[set, None] = data.get('nearbySectors', None) 57 | self.shapes: Union[list, None] = data.get('shapes', None) 58 | 59 | 60 | class Wall: 61 | 62 | def __init__(self, data:dict): 63 | self.__dict__ = data 64 | 65 | def defaults(self, data:dict): 66 | self.pos: list = data.get('pos', [0, 0]) 67 | self.next_wall: int = data.get('next_wall', 0) 68 | self.next_sector_wall: int = data.get('next_sector_wall', -1) 69 | self.next_sector: int = data.get('next_sector', -1) 70 | self.cstat: int = data.get('cstat', 0) 71 | self.picnum: int = data.get('picnum', 0) 72 | self.overpicnum: int = data.get('overpicnum', 0) 73 | self.shade: int = data.get('shade', 0) 74 | self.palette: int = data.get('palette', 0) 75 | self.texcoords: list = data.get('texcoords', [0, 0, 0, 0]) 76 | self.lowtag: int = data.get('lowtag', 0) 77 | self.hightag: int = data.get('hightag', 0) 78 | self.extra: int = data.get('extra', -1) 79 | self.length: int = data.get('length', 0) 80 | 81 | 82 | class Sprite: 83 | 84 | def __init__(self, data:dict): 85 | self.__dict__ = data 86 | 87 | def defaults(self, data:dict): 88 | self.pos: list = data.get('pos', [0, 0, 0]) 89 | self.cstat: int = data.get('cstat', 0) 90 | self.picnum: int = data.get('picnum', 0) 91 | self.shade: int = data.get('shade', 0) 92 | self.palette: int = data.get('palette', 0) 93 | self.clipdist: int = data.get('clipdist', 0) 94 | self.filler: int = data.get('filler', 0) 95 | self.texcoords: list = data.get('texcoords', [0, 0, 0, 0]) 96 | self.sectnum: int = data.get('sectnum', 0) 97 | self.statnum: int = data.get('statnum', 0) 98 | self.angle: int = data.get('angle', 0) 99 | self.owner: int = data.get('owner', 0) 100 | self.velocity: list = data.get('velocity', [0, 0, 0]) 101 | self.lowtag: int = data.get('lowtag', 0) 102 | self.hightag: int = data.get('hightag', 0) 103 | self.extra: int = data.get('extra', -1) 104 | self.extraData = data.get('extraData') 105 | self.length: int = data.get('length', 0) 106 | 107 | def __copy__(self) -> 'Sprite': 108 | cls = self.__class__ 109 | copied = cls.__new__(cls) 110 | copied.__dict__.update(self.__dict__) 111 | copied.pos = copied.pos[:] 112 | copied.texcoords = copied.texcoords[:] 113 | copied.velocity = copied.velocity[:] 114 | return copied 115 | 116 | 117 | class MapFileBase(metaclass=abc.ABCMeta): 118 | 119 | """ 120 | https://moddingwiki.shikadi.net/wiki/MAP_Format_(Build) 121 | 122 | """ 123 | 124 | def __init__(self, gameName, name, data: bytearray = None): 125 | self.full_rewrite:bool = False 126 | self.gameSettings = BuildGames.GetGameMapSettings(gameName) 127 | self.name = name 128 | self.data = data 129 | info('\n', name, len(data) if data is not None else None) 130 | 131 | self.version = 0 132 | self.startPos = [0, 0, 0] 133 | self.startAngle = 0 134 | self.startSect = 0 135 | self.num_sectors = 0 136 | self.num_sprites = 0 137 | self.num_walls = 0 138 | 139 | self.crypt = 0 140 | 141 | self.header2Len = 0 142 | self.x_sector_size = 0 143 | self.x_wall_size = 0 144 | self.x_sprite_size = 0 145 | 146 | self.CreateHeaderPacker() 147 | self.CreateSectorPacker() 148 | self.CreateWallPacker() 149 | self.CreateSpritePacker() 150 | 151 | assert self.HEADER_SIZE == self.headerPacker.calcsize() 152 | assert self.SECTOR_SIZE == self.sectorPacker.calcsize() 153 | assert self.WALL_SIZE == self.wallPacker.calcsize() 154 | assert self.SPRITE_SIZE == self.spritePacker.calcsize() 155 | 156 | self.sectors = [] 157 | self.walls = [] 158 | self.items = [] 159 | self.enemies = [] 160 | self.triggers = [] 161 | self.other_sprites = [] 162 | self.sectorCache = {} 163 | 164 | if self.gameSettings.idType == 'lowtag': 165 | self.AppendSprite = self.AppendSpriteLowtag 166 | self.GetSpriteType = self.GetSpriteTypeLowtag 167 | elif self.gameSettings.swappableItems or self.gameSettings.swappableEnemies: 168 | self.AppendSprite = self.AppendSpriteId 169 | self.GetSpriteType = self.GetSpriteTypeId 170 | else: 171 | self.AppendSprite = self.BasicAppendSprite 172 | self.GetSpriteType = self.BasicGetSpriteType 173 | warning('using fallback sprite identification methods!') 174 | 175 | if data is not None: 176 | self.ReadData() 177 | assert len(self.sectors) > 0 178 | assert len(self.walls) > 0 179 | if name != 'maps/null.map': 180 | assert len(self.sprites) > 0 181 | 182 | def __str__(self): 183 | lines = [] 184 | lines.append(f'MapFile: {self.name}') 185 | 186 | lines.append(f' version: {self.version}') 187 | lines.append(f' startPos: {self.startPos}') 188 | lines.append(f' startAngle: {self.startAngle}') 189 | lines.append(f' startSect: {self.startSect}') 190 | 191 | lines.append(f' num sectors: {self.num_sectors}') 192 | lines.append(f' num walls: {self.num_walls}') 193 | lines.append(f' num sprites: {self.num_sprites}') 194 | lines.append(f' len sectors: {len(self.sectors)}') 195 | lines.append(f' len walls: {len(self.walls)}') 196 | lines.append(f' len sprites: {len(self.sprites)}') 197 | lines.append(f' len data: {len(self.data) if self.data is not None else None}') 198 | 199 | return '\n'.join(lines) 200 | 201 | @property 202 | def sprites(self): 203 | return self.items + self.enemies + self.triggers + self.other_sprites 204 | 205 | def Randomize(self, seed:int, settings:dict, spoilerlog): 206 | try: 207 | spoilerlog.SetFilename(Path(self.name)) 208 | spoilerlog.SetGameMapSettings(self.gameSettings) 209 | self.spoilerlog = spoilerlog 210 | self._Randomize(seed, settings) 211 | except: 212 | error('Randomize', self.name) 213 | raise 214 | finally: 215 | self.spoilerlog = None 216 | spoilerlog.FinishRandomizingFile() 217 | 218 | def _Randomize(self, seed:int, settings:dict): 219 | self.spoilerlog.write('before: ' 220 | + 'items: ' + str(len(self.items)) + ', enemies: ' + str(len(self.enemies)) 221 | + ', triggers: ' + str(len(self.triggers)) + ', other_sprites: ' + str(len(self.other_sprites)) 222 | ) 223 | 224 | chanceDupeItem:float = settings['MapFile.chanceDupeItem'] 225 | chanceDeleteItem:float = settings['MapFile.chanceDeleteItem'] 226 | 227 | chanceDupeEnemy:float = settings['MapFile.chanceDupeEnemy'] 228 | chanceDeleteEnemy:float = settings['MapFile.chanceDeleteEnemy'] 229 | 230 | itemVariety:float = settings['MapFile.itemVariety'] 231 | enemyVariety:float = settings['MapFile.enemyVariety'] 232 | 233 | rng = random.Random(crc32('map dupe items', self.name, seed)) 234 | self.DupeSprites(rng, self.items, chanceDupeItem, 1, self.gameSettings.swappableItems, itemVariety, 'item') 235 | 236 | rng = random.Random(crc32('map shuffle items', self.name, seed)) 237 | self.SwapAllSprites(rng, self.items, 'item') 238 | 239 | rng = random.Random(crc32('map reduce items', self.name, seed)) 240 | self.ReduceSprites(rng, self.items, chanceDeleteItem, 'item') 241 | trace('\n') 242 | 243 | if self.gameSettings.gameName == 'Blood': 244 | # TODO: need to parse the extraData to determine if an enemy is important 245 | chanceDupeEnemy = max(chanceDupeEnemy - chanceDeleteEnemy, 0) 246 | chanceDeleteEnemy = 0 247 | 248 | rng = random.Random(crc32('map dupe enemies', self.name, seed)) 249 | enemiesReplacements = {} 250 | for i in self.gameSettings.addableEnemies: 251 | enemiesReplacements[i] = self.gameSettings.swappableEnemies[i] 252 | self.DupeSprites(rng, self.enemies, chanceDupeEnemy, 2, enemiesReplacements, enemyVariety, 'enemy') 253 | 254 | rng = random.Random(crc32('map shuffle enemies', self.name, seed)) 255 | self.SwapAllSprites(rng, self.enemies, 'enemy') 256 | 257 | rng = random.Random(crc32('map reduce enemies', self.name, seed)) 258 | self.ReduceSprites(rng, self.enemies, chanceDeleteEnemy, 'enemy') 259 | trace('\n') 260 | 261 | rng = random.Random(crc32('map rando triggers', self.name, seed)) 262 | self.RandomizeTriggers(rng, self.triggers, self.gameSettings.triggers) 263 | 264 | rng = random.Random(crc32('map additions', self.name, seed)) 265 | for add in self.gameSettings.additions.get(self.name.lower(), []): 266 | self.AddSprite(rng, add) 267 | 268 | #self.MirrorMap() 269 | self.WriteData() 270 | 271 | self.spoilerlog.ListSprites('item', self.items) 272 | self.spoilerlog.ListSprites('enemy', self.enemies) 273 | 274 | self.spoilerlog.write('after: ' 275 | + 'items: ' + str(len(self.items)) + ', enemies: ' + str(len(self.enemies)) 276 | + ', triggers: ' + str(len(self.triggers)) + ', other_sprites: ' + str(len(self.other_sprites)) 277 | ) 278 | 279 | def IsItem(self, sprite:Sprite, cstat: CStat) -> bool: 280 | if self.gameSettings.swappableItems and sprite.picnum not in self.gameSettings.swappableItems: 281 | return False 282 | elif (not self.gameSettings.swappableItems) and sprite.picnum < 10: 283 | return False 284 | #elif (self.game_name == 'Ion Fury' and not cstat.blocking) or cstat.blockingHitscan or cstat.invisible or cstat.onesided or cstat.facing != 0: 285 | elif cstat.blockingHitscan or cstat.invisible or cstat.onesided or cstat.facing != 0: 286 | return False 287 | return True 288 | 289 | def SwapSprites(self, spritetype:str, a:Sprite, b:Sprite): 290 | self.spoilerlog.SwapSprites(spritetype, a, b) 291 | 292 | swapobjkey(a, b, 'pos') 293 | swapobjkey(a, b, 'sectnum') 294 | swapobjkey(a, b, 'angle') 295 | #swapobjkey(a, b, 'hightag') 296 | #swapobjkey(a, b, 'lowtag')# this seems to cause problems with shadow warrior enemies changing types? 297 | a.length, b.length = b.length, a.length 298 | a.extra, b.extra = b.extra, a.extra 299 | a.extraData, b.extraData = b.extraData, a.extraData 300 | 301 | def DupeSprite(self, rng: random.Random, sprite:Sprite, spacing: float, possibleReplacements:dict, replacementChance:float, spritetype: str) -> Union[Sprite,None]: 302 | sprite = copy.copy(sprite) 303 | if rng.random() < replacementChance: 304 | replace = rng.choice((*possibleReplacements.keys(), sprite.picnum)) 305 | if replace != sprite.picnum: 306 | r = possibleReplacements[replace] 307 | sprite.lowtag = r.get('lowtag', sprite.lowtag) 308 | xrepeat = r.get('xrepeat', sprite.texcoords[0]) 309 | yrepeat = r.get('yrepeat', sprite.texcoords[1]) 310 | palettes = r.get('palettes', [0]) 311 | sprite.palette = rng.choice(palettes) 312 | sprite.texcoords = [xrepeat, yrepeat, 0, 0] 313 | sprite.picnum = replace 314 | for i in range(20): 315 | x = rng.choice([-350, -250, -150, 0, 150, 250, 350]) 316 | y = rng.choice([-350, -250, -150, 0, 150, 250, 350]) 317 | if x == 0 and y == 0: 318 | continue 319 | sprite.pos[0] += x * spacing 320 | sprite.pos[1] += y * spacing 321 | newsect = self.GetContainingSectorNearby(sprite.sectnum, sprite.pos) 322 | if newsect is not None: 323 | sprite.sectnum = newsect 324 | self.spoilerlog.AddSprite(spritetype, sprite) 325 | return sprite 326 | return None 327 | 328 | def SwapAllSprites(self, rng, toSwap, spritetype:str): 329 | for a in range(len(toSwap)): 330 | b = rng.randrange(0, len(toSwap)) 331 | if a == b: 332 | continue 333 | a = toSwap[a] 334 | b = toSwap[b] 335 | self.SwapSprites(spritetype, a, b) 336 | 337 | def DupeSprites(self, rng: random.Random, items: list, rate: float, spacing: float, possibleReplacements:dict, replacementChance:float, spritetype: str): 338 | for sprite in items.copy(): 339 | if rng.random() > rate: 340 | continue 341 | newsprite = self.DupeSprite(rng, sprite, spacing, possibleReplacements, replacementChance, spritetype) 342 | if newsprite: 343 | items.append(newsprite) 344 | 345 | def ReduceSprites(self, rng: random.Random, items: list, rate: float, spritetype: str): 346 | for i in range(len(items)-1, -1, -1): 347 | if rng.random() > rate: 348 | continue 349 | self.spoilerlog.DelSprite(spritetype, items[i]) 350 | items[i] = items[-1] 351 | items.pop() 352 | 353 | def RandomizeTriggers(self, rng: random.Random, sprites: list, triggerSettings: dict) -> None: 354 | if not triggerSettings: 355 | return 356 | sprite:Sprite 357 | for sprite in sprites: 358 | settings = triggerSettings.get(sprite.picnum) 359 | if not settings: 360 | continue 361 | if sprite.hightag in settings.get('not_hightags', []): 362 | continue 363 | hightags = settings.get('hightags') 364 | if hightags: 365 | sprite.hightag = rng.choice([*hightags, sprite.hightag]) 366 | self.spoilerlog.SpriteChangedTag('hightag', sprite, sprite.hightag) 367 | lowtags = settings.get('lowtags') 368 | if lowtags: 369 | sprite.lowtag = rng.choice([*lowtags, sprite.lowtag]) 370 | self.spoilerlog.SpriteChangedTag('lowtag', sprite, sprite.lowtag) 371 | 372 | def AddSprite(self, rng: random.Random, add: dict) -> None: 373 | # keep up to date with CreateSpritePacker 374 | add = { 375 | 'picnum': rng.choice(add['choices']), 376 | 'cstat': 0, 377 | 'shade': 0, 378 | 'palette': 0, 379 | 'clipdist': 32, 380 | 'filler': 0, 381 | 'texcoords': [32,32,0,0], 382 | 'statnum': 0, 383 | 'angle': 1536, 384 | 'owner': -1, 385 | 'velocity': [0,0,0], 386 | 'lowtag': 0, 387 | 'hightag': 0, 388 | 'extra': -1, 389 | 'length': self.SPRITE_SIZE, 390 | **add.copy() 391 | } 392 | del add['choices'] 393 | 394 | sprite = Sprite(add) 395 | self.AppendSprite(sprite) 396 | spritetype = self.GetSpriteType(sprite) 397 | self.spoilerlog.AddSprite(spritetype, sprite) 398 | 399 | 400 | def MirrorMap(self): 401 | # TODO, need to figure out re-ordering of walls, they need to be counterclockwise 402 | # probably need to compare coordinates and do some sorting 403 | # actually reversing the list might be good enough, maybe the issue is with all the pointer/index dependencies? 404 | self.full_rewrite = True 405 | x=1 406 | y=-1 407 | 408 | self.startPos[0] *= x 409 | self.startPos[1] *= y 410 | 411 | for w in self.walls: 412 | w.pos[0] *= x 413 | w.pos[1] *= y 414 | 415 | for sect in self.sectors: 416 | shapes = [[]] 417 | wallptr = sect.wallptr 418 | numwalls = sect.wallnum 419 | for i in range(wallptr, wallptr + numwalls): 420 | shapes[-1].append(i) 421 | if self.walls[i].next_wall != -1: 422 | shapes.append([]) 423 | 424 | for shape in shapes: 425 | #rev = shape.copy() 426 | #rev.reverse() 427 | rev = MirrorList(shape) 428 | for a, b in zip(shape, rev): 429 | if a >= b: 430 | break 431 | walla:Wall = self.walls[a] 432 | wallb:Wall = self.walls[b] 433 | 434 | next_wall_a = walla.next_wall 435 | next_sector_wall_a = walla.next_sector_wall 436 | next_sector_a = walla.next_sector 437 | 438 | next_wall_b = wallb.next_wall 439 | next_sector_wall_b = wallb.next_sector_wall 440 | next_sector_b = wallb.next_sector 441 | 442 | walla.next_wall = next_wall_b 443 | walla.next_sector_wall = next_sector_wall_b 444 | walla.next_sector = next_sector_b 445 | 446 | wallb.next_wall = next_wall_a 447 | wallb.next_sector_wall = next_sector_wall_a 448 | wallb.next_sector = next_sector_a 449 | 450 | self.walls[a] = wallb 451 | self.walls[b] = walla 452 | 453 | # need to fix all the references to these points... 454 | 455 | for s in self.sprites: 456 | s.pos[0] *= x 457 | s.pos[1] *= y 458 | 459 | def AppendSector(self, sector: Sector) -> None: 460 | self.sectors.append(sector) 461 | 462 | def AppendWall(self, wall: Wall) -> None: 463 | self.walls.append(wall) 464 | 465 | def BasicAppendSprite(self, sprite: Sprite) -> None: 466 | cstat = CStat(sprite.cstat) 467 | if self.IsItem(sprite, cstat): 468 | self.items.append(sprite) 469 | else: 470 | self.other_sprites.append(sprite) 471 | 472 | def AppendSpriteId(self, sprite: Sprite) -> None: 473 | if sprite.picnum in self.gameSettings.swappableItems: 474 | self.items.append(sprite) 475 | elif sprite.picnum in self.gameSettings.triggers: 476 | self.triggers.append(sprite) 477 | elif sprite.picnum in self.gameSettings.swappableEnemies and not CStat(sprite.cstat).invisible: 478 | self.enemies.append(sprite) 479 | else: 480 | self.other_sprites.append(sprite) 481 | 482 | def AppendSpriteLowtag(self, sprite: Sprite) -> None: 483 | if sprite.lowtag in self.gameSettings.swappableItems: 484 | self.items.append(sprite) 485 | elif sprite.lowtag in self.gameSettings.triggers: 486 | self.triggers.append(sprite) 487 | elif sprite.lowtag in self.gameSettings.swappableEnemies and not CStat(sprite.cstat).invisible: 488 | self.enemies.append(sprite) 489 | else: 490 | self.other_sprites.append(sprite) 491 | 492 | def BasicGetSpriteType(self, sprite:Sprite) -> str: 493 | cstat = CStat(sprite.cstat) 494 | if self.IsItem(sprite, cstat): 495 | return 'item' 496 | else: 497 | return 'other' 498 | 499 | def GetSpriteTypeId(self, sprite:Sprite) -> str: 500 | if sprite.picnum in self.gameSettings.swappableItems: 501 | return 'item' 502 | elif sprite.picnum in self.gameSettings.triggers: 503 | return 'trigger' 504 | elif sprite.picnum in self.gameSettings.swappableEnemies and not CStat(sprite.cstat).invisible: 505 | return 'enemy' 506 | else: 507 | return 'other' 508 | 509 | def GetSpriteTypeLowtag(self, sprite:Sprite) -> str: 510 | if sprite.lowtag in self.gameSettings.swappableItems: 511 | return 'item' 512 | elif sprite.lowtag in self.gameSettings.triggers: 513 | return 'trigger' 514 | elif sprite.lowtag in self.gameSettings.swappableEnemies and not CStat(sprite.cstat).invisible: 515 | return 'enemy' 516 | else: 517 | return 'other' 518 | 519 | def GetSector(self, pos) -> Sector: 520 | data = self.data[pos:pos + self.SECTOR_SIZE] 521 | 522 | if self.crypt and self.version == 7: 523 | data = MapCrypt(data, self.mapRevision * self.SECTOR_SIZE) 524 | 525 | sector = Sector(self.sectorPacker.unpack(data)) 526 | sector.length = self.SECTOR_SIZE 527 | if sector.extra > 0: 528 | pos += self.SECTOR_SIZE 529 | sector.extraData = self.data[pos:pos + self.x_sector_size] 530 | sector.length += self.x_sector_size 531 | return sector 532 | 533 | def GetWall(self, pos) -> Wall: 534 | data = self.data[pos:pos + self.WALL_SIZE] 535 | 536 | if self.crypt and self.version == 7: 537 | data = MapCrypt(data, (self.mapRevision * self.SECTOR_SIZE) | 0x7474614d) 538 | 539 | wall = Wall(self.wallPacker.unpack(data)) 540 | wall.length = self.WALL_SIZE 541 | if wall.extra > 0: 542 | pos += self.WALL_SIZE 543 | wall.extraData = self.data[pos:pos + self.x_wall_size] 544 | wall.length += self.x_wall_size 545 | return wall 546 | 547 | def GetSprite(self, pos) -> Sprite: 548 | data = self.data[pos:pos + self.SPRITE_SIZE] 549 | 550 | if self.crypt and self.version == 7: 551 | data = MapCrypt(data, (self.mapRevision * self.SPRITE_SIZE) | 0x7474614d) 552 | 553 | sprite = Sprite(self.spritePacker.unpack(data)) 554 | sprite.length = self.SPRITE_SIZE 555 | sprite.extraData = None 556 | if sprite.extra > 0: 557 | pos += self.SPRITE_SIZE 558 | sprite.extraData = self.data[pos:pos + self.x_sprite_size] 559 | sprite.length += self.x_sprite_size 560 | return sprite 561 | 562 | @abc.abstractmethod 563 | def CreateHeaderPacker(self): 564 | return 565 | 566 | @abc.abstractmethod 567 | def CreateSectorPacker(self): 568 | # keep AddSector up to date with this 569 | return 570 | 571 | @abc.abstractmethod 572 | def CreateWallPacker(self): 573 | # keep AddWall up to date with this 574 | return 575 | 576 | @abc.abstractmethod 577 | def CreateSpritePacker(self): 578 | # keep AddSprite up to date with this 579 | return 580 | 581 | def ReadHeaders(self) -> int: 582 | self.__dict__.update(self.headerPacker.unpack(self.data[:self.HEADER_SIZE])) 583 | return self.HEADER_SIZE 584 | 585 | def WriteHeaders(self) -> int: 586 | # TODO: Create header object 587 | newdata = self.headerPacker.pack(self.__dict__) 588 | self.data.extend(newdata) 589 | return len(newdata) 590 | 591 | def ReadNumSectors(self, start) -> int: 592 | stop = start + 2 593 | (self.num_sectors,) = struct.unpack(' int: 597 | new_data = struct.pack(' int: 602 | stop = start + 2 603 | (self.num_walls, ) = struct.unpack(' int: 607 | new_data = struct.pack(' int: 612 | stop = start + 2 613 | (self.num_sprites, ) = struct.unpack(' int: 617 | new_data = struct.pack(' int: 622 | GetSector = self.GetSector 623 | AppendSector = self.AppendSector 624 | for i in range(self.num_sectors): 625 | sector = GetSector(pos) 626 | AppendSector(sector) 627 | pos += sector.length 628 | return pos 629 | 630 | def WriteSector(self, sector: Sector): 631 | newdata = self.sectorPacker.pack(sector.__dict__) 632 | 633 | if self.crypt and self.version == 7: 634 | newdata = bytearray(newdata) 635 | newdata = MapCrypt(newdata, self.mapRevision * self.SECTOR_SIZE) 636 | 637 | if sector.extra > 0: 638 | newdata += sector.extraData 639 | self.data.extend(newdata) 640 | 641 | def WriteSectors(self, pos) -> int: 642 | WriteSector = self.WriteSector 643 | for sector in self.sectors: 644 | WriteSector(sector) 645 | pos += sector.length 646 | return pos 647 | 648 | def ReadWalls(self, pos) -> int: 649 | GetWall = self.GetWall 650 | AppendWall = self.AppendWall 651 | for i in range(self.num_walls): 652 | wall = GetWall(pos) 653 | AppendWall(wall) 654 | pos += wall.length 655 | return pos 656 | 657 | def WriteWall(self, wall: Wall): 658 | newdata = self.wallPacker.pack(wall.__dict__) 659 | 660 | if self.crypt and self.version == 7: 661 | newdata = bytearray(newdata) 662 | newdata = MapCrypt(newdata, (self.mapRevision * self.SECTOR_SIZE) | 0x7474614d) 663 | 664 | if wall.extra > 0: 665 | newdata += wall.extraData 666 | self.data.extend(newdata) 667 | 668 | def WriteWalls(self, pos) -> int: 669 | for wall in self.walls: 670 | self.WriteWall(wall) 671 | pos += wall.length 672 | return pos 673 | 674 | def ReadSprites(self, pos) -> int: 675 | GetSprite = self.GetSprite 676 | AppendSprite = self.AppendSprite 677 | for i in range(self.num_sprites): 678 | sprite = GetSprite(pos) 679 | AppendSprite(sprite) 680 | pos += sprite.length 681 | return pos 682 | 683 | def WriteSprite(self, sprite: Sprite): 684 | newdata = self.spritePacker.pack(sprite.__dict__) 685 | 686 | newdata = bytearray(newdata) 687 | if self.crypt and self.version == 7: 688 | newdata = MapCrypt(newdata, (self.mapRevision * self.SPRITE_SIZE) | 0x7474614d) 689 | 690 | if sprite.extra > 0: 691 | newdata.extend(sprite.extraData) 692 | self.data.extend(newdata) 693 | 694 | def WriteSprites(self, pos) -> int: 695 | WriteSprite = self.WriteSprite 696 | for sprite in self.sprites: 697 | WriteSprite(sprite) 698 | pos += sprite.length 699 | return pos 700 | 701 | @abc.abstractmethod 702 | def ReadData(self): 703 | return 704 | 705 | @abc.abstractmethod 706 | def WriteData(self): 707 | return 708 | 709 | def GetSectorInfo(self, sector:int) -> Sector: 710 | if sector in self.sectorCache: 711 | return self.sectorCache[sector] 712 | 713 | assert sector >= 0 714 | assert sector < len(self.sectors) 715 | 716 | wallptr = self.sectors[sector].wallptr 717 | numwalls = self.sectors[sector].wallnum 718 | 719 | walls = {} 720 | nearbySectors = set() 721 | shapes = [[]] 722 | for i in range(numwalls): 723 | w = self.walls[wallptr] 724 | nearbySectors.add(w.next_sector) 725 | walls[wallptr] = w.pos 726 | shapes[-1].append(w.pos) 727 | if w.next_wall in walls: 728 | shapes.append([]) 729 | wallptr += 1 730 | 731 | shapes.pop(-1) 732 | nearbySectors.discard(-1) 733 | nearbySectors.discard(sector) 734 | sect = Sector({'walls': walls, 'nearbySectors': nearbySectors, 'shapes': shapes}) 735 | self.sectorCache[sector] = sect 736 | return sect 737 | 738 | def GetContainingSectorNearby(self, sector:int, point) -> Union[int,None]: 739 | sectorInfo:Sector = self.GetSectorInfo(sector) 740 | if PointIsInSector(sectorInfo, point): 741 | return sector 742 | for sect2 in sectorInfo.nearbySectors: 743 | sectorInfo2:Sector = self.GetSectorInfo(sect2) 744 | if PointIsInSector(sectorInfo2, point): 745 | return sect2 746 | return None 747 | 748 | 749 | 750 | def PointIsInSector(sect:Sector, testpos:list) -> bool: 751 | intersects = 0 752 | for shape in sect.shapes: 753 | intersects = PointIsInShape(shape, testpos, intersects) 754 | return (intersects%2)==1 755 | 756 | 757 | def PointIsInShape(walls, p, intersects) -> int: 758 | # https://stackoverflow.com/a/2922778 759 | i=0 760 | n=len(walls) 761 | j=n-1 762 | while i < n: 763 | # ensure the wall straddles the point on the Y axis 764 | if ((walls[i][1] > p[1]) != (walls[j][1] > p[1])): 765 | # check slope? 766 | wallXSize = walls[j][0]-walls[i][0] 767 | wallYSize = walls[j][1]-walls[i][1] 768 | pointYDist = p[1]-walls[i][1] 769 | if p[0] < wallXSize * pointYDist / wallYSize + walls[i][0]: 770 | intersects += 1 771 | j=i 772 | i+=1 773 | return intersects 774 | 775 | 776 | def MapCrypt(data:bytearray, key:int) -> bytearray: 777 | # reversible/symmetrical 778 | for i in range(len(data)): 779 | data[i] = data[i] ^ (key & 0xff) 780 | key += 1 781 | return data 782 | 783 | def MirrorList(l): 784 | # ensure proper vertex order 785 | return l[0:1] + l[-1:0:-1] 786 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | --------------------------------------------------------------------------------