Compare commits

...

47 Commits

Author SHA1 Message Date
4cd3355ef1 Fix memory tests 2026-04-04 19:45:29 -05:00
98d70b96d1 Added proper plural support 2026-04-04 15:21:27 -05:00
64735bdf43 Implemented lua locale gettext 2026-04-04 11:32:46 -05:00
7b87347b77 Fixed small bug with parsing plurals 2026-04-04 10:19:07 -05:00
b5b29d7061 locale parsing done 2026-04-04 10:11:46 -05:00
9ec21f85a0 Asset moved some code around 2026-04-03 14:41:38 -05:00
da1a5a3f1b Asset refactor 2026-04-03 12:56:04 -05:00
0885da8d44 Fixed dynamic updates on scene rendering 2026-03-29 19:08:58 -05:00
8af961c6d3 Fixed knulli rendering 2026-03-29 18:53:42 -05:00
ef5febdde3 Fixed dolphin rendering. 2026-03-29 18:42:59 -05:00
6d7fbd3926 Change to square only 2026-03-29 17:58:13 -05:00
2680d373d8 Fixed boot.dol in wii 2026-03-29 16:51:54 -05:00
2b2ddb3cf2 Fixed spritebatch flickering on Dolphin 2026-03-29 16:10:39 -05:00
85ff95296b Fix Linux again 2026-03-29 15:19:15 -05:00
314a2de41a Fixed text on PSP 2026-03-29 14:45:40 -05:00
26fafab47a Fix copy issues 2026-03-29 14:25:10 -05:00
e56ff20e2d Attempting to fix PSP alpha textures 2026-03-29 13:38:55 -05:00
55d44f229d Fixed crash on PSP 2026-03-29 10:35:57 -05:00
1c5e50cc4d Test text rendering 2026-03-29 10:15:22 -05:00
ea898da6c2 Fix compile 2026-03-28 21:52:52 -05:00
dbb7e9f53c Getting shaders working with lua. 2026-03-28 21:50:59 -05:00
cbb68a399d Fix compile error 2026-03-28 15:43:38 -05:00
0e794f28b1 Disable paletted textures for now 2026-03-28 15:40:30 -05:00
87d2d9123e Re-implement RGBA textures 2026-03-28 15:21:33 -05:00
6823a4ddb5 Try again again 2026-03-28 11:35:11 -05:00
20a7c70081 Fixiing weird action path missing? 2026-03-28 11:26:25 -05:00
9caa33b3bb Restore all builds 2026-03-28 11:14:15 -05:00
2d7e61460a fix 2026-03-28 11:05:36 -05:00
a4b7fb3f44 Try again 2026-03-28 11:04:42 -05:00
70056cf4ca Temp only build knulli
Some checks failed
Build Dusk / build-knulli (push) Failing after 21s
2026-03-28 11:02:43 -05:00
5f4ab71ade Add knulli build 2026-03-28 11:02:34 -05:00
f3adb3257b Cleanup knulli 2026-03-28 11:00:18 -05:00
438edda7fd Fixed knulli 2026-03-28 10:56:40 -05:00
d5b0441e6f Fixed GLES support (partially), PSP still not working 2026-03-28 10:51:50 -05:00
9ba0ceb000 Moved texture setting around 2026-03-28 09:48:24 -05:00
9474a68995 Slightly more accurate, likely going to have to change how paletted textures work 2026-03-27 21:01:29 -05:00
09c35f0aa6 Builds on knulli 2026-03-27 20:48:43 -05:00
a2113442cb Builds on knulli 2026-03-27 15:59:26 -05:00
d91808487f Allow texture to be NULL.
Some checks failed
Build Dusk / run-tests (push) Failing after 14s
Build Dusk / build-linux (push) Failing after 20s
Build Dusk / build-psp (push) Failing after 16s
Build Dusk / build-gamecube (push) Failing after 18s
Build Dusk / build-wii (push) Failing after 19s
2026-03-27 13:46:18 -05:00
933949cc19 Progress on PSP paletted textures
Some checks failed
Build Dusk / run-tests (push) Failing after 19s
Build Dusk / build-linux (push) Failing after 17s
Build Dusk / build-psp (push) Failing after 21s
Build Dusk / build-gamecube (push) Failing after 19s
Build Dusk / build-wii (push) Failing after 15s
2026-03-27 08:04:34 -05:00
407620387d Test paletted stuff
Some checks failed
Build Dusk / run-tests (push) Failing after 26s
Build Dusk / build-linux (push) Failing after 25s
Build Dusk / build-psp (push) Failing after 18s
Build Dusk / build-gamecube (push) Failing after 18s
Build Dusk / build-wii (push) Failing after 18s
2026-03-26 14:48:20 -05:00
98947dea26 starting textures
Some checks failed
Build Dusk / run-tests (push) Failing after 16s
Build Dusk / build-linux (push) Failing after 17s
Build Dusk / build-psp (push) Failing after 18s
Build Dusk / build-gamecube (push) Failing after 17s
Build Dusk / build-wii (push) Failing after 17s
2026-03-23 19:42:24 -05:00
ebff7af9b5 fix
Some checks failed
Build Dusk / run-tests (push) Failing after 17s
Build Dusk / build-linux (push) Failing after 20s
Build Dusk / build-psp (push) Failing after 20s
Build Dusk / build-gamecube (push) Failing after 19s
Build Dusk / build-wii (push) Failing after 17s
2026-03-23 15:37:53 -05:00
b23c4b83ae played around with color, will likely stick to textures.
Some checks failed
Build Dusk / run-tests (push) Failing after 13s
Build Dusk / build-linux (push) Failing after 15s
Build Dusk / build-psp (push) Failing after 14s
Build Dusk / build-gamecube (push) Failing after 13s
Build Dusk / build-wii (push) Failing after 14s
2026-03-22 23:53:23 -05:00
c0cff40628 Merge pull request 'shader' (#2) from shader into main
Some checks failed
Build Dusk / run-tests (push) Failing after 14s
Build Dusk / build-linux (push) Failing after 14s
Build Dusk / build-psp (push) Failing after 14s
Build Dusk / build-gamecube (push) Failing after 13s
Build Dusk / build-wii (push) Failing after 13s
Reviewed-on: #2
2026-03-23 04:33:20 +00:00
97513e354c Dolphin shaders
Some checks failed
Build Dusk / run-tests (pull_request) Failing after 13s
Build Dusk / build-linux (pull_request) Failing after 18s
Build Dusk / build-psp (pull_request) Failing after 18s
Build Dusk / build-gamecube (pull_request) Failing after 16s
Build Dusk / build-wii (pull_request) Failing after 13s
2026-03-22 23:32:43 -05:00
c277ae7aff DOlphin shader prog 2026-03-22 18:14:56 -05:00
157 changed files with 4455 additions and 1264 deletions

View File

@@ -1,5 +1,4 @@
name: Build Dusk name: Build Dusk
on: on:
push: push:
branches: branches:
@@ -7,7 +6,6 @@ on:
pull_request: pull_request:
branches: branches:
- main - main
jobs: jobs:
run-tests: run-tests:
runs-on: ubuntu-latest runs-on: ubuntu-latest
@@ -55,6 +53,26 @@ jobs:
path: ./git-artifcats/Dusk path: ./git-artifcats/Dusk
if-no-files-found: error if-no-files-found: error
build-knulli:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v6
- name: Set up Docker
uses: docker/setup-docker-action@v5
- name: Build knulli
run: ./scripts/build-knulli-docker.sh
- name: Move output to Dusk subfolder
run: |
mkdir -p ./git-artifcats/Dusk
cp -r build-knulli/dusk ./git-artifcats/Dusk
- name: Upload knulli binary
uses: actions/upload-artifact@v6
with:
name: dusk-knulli
path: ./git-artifcats/Dusk
if-no-files-found: error
build-gamecube: build-gamecube:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
@@ -74,6 +92,7 @@ jobs:
with: with:
name: dusk-gamecube name: dusk-gamecube
path: ./git-artifcats/Dusk path: ./git-artifcats/Dusk
if-no-files-found: error
build-wii: build-wii:
runs-on: ubuntu-latest runs-on: ubuntu-latest
@@ -87,7 +106,7 @@ jobs:
- name: Copy output files. - name: Copy output files.
run: | run: |
mkdir -p ./git-artifcats/Dusk/apps/Dusk mkdir -p ./git-artifcats/Dusk/apps/Dusk
cp build-wii/Dusk.dol ./git-artifcats/Dusk/apps/Dusk/Dusk.dol cp build-wii/Dusk.dol ./git-artifcats/Dusk/apps/Dusk/boot.dol
cp build-wii/dusk.dsk ./git-artifcats/Dusk/apps/Dusk/dusk.dsk cp build-wii/dusk.dsk ./git-artifcats/Dusk/apps/Dusk/dusk.dsk
cp docker/dolphin/meta.xml ./git-artifcats/Dusk/apps/Dusk/meta.xml cp docker/dolphin/meta.xml ./git-artifcats/Dusk/apps/Dusk/meta.xml
- name: Upload Wii binary - name: Upload Wii binary
@@ -95,3 +114,4 @@ jobs:
with: with:
name: dusk-wii name: dusk-wii
path: ./git-artifcats/Dusk path: ./git-artifcats/Dusk
if-no-files-found: error

View File

@@ -10,6 +10,4 @@ target_sources(${DUSK_LIBRARY_TARGET_NAME}
assettileset.c assettileset.c
assetlanguage.c assetlanguage.c
assetscript.c assetscript.c
assetmap.c
assetmapchunk.c
) )

View File

@@ -21,8 +21,8 @@ errorret_t assetTextureLoad(assetentire_t entire) {
// Read header and version (first 4 bytes) // Read header and version (first 4 bytes)
if( if(
assetData->header[0] != 'D' || assetData->header[0] != 'D' ||
assetData->header[1] != 'P' || assetData->header[1] != 'T' ||
assetData->header[2] != 'T' assetData->header[2] != 'X'
) { ) {
errorThrow("Invalid texture header"); errorThrow("Invalid texture header");
} }
@@ -44,15 +44,35 @@ errorret_t assetTextureLoad(assetentire_t entire) {
errorThrow("Invalid texture dimensions"); errorThrow("Invalid texture dimensions");
} }
textureInit( // Validate format
texture, textureformat_t format;
assetData->width, texturedata_t data;
assetData->height,
TEXTURE_FORMAT_PALETTE, switch(assetData->type) {
(texturedata_t){ case 0x00: // RGBA8888
.paletteData = assetData->palette format = TEXTURE_FORMAT_RGBA;
data.rgbaColors = (color_t *)assetData->data;
break;
// case 0x01:
// format = TEXTURE_FORMAT_RGB;
// break;
// case 0x02:
// format = TEXTURE_FORMAT_RGB565;
// break;
// case 0x03:
// format = TEXTURE_FORMAT_RGB5A3;
// break;
default:
errorThrow("Unsupported texture format");
} }
);
errorChain(textureInit(
texture, assetData->width, assetData->height, format, data
));
errorOk(); errorOk();
} }

View File

@@ -7,6 +7,7 @@
#pragma once #pragma once
#include "error/error.h" #include "error/error.h"
#include "display/color.h"
#define ASSET_TEXTURE_WIDTH_MAX 2048 #define ASSET_TEXTURE_WIDTH_MAX 2048
#define ASSET_TEXTURE_HEIGHT_MAX 2048 #define ASSET_TEXTURE_HEIGHT_MAX 2048
@@ -20,9 +21,10 @@ typedef struct assetentire_s assetentire_t;
typedef struct { typedef struct {
char_t header[3]; char_t header[3];
uint8_t version; uint8_t version;
uint8_t type;
uint32_t width; uint32_t width;
uint32_t height; uint32_t height;
uint8_t palette[ASSET_TEXTURE_SIZE_MAX]; uint8_t data[ASSET_TEXTURE_SIZE_MAX * sizeof(color4b_t)];
} assettexture_t; } assettexture_t;
#pragma pack(pop) #pragma pack(pop)

View File

@@ -70,8 +70,9 @@ elseif LINUX then
inputBind("mouse_x", INPUT_ACTION_POINTERX) inputBind("mouse_x", INPUT_ACTION_POINTERX)
inputBind("mouse_y", INPUT_ACTION_POINTERY) inputBind("mouse_y", INPUT_ACTION_POINTERY)
end end
else else
print("Unknown platform, no default input bindings set.") print("Unknown platform, no default input bindings set.")
end end
sceneSet('scene/minesweeper.lua') sceneSet('scene/main_menu/main_menu.lua')

View File

@@ -1,9 +1,60 @@
#
msgid "" msgid ""
msgstr "" msgstr ""
"Language: en_US\n" "Project-Id-Version: ExampleApp 1.0\n"
"Language: en\n"
"Content-Type: text/plain; charset=UTF-8\n" "Content-Type: text/plain; charset=UTF-8\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n" "Plural-Forms: nplurals=4; plural=(n==1 ? 0 : n==2 ? 1 : (n<7 ? 2 : 3));\n"
msgid "ui.test" #: ui/menu.c:10
msgstr "Hello this is a test." msgid "ui.title"
msgstr ""
"Welcome"
#: ui/user.c:22
msgid "ui.greeting"
msgstr "Hello, %s!"
#: ui/files.c:40
msgid "ui.file_status"
msgstr "%s has %d files."
#: ui/cart.c:55
msgid "cart.item_count"
msgid_plural "cart.item_count"
msgstr[0] "%d item"
msgstr[1] "%d items (dual)"
msgstr[2] "%d items (few)"
msgstr[3] "%d items (many)"
#: ui/notifications.c:71
msgid ""
"ui.multiline_help"
msgstr ""
"Line one of the help text.\n"
"Line two continues here.\n"
"Line three ends here."
#: ui/errors.c:90
msgid ""
"error.upload_failed.long"
msgstr ""
"Upload failed for file \"%s\".\n"
"Please try again later or contact support."
#: ui/messages.c:110
msgid ""
"user.invite_status"
msgid_plural ""
"user.invite_status"
msgstr[0] ""
"%s invited %d user.\n"
"Please review the request."
msgstr[1] ""
"%s invited %d users (dual).\n"
"Please review the requests."
msgstr[2] ""
"%s invited %d users (few).\n"
"Please review the requests."
msgstr[3] ""
"%s invited %d users (many).\n"
"Please review the requests."

Binary file not shown.

View File

@@ -0,0 +1,46 @@
module('spritebatch')
module('camera')
module('color')
module('ui')
module('screen')
module('time')
module('text')
module('tileset')
module('texture')
module('input')
module('shader')
module('locale')
screenSetBackground(colorCornflowerBlue())
camera = cameraCreate(CAMERA_PROJECTION_TYPE_ORTHOGRAPHIC)
text = localeGetText('cart.item_count', 52, 2)
function sceneDispose()
end
function sceneUpdate()
end
function sceneRender()
-- Update camera
camera.top = screenGetHeight()
camera.right = screenGetWidth()
shaderBind(SHADER_UNLIT)
proj = cameraGetProjectionMatrix(camera)
shaderSetMatrix(SHADER_UNLIT, SHADER_UNLIT_PROJECTION, proj)
view = cameraGetViewMatrix(camera)
shaderSetMatrix(SHADER_UNLIT, SHADER_UNLIT_VIEW, view)
-- shaderSetTexture(SHADER_UNLIT, SHADER_UNLIT_TEXTURE, nil)
-- spriteBatchPush(
-- 32, 32,
-- 64, 64,
-- colorWhite()
-- )
-- spriteBatchFlush()
textDraw(10, 10, text, colorWhite())
spriteBatchFlush()
end

View File

@@ -1,256 +0,0 @@
module('spritebatch')
module('camera')
module('color')
module('ui')
module('screen')
module('time')
module('glm')
module('text')
module('tileset')
module('texture')
module('input')
CELL_STATE_DEFAULT = 0
CELL_STATE_HOVER = 1
CELL_STATE_DOWN = 2
CELL_STATE_DISABLED = 3
screenSetBackground(colorCornflowerBlue())
camera = cameraCreate(CAMERA_PROJECTION_TYPE_ORTHOGRAPHIC)
-- tilesetUi = tilesetGetByName("ui")
-- textureUi = textureLoad(tilesetUi.texture)
-- tilesetBorder = tilesetGetByName("border")
-- textureBorder = textureLoad(tilesetBorder.texture)
-- textureGrid = textureLoad("minesweeper/grid_bg.dpi")
-- tilesetCell = tilesetGetByName("cell")
-- textureCell = textureLoad(tilesetCell.texture)
-- cellSliceDefault = tilesetPositionGetUV(tilesetCell, 3, 5)
-- cellSliceHover = tilesetPositionGetUV(tilesetCell, 3, 4)
-- cellSliceDown = tilesetPositionGetUV(tilesetCell, 3, 6)
-- cellSliceDisabled = tilesetPositionGetUV(tilesetCell, 3, 7)
-- sweepwerCols = 10
-- sweeperRows = 14
-- mouseX = -1
-- mouseY = -1
-- centerX = 0
-- centerY = 0
-- boardWidth = sweepwerCols * tilesetCell.tileWidth
-- boardHeight = sweeperRows * tilesetCell.tileHeight
-- i = 0
-- cells = {}
-- for y = 1, sweeperRows do
-- for x = 1, sweepwerCols do
-- cells[i] = CELL_STATE_DEFAULT
-- i = i + 1
-- end
-- end
function cellDraw(x, y, type)
local slice = cellSliceDefault
if type == CELL_STATE_HOVER then
slice = cellSliceHover
elseif type == CELL_STATE_DOWN then
slice = cellSliceDown
elseif type == CELL_STATE_DISABLED then
slice = cellSliceDisabled
end
spriteBatchPush(textureCell,
x, y,
x + tilesetCell.tileWidth, y + tilesetCell.tileHeight,
colorWhite(),
slice.u0, slice.v0,
slice.u1, slice.v1
)
end
function backgroundDraw()
local t = (TIME.time / 40) % 1
local scaleX = screenGetWidth() / textureGrid.width
local scaleY = screenGetHeight() / textureGrid.height
local u0 = t * scaleX
local v0 = t * scaleY
local u1 = scaleX + u0
local v1 = scaleY + v0
spriteBatchPush(textureGrid,
0, 0,
screenGetWidth(), screenGetHeight(),
colorWhite(),
u0, v0,
u1, v1
)
end
function borderDraw(x, y, innerWidth, innerHeight)
-- Top Left
local uv = tilesetPositionGetUV(tilesetBorder, 0, 0)
spriteBatchPush(textureBorder,
x - tilesetBorder.tileWidth, y - tilesetBorder.tileWidth,
x, y,
colorWhite(),
uv.u0, uv.v0,
uv.u1, uv.v1
)
-- Top Right
uv = tilesetPositionGetUV(tilesetBorder, 10, 0)
spriteBatchPush(textureBorder,
x + innerWidth, y - tilesetBorder.tileHeight,
x + innerWidth + tilesetBorder.tileWidth, y,
colorWhite(),
uv.u0, uv.v0,
uv.u1, uv.v1
)
-- Bottom Left
uv = tilesetPositionGetUV(tilesetBorder, 0, 10)
spriteBatchPush(textureBorder,
x - tilesetBorder.tileWidth, y + innerHeight,
x, y + innerHeight + tilesetBorder.tileHeight,
colorWhite(),
uv.u0, uv.v0,
uv.u1, uv.v1
)
-- Bottom Right
uv = tilesetPositionGetUV(tilesetBorder, 10, 10)
spriteBatchPush(textureBorder,
x + innerWidth, y + innerHeight,
x + innerWidth + tilesetBorder.tileWidth, y + innerHeight + tilesetBorder.tileHeight,
colorWhite(),
uv.u0, uv.v0,
uv.u1, uv.v1
)
-- Top
uv = tilesetPositionGetUV(tilesetBorder, 1, 0)
spriteBatchPush(textureBorder,
x, y - tilesetBorder.tileHeight,
x + innerWidth, y,
colorWhite(),
uv.u0, uv.v0,
uv.u1, uv.v1
)
-- Bottom
uv = tilesetPositionGetUV(tilesetBorder, 1, 10)
spriteBatchPush(textureBorder,
x, y + innerHeight,
x + innerWidth, y + innerHeight + tilesetBorder.tileHeight,
colorWhite(),
uv.u0, uv.v0,
uv.u1, uv.v1
)
-- Left
uv = tilesetPositionGetUV(tilesetBorder, 0, 1)
spriteBatchPush(textureBorder,
x - tilesetBorder.tileWidth, y,
x, y + innerHeight,
colorWhite(),
uv.u0, uv.v0,
uv.u1, uv.v1
)
-- Right
uv = tilesetPositionGetUV(tilesetBorder, 10, 1)
spriteBatchPush(textureBorder,
x + innerWidth, y,
x + innerWidth + tilesetBorder.tileWidth, y + innerHeight,
colorWhite(),
uv.u0, uv.v0,
uv.u1, uv.v1
)
end
x = 0
y = 0
function sceneDispose()
end
function sceneUpdate()
x = x + inputAxis(INPUT_ACTION_LEFT, INPUT_ACTION_RIGHT)
y = y + inputAxis(INPUT_ACTION_UP, INPUT_ACTION_DOWN)
end
function sceneRender()
-- Update camera
cameraPushMatrix(camera)
camera.bottom = screenGetHeight()
camera.right = screenGetWidth()
spriteBatchPush(
nil,
x, y, x + 32, y + 32,
colorWhite()
)
-- Update mouse position
-- if INPUT_POINTER then
-- mouseX = inputGetValue(INPUT_ACTION_POINTERX) * screenGetWidth()
-- mouseY = inputGetValue(INPUT_ACTION_POINTERY) * screenGetHeight()
-- -- Draw cursor
-- spriteBatchPush(
-- nil,
-- mouseX - 2, mouseY - 2,
-- mouseX + 2, mouseY + 2,
-- colorRed(),
-- 0, 0,
-- 1, 1
-- )
-- end
-- textDraw(10, 10, "Hello World")
-- centerX = math.floor(screenGetWidth() / 2)
-- centerY = math.floor(screenGetHeight() / 2)
-- Draw elements
-- backgroundDraw()
-- borderDraw(
-- centerX - (boardWidth / 2), centerY - (boardHeight / 2),
-- boardWidth, boardHeight
-- )
-- i = 0
-- -- Foreach cell
-- local offX = centerX - (boardWidth / 2)
-- local offY = centerY - (boardHeight / 2)
-- for y = 0, sweeperRows - 1 do
-- for x = 0, sweepwerCols - 1 do
-- i = y * sweepwerCols + x
-- -- Hovered
-- if
-- cells[i] == CELL_STATE_DEFAULT and
-- mouseX >= x * tilesetCell.tileWidth + offX and mouseX < (x + 1) * tilesetCell.tileWidth + offX and
-- mouseY >= y * tilesetCell.tileHeight + offY and mouseY < (y + 1) * tilesetCell.tileHeight + offY
-- then
-- cells[i] = CELL_STATE_HOVER
-- else
-- cells[i] = CELL_STATE_DEFAULT
-- end
-- cellDraw(
-- x * tilesetCell.tileWidth + offX,
-- y * tilesetCell.tileHeight + offY,
-- cells[i]
-- )
-- end
-- end
spriteBatchFlush()
cameraPopMatrix()
end

19
assets/test.json Normal file
View File

@@ -0,0 +1,19 @@
{
"name": "Dominic",
"age": 31,
"likes": [
"thing1",
"thing2"
],
"options": {
"someParam": true,
"someSubObject": {
"someSubSubParam": 52
},
"someArray": [
1,
2,
3
]
}
}

Binary file not shown.

Binary file not shown.

BIN
assets/ui/minogram.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

View File

@@ -0,0 +1,31 @@
# Copyright (c) 2026 Dominic Masters
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
include(FetchContent)
FetchContent_Declare(
stb
GIT_REPOSITORY https://github.com/nothings/stb.git
)
# Fetch stb if not already done
FetchContent_MakeAvailable(stb)
# Find the stb_image.h header
set(STB_INCLUDE_DIR "${stb_SOURCE_DIR}")
set(STB_IMAGE_HEADER "${stb_SOURCE_DIR}/stb_image.h")
if(EXISTS "${STB_IMAGE_HEADER}")
add_library(stb_image INTERFACE)
target_include_directories(stb_image INTERFACE "${STB_INCLUDE_DIR}")
set(STB_IMAGE_FOUND TRUE)
else()
set(STB_IMAGE_FOUND FALSE)
endif()
# Standard CMake variables
set(STB_IMAGE_INCLUDE_DIRS "${STB_INCLUDE_DIR}")
set(STB_IMAGE_LIBRARIES stb_image)
mark_as_advanced(STB_IMAGE_INCLUDE_DIRS STB_IMAGE_LIBRARIES STB_IMAGE_FOUND)

View File

@@ -0,0 +1,18 @@
include(FetchContent)
if(NOT TARGET yyjson)
FetchContent_Declare(
yyjson
GIT_REPOSITORY https://github.com/ibireme/yyjson.git
GIT_TAG 0.12.0
)
FetchContent_MakeAvailable(yyjson)
endif()
# Provide an imported target if not already available
if(NOT TARGET yyjson::yyjson)
add_library(yyjson::yyjson ALIAS yyjson)
endif()
# Mark yyjson as found for find_package compatibility
set(yyjson_FOUND TRUE)

View File

@@ -0,0 +1,45 @@
# Find link platform-specific libraries
set(OpenGL_GL_PREFERENCE LEGACY)
find_package(SDL2 REQUIRED)
find_library(EGL_LIB EGL REQUIRED)
find_library(GL_LIB GL REQUIRED)
find_package(OpenGL REQUIRED)
# Setup endianess at compile time to optimize.
include(TestBigEndian)
test_big_endian(IS_BIG_ENDIAN)
if(IS_BIG_ENDIAN)
target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
DUSK_PLATFORM_ENDIAN_BIG
)
else()
target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
DUSK_PLATFORM_ENDIAN_LITTLE
)
endif()
# Link required libraries.
target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PRIVATE
SDL2
pthread
OpenGL::GLES2
${GL_LIB}
${EGL_LIB}
m
)
# Define platform-specific macros.
target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
DUSK_SDL2
DUSK_OPENGL
DUSK_OPENGL_ES
DUSK_LINUX
DUSK_DISPLAY_SIZE_DYNAMIC
DUSK_DISPLAY_WIDTH_DEFAULT=640
DUSK_DISPLAY_HEIGHT_DEFAULT=480
DUSK_DISPLAY_SCREEN_HEIGHT=240
DUSK_INPUT_KEYBOARD
DUSK_INPUT_POINTER
DUSK_INPUT_GAMEPAD
DUSK_TIME_DYNAMIC
)

View File

@@ -28,8 +28,8 @@ target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME} PUBLIC target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
DUSK_SDL2 DUSK_SDL2
DUSK_OPENGL DUSK_OPENGL
# DUSK_OPENGL_LEGACY
DUSK_LINUX DUSK_LINUX
DUSK_OPENGL_LEGACY
DUSK_DISPLAY_SIZE_DYNAMIC DUSK_DISPLAY_SIZE_DYNAMIC
DUSK_DISPLAY_WIDTH_DEFAULT=640 DUSK_DISPLAY_WIDTH_DEFAULT=640
DUSK_DISPLAY_HEIGHT_DEFAULT=480 DUSK_DISPLAY_HEIGHT_DEFAULT=480

View File

@@ -0,0 +1,29 @@
set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_SYSTEM_PROCESSOR aarch64)
set(CMAKE_C_COMPILER aarch64-linux-gnu-gcc)
set(CMAKE_CXX_COMPILER aarch64-linux-gnu-g++)
set(CMAKE_ASM_COMPILER aarch64-linux-gnu-gcc)
set(CMAKE_SYSROOT /)
set(CMAKE_C_COMPILER_TARGET aarch64-linux-gnu)
set(CMAKE_CXX_COMPILER_TARGET aarch64-linux-gnu)
set(CMAKE_FIND_ROOT_PATH
/usr/aarch64-linux-gnu
/usr/lib/aarch64-linux-gnu
/usr/include/aarch64-linux-gnu
)
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
set(ENV{PKG_CONFIG_LIBDIR} "/usr/lib/aarch64-linux-gnu/pkgconfig:/usr/share/pkgconfig")
set(ENV{PKG_CONFIG_PATH} "/usr/lib/aarch64-linux-gnu/pkgconfig")
set(CMAKE_PREFIX_PATH "/usr/aarch64-linux-gnu;/usr/lib/aarch64-linux-gnu")
# Optional: helps some Find modules
set(SDL2_DIR "/usr/lib/aarch64-linux-gnu/cmake/SDL2" CACHE PATH "")

35
docker/knulli/Dockerfile Normal file
View File

@@ -0,0 +1,35 @@
FROM debian:trixie
ENV DEBIAN_FRONTEND=noninteractive
WORKDIR /workdir
RUN dpkg --add-architecture arm64 && \
apt-get update && \
apt-get install -y --no-install-recommends \
crossbuild-essential-arm64 \
ca-certificates \
pkg-config \
cmake \
make \
ninja-build \
git \
file \
python3 \
python3-pip \
python3-polib \
python3-pil \
python3-dotenv \
python3-pyqt5 \
python3-opengl \
liblua5.4-dev:arm64 \
xz-utils:arm64 \
libbz2-dev:arm64 \
zlib1g-dev:arm64 \
libzip-dev:arm64 \
libssl-dev:arm64 \
libsdl2-dev:arm64 \
liblzma-dev:arm64 \
libopengl0:arm64 \
libgl1:arm64 \
libegl1:arm64 \
libgles2:arm64 \
libgl1-mesa-dev:arm64 && \
rm -rf /var/lib/apt/lists/*

3
scripts/build-knulli-docker.sh Executable file
View File

@@ -0,0 +1,3 @@
#!/bin/bash
docker build -t dusk-knulli -f docker/knulli/Dockerfile .
docker run --rm -v $(pwd):/workdir dusk-knulli /bin/bash -c "./scripts/build-knulli.sh"

24
scripts/build-knulli.sh Executable file
View File

@@ -0,0 +1,24 @@
#!/bin/bash
cmake -S . -B build-knulli -G Ninja \
-DDUSK_BUILD_TESTS=ON \
-DDUSK_TARGET_SYSTEM=knulli \
-DCMAKE_TOOLCHAIN_FILE=./cmake/toolchains/aarch64-linux-gnu.cmake \
-DCMAKE_BUILD_TYPE=Release
cmake --build build-knulli -- -j$(nproc)
# Copy necessary libs out
mkdir -p ./build-knulli/dusk
cp ./build-knulli/Dusk ./build-knulli/dusk/Dusk
cp ./build-knulli/dusk.dsk ./build-knulli/dusk/dusk.dsk
echo '#!/bin/bash' > build-knulli/dusk/Dusk.sh
echo 'cd "$(dirname "$(readlink -f "$0")")"' >> build-knulli/dusk/Dusk.sh
echo 'export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$(dirname "$(readlink -f "$0")")' >> build-knulli/dusk/Dusk.sh
echo 'export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/lib/gl4es' >> build-knulli/dusk/Dusk.sh
echo 'export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/lib' >> build-knulli/dusk/Dusk.sh
echo '$(dirname "$(readlink -f "$0")")/Dusk' >> build-knulli/dusk/Dusk.sh
chmod +x build-knulli/dusk/Dusk.sh
cp /usr/lib/aarch64-linux-gnu/liblua5.4.so.0 build-knulli/dusk/
# cp /usr/lib/aarch64-linux-gnu/libSDL2-2.0.so.0 build-knulli/dusk/
# cp /usr/lib/aarch64-linux-gnu/libGL.so.1 build-knulli/dusk/
# cp /usr/lib/aarch64-linux-gnu/libEGL.so.1 build-knulli/dusk/
# cp /usr/lib/aarch64-linux-gnu/libGLESv2.so.2 build-knulli/dusk/

View File

@@ -4,8 +4,10 @@
# https://opensource.org/licenses/MIT # https://opensource.org/licenses/MIT
add_subdirectory(dusk) add_subdirectory(dusk)
# add_subdirectory(duskrpg)
add_subdirectory(dusktrivia)
if(DUSK_TARGET_SYSTEM STREQUAL "linux") if(DUSK_TARGET_SYSTEM STREQUAL "linux" OR DUSK_TARGET_SYSTEM STREQUAL "knulli")
add_subdirectory(dusklinux) add_subdirectory(dusklinux)
add_subdirectory(dusksdl2) add_subdirectory(dusksdl2)
add_subdirectory(duskgl) add_subdirectory(duskgl)

View File

@@ -14,6 +14,24 @@ if(NOT libzip_FOUND)
target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PUBLIC zip) target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PUBLIC zip)
endif() endif()
if(NOT stb_image_FOUND)
find_package(stb REQUIRED)
if(STB_IMAGE_FOUND)
target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PUBLIC stb_image)
else()
message(FATAL_ERROR "stb_image not found. Please ensure stb is correctly fetched.")
endif()
endif()
if(NOT yyjson_FOUND)
find_package(yyjson REQUIRED)
if(yyjson_FOUND)
target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PUBLIC yyjson::yyjson)
else()
message(FATAL_ERROR "yyjson not found. Please ensure yyjson is correctly fetched.")
endif()
endif()
if(NOT Lua_FOUND) if(NOT Lua_FOUND)
find_package(Lua REQUIRED) find_package(Lua REQUIRED)
if(Lua_FOUND AND NOT TARGET Lua::Lua) if(Lua_FOUND AND NOT TARGET Lua::Lua)
@@ -52,12 +70,9 @@ add_subdirectory(engine)
add_subdirectory(error) add_subdirectory(error)
add_subdirectory(event) add_subdirectory(event)
add_subdirectory(input) add_subdirectory(input)
add_subdirectory(item)
add_subdirectory(locale) add_subdirectory(locale)
add_subdirectory(map)
add_subdirectory(scene) add_subdirectory(scene)
add_subdirectory(script) add_subdirectory(script)
add_subdirectory(story)
add_subdirectory(time) add_subdirectory(time)
add_subdirectory(ui) add_subdirectory(ui)
add_subdirectory(util) add_subdirectory(util)

View File

@@ -7,6 +7,7 @@
#include "assert.h" #include "assert.h"
#include "log/log.h" #include "log/log.h"
#include "util/string.h"
#ifndef DUSK_ASSERTIONS_FAKED #ifndef DUSK_ASSERTIONS_FAKED
#ifdef DUSK_TEST_ASSERT #ifdef DUSK_TEST_ASSERT
@@ -98,4 +99,14 @@
) { ) {
assertUnreachableImpl(file, line, message); assertUnreachableImpl(file, line, message);
} }
void assertStringEqualImpl(
const char *file,
const int32_t line,
const char *a,
const char *b,
const char *message
) {
assertTrueImpl(file, line, stringCompare(a, b) == 0, message);
}
#endif #endif

View File

@@ -104,6 +104,23 @@
const char *message const char *message
); );
/**
* Asserts two strings to be equal.
*
* @param file File that the assertion is being made from.
* @param line Line that the assertion is being made from.
* @param a First string to compare.
* @param b Second string to compare.
* @param message Message to throw against assertion failure.
*/
void assertStringEqualImpl(
const char *file,
const int32_t line,
const char *a,
const char *b,
const char *message
);
/** /**
* Asserts a given value to be true. * Asserts a given value to be true.
* *
@@ -178,6 +195,16 @@
#define assertStrLenMin(str, len, message) \ #define assertStrLenMin(str, len, message) \
assertTrue(strlen(str) >= len, message) assertTrue(strlen(str) >= len, message)
/**
* Asserts two strings to be equal.
*
* @param a First string to compare.
* @param b Second string to compare.
* @param message Message to throw against assertion failure.
*/
#define assertStringEqual(a, b, message) \
assertStringEqualImpl(__FILE__, __LINE__, a, b, message)
#else #else
// If assertions are faked, we define the macros to do nothing. // If assertions are faked, we define the macros to do nothing.
#define assertTrue(x, message) ((void)0) #define assertTrue(x, message) ((void)0)

View File

@@ -7,7 +7,8 @@
target_sources(${DUSK_LIBRARY_TARGET_NAME} target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC PUBLIC
asset.c asset.c
assetfile.c
) )
# Subdirs # Subdirs
add_subdirectory(type) add_subdirectory(loader)

View File

@@ -9,7 +9,6 @@
#include "util/memory.h" #include "util/memory.h"
#include "util/string.h" #include "util/string.h"
#include "assert/assert.h" #include "assert/assert.h"
#include "asset/assettype.h"
#include "engine/engine.h" #include "engine/engine.h"
#include "util/string.h" #include "util/string.h"
@@ -33,107 +32,20 @@ bool_t assetFileExists(const char_t *filename) {
return true; return true;
} }
errorret_t assetLoad(const char_t *filename, void *output) { errorret_t assetLoad(
const char_t *filename,
assetfileloader_t loader,
void *params,
void *output
) {
assertStrLenMax(filename, FILENAME_MAX, "Filename too long."); assertStrLenMax(filename, FILENAME_MAX, "Filename too long.");
assertNotNull(output, "Output pointer cannot be NULL."); assertNotNull(output, "Output pointer cannot be NULL.");
assertNotNull(loader, "Asset file loader cannot be NULL.");
// Determine the asset type by reading the extension assetfile_t file;
const assettypedef_t *def = NULL; errorChain(assetFileInit(&file, filename, params, output));
for(uint_fast8_t i = 0; i < ASSET_TYPE_COUNT; i++) { errorChain(loader(&file));
const assettypedef_t *cmp = &ASSET_TYPE_DEFINITIONS[i]; errorChain(assetFileDispose(&file));
assertNotNull(cmp, "Asset type definition cannot be NULL.");
if(cmp->extension == NULL) continue;
if(!stringEndsWithCaseInsensitive(filename, cmp->extension)) continue;
def = cmp;
break;
}
if(def == NULL) {
errorThrow("Unknown asset type for file: %s", filename);
}
// Get file size of the asset.
zip_stat_t st;
zip_stat_init(&st);
if(!zip_stat(ASSET.zip, filename, 0, &st) == 0) {
errorThrow("Failed to stat asset file: %s", filename);
}
// Minimum file size.
zip_int64_t fileSize = (zip_int64_t)st.size;
if(fileSize <= 0) {
errorThrow("Asset file is empty: %s", filename);
}
// Try to open the file
zip_file_t *file = zip_fopen(ASSET.zip, filename, 0);
if(file == NULL) {
errorThrow("Failed to open asset file: %s", filename);
}
// Load the asset data
switch(def->loadStrategy) {
case ASSET_LOAD_STRAT_ENTIRE:
assertNotNull(def->entire, "Asset load function cannot be NULL.");
// Must have more to read
if(fileSize <= 0) {
zip_fclose(file);
errorThrow("No data remaining to read for asset: %s", filename);
}
if(fileSize > def->dataSize) {
zip_fclose(file);
errorThrow(
"Asset file has too much data remaining after header: %s",
filename
);
}
// Create space to read the entire asset data
void *data = memoryAllocate(fileSize);
if(!data) {
zip_fclose(file);
errorThrow(
"Failed to allocate memory for asset data of file: %s", filename
);
}
// Read in the asset data.
zip_int64_t bytesRead = zip_fread(file, data, fileSize);
if(bytesRead == 0 || bytesRead > fileSize) {
memoryFree(data);
zip_fclose(file);
errorThrow("Failed to read asset data for file: %s", filename);
}
fileSize -= bytesRead;
// Close the file now we have the data
zip_fclose(file);
// Pass to the asset type loader
assetentire_t entire = {
.data = data,
.output = output
};
errorret_t ret = def->entire(entire);
memoryFree(data);
errorChain(ret);
break;
case ASSET_LOAD_STRAT_CUSTOM:
assertNotNull(def->custom, "Asset load function cannot be NULL.");
assetcustom_t customData = {
.zipFile = file,
.output = output
};
errorChain(def->custom(customData));
break;
default:
assertUnreachable("Unknown asset load strategy.");
}
errorOk(); errorOk();
} }

View File

@@ -7,8 +7,8 @@
#pragma once #pragma once
#include "error/error.h" #include "error/error.h"
#include "assettype.h"
#include "asset/assetplatform.h" #include "asset/assetplatform.h"
#include "assetfile.h"
#ifndef assetInitPlatform #ifndef assetInitPlatform
#error "Platform must define assetInitPlatform function." #error "Platform must define assetInitPlatform function."
@@ -20,7 +20,7 @@
#define ASSET_FILE_NAME "dusk.dsk" #define ASSET_FILE_NAME "dusk.dsk"
#define ASSET_HEADER_SIZE 3 #define ASSET_HEADER_SIZE 3
typedef struct { typedef struct asset_s {
zip_t *zip; zip_t *zip;
assetplatform_t platform; assetplatform_t platform;
} asset_t; } asset_t;
@@ -41,13 +41,20 @@ errorret_t assetInit(void);
bool_t assetFileExists(const char_t *filename); bool_t assetFileExists(const char_t *filename);
/** /**
* Loads an asset by its filename, the output type depends on the asset type. * Loads an asset by its filename,
* *
* @param filename The filename of the asset to retrieve. * @param filename The filename of the asset to retrieve.
* @param loader Loader to use for loading the asset file.
* @param params Parameters to pass to the loader.
* @param output The output pointer to store the loaded asset data. * @param output The output pointer to store the loaded asset data.
* @return An error code if the asset could not be loaded. * @return An error code if the asset could not be loaded.
*/ */
errorret_t assetLoad(const char_t *filename, void *output); errorret_t assetLoad(
const char_t *filename,
assetfileloader_t loader,
void *params,
void *output
);
/** /**
* Disposes/cleans up the asset system. * Disposes/cleans up the asset system.

309
src/dusk/asset/assetfile.c Normal file
View File

@@ -0,0 +1,309 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "asset/asset.h"
#include "assert/assert.h"
#include "util/memory.h"
errorret_t assetFileInit(
assetfile_t *file,
const char_t *filename,
void *params,
void *output
) {
memoryZero(file, sizeof(assetfile_t));
file->filename = filename;
file->params = params;
file->output = output;
// Stat the file
zip_stat_init(&file->stat);
if(!zip_stat(ASSET.zip, filename, 0, &file->stat) == 0) {
errorThrow("Failed to stat asset file: %s", filename);
}
// Minimum file size.
file->size = (zip_int64_t)file->stat.size;
if(file->size <= 0) {
errorThrow("Invalid asset file size: %s", filename);
}
errorOk();
}
errorret_t assetFileRewind(assetfile_t *file) {
assertNotNull(file, "Asset file cannot be NULL.");
assertNotNull(file->zipFile, "Asset file must be opened before rewinding.");
if(file->position == 0) {
errorOk();
}
errorChain(assetFileClose(file));
errorChain(assetFileOpen(file));
errorOk();
}
errorret_t assetFileOpen(assetfile_t *file) {
assertNotNull(file, "Asset file cannot be NULL.");
assertNotNull(file->filename, "Asset file filename cannot be NULL.");
assertNotNull(ASSET.zip, "Asset zip cannot be NULL.");
assertNull(file->zipFile, "Asset file already open.");
file->zipFile = zip_fopen(ASSET.zip, file->filename, 0);
if(file->zipFile == NULL) {
errorThrow("Failed to open asset file: %s", file->filename);
}
file->position = 0;
errorOk();
}
errorret_t assetFileRead(
assetfile_t *file,
void *buffer,
const size_t bufferSize
) {
assertNotNull(file, "Asset file cannot be NULL.");
assertNotNull(file->zipFile, "Asset file must be opened before reading.");
// I assume zip_fread takes buffer NULL for skipping?
zip_int64_t bytesRead = zip_fread(file->zipFile, buffer, bufferSize);
if(bytesRead < 0) {
errorThrow("Failed to read from asset file: %s", file->filename);
}
file->position += bytesRead;
file->lastRead = bytesRead;
errorOk();
}
errorret_t assetFileClose(assetfile_t *file) {
assertNotNull(file, "Asset file cannot be NULL.");
assertNotNull(file->zipFile, "Asset file must be opened before closing.");
if(zip_fclose(file->zipFile) != 0) {
errorThrow("Failed to close asset file: %s", file->filename);
}
file->zipFile = NULL;
file->position = 0;
errorOk();
}
errorret_t assetFileDispose(assetfile_t *file) {
if(file->zipFile != NULL) {
errorChain(assetFileClose(file));
}
memoryZero(file, sizeof(assetfile_t));
errorOk();
}
// Line Reader;
void assetFileLineReaderInit(
assetfilelinereader_t *reader,
assetfile_t *file,
uint8_t *readBuffer,
const size_t readBufferSize,
uint8_t *outBuffer,
const size_t outBufferSize
) {
assertNotNull(reader, "Line reader cannot be NULL.");
assertNotNull(file, " File cannot be NULL.");
assertNotNull(readBuffer, "Read buffer cannot be NULL.");
assertNotNull(outBuffer, "Output buffer cannot be NULL.");
assertTrue(readBufferSize > 0, "Read buffer size must be greater than 0.");
assertTrue(outBufferSize > 0, "Output buffer size must be greater than 0.");
memoryZero(reader, sizeof(assetfilelinereader_t));
reader->file = file;
reader->readBuffer = readBuffer;
reader->readBufferSize = readBufferSize;
reader->outBuffer = outBuffer;
reader->outBufferSize = outBufferSize;
}
size_t assetFileLineReaderUnreadBytes(const assetfilelinereader_t *reader) {
assertNotNull(reader, "Reader cannot be NULL.");
assertTrue(reader->bufferEnd >= reader->bufferStart, "Invalid buffer state.");
return reader->bufferEnd - reader->bufferStart;
}
const uint8_t *assetFileLineReaderUnreadPtr(const assetfilelinereader_t *reader) {
assertNotNull(reader, "Reader cannot be NULL.");
assertNotNull(reader->readBuffer, "Read buffer cannot be NULL.");
return reader->readBuffer + reader->bufferStart;
}
static errorret_t assetFileLineReaderAppend(
assetfilelinereader_t *reader,
const uint8_t *src,
size_t srcLength
) {
assertNotNull(reader, "Reader cannot be NULL.");
assertNotNull(reader->outBuffer, "Out buffer cannot be NULL.");
if(srcLength == 0) {
errorOk();
}
/* reserve room for optional NUL terminator */
if (reader->lineLength + srcLength >= reader->outBufferSize) {
errorThrow("Line length exceeds output buffer size.");
}
memoryCopy(reader->outBuffer + reader->lineLength, src, srcLength);
reader->lineLength += srcLength;
errorOk();
}
static void assetFileLineReaderTerminate(assetfilelinereader_t *reader) {
assertNotNull(reader, "Reader cannot be NULL.");
assertNotNull(reader->outBuffer, "Out buffer cannot be NULL.");
assertTrue(reader->lineLength < reader->outBufferSize, "Line length exceeds out buffer.");
reader->outBuffer[reader->lineLength] = '\0';
}
static ssize_t assetFileLineReaderFindNewline(const assetfilelinereader_t *reader) {
size_t i;
assertNotNull(reader, "Reader cannot be NULL.");
assertNotNull(reader->readBuffer, "Read buffer cannot be NULL.");
for (i = reader->bufferStart; i < reader->bufferEnd; ++i) {
if (reader->readBuffer[i] == '\n') {
return (ssize_t)i;
}
}
return -1;
}
errorret_t assetFileLineReaderFill(assetfilelinereader_t *reader) {
assertNotNull(reader, "Reader cannot be NULL.");
assertNotNull(reader->file, "File cannot be NULL.");
assertNotNull(reader->readBuffer, "Read buffer cannot be NULL.");
if(reader->eof) errorOk();
errorret_t ret;
size_t unreadBytes = assetFileLineReaderUnreadBytes(reader);
/* If buffer is fully consumed, refill from start. */
if (unreadBytes == 0) {
reader->bufferStart = 0;
reader->bufferEnd = 0;
errorChain(assetFileRead(
reader->file,
reader->readBuffer,
reader->readBufferSize
));
if(reader->file->lastRead == 0) {
reader->eof = true;
errorOk();
}
reader->bufferStart = 0;
reader->bufferEnd = reader->file->lastRead;
errorOk();
}
/*
* There are unread bytes left but no newline in them.
* If bufferStart > 0, slide unread bytes to front so we can read more.
* This only happens when necessary to make space.
*/
if(reader->bufferEnd == reader->readBufferSize) {
if(reader->bufferStart == 0) {
/*
* Entire read buffer is unread and contains no newline.
* Caller must have a large enough outBuffer to accumulate across fills,
* so we consume these bytes into outBuffer before refilling.
*/
errorOk();
}
memoryMove(
reader->readBuffer,
reader->readBuffer + reader->bufferStart,
unreadBytes
);
reader->bufferStart = 0;
reader->bufferEnd = unreadBytes;
}
errorChain(assetFileRead(
reader->file,
reader->readBuffer + reader->bufferEnd,
reader->readBufferSize - reader->bufferEnd
));
if(reader->file->lastRead == 0) {
reader->eof = true;
errorOk();
}
reader->bufferEnd += reader->file->lastRead;
errorOk();
}
errorret_t assetFileLineReaderNext(assetfilelinereader_t *reader) {
assertNotNull(reader, "Reader cannot be NULL.");
assertNotNull(reader->file, "File cannot be NULL.");
assertNotNull(reader->readBuffer, "Read buffer cannot be NULL.");
assertNotNull(reader->outBuffer, "Out buffer cannot be NULL.");
reader->lineLength = 0;
for (;;) {
ssize_t newlineIndex = assetFileLineReaderFindNewline(reader);
if (newlineIndex >= 0) {
size_t chunkLength = (size_t)newlineIndex - reader->bufferStart;
errorret_t ret;
/* strip CR in CRLF */
if (chunkLength > 0 && reader->readBuffer[(size_t)newlineIndex - 1] == '\r') {
chunkLength--;
}
errorChain(assetFileLineReaderAppend(
reader,
reader->readBuffer + reader->bufferStart,
chunkLength
));
reader->bufferStart = (size_t)newlineIndex + 1;
assetFileLineReaderTerminate(reader);
errorOk();
}
if (assetFileLineReaderUnreadBytes(reader) > 0) {
errorChain(assetFileLineReaderAppend(
reader,
assetFileLineReaderUnreadPtr(reader),
assetFileLineReaderUnreadBytes(reader)
));
reader->bufferStart = reader->bufferEnd;
}
if(reader->eof) {
if(reader->lineLength > 0) {
assetFileLineReaderTerminate(reader);
errorOk();
}
errorThrow("End of file reached.");
}
errorChain(assetFileLineReaderFill(reader));
}
}

138
src/dusk/asset/assetfile.h Normal file
View File

@@ -0,0 +1,138 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "error/error.h"
#include <zip.h>
typedef struct assetfile_s assetfile_t;
typedef errorret_t (*assetfileloader_t)(assetfile_t *file);
typedef struct assetfile_s {
const char_t *filename;
void *params;
void *output;
zip_stat_t stat;
zip_int64_t size;
zip_int64_t position;
zip_int64_t lastRead;
zip_file_t *zipFile;
} assetfile_t;
/**
* Initializes the asset file structure in preparation for loading. This will
* stat the file but not open the handle.
*
* @param file The asset file structure to initialize.
* @param filename The name of the asset file to load.
* @param params Optional loader params.
* @param output Output pointer for the loader.
* @return Error indicating success or failure.
*/
errorret_t assetFileInit(
assetfile_t *file,
const char_t *filename,
void *params,
void *output
);
/**
* Opens the asset file for reading. After opening the loader is responsible
* for closing the file.
*
* @param file The asset file to open.
* @return An error code if the file could not be opened.
*/
errorret_t assetFileOpen(assetfile_t *file);
/**
* Rewind the file to the initial position.
*
* @param file The asset file to rewind.
*/
errorret_t assetFileRewind(assetfile_t *file);
/**
* Read bytes from the asset file. Assumes the file has already been opened
* prior to trying to read anything.
*
* @param file File to read from.
* @param buffer Buffer to read the file data into., or NULL to skip bytes.
* @param size Size of the buffer to read into.
*/
errorret_t assetFileRead(
assetfile_t *file,
void *buffer,
const size_t bufferSize
);
/**
* Closes the asset file and releases any resources associated with it.
*
* @param file The asset file to close.
* @return An error code if the file could not be closed properly.
*/
errorret_t assetFileClose(assetfile_t *file);
/**
* Disposes the asset file structure, closing any open handles and zeroing
* out the structure.
*
* @param file The asset file to dispose.
* @return An error code if the file could not be disposed properly.
*/
errorret_t assetFileDispose(assetfile_t *file);
typedef struct {
assetfile_t *file;
uint8_t *readBuffer;
size_t readBufferSize;
uint8_t *outBuffer;
size_t outBufferSize;
// A
size_t bufferStart;
size_t bufferEnd;
bool_t eof;//?
// Updated each reach:
size_t lineLength;
} assetfilelinereader_t;
/**
* Initializes a line reader for the given asset file. The line reader will read
* lines from the file into the provided line buffer, using the provided buffer
* for reading chunks of the file.
*
* @param file The asset file to read from. Must already be opened.
* @param readBuffer Buffer to use for reading chunks of the file.
* @param readBufferSize Size of the read buffer.
* @param outBuffer Buffer to read lines into. Lines will be null-terminated.
* @param outBufferSize Size of the output buffer.
* @return An initialized line reader structure.
*/
void assetFileLineReaderInit(
assetfilelinereader_t *reader,
assetfile_t *file,
uint8_t *readBuffer,
const size_t readBufferSize,
uint8_t *outBuffer,
const size_t outBufferSize
);
/**
* Reads the next line from the asset file into the line buffer. The line
* buffer is null-terminated and does not include the newline character.
*
* @param reader The line reader to read from.
* @return An error code if a failure occurs, or errorOk() if a line was read
* successfully. If the end of the file is reached, errorEndOfFile() is
* returned.
*/
errorret_t assetFileLineReaderNext(assetfilelinereader_t *reader);

View File

@@ -1,106 +0,0 @@
/**
* Copyright (c) 2025 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "type/assettexture.h"
// #include "type/assetpalette.h"
#include "type/assettileset.h"
#include "type/assetlanguage.h"
#include "type/assetscript.h"
#include "type/assetmap.h"
#include "type/assetmapchunk.h"
#include <zip.h>
typedef enum {
ASSET_TYPE_NULL,
ASSET_TYPE_TEXTURE,
// ASSET_TYPE_PALETTE,
ASSET_TYPE_TILESET,
ASSET_TYPE_LANGUAGE,
ASSET_TYPE_SCRIPT,
ASSET_TYPE_MAP,
ASSET_TYPE_MAP_CHUNK,
ASSET_TYPE_COUNT,
} assettype_t;
typedef enum {
ASSET_LOAD_STRAT_ENTIRE,
ASSET_LOAD_STRAT_CUSTOM
} assetloadstrat_t;
typedef struct assetentire_s {
void *data;
void *output;
} assetentire_t;
typedef struct assetcustom_s {
zip_file_t *zipFile;
void *output;
} assetcustom_t;
typedef struct {
const char_t *extension;
const size_t dataSize;
const assetloadstrat_t loadStrategy;
union {
errorret_t (*entire)(assetentire_t entire);
errorret_t (*custom)(assetcustom_t custom);
};
} assettypedef_t;
static const assettypedef_t ASSET_TYPE_DEFINITIONS[ASSET_TYPE_COUNT] = {
[ASSET_TYPE_NULL] = {
0
},
[ASSET_TYPE_TEXTURE] = {
.extension = "dpt",
.loadStrategy = ASSET_LOAD_STRAT_ENTIRE,
.dataSize = sizeof(assettexture_t),
.entire = assetTextureLoad
},
// [ASSET_TYPE_PALETTE] = {
// .extension = "dpf",
// .loadStrategy = ASSET_LOAD_STRAT_ENTIRE,
// .dataSize = sizeof(palette_t),
// .entire = assetPaletteLoad
// },
[ASSET_TYPE_TILESET] = {
.extension = "dtf",
.loadStrategy = ASSET_LOAD_STRAT_ENTIRE,
.dataSize = sizeof(assettileset_t),
.entire = assetTilesetLoad
},
[ASSET_TYPE_LANGUAGE] = {
.extension = "DLF",
.loadStrategy = ASSET_LOAD_STRAT_CUSTOM,
.custom = assetLanguageHandler
},
[ASSET_TYPE_SCRIPT] = {
.extension = "lua",
.loadStrategy = ASSET_LOAD_STRAT_CUSTOM,
.custom = assetScriptHandler
},
// [ASSET_TYPE_MAP] = {
// .extension = "DMF",
// .loadStrategy = ASSET_LOAD_STRAT_CUSTOM,
// .custom = assetMapHandler
// },
// [ASSET_TYPE_MAP_CHUNK] = {
// .extension = "DMC",
// .loadStrategy = ASSET_LOAD_STRAT_CUSTOM,
// .custom = assetMapChunkHandler
// },
};

View File

@@ -0,0 +1,12 @@
# Copyright (c) 2026 Dominic Masters
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
# Sources
# Subdirs
add_subdirectory(display)
add_subdirectory(locale)
add_subdirectory(script)
add_subdirectory(json)

View File

@@ -0,0 +1,11 @@
# Copyright (c) 2026 Dominic Masters
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
# Sources
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
assettextureloader.c
assettilesetloader.c
)

View File

@@ -0,0 +1,115 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "assettextureloader.h"
#include "assert/assert.h"
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#include "log/log.h"
#include "util/endian.h"
stbi_io_callbacks ASSET_TEXTURE_STB_CALLBACKS = {
.read = assetTextureReader,
.skip = assetTextureSkipper,
.eof = assetTextureEOF
};
int assetTextureReader(void *user, char *data, int size) {
assertNotNull(data, "Data buffer for stb_image callbacks cannot be NULL.");
assetfile_t *file = (assetfile_t*)user;
assertNotNull(file, "Asset file in stb_image callbacks cannot be NULL.");
errorret_t ret = assetFileRead(file, data, (size_t)size);
if(ret.code != ERROR_OK) {
errorCatch(errorPrint(ret));
return -1;
}
return file->lastRead;
}
void assetTextureSkipper(void *user, int n) {
assetfile_t *file = (assetfile_t*)user;
assertNotNull(file, "Asset file in stb_image callbacks cannot be NULL.");
errorret_t ret = assetFileRead(file, NULL, (size_t)n);
if(ret.code != ERROR_OK) {
errorCatch(errorPrint(ret));
}
}
int assetTextureEOF(void *user) {
assetfile_t *file = (assetfile_t*)user;
assertNotNull(file, "Asset file in stb_image callbacks cannot be NULL.");
return file->position >= file->size;
}
errorret_t assetTextureLoader(assetfile_t *file) {
assertNotNull(file, "Asset file cannot be NULL.");
assertNotNull(file->params, "Asset file parameters cannot be NULL.");
assertNotNull(file->output, "Asset file output cannot be NULL.");
assettextureloaderparams_t *p = (assettextureloaderparams_t*)file->params;
assertNotNull(p, "Asset texture loader parameters cannot be NULL.");
int channelsDesired;
switch(p->format) {
case TEXTURE_FORMAT_RGBA:
channelsDesired = 4;
break;
default:
errorThrow("Bad texture format.");
}
int width, height, channels;
errorChain(assetFileOpen(file));
uint8_t *data = stbi_load_from_callbacks(
&ASSET_TEXTURE_STB_CALLBACKS,
file,
&width,
&height,
&channels,
channelsDesired
);
errorChain(assetFileClose(file));
if(data == NULL) {
const char_t *errorStr = stbi_failure_reason();
errorThrow("Failed to load texture from file %s.", errorStr);
}
// Fixes a specific bug probably with Dolphin but for now just assuming endian
if(!isHostLittleEndian()) {
stbi__vertical_flip(data, width, height, channelsDesired);
}
errorChain(textureInit(
(texture_t*)file->output,
(int32_t)width, (int32_t)height,
p->format,
(texturedata_t){
.rgbaColors = (color_t*)data
}
));
stbi_image_free(data);
errorOk();
}
errorret_t assetTextureLoad(
const char_t *path,
texture_t *out,
const textureformat_t format
) {
assettextureloaderparams_t params = {
.format = format
};
return assetLoad(path, assetTextureLoader, &params, out);
}

View File

@@ -0,0 +1,50 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "asset/asset.h"
#include "display/texture/texture.h"
typedef struct {
textureformat_t format;
} assettextureloaderparams_t;
/**
* STB image read callback for asset files.
*
* @param user User data passed to the callback, should be an assetfile_t*.
* @param data Buffer to read the file data into.
* @param size Size of the buffer to read into.
* @return Number of bytes read, or -1 on error.
*/
int assetTextureReader(void *user, char *data, int size);
void assetTextureSkipper(void *user, int n);
int assetTextureEOF(void *user);
/**
* Handler for texture assets.
*
* @param file Asset file to load the texture from.
* @return Any error that occurs during loading.
*/
errorret_t assetTextureLoader(assetfile_t *file);
/**
* Loads a texture from the specified path.
*
* @param path Path to the texture asset.
* @param out Output texture to load into.
* @param format Format of the texture to load.
* @return Any error that occurs during loading.
*/
errorret_t assetTextureLoad(
const char_t *path,
texture_t *out,
const textureformat_t format
);

View File

@@ -0,0 +1,80 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "assettilesetloader.h"
#include "assert/assert.h"
#include "util/memory.h"
#include "util/endian.h"
errorret_t assetTilesetLoader(assetfile_t *file) {
assertNotNull(file, "Asset file pointer for tileset loader is null.");
tileset_t *out = (tileset_t *)file->output;
assertNotNull(out, "Output pointer for tileset loader is null.");
uint8_t *entire = memoryAllocate(file->size);
errorChain(assetFileOpen(file));
errorChain(assetFileRead(file, entire, file->size));
errorChain(assetFileClose(file));
assertTrue(file->lastRead == file->size, "Failed to read entire file.");
if(
entire[0] != 'D' ||
entire[1] != 'T' ||
entire[2] != 'F'
) {
errorThrow("Invalid tileset header");
}
if(entire[3] != 0x00) {
errorThrow("Unsupported tileset version");
}
// Fix endianness
out->tileWidth = endianLittleToHost16(*(uint16_t *)(entire + 4));
out->tileHeight = endianLittleToHost16(*(uint16_t *)(entire + 6));
out->columns = endianLittleToHost16(*(uint16_t *)(entire + 8));
out->rows = endianLittleToHost16(*(uint16_t *)(entire + 10));
// out->right = endianLittleToHost16(*(uint16_t *)(entire + 12));
// out->bottom = endianLittleToHost16(*(uint16_t *)(entire + 14));
if(out->tileWidth == 0) {
errorThrow("Tile width cannot be 0");
}
if(out->tileHeight == 0) {
errorThrow("Tile height cannot be 0");
}
if(out->columns == 0) {
errorThrow("Column count cannot be 0");
}
if(out->rows == 0) {
errorThrow("Row count cannot be 0");
}
out->uv[0] = endianLittleToHostFloat(*(float *)(entire + 16));
out->uv[1] = endianLittleToHostFloat(*(float *)(entire + 20));
if(out->uv[1] < 0.0f || out->uv[1] > 1.0f) {
errorThrow("Invalid v0 value in tileset");
}
// Setup tileset
out->tileCount = out->columns * out->rows;
memoryFree(entire);
errorOk();
}
errorret_t assetTilesetLoad(
const char_t *path,
tileset_t *out
) {
return assetLoad(path, assetTilesetLoader, NULL, out);
}

View File

@@ -0,0 +1,30 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "asset/asset.h"
#include "display/texture/tileset.h"
/**
* Handler for tileset assets.
*
* @param file Asset file to load the tileset from.
* @return Any error that occurs during loading.
*/
errorret_t assetTilesetLoader(assetfile_t *file);
/**
* Loads a tileset from the specified path.
*
* @param path Path to the tileset asset.
* @param out Output tileset to load into.
* @return Any error that occurs during loading.
*/
errorret_t assetTilesetLoad(
const char_t *path,
tileset_t *out
);

View File

@@ -0,0 +1,10 @@
# Copyright (c) 2026 Dominic Masters
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
# Sources
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
assetjsonloader.c
)

View File

@@ -0,0 +1,53 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "assetjsonloader.h"
#include "util/memory.h"
#include "assert/assert.h"
errorret_t assetJsonLoadFileToDoc(assetfile_t *file, yyjson_doc **outDoc) {
assertNotNull(file, "Asset file pointer for JSON loader is null.");
assertNotNull(outDoc, "Output pointer for JSON loader is null.");
if(file->size > ASSET_JSON_FILE_SIZE_MAX) {
errorThrow("JSON exceeds maximum allowed size");
}
// Create buffer
uint8_t *buffer = memoryAllocate(file->size);
errorChain(assetFileOpen(file));
// Read entire file
errorChain(assetFileRead(file, buffer, file->size));
assertTrue(file->lastRead == file->size, "Failed to read entire JSON file.");
errorChain(assetFileClose(file));
*outDoc = yyjson_read(
buffer,
file->size,
YYJSON_READ_ALLOW_COMMENTS | YYJSON_READ_ALLOW_TRAILING_COMMAS
);
memoryFree(buffer);
if(!*outDoc) errorThrow("Failed to parse JSON");
errorOk();
}
errorret_t assetJsonLoader(assetfile_t *file) {
yyjson_doc **outDoc = (yyjson_doc **)file->output;
assertNotNull(outDoc, "Output pointer for JSON loader is null.");
return assetJsonLoadFileToDoc(file, outDoc);
}
errorret_t assetJsonLoad(
const char_t *path,
yyjson_doc **outDoc
) {
return assetLoad(path, assetJsonLoader, NULL, outDoc);
}

View File

@@ -0,0 +1,45 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "asset/asset.h"
#include "yyjson.h"
#define ASSET_JSON_FILE_SIZE_MAX 1024*256
typedef struct {
void *nothing;
} assetjsonloaderparams_t;
/**
* Loads a JSON document from the specified asset file.
*
* @param file Asset file to load the JSON document from.
* @param outDoc Pointer to store the loaded JSON document.
* @return Any error that occurs during loading.
*/
errorret_t assetJsonLoadFileToDoc(assetfile_t *file, yyjson_doc **outDoc);
/**
* Handler for locale assets.
*
* @param file Asset file to load the locale from.
* @return Any error that occurs during loading.
*/
errorret_t assetJsonLoader(assetfile_t *file);
/**
* Loads a locale from the specified path.
*
* @param path Path to the locale asset.
* @param outDoc Pointer to store the loaded JSON document.
* @return Any error that occurs during loading.
*/
errorret_t assetJsonLoad(
const char_t *path,
yyjson_doc **outDoc
);

View File

@@ -0,0 +1,10 @@
# Copyright (c) 2026 Dominic Masters
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
# Sources
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
assetlocaleloader.c
)

View File

@@ -0,0 +1,807 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "assetlocaleloader.h"
#include "util/memory.h"
#include "util/math.h"
#include "util/string.h"
#include "assert/assert.h"
errorret_t assetLocaleFileInit(
assetlocalefile_t *localeFile,
const char_t *path
) {
assertNotNull(localeFile, "Locale file cannot be NULL.");
assertNotNull(path, "Locale file path cannot be NULL.");
memoryZero(localeFile, sizeof(assetlocalefile_t));
// Init the asset file.
errorChain(assetFileInit(&localeFile->file, path, NULL, NULL));
// Open the file handle
errorChain(assetFileOpen(&localeFile->file));
// Get the blank key, this is basically the header info for po files
char_t buffer[1024];
errorChain(assetLocaleGetString(localeFile, "", 0, buffer, sizeof(buffer)));
errorChain(assetLocaleParseHeader(localeFile, buffer, sizeof(buffer)));
errorOk();
}
errorret_t assetLocaleFileDispose(assetlocalefile_t *localeFile) {
assertNotNull(localeFile, "Locale file cannot be NULL.");
errorChain(assetFileClose(&localeFile->file));
errorChain(assetFileDispose(&localeFile->file));
errorOk();
}
errorret_t assetLocaleParseHeader(
assetlocalefile_t *localeFile,
char_t *headerBuffer,
const size_t headerBufferSize
) {
assertNotNull(localeFile, "Locale file cannot be NULL.");
assertNotNull(headerBuffer, "Header buffer cannot be NULL.");
assertTrue(headerBufferSize > 0, "Header buffer size must be > 0.");
// Find "Plural-Forms: " line and parse out plural form info
char_t *pluralFormsLine = strstr(headerBuffer, "Plural-Forms:");
if(!pluralFormsLine) {
errorOk();
}
pluralFormsLine += strlen("Plural-Forms:");
// Expect nplurals
char_t *npluralsStr = strstr(pluralFormsLine, "nplurals=");
if(!npluralsStr) {
errorThrow("Failed to find nplurals in Plural-Forms header.");
}
npluralsStr += strlen("nplurals=");
localeFile->pluralStateCount = (uint8_t)atoi(npluralsStr);
if(localeFile->pluralStateCount == 0) {
errorThrow("nplurals must be greater than 0.");
}
if(localeFile->pluralStateCount > ASSET_LOCALE_FILE_PLURAL_FORM_COUNT) {
errorThrow(
"nplurals exceeds maximum supported plural forms: %d > %d",
localeFile->pluralStateCount,
ASSET_LOCALE_FILE_PLURAL_FORM_COUNT
);
}
// Expect plural=
char_t *pluralStr = strstr(pluralFormsLine, "plural=");
if(!pluralStr) {
errorThrow("Failed to find plural in Plural-Forms header.");
}
pluralStr += strlen("plural=");
// Expect ( [expressions] )
char_t *openParen = strchr(pluralStr, '(');
char_t *closeParen = strrchr(pluralStr, ')');
if(!openParen || !closeParen || closeParen < openParen) {
errorThrow("Failed to find plural expression in Plural-Forms header.");
}
// Parse:
// n [op] value ? index : n [op] value ? index : ... : final_index
char_t *ptr = openParen + 1;
uint8_t pluralIndex = 0;
uint8_t definedCount = 0;
while(1) {
while(*ptr == ' ') ptr++;
// Allow grouped subexpressions like:
// (n<7 ? 2 : 3)
// or
// (((3)))
uint8_t parenDepth = 0;
while(*ptr == '(') {
parenDepth++;
ptr++;
while(*ptr == ' ') ptr++;
}
// Final fallback: just an integer
if(*ptr != 'n') {
char_t *endPtr = NULL;
int32_t finalIndex = (int32_t)strtol(ptr, &endPtr, 10);
if(endPtr == ptr) {
errorThrow("Expected final plural index.");
}
ptr = endPtr;
while(*ptr == ' ') ptr++;
while(parenDepth > 0) {
if(*ptr != ')') {
errorThrow("Expected ')' after final plural index.");
}
ptr++;
parenDepth--;
while(*ptr == ' ') ptr++;
}
if(*ptr != ')') {
errorThrow("Expected ')' at end of plural expression.");
}
if(finalIndex < 0 || finalIndex >= localeFile->pluralStateCount) {
errorThrow(
"Final plural expression index out of bounds: %d (nplurals: %d)",
finalIndex,
localeFile->pluralStateCount
);
}
localeFile->pluralDefaultIndex = (uint8_t)finalIndex;
definedCount++;
break;
}
if(pluralIndex >= localeFile->pluralStateCount - 1) {
errorThrow(
"Too many plural conditions. Expected %d conditional clauses for nplurals=%d.",
localeFile->pluralStateCount - 1,
localeFile->pluralStateCount
);
}
ptr++; // skip 'n'
while(*ptr == ' ') ptr++;
// Determine operator
assetlocalepluraloperation_t op;
if(strncmp(ptr, "==", 2) == 0) {
op = ASSET_LOCALE_PLURAL_OP_EQUAL;
ptr += 2;
} else if(strncmp(ptr, "!=", 2) == 0) {
op = ASSET_LOCALE_PLURAL_OP_NOT_EQUAL;
ptr += 2;
} else if(strncmp(ptr, "<=", 2) == 0) {
op = ASSET_LOCALE_PLURAL_OP_LESS_EQUAL;
ptr += 2;
} else if(strncmp(ptr, ">=", 2) == 0) {
op = ASSET_LOCALE_PLURAL_OP_GREATER_EQUAL;
ptr += 2;
} else if(*ptr == '<') {
op = ASSET_LOCALE_PLURAL_OP_LESS;
ptr++;
} else if(*ptr == '>') {
op = ASSET_LOCALE_PLURAL_OP_GREATER;
ptr++;
} else {
errorThrow("Unsupported plural operator.");
}
while(*ptr == ' ') ptr++;
// Parse the comparitor value
char_t *endPtr = NULL;
int32_t value = (int32_t)strtol(ptr, &endPtr, 10);
if(endPtr == ptr) {
errorThrow("Expected value for plural expression.");
}
ptr = endPtr;
while(*ptr == ' ') ptr++;
// Parse ternary operator
if(*ptr != '?') {
errorThrow("Expected '?' after plural expression.");
}
ptr++;
while(*ptr == ' ') ptr++;
// Parse the indice
endPtr = NULL;
int32_t index = (int32_t)strtol(ptr, &endPtr, 10);
if(endPtr == ptr) {
errorThrow("Expected index for plural expression.");
}
ptr = endPtr;
if(index < 0 || index >= localeFile->pluralStateCount) {
errorThrow(
"Plural expression index out of bounds: %d (nplurals: %d)",
index,
localeFile->pluralStateCount
);
}
// Store plural expression.
localeFile->pluralIndices[pluralIndex] = (uint8_t)index;
localeFile->pluralOps[pluralIndex] = op;
localeFile->pluralValues[pluralIndex] = value;
pluralIndex++;
definedCount++;
while(*ptr == ' ') ptr++;
// Close any grouping parens that wrapped this conditional branch
while(parenDepth > 0) {
if(*ptr != ')') {
break;
}
ptr++;
parenDepth--;
while(*ptr == ' ') ptr++;
}
if(*ptr != ':') {
errorThrow("Expected ':' after plural expression.");
}
ptr++;
}
// Must define exactly nplurals outcomes:
// (nplurals - 1) conditional results + 1 final fallback result
if(
pluralIndex != localeFile->pluralStateCount - 1 ||
definedCount != localeFile->pluralStateCount
) {
errorThrow("Plural expression count does not match nplurals.");
}
errorOk();
}
uint8_t assetLocaleEvaluatePlural(
assetlocalefile_t *file,
const int32_t pluralCount
) {
assertNotNull(file, "Locale file cannot be NULL.");
assertTrue(pluralCount >= 0, "Plural count cannot be negative.");
for(uint8_t i = 0; i < file->pluralStateCount - 1; i++) {
int32_t value = file->pluralValues[i];
switch(file->pluralOps[i]) {
case ASSET_LOCALE_PLURAL_OP_EQUAL:
if(pluralCount == value) return file->pluralIndices[i];
break;
case ASSET_LOCALE_PLURAL_OP_NOT_EQUAL:
if(pluralCount != value) return file->pluralIndices[i];
break;
case ASSET_LOCALE_PLURAL_OP_LESS:
if(pluralCount < value) return file->pluralIndices[i];
break;
case ASSET_LOCALE_PLURAL_OP_LESS_EQUAL:
if(pluralCount <= value) return file->pluralIndices[i];
break;
case ASSET_LOCALE_PLURAL_OP_GREATER:
if(pluralCount > value) return file->pluralIndices[i];
break;
case ASSET_LOCALE_PLURAL_OP_GREATER_EQUAL:
if(pluralCount >= value) return file->pluralIndices[i];
break;
}
}
return file->pluralDefaultIndex;
}
errorret_t assetLocaleLineSkipBlanks(
assetfilelinereader_t *reader,
uint8_t *lineBuffer
) {
while(!reader->eof) {
// Skip blank lines
if(lineBuffer[0] == '\0') {
errorChain(assetFileLineReaderNext(reader));
continue;
}
// Skip comment lines
if(lineBuffer[0] == '#') {
errorChain(assetFileLineReaderNext(reader));
continue;
}
// Is line only spaces?
size_t lineLength = strlen((char_t *)lineBuffer);
size_t i;
bool_t onlySpaces = true;
for(i = 0; i < lineLength; i++) {
if(lineBuffer[i] != ' ') {
onlySpaces = false;
break;
}
}
if(onlySpaces) {
errorChain(assetFileLineReaderNext(reader));
continue;
}
break;
}
errorOk();
}
errorret_t assetLocaleLineUnbuffer(
assetfilelinereader_t *reader,
uint8_t *lineBuffer,
uint8_t *stringBuffer,
const size_t stringBufferSize
) {
stringBuffer[0] = '\0';
// At the point this funciton is called, we are looking for an opening quote.
char_t *start = strchr((char_t *)lineBuffer, '"');
if(!start) {
errorThrow("Expected open (0) \"");
}
char *end = strchr(start + 1, '"');
if(!end) {
errorThrow("Expected close (0) \"");
}
*end = '\0';
if(strlen(start) >= stringBufferSize) {
errorThrow("String buffer overflow");
}
memoryCopy(stringBuffer, start + 1, strlen(start));
// Now start buffering lines out
while(!reader->eof) {
errorChain(assetFileLineReaderNext(reader));
// Skip blank lines
errorChain(assetLocaleLineSkipBlanks(reader, lineBuffer));
// Skip starting spaces
char_t *ptr = (char_t *)lineBuffer;
while(*ptr == ' ') {
ptr++;
}
// Only consider lines starting with quote
if(*ptr != '"') {
break;
}
ptr++; // move past first quote
bool_t escaping = false;
char_t *dest = (char_t *)stringBuffer + strlen((char_t *)stringBuffer);
while(*ptr) {
if(escaping) {
// Handle escape sequences
switch(*ptr) {
case 'n': *dest++ = '\n'; break;
case 't': *dest++ = '\t'; break;
case '\\': *dest++ = '\\'; break;
case '"': *dest++ = '"'; break;
default:
errorThrow("Unknown escape sequence: \\%c", *ptr);
}
escaping = false;
} else if(*ptr == '\\') {
escaping = true;
} else if(*ptr == '"') {
// End of string
break;
} else {
// Regular character
*dest++ = *ptr;
}
if((size_t)(dest - (char_t *)stringBuffer) >= stringBufferSize) {
errorThrow("String buffer overflow");
}
ptr++;
}
*dest = '\0';
}
errorOk();
}
errorret_t assetLocaleGetString(
assetlocalefile_t *file,
const char_t *messageId,
const int32_t pluralCount,
char_t *stringBuffer,
const size_t stringBufferSize
) {
assertNotNull(file, "Asset file cannot be NULL.");
assertNotNull(messageId, "Message ID cannot be NULL.");
assertTrue(pluralCount >= 0, "Plural index cannot be negative.");
assertNotNull(stringBuffer, "String buffer cannot be NULL.");
assertTrue(stringBufferSize > 0, "String buffer size must be > 0");
assetfilelinereader_t reader;
bool_t msgidFound = false, msgidPluralFound = false, msgstrFound = false;
uint8_t msgidBuffer[256];
uint8_t msgidPluralBuffer[256];
uint8_t readBuffer[1024];
uint8_t lineBuffer[1024];
uint8_t pluralIndex = 0xFF;
msgidBuffer[0] = '\0';
msgidPluralBuffer[0] = '\0';
stringBuffer[0] = '\0';
// Rewind and start reading lines.
errorChain(assetFileRewind(&file->file));
assetFileLineReaderInit(
&reader,
&file->file,
readBuffer,
sizeof(readBuffer),
lineBuffer,
sizeof(lineBuffer)
);
// Skip blanks, comments, etc and start looking for msgid's
errorChain(assetLocaleLineSkipBlanks(&reader, lineBuffer));
while(!reader.eof) {
// Is this msgid?
if(memoryCompare(lineBuffer, "msgid", 5) != 0) {
errorChain(assetFileLineReaderNext(&reader));
msgidBuffer[0] = '\0';
continue;
}
// Unbuffer the msgid
assetLocaleLineUnbuffer(
&reader, lineBuffer, (uint8_t *)msgidBuffer, sizeof(msgidBuffer)
);
// Is this the needle?
if(memoryCompare(msgidBuffer, messageId, strlen(messageId)) != 0) {
continue;
}
msgidFound = true;
break;
}
if(!msgidFound) {
errorThrow("Failed to find message ID: %s", messageId);
}
// We are either going to see a msgstr or a msgid_plural
while(!reader.eof) {
errorChain(assetLocaleLineSkipBlanks(&reader, lineBuffer));
// Is msgid_plural?
if(
!msgidPluralFound &&
memoryCompare(lineBuffer, "msgid_plural", 12) == 0
) {
// Yes, start reading plural ID
assetLocaleLineUnbuffer(
&reader,
lineBuffer,
(uint8_t *)msgidPluralBuffer,
sizeof(msgidPluralBuffer)
);
msgidPluralFound = true;
// At this point we determine the plural index to use by running the
// plural formula
pluralIndex = assetLocaleEvaluatePlural(
file,
pluralCount
);
continue;
}
// Should be msgstr if not plural.
if(memoryCompare(lineBuffer, "msgstr", 6) != 0) {
errorThrow("Expected msgstr after msgid, found: %s", lineBuffer);
continue;
}
// If plural we need an index
if(msgidPluralFound) {
// Skip blank chars
char_t *ptr = (char_t *)lineBuffer + 6;
while(*ptr == ' ') {
ptr++;
}
if(*ptr != '[') {
errorThrow("Expected [ for plural form, found: %s", lineBuffer);
}
ptr++; // move past [
// Parse until ]
char *end = strchr(ptr, ']');
if(!end) {
errorThrow("Expected ] for plural form, found: %s", lineBuffer);
}
*end = '\0';
int32_t index = atoi(ptr);
if(index != pluralIndex) {
// Not the plural form we want, skip to the next useable line
while(!reader.eof) {
errorChain(assetFileLineReaderNext(&reader));
errorChain(assetLocaleLineSkipBlanks(&reader, lineBuffer));
if(
lineBuffer[0] == '\"' ||
lineBuffer[0] == '\0' ||
lineBuffer[0] == '#'
) continue;
break;
}
continue;
}
// Undo damage to line buffer from unbuffering.
*end = ']';
}
// Parse out msgstr
errorChain(assetLocaleLineUnbuffer(
&reader, lineBuffer, (uint8_t *)stringBuffer, stringBufferSize
));
msgstrFound = true;
break;
};
if(!msgstrFound) {
errorThrow("Failed to find msgstr for message ID: %s", messageId);
}
errorOk();
}
errorret_t assetLocaleGetStringWithVA(
assetlocalefile_t *file,
const char_t *messageId,
const int32_t pluralIndex,
char_t *buffer,
const size_t bufferSize,
...
) {
assertNotNull(file, "Asset file cannot be NULL.");
assertNotNull(messageId, "Message ID cannot be NULL.");
assertNotNull(buffer, "Buffer cannot be NULL.");
assertTrue(bufferSize > 0, "Buffer size must be > 0.");
assertTrue(pluralIndex >= 0, "Plural cannot be negative.");
char_t *tempBuffer;
tempBuffer = memoryAllocate(bufferSize);
errorret_t ret = assetLocaleGetString(
file,
messageId,
pluralIndex,
tempBuffer,
bufferSize
);
if(ret.code != ERROR_OK) {
memoryFree(tempBuffer);
return ret;
}
va_list args;
va_start(args, bufferSize);
int result = vsnprintf(buffer, bufferSize, tempBuffer, args);
va_end(args);
memoryFree(tempBuffer);
if(result < 0) {
errorThrow("Failed to format locale string for ID: %s", messageId);
}
return ret;
}
errorret_t assetLocaleGetStringWithArgs(
assetlocalefile_t *file,
const char_t *id,
const int32_t plural,
char_t *buffer,
const size_t bufferSize,
const assetlocalearg_t *args,
const size_t argCount
) {
assertNotNull(id, "Message ID cannot be NULL.");
assertNotNull(buffer, "Buffer cannot be NULL.");
assertTrue(bufferSize > 0, "Buffer size must be > 0.");
assertTrue(plural >= 0, "Plural cannot be negative.");
assertTrue(
argCount == 0 || args != NULL,
"Args cannot be NULL when argCount > 0."
);
char_t *format = memoryAllocate(bufferSize);
if(format == NULL) {
errorThrow("Failed to allocate format buffer.");
}
errorret_t ret = assetLocaleGetString(
file,
id,
plural,
format,
bufferSize
);
if(ret.code != ERROR_OK) {
memoryFree(format);
return ret;
}
size_t inIndex = 0;
size_t outIndex = 0;
size_t nextArg = 0;
buffer[0] = '\0';
while(format[inIndex] != '\0') {
if(format[inIndex] != '%') {
if(outIndex + 1 >= bufferSize) {
memoryFree(format);
errorThrow("Formatted locale string buffer overflow for ID: %s", id);
}
buffer[outIndex++] = format[inIndex++];
continue;
}
inIndex++;
/* Escaped percent */
if(format[inIndex] == '%') {
if(outIndex + 1 >= bufferSize) {
memoryFree(format);
errorThrow("Formatted locale string buffer overflow for ID: %s", id);
}
buffer[outIndex++] = '%';
inIndex++;
continue;
}
if(nextArg >= argCount) {
memoryFree(format);
errorThrow("Not enough locale arguments for ID: %s", id);
}
{
char_t specBuffer[32];
char_t valueBuffer[256];
size_t specLength = 0;
int written = 0;
char_t specifier;
specBuffer[specLength++] = '%';
/* Allow flags / width / precision */
while(format[inIndex] != '\0') {
char_t ch = format[inIndex];
if(
ch == '-' || ch == '+' || ch == ' ' || ch == '#' || ch == '0' ||
ch == '.' || (ch >= '0' && ch <= '9')
) {
if(specLength + 1 >= sizeof(specBuffer)) {
memoryFree(format);
errorThrow("Format specifier too long for ID: %s", id);
}
specBuffer[specLength++] = ch;
inIndex++;
continue;
}
break;
}
if(format[inIndex] == '\0') {
memoryFree(format);
errorThrow("Incomplete format specifier for ID: %s", id);
}
specifier = format[inIndex++];
if(specifier != 's' && specifier != 'd' && specifier != 'f') {
memoryFree(format);
errorThrow(
"Unsupported format specifier '%%%c' for ID: %s",
specifier,
id
);
}
specBuffer[specLength++] = specifier;
specBuffer[specLength] = '\0';
switch(specifier) {
case 's':
if(args[nextArg].type != ASSET_LOCALE_ARG_STRING) {
memoryFree(format);
errorThrow("Expected string locale argument for ID: %s", id);
}
written = snprintf(
valueBuffer,
sizeof(valueBuffer),
specBuffer,
args[nextArg].stringValue ? args[nextArg].stringValue : ""
);
break;
case 'd':
if(args[nextArg].type != ASSET_LOCALE_ARG_INT) {
memoryFree(format);
errorThrow("Expected int locale argument for ID: %s", id);
}
written = snprintf(
valueBuffer,
sizeof(valueBuffer),
specBuffer,
args[nextArg].intValue
);
break;
case 'f':
if(
args[nextArg].type != ASSET_LOCALE_ARG_FLOAT &&
args[nextArg].type != ASSET_LOCALE_ARG_INT
) {
memoryFree(format);
errorThrow("Expected float or int locale argument for ID: %s", id);
}
float_t floatValue = (
args[nextArg].type == ASSET_LOCALE_ARG_FLOAT ?
args[nextArg].floatValue :
(float_t)args[nextArg].intValue
);
written = snprintf(
valueBuffer,
sizeof(valueBuffer),
specBuffer,
floatValue
);
break;
}
nextArg++;
if(written < 0) {
memoryFree(format);
errorThrow("Failed to format locale string for ID: %s", id);
}
if(outIndex + (size_t)written >= bufferSize) {
memoryFree(format);
errorThrow("Formatted locale string buffer overflow for ID: %s", id);
}
memoryCopy(buffer + outIndex, valueBuffer, (size_t)written);
outIndex += (size_t)written;
}
}
buffer[outIndex] = '\0';
memoryFree(format);
errorOk();
}

View File

@@ -0,0 +1,161 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "asset/asset.h"
#define ASSET_LOCALE_FILE_PLURAL_FORM_COUNT 6
typedef enum {
ASSET_LOCALE_PLURAL_OP_EQUAL,
ASSET_LOCALE_PLURAL_OP_NOT_EQUAL,
ASSET_LOCALE_PLURAL_OP_LESS,
ASSET_LOCALE_PLURAL_OP_LESS_EQUAL,
ASSET_LOCALE_PLURAL_OP_GREATER,
ASSET_LOCALE_PLURAL_OP_GREATER_EQUAL
} assetlocalepluraloperation_t;
typedef enum {
ASSET_LOCALE_ARG_STRING,
ASSET_LOCALE_ARG_INT,
ASSET_LOCALE_ARG_FLOAT
} assetlocaleargtype_t;
typedef struct {
assetlocaleargtype_t type;
union {
const char_t *stringValue;
int32_t intValue;
float_t floatValue;
};
} assetlocalearg_t;
typedef struct {
assetfile_t file;
assetlocalepluraloperation_t pluralOps[ASSET_LOCALE_FILE_PLURAL_FORM_COUNT];
int32_t pluralValues[ASSET_LOCALE_FILE_PLURAL_FORM_COUNT];
int32_t pluralIndices[ASSET_LOCALE_FILE_PLURAL_FORM_COUNT];
uint8_t pluralStateCount;
uint8_t pluralDefaultIndex;
} assetlocalefile_t;
/**
* Initialize a locale asset file.
*
* @param localeFile The locale file to initialize.
* @param path The path to the locale file.
* @return An error code if a failure occurs.
*/
errorret_t assetLocaleFileInit(
assetlocalefile_t *localeFile,
const char_t *path
);
/**
* Dispose of a locale asset file.
*
* @param localeFile The locale file to dispose of.
* @return An error code if a failure occurs.
*/
errorret_t assetLocaleFileDispose(assetlocalefile_t *localeFile);
errorret_t assetLocaleParseHeader(
assetlocalefile_t *localeFile,
char_t *headerBuffer,
const size_t headerBufferSize
);
/**
* Skips blank lines and comment lines in the line reader.
*
* @param reader Line reader to read from.
* @param lineBuffer Buffer to use for reading lines.
* @return Any error that occurs during skipping.
*/
errorret_t assetLocaleLineSkipBlanks(
assetfilelinereader_t *reader,
uint8_t *lineBuffer
);
/**
* Unbuffers a potentially multi-line quoted string from the line reader.
*
* This will read lines until it finds a line that starts with a quote, then
* read until the closing quote.
*
* @param reader Line reader to read from.
* @param lineBuffer Buffer to use for reading lines.
* @param stringBuffer Buffer to write the unbuffered string to.
* @param stringBufferSize Size of the string buffer.
* @return Any error that occurs during unbuffering.
*/
errorret_t assetLocaleLineUnbuffer(
assetfilelinereader_t *reader,
uint8_t *lineBuffer,
uint8_t *stringBuffer,
const size_t stringBufferSize
);
/**
* Test function for locale asset loading.
*
* @param file Asset file to test loading from.
* @param messageId The message ID to retrieve.
* @param pluralCount Count for formulating the plural variant.
* @param stringBuffer Buffer to write the retrieved string to.
* @param stringBufferSize Size of the string buffer.
* @return Any error that occurs during testing.
*/
errorret_t assetLocaleGetString(
assetlocalefile_t *file,
const char_t *messageId,
const int32_t pluralCount,
char_t *stringBuffer,
const size_t stringBufferSize
);
/**
* Test function for locale asset loading with a variable argument list.
*
* @param file Asset file to test loading from.
* @param messageId The message ID to retrieve.
* @param pluralCount Count for formulating the plural variant.
* @param buffer Buffer to write the retrieved string to.
* @param bufferSize Size of the buffer.
* @param ... Additional arguments for formatting the string.
* @return Any error that occurs during testing.
*/
errorret_t assetLocaleGetStringWithVA(
assetlocalefile_t *file,
const char_t *messageId,
const int32_t pluralCount,
char_t *buffer,
const size_t bufferSize,
...
);
/**
* Test function for locale asset loading with a list of arguments.
*
* @param file Asset file to test loading from.
* @param messageId The message ID to retrieve.
* @param pluralCount Count for formulating the plural variant.
* @param buffer Buffer to write the retrieved string to.
* @param bufferSize Size of the buffer.
* @param args List of arguments for formatting the string.
* @param argCount Number of arguments in the list.
* @return Any error that occurs during testing.
*/
errorret_t assetLocaleGetStringWithArgs(
assetlocalefile_t *file,
const char_t *messageId,
const int32_t pluralCount,
char_t *buffer,
const size_t bufferSize,
const assetlocalearg_t *args,
const size_t argCount
);

View File

@@ -0,0 +1,10 @@
# Copyright (c) 2026 Dominic Masters
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
# Sources
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
assetscriptloader.c
)

View File

@@ -0,0 +1,82 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "assetscriptloader.h"
#include "assert/assert.h"
errorret_t assetScriptLoader(assetfile_t *file) {
assertNotNull(file, "Asset file cannot be NULL");
assertNull(file->zipFile, "Asset file zip handle must be NULL");
assertNotNull(file->output, "Asset file output cannot be NULL");
assetscript_t *script = (assetscript_t *)file->output;
// Open the asset for buffering
errorChain(assetFileOpen(file));
// Request loading
if(!lua_load(
script->ctx->luaState,
assetScriptReader,
file,
file->filename,
NULL
) == LUA_OK) {
const char_t *strErr = lua_tostring(script->ctx->luaState, -1);
lua_pop(script->ctx->luaState, 1);
errorThrow("Failed to load Lua script: %s", strErr);
}
// Now loaded, exec
if(lua_pcall(script->ctx->luaState, 0, LUA_MULTRET, 0) != LUA_OK) {
const char_t *strErr = lua_tostring(script->ctx->luaState, -1);
lua_pop(script->ctx->luaState, 1);
errorThrow("Failed to execute Lua script: %s", strErr);
}
// Close the file
return assetFileClose(file);
}
errorret_t assetScriptLoad(const char_t *path, scriptcontext_t *ctx) {
assertNotNull(path, "Script path cannot be NULL");
assertNotNull(ctx, "Script context cannot be NULL");
assetscript_t script;
script.ctx = ctx;
return assetLoad(
path,
assetScriptLoader,
NULL,
&script
);
}
const char_t * assetScriptReader(lua_State* L, void* data, size_t* size) {
assetfile_t *file = (assetfile_t*)data;
assertNotNull(file, "Script asset file cannot be NULL");
assertNotNull(file->zipFile, "Script asset zip handle cannot be NULL");
assertNotNull(file->output, "Script asset output cannot be NULL");
assetscript_t *script = (assetscript_t *)file->output;
assertNotNull(script, "Script asset output cannot be NULL");
zip_int64_t read = zip_fread(
file->zipFile,
script->buffer,
sizeof(script->buffer)
);
if(read < 0) {
*size = 0;
return NULL;
}
*size = (size_t)read;
return script->buffer;
}

View File

@@ -0,0 +1,48 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "asset/asset.h"
#include "script/scriptcontext.h"
#define ASSET_SCRIPT_BUFFER_SIZE 1024
typedef struct {
void *nothing;
} assetscriptloaderparams_t;
typedef struct {
scriptcontext_t *ctx;
char_t buffer[ASSET_SCRIPT_BUFFER_SIZE];
} assetscript_t;
/**
* Handler for script assets.
*
* @param file Asset file to load the script from.
* @return Any error that occurs during loading.
*/
errorret_t assetScriptLoader(assetfile_t *file);
/**
* Loads a script from the specified path.
*
* @param path Path to the script asset.
* @param ctx Script context to load the script into.
* @return Any error that occurs during loading.
*/
errorret_t assetScriptLoad(const char_t *path, scriptcontext_t *ctx);
/**
* Reader function for Lua to read script data from the asset.
*
* @param L Lua state.
* @param data Pointer to the scriptcontext_t structure.
* @param size Pointer to store the size of the read data.
* @return Pointer to the read data buffer.
*/
const char_t * assetScriptReader(lua_State* L, void* data, size_t* size);

View File

@@ -1,15 +0,0 @@
/**
* Copyright (c) 2025 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "asset/asset.h"
#include "assert/assert.h"
#include "util/memory.h"
errorret_t assetMapHandler(assetcustom_t custom) {
printf("Map Loaded from asset!\n");
errorOk();
}

View File

@@ -1,20 +0,0 @@
/**
* Copyright (c) 2025 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "error/error.h"
typedef struct assetcustom_s assetcustom_t;
/**
* Loads a map asset from the given data pointer into the output map structure.
*
* @param data Pointer to the raw assetmap_t data.
* @param output Pointer to the map_t to load the map into.
* @return An error code.
*/
errorret_t assetMapHandler(assetcustom_t custom);

View File

@@ -1,185 +0,0 @@
/**
* Copyright (c) 2025 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "asset/asset.h"
#include "assert/assert.h"
#include "map/mapchunk.h"
#include "util/endian.h"
#pragma pack(push, 1)
typedef struct {
uint32_t tileCount;
uint8_t modelCount;
uint8_t entityCount;
} assetchunkheader_t;
#pragma pack(pop)
#pragma pack(push, 1)
typedef struct {
maptile_t tile;
} assetchunktiledata_t;
#pragma pack(pop)
#pragma pack(push, 1)
typedef struct {
uint32_t vertexCount;
} assetchunkmodelheader_t;
#pragma pack(pop)
#pragma pack(push, 1)
typedef struct {
uint8_t entityType;
uint8_t localX;
uint8_t localY;
uint8_t localZ;
} assetchunkentityheader_t;
#pragma pack(pop)
errorret_t assetMapChunkHandler(assetcustom_t custom) {
assertNotNull(custom.output, "Output pointer cannot be NULL");
assertNotNull(custom.zipFile, "Zip file pointer cannot be NULL");
mapchunk_t *chunk = (mapchunk_t *)custom.output;
assertTrue(chunk->meshCount == 0, "Chunk is not in a good state");
// Read header
assetchunkheader_t header;
size_t bytesRead = zip_fread(
custom.zipFile, &header, sizeof(assetchunkheader_t)
);
if(bytesRead != sizeof(assetchunkheader_t)) {
zip_fclose(custom.zipFile);
errorThrow("Failed to read chunk asset header.");
}
// Fix endianess if necessary
header.tileCount = endianLittleToHost32(header.tileCount);
if(header.tileCount != CHUNK_TILE_COUNT) {
zip_fclose(custom.zipFile);
errorThrow(
"Chunk asset has invalid tile count: %d (expected %d).",
header.tileCount,
CHUNK_TILE_COUNT
);
}
if(header.modelCount > CHUNK_MESH_COUNT_MAX) {
zip_fclose(custom.zipFile);
errorThrow(
"Chunk asset has too many models: %d (max %d).",
header.modelCount,
CHUNK_MESH_COUNT_MAX
);
}
if(header.entityCount > CHUNK_ENTITY_COUNT_MAX) {
zip_fclose(custom.zipFile);
errorThrow(
"Chunk asset has too many entities: %d (max %d).",
header.entityCount,
CHUNK_ENTITY_COUNT_MAX
);
}
chunk->meshCount = header.modelCount;
// Read tile data
bytesRead = zip_fread(
custom.zipFile,
chunk->tiles,
sizeof(assetchunktiledata_t) * header.tileCount
);
if(bytesRead != sizeof(assetchunktiledata_t) * header.tileCount) {
zip_fclose(custom.zipFile);
errorThrow("Failed to read chunk tile data.");
}
// For each model...
uint32_t vertexIndex = 0;
for(uint8_t i = 0; i < header.modelCount; i++) {
assetchunkmodelheader_t modelHeader;
bytesRead = zip_fread(
custom.zipFile, &modelHeader, sizeof(assetchunkmodelheader_t)
);
if(bytesRead != sizeof(assetchunkmodelheader_t)) {
zip_fclose(custom.zipFile);
errorThrow("Failed to read chunk model header.");
}
// Fix endianess if necessary
modelHeader.vertexCount = endianLittleToHost32(modelHeader.vertexCount);
if(
vertexIndex + modelHeader.vertexCount >
CHUNK_VERTEX_COUNT_MAX
) {
zip_fclose(custom.zipFile);
errorThrow("Chunk model vertex count exceeds maximum.");
}
// Read vertex data.
bytesRead = zip_fread(
custom.zipFile,
&chunk->vertices[vertexIndex],
sizeof(meshvertex_t) * modelHeader.vertexCount
);
if(bytesRead != sizeof(meshvertex_t) * modelHeader.vertexCount) {
zip_fclose(custom.zipFile);
errorThrow("Failed to read chunk model vertex data.");
}
// Init the mesh
if(modelHeader.vertexCount > 0) {
mesh_t *mesh = &chunk->meshes[i];
meshInit(
mesh,
MESH_PRIMITIVE_TYPE_TRIANGLES,
modelHeader.vertexCount,
&chunk->vertices[vertexIndex]
);
vertexIndex += modelHeader.vertexCount;
} else {
// chunk->meshes[i].vertexCount = 0;
}
}
// Read entity data
// for(uint8_t i = 0; i < header.entityCount; i++) {
// assetchunkentityheader_t entityHeader;
// bytesRead = zip_fread(
// custom.zipFile, &entityHeader, sizeof(assetchunkentityheader_t)
// );
// if(bytesRead != sizeof(assetchunkentityheader_t)) {
// zip_fclose(custom.zipFile);
// errorThrow("Failed to read chunk entity header.");
// }
// uint8_t entityIndex = entityGetAvailable();
// if(entityIndex == 0xFF) {
// zip_fclose(custom.zipFile);
// errorThrow("No available entity slots.");
// }
// entity_t *entity = &ENTITIES[entityIndex];
// entityInit(entity, (entitytype_t)entityHeader.entityType);
// entity->position.x = (
// (chunk->position.x * CHUNK_WIDTH) + entityHeader.localX
// );
// entity->position.y = (
// (chunk->position.y * CHUNK_HEIGHT) + entityHeader.localY
// );
// entity->position.z = (
// (chunk->position.z * CHUNK_DEPTH) + entityHeader.localZ
// );
// chunk->entities[i] = entityIndex;
// }
errorOk();
}

View File

@@ -1,19 +0,0 @@
/**
* Copyright (c) 2025 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "error/error.h"
typedef struct assetcustom_s assetcustom_t;
/**
* Handles loading of map chunk data from a map chunk asset file.
*
* @param custom The custom asset loading parameters.
* @return An error code.
*/
errorret_t assetMapChunkHandler(assetcustom_t custom);

View File

@@ -35,9 +35,9 @@ void cameraInitOrthographic(camera_t *camera) {
camera->projType = CAMERA_PROJECTION_TYPE_ORTHOGRAPHIC; camera->projType = CAMERA_PROJECTION_TYPE_ORTHOGRAPHIC;
camera->orthographic.left = 0.0f; camera->orthographic.left = 0.0f;
camera->orthographic.right = SCREEN.width; camera->orthographic.right = SCREEN.width;
camera->orthographic.top = 0.0f; camera->orthographic.top = SCREEN.height;
camera->orthographic.bottom = SCREEN.height; camera->orthographic.bottom = 0.0f;
camera->nearClip = -1.0f; camera->nearClip = 0.1f;
camera->farClip = 1.0f; camera->farClip = 1.0f;
camera->viewType = CAMERA_VIEW_TYPE_2D; camera->viewType = CAMERA_VIEW_TYPE_2D;
@@ -84,7 +84,7 @@ void cameraGetViewMatrix(camera_t *camera, mat4 dest) {
assertNotNull(dest, "Destination matrix must not be null"); assertNotNull(dest, "Destination matrix must not be null");
if(camera->viewType == CAMERA_VIEW_TYPE_MATRIX) { if(camera->viewType == CAMERA_VIEW_TYPE_MATRIX) {
glm_mat4_copy(camera->view, dest); glm_mat4_ucopy(camera->view, dest);
} else if(camera->viewType == CAMERA_VIEW_TYPE_LOOKAT) { } else if(camera->viewType == CAMERA_VIEW_TYPE_LOOKAT) {
glm_mat4_identity(dest); glm_mat4_identity(dest);
glm_lookat( glm_lookat(

View File

@@ -20,7 +20,27 @@
#include "display/shader/shaderunlit.h" #include "display/shader/shaderunlit.h"
#include "time/time.h" #include "time/time.h"
#include "script/module/display/moduleshader.h"
display_t DISPLAY = { 0 }; display_t DISPLAY = { 0 };
mesh_t mesh;
meshvertex_t vertices[3] = {
{
.color = { 255, 0, 0, 255 },
.uv = { 0.0f, 0.0f },
.pos = { 0.0f, 0.5f, 0.0f }
},
{
.color = { 0, 255, 0, 255 },
.uv = { 0.5f, 1.0f },
.pos = { -0.5f, -0.5f, 0.0f }
},
{
.color = { 0, 0, 255, 255 },
.uv = { 1.0f, 0.0f },
.pos = { 0.5f, -0.5f, 0.0f }
}
};
errorret_t displayInit(void) { errorret_t displayInit(void) {
memoryZero(&DISPLAY, sizeof(DISPLAY)); memoryZero(&DISPLAY, sizeof(DISPLAY));
@@ -28,14 +48,28 @@ errorret_t displayInit(void) {
#ifdef displayPlatformInit #ifdef displayPlatformInit
errorChain(displayPlatformInit()); errorChain(displayPlatformInit());
#endif #endif
errorChain(shaderInit(&SHADER_UNLIT, &SHADER_UNLIT_DEFINITION));
errorChain(quadInit()); errorChain(quadInit());
errorChain(frameBufferInitBackBuffer()); errorChain(frameBufferInitBackBuffer());
errorChain(spriteBatchInit()); errorChain(spriteBatchInit());
errorChain(textInit()); errorChain(textInit());
errorChain(screenInit()); errorChain(screenInit());
// Setup initial shader with default values
errorChain(shaderInit(&SHADER_UNLIT, &SHADER_UNLIT_DEFINITION));
camera_t cam;
cameraInit(&cam);
mat4 mat;
cameraGetProjectionMatrix(&cam, mat);
errorChain(shaderBind(&SHADER_UNLIT));
errorChain(shaderSetMatrix(&SHADER_UNLIT, SHADER_UNLIT_PROJECTION, mat));
cameraGetViewMatrix(&cam, mat);
errorChain(shaderSetMatrix(&SHADER_UNLIT, SHADER_UNLIT_VIEW, mat));
glm_mat4_identity(mat);
errorChain(shaderSetMatrix(&SHADER_UNLIT, SHADER_UNLIT_MODEL, mat));
errorChain(shaderSetTexture(&SHADER_UNLIT, SHADER_UNLIT_TEXTURE, NULL));
errorChain(meshInit(&mesh, MESH_PRIMITIVE_TYPE_TRIANGLES, 3, vertices));
errorOk(); errorOk();
} }
@@ -55,31 +89,7 @@ errorret_t displayUpdate(void) {
SCREEN.background SCREEN.background
); );
errorChain(shaderBind(&SHADER_UNLIT)); errorChain(sceneRender());
camera_t camera;
cameraInitOrthographic(&camera);
camera.orthographic.left = 0.0f;
camera.orthographic.right = SCREEN.width;
camera.orthographic.top = SCREEN.height;
camera.orthographic.bottom = 0.0f;
mat4 proj, view, model;
cameraGetProjectionMatrix(&camera, proj);
cameraGetViewMatrix(&camera, view);
glm_mat4_identity(model);
errorChain(shaderSetMatrix(&SHADER_UNLIT, SHADER_UNLIT_PROJECTION, proj));
errorChain(shaderSetMatrix(&SHADER_UNLIT, SHADER_UNLIT_VIEW, view));
errorChain(shaderSetMatrix(&SHADER_UNLIT, SHADER_UNLIT_MODEL, model));
errorChain(spriteBatchPush(
NULL,
TIME.time * 2.0f, TIME.time * 3.0f, 100, 100, COLOR_WHITE, 0, 0, 1, 1
));
errorChain(spriteBatchFlush());
// errorCatch(errorPrint(sceneRender()));
// Render UI // Render UI
// uiRender(); // uiRender();

View File

@@ -56,6 +56,7 @@ errorret_t screenBind() {
// Screen mode backbuffer uses the full display size // Screen mode backbuffer uses the full display size
SCREEN.width = frameBufferGetWidth(FRAMEBUFFER_BOUND); SCREEN.width = frameBufferGetWidth(FRAMEBUFFER_BOUND);
SCREEN.height = frameBufferGetHeight(FRAMEBUFFER_BOUND); SCREEN.height = frameBufferGetHeight(FRAMEBUFFER_BOUND);
SCREEN.aspect = (float_t)SCREEN.width / (float_t)SCREEN.height;
// No needd for a framebuffer. // No needd for a framebuffer.
#ifdef DUSK_DISPLAY_SIZE_DYNAMIC #ifdef DUSK_DISPLAY_SIZE_DYNAMIC

View File

@@ -7,4 +7,5 @@
target_sources(${DUSK_LIBRARY_TARGET_NAME} target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC PUBLIC
shader.c shader.c
shaderunlit.c
) )

View File

@@ -8,15 +8,19 @@
#include "shader.h" #include "shader.h"
#include "assert/assert.h" #include "assert/assert.h"
shader_t *bound = NULL;
errorret_t shaderInit(shader_t *shader, const shaderdefinition_t *def) { errorret_t shaderInit(shader_t *shader, const shaderdefinition_t *def) {
assertNotNull(shader, "Shader cannot be null"); assertNotNull(shader, "Shader cannot be null");
errorChain(shaderInitPlatform(shader, def)); errorChain(shaderInitPlatform(shader, def));
bound = NULL;
errorOk(); errorOk();
} }
errorret_t shaderBind(shader_t *shader) { errorret_t shaderBind(shader_t *shader) {
assertNotNull(shader, "Shader cannot be null"); assertNotNull(shader, "Shader cannot be null");
errorChain(shaderBindPlatform(shader)); errorChain(shaderBindPlatform(shader));
bound = shader;
errorOk(); errorOk();
} }
@@ -28,12 +32,37 @@ errorret_t shaderSetMatrix(
assertNotNull(shader, "Shader cannot be null"); assertNotNull(shader, "Shader cannot be null");
assertStrLenMin(name, 1, "Uniform name cannot be empty"); assertStrLenMin(name, 1, "Uniform name cannot be empty");
assertNotNull(matrix, "Matrix cannot be null"); assertNotNull(matrix, "Matrix cannot be null");
assertTrue(bound == shader, "Shader must be bound.");
errorChain(shaderSetMatrixPlatform(shader, name, matrix)); errorChain(shaderSetMatrixPlatform(shader, name, matrix));
errorOk(); errorOk();
} }
errorret_t shaderSetTexture(
shader_t *shader,
const char_t *name,
texture_t *texture
) {
assertNotNull(shader, "Shader cannot be null");
assertStrLenMin(name, 1, "Uniform name cannot be empty");
assertTrue(bound == shader, "Shader must be bound.");
errorChain(shaderSetTexturePlatform(shader, name, texture));
errorOk();
}
// errorret_t shaderSetColor(
// shader_t *shader,
// const char_t *name,
// color_t color
// ) {
// assertNotNull(shader, "Shader cannot be null");
// assertStrLenMin(name, 1, "Uniform name cannot be empty");
// errorChain(shaderSetColorPlatform(shader, name, color));
// errorOk();
// }
errorret_t shaderDispose(shader_t *shader) { errorret_t shaderDispose(shader_t *shader) {
assertNotNull(shader, "Shader cannot be null"); assertNotNull(shader, "Shader cannot be null");
bound = NULL;
errorChain(shaderDisposePlatform(shader)); errorChain(shaderDisposePlatform(shader));
errorOk(); errorOk();
} }

View File

@@ -71,6 +71,20 @@ errorret_t shaderSetTexture(
texture_t *texture texture_t *texture
); );
/**
* Sets a color uniform in the shader. This is platform dependant.
*
* @param shader Shader to set the color in
* @param name Name of the uniform to set
* @param color Color to set
* @return Error if failure, otherwise errorOk
*/
// errorret_t shaderSetColor(
// shader_t *shader,
// const char_t *name,
// color_t color
// );
/** /**
* Disposes of a shader. This is platform dependant. * Disposes of a shader. This is platform dependant.
* *

View File

@@ -5,9 +5,6 @@
* https://opensource.org/licenses/MIT * https://opensource.org/licenses/MIT
*/ */
#pragma once #include "shaderunlit.h"
#include "dusk.h"
typedef struct { shader_t SHADER_UNLIT = { 0 };
void *nothing;
} dusklocale_t;

View File

@@ -11,6 +11,8 @@
#define SHADER_UNLIT_PROJECTION "u_Proj" #define SHADER_UNLIT_PROJECTION "u_Proj"
#define SHADER_UNLIT_VIEW "u_View" #define SHADER_UNLIT_VIEW "u_View"
#define SHADER_UNLIT_MODEL "u_Model" #define SHADER_UNLIT_MODEL "u_Model"
#define SHADER_UNLIT_TEXTURE "u_Texture"
// #define SHADER_UNLIT_COLOR "u_Color"
extern shaderdefinition_t SHADER_UNLIT_DEFINITION; extern shaderdefinition_t SHADER_UNLIT_DEFINITION;
static shader_t SHADER_UNLIT; extern shader_t SHADER_UNLIT;

View File

@@ -25,7 +25,6 @@ errorret_t spriteBatchInit() {
} }
errorret_t spriteBatchPush( errorret_t spriteBatchPush(
texture_t *texture,
const float_t minX, const float_t minX,
const float_t minY, const float_t minY,
const float_t maxX, const float_t maxX,
@@ -36,19 +35,16 @@ errorret_t spriteBatchPush(
const float_t u1, const float_t u1,
const float_t v1 const float_t v1
) { ) {
errorChain(spriteBatchPush3D( return spriteBatchPush3D(
texture,
(vec3){ minX, minY, 0 }, (vec3){ minX, minY, 0 },
(vec3){ maxX, maxY, 0 }, (vec3){ maxX, maxY, 0 },
color, color,
(vec2){ u0, v0 }, (vec2){ u0, v0 },
(vec2){ u1, v1 } (vec2){ u1, v1 }
)); );
errorOk();
} }
errorret_t spriteBatchPush3D( errorret_t spriteBatchPush3D(
texture_t *texture,
const vec3 min, const vec3 min,
const vec3 max, const vec3 max,
const color_t color, const color_t color,
@@ -56,15 +52,14 @@ errorret_t spriteBatchPush3D(
const vec2 uv1 const vec2 uv1
) { ) {
// Need to flush? // Need to flush?
if( if(SPRITEBATCH.spriteCount >= SPRITEBATCH_SPRITES_MAX_PER_FLUSH) {
SPRITEBATCH.currentTexture != texture ||
SPRITEBATCH.spriteCount >= SPRITEBATCH_SPRITES_MAX
) {
errorChain(spriteBatchFlush()); errorChain(spriteBatchFlush());
SPRITEBATCH.currentTexture = texture;
} }
size_t vertexOffset = SPRITEBATCH.spriteCount * QUAD_VERTEX_COUNT; size_t vertexOffset = (
SPRITEBATCH.spriteCount +
(SPRITEBATCH.spriteFlush * SPRITEBATCH_SPRITES_MAX_PER_FLUSH)
) * QUAD_VERTEX_COUNT;
quadBuffer3D( quadBuffer3D(
&SPRITEBATCH_VERTICES[vertexOffset], &SPRITEBATCH_VERTICES[vertexOffset],
min, max, color, uv0, uv1 min, max, color, uv0, uv1
@@ -75,7 +70,7 @@ errorret_t spriteBatchPush3D(
void spriteBatchClear() { void spriteBatchClear() {
SPRITEBATCH.spriteCount = 0; SPRITEBATCH.spriteCount = 0;
SPRITEBATCH.currentTexture = NULL; SPRITEBATCH.spriteFlush = 0;
} }
errorret_t spriteBatchFlush() { errorret_t spriteBatchFlush() {
@@ -84,10 +79,19 @@ errorret_t spriteBatchFlush() {
} }
size_t vertexCount = QUAD_VERTEX_COUNT * SPRITEBATCH.spriteCount; size_t vertexCount = QUAD_VERTEX_COUNT * SPRITEBATCH.spriteCount;
errorChain(meshFlush(&SPRITEBATCH.mesh, 0, vertexCount)); size_t vertexOffset = (
errorChain(textureBind(SPRITEBATCH.currentTexture)); SPRITEBATCH.spriteFlush * SPRITEBATCH_SPRITES_MAX_PER_FLUSH *
errorChain(meshDraw(&SPRITEBATCH.mesh, 0, vertexCount)); QUAD_VERTEX_COUNT
spriteBatchClear(); );
errorChain(meshFlush(&SPRITEBATCH.mesh, vertexOffset, vertexCount));
errorChain(meshDraw(&SPRITEBATCH.mesh, vertexOffset, vertexCount));
SPRITEBATCH.spriteFlush++;
if(SPRITEBATCH.spriteFlush >= SPRITEBATCH_FLUSH_COUNT) {
SPRITEBATCH.spriteFlush = 0;
}
SPRITEBATCH.spriteCount = 0;
errorOk(); errorOk();
} }

View File

@@ -7,16 +7,18 @@
#pragma once #pragma once
#include "display/mesh/quad.h" #include "display/mesh/quad.h"
#include "display/texture/texture.h"
#define SPRITEBATCH_SPRITES_MAX 1 #define SPRITEBATCH_SPRITES_MAX 32
#define SPRITEBATCH_VERTEX_COUNT (SPRITEBATCH_SPRITES_MAX * QUAD_VERTEX_COUNT) #define SPRITEBATCH_VERTEX_COUNT (SPRITEBATCH_SPRITES_MAX * QUAD_VERTEX_COUNT)
#define SPRITEBATCH_FLUSH_COUNT 4
#define SPRITEBATCH_SPRITES_MAX_PER_FLUSH (\
SPRITEBATCH_SPRITES_MAX / SPRITEBATCH_FLUSH_COUNT \
)
typedef struct { typedef struct {
mesh_t mesh; mesh_t mesh;
int32_t spriteCount; int32_t spriteCount;
texture_t *currentTexture; int32_t spriteFlush;
} spritebatch_t; } spritebatch_t;
// Have to define these seperately because of alignment in certain platforms. // Have to define these seperately because of alignment in certain platforms.
@@ -39,7 +41,6 @@ errorret_t spriteBatchInit();
* Currently changing texture pointer will cause the buffer to flush but this is * Currently changing texture pointer will cause the buffer to flush but this is
* also likely to change in the future. * also likely to change in the future.
* *
* @param texture The texture to use for the sprite.
* @param minX The minimum x coordinate of the sprite. * @param minX The minimum x coordinate of the sprite.
* @param minY The minimum y coordinate of the sprite. * @param minY The minimum y coordinate of the sprite.
* @param maxX The maximum x coordinate of the sprite. * @param maxX The maximum x coordinate of the sprite.
@@ -52,7 +53,6 @@ errorret_t spriteBatchInit();
* @return An error code indicating success or failure. * @return An error code indicating success or failure.
*/ */
errorret_t spriteBatchPush( errorret_t spriteBatchPush(
texture_t *texture,
const float_t minX, const float_t minX,
const float_t minY, const float_t minY,
const float_t maxX, const float_t maxX,
@@ -68,7 +68,6 @@ errorret_t spriteBatchPush(
* Pushes a 3D sprite to the batch. This is like spriteBatchPush but takes * Pushes a 3D sprite to the batch. This is like spriteBatchPush but takes
* 3D coordinates instead of 2D. * 3D coordinates instead of 2D.
* *
* @param texture The texture to use for the sprite.
* @param min The minimum (x,y,z) coordinate of the sprite. * @param min The minimum (x,y,z) coordinate of the sprite.
* @param max The maximum (x,y,z) coordinate of the sprite. * @param max The maximum (x,y,z) coordinate of the sprite.
* @param color The color to tint the sprite with. * @param color The color to tint the sprite with.
@@ -77,7 +76,6 @@ errorret_t spriteBatchPush(
* @return An error code indicating success or failure. * @return An error code indicating success or failure.
*/ */
errorret_t spriteBatchPush3D( errorret_t spriteBatchPush3D(
texture_t *texture,
const vec3 min, const vec3 min,
const vec3 max, const vec3 max,
const color_t color, const color_t color,

View File

@@ -9,19 +9,23 @@
#include "assert/assert.h" #include "assert/assert.h"
#include "util/memory.h" #include "util/memory.h"
#include "display/spritebatch/spritebatch.h" #include "display/spritebatch/spritebatch.h"
#include "asset/asset.h" #include "asset/loader/display/assettextureloader.h"
#include "asset/loader/display/assettilesetloader.h"
#include "display/shader/shaderunlit.h"
texture_t DEFAULT_FONT_TEXTURE; texture_t DEFAULT_FONT_TEXTURE;
tileset_t DEFAULT_FONT_TILESET; tileset_t DEFAULT_FONT_TILESET;
errorret_t textInit(void) { errorret_t textInit(void) {
// errorChain(assetLoad("ui/minogram.dpt", &DEFAULT_FONT_TEXTURE)); errorChain(assetTextureLoad(
// errorChain(assetLoad("ui/minogram.dtf", &DEFAULT_FONT_TILESET)); "ui/minogram.png", &DEFAULT_FONT_TEXTURE, TEXTURE_FORMAT_RGBA
));
errorChain(assetTilesetLoad("ui/minogram.dtf", &DEFAULT_FONT_TILESET));
errorOk(); errorOk();
} }
errorret_t textDispose(void) { errorret_t textDispose(void) {
// errorChain(textureDispose(&DEFAULT_FONT_TEXTURE)); errorChain(textureDispose(&DEFAULT_FONT_TEXTURE));
errorOk(); errorOk();
} }
@@ -45,8 +49,9 @@ errorret_t textDrawChar(
vec4 uv; vec4 uv;
tilesetTileGetUV(tileset, tileIndex, uv); tilesetTileGetUV(tileset, tileIndex, uv);
errorChain(spriteBatchPush( errorChain(spriteBatchPush(
texture, // texture,
x, y, x, y,
x + tileset->tileWidth, x + tileset->tileWidth,
y + tileset->tileHeight, y + tileset->tileHeight,
@@ -70,6 +75,17 @@ errorret_t textDraw(
float_t posX = x; float_t posX = x;
float_t posY = y; float_t posY = y;
errorChain(shaderSetTexture(&SHADER_UNLIT, SHADER_UNLIT_TEXTURE, texture));
// errorChain(spriteBatchPush(
// // texture,
// posX, posY,
// posX + texture->width * 1, posY + texture->height * 1,
// color,
// 0.0f, 0.0f, 1.0f, 1.0f
// ));
// errorOk();
char_t c; char_t c;
int32_t i = 0; int32_t i = 0;
while((c = text[i++]) != '\0') { while((c = text[i++]) != '\0') {

View File

@@ -8,4 +8,5 @@ target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC PUBLIC
tileset.c tileset.c
texture.c texture.c
palette.c
) )

View File

@@ -0,0 +1,10 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "palette.h"
palette_t PALETTES[PALETTE_COUNT];

View File

@@ -0,0 +1,19 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "display/color.h"
#define PALETTE_COLOR_COUNT 0xFF
#define PALETTE_COUNT 6
typedef struct {
color_t colors[PALETTE_COLOR_COUNT];
uint8_t count;
} palette_t;
extern palette_t PALETTES[PALETTE_COUNT];

View File

@@ -11,8 +11,6 @@
#include "util/math.h" #include "util/math.h"
#include "display/display.h" #include "display/display.h"
texture_t *TEXTURE_BOUND = NULL;
errorret_t textureInit( errorret_t textureInit(
texture_t *texture, texture_t *texture,
const int32_t width, const int32_t width,
@@ -25,6 +23,18 @@ errorret_t textureInit(
assertTrue(width == mathNextPowTwo(width), "Width must be a power of 2."); assertTrue(width == mathNextPowTwo(width), "Width must be a power of 2.");
assertTrue(height == mathNextPowTwo(height), "Height must be a power of 2."); assertTrue(height == mathNextPowTwo(height), "Height must be a power of 2.");
if(texture->format == TEXTURE_FORMAT_RGBA) {
assertNotNull(data.rgbaColors, "RGBA color data cannot be NULL");
} else if(texture->format == TEXTURE_FORMAT_PALETTE) {
assertNotNull(data.paletted.indices, "Palette indices cannot be NULL");
assertNotNull(data.paletted.palette, "Palette colors cannot be NULL");
assertTrue(
data.paletted.palette->count ==
mathNextPowTwo(data.paletted.palette->count),
"Palette color count must be a power of 2"
);
}
memoryZero(texture, sizeof(texture_t)); memoryZero(texture, sizeof(texture_t));
texture->width = width; texture->width = width;
texture->height = height; texture->height = height;
@@ -34,18 +44,9 @@ errorret_t textureInit(
errorOk(); errorOk();
} }
errorret_t textureBind(texture_t *texture) {
errorChain(textureBindPlatform(texture));
errorOk();
}
errorret_t textureDispose(texture_t *texture) { errorret_t textureDispose(texture_t *texture) {
assertNotNull(texture, "Texture cannot be NULL"); assertNotNull(texture, "Texture cannot be NULL");
if(TEXTURE_BOUND == texture) {
textureBind(NULL);
}
errorChain(textureDisposePlatform(texture)); errorChain(textureDisposePlatform(texture));
errorOk(); errorOk();
} }

View File

@@ -7,15 +7,12 @@
#pragma once #pragma once
#include "error/error.h" #include "error/error.h"
#include "display/color.h" #include "display/texture/palette.h"
#include "display/texture/textureplatform.h" #include "display/texture/textureplatform.h"
#ifndef textureInitPlatform #ifndef textureInitPlatform
#error "textureInitPlatform should not be defined." #error "textureInitPlatform should not be defined."
#endif #endif
#ifndef textureBindPlatform
#error "textureBindPlatform should not be defined."
#endif
#ifndef textureDisposePlatform #ifndef textureDisposePlatform
#error "textureDisposePlatform should not be defined." #error "textureDisposePlatform should not be defined."
#endif #endif
@@ -24,12 +21,13 @@ typedef textureformatplatform_t textureformat_t;
typedef textureplatform_t texture_t; typedef textureplatform_t texture_t;
typedef union texturedata_u { typedef union texturedata_u {
uint8_t *paletteData; struct {
uint8_t *indices;
palette_t *palette;
} paletted;
color_t *rgbaColors; color_t *rgbaColors;
} texturedata_t; } texturedata_t;
extern texture_t *TEXTURE_BOUND;
/** /**
* Initializes a texture. * Initializes a texture.
* *
@@ -47,13 +45,6 @@ errorret_t textureInit(
const texturedata_t data const texturedata_t data
); );
/**
* Binds a texture for rendering. Providing NULL will unbind any texture.
*
* @param texture The texture to bind.
*/
errorret_t textureBind(texture_t *texture);
/** /**
* Disposes a texture. * Disposes a texture.
* *

View File

@@ -14,10 +14,11 @@
#include "scene/scene.h" #include "scene/scene.h"
#include "asset/asset.h" #include "asset/asset.h"
#include "ui/ui.h" #include "ui/ui.h"
#include "map/map.h"
#include "script/scriptmanager.h" #include "script/scriptmanager.h"
#include "item/backpack.h"
#include "assert/assert.h" #include "assert/assert.h"
#include "game/game.h"
#include "asset/loader/json/assetjsonloader.h"
engine_t ENGINE; engine_t ENGINE;
@@ -35,9 +36,8 @@ errorret_t engineInit(const int32_t argc, const char_t **argv) {
errorChain(scriptManagerInit()); errorChain(scriptManagerInit());
errorChain(displayInit()); errorChain(displayInit());
errorChain(uiInit()); errorChain(uiInit());
errorChain(mapInit());
errorChain(sceneInit()); errorChain(sceneInit());
backpackInit(); errorChain(gameInit());
// Run the initial script. // Run the initial script.
scriptcontext_t ctx; scriptcontext_t ctx;
@@ -54,7 +54,7 @@ errorret_t engineUpdate(void) {
uiUpdate(); uiUpdate();
errorChain(sceneUpdate()); errorChain(sceneUpdate());
mapUpdate(); errorChain(gameUpdate());
errorChain(displayUpdate()); errorChain(displayUpdate());
if(inputPressed(INPUT_ACTION_RAGEQUIT)) ENGINE.running = false; if(inputPressed(INPUT_ACTION_RAGEQUIT)) ENGINE.running = false;
@@ -68,7 +68,7 @@ void engineExit(void) {
errorret_t engineDispose(void) { errorret_t engineDispose(void) {
sceneDispose(); sceneDispose();
mapDispose(); errorChain(gameDispose());
localeManagerDispose(); localeManagerDispose();
uiDispose(); uiDispose();
errorChain(displayDispose()); errorChain(displayDispose());

View File

@@ -9,5 +9,11 @@
#include "dusk.h" #include "dusk.h"
typedef struct { typedef struct {
const char_t *name;
const char_t *file; const char_t *file;
} localeinfo_t; } localeinfo_t;
static const localeinfo_t LOCALE_EN_US = {
.name = "en-US",
.file = "locale/en_US.po",
};

View File

@@ -7,32 +7,34 @@
#include "localemanager.h" #include "localemanager.h"
#include "util/memory.h" #include "util/memory.h"
#include "asset/asset.h"
#include "assert/assert.h" #include "assert/assert.h"
localemanager_t LOCALE; localemanager_t LOCALE;
errorret_t localeManagerInit() { errorret_t localeManagerInit() {
memoryZero(&LOCALE, sizeof(localemanager_t)); memoryZero(&LOCALE, sizeof(localemanager_t));
errorChain(localeManagerSetLocale(&LOCALE_EN_US));
errorOk(); errorOk();
} }
errorret_t localeManagerSetLocale(const dusklocale_t locale) { errorret_t localeManagerSetLocale(const localeinfo_t *locale) {
errorThrow("Locale setting is not yet implemented."); if(LOCALE.fileOpen) {
// assertTrue(locale < DUSK_LOCALE_COUNT, "Invalid locale."); errorChain(assetLocaleFileDispose(&LOCALE.file));
// assertTrue(locale != DUSK_LOCALE_NULL, "Cannot set locale to NULL."); LOCALE.fileOpen = false;
}
// LOCALE.locale = locale; // Init the asset file
// char_t languageFile[FILENAME_MAX]; errorChain(assetLocaleFileInit(&LOCALE.file, locale->file));
// snprintf( LOCALE.fileOpen = true;
// languageFile, FILENAME_MAX, "language/%s.dlf", LOCALE_INFOS[locale].file
// ); errorOk();
// assetLanguageDispose(&LOCALE.language);
// memoryZero(&LOCALE.language, sizeof(assetlanguage_t));
// errorChain(assetLoad(languageFile, &LOCALE.language));
// errorOk();
} }
void localeManagerDispose() { void localeManagerDispose() {
assetLanguageDispose(&LOCALE.language); if(LOCALE.fileOpen) {
errorCatch(errorPrint(assetLocaleFileDispose(&LOCALE.file)));
LOCALE.fileOpen = false;
}
} }

View File

@@ -6,13 +6,15 @@
*/ */
#pragma once #pragma once
#include "asset/asset.h" #include "error/error.h"
#include "localemanager.h" #include "localemanager.h"
#include "locale/locale.h" #include "locale/localeinfo.h"
#include "asset/loader/locale/assetlocaleloader.h"
typedef struct { typedef struct {
dusklocale_t locale; const localeinfo_t *locale;
assetlanguage_t language; assetlocalefile_t file;
bool_t fileOpen;
} localemanager_t; } localemanager_t;
extern localemanager_t LOCALE; extern localemanager_t LOCALE;
@@ -30,7 +32,51 @@ errorret_t localeManagerInit();
* @param locale The locale to set. * @param locale The locale to set.
* @return An error code if a failure occurs. * @return An error code if a failure occurs.
*/ */
errorret_t localeManagerSetLocale(const dusklocale_t locale); errorret_t localeManagerSetLocale(const localeinfo_t *locale);
/**
* Get a localized string for the given message ID.
*
* @param id The message ID to retrieve.
* @param buffer Buffer to write the retrieved string to.
* @param bufferSize Size of the buffer.
* @param plural Plural index to retrieve.
* @param ... Additional arguments for formatting the string.
* @return An error code if a failure occurs.
*/
#define localeManagerGetText(id, buffer, bufferSize, plural, ...) \
assetLocaleGetStringWithVA( \
&LOCALE.file, \
id, \
plural, \
buffer, \
bufferSize, \
__VA_ARGS__ \
)
/**
* Get a localized string for the given message ID with a list of arguments.
*
* @param id The message ID to retrieve.
* @param buffer Buffer to write the retrieved string to.
* @param bufferSize Size of the buffer.
* @param plural Plural index to retrieve.
* @param args List of arguments for formatting the string.
* @param argCount Number of arguments in the list.
* @return An error code if a failure occurs.
*/
#define localeManagerGetTextArgs( \
id, buffer, bufferSize, plural, args, argCount \
) \
assetLocaleGetStringWithArgs( \
&LOCALE.file, \
id, \
plural, \
buffer, \
bufferSize, \
args, \
argCount \
)
/** /**
* Dispose of the locale system. * Dispose of the locale system.

View File

@@ -22,7 +22,7 @@ errorret_t sceneInit(void) {
errorret_t sceneUpdate(void) { errorret_t sceneUpdate(void) {
#ifdef DUSK_TIME_DYNAMIC #ifdef DUSK_TIME_DYNAMIC
if(!TIME.dynamicUpdate) { if(TIME.dynamicUpdate) {
errorOk(); errorOk();
} }
#endif #endif

View File

@@ -7,11 +7,8 @@
add_subdirectory(display) add_subdirectory(display)
add_subdirectory(event) add_subdirectory(event)
add_subdirectory(input) add_subdirectory(input)
add_subdirectory(item)
add_subdirectory(locale) add_subdirectory(locale)
add_subdirectory(map)
add_subdirectory(system) add_subdirectory(system)
add_subdirectory(scene) add_subdirectory(scene)
add_subdirectory(story)
add_subdirectory(time) add_subdirectory(time)
add_subdirectory(ui) add_subdirectory(ui)

View File

@@ -15,4 +15,5 @@ target_sources(${DUSK_LIBRARY_TARGET_NAME}
modulescreen.c modulescreen.c
moduletileset.c moduletileset.c
moduletexture.c moduletexture.c
moduleshader.c
) )

View File

@@ -69,6 +69,16 @@ void moduleCamera(scriptcontext_t *context) {
// Methods // Methods
lua_register(context->luaState, "cameraCreate", moduleCameraCreate); lua_register(context->luaState, "cameraCreate", moduleCameraCreate);
lua_register(
context->luaState,
"cameraGetProjectionMatrix",
moduleCameraGetProjectionMatrix
);
lua_register(
context->luaState,
"cameraGetViewMatrix",
moduleCameraGetViewMatrix
);
} }
int moduleCameraCreate(lua_State *L) { int moduleCameraCreate(lua_State *L) {
@@ -289,3 +299,35 @@ int moduleCameraNewIndex(lua_State *l) {
return 0; return 0;
} }
int moduleCameraGetProjectionMatrix(lua_State *L) {
assertNotNull(L, "Lua state cannot be NULL.");
camera_t *cam = (camera_t *)luaL_checkudata(L, 1, "camera_mt");
assertNotNull(cam, "Camera pointer cannot be NULL.");
// Create mat4
mat4 test;
cameraGetProjectionMatrix(cam, test);
// Lua needs to own this matrix now
mat4 *m = (mat4 *)lua_newuserdata(L, sizeof(mat4));
memoryCopy(m, test, sizeof(mat4));
return 1;
}
int moduleCameraGetViewMatrix(lua_State *L) {
assertNotNull(L, "Lua state cannot be NULL.");
camera_t *cam = (camera_t *)luaL_checkudata(L, 1, "camera_mt");
assertNotNull(cam, "Camera pointer cannot be NULL.");
// Create mat4
mat4 test;
cameraGetViewMatrix(cam, test);
// Lua needs to own this matrix now
mat4 *m = (mat4 *)lua_newuserdata(L, sizeof(mat4));
memoryCopy(m, test, sizeof(mat4));
return 1;
}

View File

@@ -36,3 +36,19 @@ int moduleCameraIndex(lua_State *l);
* @param l The Lua state. * @param l The Lua state.
*/ */
int moduleCameraNewIndex(lua_State *l); int moduleCameraNewIndex(lua_State *l);
/**
* Script binding for getting a camera's projection matrix.
*
* @param L The Lua state.
* @return Number of return values on the Lua stack.
*/
int moduleCameraGetProjectionMatrix(lua_State *L);
/**
* Script binding for getting a camera's view matrix.
*
* @param L The Lua state.
* @return Number of return values on the Lua stack.
*/
int moduleCameraGetViewMatrix(lua_State *L);

View File

@@ -0,0 +1,120 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "moduleshader.h"
#include "assert/assert.h"
#include "display/shader/shader.h"
#include "display/shader/shaderunlit.h"
#include "display/camera/camera.h"
void moduleShader(scriptcontext_t *context) {
assertNotNull(context, "Context cannot be NULL.");
// Shader unlit defs
lua_pushlightuserdata(context->luaState, &SHADER_UNLIT);
lua_setglobal(context->luaState, "SHADER_UNLIT");
lua_pushstring(context->luaState, SHADER_UNLIT_PROJECTION);
lua_setglobal(context->luaState, "SHADER_UNLIT_PROJECTION");
lua_pushstring(context->luaState, SHADER_UNLIT_VIEW);
lua_setglobal(context->luaState, "SHADER_UNLIT_VIEW");
lua_pushstring(context->luaState, SHADER_UNLIT_MODEL);
lua_setglobal(context->luaState, "SHADER_UNLIT_MODEL");
lua_pushstring(context->luaState, SHADER_UNLIT_TEXTURE);
lua_setglobal(context->luaState, "SHADER_UNLIT_TEXTURE");
// Shader methods
lua_register(context->luaState, "shaderBind", moduleShaderBind);
lua_register(context->luaState, "shaderSetMatrix", moduleShaderSetMatrix);
lua_register(context->luaState, "shaderSetTexture", moduleShaderSetTexture);
}
int moduleShaderBind(lua_State *l) {
assertNotNull(l, "Lua state cannot be NULL.");
// Should be passed a shader userdata pointer only.
shader_t *shader = (shader_t *)lua_touserdata(l, 1);
assertNotNull(shader, "Shader pointer cannot be NULL.");
errorret_t ret = shaderBind(shader);
if(ret.code != ERROR_OK) {
luaL_error(l, "Failed to bind shader: %s", ret.state->message);
errorCatch(errorPrint(ret));
return 0;
}
return 0;
}
int moduleShaderSetMatrix(lua_State *l) {
assertNotNull(l, "Lua state cannot be NULL.");
// Expect shader, string and matrix.
if(!lua_isuserdata(l, 1)) {
luaL_error(l, "First argument must be a shader_mt userdata.");
return 0;
}
if(!lua_isstring(l, 2)) {
luaL_error(l, "Second argument must be a string.");
return 0;
}
if(!lua_isuserdata(l, 3)) {
luaL_error(l, "Third argument must be a mat4_mt userdata.");
return 0;
}
shader_t *shader = (shader_t *)lua_touserdata(l, 1);
assertNotNull(shader, "Shader pointer cannot be NULL.");
const char_t *uniformName = luaL_checkstring(l, 2);
assertStrLenMin(uniformName, 1, "Uniform name cannot be empty.");
mat4 *mat = (mat4 *)lua_touserdata(l, 3);
assertNotNull(mat, "Matrix pointer cannot be NULL.");
errorret_t ret = shaderSetMatrix(shader, uniformName, *mat);
if(ret.code != ERROR_OK) {
luaL_error(l, "Failed to set shader matrix: %s", ret.state->message);
errorCatch(errorPrint(ret));
return 0;
}
return 0;
}
int moduleShaderSetTexture(lua_State *l) {
assertNotNull(l, "Lua state cannot be NULL.");
shader_t *shader = (shader_t *)lua_touserdata(l, 1);
assertNotNull(shader, "Shader pointer cannot be NULL.");
const char_t *uniformName = luaL_checkstring(l, 2);
assertStrLenMin(uniformName, 1, "Uniform name cannot be empty.");
texture_t *texture;
// Texture can be Nil or a pointer, if not nil it must be a texture pointer.
if(lua_isnil(l, 3)) {
texture = NULL;
} else if(lua_isuserdata(l, 3)) {
texture = (texture_t *)lua_touserdata(l, 3);
assertNotNull(texture, "Texture pointer cannot be NULL.");
} else {
luaL_error(l, "Third argument must be a texture_mt userdata or nil.");
return 0;
}
errorret_t ret = shaderSetTexture(shader, uniformName, texture);
if(ret.code != ERROR_OK) {
luaL_error(l, "Failed to set shader texture: %s", ret.state->message);
errorCatch(errorPrint(ret));
return 0;
}
return 0;
}

View File

@@ -0,0 +1,42 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "script/scriptcontext.h"
/**
* Register shader functions to the given script context.
*
* @param context The script context to register shader functions to.
*/
void moduleShader(scriptcontext_t *context);
/**
* Script binding for binding a shader.
*
* @param l The Lua state.
* @return Number of return values on the Lua stack.
*/
int moduleShaderBind(lua_State *l);
/**
* Script binding for setting a matrix uniform in a shader.
*
* @param l The Lua state.
* @return Number of return values on the Lua stack.
*/
int moduleShaderSetMatrix(lua_State *l);
/**
* Script binding for setting a texture uniform in a shader.
*
* @param l The Lua state.
* @return Number of return values on the Lua stack.
*/
int moduleShaderSetTexture(lua_State *l);
errorret_t doThing();

View File

@@ -32,32 +32,20 @@ int moduleSpriteBatchClear(lua_State *L) {
int moduleSpriteBatchPush(lua_State *L) { int moduleSpriteBatchPush(lua_State *L) {
assertNotNull(L, "Lua state is null"); assertNotNull(L, "Lua state is null");
// Texture pointer or Nil for no texture
if(!lua_isuserdata(L, 1) && !lua_isnil(L, 1)) {
return luaL_error(L, "First argument must be a texture or nil");
}
// If texture is not nil, check it's a texture userdata
texture_t *tex = NULL;
if(lua_isuserdata(L, 1)) {
tex = (texture_t *)luaL_checkudata(L, 1, "texture_mt");
assertNotNull(tex, "Texture pointer cannot be NULL");
}
// MinX, MinY, MaxX, MaxY // MinX, MinY, MaxX, MaxY
if( if(
!lua_isnumber(L, 2) || !lua_isnumber(L, 3) || !lua_isnumber(L, 4) || !lua_isnumber(L, 1) || !lua_isnumber(L, 2) || !lua_isnumber(L, 3) ||
!lua_isnumber(L, 5) !lua_isnumber(L, 4)
) { ) {
return luaL_error(L, "Sprite coordinates must be numbers"); return luaL_error(L, "Sprite coordinates must be numbers");
} }
// Color (struct) or nil for white // Color (struct) or nil for white
color_t *color = NULL; color_t *color = NULL;
if(lua_gettop(L) < 6 || lua_isnil(L, 6)) { if(lua_gettop(L) < 5 || lua_isnil(L, 5)) {
// Allow NULL // Allow NULL
} else if(lua_isuserdata(L, 6)) { } else if(lua_isuserdata(L, 5)) {
color = (color_t*)luaL_checkudata(L, 6, "color_mt"); color = (color_t*)luaL_checkudata(L, 5, "color_mt");
} else { } else {
return luaL_error(L, "Sprite color must be a color struct or nil"); return luaL_error(L, "Sprite color must be a color struct or nil");
} }
@@ -68,31 +56,30 @@ int moduleSpriteBatchPush(lua_State *L) {
float_t u1 = 1.0f; float_t u1 = 1.0f;
float_t v1 = 1.0f; float_t v1 = 1.0f;
if(lua_gettop(L) >= 8) { if(lua_gettop(L) >= 7) {
if(!lua_isnumber(L, 7) || !lua_isnumber(L, 8)) { if(!lua_isnumber(L, 6) || !lua_isnumber(L, 7)) {
return luaL_error(L, "Sprite UV min coordinates must be numbers"); return luaL_error(L, "Sprite UV min coordinates must be numbers");
} }
u0 = (float_t)lua_tonumber(L, 7); u0 = (float_t)lua_tonumber(L, 6);
v0 = (float_t)lua_tonumber(L, 8); v0 = (float_t)lua_tonumber(L, 7);
} }
if(lua_gettop(L) >= 10) { if(lua_gettop(L) >= 9) {
if(!lua_isnumber(L, 9) || !lua_isnumber(L, 10)) { if(!lua_isnumber(L, 8) || !lua_isnumber(L, 9)) {
return luaL_error(L, "Sprite UV max coordinates must be numbers"); return luaL_error(L, "Sprite UV max coordinates must be numbers");
} }
u1 = (float_t)lua_tonumber(L, 9); u1 = (float_t)lua_tonumber(L, 8);
v1 = (float_t)lua_tonumber(L, 10); v1 = (float_t)lua_tonumber(L, 9);
} }
float_t minX = (float_t)lua_tonumber(L, 2); float_t minX = (float_t)lua_tonumber(L, 1);
float_t minY = (float_t)lua_tonumber(L, 3); float_t minY = (float_t)lua_tonumber(L, 2);
float_t maxX = (float_t)lua_tonumber(L, 4); float_t maxX = (float_t)lua_tonumber(L, 3);
float_t maxY = (float_t)lua_tonumber(L, 5); float_t maxY = (float_t)lua_tonumber(L, 4);
errorret_t ret = spriteBatchPush( errorret_t ret = spriteBatchPush(
tex,
minX, minX,
minY, minY,
maxX, maxX,

View File

@@ -6,9 +6,9 @@
*/ */
#include "moduletexture.h" #include "moduletexture.h"
#include "asset/asset.h"
#include "display/texture/texture.h"
#include "assert/assert.h" #include "assert/assert.h"
#include "display/texture/texture.h"
#include "asset/loader/display/assettextureloader.h"
#include "util/memory.h" #include "util/memory.h"
#include "util/string.h" #include "util/string.h"
@@ -84,6 +84,11 @@ int moduleTextureLoad(lua_State *l) {
return 0; return 0;
} }
if(!lua_isnumber(l, 2)) {
luaL_error(l, "Second argument must be a number format.");
return 0;
}
const char_t *filename = lua_tostring(l, 1); const char_t *filename = lua_tostring(l, 1);
assertNotNull(filename, "Filename cannot be NULL."); assertNotNull(filename, "Filename cannot be NULL.");
assertStrLenMin(filename, 1, "Filename cannot be empty."); assertStrLenMin(filename, 1, "Filename cannot be empty.");
@@ -92,7 +97,9 @@ int moduleTextureLoad(lua_State *l) {
texture_t *tex = (texture_t *)lua_newuserdata(l, sizeof(texture_t)); texture_t *tex = (texture_t *)lua_newuserdata(l, sizeof(texture_t));
memoryZero(tex, sizeof(texture_t)); memoryZero(tex, sizeof(texture_t));
errorret_t ret = assetLoad(filename, tex); textureformat_t format = (textureformat_t)lua_tonumber(l, 2);
errorret_t ret = assetTextureLoad(filename, tex, format);
if(ret.code != ERROR_OK) { if(ret.code != ERROR_OK) {
errorCatch(errorPrint(ret)); errorCatch(errorPrint(ret));
luaL_error(l, "Failed to load texture asset: %s", filename); luaL_error(l, "Failed to load texture asset: %s", filename);

View File

@@ -13,66 +13,87 @@ void moduleLocale(scriptcontext_t *context) {
assertNotNull(context, "Script context cannot be NULL"); assertNotNull(context, "Script context cannot be NULL");
// Execute the locale script definitions. // Execute the locale script definitions.
// scriptContextExec(context, LOCALE_SCRIPT); lua_register(context->luaState, "localeGetText", moduleLocaleGetText);
// lua_register(context->luaState, "localeGet", moduleLocaleGet);
// lua_register(context->luaState, "localeSet", moduleLocaleSet);
// lua_register(context->luaState, "localeGetName", moduleLocaleGetName);
} }
// int moduleLocaleGet(lua_State *L) { int moduleLocaleGetText(lua_State *L) {
// assertNotNull(L, "Lua state cannot be NULL"); // Expect string param for the id
if(!lua_isstring(L, 1)) {
luaL_error(L, "Expected message ID as first argument");
return 0;
}
// // No arguments expected const char_t *id = lua_tostring(L, 1);
// dusklocale_t locale = LOCALE.locale; if(id == NULL || strlen(id) == 0) {
// lua_pushnumber(L, (lua_Number)locale); luaL_error(L, "Message ID cannot be NULL or empty");
// return 1; return 0;
// } }
// int moduleLocaleSet(lua_State *L) { // Optional plural param, default to 0
// assertNotNull(L, "Lua state cannot be NULL"); int32_t plural = 0;
int top = lua_gettop(L);
int argStart = 2;
// // Requires locale ID if(top >= 2 && !lua_isnil(L, 2)) {
// if(!lua_isnumber(L, 1)) { if(!lua_isnumber(L, 2)) {
// luaL_error(L, "localeSet: Expected locale ID as first argument"); luaL_error(L, "Expected plural as second argument");
// return 0; return 0;
// } }
// errorret_t err; plural = (int32_t)lua_tointeger(L, 2);
// dusklocale_t locale = (dusklocale_t)lua_tonumber(L, 1); if(plural < 0) {
// if(locale >= DUSK_LOCALE_COUNT || locale == DUSK_LOCALE_NULL) { luaL_error(L, "Plural cannot be negative");
// luaL_error(L, "localeSet: Invalid locale ID"); return 0;
// return 0; }
// }
// err = localeManagerSetLocale(locale); argStart = 3;
// if(err.code != ERROR_OK) { }
// luaL_error(L, "localeSet: Failed to set locale");
// errorCatch(errorPrint(err));
// return 0;
// }
// return 0; // Build structured arg list from remaining Lua args
// } size_t argCount = (top >= argStart) ? (size_t)(top - argStart + 1) : 0;
#define MODULE_LOCALE_MAX_ARGS 16
assetlocalearg_t argsStack[MODULE_LOCALE_MAX_ARGS];
assetlocalearg_t *args = argsStack;
// int moduleLocaleGetName(lua_State *L) { if(argCount > MODULE_LOCALE_MAX_ARGS) {
// assertNotNull(L, "Lua state cannot be NULL"); luaL_error(L, "Too many args (max %d)", MODULE_LOCALE_MAX_ARGS);
return 0;
}
// // Optional ID, otherwise return current locale name for(size_t i = 0; i < argCount; ++i) {
// dusklocale_t locale = LOCALE.locale; int luaIndex = argStart + (int)i;
// if(lua_gettop(L) >= 1) {
// if(!lua_isnumber(L, 1)) {
// luaL_error(L, "localeGetName: Expected locale ID as first argument");
// return 0;
// }
// locale = (dusklocale_t)lua_tonumber(L, 1);
// if(locale >= DUSK_LOCALE_COUNT || locale == DUSK_LOCALE_NULL) {
// luaL_error(L, "localeGetName: Invalid locale ID");
// return 0;
// }
// }
// const char_t *localeName = LOCALE_INFOS[locale].file; if(lua_isinteger(L, luaIndex)) {
// lua_pushstring(L, localeName); args[i].type = ASSET_LOCALE_ARG_INT;
// return 1; args[i].intValue = (int32_t)lua_tonumber(L, luaIndex);
// } } else if(lua_isnumber(L, luaIndex)) {
args[i].type = ASSET_LOCALE_ARG_FLOAT;
args[i].floatValue = lua_tonumber(L, luaIndex);
} else if(lua_isstring(L, luaIndex)) {
args[i].type = ASSET_LOCALE_ARG_STRING;
args[i].stringValue = lua_tostring(L, luaIndex);
} else {
luaL_error(L, "Unsupported localization argument type");
return 0;
}
}
char_t buffer[1024];
errorret_t err = localeManagerGetTextArgs(
id,
buffer,
sizeof(buffer),
plural,
args,
argCount
);
if(err.code != ERROR_OK) {
errorCatch(errorPrint(err));
luaL_error(L, "Failed to get localized text for ID '%s'", id);
return 0;
}
lua_pushstring(L, buffer);
return 1;
}

View File

@@ -16,25 +16,9 @@
void moduleLocale(scriptcontext_t *context); void moduleLocale(scriptcontext_t *context);
/** /**
* Script binding for getting the current locale ID. * Script binding for getting a localized string.
* *
* @param L The Lua state. * @param L The Lua state.
* @return Number of return values on the Lua stack. * @return The number of return values on the Lua stack.
*/ */
int moduleLocaleGet(lua_State *L); int moduleLocaleGetText(lua_State *L);
/**
* Script binding for setting the current locale ID.
*
* @param L The Lua state.
* @return Number of return values on the Lua stack.
*/
int moduleLocaleSet(lua_State *L);
/**
* Script binding for getting the name of a locale by its ID.
*
* @param L The Lua state.
* @return Number of return values on the Lua stack.
*/
int moduleLocaleGetName(lua_State *L);

View File

@@ -11,6 +11,7 @@
#include "util/memory.h" #include "util/memory.h"
#include "script/scriptmodule.h" #include "script/scriptmodule.h"
#include "event/event.h" #include "event/event.h"
#include "asset/loader/script/assetscriptloader.h"
errorret_t scriptContextInit(scriptcontext_t *context) { errorret_t scriptContextInit(scriptcontext_t *context) {
assertNotNull(context, "Script context cannot be NULL"); assertNotNull(context, "Script context cannot be NULL");
@@ -53,26 +54,7 @@ errorret_t scriptContextExec(scriptcontext_t *context, const char_t *script) {
errorret_t scriptContextExecFile(scriptcontext_t *ctx, const char_t *fname) { errorret_t scriptContextExecFile(scriptcontext_t *ctx, const char_t *fname) {
assertNotNull(ctx, "Script context cannot be NULL"); assertNotNull(ctx, "Script context cannot be NULL");
assertNotNull(fname, "Filename cannot be NULL"); assertNotNull(fname, "Filename cannot be NULL");
return assetScriptLoad(fname, ctx);
assetscript_t script;
errorChain(assetLoad(fname, &script));
if(lua_load(
ctx->luaState, assetScriptReader, &script, fname, NULL
) != LUA_OK) {
const char_t *strErr = lua_tostring(ctx->luaState, -1);
lua_pop(ctx->luaState, 1);
errorThrow("Failed to load Lua script: %s", strErr);
}
if(lua_pcall(ctx->luaState, 0, LUA_MULTRET, 0) != LUA_OK) {
const char_t *strErr = lua_tostring(ctx->luaState, -1);
lua_pop(ctx->luaState, 1);
errorThrow("Failed to execute Lua script: %s", strErr);
}
errorChain(assetScriptDispose(&script));
errorOk();
} }
void scriptContextDispose(scriptcontext_t *context) { void scriptContextDispose(scriptcontext_t *context) {

View File

@@ -10,7 +10,6 @@
#include "script/module/input/moduleinput.h" #include "script/module/input/moduleinput.h"
#include "script/module/moduleplatform.h" #include "script/module/moduleplatform.h"
#include "script/module/scene/modulescene.h" #include "script/module/scene/modulescene.h"
#include "script/module/item/moduleitem.h"
#include "script/module/locale/modulelocale.h" #include "script/module/locale/modulelocale.h"
#include "script/module/time/moduletime.h" #include "script/module/time/moduletime.h"
#include "script/module/event/moduleevent.h" #include "script/module/event/moduleevent.h"
@@ -18,13 +17,13 @@
#include "script/module/display/modulespritebatch.h" #include "script/module/display/modulespritebatch.h"
#include "script/module/display/modulecamera.h" #include "script/module/display/modulecamera.h"
#include "script/module/display/moduleglm.h" #include "script/module/display/moduleglm.h"
#include "script/module/display/moduleshader.h"
#include "script/module/ui/moduleui.h" #include "script/module/ui/moduleui.h"
#include "script/module/display/moduletext.h" #include "script/module/display/moduletext.h"
#include "script/module/display/modulescreen.h" #include "script/module/display/modulescreen.h"
#include "script/module/story/modulestoryflag.h"
#include "script/module/map/modulemap.h"
#include "script/module/display/moduletexture.h" #include "script/module/display/moduletexture.h"
#include "script/module/display/moduletileset.h" #include "script/module/display/moduletileset.h"
#include "script/scriptgame.h"
#include "util/string.h" #include "util/string.h"
const scriptmodule_t SCRIPT_MODULE_LIST[] = { const scriptmodule_t SCRIPT_MODULE_LIST[] = {
@@ -33,7 +32,6 @@ const scriptmodule_t SCRIPT_MODULE_LIST[] = {
{ .name = "platform", .callback = modulePlatform }, { .name = "platform", .callback = modulePlatform },
{ .name = "color", .callback = moduleColor }, { .name = "color", .callback = moduleColor },
{ .name = "scene", .callback = moduleScene }, { .name = "scene", .callback = moduleScene },
{ .name = "item", .callback = moduleItem },
{ .name = "locale", .callback = moduleLocale }, { .name = "locale", .callback = moduleLocale },
{ .name = "time", .callback = moduleTime }, { .name = "time", .callback = moduleTime },
{ .name = "event", .callback = moduleEvent }, { .name = "event", .callback = moduleEvent },
@@ -43,10 +41,13 @@ const scriptmodule_t SCRIPT_MODULE_LIST[] = {
{ .name = "ui", .callback = moduleUi }, { .name = "ui", .callback = moduleUi },
{ .name = "text", .callback = moduleText }, { .name = "text", .callback = moduleText },
{ .name = "screen", .callback = moduleScreen }, { .name = "screen", .callback = moduleScreen },
{ .name = "storyflag", .callback = moduleStoryFlag },
{ .name = "map", .callback = moduleMap },
{ .name = "texture", .callback = moduleTexture }, { .name = "texture", .callback = moduleTexture },
{ .name = "tileset", .callback = moduleTileset }, { .name = "tileset", .callback = moduleTileset },
{ .name = "shader", .callback = moduleShader },
#ifdef SCRIPT_GAME_LIST
SCRIPT_GAME_LIST
#endif
}; };
#define SCRIPT_MODULE_COUNT ( \ #define SCRIPT_MODULE_COUNT ( \

View File

@@ -82,7 +82,7 @@ int_t memoryCompare(
) { ) {
assertNotNull(a, "Cannot compare NULL memory."); assertNotNull(a, "Cannot compare NULL memory.");
assertNotNull(b, "Cannot compare NULL memory."); assertNotNull(b, "Cannot compare NULL memory.");
assertTrue(size > 0, "Cannot compare 0 bytes of memory."); assertTrue(size >= 0, "Cannot compare negative bytes of memory.");
return memcmp(a, b, size); return memcmp(a, b, size);
} }

View File

@@ -15,3 +15,4 @@ add_subdirectory(camera)
add_subdirectory(framebuffer) add_subdirectory(framebuffer)
add_subdirectory(mesh) add_subdirectory(mesh)
add_subdirectory(texture) add_subdirectory(texture)
add_subdirectory(shader)

View File

@@ -11,6 +11,10 @@
void cameraPushMatrixDolphin(camera_t *camera) { void cameraPushMatrixDolphin(camera_t *camera) {
assertNotNull(camera, "Camera cannot be null"); assertNotNull(camera, "Camera cannot be null");
assertTrue(
camera->nearClip > 0.0f,
"Camera near clip must be greater than 0 for Dolphin"
);
Mtx44 guProjection; Mtx44 guProjection;
Mtx guView; Mtx guView;

View File

@@ -77,7 +77,8 @@ errorret_t displayInitDolphin(void) {
// Setup cull modes // Setup cull modes
GX_SetCullMode(GX_CULL_NONE); GX_SetCullMode(GX_CULL_NONE);
GX_SetZMode(GX_FALSE, GX_ALWAYS, GX_FALSE); GX_SetBlendMode(GX_BM_BLEND, GX_BL_SRCALPHA, GX_BL_INVSRCALPHA, GX_LO_CLEAR);
GX_SetZMode(GX_TRUE, GX_ALWAYS, GX_FALSE);
GX_SetDispCopyGamma(GX_GM_1_0); GX_SetDispCopyGamma(GX_GM_1_0);
GX_SetColorUpdate(GX_TRUE); GX_SetColorUpdate(GX_TRUE);

View File

@@ -8,6 +8,7 @@
#include "display/mesh/mesh.h" #include "display/mesh/mesh.h"
#include "display/texture/texture.h" #include "display/texture/texture.h"
#include "assert/assert.h" #include "assert/assert.h"
#include "display/shader/shader.h"
errorret_t meshInitDolphin( errorret_t meshInitDolphin(
meshdolphin_t *mesh, meshdolphin_t *mesh,
@@ -46,18 +47,21 @@ errorret_t meshDrawDolphin(
assertTrue(offsetof(meshvertex_t, uv) == 4, "uv offset wrong"); assertTrue(offsetof(meshvertex_t, uv) == 4, "uv offset wrong");
assertTrue(offsetof(meshvertex_t, pos) == 12, "pos offset wrong"); assertTrue(offsetof(meshvertex_t, pos) == 12, "pos offset wrong");
textureDolphinUploadTEV();
DCFlushRange( DCFlushRange(
(void*)&mesh->vertices[vertexOffset], (void*)&mesh->vertices[vertexOffset],
sizeof(meshvertex_t) * vertexCount sizeof(meshvertex_t) * vertexCount
); );
// Update matrix.
errorChain(shaderUpdateMVPDolphin());
const uint8_t stride = (uint8_t)sizeof(meshvertex_t); const uint8_t stride = (uint8_t)sizeof(meshvertex_t);
GX_SetArray(GX_VA_POS, (void*)&mesh->vertices[vertexOffset].pos[0], stride); GX_SetArray(GX_VA_POS, (void*)&mesh->vertices[vertexOffset].pos[0], stride);
GX_SetArray(GX_VA_CLR0, (void*)&mesh->vertices[vertexOffset].color.r, stride); GX_SetArray(GX_VA_CLR0, (void*)&mesh->vertices[vertexOffset].color.r, stride);
GX_SetArray(GX_VA_TEX0, (void*)&mesh->vertices[vertexOffset].uv[0], stride); GX_SetArray(GX_VA_TEX0, (void*)&mesh->vertices[vertexOffset].uv[0], stride);
GX_InvVtxCache();
GX_Begin(mesh->primitiveType, GX_VTXFMT0, (uint16_t)vertexCount); GX_Begin(mesh->primitiveType, GX_VTXFMT0, (uint16_t)vertexCount);
for(uint16_t i = 0; i < (uint16_t)vertexCount; ++i) { for(uint16_t i = 0; i < (uint16_t)vertexCount; ++i) {
GX_Position1x16(i); GX_Position1x16(i);

View File

@@ -0,0 +1,11 @@
# Copyright (c) 2026 Dominic Masters
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
# Sources
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
shaderdolphin.c
shaderunlitdolphin.c
)

View File

@@ -0,0 +1,245 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "util/memory.h"
#include "util/string.h"
#include "display/shader/shaderunlit.h"
#include "assert/assert.h"
#include "log/log.h"
shaderdolphin_t *SHADER_BOUND;
errorret_t shaderInitDolphin(
shaderdolphin_t *shader,
const shaderdefinitiondolphin_t *def
) {
assertNotNull(shader, "Shader must not be null");
assertNotNull(def, "Shader definition must not be null");
memoryZero(shader, sizeof(shaderdolphin_t));
glm_mat4_identity(shader->view);
glm_mat4_identity(shader->proj);
glm_mat4_identity(shader->model);
shader->dirtyMatrix = (
SHADER_DOLPHIN_DIRTY_MODEL |
SHADER_DOLPHIN_DIRTY_PROJ |
SHADER_DOLPHIN_DIRTY_VIEW
);
errorOk();
}
errorret_t shaderBindDolphin(shaderdolphin_t *shader) {
assertNotNull(shader, "Shader must not be null");
SHADER_BOUND = shader;
GX_LoadProjectionMtx(
shader->matrixProjection,
shader->isProjectionPerspective ? GX_PERSPECTIVE : GX_ORTHOGRAPHIC
);
GX_LoadPosMtxImm(shader->matrixModelView, GX_PNMTX0);
errorOk();
}
errorret_t shaderSetMatrixDolphin(
shaderdolphin_t *shader,
const char_t *name,
mat4 mat
) {
assertNotNull(shader, "Shader must not be null");
assertNotNull(name, "Uniform name must not be null");
assertStrLenMin(name, 1, "Uniform name cannot be empty");
if(stringCompare(name, SHADER_UNLIT_PROJECTION) == 0) {
shader->dirtyMatrix |= SHADER_DOLPHIN_DIRTY_PROJ;
glm_mat4_copy(mat, shader->proj);
} else if(stringCompare(name, SHADER_UNLIT_VIEW) == 0) {
shader->dirtyMatrix |= SHADER_DOLPHIN_DIRTY_VIEW;
glm_mat4_copy(mat, shader->view);
} else if(stringCompare(name, SHADER_UNLIT_MODEL) == 0) {
shader->dirtyMatrix |= SHADER_DOLPHIN_DIRTY_MODEL;
glm_mat4_copy(mat, shader->model);
} else {
assertUnreachable("Cannot use a custom matrix on dolphin.");
}
errorOk();
}
errorret_t shaderSetTextureDolphin(
shaderdolphin_t *shader,
const char_t *name,
texture_t *texture
) {
assertNotNull(shader, "Shader must not be null");
assertNotNull(name, "Uniform name must not be null");
assertStrLenMin(name, 1, "Uniform name cannot be empty");
if(texture == NULL) {
// GX_SetNumChans(0);
GX_SetNumChans(1);
GX_SetChanCtrl(
GX_COLOR0A0,
GX_DISABLE,
GX_SRC_REG,
GX_SRC_VTX,
GX_LIGHTNULL,
GX_DF_NONE,
GX_AF_NONE
);
GX_SetChanAmbColor(GX_COLOR0A0, (GXColor){ 0, 0, 0, 0 });
GX_SetChanMatColor(GX_COLOR0A0, (GXColor){ 255, 255, 255, 255 });
GX_SetNumTexGens(0);
GX_SetNumTevStages(1);
GX_SetTevOrder(GX_TEVSTAGE0, GX_TEXCOORDNULL, GX_TEXMAP_NULL, GX_COLOR0A0);
GX_SetTevOp(GX_TEVSTAGE0, GX_PASSCLR);
GX_SetBlendMode(GX_BM_NONE, GX_BL_ONE, GX_BL_ZERO, GX_LO_CLEAR);
GX_SetAlphaCompare(GX_ALWAYS, 0, GX_AOP_AND, GX_ALWAYS, 0);
errorOk();
}
// Add channel for vertex color
GX_LoadTexObj(&texture->texObj, GX_TEXMAP0);
GX_SetNumChans(1);
GX_SetChanCtrl(
GX_COLOR0A0,// Store in color channel 0
GX_DISABLE,// Lighting disabled
GX_SRC_REG,// Ambient color?
GX_SRC_VTX,// Material color?
GX_LIGHTNULL,// Light Mask
GX_DF_NONE,// Diffuse function
GX_AF_NONE// Attenuation function
);
// One set of UVs
GX_SetNumTexGens(1);
GX_SetTexCoordGen(
GX_TEXCOORD0,
GX_TG_MTX2x4,
GX_TG_TEX0,
GX_IDENTITY
);
// Basically the shader setup
switch(texture->format) {
case TEXTURE_FORMAT_RGBA:
// One TEV stage: vertex color * texture color
GX_SetNumTevStages(1);
GX_SetTevOp(GX_TEVSTAGE0, GX_MODULATE);
GX_SetTevOrder(
GX_TEVSTAGE0,
GX_TEXCOORD0,
GX_TEXMAP0,
GX_COLOR0A0
);
GX_SetBlendMode(GX_BM_BLEND, GX_BL_SRCALPHA, GX_BL_INVSRCALPHA, GX_LO_CLEAR);
GX_SetAlphaCompare(GX_ALWAYS, 0, GX_AOP_AND, GX_ALWAYS, 0);
break;
default:
assertUnreachable("Unknown texture format in meshDraw");
break;
}
errorOk();
}
errorret_t shaderDisposeDolphin(shaderdolphin_t *shader) {
assertNotNull(shader, "Shader must not be null");
SHADER_BOUND = NULL;
errorOk();
}
errorret_t shaderUpdateMVPDolphin() {
assertNotNull(SHADER_BOUND, "Shader must not be null");
// Any changes?
if(SHADER_BOUND->dirtyMatrix == 0) errorOk();
// Need to update projection?
if((SHADER_BOUND->dirtyMatrix & SHADER_DOLPHIN_DIRTY_PROJ) != 0) {
shaderMat4ToMtx44(SHADER_BOUND->proj, SHADER_BOUND->matrixProjection);
// Fix projection Z mapping between GLM and GX.
float A = SHADER_BOUND->matrixProjection[2][2];
float B = SHADER_BOUND->matrixProjection[2][3];
SHADER_BOUND->matrixProjection[2][2] = 0.5f * (A + 1.0f);
SHADER_BOUND->matrixProjection[2][3] = 0.5f * B;
// Is this perspective or ortho originally? Dolphin cares for some reason.
const float_t epsilon = 0.0001f;
SHADER_BOUND->isProjectionPerspective = (
fabsf(SHADER_BOUND->proj[3][2]) > epsilon &&
fabsf(SHADER_BOUND->proj[3][3]) < epsilon
);
GX_LoadProjectionMtx(
SHADER_BOUND->matrixProjection,
SHADER_BOUND->isProjectionPerspective ? GX_PERSPECTIVE : GX_ORTHOGRAPHIC
);
}
// Need to update view or model?
bool_t mvDirt = false;
if((SHADER_BOUND->dirtyMatrix & SHADER_DOLPHIN_DIRTY_VIEW) != 0) {
shaderMat4ToMtx(SHADER_BOUND->view, SHADER_BOUND->matrixView);
mvDirt = true;
}
if((SHADER_BOUND->dirtyMatrix & SHADER_DOLPHIN_DIRTY_MODEL) != 0) {
shaderMat4ToMtx(SHADER_BOUND->model, SHADER_BOUND->matrixModel);
mvDirt = true;
}
// Set Model/View Matrix
if(mvDirt) {
guMtxConcat(
SHADER_BOUND->matrixView,
SHADER_BOUND->matrixModel,
SHADER_BOUND->matrixModelView
);
GX_LoadPosMtxImm(SHADER_BOUND->matrixModelView, GX_PNMTX0);
}
SHADER_BOUND->dirtyMatrix = 0;
errorOk();
}
void shaderMat4ToMtx44(const mat4 inGlmMatrix, Mtx44 outGXMatrix) {
assertNotNull(inGlmMatrix, "Input matrix cannot be null");
assertNotNull(outGXMatrix, "Output matrix cannot be null");
for(int row = 0; row < 4; ++row) {
for(int col = 0; col < 4; ++col) {
outGXMatrix[row][col] = inGlmMatrix[col][row];
}
}
}
void shaderMat4ToMtx(const mat4 inGlmMatrix, Mtx outGXMatrix) {
assertNotNull(inGlmMatrix, "Input matrix cannot be null");
assertNotNull(outGXMatrix, "Output matrix cannot be null");
for(int row = 0; row < 3; ++row) {
for(int col = 0; col < 4; ++col) {
outGXMatrix[row][col] = inGlmMatrix[col][row];
}
}
}

View File

@@ -0,0 +1,113 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "display/texture/texture.h"
typedef struct {
mat4 view;
mat4 proj;
mat4 model;
bool_t isProjectionPerspective;
Mtx44 matrixProjection;
Mtx matrixView;
Mtx matrixModel;
Mtx matrixModelView;
uint_fast8_t dirtyMatrix;
} shaderdolphin_t;
typedef struct {
void *empty;
} shaderdefinitiondolphin_t;
#define SHADER_DOLPHIN_DIRTY_MODEL (1 << 0)
#define SHADER_DOLPHIN_DIRTY_PROJ (1 << 1)
#define SHADER_DOLPHIN_DIRTY_VIEW (1 << 2)
extern shaderdolphin_t *SHADER_BOUND;
/**
* Initializes a dolphin shader. Basically a render parameter pipeline.
*
* @param shader Shader to initialize.
* @param def Definition of the shader to initialize with.
* @return Error code if failure.
*/
errorret_t shaderInitDolphin(
shaderdolphin_t *shader,
const shaderdefinitiondolphin_t *def
);
/**
* Binds a dolphin shader. Basically sets the render parameters for rendering.
*
* @param shader Shader to bind.
* @return Error code if failure.
*/
errorret_t shaderBindDolphin(shaderdolphin_t *shader);
/**
* Sets a matrix uniform in the dolphin shader. Basically does nothing.
*
* @param shader Shader to set the matrix in.
* @param name Name of the uniform to set.
* @param matrix Matrix to set.
* @return Error code if failure.
*/
errorret_t shaderSetMatrixDolphin(
shaderdolphin_t *shader,
const char_t *name,
mat4 matrix
);
/**
* Sets a texture uniform in the dolphin shader. Basically does nothing.
*
* @param shader Shader to set the texture in.
* @param name Name of the uniform to set.
* @param texture Texture to set.
* @return Error code if failure.
*/
errorret_t shaderSetTextureDolphin(
shaderdolphin_t *shader,
const char_t *name,
texture_t *texture
);
/**
* Disposes a dolphin shader. Basically does nothing.
*
* @param shader Shader to dispose.
* @return Error code if failure.
*/
errorret_t shaderDisposeDolphin(shaderdolphin_t *shader);
/**
* Internal Dolphin method, called right before a draw call to perform a matrix
* update and recalc.
*
* @return Error code if failure.
*/
errorret_t shaderUpdateMVPDolphin();
/**
* Converts a glm style column major mat4 to a GX compatible row major Mtx44.
*
* @param in Matrix to convert.
* @param out Output converted matrix.
*/
void shaderMat4ToMtx44(const mat4 in, Mtx44 out);
/**
* Converts a glm style column major mat4 to a GX compatible row major Mtx.
*
* @param inGlmMatrix Matrix to convert.
* @param outGXMatrix Output converted matrix.
*/
void shaderMat4ToMtx(const mat4 inGlmMatrix, Mtx outGXMatrix);

View File

@@ -0,0 +1,18 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "shaderdolphin.h"
typedef shaderdolphin_t shaderplatform_t;
typedef shaderdefinitiondolphin_t shaderdefinitionplatform_t;
#define shaderInitPlatform shaderInitDolphin
#define shaderBindPlatform shaderBindDolphin
#define shaderSetMatrixPlatform shaderSetMatrixDolphin
#define shaderSetTexturePlatform shaderSetTextureDolphin
#define shaderDisposePlatform shaderDisposeDolphin

View File

@@ -0,0 +1,12 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "display/shader/shaderunlit.h"
shaderdefinition_t SHADER_UNLIT_DEFINITION = {
0
};

View File

@@ -7,6 +7,7 @@
#include "display/texture/texture.h" #include "display/texture/texture.h"
#include "assert/assert.h" #include "assert/assert.h"
#include "util/memory.h"
errorret_t textureInitDolphin( errorret_t textureInitDolphin(
texturedolphin_t *texture, texturedolphin_t *texture,
@@ -15,191 +16,101 @@ errorret_t textureInitDolphin(
const textureformatdolphin_t format, const textureformatdolphin_t format,
const texturedata_t data const texturedata_t data
) { ) {
// switch(format) { switch(format) {
// case TEXTURE_FORMAT_RGBA: case TEXTURE_FORMAT_RGBA: {
// assertTrue( size_t rgbaSize = width * height * sizeof(uint8_t) * 4;
// (width % 4) == 0 && (height % 4) == 0,
// "RGB5A3 requires w/h multiple of 4 (or pad)"
// );
// // Convert to RGB5A3 format // Dolphin takes the RGBA data as 4x4 tiled layout.
// size_t rgbaSize = width * height * sizeof(u16); texture->rgba = memoryAllocate(rgbaSize);
// texture->rgba = (u16*)memalign(32, rgbaSize);
// assertNotNull(texture->rgba, "Failed to allocate texture RGBA data");
// for(uint32_t y = 0; y < height; ++y) { for(uint32_t y = 0; y < height; ++y) {
// for(uint32_t x = 0; x < width; ++x) { for(uint32_t x = 0; x < width; ++x) {
// const int src = y * width + x; const int src = y * width + x;
// const int tileX = x >> 2; const int tileX = x >> 2;
// const int tileY = y >> 2; const int tileY = y >> 2;
// const int tilesPerRow = width >> 2; const int tilesPerRow = width >> 2;
// const int tileIndex = tileY * tilesPerRow + tileX; const int tileIndex = tileY * tilesPerRow + tileX;
// const int tileBaseWords = tileIndex * 16; const int inTile = ((y & 3) << 2) + (x & 3);
// const int inTile = ((y & 3) << 2) + (x & 3); const int tileBase = tileIndex * 64;
// const int dest = tileBaseWords + inTile;
// color4b_t col = data.rgba.colors[src]; color_t col = data.rgbaColors[src];
// u16 outCol; // AR plane
// if(col.a < 255) { texture->rgba[tileBase + inTile * 2 + 0] = col.a;
// // 0AAA RRRR GGGG BBBB texture->rgba[tileBase + inTile * 2 + 1] = col.r;
// outCol = (
// (0u << 15) |
// ((u16)(col.a >> 5) << 12) |
// ((u16)(col.r >> 4) << 8) |
// ((u16)(col.g >> 4) << 4) |
// ((u16)(col.b >> 4) << 0)
// );
// } else {
// // 1RRRR RRGG GGGB BBBB
// outCol = (
// (1u << 15) |
// ((u16)(col.r >> 3) << 10) |
// ((u16)(col.g >> 3) << 5) |
// ((u16)(col.b >> 3) << 0)
// );
// }
// texture->rgba[dest] = outCol;
// }
// }
// DCFlushRange(texture->rgba, rgbaSize); // GB plane
// GX_InitTexObj( texture->rgba[tileBase + 32 + inTile * 2 + 0] = col.g;
// &texture->texObj, texture->rgba[tileBase + 32 + inTile * 2 + 1] = col.b;
// texture->rgba, }
// width, height, }
// GX_TF_RGB5A3, DCFlushRange(texture->rgba, rgbaSize);
// GX_REPEAT, GX_REPEAT, GX_InitTexObj(
// GX_FALSE &texture->texObj,
// ); texture->rgba,
width, height,
format,
GX_REPEAT, GX_REPEAT,
GX_FALSE
);
// DCFlushRange(texture->rgba, rgbaSize); DCFlushRange(texture->rgba, rgbaSize);
// GX_InvalidateTexAll(); GX_InvalidateTexAll();
// GX_InitTexObjLOD( GX_InitTexObjLOD(
// &texture->texObj, &texture->texObj,
// GX_NEAR, GX_NEAR, GX_NEAR, GX_NEAR,
// 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
// GX_FALSE, GX_FALSE,
// GX_FALSE, GX_FALSE,
// GX_ANISO_1 GX_ANISO_1
// ); );
// break; break;
}
// case TEXTURE_FORMAT_PALETTE: { case TEXTURE_FORMAT_PALETTE: {
// // Not supported, convert to RGBA using lookup assertUnreachable("Paletted textures not yet implemented for Dolphin");
// color_t* formatted = memoryAllocate(width * height * sizeof(color_t)); break;
// for(int32_t i = 0; i < width * height; i++) { }
// uint8_t index = data.palette.data[i];
// assertTrue(
// index < data.palette.palette->colorCount,
// "Palette index out of range"
// );
// formatted[i] = data.palette.palette->colors[index];
// }
// textureInit( default: {
// texture, width, height, TEXTURE_FORMAT_RGBA, assertUnreachable("Unsupported texture format for Dolphin");
// (texturedata_t){ break;
// .rgba = { .colors = formatted } }
// } }
// );
// memoryFree(formatted);
// break;
// }
// default:
// assertUnreachable("Unsupported texture format for Dolphin");
// break;
// }
// texture->ready = true;
errorOk(); errorOk();
} }
errorret_t textureBindDolphin(texturedolphin_t *texture) {
if(texture == NULL) {
GX_SetNumChans(0);
errorOk();
}
GX_SetNumChans(1);
GX_LoadTexObj(&texture->texObj, GX_TEXMAP0);
errorOk();
}
errorret_t textureDisposeDolphin(texturedolphin_t *texture) { errorret_t textureDisposeDolphin(texturedolphin_t *texture) {
switch(texture->format) {
case TEXTURE_FORMAT_RGBA: {
if(texture->rgba) {
memoryFree(texture->rgba);
texture->rgba = NULL;
}
break;
}
// case TEXTURE_FORMAT_RGB4A3: {
// assertUnreachable("RGB4A3 texture format not yet implemented");
// }
// case TEXTURE_FORMAT_RGB5: {
// assertUnreachable("RGB5 texture format not yet implemented");
// }
// case TEXTURE_FORMAT_PALETTE: {
// assertUnreachable("Paletted textures not yet implemented for Dolphin");
// break;
// }
default: {
assertUnreachable("Unsupported texture format for Dolphin");
break;
}
}
errorOk(); errorOk();
} }
void textureDolphinUploadTEV(void) {
if(TEXTURE_BOUND == NULL) {
GX_SetNumChans(1);
GX_SetChanCtrl(
GX_COLOR0A0,
GX_DISABLE,
GX_SRC_REG,
GX_SRC_VTX,
GX_LIGHTNULL,
GX_DF_NONE,
GX_AF_NONE
);
GX_SetChanAmbColor(GX_COLOR0A0, (GXColor){0, 0, 0, 0});
GX_SetChanMatColor(GX_COLOR0A0, (GXColor){255, 255, 255, 255});
GX_SetNumTexGens(0);
GX_SetNumTevStages(1);
GX_SetTevOrder(GX_TEVSTAGE0, GX_TEXCOORDNULL, GX_TEXMAP_NULL, GX_COLOR0A0);
GX_SetTevOp(GX_TEVSTAGE0, GX_PASSCLR);
GX_SetBlendMode(GX_BM_NONE, GX_BL_ONE, GX_BL_ZERO, GX_LO_CLEAR);
GX_SetAlphaCompare(GX_ALWAYS, 0, GX_AOP_AND, GX_ALWAYS, 0);
return;
}
// Add channel for vertex color
GX_SetNumChans(1);
GX_SetChanCtrl(
GX_COLOR0A0,// Store in color channel 0
GX_DISABLE,// Lighting disabled
GX_SRC_REG,// Ambient color?
GX_SRC_VTX,// Material color?
GX_LIGHTNULL,// Light Mask
GX_DF_NONE,// Diffuse function
GX_AF_NONE// Attenuation function
);
// One set of UVs
GX_SetNumTexGens(1);
GX_SetTexCoordGen(
GX_TEXCOORD0,
GX_TG_MTX2x4,
GX_TG_TEX0,
GX_IDENTITY
);
// Basically the shader setup
switch(TEXTURE_BOUND->format) {
case TEXTURE_FORMAT_RGBA:
// One TEV stage: vertex color * texture color
GX_SetNumTevStages(1);
GX_SetTevOp(GX_TEVSTAGE0, GX_MODULATE);
GX_SetTevOrder(
GX_TEVSTAGE0,
GX_TEXCOORD0,
GX_TEXMAP0,
GX_COLOR0A0
);
GX_SetBlendMode(GX_BM_BLEND, GX_BL_SRCALPHA, GX_BL_INVSRCALPHA, GX_LO_CLEAR);
GX_SetAlphaCompare(GX_ALWAYS, 0, GX_AOP_AND, GX_ALWAYS, 0);
break;
default:
assertUnreachable("Unknown texture format in meshDraw");
break;
}
}

Some files were not shown because too many files have changed in this diff Show More