[
  {
    "path": ".gitattributes",
    "content": "* -text\n"
  },
  {
    "path": ".gitignore",
    "content": "*\n!*/\n!.gitignore\n!.gitattributes\n!*.v\n!*.w\n!*.pcf\n!*.ka\n!*.mu\n!*.args\n!*.h\n!*.glsl\n!*.sh\n!*.md\n!LICENSE\n!screenshot.png\n!data_gen/*.png\n!hw/build/unused.txt\n!textures/custom_*.png\ndata_gen/generated_block_info.mu\nhw/core.v\nhw/core_*.v\nhw/src/data_sim.w\nhw/src/firmware.w\nhw/src/static_data.w\n"
  },
  {
    "path": "LICENSE",
    "content": "Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "# FPGA craft\n\nA voxel game/Minecraft clone for the iCE40 UP5K FPGA (for the iCEBreaker board).\n\n## Disclaimer\n\nUse this project at your own risk. This project has had no real testing, and unlike typical software, it may have bugs that damage your hardware (board, N64 controller, etc.). Only use it if you're familiar with FPGA/HW dev and you understand the risks.\n\n## Screenshot\n\nNote: this repo *does not* contain any assets/textures, you need to provide these yourself (more details below). \n\n![image](screenshot.png \"Screenshot, made using the 'Unity' texture pack (see below)\")\n\n## Features\n\n* 3D voxel rendering on tiny FPGA!\n* 256x192 resolution (256x128 3D area), 30 fps, 12 bit color\n* Input via N64 controller\n* Real-time terrain streaming from flash memory\n* Placing and mining blocks\n* Terrain changes by player are saved back to flash\n* Max overworld size: 512x512x32 blocks (wraps at edges)\n* Offline terrain generator (run on PC, then upload terrain to flash) with multiple biomes/features (grass, forest, desert, snow, caves)\n* Low memory usage (15kb BRAM, 128kb SPRAM, 16MB flash)\n* Custom ray tracing GPU that handles ~1 million rays/second\n* Custom 16-bit CPU with its own instruction set, running at 32.625Mhz\n* Compiled firmware is ~5kb, written in custom Forth like assembly langage, compiled using custom assembler (\"kasm\")\n* Hardware design written in [Wyre, a custom hardware design language](https://github.com/nickmqb/wyre)\n* Fully dynamic hardware based lighting system\n* Day/night cycle (each full day is ~18 minutes)\n* Up to 128 textures (using palette based texture compression to save memory)\n* Dithering to emulate higher color bit depth\n* Animated textures (lava, portals)\n* Portals and multiple dimensions (though terrain gen for these is not implemented in this version, see note below)\n* Transparent water rendering (slightly hacky)\n* Underwater rendering & swim physics\n* Fly around using rockets (item)\n* Falling sand/gravel physics\n* Water/lava physics (limited to modified terrain chunks)\n* Noclip mode & debug info overlay (including player XYZ coords)\n* Inventory system\n\nNote: you may have seen (videos of) this project [on my twitter](https://twitter.com/nickmqb). This open source repo is a \"light version\" of the project, without the Minecraft specific terrain gen/biomes/structures.\n\n## Requirements\n\n* iCEBreaker board\n* VGA PMOD\n* VGA display\n* N64 controller (You don't need an original \"vintage\" controller. For example, I'm just using a cheap third party replica.)\n* Bring your own textures (see [Setting up textures](#setting-up-textures) below).\n\nIt should be possible to port the project to other boards/FPGAs, displays (e.g. using HDMI PMOD) and input devices (e.g. PS2 mouse/keyboard or GameCube controller). If you do, let me know and I'd be happy to add a link to your project.\n\n## Build steps\n\n### Preparation\n\n1. Disconnect any currently connected peripherals from board.\n1. Ensure yosys, nextpnr and icestorm are installed ([e.g. from here](https://github.com/esden/summon-fpga-tools)) and are available on your path.\n\n### Getting the code\n\n1. `git clone https://github.com/nickmqb/fpga_craft` (this repo) \n1. `git clone https://github.com/nickmqb/muon` and [follow the installation instructions](https://github.com/nickmqb/muon/blob/master/docs/getting_started.md).\n1. If not already done, move the Muon compiler binary `mu` to the `muon` directory (i.e. file path of the binary, including filename should be: `muon/mu`).\n1. `git clone https://github.com/nickmqb/wyre` and [follow the installation instructions](https://github.com/nickmqb/wyre/blob/master/docs/getting_started.md).\n1. If not already done, move the Wyre compiler binary `wyre` to the `wyre/compiler` directory (i.e. file path of the binary, including filename should be: `wyre/compiler/wyre`).\n\n### Setting up textures\n\nAs mentioned above, this repo does not include any textures (except for a few custom textures specifically made for this project). You need to provide your own. You have several options:\n\n* If you own Minecraft, find your Minecraft .jar file (e.g. `.minecraft/versions/{latest_version}/{version.jar}`). From the .jar file, extract all .png files from `assets/minecraft/textures/block` and copy them to `fpga_craft/textures`.\n* Download a Minecraft texture pack (e.g. [from here](https://www.curseforge.com/minecraft/texture-packs/sixteen-x?filter-game-version=&filter-sort=5)). This will be a .zip file with the same directory structure as the Minecraft .jar file. See the previous bullet point for which files to copy. Note: not all texture packs contain all required textures, so you may need to combine multiple packs. (Based on some quick experimentation, the [\"Unity\" pack](https://www.curseforge.com/minecraft/texture-packs/unity) works. The screenshot near the top of this doc was made with this pack.)\n* Create your own textures or use a different source (e.g. a [Minetest texture pack](https://content.minetest.net/packages/?type=txp&page=1&tag=16px)). Because the naming scheme of the texture filenames will likely be different, you will need to manually tweak `fpga_craft/block_info_gen/block_info_generator.mu` (namespace `Ids`) and provide the right filenames.\n\n### Building tools\n\n1. `cd fpga_craft`\n1. `cd bram_swap && ./build.sh && cd ..`\n1. `cd kasm && ./build.sh && cd ..`\n\n### Data gen\n\n1. `cd block_info_gen && ./run.sh && cd ..`\n1. `cd data_gen && ./run.sh && cd ..` (generates `fpga_craft/ram_a.bin` and `fpga_craft/textures.bin`)\n1. `iceprog -o 2048k ram_a.bin`\n1. `iceprog -o 2112k textures.bin`\n\n### Terrain gen\n\n1. Go to dir `fpga_craft/terrain_gen`\n1. `./build.sh`\n1. `./terrain_gen --dimension 1 --output overworld.bin` (Note: alternatively, you can use the OpenGL terrain_viewer for a preview of the generated terrain, see section below: [OpenGL terrain viewer: generating terrain](#opengl-terrain-viewer-generating-terrain))\n1. `./terrain_gen --dimension 2 --output dim2.bin` (\"Stub\" generator, also see [Multiple dimensions](#multiple-dimensions))\n1. `./terrain_gen --dimension 3 --output dim3.bin` (\"Stub\" generator)\n1. `iceprog -o 8192k overworld.bin` (file is 8MB, so this will take several minutes)\n1. `iceprog -o 4096k dim2.bin` (file is 0.5MB)\n1. `iceprog -o 6144k dim3.bin` (file is 2MB)\n\n### Building the hardware design\n\n1. Go to dir `fpga_craft/hw`\n1. By default, the code to save terrain changes to flash is commented out. You can choose to enable it.\n\t* To enable saving, overwrite `src/firmware.ka` with `src/firmware_save.ka`, i.e.: `cp src/firmware_save.ka src/firmware.ka`. Terrain changes are buffered in memory. The game automatically saves changes to flash, as needed, to keep the buffer from getting too full. Before quitting, you must manually save any remaining changes (see gameplay tips below). When the game is saving, a progress bar (consisting out of floppy disk icons) is shown in the top right. Saving is done when all floppy disks have vanished.\n\t* Keep an eye out for rapid flash usage bugs (though I didn't encounter any bugs like that so far). If the progress bar gets stuck and doesn't update at all for a long time (e.g. >10 seconds), the game may be stuck in a \"save loop\", you should disconnect power if that happens. Additionally: there are hardware counters that track the number of flash sector erase and page program operations, if you enable 'DEBUG INFO' in the game menu, these are shown on the 3rd line from the top (first 2 numbers). If these counters start going crazy, or if the game freezes, you should also disconnect power.\t\n\t* If you don't enable saving, the game buffers up to 32 changed terrain chunks (2x2) in memory. After that, subsequent placed blocks/changes will disappear as you move through the terrain. Note: if the game freezes, it's still a good idea to disconnect power; flash bugs are less likely if you don't enable saving but are still possible.\n1. `./build.sh` (builds FPGA bitstream; pay close attention to the result, may fail timing; if that happens, just re-run the command until you get a result that meets timing; may need to run a few times).\n1. When the design meets timing: `./prog.sh` (upload bitstream to FPGA)\n\n### Final steps\n\n1. Disconnect board from power\n1. Connect VGA and N64 controller according to pinout spec in `fpga_craft/hw/icebreaker_spi.pcf`\n1. Reconnect power\n1. Ready to play! (See below for controls and some useful gameplay tips)\n\n## Controls\n\n* Look around: stick\n* Move/strafe: C buttons\n* Jump: R\n* Place block: Z\n* Mine block: B (hold)\n* Select hotbar slot: DPAD left/right\n* Open door: A\n* Move down (noclip mode): A\n* Open/close inventory: L\n* Inventory, move cursor: C buttons\n* Inventory, select: A (or R)\n* Open/close game menu: Start\n* Game menu, move cursor: DPAD up/down\n* Game menu, select: A\n* Flying/boost: select rockets in hotbar, then: Z\n* When flying: brake: B\n\n## Gameplay tips\n\n* There is a day/night cycle. If it gets dark and you want to skip the night, hit Start, then select 'TIME' and hit A a bunch of times (TIME 0x10-0x80 = day, TIME 0x90-0x00 = night).\n* If you enabled saving (see instructions above), before quitting, hit Start on the controller, then select 'SAVE XY CHUNKS' to save remaining changes to flash. A progress bar (consisting out of floppy disk icons) is shown in the top right; saving is done when all floppy disks have vanished.\n\n## Optional steps\n\n### Changing the firmware\n\n1. Go to dir `fpga_craft/hw`\n1. Modify `src/firmware.ka`, e.g. to change controls or game logic.\n1. `./bfw.sh` (compiles the firmware to `src/firmware.w`, then modifies the bitstream directly; this avoids synthesis & routing stages to allow quick iteration on the firmware)\n1. `./prog.sh` to upload bitstream to FPGA.\n\n### Changing the hardware design (.w)\n\nThe HW design is written in [Wyre](https://github.com/nickmqb/wyre).\n\n*Important*: to avoid errors, set your tab size to 4 when editing .w files. (Wyre uses significant whitespace, but the feature still needs more work; this is the easiest workaround for now.)\n\n### Changing other tools (.mu)\n\nThe other tools in this repo are written in [Muon](https://github.com/nickmqb/muon). \n\n*Important*: to avoid errors, set your tab size to 4 when editing .mu files. (Muon uses significant whitespace, but the feature still needs more work; this is the easiest workaround for now.)\n\n### OpenGL terrain viewer: set up\n\n1. Go back to base directory (i.e. directory with `fpga_craft`, `muon`, etc.) \n1. `git clone https://github.com/nickmqb/muon_gfx` and [follow the setup instructions for sdl_bindings](https://github.com/nickmqb/muon_gfx/tree/master/sdl_bindings). Note: the `SDL2` directory should be a subdirectory of the `sdl_bindings` directory.\n1. `cd fpga_craft/terrain_viewer`\n1. `./build.sh`\n\n### OpenGL terrain viewer: generating terrain\n\n1. Ensure previous section is done.\n1. `./terrain_viewer --dimension 1 --output overworld.bin`\n1. Fly around with WASD/space/C. Look around with arrow keys. Move slowly by holding shift.\n1. To generate a new random world, press F3.\n1. To save the world to the output path, press F12 (you must do this before exiting, otherwise output file will not be written).\n1. The tool never frees memory, and will crash if you generate a lot of random worlds -- just restart in that case (\"good enough, ship it!\" ;)).\n\n### OpenGL terrain viewer: viewing terrain\n\n1. After playing, download modified world from flash. E.g.: `iceprog -o 8192k -R 8192k overworld_device.bin`\n1. `./terrain_viewer --input overworld_device.bin`\n1. Fly around with WASD/space/C. Look around with arrow keys. Move slowly by holding shift.\n\n### Adding new blocks/textures\n\nThere currently is room for ~75 additional textures. To add new blocks/textures:\n\n1. Modify `block_info_gen/block_info_generator.mu`. Add the textures under `Ids`, then add the block definitions in function `BlockInfoGenerator.generate`.\n1. Run block_info_gen.\n1. Add the new blocks to the inventory in `data_gen/data_generator.mu` (function `buildInventory`).\n1. Run data_gen, reupload ram_a.bin and textures.bin, and rebuild and reupload the firmware.\n\n### Multiple dimensions\n\nThe game supports multiple dimensions, though terrain gen is only implemented for the overworld.\n\n* Dimension 1: 512x512x32 (overworld)\n* Dimension 2: 128x128x32 (access by building an obsidian portal (like Nether portal in Minecraft))\n* Dimension 3: 256x256x32 (access only through portal_3 block; can be enabled by adding the block to the inventory in `data_gen/data_generator.mu` (function `buildInventory`), or modifying terrain gen).\n\n### Map file format\n\nEach map consists of a series of 128 byte chunks. There is no header.\n\nA chunk consists of 128 blocks. It has a base of 2x2 blocks (x, z) and a height of 32 blocks (y). 1 block = 1 byte. After running the block_info_generator, `block_info_generator/block_info.txt` contains the mapping from byte value to block type.\n\nThe offset (in bytes) of a block within a chunk has the bit pattern: `yyyyyzx` (rightmost bit is LSB, e.g. x=0, z=1, y=2 -> offset=10)\n\nThe offset (in whole chunks) of a chunk within a map file has the bit pattern: `zxzx xxxz zzzz zxxx` (rightmost bit is LSB, this pattern is used to ensure good data locality).\n\n## License & acknowledgements\n\nSee [LICENSE](LICENSE).\n\nstb_image.h: [https://github.com/nothings/stb](https://github.com/nothings/stb)\n\ntextures/custom_cracked.png: from [\"Pixel pack\" texture pack for Minetest by isaiah658](https://content.minetest.net/packages/isaiah658/the_pixel_pack/) (modified)\n"
  }
]