Import from local repo

This commit is contained in:
spicyjpeg 2023-05-30 18:08:52 +02:00
parent 64085be4bb
commit 4bed3c7f12
No known key found for this signature in database
GPG Key ID: 5CC87404C01DF393
84 changed files with 24281 additions and 2 deletions

13
.gitignore vendored Normal file
View File

@ -0,0 +1,13 @@
# Do not include any hidden metadata saved by apps and the OS.
desktop.ini
.DS_Store
.vscode/
# Do not include any built or cached files.
build/
__pycache__/
*.pyc
*.pyo
# Do not include the dumps used to generate the cartdb files.
#dumps/

105
CMakeLists.txt Normal file
View File

@ -0,0 +1,105 @@
cmake_minimum_required(VERSION 3.25)
set(CMAKE_TOOLCHAIN_FILE "${CMAKE_CURRENT_LIST_DIR}/cmake/toolchain.cmake")
project(
cart_tool_private
LANGUAGES C CXX ASM
VERSION 0.3.0
DESCRIPTION "Konami System 573 security cartridge tool"
)
find_package(Python3 REQUIRED COMPONENTS Interpreter)
## Main executable
add_executable(
cart_tool
src/asset.cpp
src/cart.cpp
src/cartdb.cpp
src/gpu.cpp
src/io.cpp
src/main.cpp
src/pad.cpp
src/spu.cpp
src/uibase.cpp
src/uicommon.cpp
src/util.cpp
src/zs01.cpp
src/app/actions.cpp
src/app/app.cpp
src/app/misc.cpp
src/app/unlock.cpp
src/libc/crt0.c
src/libc/cxxsupport.cpp
src/libc/malloc.c
src/libc/memset.s
src/libc/misc.c
src/libc/misc.s
src/libc/string.c
src/ps1/pcdrv.s
src/ps1/system.c
src/ps1/system.s
src/ps1/unhandledexc.c
src/vendor/miniz.c
src/vendor/printf.c
src/vendor/qrcodegen.c
)
target_include_directories(
cart_tool PRIVATE
src
src/libc
)
target_compile_definitions(
cart_tool PRIVATE
VERSION="${PROJECT_VERSION}"
#ENABLE_ARGV=1
ENABLE_PS1_CONTROLLER=1
MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS=1
MINIZ_NO_ARCHIVE_WRITING_APIS=1
MINIZ_NO_STDIO=1
MINIZ_NO_TIME=1
PRINTF_DISABLE_SUPPORT_FLOAT=1
)
add_custom_command(
TARGET cart_tool POST_BUILD
COMMAND
"${Python3_EXECUTABLE}" "${PROJECT_SOURCE_DIR}/tools/convertExecutable.py"
$<TARGET_FILE:cart_tool> cart_tool.psexe
BYPRODUCTS cart_tool.psexe
COMMENT "Converting executable"
)
## Default resource archive
add_custom_command(
COMMAND
"${Python3_EXECUTABLE}" "${PROJECT_SOURCE_DIR}/tools/buildResourceArchive.py"
"${PROJECT_SOURCE_DIR}/resources.json" resources.zip
OUTPUT resources.zip
DEPENDS resources.json
COMMENT "Building resource archive"
)
ps1_target_incbin(
cart_tool PRIVATE
.rodata _resources _resourcesSize
"${PROJECT_BINARY_DIR}/resources.zip"
)
## CD-ROM image
#configure_file(assets/cdreadme.txt cdreadme.txt NEWLINE_STYLE CRLF)
#add_custom_command(
# COMMAND
# "${Python3_EXECUTABLE}" "${PROJECT_SOURCE_DIR}/tools/buildCDImage.py"
# "${PROJECT_SOURCE_DIR}/cd.json" cart_tool.iso
# OUTPUT cart_tool.iso
# DEPENDS cd.json cart_tool
# COMMENT "Building CD-ROM image"
#)
# Add a dummy target that depends on the CD image to make sure it gets built.
#add_custom_target(cd ALL DEPENDS cart_tool.iso)

30
CMakePresets.json Normal file
View File

@ -0,0 +1,30 @@
{
"version": 6,
"cmakeMinimumRequired": {
"major": 3,
"minor": 25,
"patch": 0
},
"configurePresets": [
{
"name": "debug",
"displayName": "Debug build",
"description": "Build the project with -Og and assertions enabled.",
"generator": "Ninja",
"binaryDir": "${sourceDir}/build",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Debug"
}
},
{
"name": "release",
"displayName": "Release build",
"description": "Build the project with -O2 and assertions disabled.",
"generator": "Ninja",
"binaryDir": "${sourceDir}/build",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Release"
}
}
]
}

View File

@ -1,2 +1,36 @@
# cart-tool-private
System 573 security cartridge tool # Konami System 573 security cartridge tool
## Building
The following dependencies are required in order to build the project:
- CMake 3.25 or later;
- Python 3.10 or later;
- [Ninja](https://ninja-build.org/);
- a recent version of the GCC toolchain that targets the `mipsel-none-elf`
architecture.
The toolchain can be installed on Windows, Linux or macOS by following the
instructions [here](https://github.com/grumpycoders/pcsx-redux/blob/main/src/mips/psyqo/GETTING_STARTED.md#the-toolchain)
and should be added to `PATH`. The other dependencies can be installed through a
package manager.
The Python script used to convert images at build time requires additional
dependencies which can be installed by running:
```
py -m pip install -r tools/requirements.txt (Windows)
sudo pip install -r tools/requirements.txt (Linux/macOS)
```
Once all prerequisites are installed, the tool can be built in debug mode (with
command-line argument parsing disabled and serial port logging enabled by
default) by running:
```
cmake --preset debug
cmake --build ./build
```
Replace `debug` with `release` to build in release mode.

149
assets/app.strings.json Normal file
View File

@ -0,0 +1,149 @@
{
"App": {
"cartDetectWorker": {
"readDigitalIO": "Retrieving digital I/O board ID...",
"identifyCart": "Identifying security cartridge...",
"readCart": "Reading security cartridge...",
"identifyGame": "Attempting to identify game..."
},
"cartUnlockWorker": {
"read": "Dumping cartridge...",
"identify": "Attempting to identify game..."
},
"qrCodeWorker": {
"compress": "Compressing cartridge dump...",
"generate": "Generating QR code..."
}
},
"ButtonMappingScreen": {
"title": "{CART_ICON} Select button mapping",
"prompt": "Use {START_BUTTON} or the Test button to select a mapping preset suitable for your cabinet or JAMMA setup. Other buttons will be enabled once a mapping is selected.",
"itemPrompt": "{RIGHT_ARROW} Press and hold {START_BUTTON} or Test to confirm",
"joystick": "JAMMA supergun or joystick/buttons",
"ddrCab": "Dance Dance Revolution (2-player) cabinet",
"ddrSoloCab": "Dance Dance Revolution Solo cabinet",
"dmCab": "DrumMania or PercussionFreaks cabinet",
"dmxCab": "Dance Maniax cabinet"
},
"CartActionsScreen": {
"title": "{CART_ICON} Cartridge options",
"itemPrompt": "{RIGHT_ARROW} Press {START_BUTTON} to confirm, hold {LEFT_BUTTON} + {RIGHT_BUTTON} to go back",
"qrDump": {
"name": "Dump cartridge as QR code",
"prompt": "Generate a QR code encoding the contents of the cartridge's EEPROM in compressed format. The code can be scanned and decoded to a raw dump."
},
"hexdump": {
"name": "View cartridge hexdump",
"prompt": "Display the raw contents of the cartridge's EEPROM."
},
"resetSystemID": {
"name": "Reset system identifier (unpair cartridge)",
"prompt": "Delete any previously saved system identifier, allowing the cartridge to be used to reinstall the game on any system."
},
"editSystemID": {
"name": "Edit system identifier (pair to another 573)",
"prompt": "Edit the saved system identifier to allow the cartridge to be used on a specific system without having to reinstall the game first."
},
"reflash": {
"name": "Erase and reflash cartridge",
"prompt": "Wipe all data and flash the cartridge with another game's identifiers. All cartridges can be converted for use with any other game that uses the same cartridge type."
},
"erase": {
"name": "Erase cartridge",
"prompt": "Wipe all data including game identifiers. Erased cartridges can be flashed for use with games unsupported by this tool using a master calendar."
}
},
"CartInfoScreen": {
"title": "{CART_ICON} Cartridge information",
"digitalIOInfo": "Digital I/O ID:\t%s\nDigital I/O SN:\t%s\n\n",
"cartInfo": "Cartridge type:\t%s\nUnlock status:\t%s\nDS2401 identifier:\t%s\nZS01 identifier:\t%s\n\n",
"id": {
"error": "read failure",
"noSystemID": "no digital I/O board",
"noCartID": "cartridge has no DS2401",
"noZSID": "not a ZS01 cartridge"
},
"unlockStatus": {
"locked": "{CLOSED_LOCK} locked, game key required",
"unlocked": "{OPEN_LOCK} unlocked"
},
"description": {
"noCart": "No supported cartridge has been found.\n\nTurn off the system and insert a security cartridge in order to continue. DO NOT HOTPLUG CARTRIDGES; hotplugging may damage both the 573 and the cartridge.\n\nIf a cartridge is inserted but not detected, try cleaning its pins as well as the system's security cartridge connector.",
"initError": "Failed to initialize and read unprotected data from this cartridge.\n\nTurn off the system and make sure the cartridge is inserted correctly. If this issue persists, try using another cartridge of the same type.",
"locked": {
"unidentified": "This cartridge contains data for an unsupported game.\n\nAs the cartridge is currently locked, you will have to manually select which game it belongs to in order to dump its contents or reflash it for use with a supported game, as each game has a different unlocking key.",
"identified": "This cartridge has been identified as:\n %s\n\nIf this is correct, you may proceed to unlock the cartridge using the appropriate key for this game in order to access and modify its contents.",
"unknown": "This cartridge cannot be identified without unlocking it first.\n\nYou will have to manually select which game it belongs to in order to dump its contents or reflash it for use with a supported game, as each game has a different unlocking key."
},
"unlocked": {
"unidentified": "This cartridge contains data for an unsupported game.\n\nThe system identifier (if any) cannot be reset or edited, however you may still dump the cartridge's contents or reflash it for use with a supported game.",
"identified": "This cartridge has been identified as:\n %s\n\nYou may now proceed to reset the system identifier, edit it or erase and reflash the cartridge for use with another game.",
"blank": "This cartridge has been previously erased and is now blank.\n\nIt must be flashed and optionally initialized with a system identifier in order to be used with a supported game."
}
},
"prompt": {
"locked": "Press {START_BUTTON} to proceed to unlock the cartridge.",
"unlocked": "Press {START_BUTTON} to continue.",
"error": "Press the Test button to view debug logs."
},
"x76f041": {
"name": "{CHIP_ICON} Xicor X76F041",
"warning": "X76F041 cartridges keep track of how many times a wrong key has been used. If too many unlock attempts fail, they will lock out any further access and thus become PERMANENTLY BRICKED, with no way to restore access.\n\nAre you sure the game/key is correct?"
},
"x76f100": {
"name": "{CHIP_ICON} Xicor X76F100",
"warning": "X76F100 and ZS01 cartridges keep track of how many times a wrong key has been used. If too many unlock attempts fail, the cartridge will self-erase and will have to be reinitialized to factory data and paired to the system again if the game requires it.\n\nAre you sure the game/key is correct?"
},
"zs01": {
"name": "{CHIP_ICON} Konami ZS01 (PIC16CE625)",
"desc": null,
"warning": "X76F100 and ZS01 cartridges keep track of how many times a wrong key has been used. If too many unlock attempts fail, the cartridge will self-erase and will have to be reinitialized to factory data and paired to the system again if the game requires it.\n\nAre you sure the game/key is correct?"
}
},
"QRCodeScreen": {
"title": "{CART_ICON} Cartridge dump",
"prompt": "Scan this code and paste the resulting string into the decodeDump.py script provided alongside this tool to obtain a dump of the cartridge. Press {START_BUTTON} to go back."
},
"UnlockConfirmScreen": {
"title": "Warning",
"no": "No, go back",
"yes": "Yes, continue"
},
"UnlockErrorScreen": {
"title": "Error",
"ok": "{START_BUTTON} Continue"
},
"UnlockKeyScreen": {
"title": "{CART_ICON} Select unlocking key",
"prompt": "If the cartridge has been converted before, select the game it was last converted to.",
"itemPrompt": "{RIGHT_ARROW} Press {START_BUTTON} to confirm, hold {LEFT_BUTTON} + {RIGHT_BUTTON} to go back",
"autoUnlock": "Use identified game key",
"customKey": "Enter key manually...",
"nullKey": "Use null key (00-00-00-00-00-00-00-00)"
},
"WarningScreen": {
"title": "Warning",
"body": "This tool is experimental and provided with no warranty whatsoever. It is not guaranteed to work and improper usage may PERMANENTLY BRICK your System 573 security cartridges.\n\nUse this tool at your own risk. Do not proceed if you do not know what you are doing.",
"cooldown": "Wait... (%ds)",
"ok": "{START_BUTTON} Continue"
},
"WorkerStatusScreen": {
"title": "Working..."
}
}

16
assets/cdreadme.txt Normal file
View File

@ -0,0 +1,16 @@
Konami System 573 security cartridge reset tool
===============================================
Version ${PROJECT_VERSION}
Use this disc by simply putting it into your 573; make sure DIP switch 4 (the
rightmost one) is off. Remember to insert the cartridge you want to reset or
dump prior to turning on the system.
More information and source code are available at:
${PROJECT_HOMEPAGE_URL}
WARNING: This tool is experimental and provided with no warranty whatsoever. It
is not guaranteed to work and improper usage can PERMANENTLY BRICK your System
573 security cartridges. Use this tool at your own risk.

91
assets/licenses.txt Normal file
View File

@ -0,0 +1,91 @@
# miniz
# https://github.com/richgel999/miniz
Copyright 2013-2014 RAD Game Tools and Valve Software
Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC
All Rights Reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
# printf
# https://github.com/mpaland/printf
The MIT License (MIT)
Copyright (c) 2014 Marco Paland
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# ps1-bare-metal
# https://github.com/spicyjpeg/ps1-bare-metal
ps1-bare-metal - (C) 2023 spicyjpeg
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
# qrcodegen
# https://www.nayuki.io/page/qr-code-generator-library
Copyright (c) 2022 Project Nayuki. (MIT License)
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
* The Software is provided "as is", without warranty of any kind, express or
implied, including but not limited to the warranties of merchantability,
fitness for a particular purpose and noninfringement. In no event shall the
authors or copyright holders be liable for any claim, damages or other
liability, whether in an action of contract, tort or otherwise, arising from,
out of or in connection with the Software or the use or other dealings in the
Software.

BIN
assets/sounds/click.vag Normal file

Binary file not shown.

BIN
assets/sounds/enter.vag Normal file

Binary file not shown.

BIN
assets/sounds/exit.vag Normal file

Binary file not shown.

BIN
assets/sounds/move.vag Normal file

Binary file not shown.

BIN
assets/sounds/move_left.vag Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 636 B

View File

@ -0,0 +1,111 @@
{
" ": { "x": 0, "y": 0, "width": 4, "height": 9 },
"!": { "x": 6, "y": 0, "width": 2, "height": 9 },
"\"": { "x": 12, "y": 0, "width": 4, "height": 9 },
"#": { "x": 18, "y": 0, "width": 6, "height": 9 },
"$": { "x": 24, "y": 0, "width": 6, "height": 9 },
"%": { "x": 30, "y": 0, "width": 6, "height": 9 },
"&": { "x": 36, "y": 0, "width": 6, "height": 9 },
"'": { "x": 42, "y": 0, "width": 2, "height": 9 },
"(": { "x": 48, "y": 0, "width": 3, "height": 9 },
")": { "x": 54, "y": 0, "width": 3, "height": 9 },
"*": { "x": 60, "y": 0, "width": 4, "height": 9 },
"+": { "x": 66, "y": 0, "width": 6, "height": 9 },
",": { "x": 72, "y": 0, "width": 3, "height": 9 },
"-": { "x": 78, "y": 0, "width": 6, "height": 9 },
".": { "x": 84, "y": 0, "width": 2, "height": 9 },
"/": { "x": 90, "y": 0, "width": 6, "height": 9 },
"0": { "x": 0, "y": 9, "width": 6, "height": 9 },
"1": { "x": 6, "y": 9, "width": 6, "height": 9 },
"2": { "x": 12, "y": 9, "width": 6, "height": 9 },
"3": { "x": 18, "y": 9, "width": 6, "height": 9 },
"4": { "x": 24, "y": 9, "width": 6, "height": 9 },
"5": { "x": 30, "y": 9, "width": 6, "height": 9 },
"6": { "x": 36, "y": 9, "width": 6, "height": 9 },
"7": { "x": 42, "y": 9, "width": 6, "height": 9 },
"8": { "x": 48, "y": 9, "width": 6, "height": 9 },
"9": { "x": 54, "y": 9, "width": 6, "height": 9 },
":": { "x": 60, "y": 9, "width": 2, "height": 9 },
";": { "x": 66, "y": 9, "width": 3, "height": 9 },
"<": { "x": 72, "y": 9, "width": 6, "height": 9 },
"=": { "x": 78, "y": 9, "width": 6, "height": 9 },
">": { "x": 84, "y": 9, "width": 6, "height": 9 },
"?": { "x": 90, "y": 9, "width": 6, "height": 9 },
"@": { "x": 0, "y": 18, "width": 6, "height": 9 },
"A": { "x": 6, "y": 18, "width": 6, "height": 9 },
"B": { "x": 12, "y": 18, "width": 6, "height": 9 },
"C": { "x": 18, "y": 18, "width": 6, "height": 9 },
"D": { "x": 24, "y": 18, "width": 6, "height": 9 },
"E": { "x": 30, "y": 18, "width": 6, "height": 9 },
"F": { "x": 36, "y": 18, "width": 6, "height": 9 },
"G": { "x": 42, "y": 18, "width": 6, "height": 9 },
"H": { "x": 48, "y": 18, "width": 6, "height": 9 },
"I": { "x": 54, "y": 18, "width": 4, "height": 9 },
"J": { "x": 60, "y": 18, "width": 5, "height": 9 },
"K": { "x": 66, "y": 18, "width": 6, "height": 9 },
"L": { "x": 72, "y": 18, "width": 6, "height": 9 },
"M": { "x": 78, "y": 18, "width": 6, "height": 9 },
"N": { "x": 84, "y": 18, "width": 6, "height": 9 },
"O": { "x": 90, "y": 18, "width": 6, "height": 9 },
"P": { "x": 0, "y": 27, "width": 6, "height": 9 },
"Q": { "x": 6, "y": 27, "width": 6, "height": 9 },
"R": { "x": 12, "y": 27, "width": 6, "height": 9 },
"S": { "x": 18, "y": 27, "width": 6, "height": 9 },
"T": { "x": 24, "y": 27, "width": 6, "height": 9 },
"U": { "x": 30, "y": 27, "width": 6, "height": 9 },
"V": { "x": 36, "y": 27, "width": 6, "height": 9 },
"W": { "x": 42, "y": 27, "width": 6, "height": 9 },
"X": { "x": 48, "y": 27, "width": 6, "height": 9 },
"Y": { "x": 54, "y": 27, "width": 6, "height": 9 },
"Z": { "x": 60, "y": 27, "width": 6, "height": 9 },
"[": { "x": 66, "y": 27, "width": 3, "height": 9 },
"\\": { "x": 72, "y": 27, "width": 6, "height": 9 },
"]": { "x": 78, "y": 27, "width": 3, "height": 9 },
"^": { "x": 84, "y": 27, "width": 4, "height": 9 },
"_": { "x": 90, "y": 27, "width": 6, "height": 9 },
"`": { "x": 0, "y": 36, "width": 3, "height": 9 },
"a": { "x": 6, "y": 36, "width": 6, "height": 9 },
"b": { "x": 12, "y": 36, "width": 6, "height": 9 },
"c": { "x": 18, "y": 36, "width": 6, "height": 9 },
"d": { "x": 24, "y": 36, "width": 6, "height": 9 },
"e": { "x": 30, "y": 36, "width": 6, "height": 9 },
"f": { "x": 36, "y": 36, "width": 5, "height": 9 },
"g": { "x": 42, "y": 36, "width": 6, "height": 9 },
"h": { "x": 48, "y": 36, "width": 5, "height": 9 },
"i": { "x": 54, "y": 36, "width": 2, "height": 9 },
"j": { "x": 60, "y": 36, "width": 4, "height": 9 },
"k": { "x": 66, "y": 36, "width": 5, "height": 9 },
"l": { "x": 72, "y": 36, "width": 2, "height": 9 },
"m": { "x": 78, "y": 36, "width": 6, "height": 9 },
"n": { "x": 84, "y": 36, "width": 5, "height": 9 },
"o": { "x": 90, "y": 36, "width": 6, "height": 9 },
"p": { "x": 0, "y": 45, "width": 6, "height": 9 },
"q": { "x": 6, "y": 45, "width": 6, "height": 9 },
"r": { "x": 12, "y": 45, "width": 6, "height": 9 },
"s": { "x": 18, "y": 45, "width": 6, "height": 9 },
"t": { "x": 24, "y": 45, "width": 5, "height": 9 },
"u": { "x": 30, "y": 45, "width": 5, "height": 9 },
"v": { "x": 36, "y": 45, "width": 6, "height": 9 },
"w": { "x": 42, "y": 45, "width": 6, "height": 9 },
"x": { "x": 48, "y": 45, "width": 6, "height": 9 },
"y": { "x": 54, "y": 45, "width": 6, "height": 9 },
"z": { "x": 60, "y": 45, "width": 5, "height": 9 },
"{": { "x": 66, "y": 45, "width": 4, "height": 9 },
"|": { "x": 72, "y": 45, "width": 2, "height": 9 },
"}": { "x": 78, "y": 45, "width": 4, "height": 9 },
"~": { "x": 84, "y": 45, "width": 6, "height": 9 },
"\u007f": { "x": 90, "y": 45, "width": 6, "height": 9 },
"\u0080": { "x": 0, "y": 54, "width": 6, "height": 9 },
"\u0081": { "x": 6, "y": 54, "width": 6, "height": 9 },
"\u0082": { "x": 12, "y": 54, "width": 4, "height": 9 },
"\u0083": { "x": 18, "y": 54, "width": 4, "height": 9 },
"\u0084": { "x": 24, "y": 54, "width": 7, "height": 9, "icon": true },
"\u0085": { "x": 31, "y": 54, "width": 7, "height": 9, "icon": true },
"\u0086": { "x": 38, "y": 54, "width": 9, "height": 9, "icon": true },
"\u0087": { "x": 47, "y": 54, "width": 8, "height": 10, "icon": true },
"\u0088": { "x": 55, "y": 54, "width": 11, "height": 10, "icon": true },
"\u0089": { "x": 66, "y": 54, "width": 12, "height": 10, "icon": true },
"\u008a": { "x": 78, "y": 54, "width": 14, "height": 10, "icon": true }
}

BIN
assets/textures/font.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

106
cmake/executable.ld Normal file
View File

@ -0,0 +1,106 @@
/*
* ps1-bare-metal - (C) 2023 spicyjpeg
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
* INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
* LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
OUTPUT_FORMAT(elf32-littlemips)
ENTRY(_start)
MEMORY {
KERNEL_RAM (rwx) : ORIGIN = 0x80000000, LENGTH = 0x010000
APP_RAM (rwx) : ORIGIN = 0x80010000, LENGTH = 0x7f0000
}
SECTIONS {
/* Code sections */
.text : {
*(.text .text.* .gnu.linkonce.t.*)
*(.plt .MIPS.stubs)
} > APP_RAM
.rodata : {
*(.rodata .rodata.* .gnu.linkonce.r.*)
} > APP_RAM
/* Global constructor/destructor arrays */
. = ALIGN((. != 0) ? 4 : 1);
_preinitArrayStart = .;
.preinit_array : {
KEEP(*(.preinit_array))
}
_preinitArrayEnd = .;
_initArrayStart = .;
.init_array : {
KEEP(*(SORT(.init_array.*) SORT(.ctors.*)))
KEEP(*(.init_array .ctors))
} > APP_RAM
_initArrayEnd = .;
_finiArrayStart = .;
.fini_array : {
KEEP(*(.fini_array .dtors))
KEEP(*(SORT(.fini_array.*) SORT(.dtors.*)))
} > APP_RAM
_finiArrayEnd = .;
/* Data sections */
.data : {
*(.data .data.* .gnu.linkonce.d.*)
} > APP_RAM
/*
* Set _gp (copied to $gp) to point to the beginning of .sdata plus 0x8000,
* so anything within .sdata and .sbss can be accessed using the $gp
* register as base plus a signed 16-bit immediate.
*/
_gp = ALIGN(16) + 0x7ff0;
.sdata : {
*(.sdata .sdata.* .gnu.linkonce.s.*)
} > APP_RAM
. = ALIGN((. != 0) ? 4 : 1);
_bssStart = .;
.sbss (NOLOAD) : {
*(.sbss .sbss.* .gnu.linkonce.sb.*)
*(.scommon)
} > APP_RAM
.bss (NOLOAD) : {
*(.bss .bss.* .gnu.linkonce.b.*)
*(COMMON)
} > APP_RAM
. = ALIGN((. != 0) ? 4 : 1);
_bssEnd = .;
/* Dummy sections */
.dummy (NOLOAD) : {
KEEP(*(.dummy))
} > APP_RAM
/DISCARD/ : {
*(.gnu.lto_*)
}
}

136
cmake/setup.cmake Normal file
View File

@ -0,0 +1,136 @@
# ps1-bare-metal - (C) 2023 spicyjpeg
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
# AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
# OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
# PERFORMANCE OF THIS SOFTWARE.
cmake_minimum_required(VERSION 3.25)
# Override the default file extensions for executables and libraries. This is
# not strictly required, but it makes CMake's behavior more consistent.
set(CMAKE_EXECUTABLE_SUFFIX .elf)
set(CMAKE_STATIC_LIBRARY_PREFIX lib)
set(CMAKE_STATIC_LIBRARY_SUFFIX .a)
# Add libgcc.a (-lgcc) to the set of libraries linked to all executables by
# default. This library ships with GCC and must be linked to anything compiled
# with it.
link_libraries(-lgcc)
# Create a dummy "flags" library that is not made up of any files, but adds the
# appropriate compiler and linker flags for PS1 executables to anything linked
# to it. The library is then added to the default set of libraries.
add_library (flags INTERFACE)
link_libraries(flags)
target_compile_options(
flags INTERFACE
-g
-Wall
-Wa,--strip-local-absolute
-ffreestanding
-fno-builtin
-fno-pic
-nostdlib
-fdata-sections
-ffunction-sections
-fsigned-char
-fno-strict-overflow
-msoft-float
-march=r3000
-mabi=32
-mno-mt
-mno-llsc
-mno-abicalls
-mgpopt
-mno-extern-sdata
-G8
$<$<COMPILE_LANGUAGE:CXX>:
# These options will only be added when compiling C++ source files.
-fno-exceptions
-fno-rtti
-fno-unwind-tables
-fno-threadsafe-statics
-fno-use-cxa-atexit
>
$<IF:$<CONFIG:Debug>,
# These options will only be added if CMAKE_BUILD_TYPE is set to Debug.
-Og
-mdivide-breaks
,
# These options will be added if CMAKE_BUILD_TYPE is not set to Debug.
-O2
#-flto
>
)
target_link_options(
flags INTERFACE
-static
-nostdlib
-Wl,-gc-sections
-G8
-T${CMAKE_CURRENT_LIST_DIR}/executable.ld
)
# Define a new ps1_target_incbin() command to embed the contents of a binary
# file into an executable. This is accomplished by generating an assembly
# listing that uses the .incbin directive to embed the file from a template.
function(ps1_target_incbin
target type section symbolName sizeSymbolName path
)
string(MAKE_C_IDENTIFIER "${symbolName}" _symbolName)
string(MAKE_C_IDENTIFIER "${sizeSymbolName}" _sizeSymbolName)
string(MAKE_C_IDENTIFIER "${section}" _section)
cmake_path(ABSOLUTE_PATH path OUTPUT_VARIABLE _path)
# Generate a unique name for the assembly file by hashing the target name
# and symbol name, and place it in the current build directory.
string(SHA1 _hash "${target} ${_symbolName}")
set(_assemblyFile "${CMAKE_CURRENT_BINARY_DIR}/incbin_${_hash}.s")
file(
CONFIGURE
OUTPUT "${_assemblyFile}"
CONTENT [[
.section ${_section}.${_symbolName}, "aw"
.balign 8
.global ${_symbolName}
.local ${_symbolName}_end
.type ${_symbolName}, @object
.size ${_symbolName}, (${_symbolName}_end - ${_symbolName})
${_symbolName}:
.incbin "${_path}"
${_symbolName}_end:
.section ${_section}.${_sizeSymbolName}, "aw"
.balign 4
.global ${_sizeSymbolName}
.type ${_sizeSymbolName}, @object
.size ${_sizeSymbolName}, 4
${_sizeSymbolName}:
.int (${_symbolName}_end - ${_symbolName})
]]
ESCAPE_QUOTES
NEWLINE_STYLE LF
)
# Add the assembly file to the target and add the embedded binary file as a
# dependency to make sure it is built first if it needs to be built.
target_sources("${target}" "${type}" "${_assemblyFile}")
set_source_files_properties(
"${_assemblyFile}" PROPERTIES OBJECT_DEPENDS "${_path}"
)
endfunction()

90
cmake/toolchain.cmake Normal file
View File

@ -0,0 +1,90 @@
# ps1-bare-metal - (C) 2023 spicyjpeg
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
# AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
# OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
# PERFORMANCE OF THIS SOFTWARE.
cmake_minimum_required(VERSION 3.25)
# Create two user-editable variables to allow for a custom compiler toolchain to
# be used by passing -DTOOLCHAIN_PATH=... and -DTOOLCHAIN_TARGET=... to CMake.
set(
TOOLCHAIN_PATH "" CACHE PATH
"Directory containing GCC toolchain executables (if not listed in PATH)"
)
set(
TOOLCHAIN_TARGET mipsel-none-elf CACHE STRING
"GCC toolchain target triplet"
)
# Prevent CMake from using any host compiler by manually overriding the platform
# and setting it to "generic" (i.e. no defaults).
set(CMAKE_SYSTEM_NAME Generic)
set(CMAKE_SYSTEM_PROCESSOR mipsel)
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
# Tell CMake not to run the linker when testing the toolchain and to pass our
# custom variables through to autogenerated "compiler test" projects. This will
# prevent the compiler detection process from erroring out.
set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY)
set(CMAKE_TRY_COMPILE_PLATFORM_VARIABLES TOOLCHAIN_PATH TOOLCHAIN_TARGET)
# Always generate compile_commands.json when building. This allows some IDEs and
# tools (such as clangd) to automatically configure include directories and
# other options.
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
## Toolchain path setup
# Attempt to locate the GCC command (mipsel-none-elf-gcc) in the provided path
# (if any) as well as in the system's standard paths for programs such as the
# ones listed in the PATH environment variable.
find_program(
_gccPath ${TOOLCHAIN_TARGET}-gcc
HINTS
"${TOOLCHAIN_PATH}"
"${TOOLCHAIN_PATH}/bin"
"${TOOLCHAIN_PATH}/../bin"
NO_CACHE REQUIRED
)
cmake_path(GET _gccPath PARENT_PATH _toolchainPath)
# If a valid path was not provided but GCC was found, overwrite the variable to
# avoid searching again the next time the project is configured.
if(NOT IS_DIRECTORY TOOLCHAIN_PATH)
set(
TOOLCHAIN_PATH "${_toolchainPath}" CACHE PATH
"Directory containing GCC toolchain executables (if not listed in PATH)"
FORCE
)
endif()
# Set the paths to all tools required by CMake. The appropriate extension for
# executables (.exe on Windows, none on Unix) is extracted from the path to GCC
# using a regular expression, as CMake does not otherwise expose it.
set(_prefix "${_toolchainPath}/${TOOLCHAIN_TARGET}-")
string(REGEX MATCH ".+-gcc(.*)$" _dummy "${_gccPath}")
set(CMAKE_ASM_COMPILER "${_prefix}gcc${CMAKE_MATCH_1}")
set(CMAKE_C_COMPILER "${_prefix}gcc${CMAKE_MATCH_1}")
set(CMAKE_CXX_COMPILER "${_prefix}g++${CMAKE_MATCH_1}")
set(CMAKE_AR "${_prefix}ar${CMAKE_MATCH_1}")
set(CMAKE_LINKER "${_prefix}ld${CMAKE_MATCH_1}")
set(CMAKE_RANLIB "${_prefix}ranlib${CMAKE_MATCH_1}")
set(CMAKE_OBJCOPY "${_prefix}objcopy${CMAKE_MATCH_1}")
set(CMAKE_SIZE "${_prefix}size${CMAKE_MATCH_1}")
set(CMAKE_STRIP "${_prefix}strip${CMAKE_MATCH_1}")
# Continue initialization by running setup.cmake after project() is invoked.
set(CMAKE_PROJECT_INCLUDE "${CMAKE_CURRENT_LIST_DIR}/setup.cmake")

2081
data/games.json Normal file

File diff suppressed because it is too large Load Diff

77
resources.json Normal file
View File

@ -0,0 +1,77 @@
[
{
"type": "tim",
"name": "assets/textures/background.tim",
"source": "assets/textures/background.png",
"quantize": 16,
"imagePos": { "x": 960, "y": 0 },
"clutPos": { "x": 1008, "y": 0 }
},
{
"type": "tim",
"name": "assets/textures/font.tim",
"source": "assets/textures/font.png",
"quantize": 16,
"imagePos": { "x": 984, "y": 0 },
"clutPos": { "x": 1008, "y": 1 }
},
{
"type": "metrics",
"name": "assets/textures/font.metrics",
"source": "assets/textures/font.metrics.json"
},
{
"type": "binary",
"name": "assets/sounds/move.vag",
"source": "assets/sounds/move.vag",
"compress": null
},
{
"type": "binary",
"name": "assets/sounds/enter.vag",
"source": "assets/sounds/enter.vag",
"compress": null
},
{
"type": "binary",
"name": "assets/sounds/exit.vag",
"source": "assets/sounds/exit.vag",
"compress": null
},
{
"type": "binary",
"name": "assets/sounds/click.vag",
"source": "assets/sounds/click.vag",
"compress": null
},
{
"type": "strings",
"name": "assets/app.strings",
"source": "assets/app.strings.json"
},
{
"type": "text",
"name": "assets/licenses.txt",
"source": "assets/licenses.txt"
},
{
"type": "binary",
"name": "data/fpga.bit",
"source": "data/fpga.bit"
},
{
"type": "binary",
"name": "data/x76f041.cartdb",
"source": "data/x76f041.cartdb"
},
{
"type": "empty",
"name": "data/x76f100.cartdb"
},
{
"type": "binary",
"name": "data/zs01.cartdb",
"source": "data/zs01.cartdb"
}
]

110
src/app/actions.cpp Normal file
View File

@ -0,0 +1,110 @@
#include "app/actions.hpp"
#include "app/app.hpp"
#include "defs.hpp"
#include "uibase.hpp"
#include "util.hpp"
/* Unlocked cartridge screens */
struct Action {
public:
util::Hash name, prompt;
void (App::*target)(void);
};
// TODO: implement these
static const Action _IDENTIFIED_ACTIONS[]{
{
.name = "CartActionsScreen.qrDump.name"_h,
.prompt = "CartActionsScreen.qrDump.prompt"_h,
.target = nullptr
}, {
.name = "CartActionsScreen.hexdump.name"_h,
.prompt = "CartActionsScreen.hexdump.prompt"_h,
.target = nullptr
}, {
.name = "CartActionsScreen.resetSystemID.name"_h,
.prompt = "CartActionsScreen.resetSystemID.prompt"_h,
.target = nullptr
}, {
.name = "CartActionsScreen.editSystemID.name"_h,
.prompt = "CartActionsScreen.editSystemID.prompt"_h,
.target = nullptr
}, {
.name = "CartActionsScreen.reflash.name"_h,
.prompt = "CartActionsScreen.reflash.prompt"_h,
.target = nullptr
}, {
.name = "CartActionsScreen.erase.name"_h,
.prompt = "CartActionsScreen.erase.prompt"_h,
.target = nullptr
}
};
static const Action _UNIDENTIFIED_ACTIONS[]{
{
.name = "CartActionsScreen.qrDump.name"_h,
.prompt = "CartActionsScreen.qrDump.prompt"_h,
.target = nullptr
}, {
.name = "CartActionsScreen.hexdump.name"_h,
.prompt = "CartActionsScreen.hexdump.prompt"_h,
.target = nullptr
}, {
.name = "CartActionsScreen.reflash.name"_h,
.prompt = "CartActionsScreen.reflash.prompt"_h,
.target = nullptr
}, {
.name = "CartActionsScreen.erase.name"_h,
.prompt = "CartActionsScreen.erase.prompt"_h,
.target = nullptr
}
};
const char *CartActionsScreen::_getItemName(ui::Context &ctx, int index) const {
return STRH(_IDENTIFIED_ACTIONS[index].name);
}
void CartActionsScreen::show(ui::Context &ctx, bool goBack) {
_title = STR("CartActionsScreen.title");
_prompt = STRH(_IDENTIFIED_ACTIONS[0].prompt);
_itemPrompt = STR("CartActionsScreen.itemPrompt");
_listLength = 6;
ListScreen::show(ctx, goBack);
}
void CartActionsScreen::update(ui::Context &ctx) {
_prompt = STRH(_IDENTIFIED_ACTIONS[_activeItem].prompt);
ListScreen::update(ctx);
// TODO: implement this
if (ctx.buttons.pressed(ui::BTN_START)) {
//APP->_setupWorker(&App::_qrCodeWorker);
//ctx.show(APP->_workerStatusScreen, false, true);
}
if (ctx.buttons.held(ui::BTN_LEFT) && ctx.buttons.held(ui::BTN_RIGHT)) {
ctx.show(APP->_cartInfoScreen, true, true);
}
}
static constexpr int QR_CODE_SCALE = 2;
void QRCodeScreen::show(ui::Context &ctx, bool goBack) {
_title = STR("QRCodeScreen.title");
_prompt = STR("QRCodeScreen.prompt");
_imageScale = QR_CODE_SCALE;
_imagePadding = QR_CODE_SCALE * 6;
_backdropColor = 0xffffff;
ImageScreen::show(ctx, goBack);
}
void QRCodeScreen::update(ui::Context &ctx) {
if (ctx.buttons.pressed(ui::BTN_START))
ctx.show(APP->_cartInfoScreen, true, true);
}

32
src/app/actions.hpp Normal file
View File

@ -0,0 +1,32 @@
#pragma once
#include <stddef.h>
#include "asset.hpp"
#include "uibase.hpp"
#include "uicommon.hpp"
#include "util.hpp"
/* Unlocked cartridge screens */
class CartActionsScreen : public ui::ListScreen {
protected:
const char *_getItemName(ui::Context &ctx, int index) const;
public:
void show(ui::Context &ctx, bool goBack = false);
void update(ui::Context &ctx);
};
class QRCodeScreen : public ui::ImageScreen {
public:
inline bool generateCode(const char *textInput) {
return asset::generateQRCode(_image, 960, 128, textInput);
}
inline bool generateCode(const uint8_t *binaryInput, size_t length) {
return asset::generateQRCode(_image, 960, 128, binaryInput, length);
}
void show(ui::Context &ctx, bool goBack = false);
void update(ui::Context &ctx);
};

182
src/app/app.cpp Normal file
View File

@ -0,0 +1,182 @@
#include <stddef.h>
#include <stdint.h>
#include "app/app.hpp"
#include "ps1/system.h"
#include "asset.hpp"
#include "cart.hpp"
#include "cartdb.hpp"
#include "io.hpp"
#include "uibase.hpp"
#include "util.hpp"
/* App class */
App::App(void)
: _cart(nullptr), _identified(nullptr), _identifyResult(cartdb::UNIDENTIFIED) {
_workerStack = new uint8_t[WORKER_STACK_SIZE];
}
App::~App(void) {
//_dbFile.unload();
delete[] _workerStack;
if (_cart)
delete _cart;
}
void App::_setupWorker(void (App::* func)(void)) {
LOG("starting thread, func=0x%08x", func);
_workerStatus.reset();
initThread(
// This is not how you implement delegates in C++.
&_workerThread, util::forcedCast<ArgFunction>(func), this,
&_workerStack[(WORKER_STACK_SIZE - 1) & ~7]
);
}
void App::_setupInterrupts(void) {
setInterruptHandler(
util::forcedCast<ArgFunction>(&App::_interruptHandler), this
);
setInterruptMask((1 << IRQ_VBLANK) | (1 << IRQ_GPU));
}
void App::_dummyWorker(void) {
for (;;)
__asm__ volatile("");
}
static const char *const _CARTDB_PATHS[cart::NUM_CHIP_TYPES]{
nullptr,
"data/x76f041.cartdb",
"data/x76f100.cartdb",
"data/zs01.cartdb"
};
void App::_cartDetectWorker(void) {
_workerStatus.update(0, 4, WSTR("App.cartDetectWorker.identifyCart"));
_db.data.unload();
_cart = cart::createCart();
if (_cart->chipType) {
LOG("cart object @ 0x%08x", _cart);
_workerStatus.update(1, 4, WSTR("App.cartDetectWorker.readCart"));
_cart->readCartID();
_cart->readPublicData();
if (!_loader->loadAsset(_db.data, _CARTDB_PATHS[_cart->chipType])) {
LOG("failed to load cartdb, type=%d", _cart->chipType);
goto _cartInitDone;
}
if (!_db.init()) {
_db.data.unload();
goto _cartInitDone;
}
_workerStatus.update(2, 4, WSTR("App.cartDetectWorker.identifyGame"));
if (_cart->flags & cart::PUBLIC_DATA_OK)
_identifyResult = _db.identifyCart(*_cart);
else
LOG("no public data available");
}
_cartInitDone:
_workerStatus.update(3, 4, WSTR("App.cartDetectWorker.readDigitalIO"));
if (io::isDigitalIOPresent()) {
asset::Asset file;
bool ready;
if (!_loader->loadAsset(file, "data/fpga.bit")) {
LOG("failed to load data/fpga.bit");
goto _initDone;
}
ready = io::loadBitstream(
reinterpret_cast<const uint8_t *>(file.ptr), file.length
);
file.unload();
if (!ready) {
LOG("bitstream upload failed");
goto _initDone;
}
delayMicroseconds(5000); // Probably not necessary
io::initKonamiBitstream();
_cart->readSystemID();
}
_initDone:
_workerStatus.finish(_cartInfoScreen);
_dummyWorker();
}
void App::_cartUnlockWorker(void) {
_workerStatus.update(0, 2, WSTR("App.cartUnlockWorker.read"));
//_cart->readPrivateData(); // TODO: implement this
_workerStatus.update(1, 2, WSTR("App.cartUnlockWorker.identify"));
if (_cart->flags & cart::PRIVATE_DATA_OK)
_identifyResult = _db.identifyCart(*_cart);
_workerStatus.finish(_cartInfoScreen, true);
_dummyWorker();
}
void App::_qrCodeWorker(void) {
char qrString[cart::MAX_QR_STRING_LENGTH];
_workerStatus.update(0, 2, WSTR("App.qrCodeWorker.compress"));
_cart->toQRString(qrString);
_workerStatus.update(1, 2, WSTR("App.qrCodeWorker.generate"));
_qrCodeScreen.generateCode(qrString);
_workerStatus.finish(_qrCodeScreen);
_dummyWorker();
}
void App::_interruptHandler(void) {
if (acknowledgeInterrupt(IRQ_VBLANK)) {
_ctx->tick();
io::clearWatchdog();
switchThread(nullptr);
}
if (acknowledgeInterrupt(IRQ_GPU))
_ctx->gpuCtx.drawNextLayer();
}
void App::run(
ui::Context &ctx, asset::AssetLoader &loader, asset::StringTable &strings
) {
LOG("starting app @ 0x%08x", this);
_ctx = &ctx;
_loader = &loader;
_strings = &strings;
ctx.screenData = this;
ctx.show(_warningScreen);
ctx.sounds[ui::SOUND_STARTUP].play();
_setupWorker(&App::_dummyWorker);
_setupInterrupts();
for (;;) {
ctx.update();
ctx.draw();
switchThreadImmediate(&_workerThread);
ctx.gpuCtx.flip();
}
}

123
src/app/app.hpp Normal file
View File

@ -0,0 +1,123 @@
#pragma once
#include <stdint.h>
#include "app/actions.hpp"
#include "app/misc.hpp"
#include "app/unlock.hpp"
#include "ps1/system.h"
#include "asset.hpp"
#include "cart.hpp"
#include "cartdb.hpp"
#include "uibase.hpp"
/* Worker status class */
// This class is used by the worker thread to report its current status back to
// the main thread and the WorkerStatusScreen.
class WorkerStatus {
public:
volatile int progress, progressTotal;
volatile bool nextGoBack;
const char *volatile message;
ui::Screen *volatile nextScreen;
inline void update(int part, int total) {
auto mask = setInterruptMask(0);
progress = part;
progressTotal = total;
if (mask)
setInterruptMask(mask);
}
inline void update(int part, int total, const char *text) {
auto mask = setInterruptMask(0);
progress = part;
progressTotal = total;
message = text;
if (mask)
setInterruptMask(mask);
}
inline void finish(ui::Screen &next, bool goBack = false) {
auto mask = setInterruptMask(0);
nextScreen = &next;
nextGoBack = goBack;
if (mask)
setInterruptMask(mask);
}
inline void reset(void) {
progress = 0;
progressTotal = 1;
nextScreen = nullptr;
}
};
/* App class */
static constexpr size_t WORKER_STACK_SIZE = 0x10000;
class App {
friend class WorkerStatusScreen;
friend class WarningScreen;
friend class ButtonMappingScreen;
friend class CartInfoScreen;
friend class UnlockKeyScreen;
friend class UnlockConfirmScreen;
friend class UnlockErrorScreen;
friend class CartActionsScreen;
friend class QRCodeScreen;
private:
WorkerStatusScreen _workerStatusScreen;
WarningScreen _warningScreen;
ButtonMappingScreen _buttonMappingScreen;
CartInfoScreen _cartInfoScreen;
UnlockKeyScreen _unlockKeyScreen;
UnlockConfirmScreen _unlockConfirmScreen;
UnlockErrorScreen _unlockErrorScreen;
CartActionsScreen _cartActionsScreen;
QRCodeScreen _qrCodeScreen;
ui::Context *_ctx;
asset::AssetLoader *_loader;
asset::StringTable *_strings;
cartdb::CartDB _db;
Thread _workerThread;
WorkerStatus _workerStatus;
uint8_t *_workerStack;
cart::Cart *_cart;
cartdb::Entry *_identified;
cartdb::IdentifyResult _identifyResult;
void _setupWorker(void (App::* func)(void));
void _setupInterrupts(void);
void _dummyWorker(void);
void _cartDetectWorker(void);
void _cartUnlockWorker(void);
void _qrCodeWorker(void);
void _interruptHandler(void);
public:
App(void);
~App(void);
void run(
ui::Context &ctx, asset::AssetLoader &loader,
asset::StringTable &strings
);
};
#define APP (reinterpret_cast<App *>(ctx.screenData))
#define STR(id) (APP->_strings->get(id ## _h))
#define STRH(id) (APP->_strings->get(id))
#define WAPP (reinterpret_cast<App *>(_ctx->screenData))
#define WSTR(id) (WAPP->_strings->get(id ## _h))
#define WSTRH(id) (WAPP->_strings->get(id))

105
src/app/misc.cpp Normal file
View File

@ -0,0 +1,105 @@
#include <stdio.h>
#include "app/app.hpp"
#include "app/misc.hpp"
#include "defs.hpp"
#include "uibase.hpp"
#include "util.hpp"
/* Initial setup screens */
void WorkerStatusScreen::show(ui::Context &ctx, bool goBack) {
_title = STR("WorkerStatusScreen.title");
ProgressScreen::show(ctx, goBack);
}
void WorkerStatusScreen::update(ui::Context &ctx) {
auto &status = APP->_workerStatus;
auto nextScreen = status.nextScreen;
if (nextScreen) {
LOG("worker finished, next=0x%08x", nextScreen);
ctx.show(*nextScreen, status.nextGoBack);
return;
}
_setProgress(ctx, status.progress, status.progressTotal);
_body = status.message;
}
static constexpr int WARNING_COOLDOWN = 15;
void WarningScreen::show(ui::Context &ctx, bool goBack) {
_title = STR("WarningScreen.title");
_body = STR("WarningScreen.body");
_buttons[0] = _buttonText;
_locked = true;
_numButtons = 1;
#ifdef NDEBUG
_cooldownTimer = ctx.time + WARNING_COOLDOWN * 60;
#else
_cooldownTimer = 0;
#endif
MessageScreen::show(ctx, goBack);
ctx.buttons.buttonMap = ui::MAP_SINGLE_BUTTON;
}
void WarningScreen::update(ui::Context &ctx) {
MessageScreen::update(ctx);
int time = _cooldownTimer - ctx.time;
_locked = (time > 0);
if (_locked) {
time = (time / ctx.gpuCtx.refreshRate) + 1;
sprintf(_buttonText, STR("WarningScreen.cooldown"), time);
return;
}
_buttons[0] = STR("WarningScreen.ok");
if (ctx.buttons.pressed(ui::BTN_RIGHT) || ctx.buttons.pressed(ui::BTN_START))
ctx.show(APP->_buttonMappingScreen, false, true);
}
static const util::Hash _MAPPING_NAMES[]{
"ButtonMappingScreen.joystick"_h,
"ButtonMappingScreen.ddrCab"_h,
"ButtonMappingScreen.ddrSoloCab"_h,
"ButtonMappingScreen.dmCab"_h,
"ButtonMappingScreen.dmxCab"_h
};
const char *ButtonMappingScreen::_getItemName(ui::Context &ctx, int index) const {
return STRH(_MAPPING_NAMES[index]);
}
void ButtonMappingScreen::show(ui::Context &ctx, bool goBack) {
_title = STR("ButtonMappingScreen.title");
_prompt = STR("ButtonMappingScreen.prompt");
_itemPrompt = STR("ButtonMappingScreen.itemPrompt");
_listLength = ui::NUM_BUTTON_MAPS - 1;
ListScreen::show(ctx, goBack);
ctx.buttons.buttonMap = ui::MAP_SINGLE_BUTTON;
}
void ButtonMappingScreen::update(ui::Context &ctx) {
ListScreen::update(ctx);
if (ctx.buttons.pressed(ui::BTN_START)) {
ctx.buttons.buttonMap = ui::ButtonMap(_activeItem);
APP->_setupWorker(&App::_cartDetectWorker);
ctx.show(APP->_workerStatusScreen, false, true);
}
}

32
src/app/misc.hpp Normal file
View File

@ -0,0 +1,32 @@
#pragma once
#include "uibase.hpp"
#include "uicommon.hpp"
/* Initial setup screens */
class WorkerStatusScreen : public ui::ProgressScreen {
public:
void show(ui::Context &ctx, bool goBack = false);
void update(ui::Context &ctx);
};
class WarningScreen : public ui::MessageScreen {
private:
int _cooldownTimer;
char _buttonText[16];
public:
void show(ui::Context &ctx, bool goBack = false);
void update(ui::Context &ctx);
};
class ButtonMappingScreen : public ui::ListScreen {
protected:
const char *_getItemName(ui::Context &ctx, int index) const;
public:
void show(ui::Context &ctx, bool goBack = false);
void update(ui::Context &ctx);
};

276
src/app/unlock.cpp Normal file
View File

@ -0,0 +1,276 @@
#include <stdio.h>
#include <string.h>
#include "app/app.hpp"
#include "app/unlock.hpp"
#include "cart.hpp"
#include "cartdb.hpp"
#include "defs.hpp"
#include "uibase.hpp"
#include "util.hpp"
/* Pre-unlock cartridge screens */
struct CartType {
public:
util::Hash name, warning, error;
};
static const CartType _CART_TYPES[cart::NUM_CHIP_TYPES]{
{
.name = "CartInfoScreen.noCart.name"_h,
.warning = "CartInfoScreen.noCart.warning"_h,
.error = 0
}, {
.name = "CartInfoScreen.x76f041.name"_h,
.warning = "CartInfoScreen.x76f041.warning"_h,
.error = 0
}, {
.name = "CartInfoScreen.x76f100.name"_h,
.warning = "CartInfoScreen.x76f100.warning"_h,
.error = 0
}, {
.name = "CartInfoScreen.zs01.name"_h,
.warning = "CartInfoScreen.zs01.warning"_h,
.error = 0
}
};
static const util::Hash _LOCKED_PROMPTS[]{
"CartInfoScreen.description.locked.unidentified"_h,
"CartInfoScreen.description.locked.identified"_h,
"CartInfoScreen.description.locked.unknown"_h
};
static const util::Hash _UNLOCKED_PROMPTS[]{
"CartInfoScreen.description.unlocked.unidentified"_h,
"CartInfoScreen.description.unlocked.identified"_h,
"CartInfoScreen.description.unlocked.blank"_h
};
void CartInfoScreen::show(ui::Context &ctx, bool goBack) {
_title = STR("CartInfoScreen.title");
_body = _bodyText;
TextScreen::show(ctx, goBack);
auto &_cart = *(APP->_cart);
auto flags = _cart.flags;
char id1[32], id2[32];
char *ptr = _bodyText, *end = &_bodyText[sizeof(_bodyText)];
// Digital I/O board info
if (flags & cart::SYSTEM_ID_OK) {
util::hexToString(id1, _cart.systemID, sizeof(_cart.systemID), '-');
util::serialNumberToString(id2, &_cart.systemID[1]);
} else if (flags & cart::HAS_DIGITAL_IO) {
strcpy(id1, STR("CartInfoScreen.id.error"));
strcpy(id2, id1);
} else {
strcpy(id1, STR("CartInfoScreen.id.noSystemID"));
strcpy(id2, id1);
}
ptr += snprintf(ptr, end - ptr, STR("CartInfoScreen.digitalIOInfo"), id1, id2);
// Cartridge info
if (!_cart.chipType) {
memccpy(ptr, STR("CartInfoScreen.description.noCart"), 0, end - ptr);
_prompt = STR("CartInfoScreen.prompt.error");
return;
} else if (!(_cart.flags & cart::PUBLIC_DATA_OK)) {
memccpy(ptr, STR("CartInfoScreen.description.initError"), 0, end - ptr);
_prompt = STR("CartInfoScreen.prompt.error");
return;
}
if (flags & cart::CART_ID_OK)
util::hexToString(id1, _cart.cartID, sizeof(_cart.cartID), '-');
else if (flags & cart::HAS_DS2401)
strcpy(id1, STR("CartInfoScreen.id.error"));
else
strcpy(id1, STR("CartInfoScreen.id.noCartID"));
if (flags & cart::ZS_ID_OK)
util::hexToString(id2, _cart.zsID, sizeof(_cart.zsID), '-');
else if (_cart.chipType == cart::TYPE_ZS01)
strcpy(id2, STR("CartInfoScreen.id.error"));
else
strcpy(id2, STR("CartInfoScreen.id.noZSID"));
auto unlockStatus = (flags & cart::PRIVATE_DATA_OK) ?
STR("CartInfoScreen.unlockStatus.unlocked") :
STR("CartInfoScreen.unlockStatus.locked");
ptr += snprintf(
ptr, end - ptr, STR("CartInfoScreen.cartInfo"),
STRH(_CART_TYPES[_cart.chipType].name), unlockStatus, id1, id2
);
// At this point the cartridge can be in one of 6 states:
// - locked, identified
// => unlock required, auto unlock available
// - locked, unidentified
// => unlock required
// - locked, blank or no public data
// => unlock required
// - unlocked, identified
// => all actions available
// - unlocked, no private data, unidentified
// => only dumping/flashing available
// - unlocked, no private data, blank
// => only dumping/flashing available
auto result = APP->_identifyResult;
char name[96];
if (result == cartdb::IDENTIFIED)
APP->_identified->getDisplayName(name, sizeof(name));
if (flags & cart::PRIVATE_DATA_OK) {
ptr += snprintf(ptr, end - ptr, STRH(_UNLOCKED_PROMPTS[result]), name);
_prompt = STR("CartInfoScreen.prompt.unlocked");
} else {
ptr += snprintf(ptr, end - ptr, STRH(_LOCKED_PROMPTS[result]), name);
_prompt = STR("CartInfoScreen.prompt.locked");
}
}
void CartInfoScreen::update(ui::Context &ctx) {
auto &_cart = *(APP->_cart);
if (!_cart.chipType)
return;
if (ctx.buttons.pressed(ui::BTN_START)) {
/*if (_cart.flags & cart::PRIVATE_DATA_OK)
ctx.show(APP->_cartActionsScreen, false, true);
else
ctx.show(APP->_unlockKeyScreen, false, true);*/
}
}
enum SpecialUnlockKeyEntry {
ENTRY_AUTO_UNLOCK = -3,
ENTRY_CUSTOM_KEY = -2,
ENTRY_NULL_KEY = -1
};
int UnlockKeyScreen::_getSpecialEntryOffset(ui::Context &ctx) const {
return (APP->_identifyResult == cartdb::IDENTIFIED)
? ENTRY_AUTO_UNLOCK : ENTRY_CUSTOM_KEY;
}
const char *UnlockKeyScreen::_getItemName(ui::Context &ctx, int index) const {
static char name[96]; // TODO: get rid of this ugly crap
index += _getSpecialEntryOffset(ctx);
switch (index) {
case ENTRY_AUTO_UNLOCK:
return _autoUnlockItem;
case ENTRY_CUSTOM_KEY:
return _customKeyItem;
case ENTRY_NULL_KEY:
return _nullKeyItem;
default:
APP->_db.getEntry(index).getDisplayName(name, sizeof(name));
return name;
}
}
void UnlockKeyScreen::show(ui::Context &ctx, bool goBack) {
_title = STR("UnlockKeyScreen.title");
_prompt = STR("UnlockKeyScreen.prompt");
_itemPrompt = STR("UnlockKeyScreen.itemPrompt");
_autoUnlockItem = STR("UnlockKeyScreen.autoUnlock");
_customKeyItem = STR("UnlockKeyScreen.customKey");
_nullKeyItem = STR("UnlockKeyScreen.nullKey");
_listLength = APP->_db.numEntries - _getSpecialEntryOffset(ctx);
ListScreen::show(ctx, goBack);
}
void UnlockKeyScreen::update(ui::Context &ctx) {
ListScreen::update(ctx);
if (ctx.buttons.pressed(ui::BTN_START)) {
int index = _activeItem + _getSpecialEntryOffset(ctx);
switch (index) {
case ENTRY_AUTO_UNLOCK:
memcpy(
APP->_cart->dataKey, APP->_identified->dataKey,
sizeof(APP->_cart->dataKey)
);
ctx.show(APP->_unlockConfirmScreen, false, true);
break;
case ENTRY_CUSTOM_KEY:
//ctx.show(APP->_unlockKeyEntryScreen, false, true);
break;
case ENTRY_NULL_KEY:
memset(APP->_cart->dataKey, 0, sizeof(APP->_cart->dataKey));
ctx.show(APP->_unlockConfirmScreen, false, true);
break;
default:
memcpy(
APP->_cart->dataKey, APP->_db.getEntry(index).dataKey,
sizeof(APP->_cart->dataKey)
);
ctx.show(APP->_unlockConfirmScreen, false, true);
}
} else if (ctx.buttons.held(ui::BTN_LEFT) && ctx.buttons.held(ui::BTN_RIGHT)) {
ctx.show(APP->_cartInfoScreen, true, true);
}
}
void UnlockConfirmScreen::show(ui::Context &ctx, bool goBack) {
_title = STR("UnlockConfirmScreen.title");
_body = STRH(_CART_TYPES[APP->_cart->chipType].warning);
_buttons[0] = STR("UnlockConfirmScreen.no");
_buttons[1] = STR("UnlockConfirmScreen.yes");
_numButtons = 2;
MessageScreen::show(ctx, goBack);
}
void UnlockConfirmScreen::update(ui::Context &ctx) {
MessageScreen::update(ctx);
if (ctx.buttons.pressed(ui::BTN_START)) {
if (_activeButton) {
APP->_setupWorker(&App::_cartUnlockWorker);
ctx.show(APP->_workerStatusScreen, false, true);
} else {
ctx.show(APP->_unlockKeyScreen, true, true);
}
}
}
void UnlockErrorScreen::show(ui::Context &ctx, bool goBack) {
_title = STR("UnlockErrorScreen.title");
_body = STRH(_CART_TYPES[APP->_cart->chipType].error);
_buttons[0] = STR("UnlockErrorScreen.ok");
_numButtons = 1;
MessageScreen::show(ctx, goBack);
}
void UnlockErrorScreen::update(ui::Context &ctx) {
MessageScreen::update(ctx);
if (ctx.buttons.pressed(ui::BTN_START))
ctx.show(APP->_cartInfoScreen, true, true);
}

42
src/app/unlock.hpp Normal file
View File

@ -0,0 +1,42 @@
#pragma once
#include "uibase.hpp"
#include "uicommon.hpp"
/* Pre-unlock cartridge screens */
class CartInfoScreen : public ui::TextScreen {
private:
char _bodyText[1024];
public:
void show(ui::Context &ctx, bool goBack = false);
void update(ui::Context &ctx);
};
class UnlockKeyScreen : public ui::ListScreen {
private:
const char *_autoUnlockItem, *_customKeyItem, *_nullKeyItem;
int _getSpecialEntryOffset(ui::Context &ctx) const;
protected:
const char *_getItemName(ui::Context &ctx, int index) const;
public:
void show(ui::Context &ctx, bool goBack = false);
void update(ui::Context &ctx);
};
class UnlockConfirmScreen : public ui::MessageScreen {
public:
void show(ui::Context &ctx, bool goBack = false);
void update(ui::Context &ctx);
};
class UnlockErrorScreen : public ui::MessageScreen {
public:
void show(ui::Context &ctx, bool goBack = false);
void update(ui::Context &ctx);
};

261
src/asset.cpp Normal file
View File

@ -0,0 +1,261 @@
#include <stdarg.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include "ps1/gpucmd.h"
#include "ps1/pcdrv.h"
#include "vendor/miniz.h"
#include "vendor/qrcodegen.h"
#include "asset.hpp"
namespace asset {
/* Asset loader */
bool AssetLoader::openMemory(const void *zipData, size_t length) {
//close();
mz_zip_zero_struct(&_zip);
// Sorting the central directory in a zip with a small number of files is
// just a waste of time.
if (!mz_zip_reader_init_mem(
&_zip, zipData, length,
MZ_ZIP_FLAG_CASE_SENSITIVE | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY
)) {
LOG("zip init error, code=%d", mz_zip_get_last_error(&_zip));
return false;
}
LOG("ptr=0x%08x, length=0x%x", zipData, length);
ready = true;
return true;
}
bool AssetLoader::openHost(const char *path) {
if (pcdrvInit() < 0)
return false;
_hostFile = pcdrvOpen(path, PCDRV_MODE_READ);
if (_hostFile < 0)
return false;
int length = pcdrvSeek(_hostFile, 0, PCDRV_SEEK_END);
if (length < 0)
return false;
_zip.m_pIO_opaque = reinterpret_cast<void *>(_hostFile);
_zip.m_pNeeds_keepalive = nullptr;
_zip.m_pRead = [](
void *opaque, uint64_t offset, void *data, size_t length
) -> size_t {
int hostFile = reinterpret_cast<int>(opaque);
if (
pcdrvSeek(hostFile, static_cast<uint32_t>(offset), PCDRV_SEEK_SET)
!= int(offset)
)
return 0;
int actualLength = pcdrvRead(hostFile, data, length);
if (actualLength < 0)
return 0;
return actualLength;
};
if (!mz_zip_reader_init(
&_zip, length,
MZ_ZIP_FLAG_CASE_SENSITIVE | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY
)) {
LOG("zip init error, code=%d", mz_zip_get_last_error(&_zip));
return false;
}
LOG("length=0x%x", length);
ready = true;
return true;
}
void AssetLoader::close(void) {
if (!ready)
return;
if (_hostFile >= 0)
pcdrvClose(_hostFile);
mz_zip_reader_end(&_zip);
ready = false;
}
size_t AssetLoader::loadAsset(Asset &output, const char *path) {
output.ptr = mz_zip_reader_extract_file_to_heap(&_zip, path, &output.length, 0);
if (!output.ptr)
return 0;
return output.length;
}
size_t AssetLoader::loadTIM(gpu::Image &output, const char *path) {
size_t size;
void *data = mz_zip_reader_extract_file_to_heap(&_zip, path, &size, 0);
if (!data)
return 0;
auto header = reinterpret_cast<const gpu::TIMHeader *>(data);
auto ptr = reinterpret_cast<const uint8_t *>(&header[1]);
if (!output.initFromTIMHeader(header)) {
mz_free(data);
return 0;
}
if (header->flags & (1 << 3)) {
auto clut = reinterpret_cast<const gpu::TIMSectionHeader *>(ptr);
gpu::upload(clut->vram, &clut[1], true);
ptr += clut->length;
}
auto image = reinterpret_cast<const gpu::TIMSectionHeader *>(ptr);
gpu::upload(image->vram, &image[1], true);
mz_free(data);
return size;
}
size_t AssetLoader::loadVAG(spu::Sound &output, const char *path) {
// Sounds should be decompressed and uploaded to the SPU one chunk at a
// time, but whatever.
size_t size;
void *data = mz_zip_reader_extract_file_to_heap(&_zip, path, &size, 0);
if (!data)
return 0;
auto header = reinterpret_cast<const spu::VAGHeader *>(data);
if (!output.initFromVAGHeader(header, spuOffset)) {
mz_free(data);
return 0;
}
spuOffset += spu::upload(
spuOffset, reinterpret_cast<const uint32_t *>(&header[1]),
size - sizeof(spu::VAGHeader), true
);
mz_free(data);
return size;
}
size_t AssetLoader::loadFontMetrics(gpu::Font &output, const char *path) {
if (!mz_zip_reader_extract_file_to_mem(
&_zip, path, output.metrics, sizeof(output.metrics), 0
))
return 0;
return sizeof(output.metrics);
}
/* String table manager */
const char *StringTable::get(util::Hash id) {
if (!data.ptr)
return "missingno";
auto blob = reinterpret_cast<const char *>(data.ptr);
auto table = reinterpret_cast<const StringTableEntry *>(data.ptr);
auto entry = &table[id % TABLE_BUCKET_COUNT];
if (entry->hash == id)
return &blob[entry->offset];
while (entry->chained) {
entry = &table[entry->chained];
if (entry->hash == id)
return &blob[entry->offset];
}
return "missingno";
}
size_t StringTable::format(char *buffer, size_t length, util::Hash id, ...) {
va_list ap;
va_start(ap, id);
size_t outLength = vsnprintf(buffer, length, get(id), ap);
va_end(ap);
return outLength;
}
/* QR code encoder */
static void _loadQRCode(
gpu::Image &output, int x, int y, const uint32_t *qrCode
) {
int size = qrcodegen_getSize(qrCode);
gpu::RectWH rect;
// Generate a 16-color (only 2 colors used) palette and place it below the
// QR code in VRAM.
const uint32_t palette[8]{ 0x8000ffff };
rect.x = x;
rect.y = y + size;
rect.w = 16;
rect.h = 1;
gpu::upload(rect, palette, true);
rect.y = y;
rect.w = qrcodegen_getStride(qrCode) * 2;
rect.h = size;
gpu::upload(rect, &qrCode[1], true);
output.initFromVRAMRect(rect, GP0_COLOR_4BPP);
output.width = size;
output.palette = gp0_clut(x / 64, (y + size) / 256);
LOG("loaded at (%d,%d), size=%d", x, y, size);
}
bool generateQRCode(
gpu::Image &output, int x, int y, const char *str, qrcodegen_Ecc ecc
) {
uint32_t qrCode[qrcodegen_BUFFER_LEN_MAX];
uint32_t tempBuffer[qrcodegen_BUFFER_LEN_MAX];
auto segment = qrcodegen_makeAlphanumeric(
str, reinterpret_cast<uint8_t *>(tempBuffer)
);
if (!qrcodegen_encodeSegments(&segment, 1, ecc, tempBuffer, qrCode)) {
LOG("QR encoding failed");
return false;
}
_loadQRCode(output, x, y, qrCode);
return true;
}
bool generateQRCode(
gpu::Image &output, int x, int y, const uint8_t *data, size_t length,
qrcodegen_Ecc ecc
) {
uint32_t qrCode[qrcodegen_BUFFER_LEN_MAX];
uint32_t tempBuffer[qrcodegen_BUFFER_LEN_MAX];
auto segment = qrcodegen_makeBytes(
data, length, reinterpret_cast<uint8_t *>(tempBuffer)
);
if (!qrcodegen_encodeSegments(&segment, 1, ecc, tempBuffer, qrCode)) {
LOG("QR encoding failed");
return false;
}
_loadQRCode(output, x, y, qrCode);
return true;
}
}

92
src/asset.hpp Normal file
View File

@ -0,0 +1,92 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
#include "vendor/miniz.h"
#include "vendor/qrcodegen.h"
#include "gpu.hpp"
#include "spu.hpp"
#include "util.hpp"
namespace asset {
/* Asset loader (wrapper around a zip file) */
class Asset {
public:
void *ptr;
size_t length;
inline Asset(void)
: ptr(nullptr), length(0) {}
inline ~Asset(void) {
unload();
}
inline void unload(void) {
if (ptr) {
mz_free(ptr);
ptr = nullptr;
}
}
};
class AssetLoader {
private:
mz_zip_archive _zip;
int _hostFile;
public:
bool ready;
uint32_t spuOffset;
inline AssetLoader(uint32_t spuOffset = 0x1000)
: _hostFile(-1), ready(false), spuOffset(spuOffset) {}
inline ~AssetLoader(void) {
close();
}
bool openMemory(const void *zipData, size_t length);
bool openHost(const char *path);
void close(void);
size_t loadAsset(Asset &output, const char *path);
size_t loadTIM(gpu::Image &output, const char *path);
size_t loadVAG(spu::Sound &output, const char *path);
size_t loadFontMetrics(gpu::Font &output, const char *path);
};
/* String table manager */
static constexpr int TABLE_BUCKET_COUNT = 256;
struct [[gnu::packed]] StringTableEntry {
public:
uint32_t hash;
uint16_t offset, chained;
};
class StringTable {
public:
Asset data;
inline const char *operator[](util::Hash id) {
return get(id);
}
const char *get(util::Hash id);
size_t format(char *buffer, size_t length, util::Hash id, ...);
};
/* QR code encoder */
bool generateQRCode(
gpu::Image &output, int x, int y, const char *str,
qrcodegen_Ecc ecc = qrcodegen_Ecc_MEDIUM
);
bool generateQRCode(
gpu::Image &output, int x, int y, const uint8_t *data, size_t length,
qrcodegen_Ecc ecc = qrcodegen_Ecc_MEDIUM
);
}

497
src/cart.cpp Normal file
View File

@ -0,0 +1,497 @@
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#include "ps1/system.h"
#include "vendor/miniz.h"
#include "cart.hpp"
#include "io.hpp"
#include "util.hpp"
#include "zs01.hpp"
namespace cart {
/* Common functions */
enum ChipID : uint32_t {
_ID_X76F041 = 0x55aa5519,
_ID_X76F100 = 0x55aa0019,
_ID_ZS01 = 0x5a530001
};
static const size_t _DATA_LENGTHS[NUM_CHIP_TYPES]{ 0, 512, 112, 112 };
static constexpr int _X76_MAX_ACK_POLLS = 5;
static constexpr int _X76_WRITE_DELAY = 10000;
static constexpr int _ZS01_PACKET_DELAY = 30000;
static bool _validateID(const uint8_t *id) {
if (!id[0] || (id[0] == 0xff)) {
LOG("invalid device type 0x%02x", id[0]);
return false;
}
uint8_t crc = util::dsCRC8(id, 7);
if (crc != id[7]) {
LOG("CRC mismatch, exp=0x%02x, got=0x%02x", crc, id[7]);
return false;
}
return true;
}
size_t getDataLength(ChipType type) {
return _DATA_LENGTHS[type];
}
Cart *createCart(void) {
if (!io::getCartInsertionStatus()) {
LOG("DSR not asserted");
return new Cart();
}
uint32_t id1 = io::i2cResetX76();
LOG("id1=0x%08x", id1);
switch (id1) {
case _ID_X76F041:
return new X76F041Cart();
//case _ID_X76F100:
//return new X76F100Cart();
default:
uint32_t id2 = io::i2cResetZS01();
LOG("id2=0x%08x", id2);
if (id2 == _ID_ZS01)
return new ZS01Cart();
return new Cart();
}
}
/* Base cart class */
Cart::Cart(void) {
memset(&version, 0, 44);
version = DUMP_VERSION;
chipType = TYPE_NONE;
flags = 0;
}
size_t Cart::toQRString(char *output) {
uint8_t compressed[MAX_QR_STRING_LENGTH];
size_t uncompLength = getDumpLength();
size_t compLength = MAX_QR_STRING_LENGTH;
int error = mz_compress2(
compressed,
reinterpret_cast<mz_ulong *>(&compLength),
&version,
uncompLength,
MZ_BEST_COMPRESSION
);
if (error != MZ_OK) {
LOG("compression error, code=%d", error);
return 0;
}
LOG(
"dump compressed, size=%d, ratio=%d%%", compLength,
compLength * 100 / uncompLength
);
compLength = util::encodeBase45(&output[5], compressed, compLength);
memcpy(&output[0], "573::", 5);
memcpy(&output[compLength + 5], "::", 3);
return compLength + 7;
}
Error Cart::readSystemID(void) {
uint8_t id[8];
auto mask = setInterruptMask(0);
if (!io::dsDIOReset()) {
if (mask)
setInterruptMask(mask);
LOG("no 1-wire device found");
return DS2401_NO_RESP;
}
flags |= HAS_DIGITAL_IO;
io::dsDIOWriteByte(0x33);
for (int i = 0; i < 8; i++)
id[i] = io::dsDIOReadByte();
if (mask)
setInterruptMask(mask);
if (!_validateID(id))
return DS2401_ID_ERROR;
memcpy(systemID, id, sizeof(id));
flags |= SYSTEM_ID_OK;
return NO_ERROR;
}
Error X76Cart::readCartID(void) {
uint8_t id[8];
auto mask = setInterruptMask(0);
if (!io::dsCartReset()) {
if (mask)
setInterruptMask(mask);
LOG("no 1-wire device found");
return DS2401_NO_RESP;
}
flags |= HAS_DS2401;
io::dsCartWriteByte(0x33);
for (int i = 0; i < 8; i++)
id[i] = io::dsCartReadByte();
if (mask)
setInterruptMask(mask);
if (!_validateID(id))
return DS2401_ID_ERROR;
memcpy(cartID, id, sizeof(id));
flags |= CART_ID_OK;
return NO_ERROR;
}
Error X76Cart::_x76Command(
uint8_t command, uint8_t param, uint8_t pollByte
) const {
io::i2cStartWithCS();
io::i2cWriteByte(command);
if (!io::i2cGetACK()) {
io::i2cStopWithCS();
LOG("NACK while sending command");
return X76_NACK;
}
io::i2cWriteByte(param);
if (!io::i2cGetACK()) {
io::i2cStopWithCS();
LOG("NACK while sending parameter");
return X76_NACK;
}
if (!io::i2cWriteBytes(dataKey, sizeof(dataKey))) {
io::i2cStopWithCS();
LOG("NACK while sending data key");
return X76_NACK;
}
for (int i = _X76_MAX_ACK_POLLS; i; i--) {
delayMicroseconds(_X76_WRITE_DELAY);
io::i2cStart();
io::i2cWriteByte(pollByte);
if (io::i2cGetACK())
return NO_ERROR;
}
io::i2cStopWithCS();
LOG("ACK polling timeout (wrong key?)");
return X76_POLL_FAIL;
}
/* X76F041 driver */
enum X76F041Command : uint8_t {
_X76F041_READ = 0x60,
_X76F041_WRITE = 0x40,
_X76F041_CONFIG = 0x80,
_X76F041_ACK_POLL = 0xc0
};
enum X76F041ConfigOp : uint8_t {
_X76F041_CFG_SET_DATA_KEY = 0x20,
_X76F041_CFG_READ_CONFIG = 0x60,
_X76F041_CFG_WRITE_CONFIG = 0x50,
_X76F041_CFG_ERASE = 0x70
};
X76F041Cart::X76F041Cart(void) {
Cart();
chipType = TYPE_X76F041;
}
Error X76F041Cart::readPrivateData(void) {
// Reads can be done with any block size, but a single read operation can't
// cross 128-byte block boundaries.
for (int i = 0; i < 512; i += 128) {
Error error = _x76Command(
_X76F041_READ | (i >> 8), i & 0xff, _X76F041_ACK_POLL
);
if (error)
return error;
io::i2cReadByte(); // Ignore "secure read setup" byte
io::i2cStart();
io::i2cWriteByte(i & 0xff);
if (io::i2cGetACK()) {
LOG("NACK after resending address");
return X76_NACK;
}
io::i2cReadBytes(&data[i], 128);
io::i2cStopWithCS();
}
return NO_ERROR;
}
Error X76F041Cart::writeData(void) {
// Writes can only be done in 8-byte blocks.
for (int i = 0; i < 512; i += 8) {
Error error = _x76Command(
_X76F041_WRITE | (i >> 8), i & 0xff, _X76F041_ACK_POLL
);
if (error)
return error;
if (!io::i2cWriteBytes(&data[i], 8)) {
LOG("NACK while sending data bytes");
return X76_NACK;
}
io::i2cStopWithCS(_X76_WRITE_DELAY);
}
return NO_ERROR;
}
Error X76F041Cart::erase(void) {
Error error = _x76Command(
_X76F041_CONFIG, _X76F041_CFG_ERASE, _X76F041_ACK_POLL
);
if (error)
return error;
io::i2cStopWithCS(_X76_WRITE_DELAY);
return NO_ERROR;
}
Error X76F041Cart::setDataKey(const uint8_t *newKey) {
Error error = _x76Command(
_X76F041_CONFIG, _X76F041_CFG_SET_DATA_KEY, _X76F041_ACK_POLL
);
if (error)
return error;
// The X76F041 requires the key to be sent twice as a way of ensuring it
// gets received correctly.
for (int i = 2; i; i--) {
if (!io::i2cWriteBytes(newKey, sizeof(dataKey))) {
io::i2cStopWithCS();
LOG("NACK while setting new data key");
return X76_NACK;
}
}
io::i2cStopWithCS(_X76_WRITE_DELAY);
// Update the data key stored in the class.
memcpy(dataKey, newKey, sizeof(dataKey));
return NO_ERROR;
}
/* X76F100 driver */
enum X76F100Command : uint8_t {
_X76F100_READ = 0x81,
_X76F100_WRITE = 0x80,
_X76F100_SET_READ_KEY = 0xfe,
_X76F100_SET_WRITE_KEY = 0xfc,
_X76F100_ACK_POLL = 0x55
};
X76F100Cart::X76F100Cart(void) {
Cart();
chipType = TYPE_X76F100;
}
// TODO: actually implement this (even though no X76F100 carts were ever made)
/* ZS01 driver */
ZS01Cart::ZS01Cart(void) {
Cart();
chipType = TYPE_ZS01;
flags = HAS_DS2401;
}
Error ZS01Cart::_transact(zs01::Packet &request, zs01::Packet &response) {
io::i2cStart();
if (!io::i2cWriteBytes(
&request.command, sizeof(zs01::Packet), _ZS01_PACKET_DELAY
)) {
io::i2cStop();
LOG("NACK while sending request packet");
return ZS01_NACK;
}
io::i2cReadBytes(&response.command, sizeof(zs01::Packet));
io::i2cStop();
if (!response.decodeResponse())
return ZS01_CRC_MISMATCH;
_state = response.address;
if (response.command != zs01::RESP_NO_ERROR) {
LOG("ZS01 error, code=0x%02x", response.command);
return ZS01_ERROR;
}
return NO_ERROR;
}
Error ZS01Cart::readCartID(void) {
zs01::Packet request, response;
Error error;
request.address = zs01::ADDR_ZS01_ID;
request.encodeReadRequest();
error = _transact(request, response);
if (error)
return error;
if (!_validateID(response.data))
return DS2401_ID_ERROR;
response.copyDataTo(zsID);
flags |= ZS_ID_OK;
request.address = zs01::ADDR_DS2401_ID;
request.encodeReadRequest();
error = _transact(request, response);
if (error)
return error;
if (!_validateID(response.data))
return DS2401_ID_ERROR;
response.copyDataTo(cartID);
flags |= CART_ID_OK;
return NO_ERROR;
}
Error ZS01Cart::readPublicData(void) {
zs01::Packet request, response;
for (int i = zs01::ADDR_PUBLIC; i < zs01::ADDR_PUBLIC_END; i++) {
request.address = i;
request.encodeReadRequest();
Error error = _transact(request, response);
if (error)
return error;
response.copyDataTo(&data[i * sizeof(response.data)]);
}
flags |= PUBLIC_DATA_OK;
return NO_ERROR;
}
Error ZS01Cart::readPrivateData(void) {
zs01::Packet request, response;
zs01::Key key;
key.unpackFrom(dataKey);
for (int i = zs01::ADDR_PRIVATE; i < zs01::ADDR_PRIVATE_END; i++) {
request.address = i;
request.encodeReadRequest(key, _state);
Error error = _transact(request, response);
if (error)
return error;
response.copyDataTo(&data[i * sizeof(response.data)]);
}
flags |= PRIVATE_DATA_OK;
request.address = zs01::ADDR_CONFIG;
request.encodeReadRequest(key, _state);
Error error = _transact(request, response);
if (error)
return error;
response.copyDataTo(config);
flags |= CONFIG_OK;
return NO_ERROR;
}
Error ZS01Cart::writeData(void) {
zs01::Packet request, response;
zs01::Key key;
key.unpackFrom(dataKey);
for (int i = zs01::ADDR_PUBLIC; i < zs01::ADDR_PRIVATE_END; i++) {
request.address = i;
request.copyDataFrom(&data[i * sizeof(request.data)]);
request.encodeWriteRequest(key, _state);
Error error = _transact(request, response);
if (error)
return error;
}
request.address = zs01::ADDR_CONFIG;
request.copyDataFrom(config);
request.encodeWriteRequest(key, _state);
return _transact(request, response);
}
Error ZS01Cart::erase(void) {
zs01::Packet request, response;
zs01::Key key;
key.unpackFrom(dataKey);
memset(request.data, 0, sizeof(request.data));
request.address = zs01::ADDR_ERASE;
request.encodeWriteRequest(key, _state);
return _transact(request, response);
}
Error ZS01Cart::setDataKey(const uint8_t *newKey) {
zs01::Packet request, response;
zs01::Key key;
key.unpackFrom(dataKey);
request.address = zs01::ADDR_DATA_KEY;
request.copyDataFrom(newKey);
request.encodeWriteRequest(key, _state);
Error error = _transact(request, response);
if (error)
return error;
// Update the data key stored in the class.
memcpy(dataKey, newKey, sizeof(dataKey));
return NO_ERROR;
}
}

123
src/cart.hpp Normal file
View File

@ -0,0 +1,123 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
#include "zs01.hpp"
namespace cart {
enum Error {
NO_ERROR = 0,
UNSUPPORTED_OP = 1,
DS2401_NO_RESP = 2,
DS2401_ID_ERROR = 3,
X76_NACK = 4,
X76_POLL_FAIL = 5,
X76_VERIFY_FAIL = 6,
ZS01_NACK = 7,
ZS01_ERROR = 8,
ZS01_CRC_MISMATCH = 9
};
enum ChipType : uint8_t {
TYPE_NONE = 0,
TYPE_X76F041 = 1,
TYPE_X76F100 = 2,
TYPE_ZS01 = 3
};
enum CartFlag : uint8_t {
HAS_DIGITAL_IO = 1 << 0,
HAS_DS2401 = 1 << 1,
CONFIG_OK = 1 << 2,
SYSTEM_ID_OK = 1 << 3,
CART_ID_OK = 1 << 4,
ZS_ID_OK = 1 << 5,
PUBLIC_DATA_OK = 1 << 6,
PRIVATE_DATA_OK = 1 << 7
};
static constexpr int DUMP_VERSION = 1;
static constexpr int NUM_CHIP_TYPES = 4;
static constexpr int MAX_QR_STRING_LENGTH = 0x600;
class Cart;
size_t getDataLength(ChipType type);
Cart *createCart(void);
class [[gnu::packed]] Cart {
public:
uint8_t version;
ChipType chipType;
uint8_t flags, _state;
uint8_t dataKey[8], config[8];
uint8_t systemID[8], cartID[8], zsID[8];
inline size_t getDumpLength(void) {
return getDataLength(chipType) + 44;
}
Cart(void);
size_t toQRString(char *output);
virtual Error readSystemID(void);
virtual Error readCartID(void) { return UNSUPPORTED_OP; }
virtual Error readPublicData(void) { return UNSUPPORTED_OP; }
virtual Error readPrivateData(void) { return UNSUPPORTED_OP; }
virtual Error writeData(void) { return UNSUPPORTED_OP; }
virtual Error erase(void) { return UNSUPPORTED_OP; }
virtual Error setDataKey(const uint8_t *newKey) { return UNSUPPORTED_OP; }
};
class [[gnu::packed]] X76Cart : public Cart {
protected:
Error _readDS2401(void);
Error _x76Command(uint8_t command, uint8_t param, uint8_t pollByte) const;
public:
uint8_t data[512];
Error readCartID(void);
};
class [[gnu::packed]] X76F041Cart : public X76Cart {
public:
uint8_t data[512];
X76F041Cart(void);
Error readPrivateData(void);
Error writeData(void);
Error erase(void);
Error setDataKey(const uint8_t *newKey);
};
class [[gnu::packed]] X76F100Cart : public X76Cart {
public:
uint8_t data[112];
X76F100Cart(void);
//Error readPrivateData(void);
//Error writeData(void);
//Error erase(void);
//Error setDataKey(const uint8_t *newKey);
};
class [[gnu::packed]] ZS01Cart : public Cart {
private:
Error _transact(zs01::Packet &request, zs01::Packet &response);
public:
uint8_t data[112];
ZS01Cart(void);
Error readCartID(void);
Error readPublicData(void);
Error readPrivateData(void);
Error writeData(void);
Error erase(void);
Error setDataKey(const uint8_t *newKey);
};
}

37
src/cartdb.cpp Normal file
View File

@ -0,0 +1,37 @@
#include <stddef.h>
#include <stdint.h>
#include "asset.hpp"
#include "cart.hpp"
#include "cartdb.hpp"
#include "util.hpp"
namespace cartdb {
bool CartDB::init(void) {
if (!data.ptr)
return false;
auto &firstEntry = *reinterpret_cast<const Entry *>(data.ptr);
if (firstEntry.version != ENTRY_VERSION) {
LOG("unsupported DB version %d", firstEntry.version);
return false;
}
_chipType = firstEntry.chipType;
_entryLength = sizeof(Entry) + cart::getDataLength(_chipType);
numEntries = data.length / _entryLength;
return true;
}
IdentifyResult CartDB::identifyCart(cart::Cart &cart) const {
// TODO: implement this
LOG("no matching game found");
return UNIDENTIFIED;
}
}

79
src/cartdb.hpp Normal file
View File

@ -0,0 +1,79 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include "asset.hpp"
#include "cart.hpp"
namespace cartdb {
enum IdentifyResult {
UNIDENTIFIED = 0,
IDENTIFIED = 1,
BLANK = 2
};
enum EntryFlag : uint8_t {
HAS_SYSTEM_ID = 1 << 0,
HAS_CART_ID = 1 << 1,
HAS_ZS_ID = 1 << 2,
HAS_CHECKSUM = 1 << 3
};
static constexpr int ENTRY_VERSION = 1;
class [[gnu::packed]] Entry {
public:
uint8_t version;
cart::ChipType chipType;
uint8_t flags, _reserved;
uint8_t systemIDOffset, cartIDOffset, zsIDOffset, checksumOffset;
char code[8], region[8], name[64];
uint8_t dataKey[8], config[8];
inline int getDisplayName(char *output, size_t length) const {
return snprintf(output, length, "%s %s\t%s", code, region, name);
}
};
class [[gnu::packed]] X76F041Entry : public Entry {
public:
uint8_t data[512];
};
class [[gnu::packed]] X76F100Entry : public Entry {
public:
uint8_t data[112];
};
class [[gnu::packed]] ZS01Entry : public Entry {
public:
uint8_t data[112];
};
class CartDB {
private:
cart::ChipType _chipType;
size_t _entryLength;
public:
asset::Asset data;
size_t numEntries;
inline CartDB(void)
: _entryLength(0), numEntries(0) {}
inline const Entry &getEntry(int index) const {
auto _data = reinterpret_cast<const uint8_t *>(data.ptr);
//assert(data);
return *reinterpret_cast<const Entry *>(&_data[index * _entryLength]);
}
bool init(void);
IdentifyResult identifyCart(cart::Cart &cart) const;
};
}

24
src/defs.hpp Normal file
View File

@ -0,0 +1,24 @@
#pragma once
#ifndef VERSION
#define VERSION "<unknown build>"
#endif
#ifdef NDEBUG
#define VERSION_STRING VERSION
#else
#define VERSION_STRING VERSION "-debug"
#endif
#define CH_UP_ARROW "\x80"
#define CH_DOWN_ARROW "\x81"
#define CH_LEFT_ARROW "\x82"
#define CH_RIGHT_ARROW "\x83"
#define CH_LEFT_BUTTON "\x84"
#define CH_RIGHT_BUTTON "\x85"
#define CH_START_BUTTON "\x86"
#define CH_CLOSED_LOCK "\x87"
#define CH_OPEN_LOCK "\x88"
#define CH_CHIP_ICON "\x89"
#define CH_CART_ICON "\x8a"

474
src/gpu.cpp Normal file
View File

@ -0,0 +1,474 @@
#include <assert.h>
#include <stdint.h>
#include "ps1/gpucmd.h"
#include "ps1/registers.h"
#include "ps1/system.h"
#include "gpu.hpp"
namespace gpu {
/* Basic API */
static constexpr int _DMA_CHUNK_SIZE = 8;
static constexpr int _DMA_TIMEOUT = 10000;
size_t upload(const RectWH &rect, const void *data, bool wait) {
size_t length = (rect.w * rect.h) / 2;
assert(!(length % _DMA_CHUNK_SIZE));
length = (length + _DMA_CHUNK_SIZE - 1) / _DMA_CHUNK_SIZE;
if (!waitForDMATransfer(DMA_GPU, _DMA_TIMEOUT))
return 0;
GPU_GP1 = gp1_dmaRequestMode(GP1_DREQ_NONE);
while (!(GPU_GP1 & GP1_STAT_CMD_READY))
__asm__ volatile("");
GPU_GP0 = gp0_flushCache();
GPU_GP0 = gp0_vramWrite();
GPU_GP0 = gp0_xy(rect.x, rect.y);
GPU_GP0 = gp0_xy(rect.w, rect.h);
GPU_GP1 = gp1_dmaRequestMode(GP1_DREQ_GP0_WRITE);
while (!(GPU_GP1 & GP1_STAT_WRITE_READY))
__asm__ volatile("");
DMA_MADR(DMA_GPU) = reinterpret_cast<uint32_t>(data);
DMA_BCR (DMA_GPU) = _DMA_CHUNK_SIZE | (length << 16);
DMA_CHCR(DMA_GPU) = DMA_CHCR_WRITE | DMA_CHCR_MODE_SLICE | DMA_CHCR_ENABLE;
if (wait)
waitForDMATransfer(DMA_GPU, _DMA_TIMEOUT);
return length * _DMA_CHUNK_SIZE * 4;
}
/* Rendering context */
void Context::_flushLayer(void) {
if (_currentListPtr == _lastListPtr)
return;
auto layer = _drawBuffer().layers.pushItem();
assert(layer);
*(_currentListPtr++) = gp0_endTag(1);
*(_currentListPtr++) = gp0_irq();
*layer = _lastListPtr;
_lastListPtr = _currentListPtr;
}
void Context::_applyResolution(VideoMode mode, int shiftX, int shiftY) const {
GP1HorizontalRes hres;
GP1VerticalRes vres = (height > 256) ? GP1_VRES_512 : GP1_VRES_256;
int span;
if (width < 320) {
hres = GP1_HRES_256;
span = width * 10;
} else if (width < 368) {
hres = GP1_HRES_320;
span = width * 8;
} else if (width < 512) {
hres = GP1_HRES_368;
span = width * 7;
} else if (width < 640) {
hres = GP1_HRES_512;
span = width * 5;
} else {
hres = GP1_HRES_640;
span = width * 4;
}
int x = shiftX + 0x760, offsetX = span / 2;
int y = shiftY + (mode ? 0xa3 : 0x88), offsetY = height / (vres ? 4 : 2);
GPU_GP1 = gp1_fbMode(hres, vres, mode, height > 256, GP1_COLOR_16BPP);
GPU_GP1 = gp1_fbRangeH(x - offsetX, x + offsetX);
GPU_GP1 = gp1_fbRangeV(y - offsetY, y + offsetY);
}
void Context::flip(void) {
auto &oldBuffer = _drawBuffer(), &newBuffer = _dispBuffer();
// Ensure the GPU has finished drawing the previous frame.
while (newBuffer.layers.length)
__asm__ volatile("");
auto mask = setInterruptMask(0);
_flushLayer();
_currentListPtr = newBuffer.displayList;
_lastListPtr = newBuffer.displayList;
_currentBuffer ^= 1;
GPU_GP1 = gp1_fbOffset(oldBuffer.clip.x1, oldBuffer.clip.y1);
// Kick off drawing.
drawNextLayer();
if (mask)
setInterruptMask(mask);
}
void Context::drawNextLayer(void) {
//auto mask = setInterruptMask(0);
auto layer = _dispBuffer().layers.popItem();
//if (mask)
//setInterruptMask(mask);
if (!layer)
return;
while (DMA_CHCR(DMA_GPU) & DMA_CHCR_ENABLE)
__asm__ volatile("");
while (!(GPU_GP1 & GP1_STAT_CMD_READY))
__asm__ volatile("");
GPU_GP1 = gp1_acknowledge();
GPU_GP1 = gp1_dmaRequestMode(GP1_DREQ_GP0_WRITE);
DMA_MADR(DMA_GPU) = reinterpret_cast<uint32_t>(*layer);
DMA_CHCR(DMA_GPU) = DMA_CHCR_WRITE | DMA_CHCR_MODE_LIST | DMA_CHCR_ENABLE;
}
void Context::setResolution(
VideoMode mode, int _width, int _height, bool sideBySide
) {
auto mask = setInterruptMask(0);
width = _width;
height = _height;
refreshRate = mode ? 50 : 60;
for (int fb = 1; fb >= 0; fb--) {
auto &clip = _buffers[fb].clip;
clip.x1 = sideBySide ? (_width * fb) : 0;
clip.y1 = sideBySide ? 0 : (_height * fb);
clip.x2 = clip.x1 + _width - 1;
clip.y2 = clip.y1 + _height - 1;
}
_currentListPtr = _buffers[0].displayList;
_lastListPtr = _buffers[0].displayList;
_currentBuffer = 0;
_applyResolution(mode);
if (mask)
setInterruptMask(mask);
}
uint32_t *Context::newPacket(size_t length) {
auto ptr = _currentListPtr;
_currentListPtr = &ptr[length + 1];
//assert(_currentListPtr <= &_drawBuffer().displayList[DISPLAY_LIST_SIZE]);
*(ptr++) = gp0_tag(length, _currentListPtr);
return ptr;
}
void Context::newLayer(int x, int y, int drawWidth, int drawHeight) {
auto mask = setInterruptMask(0);
_flushLayer();
if (mask)
setInterruptMask(mask);
auto &clip = _dispBuffer().clip;
x += clip.x1;
y += clip.y1;
auto cmd = newPacket(3);
cmd[0] = gp0_fbOrigin(x, y);
cmd[1] = gp0_fbOffset1(
util::max(int(clip.x1), x),
util::max(int(clip.y1), y)
);
cmd[2] = gp0_fbOffset2(
util::min(int(clip.x2), x + drawWidth - 1),
util::min(int(clip.y2), y + drawHeight - 1)
);
}
void Context::setTexturePage(uint16_t page, bool dither) {
uint32_t cmd = gp0_texpage(page, dither, false);
if (cmd != _lastTexpage) {
*newPacket(1) = cmd;
_lastTexpage = cmd;
}
}
void Context::setBlendMode(BlendMode blendMode, bool dither) {
uint16_t page = _lastTexpage & ~gp0_texpage(
gp0_page(0, 0, GP0_BLEND_BITMASK, GP0_COLOR_4BPP), true, true
);
page |= gp0_page(0, 0, blendMode, GP0_COLOR_4BPP);
setTexturePage(page, dither);
}
void Context::drawRect(
int x, int y, int width, int height, Color color, bool blend
) {
auto cmd = newPacket(3);
cmd[0] = color | gp0_rectangle(false, false, blend);
cmd[1] = gp0_xy(x, y);
cmd[2] = gp0_xy(width, height);
}
void Context::drawGradientRectH(
int x, int y, int width, int height, Color left, Color right, bool blend
) {
auto cmd = newPacket(8);
cmd[0] = left | gp0_shadedQuad(true, false, blend);
cmd[1] = gp0_xy(x, y);
cmd[2] = right;
cmd[3] = gp0_xy(x + width, y);
cmd[4] = left;
cmd[5] = gp0_xy(x, y + height);
cmd[6] = right;
cmd[7] = gp0_xy(x + width, y + height);
}
void Context::drawGradientRectV(
int x, int y, int width, int height, Color top, Color bottom, bool blend
) {
auto cmd = newPacket(8);
cmd[0] = top | gp0_shadedQuad(true, false, blend);
cmd[1] = gp0_xy(x, y);
cmd[2] = top;
cmd[3] = gp0_xy(x + width, y);
cmd[4] = bottom;
cmd[5] = gp0_xy(x, y + height);
cmd[6] = bottom;
cmd[7] = gp0_xy(x + width, y + height);
}
void Context::drawGradientRectD(
int x, int y, int width, int height, Color top, Color middle, Color bottom,
bool blend
) {
auto cmd = newPacket(8);
cmd[0] = top | gp0_shadedQuad(true, false, blend);
cmd[1] = gp0_xy(x, y);
cmd[2] = middle;
cmd[3] = gp0_xy(x + width, y);
cmd[4] = middle;
cmd[5] = gp0_xy(x, y + height);
cmd[6] = bottom;
cmd[7] = gp0_xy(x + width, y + height);
}
void Context::drawBackdrop(Color color, BlendMode blendMode) {
setBlendMode(blendMode, true);
drawRect(0, 0, width, height, color, true);
}
/* Image and font classes */
void Image::initFromVRAMRect(
const RectWH &rect, ColorDepth colorDepth, BlendMode blendMode
) {
int shift = 2 - int(colorDepth);
u = (rect.x & 0x3f) << shift;
v = rect.y & 0xff;
width = rect.w << shift;
height = rect.h;
texpage = gp0_page(rect.x / 64, rect.y / 256, blendMode, colorDepth);
}
bool Image::initFromTIMHeader(const TIMHeader *header, BlendMode blendMode) {
if (header->magic != 0x10)
return false;
auto ptr = reinterpret_cast<const uint8_t *>(&header[1]);
if (header->flags & (1 << 3)) {
auto clut = reinterpret_cast<const TIMSectionHeader *>(ptr);
palette = gp0_clut(clut->vram.x / 16, clut->vram.y);
ptr += clut->length;
}
auto image = reinterpret_cast<const TIMSectionHeader *>(ptr);
initFromVRAMRect(image->vram, ColorDepth(header->flags & 3), blendMode);
return true;
}
void Image::drawScaled(
Context &ctx, int x, int y, int w, int h, bool blend
) const {
int x2 = x + w, u2 = u + width;
int y2 = y + h, v2 = v + height;
auto cmd = ctx.newPacket(9);
cmd[0] = gp0_quad(true, blend);
cmd[1] = gp0_xy(x, y);
cmd[2] = gp0_uv(u, v, palette);
cmd[3] = gp0_xy(x2, y);
cmd[4] = gp0_uv(u2, v, texpage);
cmd[5] = gp0_xy(x, y2);
cmd[6] = gp0_uv(u, v2, 0);
cmd[7] = gp0_xy(x2, y2);
cmd[8] = gp0_uv(u2, v2, 0);
}
void Image::draw(Context &ctx, int x, int y, bool blend) const {
ctx.setTexturePage(texpage);
auto cmd = ctx.newPacket(4);
cmd[0] = gp0_rectangle(true, true, blend);
cmd[1] = gp0_xy(x, y);
cmd[2] = gp0_uv(u, v, palette);
cmd[3] = gp0_xy(width, height);
}
void Font::draw(
Context &ctx, const char *str, const Rect &rect, Color color, bool wordWrap
) const {
// This is required for non-ASCII characters to work properly.
auto _str = reinterpret_cast<const uint8_t *>(str);
if (!str)
return;
ctx.setTexturePage(image.texpage);
int x = rect.x1;
int y = rect.y1;
for (uint8_t ch = *_str; ch; ch = *(++_str)) {
bool wrap = wordWrap;
assert(ch < (FONT_CHAR_OFFSET + FONT_CHAR_COUNT));
switch (ch) {
case '\t':
x += FONT_TAB_WIDTH - 1;
x -= x % FONT_TAB_WIDTH;
break;
case '\n':
x = rect.x1;
y += FONT_LINE_HEIGHT;
break;
case '\r':
x = rect.x1;
break;
case ' ':
x += FONT_SPACE_WIDTH;
break;
default:
uint32_t size = metrics[ch - FONT_CHAR_OFFSET];
int u = size & 0xff; size >>= 8;
int v = size & 0xff; size >>= 8;
int w = size & 0x7f; size >>= 7;
int h = size & 0x7f; size >>= 7;
auto cmd = ctx.newPacket(4);
cmd[0] = color | gp0_rectangle(true, size, true);
cmd[1] = gp0_xy(x, y);
cmd[2] = gp0_uv(u + image.u, v + image.v, image.palette);
cmd[3] = gp0_xy(w, h);
x += w;
wrap = false;
}
// Handle word wrapping by calculating the length of the next word and
// checking if it can still fit in the current line.
int boundaryX = rect.x2;
if (wrap)
boundaryX -= getStringWidth(
reinterpret_cast<const char *>(&_str[1]), true
);
if (x > boundaryX) {
x = rect.x1;
y += FONT_LINE_HEIGHT;
}
if (y > rect.y2)
break;
}
}
void Font::draw(
Context &ctx, const char *str, const RectWH &rect, Color color,
bool wordWrap
) const {
Rect _rect{
.x1 = rect.x,
.y1 = rect.y,
.x2 = int16_t(rect.x + rect.w),
.y2 = int16_t(rect.y + rect.h)
};
draw(ctx, str, _rect, color, wordWrap);
}
int Font::getStringWidth(const char *str, bool breakOnSpace) const {
auto _str = reinterpret_cast<const uint8_t *>(str);
if (!str)
return 0;
int width = 0, maxWidth = 0;
for (uint8_t ch = *_str; ch; ch = *(++_str)) {
assert(ch < (FONT_CHAR_OFFSET + FONT_CHAR_COUNT));
switch (ch) {
case '\t':
if (breakOnSpace)
goto _break;
width += FONT_TAB_WIDTH - 1;
width -= width % FONT_TAB_WIDTH;
break;
case '\n':
case '\r':
if (breakOnSpace)
goto _break;
if (width > maxWidth)
maxWidth = width;
width = 0;
break;
case ' ':
if (breakOnSpace)
goto _break;
width += FONT_SPACE_WIDTH;
break;
default:
width += (metrics[ch - FONT_CHAR_OFFSET] >> 16) & 0x7f;
}
}
_break:
return (width > maxWidth) ? width : maxWidth;
}
}

199
src/gpu.hpp Normal file
View File

@ -0,0 +1,199 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
#include "ps1/gpucmd.h"
#include "ps1/registers.h"
#include "util.hpp"
namespace gpu {
/* Types */
using Color = uint32_t;
using BlendMode = GP0BlendMode;
using ColorDepth = GP0ColorDepth;
using VideoMode = GP1VideoMode;
struct Rect {
public:
int16_t x1, y1, x2, y2;
};
struct RectWH {
public:
int16_t x, y, w, h;
};
struct RectRB {
public:
int16_t x, y, r, b;
};
/* Basic API */
static inline void init(void) {
GPU_GP1 = gp1_resetGPU();
GPU_GP1 = gp1_resetFIFO();
TIMER_CTRL(0) = TIMER_CTRL_EXT_CLOCK;
TIMER_CTRL(1) = TIMER_CTRL_EXT_CLOCK;
}
static inline void enableDisplay(bool enable) {
GPU_GP1 = gp1_dispBlank(!enable);
}
size_t upload(const RectWH &rect, const void *data, bool wait);
/* Rendering context */
static constexpr size_t DISPLAY_LIST_SIZE = 0x4000;
static constexpr size_t LAYER_STACK_SIZE = 16;
struct Buffer {
public:
Rect clip;
uint32_t displayList[DISPLAY_LIST_SIZE];
volatile util::RingBuffer<uint32_t *volatile, LAYER_STACK_SIZE> layers;
};
class Context {
private:
Buffer _buffers[2];
uint32_t *_currentListPtr, *_lastListPtr;
int _currentBuffer;
uint32_t _lastTexpage;
inline Buffer &_drawBuffer(void) {
return _buffers[_currentBuffer];
}
inline Buffer &_dispBuffer(void) {
return _buffers[_currentBuffer ^ 1];
}
void _flushLayer(void);
void _applyResolution(VideoMode mode, int shiftX = 0, int shiftY = 0) const;
public:
int width, height, refreshRate;
inline Context(
VideoMode mode, int width, int height, bool sideBySide = false
) : _lastTexpage(0) {
setResolution(mode, width, height, sideBySide);
}
inline void newLayer(int x, int y) {
newLayer(x, y, width, height);
}
inline void drawRect(RectWH &rect, Color color, bool blend = false) {
drawRect(rect.x, rect.y, rect.w, rect.h, color, blend);
}
inline void drawGradientRectH(
RectWH &rect, Color left, Color right, bool blend = false
) {
drawGradientRectH(rect.x, rect.y, rect.w, rect.h, left, right, blend);
}
inline void drawGradientRectV(
RectWH &rect, Color top, Color bottom, bool blend = false
) {
drawGradientRectV(rect.x, rect.y, rect.w, rect.h, top, bottom, blend);
}
inline void drawGradientRectD(
RectWH &rect, Color top, Color middle, Color bottom, bool blend = false
) {
drawGradientRectD(
rect.x, rect.y, rect.w, rect.h, top, middle, bottom, blend
);
}
void setResolution(
VideoMode mode, int width, int height, bool sideBySide = false
);
void drawNextLayer(void);
void flip(void);
uint32_t *newPacket(size_t length);
void newLayer(int x, int y, int drawWidth, int drawHeight);
void setTexturePage(uint16_t page, bool dither = false);
void setBlendMode(BlendMode blendMode, bool dither = false);
void drawRect(
int x, int y, int width, int height, Color color, bool blend = false
);
void drawGradientRectH(
int x, int y, int width, int height, Color left, Color right,
bool blend = false
);
void drawGradientRectV(
int x, int y, int width, int height, Color top, Color bottom,
bool blend = false
);
void drawGradientRectD(
int x, int y, int width, int height, Color top, Color middle,
Color bottom, bool blend = false
);
void drawBackdrop(Color color, BlendMode blendMode);
};
/* Image and font classes */
struct [[gnu::packed]] TIMHeader {
public:
uint32_t magic, flags;
};
struct [[gnu::packed]] TIMSectionHeader {
public:
uint32_t length;
RectWH vram;
};
class Image {
public:
uint16_t u, v, width, height;
uint16_t texpage, palette;
inline Image(void)
: width(0), height(0) {}
void initFromVRAMRect(
const RectWH &rect, ColorDepth colorDepth,
BlendMode blendMode = GP0_BLEND_SEMITRANS
);
bool initFromTIMHeader(
const TIMHeader *header, BlendMode blendMode = GP0_BLEND_SEMITRANS
);
void drawScaled(
Context &ctx, int x, int y, int w, int h, bool blend = false
) const;
void draw(Context &ctx, int x, int y, bool blend = false) const;
};
static constexpr int FONT_CHAR_OFFSET = ' ';
static constexpr int FONT_CHAR_COUNT = 120;
static constexpr int FONT_SPACE_WIDTH = 4;
static constexpr int FONT_TAB_WIDTH = 32;
static constexpr int FONT_LINE_HEIGHT = 10;
class Font {
public:
Image image;
uint32_t metrics[FONT_CHAR_COUNT];
void draw(
Context &ctx, const char *str, const Rect &rect, Color color = 0x808080,
bool wordWrap = false
) const;
void draw(
Context &ctx, const char *str, const RectWH &rect,
Color color = 0x808080, bool wordWrap = false
) const;
int getStringWidth(const char *str, bool breakOnSpace = false) const;
};
}

405
src/io.cpp Normal file
View File

@ -0,0 +1,405 @@
#include <stddef.h>
#include <stdint.h>
#include "ps1/registers.h"
#include "ps1/system.h"
#include "io.hpp"
#include "util.hpp"
namespace io {
uint16_t _bankSwitchReg, _cartOutputReg, _miscOutputReg;
void init(void) {
_bankSwitchReg = 0;
_cartOutputReg = 0;
_miscOutputReg = 0x0107;
BIU_DEV0_ADDR = 0x1f000000;
BIU_DEV0_CTRL = 0
| (7 << 0) // Write delay
| (4 << 4) // Read delay
| BIU_CTRL_RECOVERY
| BIU_CTRL_HOLD
| BIU_CTRL_FLOAT
| BIU_CTRL_PRESTROBE
| BIU_CTRL_WIDTH_16
| BIU_CTRL_AUTO_INCR
| (23 << 16) // Number of address lines
| ( 4 << 24) // DMA read/write delay
| BIU_CTRL_DMA_DELAY;
SYS573_WATCHDOG = 0;
SYS573_BANK_CTRL = 0;
SYS573_CART_OUT = 0;
SYS573_MISC_OUT = 0x0107;
// Some of the digital I/O board's light outputs are controlled by the FPGA
// and cannot be turned off until the FPGA is initialized.
if (isDigitalIOPresent()) {
//SYS573D_CPLD_LIGHTS_B0 = 0xf000;
SYS573D_CPLD_LIGHTS_C0 = 0xf000;
SYS573D_CPLD_LIGHTS_C1 = 0xf000;
} else {
SYS573A_LIGHTS_A = 0x00ff;
SYS573A_LIGHTS_B = 0x00ff;
SYS573A_LIGHTS_C = 0x00ff;
SYS573A_LIGHTS_D = 0x00ff;
}
}
uint32_t getJAMMAInputs(void) {
uint32_t inputs;
inputs = SYS573_JAMMA_MAIN;
inputs |= (SYS573_JAMMA_EXT1 & 0x0f00) << 8;
inputs |= (SYS573_JAMMA_EXT2 & 0x0f00) << 12;
inputs |= (SYS573_MISC_IN & 0x1f00) << 16;
return inputs ^ 0x1fffffff;
}
/* Digital I/O board driver */
static void _writeBitstreamLSB(const uint8_t *data, size_t length) {
for (; length; length--) {
uint16_t bits = *(data++);
for (int i = 8; i; i--, bits >>= 1)
SYS573D_CPLD_BITSTREAM = (bits & 1) << 15;
}
}
static void _writeBitstreamMSB(const uint8_t *data, size_t length) {
for (; length; length--) {
uint16_t bits = *(data++) << 8;
for (int i = 8; i; i--, bits <<= 1)
SYS573D_CPLD_BITSTREAM = bits & (1 << 15);
}
}
bool loadBitstream(const uint8_t *data, size_t length) {
if (data[0] != 0xff)
return false;
// Konami's bitstreams are always stored LSB first, however Xilinx tools
// seem to export bitstreams MSB first by default. The only way out of this
// mess is to autodetect the bit order by checking for preamble and frame
// start sequences, as specified in the XCS40XL datasheet.
uint8_t id1 = data[1], id2 = data[4];
void (*writeFunc)(const uint8_t *, size_t);
if (((id1 & 0x0f) == 0x04) && ((id2 & 0xf0) == 0xf0))
writeFunc = &_writeBitstreamLSB;
else if (((id1 & 0xf0) == 0x20) && ((id2 & 0x0f) == 0x0f))
writeFunc = &_writeBitstreamMSB;
else
return false;
for (int i = 3; i; i--) {
SYS573D_CPLD_UNK_RESET = 0;
SYS573D_CPLD_CTRL = SYS573D_CPLD_CTRL_UNK4;
SYS573D_CPLD_CTRL = SYS573D_CPLD_CTRL_UNK4 | SYS573D_CPLD_CTRL_UNK3;
SYS573D_CPLD_CTRL = SYS573D_CPLD_CTRL_UNK4 | SYS573D_CPLD_CTRL_UNK3 |
SYS573D_CPLD_CTRL_UNK2 | SYS573D_CPLD_CTRL_UNK1;
delayMicroseconds(5000);
if (!(SYS573D_CPLD_STAT & SYS573D_CPLD_STAT_INIT))
continue;
writeFunc(data, length);
for (int j = 15; j; j--) {
if (
(SYS573D_CPLD_STAT & (SYS573D_CPLD_STAT_INIT | SYS573D_CPLD_STAT_DONE))
== (SYS573D_CPLD_STAT_INIT | SYS573D_CPLD_STAT_DONE)
)
return true;
delayMicroseconds(1000);
}
}
return false;
}
void initKonamiBitstream(void) {
SYS573D_FPGA_INIT = 0xf000;
SYS573D_FPGA_INIT = 0x0000;
delayMicroseconds(1000);
SYS573D_FPGA_INIT = 0xf000;
delayMicroseconds(1000);
// Turn off all lights including the ones that were left on by init().
SYS573D_FPGA_LIGHTS_A0 = 0xf000;
SYS573D_FPGA_LIGHTS_A1 = 0xf000;
SYS573D_CPLD_LIGHTS_B0 = 0xf000;
SYS573D_FPGA_LIGHTS_B1 = 0xf000;
SYS573D_CPLD_LIGHTS_C0 = 0xf000;
SYS573D_CPLD_LIGHTS_C1 = 0xf000;
SYS573D_FPGA_LIGHTS_D0 = 0xf000;
}
/* I2C driver */
// SDA is open-drain so it is toggled by changing pin direction.
#define _SDA(value) setCartSDADir(!(value))
#define SDA(value) _SDA(value), delayMicroseconds(20)
#define _SCL(value) setCartOutput(OUT_SCL, value)
#define SCL(value) _SCL(value), delayMicroseconds(20)
#define _CS(value) setCartOutput(OUT_CS, value)
#define CS(value) _CS(value), delayMicroseconds(20)
#define _RESET(value) setCartOutput(OUT_RESET, value)
#define RESET(value) _RESET(value), delayMicroseconds(20)
void i2cStart(void) {
_SDA(true);
SCL(true);
SDA(false); // START: SDA falling, SCL high
SCL(false);
}
void i2cStartWithCS(int csDelay) {
_SDA(true);
_SCL(true);
CS(true);
CS(false);
delayMicroseconds(csDelay);
SDA(false); // START: SDA falling, SCL high
SCL(false);
}
void i2cStop(void) {
_SDA(false);
SCL(true);
SDA(true); // STOP: SDA rising, SCL high
}
void i2cStopWithCS(int csDelay) {
_SDA(false);
SCL(true);
SDA(true); // STOP: SDA rising, SCL high
delayMicroseconds(csDelay);
CS(true);
}
uint8_t i2cReadByte(void) {
uint8_t value = 0;
for (int bit = 7; bit >= 0; bit--) { // MSB first
SCL(true);
if (getCartSDA())
value |= (1 << bit);
SCL(false);
}
delayMicroseconds(20);
return value;
}
void i2cWriteByte(uint8_t value) {
for (int bit = 7; bit >= 0; bit--) { // MSB first
_SDA(value & (1 << bit));
SCL(true);
SCL(false);
}
SDA(true);
}
void i2cSendACK(bool ack) {
_SDA(!ack);
SCL(true);
SCL(false);
SDA(true);
}
bool i2cGetACK(void) {
delayMicroseconds(20); // Required for ZS01
SCL(true);
bool ack = !getCartSDA();
SCL(false);
delayMicroseconds(20);
return ack;
}
void i2cReadBytes(uint8_t *data, size_t length) {
for (; length; length--) {
*(data++) = i2cReadByte();
if (length > 1)
i2cSendACK(true);
}
}
bool i2cWriteBytes(const uint8_t *data, size_t length, int lastACKDelay) {
for (; length; length--) {
i2cWriteByte(*(data++));
if (length == 1)
delayMicroseconds(lastACKDelay);
if (!i2cGetACK())
return false;
}
return true;
}
uint32_t i2cResetX76(void) {
uint32_t value = 0;
_SDA(true);
_SCL(false);
_CS(false);
_RESET(false);
RESET(true);
SCL(true);
SCL(false);
RESET(false);
for (int bit = 0; bit < 32; bit++) { // LSB first
SCL(true);
if (getCartSDA())
value |= (1 << bit);
SCL(false);
}
SCL(true);
CS(true);
return value;
}
// For whatever reason the ZS01 does not implement the exact same response to
// reset protocol as the X76 chips. The reset pin is also active-low rather
// than active-high, and CS is ignored.
uint32_t i2cResetZS01(void) {
uint32_t value = 0;
_SDA(true);
_SCL(false);
_CS(false);
_RESET(true);
RESET(false);
RESET(true);
delayMicroseconds(100);
SCL(true);
SCL(false);
for (int bit = 31; bit >= 0; bit--) { // MSB first
if (getCartSDA())
value |= (1 << bit);
SCL(true);
SCL(false);
}
SCL(true);
return value;
}
/* 1-wire driver */
#define _CART1WIRE(value) setCartOutput(OUT_1WIRE, !(value))
#define _DIO1WIRE(value) setDIO1Wire(value)
bool dsCartReset(void) {
_CART1WIRE(false);
delayMicroseconds(480);
_CART1WIRE(true);
delayMicroseconds(60);
bool present = !getCartInput(IN_1WIRE);
delayMicroseconds(60);
delayMicroseconds(1000);
return present;
}
bool dsDIOReset(void) {
_DIO1WIRE(false);
delayMicroseconds(480);
_DIO1WIRE(true);
delayMicroseconds(60);
bool present = !getDIO1Wire();
delayMicroseconds(60);
delayMicroseconds(1000);
return present;
}
uint8_t dsCartReadByte(void) {
uint8_t value = 0;
for (int bit = 0; bit < 8; bit++) { // LSB first
_CART1WIRE(false);
delayMicroseconds(2);
_CART1WIRE(true);
delayMicroseconds(10);
if (getCartInput(IN_1WIRE))
value |= (1 << bit);
delayMicroseconds(50);
}
return value;
}
uint8_t dsDIOReadByte(void) {
uint8_t value = 0;
for (int bit = 0; bit < 8; bit++) { // LSB first
_DIO1WIRE(false);
delayMicroseconds(2);
_DIO1WIRE(true);
delayMicroseconds(10);
if (getDIO1Wire())
value |= (1 << bit);
delayMicroseconds(50);
}
return value;
}
void dsCartWriteByte(uint8_t value) {
for (int bit = 0; bit < 8; bit++) { // LSB first
if (value & (1 << bit)) {
_CART1WIRE(false);
delayMicroseconds(2);
_CART1WIRE(true);
delayMicroseconds(60);
} else {
_CART1WIRE(false);
delayMicroseconds(60);
_CART1WIRE(true);
delayMicroseconds(2);
}
}
}
void dsDIOWriteByte(uint8_t value) {
for (int bit = 0; bit < 8; bit++) { // LSB first
if (value & (1 << bit)) {
_DIO1WIRE(false);
delayMicroseconds(2);
_DIO1WIRE(true);
delayMicroseconds(60);
} else {
_DIO1WIRE(false);
delayMicroseconds(60);
_DIO1WIRE(true);
delayMicroseconds(2);
}
}
}
}

180
src/io.hpp Normal file
View File

@ -0,0 +1,180 @@
#pragma once
#include <stdint.h>
#include "ps1/registers.h"
namespace io {
/* Register and bit definitions */
enum JAMMAInput : uint32_t {
// SYS573_JAMMA_MAIN
JAMMA_P2_LEFT = 1 << 0,
JAMMA_P2_RIGHT = 1 << 1,
JAMMA_P2_UP = 1 << 2,
JAMMA_P2_DOWN = 1 << 3,
JAMMA_P2_BUTTON1 = 1 << 4,
JAMMA_P2_BUTTON2 = 1 << 5,
JAMMA_P2_BUTTON3 = 1 << 6,
JAMMA_P2_START = 1 << 7,
JAMMA_P1_LEFT = 1 << 8,
JAMMA_P1_RIGHT = 1 << 9,
JAMMA_P1_UP = 1 << 10,
JAMMA_P1_DOWN = 1 << 11,
JAMMA_P1_BUTTON1 = 1 << 12,
JAMMA_P1_BUTTON2 = 1 << 13,
JAMMA_P1_BUTTON3 = 1 << 14,
JAMMA_P1_START = 1 << 15,
// SYS573_JAMMA_EXT1
JAMMA_P1_BUTTON4 = 1 << 16,
JAMMA_P1_BUTTON5 = 1 << 17,
JAMMA_TEST = 1 << 18,
JAMMA_P1_BUTTON6 = 1 << 19,
// SYS573_JAMMA_EXT2
JAMMA_P2_BUTTON4 = 1 << 20,
JAMMA_P2_BUTTON5 = 1 << 21,
JAMMA_UNKNOWN = 1 << 22,
JAMMA_P2_BUTTON6 = 1 << 23,
// SYS573_MISC_IN
JAMMA_COIN1 = 1 << 24,
JAMMA_COIN2 = 1 << 25,
JAMMA_PCMCIA_CD1 = 1 << 26,
JAMMA_PCMCIA_CD2 = 1 << 27,
JAMMA_SERVICE = 1 << 28
};
enum CartInputPin {
IN_1WIRE = 6
};
enum CartOutputPin {
OUT_SDA = 0,
OUT_SCL = 1,
OUT_CS = 2,
OUT_RESET = 3,
OUT_1WIRE = 4
};
enum MiscOutputPin {
MISC_ADC_MOSI = 0,
MISC_ADC_CS = 1,
MISC_ADC_SCK = 2,
MISC_COIN_COUNT1 = 3,
MISC_COIN_COUNT2 = 4,
MISC_AMP_ENABLE = 5,
MISC_CDDA_ENABLE = 6,
MISC_SPU_ENABLE = 7,
MISC_JVS_STAT = 8
};
/* Inputs */
static inline void clearWatchdog(void) {
SYS573_WATCHDOG = 0;
}
static inline uint32_t getDIPSwitches(void) {
return SYS573_DIP_CART & 0xf;
}
static inline bool getCartInsertionStatus(void) {
return (SIO_STAT(1) >> 7) & 1;
}
static inline bool getCartSerialStatus(void) {
SIO_CTRL(1) |= 1 << 5;
return (SIO_STAT(1) >> 8) & 1;
}
/* Bitbanged I/O */
extern uint16_t _bankSwitchReg, _cartOutputReg, _miscOutputReg;
static inline bool getCartInput(CartInputPin pin) {
return (SYS573_DIP_CART >> (8 + pin)) & 1;
}
static inline bool getCartSDA(void) {
return (SYS573_MISC_IN >> 2) & 1;
}
static inline void setCartOutput(CartOutputPin pin, bool value) {
if (value)
_cartOutputReg |= 1 << pin;
else
_cartOutputReg &= ~(1 << pin);
SYS573_CART_OUT = _cartOutputReg;
}
static inline void setCartSDADir(bool dir) {
if (dir)
_bankSwitchReg |= 1 << 6;
else
_bankSwitchReg &= ~(1 << 6);
SYS573_BANK_CTRL = _bankSwitchReg;
}
static inline void setMiscOutput(MiscOutputPin pin, bool value) {
if (value)
_miscOutputReg |= 1 << pin;
else
_miscOutputReg &= ~(1 << pin);
SYS573_MISC_OUT = _miscOutputReg;
}
/* Digital I/O board driver */
// TODO: these do not seem to actually be LDC and HDC...
static inline bool isDigitalIOPresent(void) {
return (
(SYS573D_CPLD_STAT & (SYS573D_CPLD_STAT_LDC | SYS573D_CPLD_STAT_HDC))
== SYS573D_CPLD_STAT_HDC
);
}
static inline bool getDIO1Wire(void) {
return (SYS573D_FPGA_DS2401 >> 12) & 1;
}
static inline void setDIO1Wire(bool value) {
SYS573D_FPGA_DS2401 = (value ^ 1) << 12;
}
/* Other APIs */
void init(void);
uint32_t getJAMMAInputs(void);
bool loadBitstream(const uint8_t *data, size_t length);
void initKonamiBitstream(void);
void i2cStart(void);
void i2cStartWithCS(int csDelay = 0);
void i2cStop(void);
void i2cStopWithCS(int csDelay = 0);
uint8_t i2cReadByte(void);
void i2cWriteByte(uint8_t value);
void i2cSendACK(bool ack);
bool i2cGetACK(void);
void i2cReadBytes(uint8_t *data, size_t length);
bool i2cWriteBytes(const uint8_t *data, size_t length, int lastACKDelay = 0);
uint32_t i2cResetX76(void);
uint32_t i2cResetZS01(void);
bool dsCartReset(void);
bool dsDIOReset(void);
uint8_t dsCartReadByte(void);
uint8_t dsDIOReadByte(void);
void dsCartWriteByte(uint8_t value);
void dsDIOWriteByte(uint8_t value);
}

36
src/libc/assert.h Normal file
View File

@ -0,0 +1,36 @@
/*
* ps1-bare-metal - (C) 2023 spicyjpeg
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
* INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
* LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
#pragma once
// NDEBUG is automatically defined by CMake when the executable is built in
// release mode.
#ifdef NDEBUG
#define assert(expr)
#else
#define assert(expr) \
((expr) ? ((void) 0) : _assertAbort(__FILE__, __LINE__, #expr))
#endif
#ifdef __cplusplus
extern "C" {
#endif
void _assertAbort(const char *file, int line, const char *expr);
#ifdef __cplusplus
}
#endif

77
src/libc/crt0.c Normal file
View File

@ -0,0 +1,77 @@
/*
* ps1-bare-metal - (C) 2023 spicyjpeg
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
* INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
* LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
#include <stdint.h>
#include <stddef.h>
#define _align(x, n) (((x) + ((n) - 1)) & ~((n) - 1))
typedef void (*Function)(void);
/* Linker symbols */
// These are defined by the linker script. Note that these are not variables,
// they are virtual symbols whose location matches their value. The simplest way
// to turn them into pointers is to declare them as arrays.
extern char _sdataStart[], _bssStart[], _bssEnd[];
extern const Function _preinitArrayStart[], _preinitArrayEnd[];
extern const Function _initArrayStart[], _initArrayEnd[];
extern const Function _finiArrayStart[], _finiArrayEnd[];
/* Heap API (used by malloc) */
static uintptr_t _heapEnd = (uintptr_t) _bssEnd;
static uintptr_t _heapLimit = 0x80200000; // TODO: add a way to change this
void *sbrk(ptrdiff_t incr) {
uintptr_t currentEnd = _heapEnd;
uintptr_t newEnd = _align(currentEnd + incr, 8);
if (newEnd >= _heapLimit)
return 0;
_heapEnd = newEnd;
return (void *) currentEnd;
}
/* Program entry point */
int main(int argc, const char **argv);
int _start(int argc, const char **argv) {
// Set $gp to point to the middle of the .sdata/.sbss sections, ensuring
// variables placed in those sections can be quickly accessed. See the
// linker script for more details.
__asm__ volatile("la $gp, _gp;");
// Set all uninitialized variables to zero by clearing the BSS section.
__builtin_memset(_bssStart, 0, _bssEnd - _bssStart);
// Invoke all global constructors if any, then main() and finally all global
// destructors.
for (const Function *ctor = _preinitArrayStart; ctor < _preinitArrayEnd; ctor++)
(*ctor)();
for (const Function *ctor = _initArrayStart; ctor < _initArrayEnd; ctor++)
(*ctor)();
int returnValue = main(argc, argv);
for (const Function *dtor = _initArrayStart; dtor < _initArrayEnd; dtor++)
(*dtor)();
return returnValue;
}

35
src/libc/ctype.h Normal file
View File

@ -0,0 +1,35 @@
/*
* ps1-bare-metal - (C) 2023 spicyjpeg
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
* INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
* LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
int isprint(int ch);
int isgraph(int ch);
int isspace(int ch);
int isblank(int ch);
int isalpha(int ch);
int isdigit(int ch);
int tolower(int ch);
int toupper(int ch);
#ifdef __cplusplus
}
#endif

50
src/libc/cxxsupport.cpp Normal file
View File

@ -0,0 +1,50 @@
/*
* ps1-bare-metal - (C) 2023 spicyjpeg
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
* INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
* LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
#include <stddef.h>
#include <stdlib.h>
extern "C" void *__builtin_new(size_t size) {
return malloc(size);
}
extern "C" void __builtin_delete(void *ptr) {
free(ptr);
}
void *operator new(size_t size) noexcept {
return malloc(size);
}
void *operator new[](size_t size) noexcept {
return malloc(size);
}
void operator delete(void *ptr) noexcept {
free(ptr);
}
void operator delete[](void *ptr) noexcept {
free(ptr);
}
void operator delete(void *ptr, size_t size) noexcept {
free(ptr);
}
void operator delete[](void *ptr, size_t size) noexcept {
free(ptr);
}

238
src/libc/malloc.c Normal file
View File

@ -0,0 +1,238 @@
/*
* ps1-bare-metal - (C) 2023 spicyjpeg
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
* INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
* LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*
* This code is based on psyqo's malloc implementation, available here:
* https://github.com/grumpycoders/pcsx-redux/blob/main/src/mips/psyqo/src/alloc.c
*/
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#define _align(x, n) (((x) + ((n) - 1)) & ~((n) - 1))
#define _updateHeapUsage(incr)
/* Internal state */
typedef struct _Block {
struct _Block *prev, *next;
void *ptr;
size_t size;
} Block;
static void *_mallocStart;
static Block *_mallocHead, *_mallocTail;
/* Allocator implementation */
static Block *_findBlock(Block *head, size_t size) {
Block *prev = head;
for (; prev; prev = prev->next) {
if (prev->next) {
uintptr_t nextBot = (uintptr_t) prev->next;
nextBot -= (uintptr_t) prev->ptr + prev->size;
if (nextBot >= size)
return prev;
}
}
return prev;
}
void *malloc(size_t size) {
if (!size)
return 0;
size_t _size = _align(size + sizeof(Block), 8);
// Nothing's initialized yet? Let's just initialize the bottom of our heap,
// flag it as allocated.
if (!_mallocHead) {
if (!_mallocStart)
_mallocStart = sbrk(0);
Block *new = (Block *) sbrk(_size);
if (!new)
return 0;
void *ptr = (void *) &new[1];
new->ptr = ptr;
new->size = _size - sizeof(Block);
new->prev = 0;
new->next = 0;
_mallocHead = new;
_mallocTail = new;
_updateHeapUsage(size);
return ptr;
}
// We *may* have the bottom of our heap that has shifted, because of a free.
// So let's check first if we have free space there, because I'm nervous
// about having an incomplete data structure.
if (((uintptr_t) _mallocStart + _size) < ((uintptr_t) _mallocHead)) {
Block *new = (Block *) _mallocStart;
void *ptr = (void *) &new[1];
new->ptr = ptr;
new->size = _size - sizeof(Block);
new->prev = 0;
new->next = _mallocHead;
_mallocHead->prev = new;
_mallocHead = new;
_updateHeapUsage(size);
return ptr;
}
// No luck at the beginning of the heap, let's walk the heap to find a fit.
Block *prev = _findBlock(_mallocHead, _size);
if (prev) {
Block *new = (Block *) ((uintptr_t) prev->ptr + prev->size);
void *ptr = (void *)((uintptr_t) new + sizeof(Block));
new->ptr = ptr;
new->size = _size - sizeof(Block);
new->prev = prev;
new->next = prev->next;
(new->next)->prev = new;
prev->next = new;
_updateHeapUsage(size);
return ptr;
}
// Time to extend the size of the heap.
Block *new = (Block *) sbrk(_size);
if (!new)
return 0;
void *ptr = (void *) &new[1];
new->ptr = ptr;
new->size = _size - sizeof(Block);
new->prev = _mallocTail;
new->next = 0;
_mallocTail->next = new;
_mallocTail = new;
_updateHeapUsage(size);
return ptr;
}
void *calloc(size_t num, size_t size) {
return malloc(num * size);
}
void *realloc(void *ptr, size_t size) {
if (!size) {
free(ptr);
return 0;
}
if (!ptr)
return malloc(size);
size_t _size = _align(size + sizeof(Block), 8);
Block *prev = (Block *) ((uintptr_t) ptr - sizeof(Block));
// New memory block shorter?
if (prev->size >= _size) {
_updateHeapUsage(size - prev->size);
prev->size = _size;
if (!prev->next)
sbrk((ptr - sbrk(0)) + _size);
return ptr;
}
// New memory block larger; is it the last one?
if (!prev->next) {
void *new = sbrk(_size - prev->size);
if (!new)
return 0;
_updateHeapUsage(size - prev->size);
prev->size = _size;
return ptr;
}
// Do we have free memory after it?
if (((prev->next)->ptr - ptr) > _size) {
_updateHeapUsage(size - prev->size);
prev->size = _size;
return ptr;
}
// No luck.
void *new = malloc(_size);
if (!new)
return 0;
__builtin_memcpy(new, ptr, prev->size);
free(ptr);
return new;
}
void free(void *ptr) {
if (!ptr || !_mallocHead)
return;
// First block; bumping head ahead.
if (ptr == _mallocHead->ptr) {
size_t size = _mallocHead->size;
size += (uintptr_t) _mallocHead->ptr - (uintptr_t) _mallocHead;
_mallocHead = _mallocHead->next;
if (_mallocHead) {
_mallocHead->prev = 0;
} else {
_mallocTail = 0;
sbrk(-size);
}
_updateHeapUsage(-(_mallocHead->size));
return;
}
// Finding the proper block
Block *cur = _mallocHead;
for (cur = _mallocHead; ptr != cur->ptr; cur = cur->next) {
if (!cur->next)
return;
}
if (cur->next) {
// In the middle, just unlink it
(cur->next)->prev = cur->prev;
} else {
// At the end, shrink heap
void *top = sbrk(0);
size_t size = (top - (cur->prev)->ptr) - (cur->prev)->size;
_mallocTail = cur->prev;
sbrk(-size);
}
_updateHeapUsage(-(cur->size));
(cur->prev)->next = cur->next;
}

134
src/libc/memset.s Normal file
View File

@ -0,0 +1,134 @@
# ps1-bare-metal - (C) 2023 spicyjpeg
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
# AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
# OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
# PERFORMANCE OF THIS SOFTWARE.
.set noreorder
# This is an optimized implementation of memset() that makes use of Duff's
# device and unaligned store instructions to fill large areas of memory much
# faster than a simple byte-by-byte loop would.
.section .text.memset, "ax", @progbits
.global memset
.type memset, @function
memset:
# If more than 16 bytes have to be written then take the "large" path,
# otherwise use the code below.
addiu $t0, $a2, -16
bgtz $t0, .LlargeFill
move $v0, $a0 # returnValue = dest
# Jump to one of the sb opcodes below. This is basically a cut-down Duff's
# device implementation with no looping.
la $t0, .LsmallDuff + 0x40 # addr = &smallDuff[(16 - count) * 4]
sll $t1, $a2, 2
subu $t0, $t1
addu $a0, $a2 # dest -= 16 - count
jr $t0
addiu $a0, -16
.LsmallDuff:
sb $a1, 0x0($a0)
sb $a1, 0x1($a0)
sb $a1, 0x2($a0)
sb $a1, 0x3($a0)
sb $a1, 0x4($a0)
sb $a1, 0x5($a0)
sb $a1, 0x6($a0)
sb $a1, 0x7($a0)
sb $a1, 0x8($a0)
sb $a1, 0x9($a0)
sb $a1, 0xa($a0)
sb $a1, 0xb($a0)
sb $a1, 0xc($a0)
sb $a1, 0xd($a0)
sb $a1, 0xe($a0)
sb $a1, 0xf($a0)
jr $ra
nop
.LlargeFill:
# Initialize fast filling by repeating the fill byte 4 times, so it can be
# written 32 bits at a time.
andi $a1, 0xff # ch &= 0xff
sll $t0, $a1, 8 # ch |= (ch << 8) | (ch << 16) | (ch << 24)
or $a1, $t0
sll $t0, $a1, 16
or $a1, $t0
# Fill the first 1-4 bytes (here the swr instruction does all the magic)
# and update dest and count accordingly.
swr $a1, 0($a0)
andi $t0, $a0, 3 # align = 4 - (dest % 4)
addiu $t0, -4
addu $a2, $t0 # count -= align
subu $a0, $t0 # dest += align
la $t1, .LlargeDuff
andi $t2, $a2, 3 # remainder = count % 4
subu $a2, $t2 # count -= remainder
.LlargeFillLoop:
# If 128 bytes or more still have to be written, skip calculating the jump
# offset and execute the whole block of sw opcodes.
addiu $a2, -0x80 # count -= 0x80
bgez $a2, .LlargeDuff
#nop
# Jump to one of the sw opcodes below. This is the "full" Duff's device.
subu $t0, $t1, $a2 # addr = &largeDuff[0x80 - (count + 0x80)]
jr $t0
addu $a0, $a2 # dest -= 0x80 - (count + 0x80)
.LlargeDuff:
sw $a1, 0x00($a0)
sw $a1, 0x04($a0)
sw $a1, 0x08($a0)
sw $a1, 0x0c($a0)
sw $a1, 0x10($a0)
sw $a1, 0x14($a0)
sw $a1, 0x18($a0)
sw $a1, 0x1c($a0)
sw $a1, 0x20($a0)
sw $a1, 0x24($a0)
sw $a1, 0x28($a0)
sw $a1, 0x2c($a0)
sw $a1, 0x30($a0)
sw $a1, 0x34($a0)
sw $a1, 0x38($a0)
sw $a1, 0x3c($a0)
sw $a1, 0x40($a0)
sw $a1, 0x44($a0)
sw $a1, 0x48($a0)
sw $a1, 0x4c($a0)
sw $a1, 0x50($a0)
sw $a1, 0x54($a0)
sw $a1, 0x58($a0)
sw $a1, 0x5c($a0)
sw $a1, 0x60($a0)
sw $a1, 0x64($a0)
sw $a1, 0x68($a0)
sw $a1, 0x6c($a0)
sw $a1, 0x70($a0)
sw $a1, 0x74($a0)
sw $a1, 0x78($a0)
sw $a1, 0x7c($a0)
bgtz $a2, .LlargeFillLoop
addiu $a0, 0x80 # dest += 0x80
# Fill the remaining 1-4 bytes, using (again) an unaligned store.
addu $a0, $t2 # lastByte = dest + remainder - 1
jr $ra
swl $a1, -1($a0)

87
src/libc/misc.c Normal file
View File

@ -0,0 +1,87 @@
/*
* ps1-bare-metal - (C) 2023 spicyjpeg
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
* INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
* LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
#include <stdio.h>
#include "ps1/registers.h"
/* Serial port stdin/stdout */
void initSerialIO(int baud) {
SIO_CTRL(1) = SIO_CTRL_RESET;
SIO_MODE(1) = SIO_MODE_BAUD_DIV16 | SIO_MODE_DATA_8 | SIO_MODE_STOP_1;
SIO_BAUD(1) = (F_CPU / 16) / baud;
SIO_CTRL(1) = SIO_CTRL_TX_ENABLE | SIO_CTRL_RX_ENABLE | SIO_CTRL_RTS;
}
void _putchar(char ch) {
// The serial interface will buffer but not send any data if the CTS input
// is not asserted, so we are going to abort if CTS is not set to avoid
// waiting forever.
while (
(SIO_STAT(1) & (SIO_STAT_TX_NOT_FULL | SIO_STAT_CTS)) == SIO_STAT_CTS
)
__asm__ volatile("");
if (SIO_STAT(1) & SIO_STAT_CTS)
SIO_DATA(1) = ch;
}
int _getchar(void) {
while (!(SIO_STAT(1) & SIO_STAT_RX_NOT_EMPTY))
__asm__ volatile("");
return SIO_DATA(1);
}
int _puts(const char *str) {
int length = 1;
for (; *str; str++, length++)
_putchar(*str);
_putchar('\n');
return length;
}
/* Abort functions */
void _assertAbort(const char *file, int line, const char *expr) {
#ifndef NDEBUG
printf("%s:%d: assert(%s)\n", file, line, expr);
#endif
for (;;)
__asm__ volatile("");
}
void abort(void) {
#ifndef NDEBUG
puts("abort()");
#endif
for (;;)
__asm__ volatile("");
}
void __cxa_pure_virtual(void) {
#ifndef NDEBUG
puts("__cxa_pure_virtual()");
#endif
for (;;)
__asm__ volatile("");
}

113
src/libc/misc.s Normal file
View File

@ -0,0 +1,113 @@
# ps1-bare-metal - (C) 2023 spicyjpeg
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
# AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
# OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
# PERFORMANCE OF THIS SOFTWARE.
.set noreorder
## setjmp() and longjmp()
# This is not a "proper" implementation of setjmp/longjmp as it does not save
# COP0 and GTE registers, but it is good enough for most use cases.
.section .text.setjmp, "ax", @progbits
.global setjmp
.type setjmp, @function
setjmp:
sw $ra, 0x00($a0)
sw $s0, 0x04($a0)
sw $s1, 0x08($a0)
sw $s2, 0x0c($a0)
sw $s3, 0x10($a0)
sw $s4, 0x14($a0)
sw $s5, 0x18($a0)
sw $s6, 0x1c($a0)
sw $s7, 0x20($a0)
sw $gp, 0x24($a0)
sw $sp, 0x28($a0)
sw $fp, 0x2c($a0)
jr $ra # return 0
li $v0, 0
.section .text.longjmp, "ax", @progbits
.global longjmp
.type longjmp, @function
longjmp:
lw $ra, 0x00($a0)
lw $s0, 0x04($a0)
lw $s1, 0x08($a0)
lw $s2, 0x0c($a0)
lw $s3, 0x10($a0)
lw $s4, 0x14($a0)
lw $s5, 0x18($a0)
lw $s6, 0x1c($a0)
lw $s7, 0x20($a0)
lw $gp, 0x24($a0)
lw $sp, 0x28($a0)
lw $fp, 0x2c($a0)
jr $ra # return status (from setjmp)
move $v0, $a1
## Leading zero count intrinsics
# libgcc provides two functions used internally by GCC to count the number of
# leading zeroes in a value, __clzsi2() (32-bit) and __clzdi2() (64-bit). We're
# going to override them with smaller implementations that make use of the GTE's
# LZCS/LZCR registers.
.set LZCS, $30
.set LZCR, $31
.section .text.__clzsi2, "ax", @progbits
.global __clzsi2
.type __clzsi2, @function
__clzsi2:
mtc2 $a0, LZCS
bltz $a0, .Lreturn # if (value & (1 << 31)) return 0
li $v0, 0
mfc2 $v0, LZCR # else return GTE_CLZ(value)
.Lreturn:
jr $ra
nop
.section .text.__clzdi2, "ax", @progbits
.global __clzdi2
.type __clzdi2, @function
__clzdi2:
mtc2 $a1, LZCS
bltz $a1, .Lreturn2 # if (msb & (1 << 31)) return 0
li $v0, 0
bnez $a1, .LreturnMSB # else if (msb) return GTE_CLZ(msb)
nop
.LnoMSB:
mtc2 $a0, LZCS
bltz $a0, .Lreturn2 # else if (lsb & (1 << 31)) return 32
li $v0, 32
mfc2 $v0, LZCR # else return 32 + GTE_CLZ(lsb)
jr $ra
addiu $v0, 32
.LreturnMSB:
mfc2 $v0, LZCR
.Lreturn2:
jr $ra
nop

38
src/libc/setjmp.h Normal file
View File

@ -0,0 +1,38 @@
/*
* ps1-bare-metal - (C) 2023 spicyjpeg
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
* INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
* LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
#pragma once
#include <stdint.h>
typedef struct _JumpBuffer {
uint32_t ra;
uint32_t s0, s1, s2, s3, s4, s5, s6, s7;
uint32_t gp, sp, fp;
} JumpBuffer;
typedef JumpBuffer *jmp_buf;
#ifdef __cplusplus
extern "C" {
#endif
int setjmp(jmp_buf env);
void longjmp(jmp_buf env, int status);
#ifdef __cplusplus
}
#endif

45
src/libc/stdio.h Normal file
View File

@ -0,0 +1,45 @@
/*
* ps1-bare-metal - (C) 2023 spicyjpeg
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
* INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
* LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
#pragma once
// Include printf() from the third-party library.
#include "vendor/printf.h"
#define putchar _putchar
#define getchar _getchar
#define puts _puts
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Initializes the serial port (SIO1) with the given baud rate, no
* parity, 8 data bits and 1 stop bit. Must be called prior to using putchar(),
* getchar(), puts() or printf().
*
* @param baud
*/
void initSerialIO(int baud);
void _putchar(char ch);
int _getchar(void);
int _puts(const char *str);
#ifdef __cplusplus
}
#endif

47
src/libc/stdlib.h Normal file
View File

@ -0,0 +1,47 @@
/*
* ps1-bare-metal - (C) 2023 spicyjpeg
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
* INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
* LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
#pragma once
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
static inline int abs(int value) {
return (value < 0) ? (-value) : value;
}
static inline long labs(long value) {
return (value < 0) ? (-value) : value;
}
void abort(void);
long strtol(const char *str, char **str_end, int base);
long long strtoll(const char *str, char **str_end, int base);
void *sbrk(ptrdiff_t incr);
void *malloc(size_t size);
void *calloc(size_t num, size_t size);
void *realloc(void *ptr, size_t size);
void free(void *ptr);
#ifdef __cplusplus
}
#endif

428
src/libc/string.c Normal file
View File

@ -0,0 +1,428 @@
/*
* ps1-bare-metal - (C) 2023 spicyjpeg
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
* INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
* LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
#include <ctype.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
/* Character manipulation */
int isprint(int ch) {
return (ch >= ' ') && (ch <= '~');
}
int isgraph(int ch) {
return (ch > ' ') && (ch <= '~');
}
int isspace(int ch) {
return (ch == ' ') || ((ch >= '\t') && (ch <= '\r'));
}
int isblank(int ch) {
return (ch == ' ') || (ch == '\t');
}
int isalpha(int ch) {
return ((ch >= 'A') && (ch <= 'Z')) || ((ch >= 'a') && (ch <= 'z'));
}
int isdigit(int ch) {
return (ch >= '0') && (ch <= '9');
}
int tolower(int ch) {
if ((ch >= 'A') && (ch <= 'Z'))
ch += 'a' - 'A';
return ch;
}
int toupper(int ch) {
if ((ch >= 'a') && (ch <= 'z'))
ch += 'A' - 'a';
return ch;
}
/* Memory buffer manipulation */
#if 0
void *memset(void *dest, int ch, size_t count) {
uint8_t *_dest = (uint8_t *) dest;
for (; count; count--)
*(_dest++) = (uint8_t) ch;
return dest;
}
#endif
void *memcpy(void *restrict dest, const void *restrict src, size_t count) {
uint8_t *_dest = (uint8_t *) dest;
const uint8_t *_src = (const uint8_t *) src;
for (; count; count--)
*(_dest++) = *(_src++);
return dest;
}
void *memccpy(void *restrict dest, const void *restrict src, int ch, size_t count) {
uint8_t *_dest = (uint8_t *) dest;
const uint8_t *_src = (const uint8_t *) src;
for (; count; count--) {
uint8_t a = *(_src++);
*(_dest++) = a;
if (a == ch)
return (void *) _dest;
}
return 0;
}
void *memmove(void *dest, const void *src, size_t count) {
uint8_t *_dest = (uint8_t *) dest;
const uint8_t *_src = (const uint8_t *) src;
if (_dest == _src)
return dest;
if ((_dest >= &_src[count]) || (&_dest[count] <= _src))
return memcpy(dest, src, count);
if (_dest < _src) { // Copy forwards
for (; count; count--)
*(_dest++) = *(_src++);
} else { // Copy backwards
_src += count;
_dest += count;
for (; count; count--)
*(--_dest) = *(--_src);
}
return dest;
}
int memcmp(const void *lhs, const void *rhs, size_t count) {
const uint8_t *_lhs = (const uint8_t *) lhs;
const uint8_t *_rhs = (const uint8_t *) rhs;
for (; count; count--) {
uint8_t a = *(_lhs++), b = *(_rhs++);
if (a != b)
return a - b;
}
return 0;
}
void *memchr(const void *ptr, int ch, size_t count) {
const uint8_t *_ptr = (const uint8_t *) ptr;
for (; count; count--, _ptr++) {
if (*_ptr == ch)
return (void *) _ptr;
}
return 0;
}
/* String manipulation */
char *strcpy(char *restrict dest, const char *restrict src) {
char *_dest = dest;
while (*src)
*(_dest++) = *(src++);
*_dest = 0;
return dest;
}
char *strncpy(char *restrict dest, const char *restrict src, size_t count) {
char *_dest = dest;
for (; count && *src; count--)
*(_dest++) = *(src++);
for (; count; count--)
*(_dest++) = 0;
return dest;
}
int strcmp(const char *lhs, const char *rhs) {
for (;;) {
char a = *(lhs++), b = *(rhs++);
if (a != b)
return a - b;
if (!a && !b)
return 0;
}
}
int strncmp(const char *lhs, const char *rhs, size_t count) {
for (; count && *lhs && *rhs; count--) {
char a = *(lhs++), b = *(rhs++);
if (a != b)
return a - b;
}
return 0;
}
char *strchr(const char *str, int ch) {
for (; *str; str++) {
if (*str == ch)
return (char *) str;
}
return 0;
}
char *strrchr(const char *str, int ch) {
size_t length = strlen(str);
for (str += length; length; length--) {
str--;
if (*str == ch)
return (char *) str;
}
return 0;
}
char *strpbrk(const char *str, const char *breakset) {
for (; *str; str++) {
char a = *str;
for (const char *ch = breakset; *ch; ch++) {
if (a == *ch)
return (char *) str;
}
}
return 0;
}
char *strstr(const char *str, const char *substr) {
size_t length = strlen(substr);
if (!length)
return (char *) str;
for (; *str; str++) {
if (!memcmp(str, substr, length))
return (char *) str;
}
return 0;
}
size_t strlen(const char *str) {
size_t length = 0;
for (; *str; str++)
length++;
return length;
}
// Non-standard, used internally
size_t strnlen(const char *str, size_t count) {
size_t length = 0;
for (; *str && (length < count); str++)
length++;
return length;
}
char *strcat(char *restrict dest, const char *restrict src) {
char *_dest = &dest[strlen(dest)];
while (*src)
*(_dest++) = *(src++);
*_dest = 0;
return dest;
}
char *strncat(char *restrict dest, const char *restrict src, size_t count) {
char *_dest = &dest[strlen(dest)];
for (; count && *src; count--)
*(_dest++) = *(src++);
*_dest = 0;
return dest;
}
char *strdup(const char *str) {
size_t length = strlen(str) + 1;
char *copy = malloc(length);
if (!copy)
return 0;
memcpy(copy, str, length);
return copy;
}
char *strndup(const char *str, size_t count) {
size_t length = strnlen(str, count) + 1;
char *copy = malloc(length);
if (!copy)
return 0;
memcpy(copy, str, length);
return copy;
}
/* String tokenizer */
static char *_strtokPtr = 0, *_strtokEndPtr = 0;
char *strtok(char *restrict str, const char *restrict delim) {
if (str) {
_strtokPtr = str;
_strtokEndPtr = &str[strlen(str)];
}
if (_strtokPtr >= _strtokEndPtr)
return 0;
if (!(*_strtokPtr))
return 0;
char *split = strstr(_strtokPtr, delim);
char *token = _strtokPtr;
if (split) {
*(split++) = 0;
_strtokPtr = split;
} else {
_strtokPtr += strlen(token);
}
return token;
}
/* Number parsers */
long long strtoll(const char *restrict str, char **restrict str_end, int base) {
if (!str)
return 0;
while (isspace(*str))
str++;
int negative = (*str == '-');
if (negative)
str++;
while (isspace(*str))
str++;
// Parse any base prefix if present. If a base was specified make sure it
// matches, otherwise use it to determine which base the value is in.
long long value = 0;
if (*str == '0') {
int _base;
switch (str[1]) {
case 0:
goto _exit;
case 'X':
case 'x':
_base = 16;
str += 2;
break;
case 'O':
case 'o':
_base = 8;
str += 2;
break;
case 'B':
case 'b':
_base = 2;
str += 2;
break;
default:
// Numbers starting with a zero are *not* interpreted as octal
// unless base = 8.
_base = 0;
str++;
}
if (!base)
base = _base;
else if (base != _base)
return 0;
}
if (!base)
base = 10;
else if ((base < 2) || (base > 36))
return 0;
// Parse the actual value.
for (; *str; str++) {
char ch = *str;
int digit;
switch (ch) {
case '0' ... '9':
digit = ch - '0';
break;
case 'A' ... 'Z':
digit = (ch - 'A') + 10;
break;
case 'a' ... 'z':
digit = (ch - 'a') + 10;
break;
default:
goto _exit;
}
value = (value * base) + digit;
}
_exit:
if (str_end)
*str_end = (char *) str;
return negative ? (-value) : value;
}
long strtol(const char *restrict str, char **restrict str_end, int base) {
return (long) strtoll(str, str_end, base);
}

51
src/libc/string.h Normal file
View File

@ -0,0 +1,51 @@
/*
* ps1-bare-metal - (C) 2023 spicyjpeg
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
* INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
* LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
#pragma once
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
void *memset(void *dest, int ch, size_t count);
void *memcpy(void *dest, const void *src, size_t count);
void *memccpy(void *dest, const void *src, int ch, size_t count);
void *memmove(void *dest, const void *src, size_t count);
int memcmp(const void *lhs, const void *rhs, size_t count);
void *memchr(const void *ptr, int ch, size_t count);
char *strcpy(char *dest, const char *src);
char *strncpy(char *dest, const char *src, size_t count);
int strcmp(const char *lhs, const char *rhs);
int strncmp(const char *lhs, const char *rhs, size_t count);
char *strchr(const char *str, int ch);
char *strrchr(const char *str, int ch);
char *strpbrk(const char *str, const char *breakset);
char *strstr(const char *str, const char *substr);
size_t strlen(const char *str);
char *strcat(char *dest, const char *src);
char *strncat(char *dest, const char *src, size_t count);
char *strdup(const char *str);
char *strndup(const char *str, size_t count);
char *strtok(char *str, const char *delim);
#ifdef __cplusplus
}
#endif

129
src/main.cpp Normal file
View File

@ -0,0 +1,129 @@
#include <stdio.h>
#include <stdlib.h>
#include "app/app.hpp"
#include "ps1/gpucmd.h"
#include "ps1/system.h"
#include "asset.hpp"
#include "defs.hpp"
#include "gpu.hpp"
#include "io.hpp"
#include "spu.hpp"
#include "uibase.hpp"
#include "util.hpp"
extern "C" const uint8_t _resources[];
extern "C" const size_t _resourcesSize;
int main(int argc, const char **argv) {
installExceptionHandler();
gpu::init();
spu::init();
io::init();
int width = 320, height = 240;
const void *ptr = nullptr;
size_t length = 0;
#ifdef NDEBUG
for (; argc > 0; argc--) {
auto arg = *(argv++);
if (!arg)
continue;
switch (util::hash(arg, '=')) {
//case "boot.rom"_h:
//break;
//case "boot.from"_h:
//break;
case "console"_h:
initSerialIO(strtol(&arg[7], nullptr, 0));
util::logger.enableSyslog = true;
break;
case "screen.width"_h:
width = int(strtol(&arg[13], nullptr, 0));
break;
case "screen.height"_h:
height = int(strtol(&arg[14], nullptr, 0));
break;
// Allow the default assets to be overridden by passing a pointer to
// an in-memory ZIP file as a command-line argument.
case "resources.ptr"_h:
ptr = reinterpret_cast<const void *>(
strtol(&arg[14], nullptr, 16)
);
break;
case "resources.length"_h:
length = size_t(strtol(&arg[17], nullptr, 16));
break;
}
}
#else
// Enable serial port logging by default and skip argv parsing (some
// emulators like to leave $a0/$a1 uninitialized) in debug builds.
initSerialIO(115200);
util::logger.enableSyslog = true;
#endif
LOG("build " VERSION_STRING " (" __DATE__ " " __TIME__ ")");
LOG("(C) 2022-2023 spicyjpeg");
asset::AssetLoader loader;
if (ptr && length)
loader.openMemory(ptr, length);
if (!loader.ready) {
LOG("loading default resource archive");
loader.openMemory(_resources, _resourcesSize);
}
io::clearWatchdog();
gpu::Context gpuCtx(GP1_MODE_NTSC, width, height, height > 256);
ui::Context uiCtx(gpuCtx);
ui::TiledBackground background;
ui::LogOverlay overlay(util::logger);
asset::StringTable strings;
if (
!loader.loadTIM(background.tile, "assets/textures/background.tim") ||
!loader.loadTIM(uiCtx.font.image, "assets/textures/font.tim") ||
!loader.loadFontMetrics(uiCtx.font, "assets/textures/font.metrics") ||
!loader.loadAsset(strings.data, "assets/app.strings")
) {
LOG("required assets not found, exiting");
return 1;
}
io::clearWatchdog();
loader.loadVAG(uiCtx.sounds[ui::SOUND_STARTUP], "assets/sounds/startup.vag");
loader.loadVAG(uiCtx.sounds[ui::SOUND_MOVE], "assets/sounds/move.vag");
loader.loadVAG(uiCtx.sounds[ui::SOUND_ENTER], "assets/sounds/enter.vag");
loader.loadVAG(uiCtx.sounds[ui::SOUND_EXIT], "assets/sounds/exit.vag");
loader.loadVAG(uiCtx.sounds[ui::SOUND_CLICK], "assets/sounds/click.vag");
background.text = "v" VERSION_STRING;
uiCtx.setBackgroundLayer(background);
uiCtx.setOverlayLayer(overlay);
App app;
gpu::enableDisplay(true);
spu::setVolume(0x3fff);
io::setMiscOutput(io::MISC_SPU_ENABLE, true);
io::clearWatchdog();
app.run(uiCtx, loader, strings);
return 0;
}

136
src/pad.cpp Normal file
View File

@ -0,0 +1,136 @@
#include <stddef.h>
#include <stdint.h>
#include "ps1/registers.h"
#include "ps1/system.h"
#include "pad.hpp"
#include "util.hpp"
namespace pad {
static constexpr int _BAUD_RATE = 250000;
static constexpr int _CS_DELAY = 60;
static constexpr int _ACK_TIMEOUT = 120;
/* Basic API */
void init(void) {
SIO_CTRL(0) = SIO_CTRL_RESET;
SIO_MODE(0) = SIO_MODE_BAUD_DIV1 | SIO_MODE_DATA_8;
SIO_BAUD(0) = F_CPU / _BAUD_RATE;
SIO_CTRL(0) = 0;
}
uint8_t exchangeByte(uint8_t value) {
while (!(SIO_STAT(0) & SIO_STAT_TX_NOT_FULL))
__asm__ volatile("");
SIO_CTRL(0) |= SIO_CTRL_ACKNOWLEDGE;
SIO_DATA(0) = value;
while (!(SIO_STAT(0) & SIO_STAT_RX_NOT_EMPTY))
__asm__ volatile("");
return SIO_DATA(0);
}
/* Controller port class */
Port ports[2]{
(SIO_CTRL_TX_ENABLE | SIO_CTRL_RX_ENABLE | SIO_CTRL_DSR_IRQ_ENABLE
| SIO_CTRL_CS_PORT_1),
(SIO_CTRL_TX_ENABLE | SIO_CTRL_RX_ENABLE | SIO_CTRL_DSR_IRQ_ENABLE
| SIO_CTRL_CS_PORT_2)
};
bool Port::start(uint8_t address) const {
SIO_CTRL(0) = sioFlags | SIO_CTRL_DTR | SIO_CTRL_ACKNOWLEDGE;
delayMicroseconds(_CS_DELAY);
IRQ_STAT = ~(1 << IRQ_SIO0);
SIO_DATA(0) = address;
// The controller only pulses /ACK for a brief period of time and the DSR
// status bit in the SIO_STAT register is not latched, so the only way to
// detect the pulse reliably is to have it trigger a dummy (latched) IRQ and
// check for it.
if (!waitForInterrupt(IRQ_SIO0, _ACK_TIMEOUT))
return false;
while (SIO_STAT(0) & SIO_STAT_RX_NOT_EMPTY)
SIO_DATA(0);
return true;
}
void Port::stop(void) const {
delayMicroseconds(_CS_DELAY);
SIO_CTRL(0) = sioFlags;
}
size_t Port::exchangeBytes(
const uint8_t *input, uint8_t *output, size_t length
) const {
size_t remaining = length;
for (; remaining; remaining--) {
*(output++) = exchangeByte(*(input++));
// Controllers do not trigger /ACK on the last byte.
if (remaining > 1) {
if (!waitForInterrupt(IRQ_SIO0, _ACK_TIMEOUT))
break;
}
}
return length - remaining;
}
size_t Port::exchangePacket(
uint8_t address, const uint8_t *request, uint8_t *response,
size_t reqLength, size_t maxRespLength
) const {
if (!start(address))
return 0;
size_t respLength = 0;
while (respLength < maxRespLength) {
if (reqLength) {
*(response++) = exchangeByte(*(request++));
reqLength--;
} else {
*(response++) = exchangeByte(0);
}
respLength++;
if (!waitForInterrupt(IRQ_SIO0, _ACK_TIMEOUT))
break;
}
stop();
return respLength;
}
bool Port::pollPad(void) {
const uint8_t request[4]{ CMD_POLL, 0, 0, 0 };
uint8_t response[8];
if (exchangePacket(
ADDR_CONTROLLER, request, response, sizeof(request), sizeof(response)
) >= 4) {
if (response[1] == PREFIX_PAD) {
padType = PadType(response[0] >> 4);
buttons = ~(response[2] | (response[3] << 8));
return true;
}
}
padType = PAD_NONE;
buttons = 0;
return false;
}
}

136
src/pad.hpp Normal file
View File

@ -0,0 +1,136 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
namespace pad {
/* Definitions */
enum Address : uint8_t {
ADDR_CONTROLLER = 0x01,
ADDR_PS2_IR = 0x21,
ADDR_PS2_MULTITAP = 0x61,
ADDR_CARD = 0x81
};
enum ResponsePrefix : uint8_t {
PREFIX_PAD = 0x5a,
PREFIX_CARD = 0x5d
};
enum Command : uint8_t {
// Basic controller commands
CMD_POLL = 'B',
CMD_CONFIG = 'C',
// Configuration mode commands
CMD_INIT_PRESSURE = '@', // DualShock 2 only
CMD_RESP_INFO = 'A', // DualShock 2 only
CMD_SET_ANALOG = 'D',
CMD_GET_ANALOG = 'E',
CMD_MOTOR_INFO = 'F',
CMD_MOTOR_LIST = 'G',
CMD_MOTOR_STATE = 'H',
CMD_GET_MODES = 'L',
CMD_REQ_CONFIG = 'M',
CMD_RESP_CONFIG = 'O', // DualShock 2 only
// Memory card commands
CMD_READ_SECTOR = 'R',
CMD_IDENTIFY_CARD = 'S', // OEM cards only
CMD_WRITE_SECTOR = 'W'
};
enum PadType : uint8_t {
PAD_NONE = 0,
PAD_MOUSE = 1,
PAD_NEGCON = 2,
PAD_IRQ10_GUN = 3,
PAD_DIGITAL = 4,
PAD_ANALOG_STICK = 5,
PAD_GUNCON = 6,
PAD_ANALOG = 7,
PAD_MULTITAP = 8,
PAD_JOGCON = 14,
PAD_CONFIG_MODE = 15
};
enum PadButton : uint16_t {
// Standard controllers
BTN_SELECT = 1 << 0,
BTN_L3 = 1 << 1,
BTN_R3 = 1 << 2,
BTN_START = 1 << 3,
BTN_UP = 1 << 4,
BTN_RIGHT = 1 << 5,
BTN_DOWN = 1 << 6,
BTN_LEFT = 1 << 7,
BTN_L2 = 1 << 8,
BTN_R2 = 1 << 9,
BTN_L1 = 1 << 10,
BTN_R1 = 1 << 11,
BTN_TRIANGLE = 1 << 12,
BTN_CIRCLE = 1 << 13,
BTN_CROSS = 1 << 14,
BTN_SQUARE = 1 << 15,
// Mouse
BTN_MOUSE_RIGHT = 1 << 10,
BTN_MOUSE_LEFT = 1 << 11,
// neGcon
BTN_NEGCON_START = 1 << 3,
BTN_NEGCON_UP = 1 << 4,
BTN_NEGCON_RIGHT = 1 << 5,
BTN_NEGCON_DOWN = 1 << 6,
BTN_NEGCON_LEFT = 1 << 7,
BTN_NEGCON_R = 1 << 11,
BTN_NEGCON_B = 1 << 12,
BTN_NEGCON_A = 1 << 13,
// Guncon
BTN_GUNCON_A = 1 << 3,
BTN_GUNCON_TRIGGER = 1 << 13,
BTN_GUNCON_B = 1 << 14,
// IRQ10 lightgun
BTN_IRQ10_GUN_START = 1 << 3,
BTN_IRQ10_GUN_BACK = 1 << 14,
BTN_IRQ10_GUN_TRIGGER = 1 << 15
};
/* API */
void init(void);
uint8_t exchangeByte(uint8_t value);
/* Controller port class */
class Port {
public:
uint16_t sioFlags;
PadType padType;
uint16_t buttons;
inline Port(uint16_t sioFlags)
: sioFlags(sioFlags), padType(PAD_NONE), buttons(0) {}
bool start(uint8_t address) const;
void stop(void) const;
size_t exchangeBytes(
const uint8_t *input, uint8_t *output, size_t length
) const;
size_t exchangePacket(
uint8_t address, const uint8_t *request, uint8_t *response,
size_t reqLength, size_t maxRespLength
) const;
bool pollPad(void);
};
extern Port ports[2];
}

337
src/ps1/gpucmd.h Normal file
View File

@ -0,0 +1,337 @@
/*
* ps1-bare-metal - (C) 2023 spicyjpeg
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
* INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
* LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
#pragma once
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#define DEF16 static inline uint16_t __attribute__((always_inline))
#define DEF32 static inline uint32_t __attribute__((always_inline))
/* DMA tags */
DEF32 gp0_tag(size_t length, void *next) {
return 0
| (((uint32_t) next & 0xffffff) << 0)
| (((uint32_t) length & 0x0000ff) << 24);
}
DEF32 gp0_endTag(size_t length) {
return gp0_tag(length, (void *) 0xffffff);
}
/* Drawing attributes */
typedef enum {
GP0_BLEND_BITMASK = 3,
GP0_BLEND_SEMITRANS = 0,
GP0_BLEND_ADD = 1,
GP0_BLEND_SUBTRACT = 2,
GP0_BLEND_DIV4_ADD = 3
} GP0BlendMode;
typedef enum {
GP0_COLOR_BITMASK = 3,
GP0_COLOR_4BPP = 0,
GP0_COLOR_8BPP = 1,
GP0_COLOR_16BPP = 2
} GP0ColorDepth;
DEF16 gp0_page(
unsigned int x, unsigned int y, GP0BlendMode blendMode,
GP0ColorDepth colorDepth
) {
return 0
| ((x & 15) << 0)
| ((y & 1) << 4)
| ((blendMode & 3) << 5)
| ((colorDepth & 3) << 7)
| ((y & 2) << 10);
}
DEF16 gp0_clut(unsigned int x, unsigned int y) {
return 0
| ((x & 0x03f) << 0)
| ((y & 0x3ff) << 6);
}
DEF32 gp0_xy(int x, int y) {
return 0
| ((x & 0xffff) << 0)
| ((y & 0xffff) << 16);
}
DEF32 gp0_uv(unsigned int u, unsigned int v, uint16_t attr) {
return 0
| ((u & 0x00ff) << 0)
| ((v & 0x00ff) << 8)
| ((attr & 0xffff) << 16);
}
DEF32 gp0_rgb(uint8_t r, uint8_t g, uint8_t b) {
return 0
| ((r & 0xff) << 0)
| ((g & 0xff) << 8)
| ((b & 0xff) << 16);
}
/* GP0 (drawing) commands */
typedef enum {
GP0_CMD_MISC = 0 << 29,
GP0_CMD_POLYGON = 1 << 29,
GP0_CMD_LINE = 2 << 29,
GP0_CMD_RECTANGLE = 3 << 29,
GP0_CMD_VRAM_BLIT = 4 << 29,
GP0_CMD_VRAM_WRITE = 5 << 29,
GP0_CMD_VRAM_READ = 6 << 29,
GP0_CMD_ATTRIBUTE = 7 << 29
} GP0Command;
typedef enum {
GP0_CMD_NOP = GP0_CMD_MISC | ( 0 << 24),
GP0_CMD_FLUSH_CACHE = GP0_CMD_MISC | ( 1 << 24),
GP0_CMD_VRAM_FILL = GP0_CMD_MISC | ( 2 << 24),
GP0_CMD_NOP2 = GP0_CMD_MISC | ( 3 << 24),
GP0_CMD_IRQ = GP0_CMD_MISC | (31 << 24)
} GP0MiscCommand;
typedef enum {
GP0_CMD_TEXPAGE = GP0_CMD_ATTRIBUTE | (1 << 24),
GP0_CMD_TEXWINDOW = GP0_CMD_ATTRIBUTE | (2 << 24),
GP0_CMD_FB_OFFSET1 = GP0_CMD_ATTRIBUTE | (3 << 24),
GP0_CMD_FB_OFFSET2 = GP0_CMD_ATTRIBUTE | (4 << 24),
GP0_CMD_FB_ORIGIN = GP0_CMD_ATTRIBUTE | (5 << 24),
GP0_CMD_FB_MASK = GP0_CMD_ATTRIBUTE | (6 << 24)
} GP0AttributeCommand;
DEF32 _gp0_polygon(
bool quad, bool unshaded, bool gouraud, bool textured, bool blend
) {
return GP0_CMD_POLYGON
| ((unshaded & 1) << 24)
| ((blend & 1) << 25)
| ((textured & 1) << 26)
| ((quad & 1) << 27)
| ((gouraud & 1) << 28);
}
DEF32 gp0_triangle(bool textured, bool blend) {
return _gp0_polygon(false, true, false, textured, blend);
}
DEF32 gp0_shadedTriangle(bool gouraud, bool textured, bool blend) {
return _gp0_polygon(false, false, gouraud, textured, blend);
}
DEF32 gp0_quad(bool textured, bool blend) {
return _gp0_polygon(true, true, false, textured, blend);
}
DEF32 gp0_shadedQuad(bool gouraud, bool textured, bool blend) {
return _gp0_polygon(true, false, gouraud, textured, blend);
}
DEF32 gp0_line(bool gouraud, bool blend) {
return GP0_CMD_LINE
| ((blend & 1) << 25)
| ((gouraud & 1) << 28);
}
DEF32 gp0_polyLine(bool gouraud, bool blend) {
return GP0_CMD_LINE
| ((blend & 1) << 25)
| (1 << 27)
| ((gouraud & 1) << 28);
}
DEF32 _gp0_rectangle(uint8_t size, bool textured, bool unshaded, bool blend) {
return GP0_CMD_RECTANGLE
| ((unshaded & 1) << 24)
| ((blend & 1) << 25)
| ((textured & 1) << 26)
| ((size & 3) << 27);
}
DEF32 gp0_rectangle(bool textured, bool unshaded, bool blend) {
return _gp0_rectangle(0, textured, unshaded, blend);
}
DEF32 gp0_rectangle1x1(bool textured, bool unshaded, bool blend) {
return _gp0_rectangle(1, textured, unshaded, blend);
}
DEF32 gp0_rectangle8x8(bool textured, bool unshaded, bool blend) {
return _gp0_rectangle(2, textured, unshaded, blend);
}
DEF32 gp0_rectangle16x16(bool textured, bool unshaded, bool blend) {
return _gp0_rectangle(3, textured, unshaded, blend);
}
DEF32 gp0_vramBlit(void) {
return GP0_CMD_VRAM_BLIT;
}
DEF32 gp0_vramWrite(void) {
return GP0_CMD_VRAM_WRITE;
}
DEF32 gp0_vramRead(void) {
return GP0_CMD_VRAM_READ;
}
DEF32 gp0_flushCache(void) {
return GP0_CMD_FLUSH_CACHE;
}
DEF32 gp0_vramFill(void) {
return GP0_CMD_VRAM_FILL;
}
DEF32 gp0_irq(void) {
return GP0_CMD_IRQ;
}
DEF32 gp0_texpage(uint16_t page, bool dither, bool unlockFB) {
return GP0_CMD_TEXPAGE
| ((page & 0x9ff) << 0)
| ((dither & 1) << 9)
| ((unlockFB & 1) << 10);
}
DEF32 gp0_texwindow(
uint8_t baseX, uint8_t baseY, uint8_t maskX, uint8_t maskY
) {
return GP0_CMD_TEXWINDOW
| ((maskX & 0x1f) << 0)
| ((maskY & 0x1f) << 5)
| ((baseX & 0x1f) << 10)
| ((baseY & 0x1f) << 15);
}
DEF32 gp0_fbOffset1(unsigned int x, unsigned int y) {
return GP0_CMD_FB_OFFSET1
| ((x & 0x3ff) << 0)
| ((y & 0x3ff) << 10);
}
DEF32 gp0_fbOffset2(unsigned int x, unsigned int y) {
return GP0_CMD_FB_OFFSET2
| ((x & 0x3ff) << 0)
| ((y & 0x3ff) << 10);
}
DEF32 gp0_fbOrigin(int x, int y) {
return GP0_CMD_FB_ORIGIN
| ((x & 0x7ff) << 0)
| ((y & 0x7ff) << 11);
}
DEF32 gp0_fbMask(bool setMask, bool useMask) {
return GP0_CMD_FB_MASK
| (setMask << 0)
| (useMask << 1);
}
/* GP1 (display control) commands */
typedef enum {
GP1_HRES_BITMASK = (3 << 0) | (1 << 6),
GP1_HRES_256 = 0 << 0, // Dotclock divided by 10
GP1_HRES_320 = 1 << 0, // Dotclock divided by 8
GP1_HRES_368 = 1 << 6, // Dotclock divided by 7
GP1_HRES_512 = 2 << 0, // Dotclock divided by 5
GP1_HRES_640 = 3 << 0 // Dotclock divided by 4
} GP1HorizontalRes;
typedef enum {
GP1_VRES_BITMASK = 1 << 2,
GP1_VRES_256 = 0 << 2,
GP1_VRES_512 = 1 << 2
} GP1VerticalRes;
typedef enum {
GP1_MODE_BITMASK = 1,
GP1_MODE_NTSC = 0,
GP1_MODE_PAL = 1
} GP1VideoMode;
typedef enum {
GP1_COLOR_BITMASK = 1,
GP1_COLOR_16BPP = 0,
GP1_COLOR_24BPP = 1
} GP1ColorDepth;
typedef enum {
GP1_DREQ_BITMASK = 3,
GP1_DREQ_NONE = 0,
GP1_DREQ_FIFO = 1,
GP1_DREQ_GP0_WRITE = 2,
GP1_DREQ_GP0_READ = 3
} GP1DMARequestMode;
typedef enum {
GP1_VRAM_BITMASK = 1,
GP1_VRAM_1MB = 0,
GP1_VRAM_2MB = 1
} GP1VRAMSize;
typedef enum {
GP1_CMD_RESET_GPU = 0 << 24,
GP1_CMD_RESET_FIFO = 1 << 24,
GP1_CMD_ACKNOWLEDGE = 2 << 24,
GP1_CMD_DISP_BLANK = 3 << 24,
GP1_CMD_DREQ_MODE = 4 << 24,
GP1_CMD_FB_OFFSET = 5 << 24,
GP1_CMD_FB_RANGE_H = 6 << 24,
GP1_CMD_FB_RANGE_V = 7 << 24,
GP1_CMD_FB_MODE = 8 << 24,
GP1_CMD_VRAM_SIZE = 9 << 24,
GP1_CMD_GET_INFO = 16 << 24
} GP1Command;
DEF32 gp1_resetGPU(void) {
return GP1_CMD_RESET_GPU;
}
DEF32 gp1_resetFIFO(void) {
return GP1_CMD_RESET_FIFO;
}
DEF32 gp1_acknowledge(void) {
return GP1_CMD_ACKNOWLEDGE;
}
DEF32 gp1_dispBlank(bool blank) {
return GP1_CMD_DISP_BLANK
| (blank & 1);
}
DEF32 gp1_dmaRequestMode(GP1DMARequestMode mode) {
return GP1_CMD_DREQ_MODE
| (mode & 3);
}
DEF32 gp1_fbOffset(unsigned int x, unsigned int y) {
return GP1_CMD_FB_OFFSET
| ((x & 0x3ff) << 0)
| ((y & 0x3ff) << 10);
}
DEF32 gp1_fbRangeH(unsigned int low, unsigned int high) {
return GP1_CMD_FB_RANGE_H
| ((low & 0xfff) << 0)
| ((high & 0xfff) << 12);
}
DEF32 gp1_fbRangeV(unsigned int low, unsigned int high) {
return GP1_CMD_FB_RANGE_V
| ((low & 0x3ff) << 0)
| ((high & 0x3ff) << 10);
}
DEF32 gp1_fbMode(
GP1HorizontalRes horizontalRes, GP1VerticalRes verticalRes,
GP1VideoMode videoMode, bool interlace, GP1ColorDepth colorDepth
) {
return GP1_CMD_FB_MODE
| ((horizontalRes & 0x47) << 0)
| ((verticalRes & 1) << 2)
| ((videoMode & 1) << 3)
| ((colorDepth & 1) << 4)
| ((interlace & 1) << 5);
}
DEF32 gp1_vramSize(GP1VRAMSize size) {
return GP1_CMD_VRAM_SIZE
| (size & 1);
}
#undef DEF16
#undef DEF32

47
src/ps1/pcdrv.h Normal file
View File

@ -0,0 +1,47 @@
/*
* ps1-bare-metal - (C) 2023 spicyjpeg
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
* INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
* LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
#pragma once
#include <stddef.h>
typedef enum {
PCDRV_MODE_READ = 0,
PCDRV_MODE_WRITE = 1,
PCDRV_MODE_READ_WRITE = 2
} PCDRVOpenMode;
typedef enum {
PCDRV_SEEK_SET = 0,
PCDRV_SEEK_CUR = 1,
PCDRV_SEEK_END = 2
} PCDRVSeekMode;
#ifdef __cplusplus
extern "C" {
#endif
int pcdrvInit(void);
int pcdrvCreate(const char *path);
int pcdrvOpen(const char *path, PCDRVOpenMode mode);
int pcdrvClose(int fd);
int pcdrvRead(int fd, void *data, size_t length);
int pcdrvWrite(int fd, const void *data, size_t length);
int pcdrvSeek(int fd, int offset, PCDRVSeekMode mode);
#ifdef __cplusplus
}
#endif

117
src/ps1/pcdrv.s Normal file
View File

@ -0,0 +1,117 @@
# ps1-bare-metal - (C) 2023 spicyjpeg
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
# AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
# OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
# PERFORMANCE OF THIS SOFTWARE.
.set noreorder
.section .text.pcdrvInit, "ax", @progbits
.global pcdrvInit
.type pcdrvInit, @function
pcdrvInit:
break 0, 0x101 # () -> error
jr $ra
nop
.section .text.pcdrvCreate, "ax", @progbits
.global pcdrvCreate
.type pcdrvCreate, @function
pcdrvCreate:
li $a2, 0
move $a1, $a0
break 0, 0x102 # (path, path, 0) -> error, fd
bgez $v0, .LcreateOK # if (error < 0) fd = error
nop
move $v1, $v0
.LcreateOK:
jr $ra # return fd
move $v0, $v1
.section .text.pcdrvOpen, "ax", @progbits
.global pcdrvOpen
.type pcdrvOpen, @function
pcdrvOpen:
move $a2, $a1
move $a1, $a0
break 0, 0x103 # (path, path, mode) -> error, fd
bgez $v0, .LopenOK # if (error < 0) fd = error
nop
move $v1, $v0
.LopenOK:
jr $ra # return fd
move $v0, $v1
.section .text.pcdrvClose, "ax", @progbits
.global pcdrvClose
.type pcdrvClose, @function
pcdrvClose:
move $a1, $a0
break 0, 0x104 # (fd, fd) -> error
jr $ra
nop
.section .text.pcdrvRead, "ax", @progbits
.global pcdrvRead
.type pcdrvRead, @function
pcdrvRead:
move $a3, $a1
move $a1, $a0
break 0, 0x105 # (fd, fd, length, data) -> error, length
bgez $v0, .LreadOK # if (error < 0) length = error
nop
move $v1, $v0
.LreadOK:
jr $ra # return length
move $v0, $v1
.section .text.pcdrvWrite, "ax", @progbits
.global pcdrvWrite
.type pcdrvWrite, @function
pcdrvWrite:
move $a3, $a1
move $a1, $a0
break 0, 0x106 # (fd, fd, length, data) -> error, length
bgez $v0, .LwriteOK # if (error < 0) length = error
nop
move $v1, $v0
.LwriteOK:
jr $ra # return length
move $v0, $v1
.section .text.pcdrvSeek, "ax", @progbits
.global pcdrvSeek
.type pcdrvSeek, @function
pcdrvSeek:
move $a3, $a2
move $a2, $a1
move $a1, $a0
break 0, 0x107 # (fd, fd, offset, mode) -> error, offset
bgez $v0, .LseekOK # if (error < 0) offset = error
nop
move $v1, $v0
.LseekOK:
jr $ra # return offset
move $v0, $v1

507
src/ps1/registers.h Normal file
View File

@ -0,0 +1,507 @@
/*
* ps1-bare-metal - (C) 2023 spicyjpeg
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
* INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
* LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
#pragma once
#include <stdint.h>
#define _ADDR8(addr) ((volatile uint8_t *) (addr))
#define _ADDR16(addr) ((volatile uint16_t *) (addr))
#define _ADDR32(addr) ((volatile uint32_t *) (addr))
#define _MMIO8(addr) (*_ADDR8(addr))
#define _MMIO16(addr) (*_ADDR16(addr))
#define _MMIO32(addr) (*_ADDR32(addr))
/* Constants */
#define F_CPU 33868800
#define F_GPU_NTSC 53693175
#define F_GPU_PAL 53203425
typedef enum {
DEV0_BASE = 0xbf000000,
EXP1_BASE = 0xbf000000,
IO_BASE = 0xbf800000,
EXP2_BASE = 0xbf802000,
EXP3_BASE = 0xbfa00000
} BaseAddress;
/* Bus interface */
typedef enum {
BIU_CTRL_WRITE_DELAY_BITMASK = 15 << 0,
BIU_CTRL_READ_DELAY_BITMASK = 15 << 4,
BIU_CTRL_RECOVERY = 1 << 8,
BIU_CTRL_HOLD = 1 << 9,
BIU_CTRL_FLOAT = 1 << 10,
BIU_CTRL_PRESTROBE = 1 << 11,
BIU_CTRL_WIDTH_8 = 0 << 12,
BIU_CTRL_WIDTH_16 = 1 << 12,
BIU_CTRL_AUTO_INCR = 1 << 13,
BIU_CTRL_SIZE_BITMASK = 31 << 16,
BIU_CTRL_DMA_DELAY_BITMASK = 15 << 24,
BIU_CTRL_ADDR_ERROR = 1 << 28,
BIU_CTRL_DMA_DELAY = 1 << 29,
BIU_CTRL_DMA32 = 1 << 30,
BIU_CTRL_WAIT = 1 << 31
} BIUControlFlag;
#define BIU_DEV0_ADDR _MMIO32(IO_BASE | 0x1000) // PIO/573
#define BIU_EXP2_ADDR _MMIO32(IO_BASE | 0x1004) // PIO/debug
#define BIU_DEV0_CTRL _MMIO32(IO_BASE | 0x1008) // PIO/573
#define BIU_EXP3_CTRL _MMIO32(IO_BASE | 0x100c) // PIO/debug
#define BIU_DEV2_CTRL _MMIO32(IO_BASE | 0x1010) // BIOS ROM
#define BIU_DEV4_CTRL _MMIO32(IO_BASE | 0x1014) // SPU
#define BIU_DEV5_CTRL _MMIO32(IO_BASE | 0x1018) // CD-ROM
#define BIU_EXP2_CTRL _MMIO32(IO_BASE | 0x101c) // PIO/debug
#define BIU_COM_DELAY _MMIO32(IO_BASE | 0x1020)
/* Serial interfaces */
typedef enum {
SIO_STAT_TX_NOT_FULL = 1 << 0,
SIO_STAT_RX_NOT_EMPTY = 1 << 1,
SIO_STAT_TX_EMPTY = 1 << 2,
SIO_STAT_RX_PARITY_ERR = 1 << 3,
SIO_STAT_RX_OVERRUN = 1 << 4, // SIO1 only
SIO_STAT_RX_STOP_ERR = 1 << 5, // SIO1 only
SIO_STAT_RX_INVERT = 1 << 6, // SIO1 only
SIO_STAT_DSR = 1 << 7, // DSR is /ACK on SIO0
SIO_STAT_CTS = 1 << 8, // SIO1 only
SIO_STAT_IRQ = 1 << 9
} SIOStatusFlag;
typedef enum {
SIO_MODE_BAUD_MASK = 3 << 0,
SIO_MODE_BAUD_DIV1 = 1 << 0,
SIO_MODE_BAUD_DIV16 = 2 << 0,
SIO_MODE_BAUD_DIV64 = 3 << 0,
SIO_MODE_DATA_BITMASK = 3 << 2,
SIO_MODE_DATA_5 = 0 << 2,
SIO_MODE_DATA_6 = 1 << 2,
SIO_MODE_DATA_7 = 2 << 2,
SIO_MODE_DATA_8 = 3 << 2,
SIO_MODE_PARITY_BITMASK = 3 << 4,
SIO_MODE_PARITY_NONE = 0 << 4,
SIO_MODE_PARITY_EVEN = 1 << 4,
SIO_MODE_PARITY_ODD = 3 << 4,
SIO_MODE_STOP_BITMASK = 3 << 6, // SIO1 only
SIO_MODE_STOP_1 = 1 << 6, // SIO1 only
SIO_MODE_STOP_1_5 = 2 << 6, // SIO1 only
SIO_MODE_STOP_2 = 3 << 6, // SIO1 only
SIO_MODE_SCK_INVERT = 1 << 8 // SIO0 only
} SIOModeFlag;
typedef enum {
SIO_CTRL_TX_ENABLE = 1 << 0,
SIO_CTRL_DTR = 1 << 1, // DTR is /CS on SIO0
SIO_CTRL_RX_ENABLE = 1 << 2,
SIO_CTRL_TX_INVERT = 1 << 3, // SIO1 only
SIO_CTRL_ACKNOWLEDGE = 1 << 4,
SIO_CTRL_RTS = 1 << 5, // SIO1 only
SIO_CTRL_RESET = 1 << 6,
SIO_CTRL_TX_IRQ_ENABLE = 1 << 10,
SIO_CTRL_RX_IRQ_ENABLE = 1 << 11,
SIO_CTRL_DSR_IRQ_ENABLE = 1 << 12, // DSR is /ACK on SIO0
SIO_CTRL_CS_PORT_1 = 0 << 13, // SIO0 only
SIO_CTRL_CS_PORT_2 = 1 << 13 // SIO0 only
} SIOControlFlag;
// SIO_DATA is a 32-bit register, but some emulators do not implement it
// correctly and break if it's read more than 8 bits at a time.
#define SIO_DATA(N) _MMIO8 ((IO_BASE | 0x1040) + (16 * (N)))
#define SIO_STAT(N) _MMIO16((IO_BASE | 0x1044) + (16 * (N)))
#define SIO_MODE(N) _MMIO16((IO_BASE | 0x1048) + (16 * (N)))
#define SIO_CTRL(N) _MMIO16((IO_BASE | 0x104a) + (16 * (N)))
#define SIO_BAUD(N) _MMIO16((IO_BASE | 0x104e) + (16 * (N)))
/* DRAM controller */
typedef enum {
DRAM_CTRL_UNKNOWN = 1 << 3,
DRAM_CTRL_FETCH_DELAY = 1 << 7,
DRAM_CTRL_SIZE_MUL1 = 0 << 9,
DRAM_CTRL_SIZE_MUL4 = 1 << 9,
DRAM_CTRL_COUNT_1 = 0 << 10, // 1 DRAM bank (single RAS)
DRAM_CTRL_COUNT_2 = 1 << 10, // 2 DRAM banks (dual RAS)
DRAM_CTRL_SIZE_1MB = 0 << 11, // 1MB chips (4MB with MUL4)
DRAM_CTRL_SIZE_2MB = 1 << 11 // 2MB chips (8MB with MUL4)
} DRAMControlFlag;
#define DRAM_CTRL _MMIO32(IO_BASE | 0x1060)
/* IRQ controller */
typedef enum {
IRQ_VBLANK = 0,
IRQ_GPU = 1,
IRQ_CDROM = 2,
IRQ_DMA = 3,
IRQ_TIMER0 = 4,
IRQ_TIMER1 = 5,
IRQ_TIMER2 = 6,
IRQ_SIO0 = 7,
IRQ_SIO1 = 8,
IRQ_SPU = 9,
IRQ_GUN = 10,
IRQ_PIO = 10
} IRQChannel;
#define IRQ_STAT _MMIO16(IO_BASE | 0x1070)
#define IRQ_MASK _MMIO16(IO_BASE | 0x1074)
/* DMA */
typedef enum {
DMA_MDEC_IN = 0,
DMA_MDEC_OUT = 1,
DMA_GPU = 2,
DMA_CDROM = 3,
DMA_SPU = 4,
DMA_PIO = 5,
DMA_OTC = 6
} DMAChannel;
typedef enum {
DMA_CHCR_READ = 0 << 0,
DMA_CHCR_WRITE = 1 << 0,
DMA_CHCR_CHOPPING = 1 << 8,
DMA_CHCR_MODE_BITMASK = 3 << 9,
DMA_CHCR_MODE_BURST = 0 << 9,
DMA_CHCR_MODE_SLICE = 1 << 9,
DMA_CHCR_MODE_LIST = 2 << 9,
DMA_CHCR_DMA_TIME_BITMASK = 7 << 16,
DMA_CHCR_CPU_TIME_BITMASK = 7 << 20,
DMA_CHCR_ENABLE = 1 << 24,
DMA_CHCR_TRIGGER = 1 << 28,
DMA_CHCR_PAUSE = 1 << 29 // Burst mode only
} DMACHCRFlag;
typedef enum {
DMA_DICR_CH_MODE_MASK = 0x7f << 0,
DMA_DICR_BUS_ERROR = 1 << 15,
DMA_DICR_CH_ENABLE_MASK = 0x7f << 16,
DMA_DICR_IRQ_ENABLE = 1 << 23,
DMA_DICR_CH_STAT_MASK = 0x7f << 24,
DMA_DICR_IRQ = 1 << 31
} DMADICRFlag;
#define DMA_DICR_CH_MODE(dma) (1 << ((dma) + 0))
#define DMA_DICR_CH_ENABLE(dma) (1 << ((dma) + 16))
#define DMA_DICR_CH_STAT(dma) (1 << ((dma) + 24))
#define DMA_MADR(N) _MMIO32((IO_BASE | 0x1080) + (16 * (N)))
#define DMA_BCR(N) _MMIO32((IO_BASE | 0x1084) + (16 * (N)))
#define DMA_CHCR(N) _MMIO32((IO_BASE | 0x1088) + (16 * (N)))
#define DMA_DPCR _MMIO32(IO_BASE | 0x10f0)
#define DMA_DICR _MMIO32(IO_BASE | 0x10f4)
/* Timers */
typedef enum {
TIMER_CTRL_ENABLE_SYNC = 1 << 0,
TIMER_CTRL_SYNC_BITMASK = 3 << 1,
TIMER_CTRL_SYNC_PAUSE = 0 << 1,
TIMER_CTRL_SYNC_RESET1 = 1 << 1,
TIMER_CTRL_SYNC_RESET2 = 2 << 1,
TIMER_CTRL_SYNC_PAUSE_ONCE = 3 << 1,
TIMER_CTRL_RELOAD = 1 << 3,
TIMER_CTRL_IRQ_ON_RELOAD = 1 << 4,
TIMER_CTRL_IRQ_ON_OVERFLOW = 1 << 5,
TIMER_CTRL_IRQ_REPEAT = 1 << 6,
TIMER_CTRL_IRQ_LATCH = 1 << 7,
TIMER_CTRL_EXT_CLOCK = 1 << 8,
TIMER_CTRL_PRESCALE = 1 << 9,
TIMER_CTRL_IRQ = 1 << 10,
TIMER_CTRL_RELOADED = 1 << 11,
TIMER_CTRL_OVERFLOWED = 1 << 12
} TimerControlFlag;
#define TIMER_VALUE(N) _MMIO32((IO_BASE | 0x1100) + (16 * (N)))
#define TIMER_CTRL(N) _MMIO32((IO_BASE | 0x1104) + (16 * (N)))
#define TIMER_RELOAD(N) _MMIO32((IO_BASE | 0x1108) + (16 * (N)))
/* CD-ROM drive */
typedef enum {
CDROM_STAT_BANK_BITMASK = 3 << 0,
CDROM_STAT_BANK_0 = 0 << 0,
CDROM_STAT_BANK_1 = 1 << 0,
CDROM_STAT_BANK_2 = 2 << 0,
CDROM_STAT_BANK_3 = 3 << 0,
CDROM_STAT_ADPCM_BUSY = 1 << 2,
CDROM_STAT_PARAM_EMPTY = 1 << 3,
CDROM_STAT_PARAM_FULL = 1 << 4,
CDROM_STAT_RESP_EMPTY = 1 << 5,
CDROM_STAT_DATA_EMPTY = 1 << 6,
CDROM_STAT_BUSY = 1 << 7
} CDROMStatusFlag;
typedef enum {
CDROM_REQ_START_IRQ_ENABLE = 1 << 5,
CDROM_REQ_BUFFER_WRITE = 1 << 6,
CDROM_REQ_BUFFER_READ = 1 << 7
} CDROMRequestFlag;
typedef enum {
CDROM_IRQ_NONE = 0,
CDROM_IRQ_DATA = 1,
CDROM_IRQ_COMPLETE = 2,
CDROM_IRQ_ACKNOWLEDGE = 3,
CDROM_IRQ_DATA_END = 4,
CDROM_IRQ_ERROR = 5
} CDROMIRQType;
typedef enum {
CDROM_CMDSTAT_ERROR = 1 << 0,
CDROM_CMDSTAT_SPINDLE_ON = 1 << 1,
CDROM_CMDSTAT_SEEK_ERROR = 1 << 2,
CDROM_CMDSTAT_ID_ERROR = 1 << 3,
CDROM_CMDSTAT_LID_OPEN = 1 << 4,
CDROM_CMDSTAT_READING = 1 << 5,
CDROM_CMDSTAT_SEEKING = 1 << 6,
CDROM_CMDSTAT_PLAYING = 1 << 7
} CDROMCommandStatusFlag;
typedef enum {
CDROM_MODE_CDDA = 1 << 0,
CDROM_MODE_AUTO_PAUSE = 1 << 1,
CDROM_MODE_CDDA_REPORT = 1 << 2,
CDROM_MODE_XA_FILTER = 1 << 3,
CDROM_MODE_IGNORE_LOC = 1 << 4,
CDROM_MODE_SIZE_2048 = 0 << 5,
CDROM_MODE_SIZE_2340 = 1 << 5,
CDROM_MODE_XA_ADPCM = 1 << 6,
CDROM_MODE_SPEED_1X = 0 << 7,
CDROM_MODE_SPEED_2X = 1 << 7
} CDROMModeFlag;
#define CDROM_STAT _MMIO8(IO_BASE | 0x1800)
#define CDROM_CMD _MMIO8(IO_BASE | 0x1801)
#define CDROM_DATA _MMIO8(IO_BASE | 0x1802)
#define CDROM_IRQ _MMIO8(IO_BASE | 0x1803)
#define CDROM_REG(N) _MMIO8((IO_BASE | 0x1800) + (N))
/* GPU */
typedef enum {
GP1_STAT_MODE_PAL = 1 << 20,
GP1_STAT_DISP_BLANK = 1 << 23,
GP1_STAT_IRQ = 1 << 24,
GP1_STAT_DREQ = 1 << 25,
GP1_STAT_CMD_READY = 1 << 26,
GP1_STAT_READ_READY = 1 << 27,
GP1_STAT_WRITE_READY = 1 << 28,
GP1_STAT_FIELD_ODD = 1 << 31
} GP1StatusFlag;
#define GPU_GP0 _MMIO32(IO_BASE | 0x1810)
#define GPU_GP1 _MMIO32(IO_BASE | 0x1814)
/* MDEC */
typedef enum {
MDEC_STAT_BLOCK_BITMASK = 7 << 16,
MDEC_STAT_BLOCK_Y0 = 0 << 16,
MDEC_STAT_BLOCK_Y1 = 1 << 16,
MDEC_STAT_BLOCK_Y2 = 2 << 16,
MDEC_STAT_BLOCK_Y3 = 3 << 16,
MDEC_STAT_BLOCK_CR = 4 << 16,
MDEC_STAT_BLOCK_CB = 5 << 16,
MDEC_STAT_DREQ_OUT = 1 << 27,
MDEC_STAT_DREQ_IN = 1 << 28,
MDEC_STAT_BUSY = 1 << 29,
MDEC_STAT_DATA_FULL = 1 << 30,
MDEC_STAT_DATA_EMPTY = 1 << 31
} MDECStatusFlag;
typedef enum {
MDEC_CTRL_DMA_OUT = 1 << 29,
MDEC_CTRL_DMA_IN = 1 << 30,
MDEC_CTRL_RESET = 1 << 31
} MDECControlFlag;
#define MDEC0 _MMIO32(IO_BASE | 0x1820)
#define MDEC1 _MMIO32(IO_BASE | 0x1824)
/* SPU */
typedef enum {
SPU_STAT_CDDA = 1 << 0,
SPU_STAT_EXT = 1 << 1,
SPU_STAT_CDDA_REVERB = 1 << 2,
SPU_STAT_EXT_REVERB = 1 << 3,
SPU_STAT_XFER_BITMASK = 3 << 4,
SPU_STAT_XFER_NONE = 0 << 4,
SPU_STAT_XFER_WRITE = 1 << 4,
SPU_STAT_XFER_DMA_WRITE = 2 << 4,
SPU_STAT_XFER_DMA_READ = 3 << 4,
SPU_STAT_IRQ = 1 << 6,
SPU_STAT_DREQ = 1 << 7,
SPU_STAT_WRITE_REQ = 1 << 8,
SPU_STAT_READ_REQ = 1 << 9,
SPU_STAT_BUSY = 1 << 10,
SPU_STAT_CAPTURE_BUF = 1 << 11
} SPUStatusFlag;
typedef enum {
SPU_CTRL_CDDA = 1 << 0,
SPU_CTRL_EXT = 1 << 1,
SPU_CTRL_CDDA_REVERB = 1 << 2,
SPU_CTRL_EXT_REVERB = 1 << 3,
SPU_CTRL_XFER_BITMASK = 3 << 4,
SPU_CTRL_XFER_NONE = 0 << 4,
SPU_CTRL_XFER_WRITE = 1 << 4,
SPU_CTRL_XFER_DMA_WRITE = 2 << 4,
SPU_CTRL_XFER_DMA_READ = 3 << 4,
SPU_CTRL_IRQ_ENABLE = 1 << 6,
SPU_CTRL_REVERB = 1 << 7,
SPU_CTRL_UNMUTE = 1 << 14,
SPU_CTRL_ENABLE = 1 << 15
} SPUControlFlag;
#define SPU_CH_VOL_L(N) _MMIO16((IO_BASE | 0x1c00) + (16 * (N)))
#define SPU_CH_VOL_R(N) _MMIO16((IO_BASE | 0x1c02) + (16 * (N)))
#define SPU_CH_FREQ(N) _MMIO16((IO_BASE | 0x1c04) + (16 * (N)))
#define SPU_CH_ADDR(N) _MMIO16((IO_BASE | 0x1c06) + (16 * (N)))
#define SPU_CH_ADSR1(N) _MMIO16((IO_BASE | 0x1c08) + (16 * (N)))
#define SPU_CH_ADSR2(N) _MMIO16((IO_BASE | 0x1c0a) + (16 * (N)))
#define SPU_CH_LOOP(N) _MMIO16((IO_BASE | 0x1c0e) + (16 * (N)))
#define SPU_MASTER_VOL_L _MMIO16(IO_BASE | 0x1d80)
#define SPU_MASTER_VOL_R _MMIO16(IO_BASE | 0x1d82)
#define SPU_REVERB_VOL_L _MMIO16(IO_BASE | 0x1d84)
#define SPU_REVERB_VOL_R _MMIO16(IO_BASE | 0x1d86)
#define SPU_FLAG_ON1 _MMIO16(IO_BASE | 0x1d88)
#define SPU_FLAG_ON2 _MMIO16(IO_BASE | 0x1d8a)
#define SPU_FLAG_OFF1 _MMIO16(IO_BASE | 0x1d8c)
#define SPU_FLAG_OFF2 _MMIO16(IO_BASE | 0x1d8e)
#define SPU_FLAG_FM1 _MMIO16(IO_BASE | 0x1d90)
#define SPU_FLAG_FM2 _MMIO16(IO_BASE | 0x1d92)
#define SPU_FLAG_NOISE1 _MMIO16(IO_BASE | 0x1d94)
#define SPU_FLAG_NOISE2 _MMIO16(IO_BASE | 0x1d96)
#define SPU_FLAG_REVERB1 _MMIO16(IO_BASE | 0x1d98)
#define SPU_FLAG_REVERB2 _MMIO16(IO_BASE | 0x1d9a)
#define SPU_FLAG_STATUS1 _MMIO16(IO_BASE | 0x1d9c)
#define SPU_FLAG_STATUS2 _MMIO16(IO_BASE | 0x1d9e)
#define SPU_REVERB_ADDR _MMIO16(IO_BASE | 0x1da2)
#define SPU_IRQ_ADDR _MMIO16(IO_BASE | 0x1da4)
#define SPU_ADDR _MMIO16(IO_BASE | 0x1da6)
#define SPU_DATA _MMIO16(IO_BASE | 0x1da8)
#define SPU_CTRL _MMIO16(IO_BASE | 0x1daa)
#define SPU_DMA_CTRL _MMIO16(IO_BASE | 0x1dac)
#define SPU_STAT _MMIO16(IO_BASE | 0x1dae)
#define SPU_CDDA_VOL_L _MMIO16(IO_BASE | 0x1db0)
#define SPU_CDDA_VOL_R _MMIO16(IO_BASE | 0x1db2)
#define SPU_EXT_VOL_L _MMIO16(IO_BASE | 0x1db4)
#define SPU_EXT_VOL_R _MMIO16(IO_BASE | 0x1db6)
#define SPU_VOL_STAT_L _MMIO16(IO_BASE | 0x1db8)
#define SPU_VOL_STAT_R _MMIO16(IO_BASE | 0x1dba)
#define SPU_REVERB_BASE _ADDR16(IO_BASE | 0x1dc0)
/* System 573 base hardware */
typedef enum {
SYS573_MISC_OUT_ADC_MOSI = 1 << 0,
SYS573_MISC_OUT_ADC_CS = 1 << 1,
SYS573_MISC_OUT_ADC_SCK = 1 << 2,
SYS573_MISC_OUT_COIN_COUNT1 = 1 << 3,
SYS573_MISC_OUT_COIN_COUNT2 = 1 << 4,
SYS573_MISC_OUT_AMP_ENABLE = 1 << 5,
SYS573_MISC_OUT_CDDA_ENABLE = 1 << 6,
SYS573_MISC_OUT_SPU_ENABLE = 1 << 7,
SYS573_MISC_OUT_JVS_STAT = 1 << 8
} Sys573MiscOutputFlag;
typedef enum {
SYS573_MISC_IN_ADC_MISO = 1 << 0,
SYS573_MISC_IN_ADC_SARS = 1 << 1,
SYS573_MISC_IN_CART_SDA = 1 << 2,
SYS573_MISC_IN_JVS_SENSE = 1 << 3,
SYS573_MISC_IN_JVS_AVAIL = 1 << 4,
SYS573_MISC_IN_JVS_UNK = 1 << 5,
SYS573_MISC_IN_CART_ISIG = 1 << 6,
SYS573_MISC_IN_CART_DSIG = 1 << 7,
SYS573_MISC_IN_COIN1 = 1 << 8,
SYS573_MISC_IN_COIN2 = 1 << 9,
SYS573_MISC_IN_PCMCIA_CD1 = 1 << 10,
SYS573_MISC_IN_PCMCIA_CD2 = 1 << 11,
SYS573_MISC_IN_SERVICE = 1 << 12
} Sys573MiscInputFlag;
#define SYS573_MISC_OUT _MMIO16(DEV0_BASE | 0x400000)
#define SYS573_DIP_CART _MMIO16(DEV0_BASE | 0x400004)
#define SYS573_MISC_IN _MMIO16(DEV0_BASE | 0x400006)
#define SYS573_JAMMA_MAIN _MMIO16(DEV0_BASE | 0x400008)
#define SYS573_JVS_RX_DATA _MMIO16(DEV0_BASE | 0x40000a)
#define SYS573_JAMMA_EXT1 _MMIO16(DEV0_BASE | 0x40000c)
#define SYS573_JAMMA_EXT2 _MMIO16(DEV0_BASE | 0x40000e)
#define SYS573_BANK_CTRL _MMIO16(DEV0_BASE | 0x500000)
#define SYS573_JVS_RESET _MMIO16(DEV0_BASE | 0x520000)
#define SYS573_IDE_RESET _MMIO16(DEV0_BASE | 0x560000)
#define SYS573_WATCHDOG _MMIO16(DEV0_BASE | 0x5c0000)
#define SYS573_EXT_OUT _MMIO16(DEV0_BASE | 0x600000)
#define SYS573_JVS_TX_DATA _MMIO16(DEV0_BASE | 0x680000)
#define SYS573_CART_OUT _MMIO16(DEV0_BASE | 0x6a0000)
#define SYS573_FLASH_BASE _ADDR16(DEV0_BASE | 0x000000)
#define SYS573_IDE_CS0_BASE _ADDR16(DEV0_BASE | 0x480000)
#define SYS573_IDE_CS1_BASE _ADDR16(DEV0_BASE | 0x4c0000)
#define SYS573_RTC_BASE _ADDR16(DEV0_BASE | 0x620000)
#define SYS573_IO_BASE _ADDR16(DEV0_BASE | 0x640000)
/* System 573 analog I/O board */
#define SYS573A_LIGHTS_A _MMIO16(DEV0_BASE | 0x640080)
#define SYS573A_LIGHTS_B _MMIO16(DEV0_BASE | 0x640088)
#define SYS573A_LIGHTS_C _MMIO16(DEV0_BASE | 0x640090)
#define SYS573A_LIGHTS_D _MMIO16(DEV0_BASE | 0x640098)
/* System 573 digital I/O board */
typedef enum {
SYS573D_CPLD_STAT_INIT = 1 << 12,
SYS573D_CPLD_STAT_DONE = 1 << 13,
SYS573D_CPLD_STAT_LDC = 1 << 14,
SYS573D_CPLD_STAT_HDC = 1 << 15
} Sys573DCPLDStatusFlag;
typedef enum {
SYS573D_CPLD_CTRL_UNK1 = 1 << 12,
SYS573D_CPLD_CTRL_UNK2 = 1 << 13,
SYS573D_CPLD_CTRL_UNK3 = 1 << 14,
SYS573D_CPLD_CTRL_UNK4 = 1 << 15
} Sys573DCPLDControlFlag;
#define SYS573D_FPGA_LIGHTS_A1 _MMIO16(DEV0_BASE | 0x6400e0)
#define SYS573D_FPGA_LIGHTS_A0 _MMIO16(DEV0_BASE | 0x6400e2)
#define SYS573D_FPGA_LIGHTS_B1 _MMIO16(DEV0_BASE | 0x6400e4)
#define SYS573D_FPGA_LIGHTS_D0 _MMIO16(DEV0_BASE | 0x6400e6)
#define SYS573D_FPGA_INIT _MMIO16(DEV0_BASE | 0x6400e8)
#define SYS573D_FPGA_DS2401 _MMIO16(DEV0_BASE | 0x6400ee)
#define SYS573D_CPLD_UNK_RESET _MMIO16(DEV0_BASE | 0x6400f4)
#define SYS573D_CPLD_STAT _MMIO16(DEV0_BASE | 0x6400f6)
#define SYS573D_CPLD_CTRL _MMIO16(DEV0_BASE | 0x6400f6)
#define SYS573D_CPLD_BITSTREAM _MMIO16(DEV0_BASE | 0x6400f8)
#define SYS573D_CPLD_LIGHTS_C0 _MMIO16(DEV0_BASE | 0x6400fa)
#define SYS573D_CPLD_LIGHTS_C1 _MMIO16(DEV0_BASE | 0x6400fc)
#define SYS573D_CPLD_LIGHTS_B0 _MMIO16(DEV0_BASE | 0x6400fe)

156
src/ps1/system.c Normal file
View File

@ -0,0 +1,156 @@
/*
* ps1-bare-metal - (C) 2023 spicyjpeg
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
* INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
* LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
#include <stdatomic.h>
#include <stdbool.h>
#include <stdint.h>
#include "ps1/registers.h"
#include "ps1/system.h"
#define BIOS_API_TABLE ((VoidFunction *) 0x80000200)
#define BIOS_BP_VECTOR ((uint32_t *) 0x80000040)
#define BIOS_EXC_VECTOR ((uint32_t *) 0x80000080)
/* Internal state */
static VoidFunction _flushCache = 0;
static Thread _mainThread;
ArgFunction interruptHandler = 0;
void *interruptHandlerArg = 0;
Thread *currentThread = &_mainThread;
Thread *nextThread = &_mainThread;
/* Exception handler setup */
void _exceptionVector(void);
void installExceptionHandler(void) {
// Clear all pending IRQ flags and prevent the interrupt controller from
// generating further IRQs.
IRQ_MASK = 0;
IRQ_STAT = 0;
DMA_DPCR = 0;
DMA_DICR = DMA_DICR_CH_STAT_MASK;
// Ensure interrupts and the GTE are enabled at the COP0 side.
uint32_t sr = SR_IEc | SR_Im2 | SR_CU0 | SR_CU2;
__asm__ volatile("mtc0 %0, $12;" :: "r"(sr));
// Grab a direct pointer to the BIOS function to flush the instruction
// cache. This is the only function that must always run from the BIOS ROM
// as it temporarily disables main RAM.
_flushCache = BIOS_API_TABLE[0x44];
// Overwrite the default breakpoint and exception handlers placed into RAM
// by the BIOS with a function that will jump to our custom handler.
__builtin_memcpy(BIOS_BP_VECTOR, &_exceptionVector, 16);
__builtin_memcpy(BIOS_EXC_VECTOR, &_exceptionVector, 16);
_flushCache();
DMA_DPCR = 0x0bbbbbbb;
DMA_DICR = DMA_DICR_IRQ_ENABLE;
}
void setInterruptHandler(ArgFunction func, void *arg) {
setInterruptMask(0);
interruptHandler = func;
interruptHandlerArg = arg;
atomic_signal_fence(memory_order_release);
}
void flushCache(void) {
//if (!_flushCache)
//_flushCache = BIOS_API_TABLE[0x44];
uint32_t mask = setInterruptMask(0);
_flushCache();
if (mask)
setInterruptMask(mask);
}
/* IRQ acknowledgement and blocking delay */
void delayMicroseconds(int us) {
// 1 us = 33.8688 cycles = 17 loop iterations (2 cycles per iteration)
us *= (F_CPU + 1000000) / 2000000;
__asm__ volatile(
".set noreorder;"
"bgtz %0, .;"
"addiu %0, -1;"
".set reorder;"
: "=r"(us) : "r"(us)
);
}
bool acknowledgeInterrupt(IRQChannel irq) {
if (IRQ_STAT & (1 << irq)) {
IRQ_STAT = ~(1 << irq);
return true;
}
return false;
}
bool waitForInterrupt(IRQChannel irq, int timeout) {
for (; timeout > 0; timeout--) {
if (acknowledgeInterrupt(irq))
return true;
delayMicroseconds(1);
}
return false;
}
bool waitForDMATransfer(DMAChannel dma, int timeout) {
for (; timeout > 0; timeout--) {
if (!(DMA_CHCR(dma) & DMA_CHCR_ENABLE))
return true;
delayMicroseconds(1);
}
return false;
}
/* Thread switching */
void switchThread(Thread *thread) {
if (!thread)
thread = &_mainThread;
nextThread = thread;
atomic_signal_fence(memory_order_release);
}
void switchThreadImmediate(Thread *thread) {
if (!thread)
thread = &_mainThread;
nextThread = thread;
atomic_signal_fence(memory_order_release);
// Execute a syscall to force the switch to happen. Note that the syscall
// handler will take a different path if $a0 is zero (see system.s), but
// that will never happen here since the check above is ensuring $a0 (i.e.
// the first argument) will always be a valid pointer.
__asm__ volatile("syscall 0;" :: "r"(thread) : "a0", "memory");
}

218
src/ps1/system.h Normal file
View File

@ -0,0 +1,218 @@
/*
* ps1-bare-metal - (C) 2023 spicyjpeg
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
* INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
* LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
#pragma once
#include <stdbool.h>
#include <stdint.h>
#include "ps1/registers.h"
typedef enum {
CAUSE_INT = 0, // Interrupt
CAUSE_AdEL = 4, // Load address error
CAUSE_AdES = 5, // Store address error
CAUSE_IBE = 6, // Instruction bus error
CAUSE_DBE = 7, // Data bus error
CAUSE_SYS = 8, // Syscall
CAUSE_BP = 9, // Breakpoint or break instruction
CAUSE_RI = 10, // Reserved instruction
CAUSE_CpU = 11, // Coprocessor unusable
CAUSE_Ov = 12 // Arithmetic overflow
} ExceptionCause;
typedef enum {
SR_IEc = 1 << 0, // Current interrupt enable
SR_KUc = 1 << 1, // Current privilege level
SR_IEp = 1 << 2, // Previous interrupt enable
SR_KUp = 1 << 3, // Previous privilege level
SR_IEo = 1 << 4, // Old interrupt enable
SR_KUo = 1 << 5, // Old privilege level
SR_Im0 = 1 << 8, // IRQ mask 0 (software interrupt)
SR_Im1 = 1 << 9, // IRQ mask 1 (software interrupt)
SR_Im2 = 1 << 10, // IRQ mask 2 (hardware interrupt)
SR_CU0 = 1 << 28, // Coprocessor 0 privilege level
SR_CU2 = 1 << 30 // Coprocessor 2 enable
} SRFlag;
typedef struct {
uint32_t pc, at, v0, v1, a0, a1, a2, a3;
uint32_t t0, t1, t2, t3, t4, t5, t6, t7;
uint32_t s0, s1, s2, s3, s4, s5, s6, s7;
uint32_t t8, t9, gp, sp, fp, ra, hi, lo;
} Thread;
typedef void (*VoidFunction)(void);
typedef void (*ArgFunction)(void *arg);
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Read-only pointer to the currently running thread.
*/
extern Thread *currentThread;
/**
* @brief Read-only pointer to the thread scheduled to be executed after the
* currently running one. Use switchThread() or switchThreadImmediate() to set
* this pointer.
*/
extern Thread *nextThread;
/**
* @brief Disables interrupts temporarily, then sets the IRQ_MASK register to
* the specified value (which should be a bitfield of (1 << IRQ_*) flags) and
* returns its previous value. Must *not* be used in IRQ handlers.
*/
static inline uint32_t setInterruptMask(uint32_t mask) {
register uint32_t v0 __asm__("v0");
register uint32_t a0 __asm__("a0") = 0;
register uint32_t a1 __asm__("a1") = mask;
__asm__ volatile("syscall 0;" : "=r"(v0) : "r"(a0), "r"(a1) : "memory");
return v0;
}
/**
* @brief Initializes a thread structure with the provided entry point
* (function) and stacktop. The function *must not* return. The stack should be
* aligned to 8 bytes as required by the MIPS ABI.
*
* @param thread
* @param func
* @param stack Pointer to last 8 bytes in the stack
* @param arg Optional argument to entry point
*/
static inline void initThread(
Thread *thread, ArgFunction func, void *arg, void *stack
) {
register uint32_t gp __asm__("gp");
thread->pc = (uint32_t) func;
thread->a0 = (uint32_t) arg;
thread->gp = (uint32_t) gp;
thread->sp = (uint32_t) stack;
thread->fp = (uint32_t) stack;
thread->ra = 0;
}
/**
* @brief Sets up the exception handler, removes the BIOS from memory and
* flushes the instruction cache. Must be called only once, before *any* other
* function in this header is used.
*/
void installExceptionHandler(void);
/**
* @brief Disables interrupts and sets the function that will be called whenever
* a future interrupt or syscall occurs. Must be called after
* installExceptionHandler() and before interrupts are enabled. As the callback
* will run from within the exception handler, it is subject to several
* limitations:
*
* - it cannot call functions that rely on syscalls such as enableInterrupts(),
* switchThreadImmediate() or setInterruptHandler();
* - it cannot wait for other interrupts to occur;
* - it must return quickly, as IRQs fired while the exception handler is
* running may otherwise be missed.
*
* Interrupts must be re-enabled manually after setting a new handler.
*
* @param func
* @param arg Optional argument to be passed to handler
*/
void setInterruptHandler(ArgFunction func, void *arg);
/**
* @brief Clears the instruction cache. Must *not* be used in IRQ handlers.
*/
void flushCache(void);
/**
* @brief Blocks for (roughly) the specified number of microseconds. This
* function does not rely on a hardware timer, so interrupts may throw off
* timings if not explicitly disabled prior to calling delayMicroseconds().
*
* @param time
*/
void delayMicroseconds(int time);
/**
* @brief Checks if the specified interrupt was fired but not yet acknowledged;
* if so, acknowledges it and returns true. This function can be used in a
* callback set using setInterruptHandler() to check for individual IRQs that
* need to be processed, but will also work with interrupts that are not
* explicitly enabled in the IRQ_MASK register.
*
* Note that most interrupts must additionally be acknowledged at the device
* side (through DMA/SIO/SPU/CD-ROM registers or by issuing the GP1 IRQ
* acknowledge command) once this function returns true. Lightgun, vblank and
* timer interrupts do not require device-side acknowledgement.
*
* @param irq
* @return True if the IRQ was pending and got acknowledged, false otherwise
*/
bool acknowledgeInterrupt(IRQChannel irq);
/**
* @brief Waits for the specified interrupt to be fired for up to the specified
* number of microseconds. This function will work with interrupts that are not
* explicitly enabled in the IRQ_MASK register, but will *not* work with
* interrupts that have been enabled if any callback set using
* setInterruptHandler() acknowledges them.
*
* @param irq
* @param timeout
* @return False in case of a timeout, true otherwise
*/
bool waitForInterrupt(IRQChannel irq, int timeout);
/**
* @brief Waits for the specified DMA channel to finish any ongoing transfer for
* up to the specified number of microseconds.
*
* @param dma
* @param timeout
* @return False in case of a timeout, true otherwise
*/
bool waitForDMATransfer(DMAChannel dma, int timeout);
/**
* @brief Pauses the thread calling this function and starts/resumes executing
* the specified one. The switch will not happen immediately, but will only be
* processed once an interrupt occurs or a syscall is issued. If called from an
* IRQ handler, it will happen once all IRQ handlers have been executed.
*
* @param thread Pointer to new thread or NULL for main thread
*/
void switchThread(Thread *thread);
/**
* @brief Pauses the thread calling this function immediately and starts/resumes
* executing the specified one. Once the other thread switches back, execution
* will resume from after the call to switchThreadImmediate(). This function
* must *not* be used in IRQ handlers; use switchThread() (which will behave
* identically as thread switches are processed right after IRQ handling)
* instead.
*
* @param thread Pointer to new thread or NULL for main thread
*/
void switchThreadImmediate(Thread *thread);
#ifdef __cplusplus
}
#endif

201
src/ps1/system.s Normal file
View File

@ -0,0 +1,201 @@
# ps1-bare-metal - (C) 2023 spicyjpeg
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
# AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
# OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
# PERFORMANCE OF THIS SOFTWARE.
.set noreorder
.set noat
.set BADV, $8
.set SR, $12
.set CAUSE, $13
.set EPC, $14
.set IO_BASE, 0xbf80
.set IRQ_STAT, 0x1070
.set IRQ_MASK, 0x1074
.section .text._exceptionVector, "ax", @progbits
.global _exceptionVector
.type _exceptionVector, @function
_exceptionVector:
# This tiny stub is going to be relocated to the address the CPU jumps to
# when an exception occurs (0x80000080) at runtime, overriding the default
# one installed by the BIOS.
lui $k0, %hi(currentThread)
j _exceptionHandler
lw $k0, %lo(currentThread)($k0)
nop
.section .text._exceptionHandler, "ax", @progbits
.global _exceptionHandler
.type _exceptionHandler, @function
_exceptionHandler:
# We're going to need at least 3 registers to store a pointer to the current
# thread, the return pointer (EPC) and the state of the CAUSE register
# respectively. $k0 and $k1 are always available to the exception handler,
# so only $at needs to be saved.
nop
sw $at, 0x04($k0)
mfc0 $at, CAUSE
# Check CAUSE bits 2-6 to determine what triggered the exception. If it was
# caused by a syscall, increment EPC so it won't be executed again;
# furthermore, if the first argument passed to the syscall was zero, take an
# alternate, shorter code path (as it is the syscall to set IRQ_MASK).
li $k1, 8 << 2 # if (((CAUSE >> 2) & 0x1f) != 8) goto notFastSyscall
andi $at, 0x1f << 2
bne $at, $k1, .LnotFastSyscall
mfc0 $k1, EPC
bnez $a0, .LnotFastSyscall # if (arg0) goto notFastSyscall
addiu $k1, 4 # EPC++
.LfastSyscall:
# Save the current value of IRQ_MASK then set it "atomically" (as interrupts
# are disabled while the exception handler runs), then restore $at and
# return immediately without the overhead of saving and restoring the whole
# thread.
lui $at, IO_BASE
lhu $v0, IRQ_MASK($at) # returnValue = IRQ_MASK
lw $at, 0x04($k0)
sh $a1, IRQ_MASK($at) # IRQ_MASK = arg1
jr $k1
rfe
.LnotFastSyscall:
# If the fast path couldn't be taken, save the full state of the thread. The
# state of $hi/$lo is saved after all other registers in order to let the
# multiplier finish any ongoing calculation.
sw $v0, 0x08($k0)
sw $v1, 0x0c($k0)
sw $a0, 0x10($k0)
sw $a1, 0x14($k0)
sw $a2, 0x18($k0)
sw $a3, 0x1c($k0)
sw $t0, 0x20($k0)
sw $t1, 0x24($k0)
sw $t2, 0x28($k0)
sw $t3, 0x2c($k0)
sw $t4, 0x30($k0)
sw $t5, 0x34($k0)
sw $t6, 0x38($k0)
sw $t7, 0x3c($k0)
sw $s0, 0x40($k0)
sw $s1, 0x44($k0)
sw $s2, 0x48($k0)
sw $s3, 0x4c($k0)
sw $s4, 0x50($k0)
sw $s5, 0x54($k0)
sw $s6, 0x58($k0)
sw $s7, 0x5c($k0)
sw $t8, 0x60($k0)
sw $t9, 0x64($k0)
sw $gp, 0x68($k0)
sw $sp, 0x6c($k0)
sw $fp, 0x70($k0)
sw $ra, 0x74($k0)
mfhi $v0
mflo $v1
sw $v0, 0x78($k0)
sw $v1, 0x7c($k0)
# Check again if the CAUSE code is either 0 (IRQ) or 8 (syscall). If not
# call _unhandledException(), which will then display information about the
# exception and lock up.
lui $v0, %hi(interruptHandler)
andi $v1, $at, 0x17 << 2 # if (!(((CAUSE >> 2) & 0x1f) % 8)) goto irqOrSyscall
beqz $v1, .LirqOrSyscall
lw $v0, %lo(interruptHandler)($v0)
.LotherException:
mfc0 $a1, BADV # _unhandledException((CAUSE >> 2) & 0x1f, BADV)
srl $a0, $at, 2
jal _unhandledException
addiu $sp, -8
b .Lreturn
addiu $sp, 8
.LirqOrSyscall:
# Otherwise, check if the interrupted instruction was a GTE opcode and
# increment EPC to avoid executing it again (as with syscalls). This is a
# workaround for a hardware bug.
lw $v1, 0($k1)
li $at, 0x25 # if ((*EPC >> 25) == 0x25) EPC++
srl $v1, 25
bne $v1, $at, .LskipIncrement
lui $a0, %hi(interruptHandlerArg)
addiu $k1, 4
.LskipIncrement:
lw $a0, %lo(interruptHandlerArg)($a0)
sw $k1, 0x00($k0)
# Dispatch any pending interrupts.
jalr $v0 # interruptHandler(interruptHandlerArg)
addiu $sp, -8
addiu $sp, 8
.Lreturn:
# Grab a pointer to the next thread to be executed, restore its state and
# return.
lui $k0, %hi(nextThread)
lw $k0, %lo(nextThread)($k0)
lui $at, %hi(currentThread)
sw $k0, %lo(currentThread)($at)
lw $v0, 0x78($k0)
lw $v1, 0x7c($k0)
mthi $v0
mtlo $v1
lw $k1, 0x00($k0)
lw $at, 0x04($k0)
lw $v0, 0x08($k0)
lw $v1, 0x0c($k0)
lw $a0, 0x10($k0)
lw $a1, 0x14($k0)
lw $a2, 0x18($k0)
lw $a3, 0x1c($k0)
lw $t0, 0x20($k0)
lw $t1, 0x24($k0)
lw $t2, 0x28($k0)
lw $t3, 0x2c($k0)
lw $t4, 0x30($k0)
lw $t5, 0x34($k0)
lw $t6, 0x38($k0)
lw $t7, 0x3c($k0)
lw $s0, 0x40($k0)
lw $s1, 0x44($k0)
lw $s2, 0x48($k0)
lw $s3, 0x4c($k0)
lw $s4, 0x50($k0)
lw $s5, 0x54($k0)
lw $s6, 0x58($k0)
lw $s7, 0x5c($k0)
lw $t8, 0x60($k0)
lw $t9, 0x64($k0)
lw $gp, 0x68($k0)
lw $sp, 0x6c($k0)
lw $fp, 0x70($k0)
lw $ra, 0x74($k0)
jr $k1
rfe

78
src/ps1/unhandledexc.c Normal file
View File

@ -0,0 +1,78 @@
/*
* ps1-bare-metal - (C) 2023 spicyjpeg
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
* INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
* LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*
* If any exception other than an IRQ or syscall (such as a bus or alignment
* error) occurs, the exception handler defined in system.s will call
* _unhandledException() to safely halt the program. This is a very simple
* implementation of it that prints the state of all registers then locks up.
*/
#include <stdint.h>
#include <stdio.h>
#include "ps1/system.h"
#ifndef NDEBUG
static const char *const _causeNames[] = {
"load address error",
"store address error",
"instruction bus error",
"data bus error",
"syscall",
"break instruction",
"reserved instruction",
"coprocessor unusable",
"arithmetic overflow"
};
static const char _registerNames[] =
"pc" "at" "v0" "v1" "a0" "a1" "a2" "a3"
"t0" "t1" "t2" "t3" "t4" "t5" "t6" "t7"
"s0" "s1" "s2" "s3" "s4" "s5" "s6" "s7"
"t8" "t9" "gp" "sp" "fp" "ra" "hi" "lo";
#endif
void _unhandledException(ExceptionCause cause, uint32_t badv) {
#ifndef NDEBUG
if ((cause == CAUSE_AdEL) || (cause == CAUSE_AdES))
printf("Exception: %s (%08x)\nRegister dump:\n", _causeNames[cause - 4], badv);
else
printf("Exception: %s\nRegister dump:\n", _causeNames[cause - 4]);
const char *name = _registerNames;
uint32_t *reg = (uint32_t *) &(currentThread->pc);
for (int i = 31; i >= 0; i--) {
char a = *(name++), b = *(name++);
printf(" %c%c=%08x", a, b, *(reg++));
if (!(i % 4))
putchar('\n');
}
printf("Stack dump:\n");
uint32_t *addr = ((uint32_t *) currentThread->sp) - 7;
uint32_t *end = ((uint32_t *) currentThread->sp) + 7;
for (; addr <= end; addr++) {
char arrow = (((uint32_t) addr) == currentThread->sp) ? '>' : ' ';
printf("%c %08x: %08x\n", arrow, addr, *addr);
}
#endif
for (;;)
__asm__ volatile("");
}

175
src/spu.cpp Normal file
View File

@ -0,0 +1,175 @@
#include <assert.h>
#include <stdint.h>
#include "ps1/registers.h"
#include "spu.hpp"
#include "util.hpp"
namespace spu {
/* Basic API */
static constexpr int _DMA_CHUNK_SIZE = 8;
static constexpr int _DMA_TIMEOUT = 10000;
static constexpr int _STATUS_TIMEOUT = 1000;
static constexpr uint32_t _DUMMY_BLOCK_ADDR = 0x1000;
static bool _waitForStatus(uint16_t mask, uint16_t value) {
for (int timeout = _STATUS_TIMEOUT; timeout > 0; timeout--) {
if ((SPU_STAT & mask) == value)
return true;
delayMicroseconds(1);
}
return false;
}
void init(void) {
BIU_DEV4_CTRL = 0
| ( 1 << 0) // Write delay
| (14 << 4) // Read delay
| BIU_CTRL_RECOVERY
| BIU_CTRL_WIDTH_16
| BIU_CTRL_AUTO_INCR
| (9 << 16) // Number of address lines
| (0 << 24) // DMA read/write delay
| BIU_CTRL_DMA_DELAY;
SPU_CTRL = 0;
_waitForStatus(0x3f, 0);
SPU_MASTER_VOL_L = 0;
SPU_MASTER_VOL_R = 0;
SPU_REVERB_VOL_L = 0;
SPU_REVERB_VOL_R = 0;
SPU_REVERB_ADDR = 0xfffe;
SPU_CTRL = SPU_CTRL_ENABLE;
_waitForStatus(0x3f, 0);
// Place a dummy (silent) looping block at the beginning of SPU RAM.
SPU_DMA_CTRL = 4;
SPU_ADDR = _DUMMY_BLOCK_ADDR / 8;
SPU_DATA = 0x0500;
for (int i = 7; i > 0; i--)
SPU_DATA = 0;
SPU_CTRL = SPU_CTRL_XFER_WRITE | SPU_CTRL_ENABLE;
_waitForStatus(SPU_CTRL_XFER_BITMASK | SPU_STAT_BUSY, SPU_CTRL_XFER_WRITE);
delayMicroseconds(100);
SPU_CTRL = SPU_CTRL_UNMUTE | SPU_CTRL_ENABLE;
resetAllChannels();
}
int getFreeChannel(void) {
uint32_t flags = SPU_FLAG_STATUS1 | (SPU_FLAG_STATUS2 << 16);
for (int ch = 0; flags; ch++, flags >>= 1) {
if (flags & 1)
return ch;
}
return -1;
}
void stopChannel(int ch) {
SPU_CH_VOL_L(ch) = 0;
SPU_CH_VOL_R(ch) = 0;
SPU_CH_FREQ(ch) = 0;
SPU_CH_ADDR(ch) = 0;
if (ch < 16) {
SPU_FLAG_OFF1 = 1 << ch;
SPU_FLAG_ON1 = 1 << ch;
} else {
SPU_FLAG_OFF2 = 1 << (ch - 16);
SPU_FLAG_ON2 = 1 << (ch - 16);
}
}
void resetAllChannels(void) {
for (int ch = 23; ch >= 0; ch--) {
SPU_CH_VOL_L(ch) = 0;
SPU_CH_VOL_R(ch) = 0;
SPU_CH_FREQ(ch) = 0x1000;
SPU_CH_ADDR(ch) = _DUMMY_BLOCK_ADDR / 8;
}
SPU_FLAG_FM1 = 0;
SPU_FLAG_FM2 = 0;
SPU_FLAG_NOISE1 = 0;
SPU_FLAG_NOISE2 = 0;
SPU_FLAG_REVERB1 = 0;
SPU_FLAG_REVERB2 = 0;
SPU_FLAG_ON1 = 0xffff;
SPU_FLAG_ON2 = 0x00ff;
}
size_t upload(uint32_t ramOffset, const void *data, size_t length, bool wait) {
length /= 4;
assert(!(length % _DMA_CHUNK_SIZE));
length = (length + _DMA_CHUNK_SIZE - 1) / _DMA_CHUNK_SIZE;
if (!waitForDMATransfer(DMA_SPU, _DMA_TIMEOUT))
return 0;
uint16_t ctrlReg = SPU_CTRL & ~SPU_CTRL_XFER_BITMASK;
SPU_CTRL = ctrlReg;
_waitForStatus(SPU_CTRL_XFER_BITMASK, 0);
SPU_DMA_CTRL = 4;
SPU_ADDR = ramOffset / 8;
SPU_CTRL = ctrlReg | SPU_CTRL_XFER_DMA_WRITE;
_waitForStatus(SPU_CTRL_XFER_BITMASK, SPU_CTRL_XFER_DMA_WRITE);
DMA_MADR(DMA_SPU) = reinterpret_cast<uint32_t>(data);
DMA_BCR (DMA_SPU) = _DMA_CHUNK_SIZE | (length << 16);
DMA_CHCR(DMA_SPU) = DMA_CHCR_WRITE | DMA_CHCR_MODE_SLICE | DMA_CHCR_ENABLE;
if (wait)
waitForDMATransfer(DMA_SPU, _DMA_TIMEOUT);
return length * _DMA_CHUNK_SIZE * 4;
}
/* Sound class */
bool Sound::initFromVAGHeader(const VAGHeader *header, uint32_t ramOffset) {
if ((header->magic != 0x70474156) || header->interleave)
return false;
offset = ramOffset / 8;
sampleRate = (util::swapEndian(header->sampleRate) << 12) / 44100;
length = util::swapEndian(header->length);
return true;
}
int Sound::play(int ch, int16_t volume) const {
if ((ch < 0) || (ch > 23))
return -1;
if (!offset)
return -1;
SPU_CH_VOL_L(ch) = volume;
SPU_CH_VOL_R(ch) = volume;
SPU_CH_FREQ (ch) = sampleRate;
SPU_CH_ADDR (ch) = offset;
SPU_CH_ADSR1(ch) = 0x00ff;
SPU_CH_ADSR2(ch) = 0x0000;
if (ch < 16)
SPU_FLAG_ON1 = 1 << ch;
else
SPU_FLAG_ON2 = 1 << (ch - 16);
return ch;
}
}

49
src/spu.hpp Normal file
View File

@ -0,0 +1,49 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
#include "ps1/registers.h"
namespace spu {
/* Basic API */
static inline void setVolume(int16_t master, int16_t reverb = 0) {
SPU_MASTER_VOL_L = master;
SPU_MASTER_VOL_R = master;
SPU_REVERB_VOL_L = reverb;
SPU_REVERB_VOL_R = reverb;
}
void init(void);
int getFreeChannel(void);
void stopChannel(int ch);
void resetAllChannels(void);
size_t upload(uint32_t ramOffset, const void *data, size_t length, bool wait);
/* Sound class */
struct [[gnu::packed]] VAGHeader {
public:
uint32_t magic, version, interleave, length, sampleRate;
uint16_t _reserved[5], channels;
char name[16];
};
class Sound {
public:
uint16_t offset, sampleRate;
size_t length;
inline Sound(void)
: offset(0), length(0) {}
inline int play(int16_t volume = 0x3fff) const {
return play(getFreeChannel(), volume);
}
bool initFromVAGHeader(const VAGHeader *header, uint32_t ramOffset);
int play(int ch, int16_t volume = 0x3fff) const;
};
}

345
src/uibase.cpp Normal file
View File

@ -0,0 +1,345 @@
#include <stdint.h>
#include "ps1/gpucmd.h"
#include "gpu.hpp"
#include "io.hpp"
#include "pad.hpp"
#include "uibase.hpp"
namespace ui {
/* Button state manager */
static const uint32_t _BUTTON_MAPPINGS[NUM_BUTTON_MAPS][NUM_BUTTONS]{
{ // MAP_JOYSTICK
io::JAMMA_P1_LEFT | io::JAMMA_P1_UP | io::JAMMA_P2_LEFT | io::JAMMA_P2_UP,
io::JAMMA_P1_RIGHT | io::JAMMA_P1_DOWN | io::JAMMA_P2_RIGHT | io::JAMMA_P2_DOWN,
io::JAMMA_P1_START | io::JAMMA_P2_START,
io::JAMMA_TEST | io::JAMMA_SERVICE
},
{ // MAP_DDR_CAB
io::JAMMA_P1_BUTTON2 | io::JAMMA_P2_BUTTON2,
io::JAMMA_P1_BUTTON3 | io::JAMMA_P2_BUTTON3,
io::JAMMA_P1_START | io::JAMMA_P2_START,
io::JAMMA_TEST | io::JAMMA_SERVICE
},
{ // MAP_DDR_SOLO_CAB
io::JAMMA_P1_BUTTON5,
io::JAMMA_P2_BUTTON5,
io::JAMMA_P1_START,
io::JAMMA_TEST | io::JAMMA_SERVICE
},
{ // MAP_DM_CAB
io::JAMMA_P2_LEFT,
io::JAMMA_P2_RIGHT,
io::JAMMA_P1_START,
io::JAMMA_TEST | io::JAMMA_SERVICE
},
{ // MAP_DMX_CAB (more or less redundant with MAP_JOYSTICK)
io::JAMMA_P1_UP | io::JAMMA_P2_UP,
io::JAMMA_P1_DOWN | io::JAMMA_P2_DOWN,
io::JAMMA_P1_START | io::JAMMA_P2_START,
io::JAMMA_TEST | io::JAMMA_SERVICE
},
{ // MAP_SINGLE_BUTTON
0,
0,
io::JAMMA_P1_START | io::JAMMA_P2_START | io::JAMMA_TEST | io::JAMMA_SERVICE,
0
}
};
ButtonState::ButtonState(void)
: _held(0), _repeatTimer(0) {}
void ButtonState::update(void) {
_prevHeld = _held;
_held = 0;
uint32_t inputs = io::getJAMMAInputs();
auto map = _BUTTON_MAPPINGS[buttonMap];
for (int i = 0; i < NUM_BUTTONS; i++) {
if (inputs & map[i])
_held |= 1 << i;
}
#ifdef ENABLE_PS1_CONTROLLER
if (pad::ports[0].pollPad() || pad::ports[1].pollPad()) {
_held = 0; // Ignore JAMMA inputs
for (int i = 1; i >= 0; i--) {
auto &port = pad::ports[i];
if (
(port.padType != pad::PAD_DIGITAL) &&
(port.padType != pad::PAD_ANALOG) &&
(port.padType != pad::PAD_ANALOG_STICK)
)
continue;
if (port.buttons & (pad::BTN_LEFT | pad::BTN_UP))
_held |= 1 << BTN_LEFT;
if (port.buttons & (pad::BTN_RIGHT | pad::BTN_DOWN))
_held |= 1 << BTN_RIGHT;
if (port.buttons & (pad::BTN_CIRCLE | pad::BTN_CROSS))
_held |= 1 << BTN_START;
if (port.buttons & pad::BTN_SELECT)
_held |= 1 << BTN_DEBUG;
}
}
#endif
uint32_t changed = _prevHeld ^ _held;
if (buttonMap == MAP_SINGLE_BUTTON) {
_pressed = 0;
_released = 0;
_repeating = 0;
// In single-button mode, interpret a short button press as the right
// button and a long press as start.
if (_held) {
if (_repeatTimer == REPEAT_DELAY)
_pressed |= 1 << BTN_START;
_repeatTimer++;
} else if (_prevHeld) {
if (_repeatTimer >= REPEAT_DELAY)
_released |= 1 << BTN_START;
else
_pressed |= 1 << BTN_RIGHT;
_repeatTimer = 0;
}
} else {
if (changed)
_repeatTimer = 0;
else if (_held)
_repeatTimer++;
_pressed = (changed & _held) & ~_pressed;
_released = (changed & _prevHeld) & ~_released;
_repeating = (_repeatTimer >= REPEAT_DELAY) ? _held : 0;
}
}
/* UI context */
Context::Context(gpu::Context &gpuCtx, void *screenData)
: _background(nullptr), _overlay(nullptr), _currentScreen(0), gpuCtx(gpuCtx),
time(0), screenData(screenData) {
_screens[0] = nullptr;
_screens[1] = nullptr;
}
void Context::show(Screen &screen, bool goBack, bool playSound) {
auto oldScreen = _screens[_currentScreen];
if (oldScreen)
oldScreen->hide(*this, goBack);
_currentScreen ^= 1;
_screens[_currentScreen] = &screen;
screen.show(*this, goBack);
if (playSound)
sounds[goBack ? SOUND_EXIT : SOUND_ENTER].play();
}
void Context::draw(void) {
auto oldScreen = _screens[_currentScreen ^ 1];
auto newScreen = _screens[_currentScreen];
if (_background)
_background->draw(*this);
if (oldScreen)
oldScreen->draw(*this, false);
if (newScreen)
newScreen->draw(*this, true);
if (_overlay)
_overlay->draw(*this);
}
void Context::update(void) {
buttons.update();
if (_overlay)
_overlay->update(*this);
if (_screens[_currentScreen])
_screens[_currentScreen]->update(*this);
}
/* Layer classes */
void Layer::_newLayer(Context &ctx, int x, int y, int width, int height) const {
ctx.gpuCtx.newLayer(x, y, width, height);
}
void Layer::_setTexturePage(Context &ctx, uint16_t texpage, bool dither) const {
ctx.gpuCtx.setTexturePage(texpage, dither);
}
void Layer::_setBlendMode(
Context &ctx, gpu::BlendMode blendMode, bool dither
) const {
ctx.gpuCtx.setBlendMode(blendMode, dither);
}
void TiledBackground::draw(Context &ctx) const {
_newLayer(ctx, 0, 0, ctx.gpuCtx.width, ctx.gpuCtx.height);
_setTexturePage(ctx, tile.texpage);
int offsetX = uint32_t(ctx.time / 2) % tile.width;
int offsetY = uint32_t(ctx.time / 3) % tile.height;
for (int x = -offsetX; x < ctx.gpuCtx.width; x += tile.width) {
for (int y = -offsetY; y < ctx.gpuCtx.height; y += tile.height)
tile.draw(ctx.gpuCtx, x, y);
}
gpu::RectWH rect;
int width = ctx.font.getStringWidth(text);
rect.x = ctx.gpuCtx.width - (8 + width);
rect.y = ctx.gpuCtx.height - (8 + gpu::FONT_LINE_HEIGHT);
rect.w = width;
rect.h = gpu::FONT_LINE_HEIGHT;
ctx.font.draw(ctx.gpuCtx, text, rect, COLOR_TEXT2);
}
LogOverlay::LogOverlay(util::Logger &logger)
: _logger(logger) {
_slideAnim.setValue(0);
}
void LogOverlay::draw(Context &ctx) const {
int offset = _slideAnim.getValue(ctx.time);
if (!offset)
return;
_newLayer(
ctx, 0, offset - ctx.gpuCtx.height, ctx.gpuCtx.width,
ctx.gpuCtx.height
);
ctx.gpuCtx.drawBackdrop(COLOR_BACKDROP, GP0_BLEND_SUBTRACT);
int screenHeight = ctx.gpuCtx.height - SCREEN_MARGIN_Y * 2;
int linesShown = screenHeight / gpu::FONT_LINE_HEIGHT;
gpu::Rect rect;
rect.x1 = SCREEN_MARGIN_X;
rect.y1 = SCREEN_MARGIN_Y;
rect.x2 = ctx.gpuCtx.width - SCREEN_MARGIN_X;
rect.y2 = SCREEN_MARGIN_Y + gpu::FONT_LINE_HEIGHT;
for (int i = linesShown - 1; i >= 0; i--) {
ctx.font.draw(ctx.gpuCtx, _logger.getLine(i), rect, COLOR_TEXT1);
rect.y1 = rect.y2;
rect.y2 += gpu::FONT_LINE_HEIGHT;
}
}
void LogOverlay::update(Context &ctx) {
if (ctx.buttons.pressed(BTN_DEBUG)) {
bool shown = !_slideAnim.getTargetValue();
_slideAnim.setValue(ctx.time, shown ? ctx.gpuCtx.height : 0, SPEED_SLOW);
ctx.sounds[shown ? SOUND_ENTER : SOUND_EXIT].play();
}
}
/* Base screen classes */
void AnimatedScreen::_newLayer(
Context &ctx, int x, int y, int width, int height
) const {
Screen::_newLayer(ctx, x + _slideAnim.getValue(ctx.time), y, width, height);
}
void AnimatedScreen::show(Context &ctx, bool goBack) {
int width = ctx.gpuCtx.width;
_slideAnim.setValue(ctx.time, goBack ? (-width) : width, 0, SPEED_SLOW);
}
void AnimatedScreen::hide(Context &ctx, bool goBack) {
int width = ctx.gpuCtx.width;
_slideAnim.setValue(ctx.time, 0, goBack ? width : (-width), SPEED_SLOW);
}
void BackdropScreen::show(Context &ctx, bool goBack) {
_backdropAnim.setValue(ctx.time, 0, 0x50, SPEED_FAST);
}
void BackdropScreen::hide(Context &ctx, bool goBack) {
_backdropAnim.setValue(ctx.time, 0x50, 0, SPEED_FAST);
}
void BackdropScreen::draw(Context &ctx, bool active) const {
int brightness = _backdropAnim.getValue(ctx.time);
if (!brightness)
return;
_newLayer(ctx, 0, 0, ctx.gpuCtx.width, ctx.gpuCtx.height);
ctx.gpuCtx.drawBackdrop(
gp0_rgb(brightness, brightness, brightness), GP0_BLEND_ADD
);
}
ModalScreen::ModalScreen(int width, int height)
: _width(width), _height(height), _title(nullptr), _body(nullptr) {}
void ModalScreen::show(Context &ctx, bool goBack) {
BackdropScreen::show(ctx, goBack);
_titleBarAnim.setValue(ctx.time, 0, _width, SPEED_SLOW);
}
void ModalScreen::draw(Context &ctx, bool active) const {
BackdropScreen::draw(ctx, active);
if (active) {
int windowHeight = TITLE_BAR_HEIGHT + _height;
_newLayer(
ctx, (ctx.gpuCtx.width - _width) / 2,
(ctx.gpuCtx.height - windowHeight) / 2, _width + SHADOW_OFFSET,
windowHeight + SHADOW_OFFSET
);
_setBlendMode(ctx, GP0_BLEND_SEMITRANS, true);
// Window
ctx.gpuCtx.drawGradientRectD(
0, 0, _width, windowHeight, COLOR_WINDOW1, COLOR_WINDOW2,
COLOR_WINDOW3
);
ctx.gpuCtx.drawGradientRectH(
0, 0, _titleBarAnim.getValue(ctx.time), TITLE_BAR_HEIGHT,
COLOR_ACCENT1, COLOR_ACCENT2
);
ctx.gpuCtx.drawRect(
_width, SHADOW_OFFSET, SHADOW_OFFSET, windowHeight, COLOR_SHADOW,
true
);
ctx.gpuCtx.drawRect(
SHADOW_OFFSET, windowHeight, _width - SHADOW_OFFSET, SHADOW_OFFSET,
COLOR_SHADOW, true
);
// Text
gpu::Rect rect;
rect.x1 = TITLE_BAR_PADDING;
rect.y1 = TITLE_BAR_PADDING;
rect.x2 = _width - TITLE_BAR_PADDING;
rect.y2 = TITLE_BAR_HEIGHT - TITLE_BAR_PADDING;
ctx.font.draw(ctx.gpuCtx, _title, rect, COLOR_TITLE);
rect.y1 = TITLE_BAR_HEIGHT + MODAL_PADDING;
rect.y2 = _height - MODAL_PADDING;
ctx.font.draw(ctx.gpuCtx, _body, rect, COLOR_TEXT1, true);
}
}
}

247
src/uibase.hpp Normal file
View File

@ -0,0 +1,247 @@
#pragma once
#include <stdint.h>
#include "gpu.hpp"
#include "spu.hpp"
#include "util.hpp"
namespace ui {
/* Public constants */
enum Color : gpu::Color {
COLOR_DEFAULT = 0x808080,
COLOR_SHADOW = 0x000000,
COLOR_BACKDROP = 0xb0b0b0,
COLOR_ACCENT1 = 0x50d0f0,
COLOR_ACCENT2 = 0x3088a0,
COLOR_WINDOW1 = 0x505050,
COLOR_WINDOW2 = 0x242424,
COLOR_WINDOW3 = 0x080808,
COLOR_HIGHLIGHT1 = 0x40b0c8,
COLOR_HIGHLIGHT2 = 0x3088a0,
COLOR_PROGRESS1 = 0x10c048,
COLOR_PROGRESS2 = 0x007820,
COLOR_BOX1 = 0x000000,
COLOR_BOX2 = 0x282828,
COLOR_TEXT1 = 0x707070,
COLOR_TEXT2 = 0x383838,
COLOR_TITLE = 0x808080,
COLOR_SUBTITLE = 0x4078a0
};
static constexpr int NUM_UI_SOUNDS = 5;
enum Sound {
SOUND_STARTUP = 0,
SOUND_MOVE = 1,
SOUND_ENTER = 2,
SOUND_EXIT = 3,
SOUND_CLICK = 4
};
enum AnimationSpeed {
SPEED_FASTEST = 10,
SPEED_FAST = 15,
SPEED_SLOW = 20
};
static constexpr int SCREEN_MARGIN_X = 16;
static constexpr int SCREEN_MARGIN_Y = 20;
static constexpr int SCREEN_BLOCK_MARGIN = 6;
static constexpr int SCREEN_PROMPT_HEIGHT = 30;
static constexpr int LIST_BOX_PADDING = 4;
static constexpr int LIST_ITEM_PADDING = 2;
static constexpr int MODAL_WIDTH = 256;
static constexpr int MODAL_HEIGHT_FULL = 120;
static constexpr int MODAL_HEIGHT_REDUCED = 50;
static constexpr int MODAL_PADDING = 5;
static constexpr int TITLE_BAR_HEIGHT = 18;
static constexpr int TITLE_BAR_PADDING = 5;
static constexpr int BUTTON_HEIGHT = 18;
static constexpr int BUTTON_SPACING = 3;
static constexpr int BUTTON_PADDING = 5;
static constexpr int PROGRESS_BAR_HEIGHT = 8;
static constexpr int SHADOW_OFFSET = 4;
/* Button state manager */
static constexpr int NUM_BUTTONS = 4;
static constexpr int NUM_BUTTON_MAPS = 6;
static constexpr int REPEAT_DELAY = 30;
enum Button {
BTN_LEFT = 0,
BTN_RIGHT = 1,
BTN_START = 2,
BTN_DEBUG = 3
};
enum ButtonMap {
MAP_JOYSTICK = 0,
MAP_DDR_CAB = 1,
MAP_DDR_SOLO_CAB = 2,
MAP_DM_CAB = 3,
MAP_DMX_CAB = 4,
MAP_SINGLE_BUTTON = 5 // Used when selecting button mapping
};
class ButtonState {
private:
uint32_t _mappings[NUM_BUTTONS];
uint8_t _held, _prevHeld;
uint8_t _pressed, _released, _repeating;
int _repeatTimer;
public:
ButtonMap buttonMap;
inline bool pressed(Button button) const {
return _pressed & (1 << button);
}
inline bool pressedRepeating(Button button) const {
return (_pressed | _repeating) & (1 << button);
}
inline bool released(Button button) const {
return _released & (1 << button);
}
inline bool repeating(Button button) const {
return _repeating & (1 << button);
}
inline bool held(Button button) const {
return _held & (1 << button);
}
ButtonState(void);
void update(void);
};
/* UI context */
class Layer;
class Screen;
class Context {
private:
Screen *_screens[2];
Layer *_background, *_overlay;
int _currentScreen;
public:
gpu::Context &gpuCtx;
gpu::Font font;
spu::Sound sounds[NUM_UI_SOUNDS];
ButtonState buttons;
int time;
void *screenData; // Opaque, can be accessed by screens
inline void tick(void) {
time++;
}
inline void setBackgroundLayer(Layer &layer) {
_background = &layer;
}
inline void setOverlayLayer(Layer &layer) {
_overlay = &layer;
}
Context(gpu::Context &gpuCtx, void *screenData = nullptr);
void show(Screen &screen, bool goBack = false, bool playSound = false);
void draw(void);
void update(void);
};
/* Layer classes */
class Layer {
protected:
void _newLayer(Context &ctx, int x, int y, int width, int height) const;
void _setTexturePage(Context &ctx, uint16_t texpage, bool dither = false) const;
void _setBlendMode(Context &ctx, gpu::BlendMode blendMode, bool dither = false) const;
public:
virtual void draw(Context &ctx) const {}
virtual void update(Context &ctx) {}
};
class TiledBackground : public Layer {
public:
gpu::Image tile;
const char *text;
void draw(Context &ctx) const;
};
class LogOverlay : public Layer {
private:
util::Logger &_logger;
util::Tween<int, util::QuadOutEasing> _slideAnim;
public:
LogOverlay(util::Logger &logger);
void draw(Context &ctx) const;
void update(Context &ctx);
};
/* Base screen classes */
// This is probably the most stripped-down way to implement something that
// vaguely resembles MVC. The class is the model, draw() is the view, update()
// is the controller.
class Screen : public Layer {
public:
virtual void show(Context &ctx, bool goBack = false) {}
virtual void hide(Context &ctx, bool goBack = false) {}
virtual void draw(Context &ctx, bool active = true) const {}
virtual void update(Context &ctx) {}
};
class AnimatedScreen : public Screen {
private:
util::Tween<int, util::QuadOutEasing> _slideAnim;
protected:
void _newLayer(Context &ctx, int x, int y, int width, int height) const;
public:
virtual void show(Context &ctx, bool goBack = false);
virtual void hide(Context &ctx, bool goBack = false);
};
class BackdropScreen : public Screen {
private:
util::Tween<int, util::LinearEasing> _backdropAnim;
public:
virtual void show(Context &ctx, bool goBack = false);
virtual void hide(Context &ctx, bool goBack = false);
virtual void draw(Context &ctx, bool active = true) const;
};
class ModalScreen : public BackdropScreen {
private:
util::Tween<int, util::QuadOutEasing> _titleBarAnim;
protected:
int _width, _height;
const char *_title, *_body;
public:
ModalScreen(int width, int height);
virtual void show(Context &ctx, bool goBack = false);
virtual void draw(Context &ctx, bool active = true) const;
};
}

386
src/uicommon.cpp Normal file
View File

@ -0,0 +1,386 @@
#include "ps1/gpucmd.h"
#include "defs.hpp"
#include "gpu.hpp"
#include "uibase.hpp"
#include "uicommon.hpp"
namespace ui {
/* Common higher-level screens */
void PlaceholderScreen::draw(Context &ctx, bool active) const {
_newLayer(ctx, 0, 0, ctx.gpuCtx.width, ctx.gpuCtx.height);
ctx.gpuCtx.drawRect(
0, 0, ctx.gpuCtx.width, ctx.gpuCtx.height, COLOR_WINDOW2
);
}
MessageScreen::MessageScreen(void)
: ModalScreen(MODAL_WIDTH, MODAL_HEIGHT_FULL), _numButtons(0), _locked(false) {}
void MessageScreen::show(Context &ctx, bool goBack) {
ModalScreen::show(ctx, goBack);
_activeButton = 0;
_buttonAnim.setValue(_getButtonWidth());
}
void MessageScreen::draw(Context &ctx, bool active) const {
ModalScreen::draw(ctx, active);
if (!active || !_numButtons)
return;
int buttonX = _width / 8;
int buttonY = TITLE_BAR_HEIGHT + _height - (BUTTON_HEIGHT + MODAL_PADDING);
gpu::RectWH rect;
rect.y = buttonY + BUTTON_PADDING;
rect.w = _getButtonWidth();
rect.h = BUTTON_HEIGHT - BUTTON_PADDING * 2;
for (int i = 0; i < _numButtons; i++) {
rect.x = buttonX +
(rect.w - ctx.font.getStringWidth(_buttons[i])) / 2;
if (_locked) {
ctx.gpuCtx.drawRect(
buttonX, buttonY, rect.w, BUTTON_HEIGHT, COLOR_SHADOW, true
);
ctx.font.draw(ctx.gpuCtx, _buttons[i], rect, COLOR_TEXT2);
} else {
if (i == _activeButton) {
ctx.gpuCtx.drawRect(
buttonX, buttonY, rect.w, BUTTON_HEIGHT, COLOR_HIGHLIGHT2
);
ctx.gpuCtx.drawRect(
buttonX, buttonY, _buttonAnim.getValue(ctx.time), BUTTON_HEIGHT,
COLOR_HIGHLIGHT1
);
} else {
ctx.gpuCtx.drawRect(
buttonX, buttonY, rect.w, BUTTON_HEIGHT, COLOR_WINDOW3
);
}
ctx.font.draw(ctx.gpuCtx, _buttons[i], rect, COLOR_TITLE);
}
buttonX += rect.w + BUTTON_SPACING;
}
}
void MessageScreen::update(Context &ctx) {
if (_locked)
return;
if (ctx.buttons.pressed(ui::BTN_LEFT)) {
if (_activeButton > 0) {
_activeButton--;
_buttonAnim.setValue(ctx.time, 0, _getButtonWidth(), SPEED_FASTEST);
ctx.sounds[SOUND_MOVE].play();
} else {
ctx.sounds[SOUND_CLICK].play();
}
}
if (ctx.buttons.pressed(ui::BTN_RIGHT)) {
if (_activeButton < (_numButtons - 1)) {
_activeButton++;
_buttonAnim.setValue(ctx.time, 0, _getButtonWidth(), SPEED_FASTEST);
ctx.sounds[SOUND_MOVE].play();
} else {
ctx.sounds[SOUND_CLICK].play();
}
}
}
ProgressScreen::ProgressScreen(void)
: ModalScreen(MODAL_WIDTH, MODAL_HEIGHT_REDUCED) {}
void ProgressScreen::show(Context &ctx, bool goBack) {
ModalScreen::show(ctx, goBack);
_progressBarAnim.setValue(0);
}
void ProgressScreen::draw(Context &ctx, bool active) const {
ModalScreen::draw(ctx, active);
if (!active)
return;
int fullBarWidth = _width - MODAL_PADDING * 2;
int barX = (_width - fullBarWidth) / 2;
int barY = TITLE_BAR_HEIGHT + _height -
(PROGRESS_BAR_HEIGHT + MODAL_PADDING);
_setBlendMode(ctx, GP0_BLEND_SEMITRANS, true);
ctx.gpuCtx.drawRect(
barX, barY, fullBarWidth, PROGRESS_BAR_HEIGHT, COLOR_WINDOW3
);
ctx.gpuCtx.drawGradientRectH(
barX, barY, _progressBarAnim.getValue(ctx.time), PROGRESS_BAR_HEIGHT,
COLOR_PROGRESS2, COLOR_PROGRESS1
);
}
TextScreen::TextScreen(void)
: _title(nullptr), _body(nullptr), _prompt(nullptr) {}
void TextScreen::draw(Context &ctx, bool active) const {
int screenWidth = ctx.gpuCtx.width - SCREEN_MARGIN_X * 2;
int screenHeight = ctx.gpuCtx.height - SCREEN_MARGIN_Y * 2;
_newLayer(
ctx, SCREEN_MARGIN_X, SCREEN_MARGIN_Y, screenWidth, screenHeight
);
gpu::Rect rect;
rect.x1 = 0;
rect.y1 = 0;
rect.x2 = screenWidth;
rect.y2 = gpu::FONT_LINE_HEIGHT;
ctx.font.draw(ctx.gpuCtx, _title, rect, COLOR_TITLE);
rect.y1 = gpu::FONT_LINE_HEIGHT + SCREEN_BLOCK_MARGIN;
rect.y2 = screenHeight - SCREEN_PROMPT_HEIGHT;
ctx.font.draw(ctx.gpuCtx, _body, rect, COLOR_TEXT1, true);
rect.y1 = screenHeight - SCREEN_PROMPT_HEIGHT;
rect.y2 = screenHeight;
ctx.font.draw(ctx.gpuCtx, _prompt, rect, COLOR_TEXT1, true);
}
ImageScreen::ImageScreen(void)
: _imageScale(1), _imagePadding(0), _title(nullptr), _prompt(nullptr) {}
void ImageScreen::draw(Context &ctx, bool active) const {
_newLayer(ctx, 0, 0, ctx.gpuCtx.width, ctx.gpuCtx.height);
if (_image.width && _image.height) {
int x = ctx.gpuCtx.width / 2;
int y = ctx.gpuCtx.height / 2;
int width = _image.width * _imageScale / 2;
int height = _image.height * _imageScale / 2;
if (_prompt)
y -= (SCREEN_PROMPT_HEIGHT - gpu::FONT_LINE_HEIGHT) / 2;
// Backdrop
if (_imagePadding) {
width += _imagePadding;
height += _imagePadding;
ctx.gpuCtx.drawRect(
x - width, y - height, width * 2, height * 2, _backdropColor
);
}
// Image
width += 1;
height += 1;
_image.drawScaled(
ctx.gpuCtx, x - width, y - height, width * 2, height * 2
);
}
// Text
gpu::Rect rect;
rect.x1 = SCREEN_MARGIN_X;
rect.y1 = SCREEN_MARGIN_Y;
rect.x2 = ctx.gpuCtx.width - SCREEN_MARGIN_X;
rect.y2 = SCREEN_MARGIN_Y + gpu::FONT_LINE_HEIGHT;
ctx.font.draw(ctx.gpuCtx, _title, rect, COLOR_TITLE);
rect.y1 = ctx.gpuCtx.height - (SCREEN_MARGIN_Y + SCREEN_PROMPT_HEIGHT);
rect.y2 = ctx.gpuCtx.height - SCREEN_MARGIN_Y;
ctx.font.draw(ctx.gpuCtx, _prompt, rect, COLOR_TEXT1, true);
}
ListScreen::ListScreen(void)
: _listLength(0), _prompt(nullptr) {}
void ListScreen::_drawItems(Context &ctx) const {
int itemY = _scrollAnim.getValue(ctx.time);
int itemWidth = _getItemWidth(ctx);
int listHeight = _getListHeight(ctx);
gpu::Rect rect;
rect.x1 = LIST_BOX_PADDING + LIST_ITEM_PADDING;
rect.x2 = itemWidth - LIST_ITEM_PADDING;
rect.y2 = listHeight;
for (int i = 0; (i < _listLength) && (itemY < listHeight); i++) {
int itemHeight = gpu::FONT_LINE_HEIGHT + LIST_ITEM_PADDING * 2;
if (i == _activeItem)
itemHeight += gpu::FONT_LINE_HEIGHT;
if ((itemY + itemHeight) >= 0) {
if (i == _activeItem) {
ctx.gpuCtx.drawRect(
LIST_BOX_PADDING, itemY, itemWidth, itemHeight,
COLOR_HIGHLIGHT2
);
ctx.gpuCtx.drawRect(
LIST_BOX_PADDING, itemY, _itemAnim.getValue(ctx.time),
itemHeight, COLOR_HIGHLIGHT1
);
rect.y1 = itemY + LIST_ITEM_PADDING + gpu::FONT_LINE_HEIGHT;
ctx.font.draw(ctx.gpuCtx, _itemPrompt, rect, COLOR_SUBTITLE);
}
rect.y1 = itemY + LIST_ITEM_PADDING;
ctx.font.draw(ctx.gpuCtx, _getItemName(ctx, i), rect, COLOR_TITLE);
}
itemY += itemHeight;
}
}
void ListScreen::show(Context &ctx, bool goBack) {
AnimatedScreen::show(ctx, goBack);
_activeItem = 0;
_scrollAnim.setValue(LIST_BOX_PADDING);
_itemAnim.setValue(_getItemWidth(ctx));
}
void ListScreen::draw(Context &ctx, bool active) const {
int screenWidth = ctx.gpuCtx.width - SCREEN_MARGIN_X * 2;
int screenHeight = ctx.gpuCtx.height - SCREEN_MARGIN_Y * 2;
int listHeight = _getListHeight(ctx);
_newLayer(
ctx, SCREEN_MARGIN_X, SCREEN_MARGIN_Y, screenWidth, screenHeight
);
// Text
gpu::Rect rect;
rect.x1 = 0;
rect.y1 = 0;
rect.x2 = screenWidth;
rect.y2 = gpu::FONT_LINE_HEIGHT;
ctx.font.draw(ctx.gpuCtx, _title, rect, COLOR_TITLE);
rect.y1 = screenHeight - SCREEN_PROMPT_HEIGHT;
rect.y2 = screenHeight;
ctx.font.draw(ctx.gpuCtx, _prompt, rect, COLOR_TEXT1, true);
_newLayer(
ctx, SCREEN_MARGIN_X,
SCREEN_MARGIN_Y + gpu::FONT_LINE_HEIGHT + SCREEN_BLOCK_MARGIN,
screenWidth, listHeight
);
_setBlendMode(ctx, GP0_BLEND_SEMITRANS, true);
// List box
ctx.gpuCtx.drawRect(0, 0, screenWidth / 2, listHeight, COLOR_BOX1);
ctx.gpuCtx.drawGradientRectH(
screenWidth / 2, 0, screenWidth / 2, listHeight, COLOR_BOX1, COLOR_BOX2
);
if (_listLength) {
_drawItems(ctx);
// Up/down arrow icons
gpu::RectWH iconRect;
iconRect.x = screenWidth - (gpu::FONT_LINE_HEIGHT + LIST_BOX_PADDING);
iconRect.w = gpu::FONT_LINE_HEIGHT;
iconRect.h = gpu::FONT_LINE_HEIGHT;
if (_activeItem) {
iconRect.y = LIST_BOX_PADDING;
ctx.font.draw(ctx.gpuCtx, CH_UP_ARROW, iconRect, COLOR_TEXT1);
}
if (_activeItem < (_listLength - 1)) {
iconRect.y = listHeight - (gpu::FONT_LINE_HEIGHT + LIST_BOX_PADDING);
ctx.font.draw(ctx.gpuCtx, CH_DOWN_ARROW, iconRect, COLOR_TEXT1);
}
}
}
void ListScreen::update(Context &ctx) {
if (
ctx.buttons.pressed(ui::BTN_LEFT) ||
(ctx.buttons.repeating(ui::BTN_LEFT) && (_activeItem > 0))
) {
_activeItem--;
if (_activeItem < 0) {
_activeItem += _listLength;
ctx.sounds[SOUND_CLICK].play();
} else {
ctx.sounds[SOUND_MOVE].play();
}
_itemAnim.setValue(ctx.time, 0, _getItemWidth(ctx), SPEED_FAST);
}
if (
ctx.buttons.pressed(ui::BTN_RIGHT) ||
(ctx.buttons.repeating(ui::BTN_RIGHT) && (_activeItem < (_listLength - 1)))
) {
_activeItem++;
if (_activeItem >= _listLength) {
_activeItem -= _listLength;
ctx.sounds[SOUND_CLICK].play();
} else {
ctx.sounds[SOUND_MOVE].play();
}
_itemAnim.setValue(ctx.time, 0, _getItemWidth(ctx), SPEED_FAST);
}
// Scroll the list if the selected item is not fully visible.
int itemHeight = gpu::FONT_LINE_HEIGHT + LIST_ITEM_PADDING * 2;
int activeItemHeight = itemHeight + gpu::FONT_LINE_HEIGHT;
int topOffset = _activeItem * itemHeight;
int bottomOffset = topOffset + activeItemHeight - _getListHeight(ctx);
int currentOffset = -_scrollAnim.getTargetValue();
if (topOffset < currentOffset)
_scrollAnim.setValue(ctx.time, LIST_BOX_PADDING - topOffset, SPEED_FAST);
else if (bottomOffset > currentOffset)
_scrollAnim.setValue(ctx.time, -(LIST_BOX_PADDING + bottomOffset), SPEED_FAST);
}
HexEntryScreen::HexEntryScreen(void)
: _title(nullptr), _prompt(nullptr) {}
void HexEntryScreen::draw(Context &ctx, bool active) const {
int screenWidth = ctx.gpuCtx.width - SCREEN_MARGIN_X * 2;
int screenHeight = ctx.gpuCtx.height - SCREEN_MARGIN_Y * 2;
_newLayer(
ctx, SCREEN_MARGIN_X, SCREEN_MARGIN_Y, screenWidth, screenHeight
);
/*gpu::RectWH rect;
rect.x = 0;
rect.y = 0;
rect.w = screenWidth;
rect.h = gpu::FONT_LINE_HEIGHT;
ctx.font.draw(ctx.gpuCtx, _title, rect, COLOR_TITLE);
rect.y = screenHeight - SCREEN_PROMPT_HEIGHT;
rect.h = SCREEN_PROMPT_HEIGHT;
ctx.font.draw(ctx.gpuCtx, _prompt, rect, COLOR_TEXT1, true);*/
}
void HexEntryScreen::update(Context &ctx) {
}
}

120
src/uicommon.hpp Normal file
View File

@ -0,0 +1,120 @@
#pragma once
#include "uibase.hpp"
namespace ui {
/* Common higher-level screens */
class PlaceholderScreen : public AnimatedScreen {
public:
void draw(Context &ctx, bool active) const;
};
class MessageScreen : public ModalScreen {
private:
util::Tween<int, util::QuadOutEasing> _buttonAnim;
inline int _getButtonWidth(void) const {
return ((_width / 4) * 3) / _numButtons - BUTTON_SPACING;
}
protected:
int _numButtons, _activeButton;
bool _locked;
const char *_buttons[3];
public:
MessageScreen(void);
virtual void show(Context &ctx, bool goBack = false);
virtual void draw(Context &ctx, bool active = true) const;
virtual void update(Context &ctx);
};
class ProgressScreen : public ModalScreen {
private:
util::Tween<int, util::QuadOutEasing> _progressBarAnim;
protected:
inline void _setProgress(Context &ctx, int part, int total) {
int totalWidth = _width - MODAL_PADDING * 2;
int partWidth = (totalWidth * part) / total;
if (_progressBarAnim.getTargetValue() != partWidth)
_progressBarAnim.setValue(ctx.time, partWidth, SPEED_FASTEST);
}
public:
ProgressScreen(void);
virtual void show(Context &ctx, bool goBack = false);
virtual void draw(Context &ctx, bool active = true) const;
};
class TextScreen : public AnimatedScreen {
protected:
const char *_title, *_body, *_prompt;
public:
TextScreen(void);
virtual void draw(Context &ctx, bool active = true) const;
};
class ImageScreen : public AnimatedScreen {
protected:
gpu::Image _image;
int _imageScale, _imagePadding;
gpu::Color _backdropColor;
const char *_title, *_prompt;
public:
ImageScreen(void);
virtual void draw(Context &ctx, bool active = true) const;
};
class ListScreen : public AnimatedScreen {
private:
util::Tween<int, util::QuadOutEasing> _scrollAnim, _itemAnim;
inline int _getItemWidth(Context &ctx) const {
return ctx.gpuCtx.width - (SCREEN_MARGIN_X + LIST_BOX_PADDING) * 2;
}
inline int _getListHeight(Context &ctx) const {
int screenHeight = ctx.gpuCtx.height - SCREEN_MARGIN_Y * 2;
return screenHeight -
(gpu::FONT_LINE_HEIGHT + SCREEN_PROMPT_HEIGHT + SCREEN_BLOCK_MARGIN * 2);
}
void _drawItems(Context &ctx) const;
protected:
int _listLength, _activeItem;
const char *_title, *_prompt, *_itemPrompt;
virtual const char *_getItemName(ui::Context &ctx, int index) const {
return nullptr;
}
public:
ListScreen(void);
virtual void show(Context &ctx, bool goBack = false);
virtual void draw(Context &ctx, bool active = true) const;
virtual void update(Context &ctx);
};
class HexEntryScreen : public AnimatedScreen {
protected:
uint8_t _buffer[16];
const char *_title, *_prompt;
public:
HexEntryScreen(void);
virtual void draw(Context &ctx, bool active = true) const;
virtual void update(Context &ctx);
};
}

159
src/util.cpp Normal file
View File

@ -0,0 +1,159 @@
#include <stdarg.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "ps1/registers.h"
#include "ps1/system.h"
#include "vendor/qrcodegen.h"
#include "util.hpp"
namespace util {
/* String hashing */
Hash hash(const char *str, char terminator) {
auto _str = reinterpret_cast<const uint8_t *>(str);
Hash value = 0;
while (*_str && (*_str != terminator))
value = Hash(*(_str++)) + (value << 6) + (value << 16) - value;
return value;
}
Hash hash(const uint8_t *data, size_t length) {
Hash value = 0;
for (; length; length--)
value = Hash(*(data++)) + (value << 6) + (value << 16) - value;
return value;
}
/* Logger */
// Global state, I know, but it's a necessary evil.
Logger logger;
Logger::Logger(void)
: _tail(0), enableSyslog(false) {
clear();
}
void Logger::clear(void) {
for (int i = 0; i < MAX_LOG_LINES; i++)
_lines[i][0] = 0;
}
void Logger::log(const char *format, ...) {
auto mask = setInterruptMask(0);
size_t tail = _tail;
va_list ap;
_tail = size_t(tail + 1) % MAX_LOG_LINES;
va_start(ap, format);
vsnprintf(_lines[tail], MAX_LOG_LINE_LENGTH, format, ap);
va_end(ap);
if (enableSyslog)
puts(_lines[tail]);
if (mask)
setInterruptMask(mask);
}
/* CRC calculation */
static constexpr uint16_t _CRC8_POLY = 0x8c;
static constexpr uint16_t _CRC16_POLY = 0x1021;
uint8_t dsCRC8(const uint8_t *data, size_t length) {
uint8_t crc = 0;
for (; length; length--) {
uint8_t value = *(data++);
for (int bit = 8; bit; bit--) {
uint8_t temp = crc ^ value;
value >>= 1;
crc >>= 1;
if (temp & 1)
crc ^= _CRC8_POLY;
}
}
return crc & 0xff;
}
uint16_t zsCRC16(const uint8_t *data, size_t length) {
uint16_t crc = 0xffff;
for (; length; length--) {
crc ^= *(data++) << 8;
for (int bit = 8; bit; bit--) {
uint16_t temp = crc;
crc <<= 1;
if (temp & 0x8000)
crc ^= _CRC16_POLY;
}
}
return (crc ^ 0xffff) & 0xffff;
}
/* String manipulation */
static const char HEX_CHARSET[] = "0123456789ABCDEF";
size_t hexToString(char *output, const uint8_t *input, size_t length, char sep) {
size_t outLength = 0;
for (; length; length--) {
uint8_t value = *(input++);
*(output++) = HEX_CHARSET[value >> 4];
*(output++) = HEX_CHARSET[value & 0xf];
if (sep && (length > 1)) {
*(output++) = sep;
outLength += 3;
} else {
outLength += 2;
}
}
*output = 0;
return outLength;
}
size_t serialNumberToString(char *output, const uint8_t *input) {
uint32_t value = input[0] | (input[1] << 8) | (input[2] << 16) | (input[3] << 24);
return sprintf(output, "%04d-%04d", (value / 10000) % 10000, value % 10000);
}
// https://datatracker.ietf.org/doc/rfc9285
size_t encodeBase45(char *output, const uint8_t *input, size_t length) {
size_t outLength = 0;
for (int i = length + 1; i > 0; i -= 2) {
int value = *(input++) << 8;
value |= *(input++);
*(output++) = qrcodegen_ALPHANUMERIC_CHARSET[value % 45];
*(output++) = qrcodegen_ALPHANUMERIC_CHARSET[(value / 45) % 45];
*(output++) = qrcodegen_ALPHANUMERIC_CHARSET[value / 2025];
outLength += 3;
}
*output = 0;
return outLength;
}
}

229
src/util.hpp Normal file
View File

@ -0,0 +1,229 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
#include "ps1/system.h"
namespace util {
/* Misc. template utilities */
template<typename T> static inline T min(T a, T b) {
return (a < b) ? a : b;
}
template<typename T> static inline T max(T a, T b) {
return (a > b) ? a : b;
}
template<typename T> static inline T clamp(T value, T minValue, T maxValue) {
return (value < minValue) ? minValue :
((value > maxValue) ? maxValue : value);
}
// These shall only be used with unsigned types.
template<typename T> static inline T truncateToMultiple(T value, T length) {
return value - (value % length);
}
template<typename T> static inline T roundUpToMultiple(T value, T length) {
T diff = value % length;
return diff ? (value - diff + length) : value;
}
static inline uint16_t swapEndian(uint16_t value) {
value = ((value & 0x00ff) << 8) | ((value & 0xff00) >> 8);
return value;
}
static inline uint32_t swapEndian(uint32_t value) {
value = ((value & 0x0000ffff) << 16) | ((value & 0xffff0000) >> 16);
value = ((value & 0x00ff00ff) << 8) | ((value & 0xff00ff00) >> 8);
return value;
}
template<typename T, typename X> static constexpr inline T forcedCast(X item) {
return reinterpret_cast<T>(reinterpret_cast<void *>(item));
}
/* String hashing (http://www.cse.yorku.ca/~oz/hash.html) */
using Hash = uint32_t;
template<typename T> static constexpr inline Hash hash(
const T *const data, size_t length = -1, Hash value = 0
) {
if (*data && length)
return hash(
&data[1], length - 1,
Hash(*data) + (value << 6) + (value << 16) - value
);
return value;
}
Hash hash(const char *str, char terminator = 0);
Hash hash(const uint8_t *data, size_t length);
/* Simple ring buffer */
template<typename T, size_t N> class RingBuffer {
private:
T _items[N];
size_t _head, _tail;
public:
size_t length;
inline RingBuffer(void)
: _head(0), _tail(0), length(0) {}
inline T *pushItem(void) volatile {
if (length >= N)
return nullptr;
size_t i = _tail;
_tail = (i + 1) % N;
length++;
return &_items[i];
}
inline T *popItem(void) volatile {
if (!length)
return nullptr;
size_t i = _head;
_head = (i + 1) % N;
length--;
return &_items[i];
}
inline T *peekItem(void) const {
if (!length)
return nullptr;
return &_items[_head];
}
};
/* Tween/animation classes */
static constexpr int TWEEN_UNIT = 1 << 12;
class LinearEasing {
public:
template<typename T> static inline T apply(T value) {
return value;
}
};
class QuadInEasing {
public:
template<typename T> static inline T apply(T value) {
return (value * value) / TWEEN_UNIT;
}
};
class QuadOutEasing {
public:
template<typename T> static inline T apply(T value) {
return (value * 2) - ((value * value) / TWEEN_UNIT);
}
};
template<typename T, typename E> class Tween {
private:
T _base, _delta;
int _endTime, _timeScale;
public:
inline Tween(void) {
setValue(static_cast<T>(0));
}
inline Tween(T start) {
setValue(start);
}
inline T getValue(int time) const {
int remaining = time - _endTime;
if (remaining >= 0)
return _base + _delta;
return _base + (
_delta * E::apply(remaining * _timeScale + TWEEN_UNIT)
) / TWEEN_UNIT;
}
inline T getTargetValue(void) const {
return _base + _delta;
}
inline bool isDone(int time) const {
return time >= _endTime;
}
inline void setValue(int time, T start, T target, int duration) {
//assert(duration <= 0x800);
_base = start;
_delta = target - start;
_endTime = time + duration;
_timeScale = TWEEN_UNIT / duration;
}
inline void setValue(int time, T target, int duration) {
setValue(time, getValue(time), target, duration);
}
inline void setValue(T target) {
_base = target;
_delta = static_cast<T>(0);
_endTime = 0;
}
};
/* Logger (basically a ring buffer of lines) */
static constexpr int MAX_LOG_LINE_LENGTH = 128;
static constexpr int MAX_LOG_LINES = 32;
class Logger {
private:
char _lines[MAX_LOG_LINES][MAX_LOG_LINE_LENGTH];
int _tail;
public:
bool enableSyslog;
// 0 = last line, 1 = second to last, etc.
inline const char *getLine(int line) const {
return _lines[size_t(_tail - (line + 1)) % MAX_LOG_LINES];
}
Logger(void);
void clear(void);
void log(const char *format, ...);
};
extern Logger logger;
/* Other APIs */
uint8_t dsCRC8(const uint8_t *data, size_t length);
uint16_t zsCRC16(const uint8_t *data, size_t length);
size_t hexToString(char *output, const uint8_t *input, size_t length, char sep = 0);
size_t serialNumberToString(char *output, const uint8_t *input);
size_t encodeBase45(char *output, const uint8_t *input, size_t length);
}
//#define LOG(...) util::logger.log(__VA_ARGS__)
#define LOG(fmt, ...) \
util::logger.log("%s(%d): " fmt, __func__, __LINE__ __VA_OPT__(,) __VA_ARGS__)
static constexpr inline util::Hash operator""_h(
const char *const literal, size_t length
) {
return util::hash(literal, length);
}

7833
src/vendor/miniz.c vendored Normal file

File diff suppressed because it is too large Load Diff

1422
src/vendor/miniz.h vendored Normal file

File diff suppressed because it is too large Load Diff

914
src/vendor/printf.c vendored Normal file
View File

@ -0,0 +1,914 @@
///////////////////////////////////////////////////////////////////////////////
// \author (c) Marco Paland (info@paland.com)
// 2014-2019, PALANDesign Hannover, Germany
//
// \license The MIT License (MIT)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// \brief Tiny printf, sprintf and (v)snprintf implementation, optimized for speed on
// embedded systems with a very limited resources. These routines are thread
// safe and reentrant!
// Use this instead of the bloated standard/newlib printf cause these use
// malloc for printf (and may not be thread safe).
//
///////////////////////////////////////////////////////////////////////////////
#include <stdbool.h>
#include <stdint.h>
#include "printf.h"
// define this globally (e.g. gcc -DPRINTF_INCLUDE_CONFIG_H ...) to include the
// printf_config.h header file
// default: undefined
#ifdef PRINTF_INCLUDE_CONFIG_H
#include "printf_config.h"
#endif
// 'ntoa' conversion buffer size, this must be big enough to hold one converted
// numeric number including padded zeros (dynamically created on stack)
// default: 32 byte
#ifndef PRINTF_NTOA_BUFFER_SIZE
#define PRINTF_NTOA_BUFFER_SIZE 32U
#endif
// 'ftoa' conversion buffer size, this must be big enough to hold one converted
// float number including padded zeros (dynamically created on stack)
// default: 32 byte
#ifndef PRINTF_FTOA_BUFFER_SIZE
#define PRINTF_FTOA_BUFFER_SIZE 32U
#endif
// support for the floating point type (%f)
// default: activated
#ifndef PRINTF_DISABLE_SUPPORT_FLOAT
#define PRINTF_SUPPORT_FLOAT
#endif
// support for exponential floating point notation (%e/%g)
// default: activated
#ifndef PRINTF_DISABLE_SUPPORT_EXPONENTIAL
#define PRINTF_SUPPORT_EXPONENTIAL
#endif
// define the default floating point precision
// default: 6 digits
#ifndef PRINTF_DEFAULT_FLOAT_PRECISION
#define PRINTF_DEFAULT_FLOAT_PRECISION 6U
#endif
// define the largest float suitable to print with %f
// default: 1e9
#ifndef PRINTF_MAX_FLOAT
#define PRINTF_MAX_FLOAT 1e9
#endif
// support for the long long types (%llu or %p)
// default: activated
#ifndef PRINTF_DISABLE_SUPPORT_LONG_LONG
#define PRINTF_SUPPORT_LONG_LONG
#endif
// support for the ptrdiff_t type (%t)
// ptrdiff_t is normally defined in <stddef.h> as long or long long type
// default: activated
#ifndef PRINTF_DISABLE_SUPPORT_PTRDIFF_T
#define PRINTF_SUPPORT_PTRDIFF_T
#endif
///////////////////////////////////////////////////////////////////////////////
// internal flag definitions
#define FLAGS_ZEROPAD (1U << 0U)
#define FLAGS_LEFT (1U << 1U)
#define FLAGS_PLUS (1U << 2U)
#define FLAGS_SPACE (1U << 3U)
#define FLAGS_HASH (1U << 4U)
#define FLAGS_UPPERCASE (1U << 5U)
#define FLAGS_CHAR (1U << 6U)
#define FLAGS_SHORT (1U << 7U)
#define FLAGS_LONG (1U << 8U)
#define FLAGS_LONG_LONG (1U << 9U)
#define FLAGS_PRECISION (1U << 10U)
#define FLAGS_ADAPT_EXP (1U << 11U)
// import float.h for DBL_MAX
#if defined(PRINTF_SUPPORT_FLOAT)
#include <float.h>
#endif
// output function type
typedef void (*out_fct_type)(char character, void* buffer, size_t idx, size_t maxlen);
// wrapper (used as buffer) for output function type
typedef struct {
void (*fct)(char character, void* arg);
void* arg;
} out_fct_wrap_type;
// internal buffer output
static inline void _out_buffer(char character, void* buffer, size_t idx, size_t maxlen)
{
if (idx < maxlen) {
((char*)buffer)[idx] = character;
}
}
// internal null output
static inline void _out_null(char character, void* buffer, size_t idx, size_t maxlen)
{
(void)character; (void)buffer; (void)idx; (void)maxlen;
}
// internal _putchar wrapper
static inline void _out_char(char character, void* buffer, size_t idx, size_t maxlen)
{
(void)buffer; (void)idx; (void)maxlen;
if (character) {
_putchar(character);
}
}
// internal output function wrapper
static inline void _out_fct(char character, void* buffer, size_t idx, size_t maxlen)
{
(void)idx; (void)maxlen;
if (character) {
// buffer is the output fct pointer
((out_fct_wrap_type*)buffer)->fct(character, ((out_fct_wrap_type*)buffer)->arg);
}
}
// internal secure strlen
// \return The length of the string (excluding the terminating 0) limited by 'maxsize'
static inline unsigned int _strnlen_s(const char* str, size_t maxsize)
{
const char* s;
for (s = str; *s && maxsize--; ++s);
return (unsigned int)(s - str);
}
// internal test if char is a digit (0-9)
// \return true if char is a digit
static inline bool _is_digit(char ch)
{
return (ch >= '0') && (ch <= '9');
}
// internal ASCII string to unsigned int conversion
static unsigned int _atoi(const char** str)
{
unsigned int i = 0U;
while (_is_digit(**str)) {
i = i * 10U + (unsigned int)(*((*str)++) - '0');
}
return i;
}
// output the specified string in reverse, taking care of any zero-padding
static size_t _out_rev(out_fct_type out, char* buffer, size_t idx, size_t maxlen, const char* buf, size_t len, unsigned int width, unsigned int flags)
{
const size_t start_idx = idx;
// pad spaces up to given width
if (!(flags & FLAGS_LEFT) && !(flags & FLAGS_ZEROPAD)) {
for (size_t i = len; i < width; i++) {
out(' ', buffer, idx++, maxlen);
}
}
// reverse string
while (len) {
out(buf[--len], buffer, idx++, maxlen);
}
// append pad spaces up to given width
if (flags & FLAGS_LEFT) {
while (idx - start_idx < width) {
out(' ', buffer, idx++, maxlen);
}
}
return idx;
}
// internal itoa format
static size_t _ntoa_format(out_fct_type out, char* buffer, size_t idx, size_t maxlen, char* buf, size_t len, bool negative, unsigned int base, unsigned int prec, unsigned int width, unsigned int flags)
{
// pad leading zeros
if (!(flags & FLAGS_LEFT)) {
if (width && (flags & FLAGS_ZEROPAD) && (negative || (flags & (FLAGS_PLUS | FLAGS_SPACE)))) {
width--;
}
while ((len < prec) && (len < PRINTF_NTOA_BUFFER_SIZE)) {
buf[len++] = '0';
}
while ((flags & FLAGS_ZEROPAD) && (len < width) && (len < PRINTF_NTOA_BUFFER_SIZE)) {
buf[len++] = '0';
}
}
// handle hash
if (flags & FLAGS_HASH) {
if (!(flags & FLAGS_PRECISION) && len && ((len == prec) || (len == width))) {
len--;
if (len && (base == 16U)) {
len--;
}
}
if ((base == 16U) && !(flags & FLAGS_UPPERCASE) && (len < PRINTF_NTOA_BUFFER_SIZE)) {
buf[len++] = 'x';
}
else if ((base == 16U) && (flags & FLAGS_UPPERCASE) && (len < PRINTF_NTOA_BUFFER_SIZE)) {
buf[len++] = 'X';
}
else if ((base == 2U) && (len < PRINTF_NTOA_BUFFER_SIZE)) {
buf[len++] = 'b';
}
if (len < PRINTF_NTOA_BUFFER_SIZE) {
buf[len++] = '0';
}
}
if (len < PRINTF_NTOA_BUFFER_SIZE) {
if (negative) {
buf[len++] = '-';
}
else if (flags & FLAGS_PLUS) {
buf[len++] = '+'; // ignore the space if the '+' exists
}
else if (flags & FLAGS_SPACE) {
buf[len++] = ' ';
}
}
return _out_rev(out, buffer, idx, maxlen, buf, len, width, flags);
}
// internal itoa for 'long' type
static size_t _ntoa_long(out_fct_type out, char* buffer, size_t idx, size_t maxlen, unsigned long value, bool negative, unsigned long base, unsigned int prec, unsigned int width, unsigned int flags)
{
char buf[PRINTF_NTOA_BUFFER_SIZE];
size_t len = 0U;
// no hash for 0 values
if (!value) {
flags &= ~FLAGS_HASH;
}
// write if precision != 0 and value is != 0
if (!(flags & FLAGS_PRECISION) || value) {
do {
const char digit = (char)(value % base);
buf[len++] = digit < 10 ? '0' + digit : (flags & FLAGS_UPPERCASE ? 'A' : 'a') + digit - 10;
value /= base;
} while (value && (len < PRINTF_NTOA_BUFFER_SIZE));
}
return _ntoa_format(out, buffer, idx, maxlen, buf, len, negative, (unsigned int)base, prec, width, flags);
}
// internal itoa for 'long long' type
#if defined(PRINTF_SUPPORT_LONG_LONG)
static size_t _ntoa_long_long(out_fct_type out, char* buffer, size_t idx, size_t maxlen, unsigned long long value, bool negative, unsigned long long base, unsigned int prec, unsigned int width, unsigned int flags)
{
char buf[PRINTF_NTOA_BUFFER_SIZE];
size_t len = 0U;
// no hash for 0 values
if (!value) {
flags &= ~FLAGS_HASH;
}
// write if precision != 0 and value is != 0
if (!(flags & FLAGS_PRECISION) || value) {
do {
const char digit = (char)(value % base);
buf[len++] = digit < 10 ? '0' + digit : (flags & FLAGS_UPPERCASE ? 'A' : 'a') + digit - 10;
value /= base;
} while (value && (len < PRINTF_NTOA_BUFFER_SIZE));
}
return _ntoa_format(out, buffer, idx, maxlen, buf, len, negative, (unsigned int)base, prec, width, flags);
}
#endif // PRINTF_SUPPORT_LONG_LONG
#if defined(PRINTF_SUPPORT_FLOAT)
#if defined(PRINTF_SUPPORT_EXPONENTIAL)
// forward declaration so that _ftoa can switch to exp notation for values > PRINTF_MAX_FLOAT
static size_t _etoa(out_fct_type out, char* buffer, size_t idx, size_t maxlen, double value, unsigned int prec, unsigned int width, unsigned int flags);
#endif
// internal ftoa for fixed decimal floating point
static size_t _ftoa(out_fct_type out, char* buffer, size_t idx, size_t maxlen, double value, unsigned int prec, unsigned int width, unsigned int flags)
{
char buf[PRINTF_FTOA_BUFFER_SIZE];
size_t len = 0U;
double diff = 0.0;
// powers of 10
static const double pow10[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 };
// test for special values
if (value != value)
return _out_rev(out, buffer, idx, maxlen, "nan", 3, width, flags);
if (value < -DBL_MAX)
return _out_rev(out, buffer, idx, maxlen, "fni-", 4, width, flags);
if (value > DBL_MAX)
return _out_rev(out, buffer, idx, maxlen, (flags & FLAGS_PLUS) ? "fni+" : "fni", (flags & FLAGS_PLUS) ? 4U : 3U, width, flags);
// test for very large values
// standard printf behavior is to print EVERY whole number digit -- which could be 100s of characters overflowing your buffers == bad
if ((value > PRINTF_MAX_FLOAT) || (value < -PRINTF_MAX_FLOAT)) {
#if defined(PRINTF_SUPPORT_EXPONENTIAL)
return _etoa(out, buffer, idx, maxlen, value, prec, width, flags);
#else
return 0U;
#endif
}
// test for negative
bool negative = false;
if (value < 0) {
negative = true;
value = 0 - value;
}
// set default precision, if not set explicitly
if (!(flags & FLAGS_PRECISION)) {
prec = PRINTF_DEFAULT_FLOAT_PRECISION;
}
// limit precision to 9, cause a prec >= 10 can lead to overflow errors
while ((len < PRINTF_FTOA_BUFFER_SIZE) && (prec > 9U)) {
buf[len++] = '0';
prec--;
}
int whole = (int)value;
double tmp = (value - whole) * pow10[prec];
unsigned long frac = (unsigned long)tmp;
diff = tmp - frac;
if (diff > 0.5) {
++frac;
// handle rollover, e.g. case 0.99 with prec 1 is 1.0
if (frac >= pow10[prec]) {
frac = 0;
++whole;
}
}
else if (diff < 0.5) {
}
else if ((frac == 0U) || (frac & 1U)) {
// if halfway, round up if odd OR if last digit is 0
++frac;
}
if (prec == 0U) {
diff = value - (double)whole;
if ((!(diff < 0.5) || (diff > 0.5)) && (whole & 1)) {
// exactly 0.5 and ODD, then round up
// 1.5 -> 2, but 2.5 -> 2
++whole;
}
}
else {
unsigned int count = prec;
// now do fractional part, as an unsigned number
while (len < PRINTF_FTOA_BUFFER_SIZE) {
--count;
buf[len++] = (char)(48U + (frac % 10U));
if (!(frac /= 10U)) {
break;
}
}
// add extra 0s
while ((len < PRINTF_FTOA_BUFFER_SIZE) && (count-- > 0U)) {
buf[len++] = '0';
}
if (len < PRINTF_FTOA_BUFFER_SIZE) {
// add decimal
buf[len++] = '.';
}
}
// do whole part, number is reversed
while (len < PRINTF_FTOA_BUFFER_SIZE) {
buf[len++] = (char)(48 + (whole % 10));
if (!(whole /= 10)) {
break;
}
}
// pad leading zeros
if (!(flags & FLAGS_LEFT) && (flags & FLAGS_ZEROPAD)) {
if (width && (negative || (flags & (FLAGS_PLUS | FLAGS_SPACE)))) {
width--;
}
while ((len < width) && (len < PRINTF_FTOA_BUFFER_SIZE)) {
buf[len++] = '0';
}
}
if (len < PRINTF_FTOA_BUFFER_SIZE) {
if (negative) {
buf[len++] = '-';
}
else if (flags & FLAGS_PLUS) {
buf[len++] = '+'; // ignore the space if the '+' exists
}
else if (flags & FLAGS_SPACE) {
buf[len++] = ' ';
}
}
return _out_rev(out, buffer, idx, maxlen, buf, len, width, flags);
}
#if defined(PRINTF_SUPPORT_EXPONENTIAL)
// internal ftoa variant for exponential floating-point type, contributed by Martijn Jasperse <m.jasperse@gmail.com>
static size_t _etoa(out_fct_type out, char* buffer, size_t idx, size_t maxlen, double value, unsigned int prec, unsigned int width, unsigned int flags)
{
// check for NaN and special values
if ((value != value) || (value > DBL_MAX) || (value < -DBL_MAX)) {
return _ftoa(out, buffer, idx, maxlen, value, prec, width, flags);
}
// determine the sign
const bool negative = value < 0;
if (negative) {
value = -value;
}
// default precision
if (!(flags & FLAGS_PRECISION)) {
prec = PRINTF_DEFAULT_FLOAT_PRECISION;
}
// determine the decimal exponent
// based on the algorithm by David Gay (https://www.ampl.com/netlib/fp/dtoa.c)
union {
uint64_t U;
double F;
} conv;
conv.F = value;
int exp2 = (int)((conv.U >> 52U) & 0x07FFU) - 1023; // effectively log2
conv.U = (conv.U & ((1ULL << 52U) - 1U)) | (1023ULL << 52U); // drop the exponent so conv.F is now in [1,2)
// now approximate log10 from the log2 integer part and an expansion of ln around 1.5
int expval = (int)(0.1760912590558 + exp2 * 0.301029995663981 + (conv.F - 1.5) * 0.289529654602168);
// now we want to compute 10^expval but we want to be sure it won't overflow
exp2 = (int)(expval * 3.321928094887362 + 0.5);
const double z = expval * 2.302585092994046 - exp2 * 0.6931471805599453;
const double z2 = z * z;
conv.U = (uint64_t)(exp2 + 1023) << 52U;
// compute exp(z) using continued fractions, see https://en.wikipedia.org/wiki/Exponential_function#Continued_fractions_for_ex
conv.F *= 1 + 2 * z / (2 - z + (z2 / (6 + (z2 / (10 + z2 / 14)))));
// correct for rounding errors
if (value < conv.F) {
expval--;
conv.F /= 10;
}
// the exponent format is "%+03d" and largest value is "307", so set aside 4-5 characters
unsigned int minwidth = ((expval < 100) && (expval > -100)) ? 4U : 5U;
// in "%g" mode, "prec" is the number of *significant figures* not decimals
if (flags & FLAGS_ADAPT_EXP) {
// do we want to fall-back to "%f" mode?
if ((value >= 1e-4) && (value < 1e6)) {
if ((int)prec > expval) {
prec = (unsigned)((int)prec - expval - 1);
}
else {
prec = 0;
}
flags |= FLAGS_PRECISION; // make sure _ftoa respects precision
// no characters in exponent
minwidth = 0U;
expval = 0;
}
else {
// we use one sigfig for the whole part
if ((prec > 0) && (flags & FLAGS_PRECISION)) {
--prec;
}
}
}
// will everything fit?
unsigned int fwidth = width;
if (width > minwidth) {
// we didn't fall-back so subtract the characters required for the exponent
fwidth -= minwidth;
} else {
// not enough characters, so go back to default sizing
fwidth = 0U;
}
if ((flags & FLAGS_LEFT) && minwidth) {
// if we're padding on the right, DON'T pad the floating part
fwidth = 0U;
}
// rescale the float value
if (expval) {
value /= conv.F;
}
// output the floating part
const size_t start_idx = idx;
idx = _ftoa(out, buffer, idx, maxlen, negative ? -value : value, prec, fwidth, flags & ~FLAGS_ADAPT_EXP);
// output the exponent part
if (minwidth) {
// output the exponential symbol
out((flags & FLAGS_UPPERCASE) ? 'E' : 'e', buffer, idx++, maxlen);
// output the exponent value
idx = _ntoa_long(out, buffer, idx, maxlen, (expval < 0) ? -expval : expval, expval < 0, 10, 0, minwidth-1, FLAGS_ZEROPAD | FLAGS_PLUS);
// might need to right-pad spaces
if (flags & FLAGS_LEFT) {
while (idx - start_idx < width) out(' ', buffer, idx++, maxlen);
}
}
return idx;
}
#endif // PRINTF_SUPPORT_EXPONENTIAL
#endif // PRINTF_SUPPORT_FLOAT
// internal vsnprintf
static int _vsnprintf(out_fct_type out, char* buffer, const size_t maxlen, const char* format, va_list va)
{
unsigned int flags, width, precision, n;
size_t idx = 0U;
if (!buffer) {
// use null output function
out = _out_null;
}
while (*format)
{
// format specifier? %[flags][width][.precision][length]
if (*format != '%') {
// no
out(*format, buffer, idx++, maxlen);
format++;
continue;
}
else {
// yes, evaluate it
format++;
}
// evaluate flags
flags = 0U;
do {
switch (*format) {
case '0': flags |= FLAGS_ZEROPAD; format++; n = 1U; break;
case '-': flags |= FLAGS_LEFT; format++; n = 1U; break;
case '+': flags |= FLAGS_PLUS; format++; n = 1U; break;
case ' ': flags |= FLAGS_SPACE; format++; n = 1U; break;
case '#': flags |= FLAGS_HASH; format++; n = 1U; break;
default : n = 0U; break;
}
} while (n);
// evaluate width field
width = 0U;
if (_is_digit(*format)) {
width = _atoi(&format);
}
else if (*format == '*') {
const int w = va_arg(va, int);
if (w < 0) {
flags |= FLAGS_LEFT; // reverse padding
width = (unsigned int)-w;
}
else {
width = (unsigned int)w;
}
format++;
}
// evaluate precision field
precision = 0U;
if (*format == '.') {
flags |= FLAGS_PRECISION;
format++;
if (_is_digit(*format)) {
precision = _atoi(&format);
}
else if (*format == '*') {
const int prec = (int)va_arg(va, int);
precision = prec > 0 ? (unsigned int)prec : 0U;
format++;
}
}
// evaluate length field
switch (*format) {
case 'l' :
flags |= FLAGS_LONG;
format++;
if (*format == 'l') {
flags |= FLAGS_LONG_LONG;
format++;
}
break;
case 'h' :
flags |= FLAGS_SHORT;
format++;
if (*format == 'h') {
flags |= FLAGS_CHAR;
format++;
}
break;
#if defined(PRINTF_SUPPORT_PTRDIFF_T)
case 't' :
flags |= (sizeof(ptrdiff_t) == sizeof(long) ? FLAGS_LONG : FLAGS_LONG_LONG);
format++;
break;
#endif
case 'j' :
flags |= (sizeof(intmax_t) == sizeof(long) ? FLAGS_LONG : FLAGS_LONG_LONG);
format++;
break;
case 'z' :
flags |= (sizeof(size_t) == sizeof(long) ? FLAGS_LONG : FLAGS_LONG_LONG);
format++;
break;
default :
break;
}
// evaluate specifier
switch (*format) {
case 'd' :
case 'i' :
case 'u' :
case 'x' :
case 'X' :
case 'o' :
case 'b' : {
// set the base
unsigned int base;
if (*format == 'x' || *format == 'X') {
base = 16U;
}
else if (*format == 'o') {
base = 8U;
}
else if (*format == 'b') {
base = 2U;
}
else {
base = 10U;
flags &= ~FLAGS_HASH; // no hash for dec format
}
// uppercase
if (*format == 'X') {
flags |= FLAGS_UPPERCASE;
}
// no plus or space flag for u, x, X, o, b
if ((*format != 'i') && (*format != 'd')) {
flags &= ~(FLAGS_PLUS | FLAGS_SPACE);
}
// ignore '0' flag when precision is given
if (flags & FLAGS_PRECISION) {
flags &= ~FLAGS_ZEROPAD;
}
// convert the integer
if ((*format == 'i') || (*format == 'd')) {
// signed
if (flags & FLAGS_LONG_LONG) {
#if defined(PRINTF_SUPPORT_LONG_LONG)
const long long value = va_arg(va, long long);
idx = _ntoa_long_long(out, buffer, idx, maxlen, (unsigned long long)(value > 0 ? value : 0 - value), value < 0, base, precision, width, flags);
#endif
}
else if (flags & FLAGS_LONG) {
const long value = va_arg(va, long);
idx = _ntoa_long(out, buffer, idx, maxlen, (unsigned long)(value > 0 ? value : 0 - value), value < 0, base, precision, width, flags);
}
else {
const int value = (flags & FLAGS_CHAR) ? (char)va_arg(va, int) : (flags & FLAGS_SHORT) ? (short int)va_arg(va, int) : va_arg(va, int);
idx = _ntoa_long(out, buffer, idx, maxlen, (unsigned int)(value > 0 ? value : 0 - value), value < 0, base, precision, width, flags);
}
}
else {
// unsigned
if (flags & FLAGS_LONG_LONG) {
#if defined(PRINTF_SUPPORT_LONG_LONG)
idx = _ntoa_long_long(out, buffer, idx, maxlen, va_arg(va, unsigned long long), false, base, precision, width, flags);
#endif
}
else if (flags & FLAGS_LONG) {
idx = _ntoa_long(out, buffer, idx, maxlen, va_arg(va, unsigned long), false, base, precision, width, flags);
}
else {
const unsigned int value = (flags & FLAGS_CHAR) ? (unsigned char)va_arg(va, unsigned int) : (flags & FLAGS_SHORT) ? (unsigned short int)va_arg(va, unsigned int) : va_arg(va, unsigned int);
idx = _ntoa_long(out, buffer, idx, maxlen, value, false, base, precision, width, flags);
}
}
format++;
break;
}
#if defined(PRINTF_SUPPORT_FLOAT)
case 'f' :
case 'F' :
if (*format == 'F') flags |= FLAGS_UPPERCASE;
idx = _ftoa(out, buffer, idx, maxlen, va_arg(va, double), precision, width, flags);
format++;
break;
#if defined(PRINTF_SUPPORT_EXPONENTIAL)
case 'e':
case 'E':
case 'g':
case 'G':
if ((*format == 'g')||(*format == 'G')) flags |= FLAGS_ADAPT_EXP;
if ((*format == 'E')||(*format == 'G')) flags |= FLAGS_UPPERCASE;
idx = _etoa(out, buffer, idx, maxlen, va_arg(va, double), precision, width, flags);
format++;
break;
#endif // PRINTF_SUPPORT_EXPONENTIAL
#endif // PRINTF_SUPPORT_FLOAT
case 'c' : {
unsigned int l = 1U;
// pre padding
if (!(flags & FLAGS_LEFT)) {
while (l++ < width) {
out(' ', buffer, idx++, maxlen);
}
}
// char output
out((char)va_arg(va, int), buffer, idx++, maxlen);
// post padding
if (flags & FLAGS_LEFT) {
while (l++ < width) {
out(' ', buffer, idx++, maxlen);
}
}
format++;
break;
}
case 's' : {
const char* p = va_arg(va, char*);
unsigned int l = _strnlen_s(p, precision ? precision : (size_t)-1);
// pre padding
if (flags & FLAGS_PRECISION) {
l = (l < precision ? l : precision);
}
if (!(flags & FLAGS_LEFT)) {
while (l++ < width) {
out(' ', buffer, idx++, maxlen);
}
}
// string output
while ((*p != 0) && (!(flags & FLAGS_PRECISION) || precision--)) {
out(*(p++), buffer, idx++, maxlen);
}
// post padding
if (flags & FLAGS_LEFT) {
while (l++ < width) {
out(' ', buffer, idx++, maxlen);
}
}
format++;
break;
}
case 'p' : {
width = sizeof(void*) * 2U;
flags |= FLAGS_ZEROPAD | FLAGS_UPPERCASE;
#if defined(PRINTF_SUPPORT_LONG_LONG)
const bool is_ll = sizeof(uintptr_t) == sizeof(long long);
if (is_ll) {
idx = _ntoa_long_long(out, buffer, idx, maxlen, (uintptr_t)va_arg(va, void*), false, 16U, precision, width, flags);
}
else {
#endif
idx = _ntoa_long(out, buffer, idx, maxlen, (unsigned long)((uintptr_t)va_arg(va, void*)), false, 16U, precision, width, flags);
#if defined(PRINTF_SUPPORT_LONG_LONG)
}
#endif
format++;
break;
}
case '%' :
out('%', buffer, idx++, maxlen);
format++;
break;
default :
out(*format, buffer, idx++, maxlen);
format++;
break;
}
}
// termination
out((char)0, buffer, idx < maxlen ? idx : maxlen - 1U, maxlen);
// return written chars without terminating \0
return (int)idx;
}
///////////////////////////////////////////////////////////////////////////////
int printf_(const char* format, ...)
{
va_list va;
va_start(va, format);
char buffer[1];
const int ret = _vsnprintf(_out_char, buffer, (size_t)-1, format, va);
va_end(va);
return ret;
}
int sprintf_(char* buffer, const char* format, ...)
{
va_list va;
va_start(va, format);
const int ret = _vsnprintf(_out_buffer, buffer, (size_t)-1, format, va);
va_end(va);
return ret;
}
int snprintf_(char* buffer, size_t count, const char* format, ...)
{
va_list va;
va_start(va, format);
const int ret = _vsnprintf(_out_buffer, buffer, count, format, va);
va_end(va);
return ret;
}
int vprintf_(const char* format, va_list va)
{
char buffer[1];
return _vsnprintf(_out_char, buffer, (size_t)-1, format, va);
}
int vsnprintf_(char* buffer, size_t count, const char* format, va_list va)
{
return _vsnprintf(_out_buffer, buffer, count, format, va);
}
int fctprintf(void (*out)(char character, void* arg), void* arg, const char* format, ...)
{
va_list va;
va_start(va, format);
const out_fct_wrap_type out_fct_wrap = { out, arg };
const int ret = _vsnprintf(_out_fct, (char*)(uintptr_t)&out_fct_wrap, (size_t)-1, format, va);
va_end(va);
return ret;
}

117
src/vendor/printf.h vendored Normal file
View File

@ -0,0 +1,117 @@
///////////////////////////////////////////////////////////////////////////////
// \author (c) Marco Paland (info@paland.com)
// 2014-2019, PALANDesign Hannover, Germany
//
// \license The MIT License (MIT)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// \brief Tiny printf, sprintf and snprintf implementation, optimized for speed on
// embedded systems with a very limited resources.
// Use this instead of bloated standard/newlib printf.
// These routines are thread safe and reentrant.
//
///////////////////////////////////////////////////////////////////////////////
#ifndef _PRINTF_H_
#define _PRINTF_H_
#include <stdarg.h>
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* Output a character to a custom device like UART, used by the printf() function
* This function is declared here only. You have to write your custom implementation somewhere
* \param character Character to output
*/
void _putchar(char character);
/**
* Tiny printf implementation
* You have to implement _putchar if you use printf()
* To avoid conflicts with the regular printf() API it is overridden by macro defines
* and internal underscore-appended functions like printf_() are used
* \param format A string that specifies the format of the output
* \return The number of characters that are written into the array, not counting the terminating null character
*/
#define printf printf_
int printf_(const char* format, ...);
/**
* Tiny sprintf implementation
* Due to security reasons (buffer overflow) YOU SHOULD CONSIDER USING (V)SNPRINTF INSTEAD!
* \param buffer A pointer to the buffer where to store the formatted string. MUST be big enough to store the output!
* \param format A string that specifies the format of the output
* \return The number of characters that are WRITTEN into the buffer, not counting the terminating null character
*/
#define sprintf sprintf_
int sprintf_(char* buffer, const char* format, ...);
/**
* Tiny snprintf/vsnprintf implementation
* \param buffer A pointer to the buffer where to store the formatted string
* \param count The maximum number of characters to store in the buffer, including a terminating null character
* \param format A string that specifies the format of the output
* \param va A value identifying a variable arguments list
* \return The number of characters that COULD have been written into the buffer, not counting the terminating
* null character. A value equal or larger than count indicates truncation. Only when the returned value
* is non-negative and less than count, the string has been completely written.
*/
#define snprintf snprintf_
#define vsnprintf vsnprintf_
int snprintf_(char* buffer, size_t count, const char* format, ...);
int vsnprintf_(char* buffer, size_t count, const char* format, va_list va);
/**
* Tiny vprintf implementation
* \param format A string that specifies the format of the output
* \param va A value identifying a variable arguments list
* \return The number of characters that are WRITTEN into the buffer, not counting the terminating null character
*/
#define vprintf vprintf_
int vprintf_(const char* format, va_list va);
/**
* printf with output function
* You may use this as dynamic alternative to printf() with its fixed _putchar() output
* \param out An output function which takes one character and an argument pointer
* \param arg An argument pointer for user data passed to output function
* \param format A string that specifies the format of the output
* \return The number of characters that are sent to the output function, not counting the terminating null character
*/
int fctprintf(void (*out)(char character, void* arg), void* arg, const char* format, ...);
#ifdef __cplusplus
}
#endif
#endif // _PRINTF_H_

1039
src/vendor/qrcodegen.c vendored Normal file

File diff suppressed because it is too large Load Diff

402
src/vendor/qrcodegen.h vendored Normal file
View File

@ -0,0 +1,402 @@
/*
* This library has been modified to output QR codes in a 4bpp format suitable
* for use as a texture without any additional conversion. The original license
* and copyright notice is below.
* ----------------------------------------------------------------------------
*
* QR Code generator library (C)
*
* Copyright (c) Project Nayuki. (MIT License)
* https://www.nayuki.io/page/qr-code-generator-library
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
* - The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* - The Software is provided "as is", without warranty of any kind, express or
* implied, including but not limited to the warranties of merchantability,
* fitness for a particular purpose and noninfringement. In no event shall the
* authors or copyright holders be liable for any claim, damages or other
* liability, whether in an action of contract, tort or otherwise, arising from,
* out of or in connection with the Software or the use or other dealings in the
* Software.
*/
#pragma once
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/*
* This library creates QR Code symbols, which is a type of two-dimension barcode.
* Invented by Denso Wave and described in the ISO/IEC 18004 standard.
* A QR Code structure is an immutable square grid of dark and light cells.
* The library provides functions to create a QR Code from text or binary data.
* The library covers the QR Code Model 2 specification, supporting all versions (sizes)
* from 1 to 40, all 4 error correction levels, and 4 character encoding modes.
*
* Ways to create a QR Code object:
* - High level: Take the payload data and call qrcodegen_encodeText() or qrcodegen_encodeBinary().
* - Low level: Custom-make the list of segments and call
* qrcodegen_encodeSegments() or qrcodegen_encodeSegmentsAdvanced().
* (Note that all ways require supplying the desired error correction level and various byte buffers.)
*/
/*---- Enum and struct types----*/
/*
* The error correction level in a QR Code symbol.
*/
enum qrcodegen_Ecc {
// Must be declared in ascending order of error protection
// so that an internal qrcodegen function works properly
qrcodegen_Ecc_LOW = 0 , // The QR Code can tolerate about 7% erroneous codewords
qrcodegen_Ecc_MEDIUM , // The QR Code can tolerate about 15% erroneous codewords
qrcodegen_Ecc_QUARTILE, // The QR Code can tolerate about 25% erroneous codewords
qrcodegen_Ecc_HIGH , // The QR Code can tolerate about 30% erroneous codewords
};
/*
* The mask pattern used in a QR Code symbol.
*/
enum qrcodegen_Mask {
// A special value to tell the QR Code encoder to
// automatically select an appropriate mask pattern
qrcodegen_Mask_AUTO = -1,
// The eight actual mask patterns
qrcodegen_Mask_0 = 0,
qrcodegen_Mask_1,
qrcodegen_Mask_2,
qrcodegen_Mask_3,
qrcodegen_Mask_4,
qrcodegen_Mask_5,
qrcodegen_Mask_6,
qrcodegen_Mask_7,
};
/*
* Describes how a segment's data bits are interpreted.
*/
enum qrcodegen_Mode {
qrcodegen_Mode_NUMERIC = 0x1,
qrcodegen_Mode_ALPHANUMERIC = 0x2,
qrcodegen_Mode_BYTE = 0x4,
qrcodegen_Mode_KANJI = 0x8,
qrcodegen_Mode_ECI = 0x7,
};
/*
* A segment of character/binary/control data in a QR Code symbol.
* The mid-level way to create a segment is to take the payload data
* and call a factory function such as qrcodegen_makeNumeric().
* The low-level way to create a segment is to custom-make the bit buffer
* and initialize a qrcodegen_Segment struct with appropriate values.
* Even in the most favorable conditions, a QR Code can only hold 7089 characters of data.
* Any segment longer than this is meaningless for the purpose of generating QR Codes.
* Moreover, the maximum allowed bit length is 32767 because
* the largest QR Code (version 40) has 31329 modules.
*/
struct qrcodegen_Segment {
// The mode indicator of this segment.
enum qrcodegen_Mode mode;
// The length of this segment's unencoded data. Measured in characters for
// numeric/alphanumeric/kanji mode, bytes for byte mode, and 0 for ECI mode.
// Always zero or positive. Not the same as the data's bit length.
int numChars;
// The data bits of this segment, packed in bitwise big endian.
// Can be null if the bit length is zero.
uint8_t *data;
// The number of valid data bits used in the buffer. Requires
// 0 <= bitLength <= 32767, and bitLength <= (capacity of data array) * 8.
// The character count (numChars) must agree with the mode and the bit buffer length.
int bitLength;
};
extern const char *qrcodegen_ALPHANUMERIC_CHARSET;
/*---- Macro constants and functions ----*/
#define qrcodegen_VERSION_MIN 1 // The minimum version number supported in the QR Code Model 2 standard
#define qrcodegen_VERSION_MAX 40 // The maximum version number supported in the QR Code Model 2 standard
// Calculates the number of uint32s needed to store any QR Code up to and including the given version number,
// as a compile-time constant. For example, 'uint32_t buffer[qrcodegen_BUFFER_LEN_FOR_VERSION(25)];'
// can store any single QR Code from version 1 to 25 (inclusive). The result fits in an int (or int16).
// Requires qrcodegen_VERSION_MIN <= n <= qrcodegen_VERSION_MAX.
#define qrcodegen_SIZE_FOR_VERSION(n) ((n) * 4 + 17)
#define qrcodegen_STRIDE_FOR_VERSION(n) ((qrcodegen_SIZE_FOR_VERSION(n) + 7) / 8)
#define qrcodegen_BUFFER_LEN_FOR_VERSION(n) (qrcodegen_SIZE_FOR_VERSION(n) * qrcodegen_STRIDE_FOR_VERSION(n) + 1)
// The worst-case number of bytes needed to store one QR Code, up to and including
// version 40. This value equals 3918, which is just under 4 kilobytes.
// Use this more convenient value to avoid calculating tighter memory bounds for buffers.
#define qrcodegen_TEMP_BUFFER_LEN_MAX qrcodegen_TEMP_BUFFER_LEN_FOR_VERSION(qrcodegen_VERSION_MAX)
#define qrcodegen_BUFFER_LEN_MAX qrcodegen_BUFFER_LEN_FOR_VERSION(qrcodegen_VERSION_MAX)
/*---- Functions (high level) to generate QR Codes ----*/
/*
* Encodes the given text string to a QR Code, returning true if successful.
* If the data is too long to fit in any version in the given range
* at the given ECC level, then false is returned.
*
* The input text must be encoded in UTF-8 and contain no NULs.
* Requires 1 <= minVersion <= maxVersion <= 40.
*
* The smallest possible QR Code version within the given range is automatically
* chosen for the output. Iff boostEcl is true, then the ECC level of the result
* may be higher than the ecl argument if it can be done without increasing the
* version. The mask is either between qrcodegen_Mask_0 to 7 to force that mask, or
* qrcodegen_Mask_AUTO to automatically choose an appropriate mask (which may be slow).
*
* About the arrays, letting len = qrcodegen_BUFFER_LEN_FOR_VERSION(maxVersion):
* - Before calling the function:
* - The array ranges tempBuffer[0 : len] and qrcode[0 : len] must allow
* reading and writing; hence each array must have a length of at least len.
* - The two ranges must not overlap (aliasing).
* - The initial state of both ranges can be uninitialized
* because the function always writes before reading.
* - After the function returns:
* - Both ranges have no guarantee on which elements are initialized and what values are stored.
* - tempBuffer contains no useful data and should be treated as entirely uninitialized.
* - If successful, qrcode can be passed into qrcodegen_getSize() and qrcodegen_getModule().
*
* If successful, the resulting QR Code may use numeric,
* alphanumeric, or byte mode to encode the text.
*
* In the most optimistic case, a QR Code at version 40 with low ECC
* can hold any UTF-8 string up to 2953 bytes, or any alphanumeric string
* up to 4296 characters, or any digit string up to 7089 characters.
* These numbers represent the hard upper limit of the QR Code standard.
*
* Please consult the QR Code specification for information on
* data capacities per version, ECC level, and text encoding mode.
*/
bool qrcodegen_encodeText(const char *text, uint32_t tempBuffer[], uint32_t qrcode[],
enum qrcodegen_Ecc ecl, int minVersion, int maxVersion, enum qrcodegen_Mask mask, bool boostEcl);
/*
* Encodes the given binary data to a QR Code, returning true if successful.
* If the data is too long to fit in any version in the given range
* at the given ECC level, then false is returned.
*
* Requires 1 <= minVersion <= maxVersion <= 40.
*
* The smallest possible QR Code version within the given range is automatically
* chosen for the output. Iff boostEcl is true, then the ECC level of the result
* may be higher than the ecl argument if it can be done without increasing the
* version. The mask is either between qrcodegen_Mask_0 to 7 to force that mask, or
* qrcodegen_Mask_AUTO to automatically choose an appropriate mask (which may be slow).
*
* About the arrays, letting len = qrcodegen_BUFFER_LEN_FOR_VERSION(maxVersion):
* - Before calling the function:
* - The array ranges dataAndTemp[0 : len] and qrcode[0 : len] must allow
* reading and writing; hence each array must have a length of at least len.
* - The two ranges must not overlap (aliasing).
* - The input array range dataAndTemp[0 : dataLen] should normally be
* valid UTF-8 text, but is not required by the QR Code standard.
* - The initial state of dataAndTemp[dataLen : len] and qrcode[0 : len]
* can be uninitialized because the function always writes before reading.
* - After the function returns:
* - Both ranges have no guarantee on which elements are initialized and what values are stored.
* - dataAndTemp contains no useful data and should be treated as entirely uninitialized.
* - If successful, qrcode can be passed into qrcodegen_getSize() and qrcodegen_getModule().
*
* If successful, the resulting QR Code will use byte mode to encode the data.
*
* In the most optimistic case, a QR Code at version 40 with low ECC can hold any byte
* sequence up to length 2953. This is the hard upper limit of the QR Code standard.
*
* Please consult the QR Code specification for information on
* data capacities per version, ECC level, and text encoding mode.
*/
bool qrcodegen_encodeBinary(uint32_t dataAndTemp[], size_t dataLen, uint32_t qrcode[],
enum qrcodegen_Ecc ecl, int minVersion, int maxVersion, enum qrcodegen_Mask mask, bool boostEcl);
/*---- Functions (low level) to generate QR Codes ----*/
/*
* Encodes the given segments to a QR Code, returning true if successful.
* If the data is too long to fit in any version at the given ECC level,
* then false is returned.
*
* The smallest possible QR Code version is automatically chosen for
* the output. The ECC level of the result may be higher than the
* ecl argument if it can be done without increasing the version.
*
* About the byte arrays, letting len = qrcodegen_BUFFER_LEN_FOR_VERSION(qrcodegen_VERSION_MAX):
* - Before calling the function:
* - The array ranges tempBuffer[0 : len] and qrcode[0 : len] must allow
* reading and writing; hence each array must have a length of at least len.
* - The two ranges must not overlap (aliasing).
* - The initial state of both ranges can be uninitialized
* because the function always writes before reading.
* - The input array segs can contain segments whose data buffers overlap with tempBuffer.
* - After the function returns:
* - Both ranges have no guarantee on which elements are initialized and what values are stored.
* - tempBuffer contains no useful data and should be treated as entirely uninitialized.
* - Any segment whose data buffer overlaps with tempBuffer[0 : len]
* must be treated as having invalid values in that array.
* - If successful, qrcode can be passed into qrcodegen_getSize() and qrcodegen_getModule().
*
* Please consult the QR Code specification for information on
* data capacities per version, ECC level, and text encoding mode.
*
* This function allows the user to create a custom sequence of segments that switches
* between modes (such as alphanumeric and byte) to encode text in less space.
* This is a low-level API; the high-level API is qrcodegen_encodeText() and qrcodegen_encodeBinary().
*/
bool qrcodegen_encodeSegments(const struct qrcodegen_Segment segs[], size_t len,
enum qrcodegen_Ecc ecl, uint32_t tempBuffer[], uint32_t qrcode[]);
/*
* Encodes the given segments to a QR Code, returning true if successful.
* If the data is too long to fit in any version in the given range
* at the given ECC level, then false is returned.
*
* Requires 1 <= minVersion <= maxVersion <= 40.
*
* The smallest possible QR Code version within the given range is automatically
* chosen for the output. Iff boostEcl is true, then the ECC level of the result
* may be higher than the ecl argument if it can be done without increasing the
* version. The mask is either between qrcodegen_Mask_0 to 7 to force that mask, or
* qrcodegen_Mask_AUTO to automatically choose an appropriate mask (which may be slow).
*
* About the byte arrays, letting len = qrcodegen_BUFFER_LEN_FOR_VERSION(qrcodegen_VERSION_MAX):
* - Before calling the function:
* - The array ranges tempBuffer[0 : len] and qrcode[0 : len] must allow
* reading and writing; hence each array must have a length of at least len.
* - The two ranges must not overlap (aliasing).
* - The initial state of both ranges can be uninitialized
* because the function always writes before reading.
* - The input array segs can contain segments whose data buffers overlap with tempBuffer.
* - After the function returns:
* - Both ranges have no guarantee on which elements are initialized and what values are stored.
* - tempBuffer contains no useful data and should be treated as entirely uninitialized.
* - Any segment whose data buffer overlaps with tempBuffer[0 : len]
* must be treated as having invalid values in that array.
* - If successful, qrcode can be passed into qrcodegen_getSize() and qrcodegen_getModule().
*
* Please consult the QR Code specification for information on
* data capacities per version, ECC level, and text encoding mode.
*
* This function allows the user to create a custom sequence of segments that switches
* between modes (such as alphanumeric and byte) to encode text in less space.
* This is a low-level API; the high-level API is qrcodegen_encodeText() and qrcodegen_encodeBinary().
*/
bool qrcodegen_encodeSegmentsAdvanced(const struct qrcodegen_Segment segs[], size_t len, enum qrcodegen_Ecc ecl,
int minVersion, int maxVersion, enum qrcodegen_Mask mask, bool boostEcl, uint32_t tempBuffer[], uint32_t qrcode[]);
/*
* Tests whether the given string can be encoded as a segment in numeric mode.
* A string is encodable iff each character is in the range 0 to 9.
*/
bool qrcodegen_isNumeric(const char *text);
/*
* Tests whether the given string can be encoded as a segment in alphanumeric mode.
* A string is encodable iff each character is in the following set: 0 to 9, A to Z
* (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon.
*/
bool qrcodegen_isAlphanumeric(const char *text);
/*
* Returns the number of bytes (uint8_t) needed for the data buffer of a segment
* containing the given number of characters using the given mode. Notes:
* - Returns SIZE_MAX on failure, i.e. numChars > INT16_MAX or the internal
* calculation of the number of needed bits exceeds INT16_MAX (i.e. 32767).
* - Otherwise, all valid results are in the range [0, ceil(INT16_MAX / 8)], i.e. at most 4096.
* - It is okay for the user to allocate more bytes for the buffer than needed.
* - For byte mode, numChars measures the number of bytes, not Unicode code points.
* - For ECI mode, numChars must be 0, and the worst-case number of bytes is returned.
* An actual ECI segment can have shorter data. For non-ECI modes, the result is exact.
*/
size_t qrcodegen_calcSegmentBufferSize(enum qrcodegen_Mode mode, size_t numChars);
/*
* Returns a segment representing the given binary data encoded in
* byte mode. All input byte arrays are acceptable. Any text string
* can be converted to UTF-8 bytes and encoded as a byte mode segment.
*/
struct qrcodegen_Segment qrcodegen_makeBytes(const uint8_t data[], size_t len, uint8_t buf[]);
/*
* Returns a segment representing the given string of decimal digits encoded in numeric mode.
*/
struct qrcodegen_Segment qrcodegen_makeNumeric(const char *digits, uint8_t buf[]);
/*
* Returns a segment representing the given text string encoded in alphanumeric mode.
* The characters allowed are: 0 to 9, A to Z (uppercase only), space,
* dollar, percent, asterisk, plus, hyphen, period, slash, colon.
*/
struct qrcodegen_Segment qrcodegen_makeAlphanumeric(const char *text, uint8_t buf[]);
/*
* Returns a segment representing an Extended Channel Interpretation
* (ECI) designator with the given assignment value.
*/
struct qrcodegen_Segment qrcodegen_makeEci(long assignVal, uint8_t buf[]);
/*---- Functions to extract raw data from QR Codes ----*/
/*
* Returns the side length of the given QR Code, assuming that encoding succeeded.
* The result is in the range [21, 177]. Note that the length of the array buffer
* is related to the side length - every 'uint32_t qrcode[]' must have length at least
* qrcodegen_BUFFER_LEN_FOR_VERSION(version), which equals ceil(size^2 / 8 + 1).
*/
int qrcodegen_getSize(const uint32_t qrcode[]);
/*
* Returns the horizontal stride (number of uint32s per row) of the given QR Code.
*/
int qrcodegen_getStride(const uint32_t qrcode[]);
/*
* Returns the color of the module (pixel) at the given coordinates, which is false
* for light or true for dark. The top left corner has the coordinates (x=0, y=0).
* If the given coordinates are out of bounds, then false (light) is returned.
*/
bool qrcodegen_getModule(const uint32_t qrcode[], int x, int y);
#ifdef __cplusplus
}
#endif

155
src/zs01.cpp Normal file
View File

@ -0,0 +1,155 @@
#include <stddef.h>
#include <stdint.h>
#include "util.hpp"
#include "zs01.hpp"
namespace zs01 {
/* Fixed keys */
// This key is identical across all ZS01 cartridges and seems to be hardcoded.
static const Key _COMMAND_KEY{
.add = { 237, 8, 16, 11, 6, 4, 8, 30 },
.shift = { 0, 3, 2, 2, 6, 2, 2, 1 }
};
// This key is provided by the 573 to the ZS01 and is used to encode responses.
// Konami's driver generates a pseudorandom key for each transaction, but it can
// be a fixed key as well.
static const Key _RESPONSE_KEY{
.add = { 0, 0, 0, 0, 0, 0, 0, 0 },
.shift = { 0, 0, 0, 0, 0, 0, 0, 0 }
};
/* Packet encoding/decoding */
void Key::unpackFrom(const uint8_t *key) {
add[0] = key[0];
shift[0] = 0;
for (int i = 1; i < 8; i++) {
add[i] = key[i] & 0x1f;
shift[i] = key[i] >> 5;
}
}
void Key::packInto(uint8_t *key) const {
key[0] = add[0];
for (int i = 1; i < 8; i++)
key[i] = (add[i] & 0x1f) | (shift[i] << 5);
}
void Key::encodePacket(uint8_t *data, size_t length, uint8_t state) const {
for (data += length; length; length--) {
uint8_t value = *(--data) ^ state;
value = (value + add[0]) & 0xff;
for (int i = 1; i < 8; i++) {
int newValue;
newValue = static_cast<int>(value) << shift[i];
newValue |= static_cast<int>(value) >> (8 - shift[i]);
newValue &= 0xff;
value = (newValue + add[i]) & 0xff;
}
state = value;
*data = value;
}
}
void Key::decodePacket(uint8_t *data, size_t length, uint8_t state) const {
for (data += length; length; length--) {
uint8_t value = *(--data), prevState = state;
state = value;
for (int i = 7; i; i--) {
int newValue = (value - add[i]) & 0xff;
value = static_cast<int>(newValue) >> shift[i];
value |= static_cast<int>(newValue) << (8 - shift[i]);
value &= 0xff;
}
value = (value - add[0]) & 0xff;
*data = value ^ prevState;
}
}
void Key::encodePayload(uint8_t *data, size_t length, uint8_t state) const {
for (; length; length--) {
uint8_t value = *data ^ state;
value = (value + add[0]) & 0xff;
for (int i = 1; i < 8; i++) {
int newValue;
newValue = static_cast<int>(value) << shift[i];
newValue |= static_cast<int>(value) >> (8 - shift[i]);
newValue &= 0xff;
value = (newValue + add[i]) & 0xff;
}
state = value;
*(data++) = value;
}
}
void Packet::updateCRC(void) {
uint16_t value = util::zsCRC16(&command, sizeof(Packet) - sizeof(crc));
crc[0] = value >> 8;
crc[1] = value & 0xff;
}
bool Packet::validateCRC(void) const {
uint16_t _crc = (crc[0] << 8) | crc[1];
uint16_t value = util::zsCRC16(&command, sizeof(Packet) - sizeof(crc));
if (value != _crc) {
LOG("CRC mismatch, exp=0x%04x, got=0x%04x", value, _crc);
return false;
}
return true;
}
void Packet::encodeReadRequest(void) {
command = REQ_READ;
_RESPONSE_KEY.packInto(data);
updateCRC();
_COMMAND_KEY.encodePacket(&command, sizeof(Packet));
}
void Packet::encodeReadRequest(Key &dataKey, uint8_t state) {
command = REQ_READ | REQ_USE_DATA_KEY;
_RESPONSE_KEY.packInto(data);
updateCRC();
dataKey.encodePayload(data, sizeof(data), state);
_COMMAND_KEY.encodePacket(&command, sizeof(Packet));
}
void Packet::encodeWriteRequest(Key &dataKey, uint8_t state) {
command = REQ_WRITE | REQ_USE_DATA_KEY;
updateCRC();
dataKey.encodePayload(data, sizeof(data), state);
_COMMAND_KEY.encodePacket(&command, sizeof(Packet));
}
bool Packet::decodeResponse(void) {
// NOTE: if a non-fixed response key is used, the ZS01 may encode the
// response to a read request with either the key provided in the request
// *or* the last key used (Konami's driver attempts decoding the response
// with both keys before giving up). When replying to a write request, the
// ZS01 always encodes the response with the same key it used when replying
// to the last read request. Confused yet?
_RESPONSE_KEY.decodePacket(&command, sizeof(Packet));
return validateCRC();
}
}

81
src/zs01.hpp Normal file
View File

@ -0,0 +1,81 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
#include <string.h>
namespace zs01 {
/* Command definitions */
enum Address : uint8_t {
ADDR_PUBLIC = 0x00,
ADDR_PUBLIC_END = 0x04,
ADDR_PRIVATE = 0x04,
ADDR_PRIVATE_END = 0x0e,
ADDR_ZS01_ID = 0xfc, // Read-only (?)
ADDR_DS2401_ID = 0xfd, // Read-only
ADDR_ERASE = 0xfd, // Write-only
ADDR_CONFIG = 0xfe,
ADDR_DATA_KEY = 0xff // Write-only
};
enum RequestFlag : uint8_t {
REQ_WRITE = 0 << 0,
REQ_READ = 1 << 0,
REQ_BANK_SWITCH = 1 << 1, // Unused (should be bit 8 of block address)
REQ_USE_DATA_KEY = 1 << 2
};
enum ResponseCode : uint8_t {
// The meaning of these codes is currently unknown. Presumably:
// - one of the "security errors" is a CRC validation failure, the other
// could be data key related
// - one of the unknown errors is for invalid commands or addresses
// - one or two of the unknown errors are for actual read/write failures
RESP_NO_ERROR = 0x00,
RESP_SECURITY_ERROR1 = 0x01,
RESP_UNKNOWN_ERROR1 = 0x02,
RESP_UNKNOWN_ERROR2 = 0x03,
RESP_SECURITY_ERROR2 = 0x04,
RESP_UNKNOWN_ERROR3 = 0x05
};
/* Packet encoding/decoding */
class Key {
public:
uint8_t add[8], shift[8];
void unpackFrom(const uint8_t *key);
void packInto(uint8_t *key) const;
void encodePacket(uint8_t *data, size_t length, uint8_t state = 0xff) const;
void decodePacket(uint8_t *data, size_t length, uint8_t state = 0xff) const;
void encodePayload(uint8_t *data, size_t length, uint8_t state = 0xff) const;
};
class Packet {
public:
uint8_t command, address, data[8], crc[2];
inline void copyDataFrom(const uint8_t *source) {
memcpy(data, source, sizeof(data));
}
inline void copyDataTo(uint8_t *dest) const {
memcpy(dest, data, sizeof(data));
}
inline void clearData(void) {
memset(data, 0, sizeof(data));
}
void updateCRC(void);
bool validateCRC(void) const;
void encodeReadRequest(void);
void encodeReadRequest(Key &dataKey, uint8_t state = 0xff);
void encodeWriteRequest(Key &dataKey, uint8_t state = 0xff);
bool decodeResponse(void);
};
}

391
tools/buildResourceArchive.py Executable file
View File

@ -0,0 +1,391 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__version__ = "0.3.0"
__author__ = "spicyjpeg"
import json, re
from argparse import ArgumentParser, FileType, Namespace
from collections import defaultdict
from itertools import chain
from pathlib import Path
from struct import Struct
from typing import Any, ByteString, Generator, Mapping
from zipfile import ZIP_DEFLATED, ZIP_STORED, ZipFile
import numpy
from numpy import ndarray
from PIL import Image
## .TIM image converter
TIM_HEADER_STRUCT: Struct = Struct("< 2I")
TIM_SECTION_STRUCT: Struct = Struct("< I 4H")
TIM_HEADER_VERSION: int = 0x10
LOWER_ALPHA_BOUND: int = 0x20
UPPER_ALPHA_BOUND: int = 0xe0
# Color 0x0000 is interpreted by the PS1 GPU as fully transparent, so black
# pixels must be changed to dark gray to prevent them from becoming transparent.
TRANSPARENT_COLOR: int = 0x0000
BLACK_COLOR: int = 0x0421
def convertRGBAto16(inputData: ndarray) -> ndarray:
source: ndarray = inputData.astype("<H")
r: ndarray = ((source[:, :, 0] * 249) + 1014) >> 11
g: ndarray = ((source[:, :, 1] * 249) + 1014) >> 11
b: ndarray = ((source[:, :, 2] * 249) + 1014) >> 11
data: ndarray = r | (g << 5) | (b << 10)
data = numpy.where(data != TRANSPARENT_COLOR, data, BLACK_COLOR)
if source.shape[2] == 4:
alpha: ndarray = source[:, :, 3]
data = numpy.select(
(
alpha > UPPER_ALPHA_BOUND, # Leave as-is
alpha > LOWER_ALPHA_BOUND # Set semitransparency flag
), (
data,
data | (1 << 15)
),
TRANSPARENT_COLOR
)
return data.reshape(source.shape[:-1])
def convertIndexedImage(imageObj: Image.Image) -> tuple[ndarray, ndarray]:
# PIL/Pillow doesn't provide a proper way to get the number of colors in a
# palette, so here's an extremely ugly hack.
colorDepth: int = { "RGB": 3, "RGBA": 4 }[imageObj.palette.mode]
clutData: bytes = imageObj.palette.tobytes()
numColors: int = len(clutData) // colorDepth
clut: ndarray = convertRGBAto16(
numpy.frombuffer(clutData, "B").reshape(( 1, numColors, colorDepth ))
)
# Pad the palette to 16 or 256 colors.
padAmount: int = (16 if (numColors <= 16) else 256) - numColors
if padAmount:
clut = numpy.c_[ clut, numpy.zeros(padAmount, "<H") ]
image: ndarray = numpy.asarray(imageObj, "B")
if image.shape[1] % 2:
image = numpy.c_[ image, numpy.zeros(image.shape[0], "B") ]
# Pack two pixels into each byte for 4bpp images.
if numColors <= 16:
image = image[:, 0::2] | (image[:, 1::2] << 4)
if image.shape[1] % 2:
image = numpy.c_[ image, numpy.zeros(image.shape[0], "B") ]
return image, clut
def generateIndexedTIM(
imageObj: Image.Image, ix: int, iy: int, cx: int, cy: int
) -> bytearray:
if (ix < 0) or (ix > 1023) or (iy < 0) or (iy > 1023):
raise ValueError("image X/Y coordinates must be in 0-1023 range")
if (cx < 0) or (cx > 1023) or (cy < 0) or (cy > 1023):
raise ValueError("palette X/Y coordinates must be in 0-1023 range")
image, clut = convertIndexedImage(imageObj)
mode: int = 0x8 if (clut.size <= 16) else 0x9
data: bytearray = bytearray(TIM_HEADER_STRUCT.pack(TIM_HEADER_VERSION, mode))
data.extend(TIM_SECTION_STRUCT.pack(
TIM_SECTION_STRUCT.size + clut.size * 2,
cx, cy, clut.shape[1], clut.shape[0]
))
data.extend(clut)
data.extend(TIM_SECTION_STRUCT.pack(
TIM_SECTION_STRUCT.size + image.size,
ix, iy, image.shape[1] // 2, image.shape[0]
))
data.extend(image)
return data
## Font metrics generator
FONT_CHAR_OFFSET: int = ord(" ")
FONT_CHAR_COUNT: int = 120
METRICS_ENTRY_STRUCT: Struct = Struct("< 2B H")
def generateFontMetrics(
metrics: Mapping[str, Mapping[str, int | bool]]
) -> bytearray:
data: bytearray = bytearray(FONT_CHAR_COUNT * METRICS_ENTRY_STRUCT.size)
for ch, entry in metrics.items():
index: int = ord(ch) - FONT_CHAR_OFFSET
if (index < 0) or (index > FONT_CHAR_COUNT):
raise ValueError(f"non-ASCII character {index} is not supported")
x: int = int(entry["x"])
y: int = int(entry["y"])
w: int = int(entry["width"])
h: int = int(entry["height"])
i: bool = bool(entry.get("icon", False))
if (x < 0) or (x > 255) or (y < 0) or (y > 255):
raise ValueError("all X/Y coordinates must be in 0-255 range")
if (w < 0) or (w > 127) or (h < 0) or (h > 127):
raise ValueError("all characters must be <=127x127 pixels")
data[
METRICS_ENTRY_STRUCT.size * index:
METRICS_ENTRY_STRUCT.size * (index + 1)
] = METRICS_ENTRY_STRUCT.pack(x, y, w | (h << 7) | (i << 14))
return data
## String table generator
TABLE_ENTRY_STRUCT: Struct = Struct("< I 2H")
TABLE_BUCKET_COUNT: int = 256
TABLE_STRING_ALIGN: int = 4
TABLE_ESCAPE_REGEX: re.Pattern = re.compile(rb"\$?\{(.+?)\}")
TABLE_ESCAPE_REPL: Mapping[bytes, bytes] = {
b"UP_ARROW": b"\x80",
b"DOWN_ARROW": b"\x81",
b"LEFT_ARROW": b"\x82",
b"RIGHT_ARROW": b"\x83",
b"LEFT_BUTTON": b"\x84",
b"RIGHT_BUTTON": b"\x85",
b"START_BUTTON": b"\x86",
b"CLOSED_LOCK": b"\x87",
b"OPEN_LOCK": b"\x88",
b"CHIP_ICON": b"\x89",
b"CART_ICON": b"\x8a"
}
def hashString(string: str) -> int:
value: int = 0
for byte in string.encode("ascii"):
value = (
byte + \
((value << 6) & 0xffffffff) + \
((value << 16) & 0xffffffff) - \
value
) & 0xffffffff
return value
def convertString(string: str) -> bytes:
return TABLE_ESCAPE_REGEX.sub(
lambda match: TABLE_ESCAPE_REPL[match.group(1).strip().upper()],
string.encode("ascii")
)
def prepareStrings(
strings: Mapping[str, Any], prefix: str = ""
) -> Generator[tuple[int, bytes | None], None, None]:
for key, value in strings.items():
fullKey: str = prefix + key
if value is None:
yield hashString(fullKey), None
elif type(value) is str:
yield hashString(fullKey), convertString(value)
else:
yield from prepareStrings(value, f"{fullKey}.")
def generateStringTable(strings: Mapping[str, Any]) -> bytearray:
offsets: dict[bytes, int] = {}
chains: defaultdict[int, list[tuple[int, int | None]]] = defaultdict(list)
blob: bytearray = bytearray()
for fullHash, string in prepareStrings(strings):
if string is None:
entry: tuple[int, int | None] = fullHash, 0
else:
offset: int | None = offsets.get(string, None)
if offset is None:
offset = len(blob)
offsets[string] = offset
blob.extend(string)
blob.append(0)
while len(blob) % TABLE_STRING_ALIGN:
blob.append(0)
entry: tuple[int, int | None] = fullHash, offset
chains[fullHash % TABLE_BUCKET_COUNT].append(entry)
# Build the bucket array and all chains of entries.
buckets: list[tuple[int, int | None, int]] = []
chained: list[tuple[int, int | None, int]] = []
for shortHash in range(TABLE_BUCKET_COUNT):
entries: list[tuple[int, int | None]] = chains[shortHash]
if not entries:
buckets.append(( 0, None, 0 ))
continue
for index, entry in enumerate(entries):
if index < (len(entries) - 1):
chainIndex: int = TABLE_BUCKET_COUNT + len(chained)
else:
chainIndex: int = 0
fullHash, offset = entry
if index:
chained.append(( fullHash, offset, chainIndex ))
else:
buckets.append(( fullHash, offset, chainIndex ))
# Relocate the offsets and serialize the table.
blobAddr: int = TABLE_ENTRY_STRUCT.size * (len(buckets) + len(chained))
data: bytearray = bytearray()
for fullHash, offset, chainIndex in chain(buckets, chained):
absOffset: int = 0 if (offset is None) else (blobAddr + offset)
if absOffset > 0xffff:
raise RuntimeError("string table exceeds 64 KB size limit")
data.extend(TABLE_ENTRY_STRUCT.pack( fullHash, absOffset, chainIndex ))
data.extend(blob)
return data
## Main
def createParser() -> ArgumentParser:
parser = ArgumentParser(
description = \
"Parses a JSON file containing a list of resources to convert, "
"generates the respective files and packs them into a ZIP archive.",
add_help = False
)
group = parser.add_argument_group("Tool options")
group.add_argument(
"-h", "--help",
action = "help",
help = "Show this help message and exit"
)
group = parser.add_argument_group("ZIP compression options")
group.add_argument(
"-c", "--compress-level",
type = int,
default = 9,
help = "Set default gzip compression level (default 9)",
metavar = "0-9"
)
group.add_argument(
"-n", "--no-compression",
action = "store_true",
help = "Forcefully disable gzip compression for all files"
)
group = parser.add_argument_group("File paths")
group.add_argument(
"-s", "--source-dir",
type = Path,
help = \
"Set path to directory containing source files (same directory as "
"resource list by default)"
)
group.add_argument(
"resourceList",
type = FileType("rt"),
help = "Path to JSON resource list",
)
group.add_argument(
"output",
type = Path,
help = "Path to ZIP file to generate"
)
return parser
def main():
parser: ArgumentParser = createParser()
args: Namespace = parser.parse_args()
with args.resourceList as _file:
assetList: list = json.load(_file)
sourceDir: Path = args.source_dir or Path(_file.name).parent
with ZipFile(args.output, "w", allowZip64 = False) as _zip:
for asset in assetList:
match asset.get("type", "file").strip():
case "empty":
data: ByteString = b""
case "text":
with open(sourceDir / asset["source"], "rt") as _file:
data: ByteString = _file.read().encode("ascii")
case "binary":
with open(sourceDir / asset["source"], "rb") as _file:
data: ByteString = _file.read()
case "tim":
ix: int = int(asset["imagePos"]["x"])
iy: int = int(asset["imagePos"]["y"])
cx: int = int(asset["clutPos"]["x"])
cy: int = int(asset["clutPos"]["y"])
image: Image.Image = Image.open(sourceDir / asset["source"])
image.load()
if image.mode != "P":
image = image.quantize(
int(asset["quantize"]), dither = Image.Dither.NONE
)
data: ByteString = generateIndexedTIM(image, ix, iy, cx, cy)
case "metrics":
if "metrics" in asset:
metrics: dict = asset["metrics"]
else:
with open(sourceDir / asset["source"], "rt") as _file:
metrics: dict = json.load(_file)
data: ByteString = generateFontMetrics(metrics)
case "strings":
if "strings" in asset:
strings: dict = asset["strings"]
else:
with open(sourceDir / asset["source"], "rt") as _file:
strings: dict = json.load(_file)
data: ByteString = generateStringTable(strings)
case _type:
raise KeyError(f"unsupported asset type '{_type}'")
gzipLevel: int | None = asset.get("compress", args.compress_level)
disallow: bool = (gzipLevel is None) or args.no_compression
_zip.writestr(
asset["name"], data,
ZIP_STORED if disallow else ZIP_DEFLATED, gzipLevel
)
if __name__ == "__main__":
main()

260
tools/convertExecutable.py Executable file
View File

@ -0,0 +1,260 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""ELF executable to PlayStation 1 .EXE converter
A very simple script to convert ELF files compiled for the PS1 to the executable
format used by the BIOS, with support for setting initial $sp/$gp values and
customizing the region string (used by some emulators to determine whether they
should start in PAL or NTSC mode by default). Requires no external dependencies.
"""
__version__ = "0.1.0"
__author__ = "spicyjpeg"
from argparse import ArgumentParser, FileType, Namespace
from enum import IntEnum, IntFlag
from struct import Struct
from typing import BinaryIO, ByteString, Generator
## Utilities
def alignToMultiple(data: bytearray, alignment: int):
padAmount: int = alignment - (len(data) % alignment)
if padAmount < alignment:
data.extend(b"\0" * padAmount)
def parseStructFromFile(_file: BinaryIO, _struct: Struct) -> tuple:
return _struct.unpack(_file.read(_struct.size))
def parseStructsFromFile(
_file: BinaryIO, _struct: Struct, count: int
) -> Generator[tuple, None, None]:
data: bytes = _file.read(_struct.size * count)
for offset in range(0, len(data), _struct.size):
yield _struct.unpack(data[offset:offset + _struct.size])
## ELF file parser
ELF_HEADER_STRUCT: Struct = Struct("< 4s 4B 8x 2H 5I 6H")
ELF_HEADER_MAGIC: bytes = b"\x7fELF"
PROG_HEADER_STRUCT: Struct = Struct("< 8I")
class ELFType(IntEnum):
RELOCATABLE = 1
EXECUTABLE = 2
SHARED = 3
CORE = 4
class ELFArchitecture(IntEnum):
MIPS = 8
class ELFEndianness(IntEnum):
LITTLE = 1
BIG = 2
class ProgHeaderType(IntEnum):
NONE = 0
LOAD = 1
DYNAMIC = 2
INTERPRETER = 3
NOTE = 4
class ProgHeaderFlag(IntFlag):
EXECUTE = 1 << 0
WRITE = 1 << 1
READ = 1 << 2
class Segment:
def __init__(self, address: int, data: ByteString, flags: int):
self.address: int = address
self.data: ByteString = data
self.flags: ProgHeaderFlag = ProgHeaderFlag(flags)
def isReadOnly(self) -> bool:
return not \
(self.flags & (ProgHeaderFlag.WRITE | ProgHeaderFlag.EXECUTE))
class ELF:
def __init__(self, _file: BinaryIO):
self.type: ELFType | None = None
self.architecture: ELFArchitecture | None = None
self.abi: int | None = None
self.entryPoint: int | None = None
self.flags: int | None = None
self.segments: list[Segment] = []
self._parse(_file)
def _parse(self, _file: BinaryIO):
# Parse the file header and perform some minimal validation.
_file.seek(0)
magic, wordSize, endianness, _, self.abi, _type, architecture, _, \
self.entryPoint, progHeaderOffset, secHeaderOffset, self.flags, \
elfHeaderLength, progHeaderLength, progHeaderCount, secHeaderLength, \
secHeaderCount, _ = \
parseStructFromFile(_file, ELF_HEADER_STRUCT)
self.type = ELFType(_type)
self.architecture = ELFArchitecture(architecture)
if magic != ELF_HEADER_MAGIC:
raise RuntimeError("file is not a valid ELF")
if wordSize != 1 or endianness != ELFEndianness.LITTLE:
raise RuntimeError("ELF file must be 32-bit little-endian")
if (
elfHeaderLength != ELF_HEADER_STRUCT.size or
progHeaderLength != PROG_HEADER_STRUCT.size
):
raise RuntimeError("unsupported ELF format")
# Parse the program headers and extract all loadable segments.
_file.seek(progHeaderOffset)
for (
headerType, fileOffset, address, _, fileLength, length, flags, _
) in parseStructsFromFile(_file, PROG_HEADER_STRUCT, progHeaderCount):
if headerType != ProgHeaderType.LOAD:
continue
# Retrieve the segment and trim or pad it if necessary.
_file.seek(fileOffset)
data: bytes = _file.read(fileLength)
if length > len(data):
data = data.ljust(length, b"\0")
else:
data = data[0:length]
self.segments.append(Segment(address, data, flags))
#_file.close()
def flatten(self, stripReadOnly: bool = False) -> tuple[int, bytearray]:
# Find the lower and upper boundaries of the segments' address space.
startAddress: int = min(
seg.address for seg in self.segments
)
endAddress: int = max(
(seg.address + len(seg.data)) for seg in self.segments
)
# Copy all segments into a new byte array at their respective offsets.
data: bytearray = bytearray(endAddress - startAddress)
for seg in self.segments:
if stripReadOnly and seg.isReadOnly():
continue
offset: int = seg.address - startAddress
data[offset:offset + len(seg.data)] = seg.data
return startAddress, data
## Main
EXE_HEADER_STRUCT: Struct = Struct("< 16s 4I 16x 2I 20x 1972s")
EXE_HEADER_MAGIC: bytes = b"PS-X EXE"
EXE_ALIGNMENT: int = 2048
def createParser() -> ArgumentParser:
parser = ArgumentParser(
description = \
"Converts an ELF executable into a PlayStation 1 .EXE file.",
add_help = False
)
group = parser.add_argument_group("Tool options")
group.add_argument(
"-h", "--help",
action = "help",
help = "Show this help message and exit"
)
group = parser.add_argument_group("Conversion options")
group.add_argument(
"-r", "--region-str",
type = str,
default = "",
help = "Add a custom region string to the header",
metavar = "string"
)
group.add_argument(
"-s", "--set-sp",
type = lambda value: int(value, 0),
default = 0,
help = "Add an initial value for the stack pointer to the header",
metavar = "value"
)
group.add_argument(
"-g", "--set-gp",
type = lambda value: int(value, 0),
default = 0,
help = "Add an initial value for the global pointer to the header",
metavar = "value"
)
group.add_argument(
"-S", "--strip-read-only",
action = "store_true",
help = \
"Remove all ELF segments not marked writable nor executable from "
"the output file"
)
group = parser.add_argument_group("File paths")
group.add_argument(
"input",
type = FileType("rb"),
help = "Path to ELF input executable",
)
group.add_argument(
"output",
type = FileType("wb"),
help = "Path to PS1 executable to generate"
)
return parser
def main():
parser: ArgumentParser = createParser()
args: Namespace = parser.parse_args()
with args.input as _file:
try:
elf: ELF = ELF(_file)
except RuntimeError as err:
parser.error(err.args[0])
if elf.type != ELFType.EXECUTABLE:
parser.error("ELF file must be an executable")
if elf.architecture != ELFArchitecture.MIPS:
parser.error("ELF architecture must be MIPS")
if not elf.segments:
parser.error("ELF file must contain at least one segment")
startAddress, data = elf.flatten(args.strip_read_only)
alignToMultiple(data, EXE_ALIGNMENT)
region: bytes = args.region_str.strip().encode("ascii")
header: bytes = EXE_HEADER_STRUCT.pack(
EXE_HEADER_MAGIC, # Magic
elf.entryPoint, # Entry point
args.set_gp, # Initial global pointer
startAddress, # Data load address
len(data), # Data size
args.set_sp, # Stack offset
0, # Stack size
region # Region string
)
with args.output as _file:
_file.write(header)
_file.write(data)
if __name__ == "__main__":
main()

196
tools/decodeDump.py Executable file
View File

@ -0,0 +1,196 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__version__ = "0.3.0"
__author__ = "spicyjpeg"
import sys
from argparse import ArgumentParser, FileType, Namespace
from enum import IntEnum, IntFlag
from struct import Struct
from typing import BinaryIO, ByteString, Mapping, Sequence, TextIO
from zlib import decompress
## Base45 decoder
BASE45_CHARSET: str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:"
def decodeBase45(data: str) -> bytearray:
mapped: map = map(BASE45_CHARSET.index, data)
output: bytearray = bytearray()
for a, b, c in zip(mapped, mapped, mapped):
value: int = a + (b * 45) + (c * 2025)
output.append(value >> 8)
output.append(value & 0xff)
return output
def serialNumberToString(_id: ByteString) -> str:
value: int = int.from_bytes(_id[1:7], "little")
if value >= 100000000:
return "xxxx-xxxx"
return f"{(value // 10000) % 10000:04d}-{value % 10000:04d}"
## Dump parser
DUMP_START: str = "573::"
DUMP_END: str = "::"
DUMP_STRUCT: Struct = Struct("< 3B x 8s 8s 8s 8s 8s 512s")
DUMP_VERSION: int = 1
class ChipType(IntEnum):
TYPE_NONE = 0
TYPE_X76F041 = 1
TYPE_X76F100 = 2
TYPE_ZS01 = 3
class CartFlag(IntFlag):
HAS_DIGITAL_IO = 1 << 0
HAS_DS2401 = 1 << 1
CONFIG_OK = 1 << 2
SYSTEM_ID_OK = 1 << 3
CART_ID_OK = 1 << 4
ZS_ID_OK = 1 << 5
PUBLIC_DATA_OK = 1 << 6
PRIVATE_DATA_OK = 1 << 7
CHIP_NAMES: Mapping[ChipType, str] = {
ChipType.TYPE_NONE: "None",
ChipType.TYPE_X76F041: "Xicor X76F041",
ChipType.TYPE_X76F100: "Xicor X76F100",
ChipType.TYPE_ZS01: "Konami ZS01 (PIC16CE625)"
}
DATA_LENGTHS: Mapping[ChipType, int] = {
ChipType.TYPE_NONE: 0,
ChipType.TYPE_X76F041: 512,
ChipType.TYPE_X76F100: 112,
ChipType.TYPE_ZS01: 112
}
def toPrintableChar(value: int):
if (value < 0x20) or (value > 0x7e):
return "."
return chr(value)
def hexdump(data: ByteString | Sequence[int], output: TextIO, width: int = 16):
for i in range(0, len(data), width):
hexBytes: map = map(lambda value: f"{value:02x}", data[i:i + width])
hexLine: str = " ".join(hexBytes).ljust(width * 3 - 1)
asciiBytes: map = map(toPrintableChar, data[i:i + width])
asciiLine: str = "".join(asciiBytes).ljust(width)
output.write(f"{i:04x}: {hexLine} |{asciiLine}|\n")
def parseDump(
dumpString: str, logOutput: TextIO | None = None,
exportOutput: BinaryIO | None = None
):
_dumpString: str = dumpString.strip().upper()
if (
not _dumpString.startswith(DUMP_START) or
not _dumpString.endswith(DUMP_END)
):
raise ValueError(f"dump string does not begin with '{DUMP_START}' and end with '{DUMP_END}'")
_dumpString = _dumpString[len(DUMP_START):-len(DUMP_END)]
dump: bytes = decompress(decodeBase45(_dumpString))
version, chipType, flags, dataKey, config, systemID, cartID, zsID, data = \
DUMP_STRUCT.unpack(dump[0:DUMP_STRUCT.size])
if version != DUMP_VERSION:
raise ValueError(f"unsupported dump version {version}")
chipType: ChipType = ChipType(chipType)
flags: CartFlag = CartFlag(flags)
data: bytes = data[0:DATA_LENGTHS[chipType]]
if logOutput:
if flags & CartFlag.SYSTEM_ID_OK:
logOutput.write(f"Digital I/O ID: {systemID.hex('-')}\n")
logOutput.write(f"Serial number: {serialNumberToString(systemID)}\n")
logOutput.write(f"Cartridge type: {CHIP_NAMES[chipType]}\n")
if flags & CartFlag.CART_ID_OK:
logOutput.write(f"DS2401 identifier: {cartID.hex('-')}\n")
if flags & CartFlag.ZS_ID_OK:
logOutput.write(f"ZS01 identifier: {zsID.hex('-')}\n")
if flags & CartFlag.CONFIG_OK:
logOutput.write(f"Configuration: {config.hex('-')}\n")
logOutput.write("\nEEPROM dump:\n")
hexdump(data, logOutput)
logOutput.write("\n")
if exportOutput:
pass # TODO: implement exporting
## Main
def createParser() -> ArgumentParser:
parser = ArgumentParser(
description = "Decodes the contents of a QR code generated by the tool.",
add_help = False
)
group = parser.add_argument_group("Tool options")
group.add_argument(
"-h", "--help",
action = "help",
help = "Show this help message and exit"
)
group = parser.add_argument_group("File paths")
group.add_argument(
"-i", "--input",
type = FileType("rt"),
help = "read dump from specified file",
metavar = "file"
)
group.add_argument(
"-l", "--log",
type = FileType("at"),
default = sys.stdout,
help = "log cartridge info to specified file (stdout by default)",
metavar = "file"
)
group.add_argument(
"-e", "--export",
type = FileType("wb"),
help = "export dump in MAME format to specified file",
metavar = "file"
)
group.add_argument(
"dump",
type = str,
nargs = "?",
help = "QR string to decode (if -i was not passed)"
)
return parser
def main():
parser: ArgumentParser = createParser()
args: Namespace = parser.parse_args()
if args.input:
with args.input as _file:
dump: str = _file.read()
elif args.dump:
dump: str = args.dump
else:
parser.error("a dump must be passed on the command line or using -i")
parseDump(dump, args.log, args.export)
if __name__ == "__main__":
main()

6
tools/requirements.txt Normal file
View File

@ -0,0 +1,6 @@
# Install the dependencies required by the tools by running:
# py -m pip install -r tools/requirements.txt (Windows)
# sudo pip install -r tools/requirements.txt (Linux/macOS)
numpy >= 1.19.4
Pillow >= 8.2.0