16 Commits

Author SHA1 Message Date
YourWishes 9551e222dc Chunks as json 2026-07-11 17:43:26 -05:00
YourWishes 60dfb89b53 Map as a file 2026-07-11 17:07:03 -05:00
YourWishes b08ad308e4 item but as a file 2026-07-11 11:44:34 -05:00
YourWishes ca02ee0352 Add camera shake 2026-07-11 11:02:09 -05:00
YourWishes fbaa54145e Fixed dolphin rendering. 2026-07-10 20:15:26 -05:00
YourWishes 28754ffbf2 Removed old scripted types 2026-07-10 13:24:21 -05:00
YourWishes 470c0eba7a Whatever, some minor map chunking improvements 2026-07-10 12:57:31 -05:00
YourWishes 7098dcec43 Cleaned some log 2026-07-09 23:25:43 -05:00
YourWishes 07137f57af Assets are slightly optimized 2026-07-09 23:25:26 -05:00
YourWishes 8b7491a3d3 Emoji support to characters 2026-07-09 13:18:48 -05:00
YourWishes 8cfa8ddfeb Weaather baseline 2026-07-08 12:57:13 -05:00
YourWishes ef284a15a1 pre-cache shader matrices 2026-07-08 12:36:40 -05:00
YourWishes 3723921573 Render culling on sceneoverworld.h 2026-07-08 12:02:41 -05:00
YourWishes 195399635e Updating mini textbox 2026-07-08 11:45:10 -05:00
YourWishes 46e2a924d3 Mini textboxes 2026-07-08 10:53:53 -05:00
YourWishes b693ea4102 Starting item and battle stuff 2026-07-08 10:05:21 -05:00
170 changed files with 6497 additions and 15728 deletions
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+25
View File
@@ -0,0 +1,25 @@
{
"pause": "DEFAULT",
"items": [
{ "type": "text", "text": "Test Two." },
{ "type": "entityAdd", "entityType": "npc", "position": [4, 4, 0] },
{
"type": "textMini",
"text": "Hello!",
"position": [4, 4, 0],
"duration": 3.0
},
{
"type": "emoji",
"entityIndex": "lastCreated",
"emojiType": "exclamation",
"duration": 2.0
},
{
"type": "entityWalkTo",
"entityIndex": "lastCreated",
"positions": [[8, 2, 0]]
},
{ "type": "text", "text": "Done." }
]
}
+5
View File
@@ -0,0 +1,5 @@
[
{ "id": "POTION", "type": "MEDICINE", "weight": 1.0, "name": "potion" },
{ "id": "POTATO", "type": "FOOD", "weight": 0.5, "name": "potato" },
{ "id": "APPLE", "type": "FOOD", "weight": 0.3, "name": "apple" }
]
+21
View File
@@ -43,3 +43,24 @@ msgstr "Apply"
#: src/dusk/ui/frame/uiconfirm.c
msgid "ui.confirm.discard_changes"
msgstr "Discard unsaved changes?"
#: src/dusk/ui/frame/game/uigamemenu.c
msgid "ui.game_menu.characters"
msgstr "Characters"
#: src/dusk/ui/frame/game/uigamemenu.c
msgid "ui.game_menu.items"
msgstr "Items"
#: src/dusk/ui/frame/game/uigamemenu.c
msgid "ui.game_menu.settings"
msgstr "Settings"
msgid "item.potion.name"
msgstr "Potion"
msgid "item.potato.name"
msgstr "Potato"
msgid "item.apple.name"
msgstr "Apple"
+24
View File
@@ -44,3 +44,27 @@ msgstr "Aplicar"
#: src/dusk/ui/frame/uiconfirm.c
msgid "ui.confirm.discard_changes"
msgstr "¿Descartar los cambios no guardados?"
#: src/dusk/ui/frame/game/uigamemenu.c
msgid "ui.game_menu.characters"
msgstr "Personajes"
#: src/dusk/ui/frame/game/uigamemenu.c
msgid "ui.game_menu.items"
msgstr "Objetos"
#: src/dusk/ui/frame/game/uigamemenu.c
msgid "ui.game_menu.settings"
msgstr "Configuración"
#: src/dusk/rpg/item/item.json
msgid "item.potion.name"
msgstr "Poción"
#: src/dusk/rpg/item/item.json
msgid "item.potato.name"
msgstr "Papa"
#: src/dusk/rpg/item/item.json
msgid "item.apple.name"
msgstr "Manzana"
+24
View File
@@ -44,3 +44,27 @@ msgstr "適用"
#: src/dusk/ui/frame/uiconfirm.c
msgid "ui.confirm.discard_changes"
msgstr "未保存の変更を破棄しますか?"
#: src/dusk/ui/frame/game/uigamemenu.c
msgid "ui.game_menu.characters"
msgstr "キャラクター"
#: src/dusk/ui/frame/game/uigamemenu.c
msgid "ui.game_menu.items"
msgstr "アイテム"
#: src/dusk/ui/frame/game/uigamemenu.c
msgid "ui.game_menu.settings"
msgstr "設定"
#: src/dusk/rpg/item/item.json
msgid "item.potion.name"
msgstr "ポーション"
#: src/dusk/rpg/item/item.json
msgid "item.potato.name"
msgstr "ジャガイモ"
#: src/dusk/rpg/item/item.json
msgid "item.apple.name"
msgstr "リンゴ"
+1
View File
@@ -0,0 +1 @@
{"tiles": [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [0, 0], [0, 0], [0, 0], [0, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [0, 0], [0, 0], [0, 0], [0, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [0, 0], [0, 0], [0, 0], [0, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [0, 0], [0, 0], [0, 0], [0, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [0, 0], [0, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [0, 0], [0, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]], "meshes": [{"model": "models/chunks/chunk_-1_0_0_0.json", "offset": [0.0, 0.0, 0.0]}, {"model": "models/buildings/house_4_4.json", "offset": [2.0, 1.0, 0.0]}, {"model": "models/buildings/house_6_3.json", "offset": [1.0, 9.0, 0.0]}, {"model": "models/buildings/house_2_2.json", "offset": [12.0, 6.0, 0.0]}]}
File diff suppressed because it is too large Load Diff
+1
View File
@@ -0,0 +1 @@
{"tiles": [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [1, 0], [1, 0], [0, 0], [0, 0], [0, 0], [1, 0], [1, 0], [1, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [1, 0], [1, 0], [0, 0], [0, 0], [0, 0], [1, 0], [1, 0], [1, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [1, 0], [1, 0], [0, 0], [0, 0], [0, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [0, 0], [0, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [0, 0], [0, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]], "meshes": [{"model": "models/chunks/chunk_0_1_0_0.json", "offset": [0.0, 0.0, 0.0]}, {"model": "models/buildings/house_8_4.json", "offset": [1.0, 1.0, 0.0]}, {"model": "models/buildings/house_3_3.json", "offset": [11.0, 2.0, 0.0]}, {"model": "models/buildings/house_2_2.json", "offset": [3.0, 11.0, 0.0]}]}
+1
View File
@@ -0,0 +1 @@
{"tiles": [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [0, 0], [0, 0], [0, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [0, 0], [0, 0], [0, 0], [1, 0], [1, 0], [1, 0], [0, 0], [0, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [0, 0], [0, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [0, 0], [0, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [0, 0], [0, 0], [0, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [0, 0], [0, 0], [0, 0], [1, 0], [0, 0], [0, 0], [0, 0], [0, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [0, 0], [0, 0], [0, 0], [0, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [0, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]], "meshes": [{"model": "models/chunks/chunk_1_0_0_0.json", "offset": [0.0, 0.0, 0.0]}, {"model": "models/buildings/house_3_2.json", "offset": [1.0, 1.0, 0.0]}, {"model": "models/buildings/house_2_3.json", "offset": [7.0, 2.0, 0.0]}, {"model": "models/buildings/house_4_2.json", "offset": [1.0, 8.0, 0.0]}, {"model": "models/buildings/house_1_1.json", "offset": [11.0, 10.0, 0.0]}, {"model": "models/buildings/house_5_2.json", "offset": [13.0, 6.0, 0.0]}]}
+1
View File
@@ -0,0 +1 @@
{"tiles": [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [1, 0], [1, 0], [0, 0], [0, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [1, 0], [1, 0], [0, 0], [0, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [1, 0], [1, 0], [0, 0], [0, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [0, 0], [0, 0], [0, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]], "meshes": [{"model": "models/chunks/chunk_1_1_0_0.json", "offset": [0.0, 0.0, 0.0]}, {"model": "models/buildings/house_5_5.json", "offset": [3.0, 2.0, 0.0]}, {"model": "models/buildings/house_2_3.json", "offset": [10.0, 3.0, 0.0]}, {"model": "models/buildings/house_3_1.json", "offset": [1.0, 12.0, 0.0]}]}
+1
View File
@@ -0,0 +1 @@
{"tiles": [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 3], [1, 3], [1, 3], [1, 3], [1, 3], [1, 3], [1, 0], [1, 0], [1, 0], [1, 0], [0, 0], [0, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 3], [1, 3], [1, 3], [1, 3], [1, 3], [1, 3], [1, 0], [1, 0], [1, 0], [1, 0], [0, 0], [0, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 3], [1, 3], [1, 3], [1, 3], [1, 3], [1, 3], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [4, 1], [4, 1], [4, 1], [4, 1], [4, 1], [4, 1], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [4, 0], [4, 0], [4, 0], [4, 0], [4, 0], [4, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]], "meshes": [{"model": "models/chunks/chunk_2_0_0_0.json", "offset": [0.0, 0.0, 0.0]}]}
+13
View File
@@ -0,0 +1,13 @@
{
"name": "Test Map",
"entities": [
{ "type": "player", "position": [10, 2, 0], "direction": "north" },
{ "type": "item", "position": [12, 2, 0], "item": "POTION", "quantity": 1 },
{
"type": "npc",
"position": [8, 8, 1],
"path": [[4, 4, 0], [10, 10, 1], [4, 4, 0], [10, 10, 1]],
"cutscene": "test_npc"
}
]
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+3
View File
@@ -16,6 +16,9 @@ target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
DOL=1
ISO=2
DUSK_DOLPHIN_BUILD_TYPE=${DUSK_DOLPHIN_BUILD_TYPE}
# GameCube/Wii PowerPC is always big-endian; declare it at compile time
# like every other target instead of relying on endian.h's runtime probe.
DUSK_PLATFORM_ENDIAN_BIG
)
# Custom compiler flags
+1
View File
@@ -56,6 +56,7 @@ target_compile_definitions(${DUSK_BINARY_TARGET_NAME} PUBLIC
DUSK_DISPLAY_HEIGHT=272
DUSK_THREAD_PTHREAD
DUSK_TIME_DYNAMIC
DUSK_DISPLAY_OVERSCAN=6
)
if(NOT CMAKE_BUILD_TYPE STREQUAL "Debug")
+36 -45
View File
@@ -59,7 +59,10 @@ assetentry_t * assetGetEntry(
entry++;
} while(entry < ASSET.entries + ASSET_ENTRY_COUNT_MAX);
// We did not find one existing, Find first available slot.
// We did not find one existing. Find first available slot, reaping
// zero-ref entries to make room if none are immediately available.
bool_t reaped = false;
for(;;) {
entry = ASSET.entries;
do {
if(entry->type != ASSET_LOADER_TYPE_NULL) {
@@ -74,6 +77,11 @@ assetentry_t * assetGetEntry(
entry++;
} while(entry < ASSET.entries + ASSET_ENTRY_COUNT_MAX);
if(reaped) break;
reaped = true;
errorCatch(assetReapUnused());
}
assertUnreachable("No available asset entry slots.");
return NULL;
}
@@ -191,6 +199,32 @@ void assetUnlockEntry(assetentry_t *entry) {
assetEntryUnlock(entry);
}
errorret_t assetReapUnused(void) {
assertIsMainThread("assetReapUnused must be called from the main thread.");
// Repeatedly find and dispose zero-ref LOADED entries until none remain.
// This handles dependency chains where an entry (e.g. a model) holds refs
// on child entries (mesh, texture): dispose parents first so child ref
// counts drop to zero, then pick up the children on the next pass. Without
// this, a forward-only scan fails when a shared child entry appears before
// a parent that still holds a ref to it.
bool_t any;
do {
any = false;
assetentry_t *entry = ASSET.entries;
do {
if(entry->type == ASSET_LOADER_TYPE_NULL) { entry++; continue; }
if(entry->state != ASSET_ENTRY_STATE_LOADED) { entry++; continue; }
if(entry->refs.count > 0) { entry++; continue; }
errorChain(assetEntryDispose(entry));
any = true;
entry++;
} while(entry < ASSET.entries + ASSET_ENTRY_COUNT_MAX);
} while(any);
errorOk();
}
errorret_t assetUpdate(void) {
assertIsMainThread("assetUpdate must be called from the main thread.");
@@ -324,30 +358,6 @@ errorret_t assetUpdate(void) {
}
} while(loading < ASSET.loading + ASSET_LOADING_COUNT_MAX);
// Reap unused entries.
entry = ASSET.entries;
do {
if(entry->state != ASSET_ENTRY_STATE_LOADED) {
entry++;
continue;
}
if(entry->type == ASSET_LOADER_TYPE_NULL) {
entry++;
continue;
}
if(entry->refs.count > 0) {
entry++;
continue;
}
// consolePrint("Reaping asset %s", entry->name);
errorChain(assetEntryDispose(entry));
entry++;
} while(entry < ASSET.entries + ASSET_ENTRY_COUNT_MAX);
errorOk();
}
@@ -413,26 +423,7 @@ errorret_t assetDispose(void) {
assertIsMainThread("Must be called from the main thread.");
threadStop(&ASSET.loadThread);
// Drain-dispose: repeatedly find and dispose zero-ref LOADED entries
// until none remain. This handles dependency chains where an entry
// (e.g. a model) holds refs on child entries (mesh, texture): dispose
// parents first so child ref counts drop to zero, then pick up the
// children on the next pass. Without this, a forward-only scan fails
// when a shared child entry appears before a parent that still holds a
// ref to it.
bool_t any;
do {
any = false;
assetentry_t *e = ASSET.entries;
do {
if(e->type == ASSET_LOADER_TYPE_NULL) { e++; continue; }
if(e->state != ASSET_ENTRY_STATE_LOADED) { e++; continue; }
if(e->refs.count > 0) { e++; continue; }
errorChain(assetEntryDispose(e));
any = true;
e++;
} while(e < ASSET.entries + ASSET_ENTRY_COUNT_MAX);
} while(any);
errorChain(assetReapUnused());
// Cleanup zip file.
if(ASSET.zip != NULL) {
+12 -2
View File
@@ -23,8 +23,8 @@
#define ASSET_FILE_NAME "dusk.dsk"
#define ASSET_HEADER_SIZE 3
#define ASSET_LOADING_COUNT_MAX 20
#define ASSET_ENTRY_COUNT_MAX 128
#define ASSET_LOADING_COUNT_MAX 10
#define ASSET_ENTRY_COUNT_MAX 64
typedef struct asset_s {
zip_t *zip;
@@ -112,6 +112,16 @@ void assetUnlock(const char_t *name);
*/
void assetUnlockEntry(assetentry_t *entry);
/**
* Frees every currently unreferenced (zero-ref) loaded asset entry. Repeats
* until a full pass frees nothing further, since disposing a parent entry
* (e.g. a model) may drop a child entry's (e.g. a mesh) ref count to zero,
* making it eligible for reaping too.
*
* @return An error code if any entry could not be disposed properly.
*/
errorret_t assetReapUnused(void);
/**
* Requires an asset entry to be loaded. This will block until the asset entry
* is fully loaded.
+142 -88
View File
@@ -8,40 +8,17 @@
#include "assetchunkloader.h"
#include "assert/assert.h"
#include "util/memory.h"
#include "util/endian.h"
#include "util/string.h"
#include "asset/loader/assetloading.h"
#include "asset/loader/assetentry.h"
#include "asset/loader/assetloader.h"
#include "asset/loader/json/assetjsonloader.h"
#include "asset/asset.h"
#include "yyjson.h"
errorret_t assetChunkLoaderAsync(assetloading_t *loading) {
assertNotNull(loading, "Loading cannot be NULL");
assertNotMainThread("Should be called from an async thread.");
if(loading->loading.chunk.state != ASSET_CHUNK_LOADING_STATE_READ_FILE) {
errorOk();
}
assertNull(loading->loading.chunk.data, "Data already defined?");
assetfile_t *file = &loading->loading.chunk.file;
assetLoaderErrorChain(loading,
assetFileInit(file, loading->entry->name, NULL, NULL)
);
uint8_t *data = memoryAllocate(file->size);
assetLoaderErrorChain(loading, assetFileOpen(file));
assetLoaderErrorChain(loading, assetFileRead(file, data, file->size));
assetLoaderErrorChain(loading, assetFileClose(file));
assetLoaderErrorChain(loading, assetFileDispose(file));
assertTrue(
file->lastRead == file->size,
"Failed to read entire chunk file."
);
loading->loading.chunk.data = data;
loading->loading.chunk.state = ASSET_CHUNK_LOADING_STATE_PARSE;
loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
errorOk();
}
@@ -54,12 +31,141 @@ errorret_t assetChunkLoaderSync(assetloading_t *loading) {
switch(loading->loading.chunk.state) {
case ASSET_CHUNK_LOADING_STATE_INITIAL:
loading->loading.chunk.state = ASSET_CHUNK_LOADING_STATE_READ_FILE;
loading->entry->state = ASSET_ENTRY_STATE_PENDING_ASYNC;
loading->loading.chunk.state = ASSET_CHUNK_LOADING_STATE_LOAD_JSON;
loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
errorOk();
case ASSET_CHUNK_LOADING_STATE_PARSE:
break;
case ASSET_CHUNK_LOADING_STATE_LOAD_JSON: {
// Lock the chunk's JSON as a sub-asset. The entry key is prefixed
// with "json:" to avoid a type-collision with the chunk entry
// itself (both share the same filename). The JSON loader reads
// the real file path supplied in the input.
char_t jsonKey[ASSET_FILE_NAME_MAX];
stringFormat(
jsonKey, sizeof(jsonKey), "json:%s", loading->entry->name
);
assetloaderinput_t jsonInput;
memoryZero(&jsonInput, sizeof(jsonInput));
stringCopy(
jsonInput.json.path, loading->entry->name, ASSET_FILE_NAME_MAX
);
assetentry_t *jsonEntry = assetLock(
jsonKey, ASSET_LOADER_TYPE_JSON, &jsonInput
);
errorret_t ret = assetRequireLoaded(jsonEntry);
if(errorIsNotOk(ret)) {
assetUnlockEntry(jsonEntry);
loading->entry->state = ASSET_ENTRY_STATE_ERROR;
errorChain(ret);
}
yyjson_val *root = yyjson_doc_get_root(jsonEntry->data.json);
yyjson_val *tilesVal = yyjson_obj_get(root, "tiles");
if(
!tilesVal || !yyjson_is_arr(tilesVal) ||
yyjson_arr_size(tilesVal) != CHUNK_TILE_COUNT
) {
assetUnlockEntry(jsonEntry);
loading->entry->state = ASSET_ENTRY_STATE_ERROR;
errorThrow(
"Chunk JSON 'tiles' must have exactly %d entries",
CHUNK_TILE_COUNT
);
}
out->tiles = memoryAllocate(CHUNK_TILE_COUNT * sizeof(tile_t));
size_t tileIdx, tileMax;
yyjson_val *tileVal;
yyjson_arr_foreach(tilesVal, tileIdx, tileMax, tileVal) {
yyjson_val *shapeVal = yyjson_arr_get(tileVal, 0);
yyjson_val *zVal = yyjson_arr_get(tileVal, 1);
if(
!yyjson_is_arr(tileVal) || yyjson_arr_size(tileVal) != 2 ||
!yyjson_is_int(shapeVal) || !yyjson_is_int(zVal)
) {
memoryFree(out->tiles);
out->tiles = NULL;
assetUnlockEntry(jsonEntry);
loading->entry->state = ASSET_ENTRY_STATE_ERROR;
errorThrow("Chunk JSON tile entries must be [shape, z] arrays");
}
out->tiles[tileIdx] = (tile_t){
.shape = (tileshape_t)yyjson_get_int(shapeVal),
.z = (uint8_t)yyjson_get_int(zVal)
};
}
yyjson_val *meshesVal = yyjson_obj_get(root, "meshes");
out->meshCount = 0;
if(meshesVal && yyjson_is_arr(meshesVal)) {
size_t meshCount = yyjson_arr_size(meshesVal);
if(meshCount > CHUNK_MESH_COUNT_MAX) {
memoryFree(out->tiles);
out->tiles = NULL;
assetUnlockEntry(jsonEntry);
loading->entry->state = ASSET_ENTRY_STATE_ERROR;
errorThrow(
"Chunk JSON 'meshes' exceeds CHUNK_MESH_COUNT_MAX (%d)",
CHUNK_MESH_COUNT_MAX
);
}
size_t meshIdx, meshMax;
yyjson_val *meshVal;
yyjson_arr_foreach(meshesVal, meshIdx, meshMax, meshVal) {
yyjson_val *modelVal = yyjson_obj_get(meshVal, "model");
if(!modelVal || !yyjson_is_str(modelVal)) {
memoryFree(out->tiles);
out->tiles = NULL;
assetUnlockEntry(jsonEntry);
loading->entry->state = ASSET_ENTRY_STATE_ERROR;
errorThrow("Chunk JSON mesh entry missing 'model' string");
}
const char_t *modelStr = yyjson_get_str(modelVal);
size_t modelLen = yyjson_get_len(modelVal);
if(modelLen >= CHUNK_MESH_NAME_MAX) {
memoryFree(out->tiles);
out->tiles = NULL;
assetUnlockEntry(jsonEntry);
loading->entry->state = ASSET_ENTRY_STATE_ERROR;
errorThrow(
"Chunk JSON model path '%s' exceeds max length", modelStr
);
}
memoryCopy(out->modelNames[meshIdx], modelStr, modelLen + 1);
vec3 offset = { 0.0f, 0.0f, 0.0f };
yyjson_val *offsetVal = yyjson_obj_get(meshVal, "offset");
if(
offsetVal && yyjson_is_arr(offsetVal) &&
yyjson_arr_size(offsetVal) == 3
) {
size_t offIdx, offMax;
yyjson_val *offElem;
yyjson_arr_foreach(offsetVal, offIdx, offMax, offElem) {
if(yyjson_is_num(offElem)) {
offset[offIdx] = (float_t)yyjson_get_num(offElem);
}
}
}
glm_vec3_copy(offset, out->meshOffsets[meshIdx]);
}
out->meshCount = (uint8_t)meshCount;
}
assetUnlockEntry(jsonEntry);
if(out->meshCount == 0) {
loading->entry->state = ASSET_ENTRY_STATE_LOADED;
errorOk();
}
loading->loading.chunk.state = ASSET_CHUNK_LOADING_STATE_LOAD_MODELS;
loading->loading.chunk.modelIndex = 0;
loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
errorOk();
}
case ASSET_CHUNK_LOADING_STATE_LOAD_MODELS:
while(loading->loading.chunk.modelIndex < out->meshCount) {
@@ -91,64 +197,6 @@ errorret_t assetChunkLoaderSync(assetloading_t *loading) {
default:
errorOk();
}
uint8_t *data = loading->loading.chunk.data;
assertNotNull(data, "Chunk data should have been loaded by now.");
if(data[0] != 'D' || data[1] != 'C' || data[2] != 'F') {
memoryFree(data);
assetLoaderErrorThrow(loading, "Invalid chunk file header");
}
uint32_t version = endianLittleToHost32(*(uint32_t *)(data + 4));
if(version != ASSET_CHUNK_FILE_VERSION) {
memoryFree(data);
assetLoaderErrorThrow(
loading, "Unsupported chunk file version %u", version
);
}
size_t offset = 8;
size_t tileSize = CHUNK_TILE_COUNT * sizeof(tile_t);
memoryCopy(out->tiles, data + offset, tileSize);
offset += tileSize;
out->meshCount = data[offset];
offset += sizeof(uint8_t);
assertTrue(
out->meshCount <= CHUNK_MESH_COUNT_MAX,
"Chunk mesh count exceeds maximum."
);
for(uint8_t m = 0; m < out->meshCount; m++) {
uint8_t nameLen = 0;
while(
data[offset + nameLen] != '\0' &&
nameLen < CHUNK_MESH_NAME_MAX - 1
) {
nameLen++;
}
memoryCopy(out->modelNames[m], data + offset, nameLen);
out->modelNames[m][nameLen] = '\0';
offset += nameLen + 1;
memoryCopy(out->meshOffsets[m], data + offset, sizeof(vec3));
offset += sizeof(vec3);
}
memoryFree(data);
loading->loading.chunk.data = NULL;
if(out->meshCount == 0) {
loading->entry->state = ASSET_ENTRY_STATE_LOADED;
errorOk();
}
loading->loading.chunk.state = ASSET_CHUNK_LOADING_STATE_LOAD_MODELS;
loading->loading.chunk.modelIndex = 0;
loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
errorOk();
}
errorret_t assetChunkDispose(assetentry_t *entry) {
@@ -157,6 +205,12 @@ errorret_t assetChunkDispose(assetentry_t *entry) {
assertIsMainThread("Must be called from the main thread.");
assetchunkoutput_t *out = &entry->data.chunk;
if(out->tiles != NULL) {
memoryFree(out->tiles);
out->tiles = NULL;
}
for(uint8_t m = 0; m < out->meshCount; m++) {
if(out->modelEntries[m] == NULL) continue;
assetUnlockEntry(out->modelEntries[m]);
+22 -15
View File
@@ -9,8 +9,6 @@
#include "asset/assetfile.h"
#include "rpg/overworld/chunk.h"
#define ASSET_CHUNK_FILE_VERSION 4
typedef struct assetloading_s assetloading_t;
typedef struct assetentry_s assetentry_t;
@@ -20,21 +18,17 @@ typedef struct {
typedef enum {
ASSET_CHUNK_LOADING_STATE_INITIAL,
ASSET_CHUNK_LOADING_STATE_READ_FILE,
ASSET_CHUNK_LOADING_STATE_PARSE,
ASSET_CHUNK_LOADING_STATE_LOAD_MODELS,
ASSET_CHUNK_LOADING_STATE_DONE
ASSET_CHUNK_LOADING_STATE_LOAD_JSON,
ASSET_CHUNK_LOADING_STATE_LOAD_MODELS
} assetchunkloadingstate_t;
typedef struct {
assetfile_t file;
assetchunkloadingstate_t state;
uint8_t *data;
uint8_t modelIndex;
} assetchunkloaderloading_t;
typedef struct {
tile_t tiles[CHUNK_TILE_COUNT];
tile_t *tiles;
uint8_t meshCount;
char_t modelNames[CHUNK_MESH_COUNT_MAX][CHUNK_MESH_NAME_MAX];
vec3 meshOffsets[CHUNK_MESH_COUNT_MAX];
@@ -42,9 +36,9 @@ typedef struct {
} assetchunkoutput_t;
/**
* Asynchronous loader for chunk assets. Reads the raw DCF file bytes into
* the loading buffer so the sync phase can parse without blocking the
* main thread on I/O.
* Asynchronous loader for chunk assets. No-op - the chunk's JSON file is
* loaded via a JSON sub-asset in the sync phase (see assetChunkLoaderSync),
* which handles its own async file I/O.
*
* @param loading Loading information for the asset being loaded.
* @return Error code indicating success or failure of the load operation.
@@ -52,9 +46,22 @@ typedef struct {
errorret_t assetChunkLoaderAsync(assetloading_t *loading);
/**
* Synchronous loader for chunk assets. Validates the DCF binary previously
* read by the async phase and populates the output assetchunkoutput_t with
* tile data and model paths.
* Synchronous loader for chunk assets. Locks and parses the chunk's JSON
* file (tiles plus referenced model paths/offsets), then locks each
* referenced model asset before marking the entry loaded.
*
* Expected JSON shape:
* {
* "tiles": [ [shape, z], ... ] // exactly CHUNK_TILE_COUNT entries,
* // one per (x, y) column, x-major
* "meshes": [
* { "model": "models/chunks/chunk_0_0_0_0.json",
* "offset": [0.0, 0.0, 0.0] }
* ]
* }
* "meshes" is optional; each entry's "offset" defaults to [0, 0, 0] if
* omitted. By convention mesh index 0 is the chunk's terrain and the
* rest are props (see sceneOverworldDrawChunksBase/Props).
*
* @param loading Loading information for the asset being loaded.
* @return Error code indicating success or failure of the load operation.
+23 -4
View File
@@ -48,8 +48,20 @@ errorret_t assetMeshLoaderAsync(assetloading_t *loading) {
uint32_t vertCount = endianLittleToHost32(*(uint32_t *)(raw + 8));
meshvertex_t *vertices = NULL;
if(vertCount > 0) {
vertices = memoryAllocate(vertCount * sizeof(meshvertex_t));
// 32-byte (cache-line) aligned: GX_SetArray + DCFlushRange on Dolphin
// require this for the DMA'd vertex data to actually reach the GPU
// coherently. Static compiled-in vertex arrays happen to get this from
// the linker; a plain memoryAllocate here would not.
vertices = memoryAlign(32, vertCount * sizeof(meshvertex_t));
memoryCopy(vertices, raw + 12, vertCount * sizeof(meshvertex_t));
for(uint32_t v = 0; v < vertCount; v++) {
vertices[v].uv[0] = endianLittleToHostFloat(vertices[v].uv[0]);
vertices[v].uv[1] = endianLittleToHostFloat(vertices[v].uv[1]);
vertices[v].pos[0] = endianLittleToHostFloat(vertices[v].pos[0]);
vertices[v].pos[1] = endianLittleToHostFloat(vertices[v].pos[1]);
vertices[v].pos[2] = endianLittleToHostFloat(vertices[v].pos[2]);
}
}
memoryFree(raw);
@@ -103,18 +115,22 @@ errorret_t assetMeshLoaderSync(assetloading_t *loading) {
out->vertices = NULL;
errorChain(ret);
}
out->meshInitialized = true;
ret = meshFlush(&out->mesh, 0, (int32_t)vertCount);
if(errorIsNotOk(ret)) {
loading->entry->state = ASSET_ENTRY_STATE_ERROR;
meshDispose(&out->mesh);
out->meshInitialized = false;
memoryFree(out->vertices);
out->vertices = NULL;
errorChain(ret);
}
#ifndef DUSK_OPENGL_LEGACY
// VBO owns the data now; CPU copy is no longer needed.
#if defined(DUSK_OPENGL) && !defined(DUSK_OPENGL_LEGACY)
// VBO owns the data now; CPU copy is no longer needed. The platform
// mesh object itself still needs meshDispose later - tracked via
// out->meshInitialized, independent of the CPU buffer's lifetime.
memoryFree(out->vertices);
out->vertices = NULL;
#endif
@@ -129,8 +145,11 @@ errorret_t assetMeshDispose(assetentry_t *entry) {
assertIsMainThread("Must be called from the main thread.");
assetmeshoutput_t *out = &entry->data.mesh;
if(out->vertices != NULL) {
if(out->meshInitialized) {
errorChain(meshDispose(&out->mesh));
out->meshInitialized = false;
}
if(out->vertices != NULL) {
memoryFree(out->vertices);
out->vertices = NULL;
}
@@ -30,6 +30,7 @@ typedef struct {
typedef struct {
mesh_t mesh;
bool_t meshInitialized;
meshvertex_t *vertices;
} assetmeshoutput_t;
+1 -1
View File
@@ -17,7 +17,7 @@ console_t CONSOLE;
void consoleInit(void) {
memoryZero(&CONSOLE, sizeof(console_t));
CONSOLE.visible = true;
CONSOLE.visible = false;
#ifdef DUSK_CONSOLE_POSIX
threadMutexInit(&CONSOLE.printMutex);
+2
View File
@@ -10,6 +10,7 @@
#include "time/time.h"
#include "input/input.h"
#include "locale/localemanager.h"
#include "rpg/item/item.h"
#include "rpg/rpg.h"
#include "display/display.h"
#include "scene/scene.h"
@@ -39,6 +40,7 @@ errorret_t engineInit(const int32_t argc, const char_t **argv) {
errorChain(assetInit());
// errorChain(saveInit());
errorChain(localeManagerInit());
errorChain(itemInit());
errorChain(displayInit());
errorChain(uiInit());
errorChain(rpgInit());
+175 -1
View File
@@ -6,6 +6,7 @@
*/
#include "battle.h"
#include "assert/assert.h"
#include "util/memory.h"
battle_t BATTLE;
@@ -40,10 +41,183 @@ battlefighter_t *battleAddFighter(
return fighter;
}
void battleStart(void) {
void battleStart(
const battleencountertype_t encounterType,
const bool_t fleeAvailable
) {
assertTrue(encounterType < BATTLE_ENCOUNTER_COUNT, "Invalid encounter type");
BATTLE.encounterType = encounterType;
BATTLE.fleeAvailable = fleeAvailable;
BATTLE.result = BATTLE_RESULT_NONE;
BATTLE.round = 1;
BATTLE.turnIndex = 0;
battleBuildTurnOrder(true);
BATTLE.active = true;
}
void battleDispose(void) {
battleInit();
}
battlefighter_t *battleGetCurrentFighter(void) {
if(!BATTLE.active) return NULL;
if(BATTLE.turnIndex >= BATTLE.turnCount) return NULL;
return &BATTLE.fighters[BATTLE.turnOrder[BATTLE.turnIndex]];
}
uint8_t battleGetAliveCount(const battlefighterteam_t team) {
uint8_t count = 0;
for(uint8_t i = 0; i < BATTLE_FIGHTER_COUNT_MAX; i++) {
if(BATTLE.fighters[i].team != team) continue;
if(!battleFighterIsAlive(&BATTLE.fighters[i])) continue;
count++;
}
return count;
}
void battleResolveAttack(
battlefighter_t *attacker,
battlefighter_t *defender
) {
assertNotNull(attacker, "Attacker cannot be NULL");
assertNotNull(defender, "Defender cannot be NULL");
const int32_t rawDamage =
(int32_t)attacker->stats.attack - (int32_t)defender->stats.defense;
const uint16_t damage = rawDamage > 0 ? (uint16_t)rawDamage : 1;
defender->health = damage >= defender->health ? 0 : defender->health - damage;
if(defender->health == 0) defender->status = BATTLE_FIGHTER_STATUS_DEAD;
}
void battleNextTurn(void) {
BATTLE.turnIndex++;
if(BATTLE.turnIndex < BATTLE.turnCount) return;
BATTLE.round++;
BATTLE.turnIndex = 0;
battleBuildTurnOrder(false);
}
battleresult_t battleCheckResult(void) {
if(BATTLE.result != BATTLE_RESULT_NONE) return BATTLE.result;
if(battleGetAliveCount(BATTLE_FIGHTER_TEAM_ALLY) == 0) {
BATTLE.result = BATTLE_RESULT_LOSS;
} else if(battleGetAliveCount(BATTLE_FIGHTER_TEAM_ENEMY) == 0) {
BATTLE.result = BATTLE_RESULT_WIN;
}
return BATTLE.result;
}
void battlePlayerAttack(const uint8_t targetIndex) {
battlefighter_t *attacker = battleGetCurrentFighter();
if(attacker == NULL) return;
if(attacker->controller != BATTLE_FIGHTER_CONTROLLER_PLAYER) return;
if(targetIndex >= BATTLE_FIGHTER_COUNT_MAX) return;
battlefighter_t *defender = &BATTLE.fighters[targetIndex];
if(!battleFighterIsAlive(defender)) return;
battleResolveAttack(attacker, defender);
battleCheckResult();
if(BATTLE.result == BATTLE_RESULT_NONE) battleNextTurn();
}
void battlePlayerFlee(void) {
battlefighter_t *fighter = battleGetCurrentFighter();
if(fighter == NULL) return;
if(fighter->controller != BATTLE_FIGHTER_CONTROLLER_PLAYER) return;
if(!BATTLE.fleeAvailable) return;
BATTLE.result = BATTLE_RESULT_FLED;
}
void battleUpdate(void) {
if(!BATTLE.active) return;
if(BATTLE.result != BATTLE_RESULT_NONE) return;
battlefighter_t *current = battleGetCurrentFighter();
if(current == NULL) return;
if(!battleFighterIsAlive(current)) {
battleNextTurn();
return;
}
if(current->controller != BATTLE_FIGHTER_CONTROLLER_AI) return;
battlefighter_t *target = battleAIChooseTarget(current);
if(target != NULL) battleResolveAttack(current, target);
battleCheckResult();
if(BATTLE.result == BATTLE_RESULT_NONE) battleNextTurn();
}
void battleBuildTurnOrder(const bool_t applyEncounterBias) {
BATTLE.turnCount = 0;
for(uint8_t i = 0; i < BATTLE_FIGHTER_COUNT_MAX; i++) {
if(!battleFighterIsAlive(&BATTLE.fighters[i])) continue;
BATTLE.turnOrder[BATTLE.turnCount++] = i;
}
// Insertion sort by speed descending -- fine for BATTLE_FIGHTER_COUNT_MAX.
for(uint8_t i = 1; i < BATTLE.turnCount; i++) {
const uint8_t key = BATTLE.turnOrder[i];
const uint16_t keySpeed = BATTLE.fighters[key].stats.speed;
int8_t j = (int8_t)i - 1;
while(
j >= 0 && BATTLE.fighters[BATTLE.turnOrder[j]].stats.speed < keySpeed
) {
BATTLE.turnOrder[j + 1] = BATTLE.turnOrder[j];
j--;
}
BATTLE.turnOrder[j + 1] = key;
}
if(!applyEncounterBias) return;
if(BATTLE.encounterType == BATTLE_ENCOUNTER_PLAYER_ADVANTAGE) {
battleMoveTeamFirst(BATTLE_FIGHTER_TEAM_ALLY);
} else if(BATTLE.encounterType == BATTLE_ENCOUNTER_BACK_ATTACK) {
battleMoveTeamFirst(BATTLE_FIGHTER_TEAM_ENEMY);
}
}
void battleMoveTeamFirst(const battlefighterteam_t team) {
uint8_t sorted[BATTLE_FIGHTER_COUNT_MAX];
uint8_t count = 0;
for(uint8_t i = 0; i < BATTLE.turnCount; i++) {
if(BATTLE.fighters[BATTLE.turnOrder[i]].team != team) continue;
sorted[count++] = BATTLE.turnOrder[i];
}
for(uint8_t i = 0; i < BATTLE.turnCount; i++) {
if(BATTLE.fighters[BATTLE.turnOrder[i]].team == team) continue;
sorted[count++] = BATTLE.turnOrder[i];
}
memoryCopy(BATTLE.turnOrder, sorted, sizeof(uint8_t) * BATTLE.turnCount);
}
battlefighter_t *battleAIChooseTarget(const battlefighter_t *fighter) {
const battlefighterteam_t enemyTeam =
fighter->team == BATTLE_FIGHTER_TEAM_ALLY ?
BATTLE_FIGHTER_TEAM_ENEMY : BATTLE_FIGHTER_TEAM_ALLY;
battlefighter_t *weakest = NULL;
for(uint8_t i = 0; i < BATTLE_FIGHTER_COUNT_MAX; i++) {
battlefighter_t *candidate = &BATTLE.fighters[i];
if(candidate->team != enemyTeam) continue;
if(!battleFighterIsAlive(candidate)) continue;
if(weakest == NULL || candidate->health < weakest->health) {
weakest = candidate;
}
}
return weakest;
}
+136 -3
View File
@@ -10,9 +10,36 @@
#define BATTLE_FIGHTER_COUNT_MAX 8
typedef enum {
BATTLE_ENCOUNTER_REGULAR,
BATTLE_ENCOUNTER_PLAYER_ADVANTAGE,
BATTLE_ENCOUNTER_BACK_ATTACK,
BATTLE_ENCOUNTER_COUNT
} battleencountertype_t;
typedef enum {
BATTLE_RESULT_NONE,
BATTLE_RESULT_WIN,
BATTLE_RESULT_LOSS,
BATTLE_RESULT_FLED,
BATTLE_RESULT_COUNT
} battleresult_t;
typedef struct {
bool_t active;
battlefighter_t fighters[BATTLE_FIGHTER_COUNT_MAX];
battleencountertype_t encounterType;
bool_t fleeAvailable;
battleresult_t result;
// Fighter indices (into fighters[]), sorted for the current round.
uint8_t turnOrder[BATTLE_FIGHTER_COUNT_MAX];
uint8_t turnCount;
uint8_t turnIndex;
uint16_t round;
} battle_t;
extern battle_t BATTLE;
@@ -50,12 +77,118 @@ battlefighter_t *battleAddFighter(
);
/**
* Starts a battle, marking it active. Any fighters already added via
* battleAddFighter remain in place.
* Starts the battle: builds the opening turn order (biased by
* encounterType for the first round only) and marks the battle active.
* Call once every fighter has been added via battleAddFighter.
*
* @param encounterType Determines the opening round's turn order.
* @param fleeAvailable Whether the party may attempt to flee this battle.
*/
void battleStart(void);
void battleStart(
const battleencountertype_t encounterType,
const bool_t fleeAvailable
);
/**
* Disposes of the battle, clearing all fighters and marking it inactive.
*/
void battleDispose(void);
/**
* Returns the fighter whose turn it currently is.
*
* @return Pointer to the active fighter, or NULL if the battle isn't
* active or has no living fighters left to act.
*/
battlefighter_t *battleGetCurrentFighter(void);
/**
* Returns the number of living fighters on a team.
*
* @param team The team to count.
* @return Count of living fighters on that team.
*/
uint8_t battleGetAliveCount(const battlefighterteam_t team);
/**
* Resolves a physical attack from attacker onto defender: damage is the
* attacker's attack stat minus the defender's defense stat (minimum 1),
* subtracted from the defender's health. The defender is marked dead
* once health reaches 0.
*
* @param attacker The attacking fighter.
* @param defender The defending fighter.
*/
void battleResolveAttack(
battlefighter_t *attacker,
battlefighter_t *defender
);
/**
* Ends the current fighter's turn and advances to the next fighter in
* the turn order, starting a new round (rebuilding turn order purely by
* speed) once every fighter in the current round has acted.
*/
void battleNextTurn(void);
/**
* Checks whether the battle has been won or lost, updating and
* returning BATTLE.result. Does nothing if a result has already been
* set (e.g. by a successful flee).
*
* @return The battle's current result.
*/
battleresult_t battleCheckResult(void);
/**
* Submits the current fighter's attack against a target, if it is
* currently a player-controlled fighter's turn. Resolves the attack,
* checks for a battle result, and advances the turn.
*
* @param targetIndex Index into BATTLE.fighters of the target.
*/
void battlePlayerAttack(const uint8_t targetIndex);
/**
* Submits a flee attempt for the current fighter's turn, if it is
* currently a player-controlled fighter's turn and fleeing is
* available for this battle. Always succeeds, ending the battle with
* BATTLE_RESULT_FLED.
*/
void battlePlayerFlee(void);
/**
* Updates the battle simulation for one frame: resolves the current
* fighter's turn automatically if AI-controlled, otherwise waits for a
* player action via battlePlayerAttack/battlePlayerFlee. No-op if the
* battle isn't active or already has a result.
*/
void battleUpdate(void);
/**
* Rebuilds BATTLE.turnOrder/turnCount from every currently living
* fighter, sorted by speed descending.
*
* @param applyEncounterBias If true, reorders the freshly speed-sorted
* queue so BATTLE.encounterType's favoured team goes first (used only
* for the opening round).
*/
void battleBuildTurnOrder(const bool_t applyEncounterBias);
/**
* Stably partitions BATTLE.turnOrder so every fighter on the given team
* comes first, preserving each side's relative (speed-sorted) order.
*
* @param team The team to move to the front of the turn order.
*/
void battleMoveTeamFirst(const battlefighterteam_t team);
/**
* Picks an AI target for fighter: the lowest-health living fighter on
* the opposing team.
*
* @param fighter The AI-controlled fighter choosing a target.
* @return The chosen target, or NULL if the opposing team has no
* living fighters.
*/
battlefighter_t *battleAIChooseTarget(const battlefighter_t *fighter);
+1
View File
@@ -6,6 +6,7 @@
# Sources
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
cutscene.c
cutscenesystem.c
)
+444
View File
@@ -0,0 +1,444 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "cutscene.h"
#include "assert/assert.h"
#include "util/memory.h"
#include "util/string.h"
#include "asset/asset.h"
#include "asset/loader/assetloader.h"
#include "asset/loader/assetentry.h"
#include "asset/loader/json/assetjsonloader.h"
#include "rpg/cutscene/cutscenesystem.h"
#include "rpg/entity/entitytype.h"
#include "rpg/entity/entitydir.h"
#include "ui/rpg/uiemoji.h"
#include "yyjson.h"
static cutscenejsoncacheentry_t CUTSCENE_JSON_CACHE[CUTSCENE_JSON_CACHE_MAX];
static uint32_t CUTSCENE_JSON_CACHE_COUNT;
errorret_t cutsceneJsonParsePause(yyjson_val *val, cutscenepause_t *outPause) {
assertNotNull(outPause, "Output pause pointer cannot be NULL");
if(!val || !yyjson_is_str(val)) {
errorThrow("Cutscene pause value must be a string");
}
const char_t *str = yyjson_get_str(val);
if(stringEquals(str, "NONE")) {
*outPause = CUTSCENE_PAUSE_NONE;
} else if(stringEquals(str, "DEFAULT")) {
*outPause = CUTSCENE_PAUSE_DEFAULT;
} else if(stringEquals(str, "ALL")) {
*outPause = CUTSCENE_PAUSE_ALL;
} else {
errorThrow("Unknown cutscene pause value '%s'", str);
}
errorOk();
}
errorret_t cutsceneJsonParseEntityIndex(yyjson_val *val, uint8_t *outIndex) {
assertNotNull(outIndex, "Output entity index pointer cannot be NULL");
if(val && yyjson_is_str(val)) {
const char_t *str = yyjson_get_str(val);
if(stringEquals(str, "interact")) {
*outIndex = CUTSCENE_ENTITY_INTERACT;
} else if(stringEquals(str, "interacted")) {
*outIndex = CUTSCENE_ENTITY_INTERACTED;
} else if(stringEquals(str, "lastCreated")) {
*outIndex = CUTSCENE_ENTITY_LAST_CREATED;
} else {
errorThrow("Unknown entity index sentinel '%s'", str);
}
errorOk();
}
if(!val || !yyjson_is_int(val)) {
errorThrow("Entity index must be a number or sentinel string");
}
*outIndex = (uint8_t)yyjson_get_int(val);
errorOk();
}
errorret_t cutsceneJsonParseWorldPos(yyjson_val *val, worldpos_t *outPos) {
assertNotNull(outPos, "Output position pointer cannot be NULL");
if(!val || !yyjson_is_arr(val) || yyjson_arr_size(val) != 3) {
errorThrow("Position must be a [x, y, z] array");
}
worldunit_t comps[3];
size_t idx, max;
yyjson_val *elem;
yyjson_arr_foreach(val, idx, max, elem) {
if(!yyjson_is_num(elem)) {
errorThrow("Position elements must be numbers");
}
comps[idx] = (worldunit_t)yyjson_get_num(elem);
}
*outPos = (worldpos_t){ comps[0], comps[1], comps[2] };
errorOk();
}
errorret_t cutsceneItemCreateFromJson(
yyjson_val *obj,
cutsceneitem_t *outItem,
worldpos_t *waypoints,
const uint8_t waypointsMax
) {
assertNotNull(obj, "Cutscene item JSON object cannot be NULL");
assertNotNull(outItem, "Output item pointer cannot be NULL");
yyjson_val *typeVal = yyjson_obj_get(obj, "type");
if(!typeVal || !yyjson_is_str(typeVal)) {
errorThrow("Cutscene item JSON missing 'type' string");
}
const char_t *typeStr = yyjson_get_str(typeVal);
memoryZero(outItem, sizeof(cutsceneitem_t));
if(stringEquals(typeStr, "text")) {
yyjson_val *textVal = yyjson_obj_get(obj, "text");
if(!textVal || !yyjson_is_str(textVal)) {
errorThrow("Cutscene 'text' item missing 'text' string");
}
outItem->type = CUTSCENE_ITEM_TYPE_TEXT;
stringCopy(
outItem->text.text, yyjson_get_str(textVal), CUTSCENE_TEXT_MAX_CHARS
);
} else if(stringEquals(typeStr, "textMini")) {
yyjson_val *textVal = yyjson_obj_get(obj, "text");
if(!textVal || !yyjson_is_str(textVal)) {
errorThrow("Cutscene 'textMini' item missing 'text' string");
}
worldpos_t pos;
errorChain(
cutsceneJsonParseWorldPos(yyjson_obj_get(obj, "position"), &pos)
);
yyjson_val *durVal = yyjson_obj_get(obj, "duration");
if(!durVal || !yyjson_is_num(durVal)) {
errorThrow("Cutscene 'textMini' item missing 'duration' number");
}
outItem->type = CUTSCENE_ITEM_TYPE_TEXT_MINI;
stringCopy(
outItem->textMini.text, yyjson_get_str(textVal),
CUTSCENE_TEXT_MINI_MAX_CHARS
);
outItem->textMini.position[0] = (float_t)pos.x;
outItem->textMini.position[1] = (float_t)pos.y;
outItem->textMini.position[2] = (float_t)pos.z;
outItem->textMini.duration = (float_t)yyjson_get_num(durVal);
} else if(stringEquals(typeStr, "textMiniHide")) {
yyjson_val *indexVal = yyjson_obj_get(obj, "index");
if(!indexVal || !yyjson_is_int(indexVal)) {
errorThrow("Cutscene 'textMiniHide' item missing 'index' number");
}
outItem->type = CUTSCENE_ITEM_TYPE_TEXT_MINI_HIDE;
outItem->textMiniHide.index = (uint8_t)yyjson_get_int(indexVal);
} else if(stringEquals(typeStr, "wait")) {
yyjson_val *durVal = yyjson_obj_get(obj, "duration");
if(!durVal || !yyjson_is_num(durVal)) {
errorThrow("Cutscene 'wait' item missing 'duration' number");
}
outItem->type = CUTSCENE_ITEM_TYPE_WAIT;
outItem->wait = (float_t)yyjson_get_num(durVal);
} else if(stringEquals(typeStr, "entityAdd")) {
yyjson_val *entityTypeVal = yyjson_obj_get(obj, "entityType");
if(!entityTypeVal || !yyjson_is_str(entityTypeVal)) {
errorThrow("Cutscene 'entityAdd' item missing 'entityType' string");
}
const char_t *entityTypeStr = yyjson_get_str(entityTypeVal);
entitytype_t entityType;
if(stringEquals(entityTypeStr, "player")) {
entityType = ENTITY_TYPE_PLAYER;
} else if(stringEquals(entityTypeStr, "npc")) {
entityType = ENTITY_TYPE_NPC;
} else if(stringEquals(entityTypeStr, "item")) {
entityType = ENTITY_TYPE_ITEM;
} else {
errorThrow(
"Cutscene 'entityAdd' has unknown entityType '%s'", entityTypeStr
);
}
worldpos_t pos;
errorChain(
cutsceneJsonParseWorldPos(yyjson_obj_get(obj, "position"), &pos)
);
outItem->type = CUTSCENE_ITEM_TYPE_ENTITY_ADD;
outItem->entityAdd.entityType = entityType;
outItem->entityAdd.position = pos;
} else if(stringEquals(typeStr, "entityRemove")) {
uint8_t entityIndex;
errorChain(cutsceneJsonParseEntityIndex(
yyjson_obj_get(obj, "entityIndex"), &entityIndex
));
outItem->type = CUTSCENE_ITEM_TYPE_ENTITY_REMOVE;
outItem->entityRemove.entityIndex = entityIndex;
} else if(stringEquals(typeStr, "entityTurn")) {
uint8_t entityIndex;
errorChain(cutsceneJsonParseEntityIndex(
yyjson_obj_get(obj, "entityIndex"), &entityIndex
));
yyjson_val *dirVal = yyjson_obj_get(obj, "direction");
if(!dirVal || !yyjson_is_str(dirVal)) {
errorThrow("Cutscene 'entityTurn' item missing 'direction' string");
}
const char_t *dirStr = yyjson_get_str(dirVal);
entitydir_t direction;
if(stringEquals(dirStr, "north")) {
direction = ENTITY_DIR_NORTH;
} else if(stringEquals(dirStr, "east")) {
direction = ENTITY_DIR_EAST;
} else if(stringEquals(dirStr, "south")) {
direction = ENTITY_DIR_SOUTH;
} else if(stringEquals(dirStr, "west")) {
direction = ENTITY_DIR_WEST;
} else {
errorThrow("Cutscene 'entityTurn' has unknown direction '%s'", dirStr);
}
outItem->type = CUTSCENE_ITEM_TYPE_ENTITY_TURN;
outItem->entityTurn.entityIndex = entityIndex;
outItem->entityTurn.direction = direction;
} else if(stringEquals(typeStr, "entityWalkTo")) {
uint8_t entityIndex;
errorChain(cutsceneJsonParseEntityIndex(
yyjson_obj_get(obj, "entityIndex"), &entityIndex
));
yyjson_val *positionsVal = yyjson_obj_get(obj, "positions");
if(!positionsVal || !yyjson_is_arr(positionsVal)) {
errorThrow("Cutscene 'entityWalkTo' item missing 'positions' array");
}
size_t count = yyjson_arr_size(positionsVal);
if(count == 0 || count > waypointsMax) {
errorThrow(
"Cutscene 'entityWalkTo' 'positions' must have 1-%d entries",
waypointsMax
);
}
assertNotNull(waypoints, "Waypoint storage cannot be NULL");
size_t idx, max;
yyjson_val *posVal;
yyjson_arr_foreach(positionsVal, idx, max, posVal) {
errorChain(cutsceneJsonParseWorldPos(posVal, &waypoints[idx]));
}
bool_t walkAround = true;
yyjson_val *walkAroundVal = yyjson_obj_get(obj, "walkAround");
if(walkAroundVal && yyjson_is_bool(walkAroundVal)) {
walkAround = yyjson_get_bool(walkAroundVal);
}
outItem->type = CUTSCENE_ITEM_TYPE_ENTITY_WALK_TO;
outItem->entityWalkTo.entityIndex = entityIndex;
outItem->entityWalkTo.positions = waypoints;
outItem->entityWalkTo.count = (uint8_t)count;
outItem->entityWalkTo.walkAround = walkAround;
} else if(stringEquals(typeStr, "entityWalkToEntity")) {
uint8_t entityIndex, targetEntityIndex;
errorChain(cutsceneJsonParseEntityIndex(
yyjson_obj_get(obj, "entityIndex"), &entityIndex
));
errorChain(cutsceneJsonParseEntityIndex(
yyjson_obj_get(obj, "targetEntityIndex"), &targetEntityIndex
));
yyjson_val *offsetXVal = yyjson_obj_get(obj, "offsetX");
yyjson_val *offsetYVal = yyjson_obj_get(obj, "offsetY");
if(
!offsetXVal || !yyjson_is_num(offsetXVal) ||
!offsetYVal || !yyjson_is_num(offsetYVal)
) {
errorThrow(
"Cutscene 'entityWalkToEntity' item missing "
"'offsetX'/'offsetY' numbers"
);
}
outItem->type = CUTSCENE_ITEM_TYPE_ENTITY_WALK_TO_ENTITY;
outItem->entityWalkToEntity.entityIndex = entityIndex;
outItem->entityWalkToEntity.targetEntityIndex = targetEntityIndex;
outItem->entityWalkToEntity.offsetX =
(worldunit_t)yyjson_get_num(offsetXVal);
outItem->entityWalkToEntity.offsetY =
(worldunit_t)yyjson_get_num(offsetYVal);
} else if(stringEquals(typeStr, "entityTeleport")) {
uint8_t entityIndex;
errorChain(cutsceneJsonParseEntityIndex(
yyjson_obj_get(obj, "entityIndex"), &entityIndex
));
worldpos_t pos;
errorChain(
cutsceneJsonParseWorldPos(yyjson_obj_get(obj, "position"), &pos)
);
outItem->type = CUTSCENE_ITEM_TYPE_ENTITY_TELEPORT;
outItem->entityTeleport.entityIndex = entityIndex;
outItem->entityTeleport.target = pos;
} else if(stringEquals(typeStr, "emoji")) {
uint8_t entityIndex;
errorChain(cutsceneJsonParseEntityIndex(
yyjson_obj_get(obj, "entityIndex"), &entityIndex
));
yyjson_val *emojiTypeVal = yyjson_obj_get(obj, "emojiType");
if(!emojiTypeVal || !yyjson_is_str(emojiTypeVal)) {
errorThrow("Cutscene 'emoji' item missing 'emojiType' string");
}
const char_t *emojiTypeStr = yyjson_get_str(emojiTypeVal);
uiemojitype_t emojiType;
if(stringEquals(emojiTypeStr, "question")) {
emojiType = UI_EMOJI_QUESTION_MARK;
} else if(stringEquals(emojiTypeStr, "exclamation")) {
emojiType = UI_EMOJI_EXCLAMATION_MARK;
} else {
errorThrow(
"Cutscene 'emoji' has unknown emojiType '%s'", emojiTypeStr
);
}
yyjson_val *durVal = yyjson_obj_get(obj, "duration");
if(!durVal || !yyjson_is_num(durVal)) {
errorThrow("Cutscene 'emoji' item missing 'duration' number");
}
outItem->type = CUTSCENE_ITEM_TYPE_EMOJI;
outItem->emoji.entityIndex = entityIndex;
outItem->emoji.emojiType = emojiType;
outItem->emoji.duration = (float_t)yyjson_get_num(durVal);
} else if(stringEquals(typeStr, "shake")) {
yyjson_val *amountVal = yyjson_obj_get(obj, "amount");
yyjson_val *durVal = yyjson_obj_get(obj, "duration");
if(
!amountVal || !yyjson_is_int(amountVal) ||
!durVal || !yyjson_is_num(durVal)
) {
errorThrow("Cutscene 'shake' item missing 'amount'/'duration' numbers");
}
outItem->type = CUTSCENE_ITEM_TYPE_SHAKE;
outItem->shake.amount = (uint8_t)yyjson_get_int(amountVal);
outItem->shake.duration = (float_t)yyjson_get_num(durVal);
} else if(stringEquals(typeStr, "setPause")) {
cutscenepause_t pause;
errorChain(
cutsceneJsonParsePause(yyjson_obj_get(obj, "pause"), &pause)
);
outItem->type = CUTSCENE_ITEM_TYPE_SET_PAUSE;
outItem->setPause = pause;
} else {
errorThrow("Cutscene item JSON has unknown 'type': %s", typeStr);
}
errorOk();
}
errorret_t cutsceneGetByName(
const char_t *name, const cutscene_t **outCutscene
) {
assertNotNull(name, "Cutscene name cannot be NULL");
assertNotNull(outCutscene, "Output cutscene pointer cannot be NULL");
assertStrLenMax(name, CUTSCENE_JSON_NAME_MAX, "Cutscene name too long");
for(uint32_t i = 0; i < CUTSCENE_JSON_CACHE_COUNT; i++) {
if(!stringEquals(CUTSCENE_JSON_CACHE[i].name, name)) continue;
*outCutscene = &CUTSCENE_JSON_CACHE[i].cutscene;
errorOk();
}
if(CUTSCENE_JSON_CACHE_COUNT >= CUTSCENE_JSON_CACHE_MAX) {
errorThrow(
"Too many cutscenes loaded: exceeds CUTSCENE_JSON_CACHE_MAX (%d)",
CUTSCENE_JSON_CACHE_MAX
);
}
char_t path[CUTSCENE_JSON_NAME_MAX + 24];
stringFormat(path, sizeof(path), "cutscene/%s.json", name);
assetentry_t *entry = assetLock(path, ASSET_LOADER_TYPE_JSON, NULL);
errorret_t ret = assetRequireLoaded(entry);
if(errorIsNotOk(ret)) {
assetUnlockEntry(entry);
errorChain(ret);
}
yyjson_val *root = yyjson_doc_get_root(entry->data.json);
cutscenepause_t pause = CUTSCENE_PAUSE_DEFAULT;
yyjson_val *pauseVal = yyjson_obj_get(root, "pause");
if(pauseVal) {
errorret_t pauseRet = cutsceneJsonParsePause(pauseVal, &pause);
if(errorIsNotOk(pauseRet)) {
assetUnlockEntry(entry);
errorChain(pauseRet);
}
}
yyjson_val *itemsVal = yyjson_obj_get(root, "items");
if(!itemsVal || !yyjson_is_arr(itemsVal)) {
assetUnlockEntry(entry);
errorThrow("Cutscene '%s' JSON missing 'items' array", name);
}
size_t itemCount = yyjson_arr_size(itemsVal);
if(itemCount == 0 || itemCount > CUTSCENE_JSON_ITEM_COUNT_MAX) {
assetUnlockEntry(entry);
errorThrow(
"Cutscene '%s' 'items' must have 1-%d entries",
name, CUTSCENE_JSON_ITEM_COUNT_MAX
);
}
cutscenejsoncacheentry_t *cache =
&CUTSCENE_JSON_CACHE[CUTSCENE_JSON_CACHE_COUNT];
memoryZero(cache, sizeof(cutscenejsoncacheentry_t));
stringCopy(cache->name, name, CUTSCENE_JSON_NAME_MAX);
size_t idx, max;
yyjson_val *itemVal;
yyjson_arr_foreach(itemsVal, idx, max, itemVal) {
errorret_t itemRet = cutsceneItemCreateFromJson(
itemVal, &cache->items[idx], cache->waypoints[idx],
CUTSCENE_JSON_WAYPOINT_COUNT_MAX
);
if(errorIsNotOk(itemRet)) {
assetUnlockEntry(entry);
errorChain(itemRet);
}
}
assetUnlockEntry(entry);
cache->cutscene.items = cache->items;
cache->cutscene.itemCount = (uint8_t)itemCount;
cache->cutscene.pause = pause;
cache->cutscene.dataSize = 0;
CUTSCENE_JSON_CACHE_COUNT++;
*outCutscene = &cache->cutscene;
errorOk();
}
+153 -2
View File
@@ -9,6 +9,8 @@
#include "rpg/cutscene/item/cutsceneitem.h"
#include "rpg/cutscene/cutscenepause.h"
typedef struct yyjson_val yyjson_val;
typedef struct cutscene_s {
const cutsceneitem_t *items;
uint8_t itemCount;
@@ -34,6 +36,22 @@ typedef struct cutscene_s {
#define CUTSCENE_TEXT(TEXT) \
{ .type = CUTSCENE_ITEM_TYPE_TEXT, .text = { .text = TEXT } }
#define CUTSCENE_TEXT_MINI(TEXT, X, Y, Z, DURATION) \
{ \
.type = CUTSCENE_ITEM_TYPE_TEXT_MINI, \
.textMini = { \
.text = TEXT, \
.position = { X, Y, Z }, \
.duration = DURATION \
} \
}
#define CUTSCENE_TEXT_MINI_HIDE(INDEX) \
{ \
.type = CUTSCENE_ITEM_TYPE_TEXT_MINI_HIDE, \
.textMiniHide = { .index = INDEX } \
}
#define CUTSCENE_WAIT(WAIT) \
{ .type = CUTSCENE_ITEM_TYPE_WAIT, .wait = WAIT }
@@ -128,13 +146,31 @@ typedef struct cutscene_s {
#define CUTSCENE_FADE_FROM_WHITE(DURATION) \
CUTSCENE_FADE(COLOR_WHITE, COLOR_TRANSPARENT_WHITE, DURATION, EASING_LINEAR)
#define CUTSCENE_EMOJI(ENTITY_INDEX, EMOJI_TYPE, DURATION) \
{ \
.type = CUTSCENE_ITEM_TYPE_EMOJI, \
.emoji = { \
.entityIndex = ENTITY_INDEX, \
.emojiType = EMOJI_TYPE, \
.duration = DURATION \
} \
}
// AMOUNT ranges 0 (no shake) to 4 (three tiles): 1 is half a tile, 2 is
// a full tile, 3 is two tiles, and 4 is three tiles.
#define CUTSCENE_SHAKE(AMOUNT, DURATION) \
{ \
.type = CUTSCENE_ITEM_TYPE_SHAKE, \
.shake = { .amount = AMOUNT, .duration = DURATION } \
}
#define CUTSCENE_SET_PAUSE(FLAGS) \
{ .type = CUTSCENE_ITEM_TYPE_SET_PAUSE, .setPause = (FLAGS) }
#define CUTSCENE_ITEM_GIVE(ITEM_ID, QUANTITY) \
#define CUTSCENE_ITEM_GIVE(ITEM_NAME, QUANTITY) \
{ \
.type = CUTSCENE_ITEM_TYPE_ITEM_GIVE, \
.itemGive = { .item = ITEM_ID, .quantity = QUANTITY } \
.itemGive = { .itemName = ITEM_NAME, .quantity = QUANTITY } \
}
// Runs all listed items simultaneously and waits until all are done.
@@ -196,3 +232,118 @@ typedef struct cutscene_s {
), \
CUTSCENE_MAP_AREA_WAIT(CUTSCENE_AREA_LAST_CREATED), \
CUTSCENE_MAP_AREA_REMOVE(CUTSCENE_AREA_LAST_CREATED)
#define CUTSCENE_JSON_NAME_MAX 32
#define CUTSCENE_JSON_ITEM_COUNT_MAX 32
#define CUTSCENE_JSON_WAYPOINT_COUNT_MAX 8
#define CUTSCENE_JSON_CACHE_MAX 16
// One slot of the cutsceneGetByName cache: a parsed cutscene plus the
// backing storage its items point into (items themselves, and the
// waypoint lists any "entityWalkTo" items reference).
typedef struct {
char_t name[CUTSCENE_JSON_NAME_MAX];
cutscene_t cutscene;
cutsceneitem_t items[CUTSCENE_JSON_ITEM_COUNT_MAX];
worldpos_t waypoints
[CUTSCENE_JSON_ITEM_COUNT_MAX][CUTSCENE_JSON_WAYPOINT_COUNT_MAX];
} cutscenejsoncacheentry_t;
/**
* Parses a cutscene pause value ("NONE", "DEFAULT" or "ALL") from a
* yyjson string value.
*
* @param val The yyjson value to parse.
* @param outPause Output pointer, set to the parsed pause flags.
* @return Any error that occurs (missing/invalid/unknown value).
*/
errorret_t cutsceneJsonParsePause(yyjson_val *val, cutscenepause_t *outPause);
/**
* Parses an entityIndex-shaped yyjson value - a raw number, or one of
* "interact", "interacted", "lastCreated" - into a raw uint8_t index or
* the matching CUTSCENE_ENTITY_* sentinel (see cutscenesystem.h).
*
* @param val The yyjson value to parse.
* @param outIndex Output pointer, set to the parsed index.
* @return Any error that occurs (missing/invalid/unknown value).
*/
errorret_t cutsceneJsonParseEntityIndex(yyjson_val *val, uint8_t *outIndex);
/**
* Parses a [x, y, z] yyjson array into a worldpos_t.
*
* @param val The yyjson value to parse.
* @param outPos Output pointer, set to the parsed position.
* @return Any error that occurs (missing/invalid value).
*/
errorret_t cutsceneJsonParseWorldPos(yyjson_val *val, worldpos_t *outPos);
/**
* Parses a single cutscene item from a yyjson object into outItem.
* "type" selects the item shape (required):
* { "type": "text", "text": "Hello!" }
* { "type": "textMini", "text": "Hi", "position": [x, y, z],
* "duration": 3.0 }
* { "type": "textMiniHide", "index": 0 }
* { "type": "wait", "duration": 1.5 }
* { "type": "entityAdd", "entityType": "npc", "position": [x, y, z] }
* { "type": "entityRemove", "entityIndex": 0 }
* { "type": "entityTurn", "entityIndex": 0, "direction": "south" }
* { "type": "entityWalkTo", "entityIndex": 0,
* "positions": [[x, y, z], ...], "walkAround": true }
* { "type": "entityWalkToEntity", "entityIndex": 0,
* "targetEntityIndex": 1, "offsetX": 1, "offsetY": 0 }
* { "type": "entityTeleport", "entityIndex": 0, "position": [x, y, z] }
* { "type": "emoji", "entityIndex": 0, "emojiType": "exclamation",
* "duration": 2.0 }
* { "type": "shake", "amount": 2, "duration": 0.5 }
* { "type": "setPause", "pause": "ALL" }
* "entityIndex"/"targetEntityIndex" accept a raw number, or one of
* "interact", "interacted", "lastCreated" for the matching
* CUTSCENE_ENTITY_* sentinel. "entityType" uses the same strings as
* entityCreateFromJson ("player", "npc", "item"); "direction" is one of
* "north"/"east"/"south"/"west"; "emojiType" is "question" or
* "exclamation"; "pause" is "NONE", "DEFAULT" or "ALL".
*
* Not supported (would need persistent string/array storage or function
* pointers this parser doesn't provide): itemGive, concurrent, fade,
* map area items, callbacks, nested cutscene references.
*
* @param obj The yyjson object describing a single cutscene item.
* @param outItem Output pointer, filled with the parsed item.
* @param waypoints Backing storage for an "entityWalkTo" item's waypoint
* list; must remain valid for as long as the parsed item is used.
* Unused (may be NULL) for any other item type.
* @param waypointsMax Capacity of waypoints.
* @return Any error that occurs (missing/invalid/unknown fields).
*/
errorret_t cutsceneItemCreateFromJson(
yyjson_val *obj,
cutsceneitem_t *outItem,
worldpos_t *waypoints,
const uint8_t waypointsMax
);
/**
* Loads (or returns the cached result of an earlier load of) the named
* cutscene from assets/cutscene/<name>.json, parsing each entry of its
* "items" array with cutsceneItemCreateFromJson. Parsed once per name
* and cached for the lifetime of the process; holds at most
* CUTSCENE_JSON_CACHE_MAX distinct names, each with at most
* CUTSCENE_JSON_ITEM_COUNT_MAX items.
*
* File shape:
* { "pause": "DEFAULT", "items": [ { "type": "text", ... }, ... ] }
* "pause" is optional (one of "NONE", "DEFAULT", "ALL"; defaults to
* "DEFAULT" when absent).
*
* @param name The cutscene's file name (without extension), under
* assets/cutscene/.
* @param outCutscene Output pointer, set to the loaded cutscene.
* @return Any error that occurs (missing/malformed file, cache full,
* unsupported/invalid item).
*/
errorret_t cutsceneGetByName(
const char_t *name, const cutscene_t **outCutscene
);
+15
View File
@@ -37,6 +37,7 @@ void cutsceneSystemStartCutsceneWith(
CUTSCENE_SYSTEM.entityLastCreated = NULL;
CUTSCENE_SYSTEM.entityLastRef = NULL;
CUTSCENE_SYSTEM.areaLastCreated = CUTSCENE_AREA_LAST_CREATED;
CUTSCENE_SYSTEM.textMiniLastCreated = CUTSCENE_TEXT_MINI_LAST_CREATED;
CUTSCENE_SYSTEM.currentItem = 0xFF;// Set to 0xFF so Next wraps to 0.
cutsceneSystemNext();
}
@@ -65,6 +66,7 @@ void cutsceneSystemNext() {
CUTSCENE_SYSTEM.entityLastCreated = NULL;
CUTSCENE_SYSTEM.entityLastRef = NULL;
CUTSCENE_SYSTEM.areaLastCreated = CUTSCENE_AREA_LAST_CREATED;
CUTSCENE_SYSTEM.textMiniLastCreated = CUTSCENE_TEXT_MINI_LAST_CREATED;
return;
}
@@ -130,6 +132,18 @@ uint8_t cutsceneSystemGetAreaId(const uint8_t areaId) {
return areaId;
}
uint8_t cutsceneSystemGetTextMiniId(const uint8_t index) {
if(index == CUTSCENE_TEXT_MINI_LAST_CREATED) {
assertTrue(
CUTSCENE_SYSTEM.textMiniLastCreated != CUTSCENE_TEXT_MINI_LAST_CREATED,
"CUTSCENE_TEXT_MINI_LAST_CREATED used but no mini textbox has been "
"shown"
);
return CUTSCENE_SYSTEM.textMiniLastCreated;
}
return index;
}
void cutsceneSystemDispose() {
CUTSCENE_SYSTEM.scene = NULL;
CUTSCENE_SYSTEM.currentItem = 0xFF;
@@ -139,4 +153,5 @@ void cutsceneSystemDispose() {
CUTSCENE_SYSTEM.entityLastCreated = NULL;
CUTSCENE_SYSTEM.entityLastRef = NULL;
CUTSCENE_SYSTEM.areaLastCreated = CUTSCENE_AREA_LAST_CREATED;
CUTSCENE_SYSTEM.textMiniLastCreated = CUTSCENE_TEXT_MINI_LAST_CREATED;
}
+11
View File
@@ -15,6 +15,7 @@ typedef struct entity_s entity_t;
#define CUTSCENE_ENTITY_LAST_CREATED ((uint8_t)0xFC)
#define CUTSCENE_ENTITY_LAST_REF ((uint8_t)0xFB)
#define CUTSCENE_AREA_LAST_CREATED ((uint8_t)0xFF)
#define CUTSCENE_TEXT_MINI_LAST_CREATED ((uint8_t)0xFA)
// Maximum number of bytes a running cutscene may request via
// cutscene_t.dataSize.
@@ -29,6 +30,7 @@ typedef struct {
entity_t *entityLastCreated;
entity_t *entityLastRef;
uint8_t areaLastCreated;
uint8_t textMiniLastCreated;
// Data (used by the current item).
cutsceneitemdata_t data;
@@ -86,6 +88,15 @@ entity_t * cutsceneSystemGetEntity(const uint8_t entityIndex);
*/
uint8_t cutsceneSystemGetAreaId(const uint8_t areaId);
/**
* Resolves a raw mini textbox slot index (or CUTSCENE_TEXT_MINI_LAST_CREATED
* sentinel) to a concrete UI_TEXTBOX_MINI_LIST slot index.
*
* @param index Raw slot index or sentinel value.
* @returns The resolved slot index.
*/
uint8_t cutsceneSystemGetTextMiniId(const uint8_t index);
/**
* Advance to the next item in the cutscene.
*/
@@ -14,3 +14,4 @@ add_subdirectory(entity)
add_subdirectory(item)
add_subdirectory(maparea)
add_subdirectory(ui)
add_subdirectory(battle)
@@ -0,0 +1,9 @@
# Copyright (c) 2026 Dominic Masters
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
cutscenestartbattle.c
)
@@ -0,0 +1,71 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "rpg/cutscene/item/cutsceneitem.h"
#include "rpg/battle/party.h"
#include "scene/scene.h"
void cutsceneStartBattleStart(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
const cutscenestartbattle_t *config = &item->startBattle;
battleInit();
for(uint8_t i = 0; i < PARTY_ACTIVE_SIZE_MAX; i++) {
battlefighter_t *member = partyGetOrderMember(i);
if(member == NULL) continue;
battlefighter_t *fighter = battleAddFighter(
BATTLE_FIGHTER_TEAM_ALLY, BATTLE_FIGHTER_CONTROLLER_PLAYER,
member->stats, member->healthMax, member->mpMax
);
if(fighter == NULL) continue;
fighter->health = member->health;
fighter->mp = member->mp;
fighter->status = member->status;
}
for(uint8_t i = 0; i < config->enemyCount; i++) {
const cutscenestartbattleenemy_t *enemy = &config->enemies[i];
battleAddFighter(
BATTLE_FIGHTER_TEAM_ENEMY, BATTLE_FIGHTER_CONTROLLER_AI,
enemy->stats, enemy->healthMax, enemy->mpMax
);
}
battleStart(config->encounterType, config->fleeAvailable);
sceneSet(SCENE_TYPE_BATTLE);
}
bool_t cutsceneStartBattleUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
if(BATTLE.result == BATTLE_RESULT_NONE) return false;
// Sync ally HP/MP back to the persistent party roster. Relies on
// ally fighters having been added to BATTLE.fighters in the same
// order partyGetOrderMember() iterates, starting at index 0 (see
// cutsceneStartBattleStart).
uint8_t allySlot = 0;
for(uint8_t i = 0; i < PARTY_ACTIVE_SIZE_MAX; i++) {
battlefighter_t *member = partyGetOrderMember(i);
if(member == NULL) continue;
battlefighter_t *fighter = &BATTLE.fighters[allySlot++];
member->health = fighter->health;
member->mp = fighter->mp;
member->status = fighter->status;
}
sceneSet(SCENE_TYPE_OVERWORLD);
battleDispose();
return true;
}
@@ -0,0 +1,53 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "rpg/battle/battle.h"
#define CUTSCENE_START_BATTLE_ENEMY_COUNT_MAX 4
typedef struct {
battlefighterstats_t stats;
uint16_t healthMax;
uint16_t mpMax;
} cutscenestartbattleenemy_t;
typedef struct cutsceneitem_s cutsceneitem_t;
typedef union cutsceneitemdata_u cutsceneitemdata_t;
typedef struct {
battleencountertype_t encounterType;
bool_t fleeAvailable;
uint8_t enemyCount;
cutscenestartbattleenemy_t enemies[CUTSCENE_START_BATTLE_ENEMY_COUNT_MAX];
} cutscenestartbattle_t;
/**
* Starts a battle: seeds BATTLE with the party's active order members
* and the item's configured enemies, then switches to the battle
* scene.
*
* @param item The cutscene item.
* @param data Runtime data storage.
*/
void cutsceneStartBattleStart(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
);
/**
* Waits for the battle to produce a result, syncs ally HP/MP back to
* the party roster, then returns to the overworld scene.
*
* @param item The cutscene item.
* @param data Runtime data storage.
* @returns true once the battle has ended.
*/
bool_t cutsceneStartBattleUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
);
+134 -120
View File
@@ -7,132 +7,146 @@
#include "rpg/cutscene/cutscenesystem.h"
cutsceneitemcallbacks_t CUTSCENE_ITEM_CALLBACKS[CUTSCENE_ITEM_TYPE_COUNT] = {
[CUTSCENE_ITEM_TYPE_NULL] = { 0 },
[CUTSCENE_ITEM_TYPE_TEXT] = {
.init = cutsceneTextStart,
.update = cutsceneTextUpdate
},
[CUTSCENE_ITEM_TYPE_TEXT_MINI] = {
.init = cutsceneTextMiniStart,
.update = cutsceneTextMiniUpdate
},
[CUTSCENE_ITEM_TYPE_TEXT_MINI_HIDE] = {
.init = cutsceneTextMiniHideStart,
.update = cutsceneTextMiniHideUpdate
},
[CUTSCENE_ITEM_TYPE_CALLBACK] = {
.init = cutsceneCallbackStart,
.update = cutsceneCallbackUpdate
},
[CUTSCENE_ITEM_TYPE_WAIT] = {
.init = cutsceneWaitStart,
.update = cutsceneWaitUpdate
},
[CUTSCENE_ITEM_TYPE_CUTSCENE] = {
.init = cutsceneCutsceneStart,
.update = cutsceneCutsceneUpdate
},
[CUTSCENE_ITEM_TYPE_ENTITY_TELEPORT] = {
.init = cutsceneEntityTeleportStart,
.update = cutsceneEntityTeleportUpdate
},
[CUTSCENE_ITEM_TYPE_ENTITY_WALK_TO] = {
.init = cutsceneEntityWalkToStart,
.update = cutsceneEntityWalkToUpdate
},
[CUTSCENE_ITEM_TYPE_FADE] = {
.init = cutsceneFadeStart,
.update = cutsceneFadeUpdate
},
[CUTSCENE_ITEM_TYPE_SET_PAUSE] = {
.init = cutsceneSetPauseStart,
.update = cutsceneSetPauseUpdate
},
[CUTSCENE_ITEM_TYPE_CONCURRENT] = {
.init = cutsceneConcurrentStart,
.update = cutsceneConcurrentUpdate
},
[CUTSCENE_ITEM_TYPE_ITEM_GIVE] = {
.init = cutsceneItemGiveStart,
.update = cutsceneItemGiveUpdate
},
[CUTSCENE_ITEM_TYPE_ENTITY_REMOVE] = {
.init = cutsceneEntityRemoveStart,
.update = cutsceneEntityRemoveUpdate
},
[CUTSCENE_ITEM_TYPE_ENTITY_ADD] = {
.init = cutsceneEntityAddStart,
.update = cutsceneEntityAddUpdate
},
[CUTSCENE_ITEM_TYPE_ENTITY_TURN] = {
.init = cutsceneEntityTurnStart,
.update = cutsceneEntityTurnUpdate
},
[CUTSCENE_ITEM_TYPE_ENTITY_WALK_TO_ENTITY] = {
.init = cutsceneEntityWalkToEntityStart,
.update = cutsceneEntityWalkToEntityUpdate
},
[CUTSCENE_ITEM_TYPE_MAP_AREA_ADD] = {
.init = cutsceneMapAreaAddStart,
.update = cutsceneMapAreaAddUpdate
},
[CUTSCENE_ITEM_TYPE_MAP_AREA_REMOVE] = {
.init = cutsceneMapAreaRemoveStart,
.update = cutsceneMapAreaRemoveUpdate
},
[CUTSCENE_ITEM_TYPE_MAP_AREA_WAIT] = {
.init = cutsceneMapAreaWaitStart,
.update = cutsceneMapAreaWaitUpdate
},
[CUTSCENE_ITEM_TYPE_START_BATTLE] = {
.init = cutsceneStartBattleStart,
.update = cutsceneStartBattleUpdate
},
[CUTSCENE_ITEM_TYPE_EMOJI] = {
.init = cutsceneEmojiStart,
.update = cutsceneEmojiUpdate
},
[CUTSCENE_ITEM_TYPE_SHAKE] = {
.init = cutsceneShakeStart,
.update = cutsceneShakeUpdate
}
};
void cutsceneItemStart(const cutsceneitem_t *item, cutsceneitemdata_t *data) {
switch(item->type) {
case CUTSCENE_ITEM_TYPE_TEXT:
cutsceneTextStart(item, data);
break;
cutsceneiteminitcallback_t *init = CUTSCENE_ITEM_CALLBACKS[item->type].init;
if(init != NULL) init(item, data);
}
case CUTSCENE_ITEM_TYPE_CALLBACK:
cutsceneCallbackStart(item, data);
break;
bool_t cutsceneItemUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
cutsceneitemupdatecallback_t *update =
CUTSCENE_ITEM_CALLBACKS[item->type].update;
if(update == NULL) return false;
case CUTSCENE_ITEM_TYPE_WAIT:
cutsceneWaitStart(item, data);
break;
return update(item, data);
}
case CUTSCENE_ITEM_TYPE_CUTSCENE:
void cutsceneCutsceneStart(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
if(item->cutscene != NULL) cutsceneSystemStartCutscene(item->cutscene);
break;
case CUTSCENE_ITEM_TYPE_ENTITY_TELEPORT:
cutsceneEntityTeleportStart(item, data);
break;
case CUTSCENE_ITEM_TYPE_ENTITY_WALK_TO:
cutsceneEntityWalkToStart(item, data);
break;
case CUTSCENE_ITEM_TYPE_FADE:
cutsceneFadeStart(item, data);
break;
case CUTSCENE_ITEM_TYPE_SET_PAUSE:
cutsceneSetPauseStart(item, data);
break;
case CUTSCENE_ITEM_TYPE_CONCURRENT:
cutsceneConcurrentStart(item, data);
break;
case CUTSCENE_ITEM_TYPE_ITEM_GIVE:
cutsceneItemGiveStart(item, data);
break;
case CUTSCENE_ITEM_TYPE_ENTITY_REMOVE:
cutsceneEntityRemoveStart(item, data);
break;
case CUTSCENE_ITEM_TYPE_ENTITY_ADD:
cutsceneEntityAddStart(item, data);
break;
case CUTSCENE_ITEM_TYPE_ENTITY_TURN:
cutsceneEntityTurnStart(item, data);
break;
case CUTSCENE_ITEM_TYPE_ENTITY_WALK_TO_ENTITY:
cutsceneEntityWalkToEntityStart(item, data);
break;
case CUTSCENE_ITEM_TYPE_MAP_AREA_ADD:
cutsceneMapAreaAddStart(item, data);
break;
case CUTSCENE_ITEM_TYPE_MAP_AREA_REMOVE:
cutsceneMapAreaRemoveStart(item, data);
break;
case CUTSCENE_ITEM_TYPE_MAP_AREA_WAIT:
cutsceneMapAreaWaitStart(item, data);
break;
default:
break;
}
}
bool_t cutsceneItemUpdate(const cutsceneitem_t *item, cutsceneitemdata_t *data) {
switch(item->type) {
case CUTSCENE_ITEM_TYPE_TEXT:
return cutsceneTextUpdate(item, data);
case CUTSCENE_ITEM_TYPE_CALLBACK:
return cutsceneCallbackUpdate(item, data);
case CUTSCENE_ITEM_TYPE_WAIT:
return cutsceneWaitUpdate(item, data);
case CUTSCENE_ITEM_TYPE_ENTITY_TELEPORT:
return cutsceneEntityTeleportUpdate(item, data);
case CUTSCENE_ITEM_TYPE_ENTITY_WALK_TO:
return cutsceneEntityWalkToUpdate(item, data);
case CUTSCENE_ITEM_TYPE_FADE:
return cutsceneFadeUpdate(item, data);
case CUTSCENE_ITEM_TYPE_SET_PAUSE:
return cutsceneSetPauseUpdate(item, data);
case CUTSCENE_ITEM_TYPE_CONCURRENT:
return cutsceneConcurrentUpdate(item, data);
case CUTSCENE_ITEM_TYPE_ITEM_GIVE:
return cutsceneItemGiveUpdate(item, data);
case CUTSCENE_ITEM_TYPE_ENTITY_REMOVE:
return cutsceneEntityRemoveUpdate(item, data);
case CUTSCENE_ITEM_TYPE_ENTITY_ADD:
return cutsceneEntityAddUpdate(item, data);
case CUTSCENE_ITEM_TYPE_ENTITY_TURN:
return cutsceneEntityTurnUpdate(item, data);
case CUTSCENE_ITEM_TYPE_ENTITY_WALK_TO_ENTITY:
return cutsceneEntityWalkToEntityUpdate(item, data);
case CUTSCENE_ITEM_TYPE_MAP_AREA_ADD:
return cutsceneMapAreaAddUpdate(item, data);
case CUTSCENE_ITEM_TYPE_MAP_AREA_REMOVE:
return cutsceneMapAreaRemoveUpdate(item, data);
case CUTSCENE_ITEM_TYPE_MAP_AREA_WAIT:
return cutsceneMapAreaWaitUpdate(item, data);
default:
bool_t cutsceneCutsceneUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
return false;
}
}
+63 -1
View File
@@ -17,17 +17,25 @@
#include "entity/cutsceneentityturn.h"
#include "entity/cutsceneentitywalktoentity.h"
#include "ui/cutscenetext.h"
#include "ui/cutscenetextmini.h"
#include "ui/cutscenetextminihide.h"
#include "ui/cutscenefade.h"
#include "ui/cutsceneemoji.h"
#include "ui/cutsceneshake.h"
#include "item/cutsceneitemgive.h"
#include "maparea/cutscenemapareaadd.h"
#include "maparea/cutscenemaparearemove.h"
#include "maparea/cutscenemapareawait.h"
#include "battle/cutscenestartbattle.h"
typedef struct cutscene_s cutscene_t;
typedef enum {
CUTSCENE_ITEM_TYPE_NULL,
CUTSCENE_ITEM_TYPE_TEXT,
CUTSCENE_ITEM_TYPE_TEXT_MINI,
CUTSCENE_ITEM_TYPE_TEXT_MINI_HIDE,
CUTSCENE_ITEM_TYPE_CALLBACK,
CUTSCENE_ITEM_TYPE_WAIT,
CUTSCENE_ITEM_TYPE_CUTSCENE,
@@ -43,7 +51,12 @@ typedef enum {
CUTSCENE_ITEM_TYPE_ENTITY_WALK_TO_ENTITY,
CUTSCENE_ITEM_TYPE_MAP_AREA_ADD,
CUTSCENE_ITEM_TYPE_MAP_AREA_REMOVE,
CUTSCENE_ITEM_TYPE_MAP_AREA_WAIT
CUTSCENE_ITEM_TYPE_MAP_AREA_WAIT,
CUTSCENE_ITEM_TYPE_START_BATTLE,
CUTSCENE_ITEM_TYPE_EMOJI,
CUTSCENE_ITEM_TYPE_SHAKE,
CUTSCENE_ITEM_TYPE_COUNT
} cutsceneitemtype_t;
struct cutsceneitem_s {
@@ -51,6 +64,8 @@ struct cutsceneitem_s {
union {
cutscenetext_t text;
cutscenetextmini_t textMini;
cutscenetextminihide_t textMiniHide;
cutscenecallback_t callback;
cutscenewait_t wait;
const cutscene_t *cutscene;
@@ -67,6 +82,9 @@ struct cutsceneitem_s {
cutscenemapareaadd_t mapAreaAdd;
cutscenemaparearemove_t mapAreaRemove;
cutscenemapareawait_t mapAreaWait;
cutscenestartbattle_t startBattle;
cutsceneemoji_t emoji;
cutsceneshake_t shake;
};
};
@@ -77,6 +95,24 @@ typedef union cutsceneitemdata_u {
cutscenemapareawaitdata_t mapAreaWait;
} cutsceneitemdata_t;
typedef void (cutsceneiteminitcallback_t)(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
);
typedef bool_t (cutsceneitemupdatecallback_t)(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
);
typedef struct {
cutsceneiteminitcallback_t *init;
cutsceneitemupdatecallback_t *update;
} cutsceneitemcallbacks_t;
extern cutsceneitemcallbacks_t
CUTSCENE_ITEM_CALLBACKS[CUTSCENE_ITEM_TYPE_COUNT];
/**
* Start the given cutscene item.
*
@@ -99,3 +135,29 @@ bool_t cutsceneItemUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
);
/**
* Starts a nested-cutscene item, handing control over to the
* referenced cutscene.
*
* @param item The cutscene item.
* @param data Runtime data storage.
*/
void cutsceneCutsceneStart(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
);
/**
* Updates a nested-cutscene item. By the time this would run, control
* has already moved on to the referenced cutscene, so this always
* reports incomplete.
*
* @param item The cutscene item.
* @param data Runtime data storage.
* @returns false always.
*/
bool_t cutsceneCutsceneUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
);
@@ -9,7 +9,7 @@
#include "rpg/cutscene/cutscenesystem.h"
#include "rpg/entity/entity.h"
#include "rpg/entity/entitypathstep.h"
#include "rpg/overworld/map.h"
#include "rpg/overworld/chunk.h"
void cutsceneEntityWalkToEntityStart(
const cutsceneitem_t *item,
@@ -35,7 +35,7 @@ bool_t cutsceneEntityWalkToEntityUpdate(
};
worldunit_t z;
if(mapGetWalkableZNear(dest.x, dest.y, target->position.z, &z)) dest.z = z;
if(chunkGetWalkableZNear(dest.x, dest.y, target->position.z, &z)) dest.z = z;
return entityPathStep(entity, dest, true);
}
@@ -6,14 +6,16 @@
*/
#include "rpg/cutscene/item/cutsceneitem.h"
#include "rpg/item/item.h"
#include "rpg/item/itemgive.h"
#include "ui/rpg/uitextboxmain.h"
#include "ui/rpg/textbox/uitextboxmain.h"
void cutsceneItemGiveStart(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
itemGive(item->itemGive.item, item->itemGive.quantity);
itemid_t itemId = itemGetIdByName(item->itemGive.itemName);
itemGive(itemId, item->itemGive.quantity);
}
bool_t cutsceneItemGiveUpdate(
@@ -6,13 +6,13 @@
*/
#pragma once
#include "rpg/item/item.h"
#include "dusk.h"
typedef struct cutsceneitem_s cutsceneitem_t;
typedef union cutsceneitemdata_u cutsceneitemdata_t;
typedef struct {
itemid_t item;
const char_t *itemName;
uint8_t quantity;
} cutsceneitemgive_t;
@@ -6,5 +6,9 @@
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
cutscenetext.c
cutscenetextmini.c
cutscenetextminihide.c
cutscenefade.c
cutsceneemoji.c
cutsceneshake.c
)
@@ -0,0 +1,25 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "rpg/cutscene/item/cutsceneitem.h"
#include "rpg/cutscene/cutscenesystem.h"
#include "rpg/entity/entity.h"
void cutsceneEmojiStart(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
entity_t *entity = cutsceneSystemGetEntity(item->emoji.entityIndex);
uiEmojiAdd(entity->id, item->emoji.duration, item->emoji.emojiType);
}
bool_t cutsceneEmojiUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
return true;
}
@@ -0,0 +1,43 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "dusk.h"
#include "ui/rpg/uiemoji.h"
typedef struct cutsceneitem_s cutsceneitem_t;
typedef union cutsceneitemdata_u cutsceneitemdata_t;
typedef struct {
uint8_t entityIndex;
float_t duration;
uiemojitype_t emojiType;
} cutsceneemoji_t;
/**
* Starts an emoji step (shows an emoji above the entity for the given
* duration, then completes immediately).
*
* @param item The cutscene item.
* @param data Runtime data storage.
*/
void cutsceneEmojiStart(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
);
/**
* Updates an emoji step (always completes immediately).
*
* @param item The cutscene item.
* @param data Runtime data storage.
* @returns true always.
*/
bool_t cutsceneEmojiUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
);
@@ -0,0 +1,23 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "rpg/cutscene/item/cutsceneitem.h"
#include "rpg/rpgcamera.h"
void cutsceneShakeStart(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
rpgCameraShake(item->shake.amount, item->shake.duration);
}
bool_t cutsceneShakeUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
return true;
}
@@ -0,0 +1,41 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "dusk.h"
typedef struct cutsceneitem_s cutsceneitem_t;
typedef union cutsceneitemdata_u cutsceneitemdata_t;
typedef struct {
uint8_t amount;
float_t duration;
} cutsceneshake_t;
/**
* Starts a camera shake item (kicks off the shake on the RPG camera).
*
* @param item The cutscene item.
* @param data Runtime data storage.
*/
void cutsceneShakeStart(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
);
/**
* Updates a camera shake item. The shake itself runs asynchronously on
* the RPG camera, so this always completes immediately.
*
* @param item The cutscene item.
* @param data Runtime data storage.
* @returns true always.
*/
bool_t cutsceneShakeUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
);
+1 -1
View File
@@ -6,7 +6,7 @@
*/
#include "rpg/cutscene/item/cutsceneitem.h"
#include "ui/rpg/uitextboxmain.h"
#include "ui/rpg/textbox/uitextboxmain.h"
void cutsceneTextStart(
const cutsceneitem_t *item,
@@ -0,0 +1,33 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "rpg/cutscene/item/cutsceneitem.h"
#include "rpg/cutscene/cutscenesystem.h"
#include "ui/rpg/textbox/uitextboxminilist.h"
void cutsceneTextMiniStart(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
uint8_t index = uiTextboxMiniListGetNext();
uiTextboxMiniShow(
&UI_TEXTBOX_MINI_LIST[index],
item->textMini.text,
item->textMini.position,
item->textMini.duration,
NULL,
NULL
);
CUTSCENE_SYSTEM.textMiniLastCreated = index;
}
bool_t cutsceneTextMiniUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
return true;
}
@@ -0,0 +1,44 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "dusk.h"
typedef struct cutsceneitem_s cutsceneitem_t;
typedef union cutsceneitemdata_u cutsceneitemdata_t;
#define CUTSCENE_TEXT_MINI_MAX_CHARS 128
typedef struct {
char_t text[CUTSCENE_TEXT_MINI_MAX_CHARS];
vec3 position;
float_t duration;
} cutscenetextmini_t;
/**
* Starts a mini text item (shows a mini textbox at the given world
* position for the given duration, then completes immediately).
*
* @param item The cutscene item.
* @param data Runtime data storage.
*/
void cutsceneTextMiniStart(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
);
/**
* Updates a mini text item (always completes immediately).
*
* @param item The cutscene item.
* @param data Runtime data storage.
* @returns true always.
*/
bool_t cutsceneTextMiniUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
);
@@ -0,0 +1,25 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "rpg/cutscene/item/cutsceneitem.h"
#include "rpg/cutscene/cutscenesystem.h"
#include "ui/rpg/textbox/uitextboxminilist.h"
void cutsceneTextMiniHideStart(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
uint8_t index = cutsceneSystemGetTextMiniId(item->textMiniHide.index);
uiTextboxMiniClose(&UI_TEXTBOX_MINI_LIST[index]);
}
bool_t cutsceneTextMiniHideUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
return true;
}
@@ -0,0 +1,39 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "dusk.h"
typedef struct cutsceneitem_s cutsceneitem_t;
typedef union cutsceneitemdata_u cutsceneitemdata_t;
typedef struct {
uint8_t index;
} cutscenetextminihide_t;
/**
* Starts a mini text hide step (closes the mini textbox immediately).
*
* @param item The cutscene item.
* @param data Runtime data storage.
*/
void cutsceneTextMiniHideStart(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
);
/**
* Updates a mini text hide step (always completes immediately).
*
* @param item The cutscene item.
* @param data Runtime data storage.
* @returns true always.
*/
bool_t cutsceneTextMiniHideUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
);
@@ -12,16 +12,3 @@
CUTSCENE(TEST_ONE, 0, DEFAULT,
CUTSCENE_TEXT("Test One."),
);
CUTSCENE(TEST_TWO, 0, DEFAULT,
CUTSCENE_TEXT("Test Two."),
CUTSCENE_ENTITY_ADD(ENTITY_TYPE_NPC, 4, 4, 0),
CUTSCENE_ENTITY_WALK_TO(CUTSCENE_ENTITY_LAST_CREATED, 8, 2, 0),
// CUTSCENE_CONCURRENT(
// CUTSCENE_ENTITY_WALK_TO(CUTSCENE_ENTITY_INTERACT, 4, 4, 0),
// CUTSCENE_ENTITY_WALK_TO(CUTSCENE_ENTITY_INTERACTED, 8, 2, 0),
// ),
// CUTSCENE_ITEM_GIVE(ITEM_ID_POTATO, 3),
// CUTSCENE_ENTITY_REMOVE(CUTSCENE_ENTITY_INTERACT),
CUTSCENE_TEXT("Done."),
);
-1
View File
@@ -16,4 +16,3 @@ add_subdirectory(anim)
add_subdirectory(interact)
add_subdirectory(npc)
add_subdirectory(item)
add_subdirectory(global)
+2 -2
View File
@@ -6,7 +6,7 @@
*/
#include "rpg/entity/entity.h"
#include "rpg/overworld/map.h"
#include "rpg/overworld/chunk.h"
#include "rpg/overworld/tile.h"
#include "time/time.h"
#include "entityanimwalk.h"
@@ -19,7 +19,7 @@ const entityanimcallback_t ENTITY_ANIM_CALLBACKS[ENTITY_ANIM_COUNT] = {
};
float_t entityAnimTileZOffset(const worldpos_t pos) {
return tileShapeIsRamp(mapGetTile(pos).shape) ? 0.5f : 0.0f;
return tileShapeIsRamp(chunkGetTile(pos).shape) ? 0.5f : 0.0f;
}
void entityAnimUpdate(entity_t *entity) {
+163 -8
View File
@@ -8,12 +8,14 @@
#include "entity.h"
#include "assert/assert.h"
#include "util/memory.h"
#include "util/string.h"
#include "time/time.h"
#include "util/math.h"
#include "rpg/overworld/map.h"
#include "rpg/overworld/maparea.h"
#include "rpg/overworld/chunk.h"
#include "rpg/overworld/tile.h"
#include "rpg/cutscene/cutscene.h"
#include "yyjson.h"
entity_t ENTITIES[ENTITY_COUNT];
@@ -88,8 +90,8 @@ void entityWalk(entity_t *entity, const entitydir_t direction) {
}
// Get tile under foot
tile_t tileCurrent = mapGetTile(entity->position);
tile_t tileNew = mapGetTile(newPos);
tile_t tileCurrent = chunkGetTile(entity->position);
tile_t tileNew = chunkGetTile(newPos);
bool_t fall = false;
bool_t raise = false;
@@ -138,7 +140,7 @@ void entityWalk(entity_t *entity, const entitydir_t direction) {
tileNew = TILE_NULL;
worldpos_t abovePos = newPos;
abovePos.z += 1;
tile_t tileAbove = mapGetTile(abovePos);
tile_t tileAbove = chunkGetTile(abovePos);
if(
tileAbove.shape != TILE_SHAPE_NULL &&
@@ -152,7 +154,7 @@ void entityWalk(entity_t *entity, const entitydir_t direction) {
// Falling down?
worldpos_t belowPos = newPos;
belowPos.z -= 1;
tile_t tileBelow = mapGetTile(belowPos);
tile_t tileBelow = chunkGetTile(belowPos);
if(
tileBelow.shape != TILE_SHAPE_NULL &&
tileShapeIsRamp(tileBelow.shape) &&
@@ -282,7 +284,7 @@ void entitySetChunk(entity_t *entity, const uint8_t chunkIndex) {
assertNotNull(entity, "Entity pointer cannot be NULL");
if(entity->chunkIndex != 0xFF) {
chunk_t *old = mapGetChunk(entity->chunkIndex);
chunk_t *old = chunkGet(entity->chunkIndex);
if(old != NULL) {
for(uint8_t i = 0; i < CHUNK_ENTITY_COUNT_MAX; i++) {
if(old->entities[i] != entity->id) continue;
@@ -295,7 +297,7 @@ void entitySetChunk(entity_t *entity, const uint8_t chunkIndex) {
entity->chunkIndex = chunkIndex;
if(chunkIndex != 0xFF) {
chunk_t *next = mapGetChunk(chunkIndex);
chunk_t *next = chunkGet(chunkIndex);
if(next != NULL) {
for(uint8_t i = 0; i < CHUNK_ENTITY_COUNT_MAX; i++) {
if(next->entities[i] != 0xFF) continue;
@@ -311,6 +313,159 @@ void entityUpdateChunk(entity_t *entity) {
chunkpos_t cp;
worldPosToChunkPos(&entity->position, &cp);
chunkindex_t ci = mapGetChunkIndexAt(cp);
chunkindex_t ci = chunkGetIndexAt(cp);
if(ci != -1) entitySetChunk(entity, (uint8_t)ci);
}
errorret_t entityCreateFromJson(yyjson_val *obj, entity_t **outEntity) {
assertNotNull(obj, "Entity JSON object cannot be NULL");
assertNotNull(outEntity, "Output entity pointer cannot be NULL");
yyjson_val *typeVal = yyjson_obj_get(obj, "type");
if(!typeVal || !yyjson_is_str(typeVal)) {
errorThrow("Entity JSON missing 'type' string");
}
const char_t *typeStr = yyjson_get_str(typeVal);
entitytype_t type;
if(stringEquals(typeStr, "player")) {
type = ENTITY_TYPE_PLAYER;
} else if(stringEquals(typeStr, "npc")) {
type = ENTITY_TYPE_NPC;
} else if(stringEquals(typeStr, "item")) {
type = ENTITY_TYPE_ITEM;
} else {
errorThrow("Entity JSON has unknown 'type': %s", typeStr);
}
yyjson_val *posVal = yyjson_obj_get(obj, "position");
if(!posVal || !yyjson_is_arr(posVal) || yyjson_arr_size(posVal) != 3) {
errorThrow("Entity JSON missing 'position' [x, y, z] array");
}
worldunit_t pos[3];
size_t posIdx, posLen;
yyjson_val *posElem;
yyjson_arr_foreach(posVal, posIdx, posLen, posElem) {
if(!yyjson_is_num(posElem)) {
errorThrow("Entity JSON 'position' elements must be numbers");
}
pos[posIdx] = (worldunit_t)yyjson_get_num(posElem);
}
entitydir_t direction = ENTITY_DIR_SOUTH;
yyjson_val *dirVal = yyjson_obj_get(obj, "direction");
if(dirVal && yyjson_is_str(dirVal)) {
const char_t *dirStr = yyjson_get_str(dirVal);
if(stringEquals(dirStr, "north")) {
direction = ENTITY_DIR_NORTH;
} else if(stringEquals(dirStr, "east")) {
direction = ENTITY_DIR_EAST;
} else if(stringEquals(dirStr, "south")) {
direction = ENTITY_DIR_SOUTH;
} else if(stringEquals(dirStr, "west")) {
direction = ENTITY_DIR_WEST;
} else {
errorThrow("Entity JSON has unknown 'direction': %s", dirStr);
}
}
// Item entities require a valid item reference, resolved up front so a
// bad reference fails before an entity slot is ever claimed.
itemid_t itemId = ITEM_ID_NULL;
uint8_t itemQuantity = 1;
if(type == ENTITY_TYPE_ITEM) {
yyjson_val *itemVal = yyjson_obj_get(obj, "item");
if(!itemVal || !yyjson_is_str(itemVal)) {
errorThrow("Entity JSON with type 'item' missing 'item' string");
}
const char_t *itemStr = yyjson_get_str(itemVal);
itemId = itemGetIdByName(itemStr);
if(itemId == ITEM_ID_NULL) {
errorThrow("Entity JSON references unknown item '%s'", itemStr);
}
yyjson_val *quantityVal = yyjson_obj_get(obj, "quantity");
if(quantityVal && yyjson_is_int(quantityVal)) {
itemQuantity = (uint8_t)yyjson_get_int(quantityVal);
}
}
// Only one player may exist at a time - it always holds the reserved
// ENTITY_GLOBAL_ID_PLAYER global ID, so that's how callers (e.g. the
// camera) find it regardless of how it was spawned.
if(
type == ENTITY_TYPE_PLAYER &&
entityGetByGlobalId(ENTITY_GLOBAL_ID_PLAYER) != NULL
) {
errorThrow("A player entity has already been spawned");
}
// NPC path waypoints, resolved up front for the same reason as above.
worldpos_t path[NPC_PATH_COUNT_MAX];
uint8_t pathCount = 0;
if(type == ENTITY_TYPE_NPC) {
yyjson_val *pathVal = yyjson_obj_get(obj, "path");
if(pathVal) {
if(!yyjson_is_arr(pathVal)) {
errorThrow("Entity JSON 'path' must be an array");
}
size_t count = yyjson_arr_size(pathVal);
if(count == 0 || count > NPC_PATH_COUNT_MAX) {
errorThrow(
"Entity JSON 'path' must have 1-%d waypoints", NPC_PATH_COUNT_MAX
);
}
size_t pathIdx, pathLen;
yyjson_val *pathElem;
yyjson_arr_foreach(pathVal, pathIdx, pathLen, pathElem) {
if(!yyjson_is_arr(pathElem) || yyjson_arr_size(pathElem) != 3) {
errorThrow("Entity JSON 'path' entries must be [x, y, z] arrays");
}
worldunit_t comps[3];
size_t compIdx, compLen;
yyjson_val *compElem;
yyjson_arr_foreach(pathElem, compIdx, compLen, compElem) {
if(!yyjson_is_num(compElem)) {
errorThrow("Entity JSON 'path' elements must be numbers");
}
comps[compIdx] = (worldunit_t)yyjson_get_num(compElem);
}
path[pathIdx] = (worldpos_t){ comps[0], comps[1], comps[2] };
}
pathCount = (uint8_t)count;
}
}
// Interact cutscene, resolved up front for the same reason as above.
const cutscene_t *cutscene = NULL;
yyjson_val *cutsceneVal = yyjson_obj_get(obj, "cutscene");
if(cutsceneVal) {
if(!yyjson_is_str(cutsceneVal)) {
errorThrow("Entity JSON 'cutscene' must be a string");
}
errorChain(cutsceneGetByName(yyjson_get_str(cutsceneVal), &cutscene));
}
uint8_t index = entityGetAvailable();
if(index == 0xFF) errorThrow("No available entity slots");
entity_t *entity = &ENTITIES[index];
entityInit(entity, type);
entity->direction = direction;
entityPositionSet(entity, (worldpos_t){ pos[0], pos[1], pos[2] });
if(type == ENTITY_TYPE_ITEM) entityItemSet(entity, itemId, itemQuantity);
if(pathCount > 0) {
npcSetMoveType(entity, NPC_MOVE_TYPE_PATH);
for(uint8_t i = 0; i < pathCount; i++) {
npcPathAddNode(&entity->data.npc, path[i]);
}
}
if(cutscene != NULL) {
entity->interact.type = ENTITY_INTERACT_CUTSCENE;
entity->interact.data.cutscene = cutscene;
}
*outEntity = entity;
errorOk();
}
+39
View File
@@ -13,6 +13,7 @@
#include "npc/npc.h"
typedef struct map_s map_t;
typedef struct yyjson_val yyjson_val;
typedef uint16_t entityglobalid_t;
@@ -165,3 +166,41 @@ void entityUpdateChunk(entity_t *entity);
* @param pos The world position to place the entity at.
*/
void entityPositionSet(entity_t *entity, const worldpos_t pos);
/**
* Parses an entity descriptor from a yyjson object and spawns it as a new
* entity in an available slot. Expected shape:
* { "type": "npc", "position": [x, y, z], "direction": "south" }
* "type" must be one of "player", "npc", "item". "direction" is optional
* (one of "north", "east", "south", "west") and defaults to
* ENTITY_DIR_SOUTH when absent.
*
* When "type" is "item", two extra fields apply:
* { "type": "item", "position": [x, y, z], "item": "POTION",
* "quantity": 1 }
* "item" (required) is the item's string ID, resolved via
* itemGetIdByName. "quantity" (optional) defaults to 1.
*
* When "type" is "player", the spawned entity is assigned the reserved
* ENTITY_GLOBAL_ID_PLAYER global ID (so entityGetByGlobalId can find it
* regardless of how it was spawned), and it is an error to spawn a
* second one while one is already loaded.
*
* When "type" is "npc", an optional "path" field sets it up with
* NPC_MOVE_TYPE_PATH movement:
* { "type": "npc", "position": [x, y, z],
* "path": [[4, 4, 0], [10, 10, 1]] }
* "path" must have 1-NPC_PATH_COUNT_MAX waypoints.
*
* Any entity type may set an optional "cutscene" field to wire up an
* interact component that starts the named cutscene (resolved via
* cutsceneGetByName) when interacted with:
* { "type": "npc", "position": [x, y, z], "cutscene": "test_npc" }
*
* @param obj The yyjson object describing the entity.
* @param outEntity Output pointer, set to the newly spawned entity on
* success.
* @return Any error that occurs (missing/invalid fields, unknown item,
* duplicate player, unknown/malformed cutscene, no free slots).
*/
errorret_t entityCreateFromJson(yyjson_val *obj, entity_t **outEntity);
-17
View File
@@ -1,17 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "entityglobaldefs.h"
#include "entitygloballist.h"
#define ENTITY_GLOBAL_LIST_COUNT ( \
sizeof(ENTITY_GLOBAL_LIST) / \
sizeof(ENTITY_GLOBAL_LIST[0]) \
)
//EOF
@@ -1,44 +0,0 @@
/**
* 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 "rpg/overworld/worldpos.h"
#include "rpg/entity/entity.h"
typedef struct entity_s entity_t;
typedef struct {
entity_t *entity;
worldpos_t position;
} entityglobalcreate_t;
/**
* Callback invoked to initialize a global entity.
*
* @param create Pointer to the entity/position being initialized.
* @returns An error code.
*/
typedef void (*entityglobalinitcallback_t)(
entityglobalcreate_t *create
);
typedef struct {
entitytype_t type;
entityglobalinitcallback_t callback;
} entityglobaldef_t;
#define ENTITY_GLOBAL(id, entType, callbackFn) \
[id] = { .type = entType, .callback = callbackFn }
#define ENTITY_GLOBAL_CALLBACK(id) \
static void ENTTIYT_GLOBAL_CALLBACK_##id(entityglobalcreate_t *create)
#define ENTITY_GLOBAL_REF(id) \
ENTTIYT_GLOBAL_CALLBACK_##id
//EOF
@@ -1,30 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "entityglobaldefs.h"
#include "rpg/cutscene/scene/testcutscene.h"
ENTITY_GLOBAL_CALLBACK(3) {
create->entity->data.npc.moveType = NPC_MOVE_TYPE_PATH;
npcPathAddNode(&create->entity->data.npc, (worldpos_t){ 4, 4, 0 });
npcPathAddNode(&create->entity->data.npc, (worldpos_t){ 10, 10, 1 });
npcPathAddNode(&create->entity->data.npc, (worldpos_t){ 4, 4, 0 });
npcPathAddNode(&create->entity->data.npc, (worldpos_t){ 10, 10, 1 });
create->entity->interact.type = ENTITY_INTERACT_CUTSCENE;
create->entity->interact.data.cutscene = CUTSCENE_REFERENCE(TEST_TWO);
}
static const entityglobaldef_t ENTITY_GLOBAL_LIST[] = {
ENTITY_GLOBAL(ENTITY_GLOBAL_ID_NULL, ENTITY_TYPE_NULL, NULL),
ENTITY_GLOBAL(ENTITY_GLOBAL_ID_PLAYER, ENTITY_TYPE_PLAYER, NULL),
ENTITY_GLOBAL(3, ENTITY_TYPE_NPC, ENTITY_GLOBAL_REF(3)),
};
//EOF
@@ -8,7 +8,7 @@
#include "rpg/entity/entity.h"
#include "assert/assert.h"
#include "rpg/cutscene/cutscenesystem.h"
#include "ui/rpg/uitextboxmain.h"
#include "ui/rpg/textbox/uitextboxmain.h"
void entityInteractWith(entity_t *player, entity_t *target) {
assertNotNull(player, "Player entity pointer cannot be NULL");
+1 -1
View File
@@ -9,7 +9,7 @@
#include "rpg/entity/entity.h"
#include "assert/assert.h"
#include "rpg/item/itemgive.h"
#include "ui/rpg/uitextboxmain.h"
#include "ui/rpg/textbox/uitextboxmain.h"
void entityItemInit(entity_t *entity) {
assertNotNull(entity, "Entity pointer cannot be NULL");
+1 -9
View File
@@ -6,16 +6,8 @@
# Sources
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
item.c
inventory.c
backpack.c
itemgive.c
)
# Item Definitions
dusk_run_python(
dusk_item_csv_defs
tools.item
--csv ${CMAKE_CURRENT_SOURCE_DIR}/item.csv
--output ${DUSK_GENERATED_HEADERS_DIR}/rpg/item/item.h
)
add_dependencies(${DUSK_LIBRARY_TARGET_NAME} dusk_item_csv_defs)
+14 -14
View File
@@ -11,69 +11,69 @@
backpack_t BACKPACK;
void backpackInit() {
for(uint8_t i = 0; i < ITEM_TYPE_COUNT; i++) {
for(uint32_t i = 0; i < ITEM_TYPE_COUNT_MAX; i++) {
inventoryInit(
&BACKPACK.inventories[i],
BACKPACK.storage[i],
ITEM_TYPE_COUNT_MAX
INVENTORY_CAPACITY_MAX
);
}
}
inventory_t *backpackGetInventory(const itemtype_t type) {
inventory_t *backpackGetInventory(const itemtypeid_t type) {
assertTrue(type > ITEM_TYPE_NULL, "Item type must not be null");
assertTrue(type < ITEM_TYPE_COUNT, "Item type out of range");
assertTrue(type <= ITEM_TYPE_COUNT, "Item type out of range");
return &BACKPACK.inventories[type];
}
void backpackAdd(const itemid_t item, const uint8_t quantity) {
assertTrue(item > ITEM_ID_NULL, "Item ID must not be null");
assertTrue(item < ITEM_ID_COUNT, "Item ID out of range");
assertTrue(item <= ITEM_COUNT, "Item ID out of range");
inventoryAdd(backpackGetInventory(ITEMS[item].type), item, quantity);
}
void backpackRemove(const itemid_t item) {
assertTrue(item > ITEM_ID_NULL, "Item ID must not be null");
assertTrue(item < ITEM_ID_COUNT, "Item ID out of range");
assertTrue(item <= ITEM_COUNT, "Item ID out of range");
inventoryRemove(backpackGetInventory(ITEMS[item].type), item);
}
void backpackSet(const itemid_t item, const uint8_t quantity) {
assertTrue(item > ITEM_ID_NULL, "Item ID must not be null");
assertTrue(item < ITEM_ID_COUNT, "Item ID out of range");
assertTrue(item <= ITEM_COUNT, "Item ID out of range");
inventorySet(backpackGetInventory(ITEMS[item].type), item, quantity);
}
uint8_t backpackGetCount(const itemid_t item) {
assertTrue(item > ITEM_ID_NULL, "Item ID must not be null");
assertTrue(item < ITEM_ID_COUNT, "Item ID out of range");
assertTrue(item <= ITEM_COUNT, "Item ID out of range");
return inventoryGetCount(backpackGetInventory(ITEMS[item].type), item);
}
bool_t backpackItemExists(const itemid_t item) {
assertTrue(item > ITEM_ID_NULL, "Item ID must not be null");
assertTrue(item < ITEM_ID_COUNT, "Item ID out of range");
assertTrue(item <= ITEM_COUNT, "Item ID out of range");
return inventoryItemExists(backpackGetInventory(ITEMS[item].type), item);
}
bool_t backpackIsFull(const itemtype_t type) {
bool_t backpackIsFull(const itemtypeid_t type) {
assertTrue(type > ITEM_TYPE_NULL, "Item type must not be null");
assertTrue(type < ITEM_TYPE_COUNT, "Item type out of range");
assertTrue(type <= ITEM_TYPE_COUNT, "Item type out of range");
return inventoryIsFull(backpackGetInventory(type));
}
bool_t backpackItemFull(const itemid_t item) {
assertTrue(item > ITEM_ID_NULL, "Item ID must not be null");
assertTrue(item < ITEM_ID_COUNT, "Item ID out of range");
assertTrue(item <= ITEM_COUNT, "Item ID out of range");
return inventoryItemFull(backpackGetInventory(ITEMS[item].type), item);
}
void backpackSort(
const itemtype_t type,
const itemtypeid_t type,
const inventorysort_t sortBy,
const bool_t reverse
) {
assertTrue(type > ITEM_TYPE_NULL, "Item type must not be null");
assertTrue(type < ITEM_TYPE_COUNT, "Item type out of range");
assertTrue(type <= ITEM_TYPE_COUNT, "Item type out of range");
inventorySort(backpackGetInventory(type), sortBy, reverse);
}
+5 -5
View File
@@ -9,8 +9,8 @@
#include "inventory.h"
typedef struct {
inventorystack_t storage[ITEM_TYPE_COUNT][ITEM_TYPE_COUNT_MAX];
inventory_t inventories[ITEM_TYPE_COUNT];
inventorystack_t storage[ITEM_TYPE_COUNT_MAX][INVENTORY_CAPACITY_MAX];
inventory_t inventories[ITEM_TYPE_COUNT_MAX];
} backpack_t;
extern backpack_t BACKPACK;
@@ -26,7 +26,7 @@ void backpackInit();
* @param type The item type.
* @returns Pointer to the inventory for that type.
*/
inventory_t *backpackGetInventory(const itemtype_t type);
inventory_t *backpackGetInventory(const itemtypeid_t type);
/**
* Adds a quantity of an item to the backpack.
@@ -73,7 +73,7 @@ bool_t backpackItemExists(const itemid_t item);
* @param type The item type to check.
* @returns true if the type's inventory is full.
*/
bool_t backpackIsFull(const itemtype_t type);
bool_t backpackIsFull(const itemtypeid_t type);
/**
* Checks if an item's stack is full in the backpack.
@@ -91,7 +91,7 @@ bool_t backpackItemFull(const itemid_t item);
* @param reverse Whether to sort in reverse order.
*/
void backpackSort(
const itemtype_t type,
const itemtypeid_t type,
const inventorysort_t sortBy,
const bool_t reverse
);
+4 -4
View File
@@ -188,8 +188,8 @@ int_t inventorySortByIdReverse(const void *a, const void *b) {
int_t inventorySortByType(const void *a, const void *b) {
const inventorystack_t *stackA = (const inventorystack_t*)a;
const inventorystack_t *stackB = (const inventorystack_t*)b;
const itemtype_t typeA = ITEMS[stackA->item].type;
const itemtype_t typeB = ITEMS[stackB->item].type;
const itemtypeid_t typeA = ITEMS[stackA->item].type;
const itemtypeid_t typeB = ITEMS[stackB->item].type;
if(typeA < typeB) return -1;
if(typeA > typeB) return 1;
return 0;
@@ -198,8 +198,8 @@ int_t inventorySortByType(const void *a, const void *b) {
int_t inventorySortByTypeReverse(const void *a, const void *b) {
const inventorystack_t *stackA = (const inventorystack_t*)a;
const inventorystack_t *stackB = (const inventorystack_t*)b;
const itemtype_t typeA = ITEMS[stackA->item].type;
const itemtype_t typeB = ITEMS[stackB->item].type;
const itemtypeid_t typeA = ITEMS[stackA->item].type;
const itemtypeid_t typeB = ITEMS[stackB->item].type;
if(typeA < typeB) return 1;
if(typeA > typeB) return -1;
return 0;
+1
View File
@@ -9,6 +9,7 @@
#include "rpg/item/item.h"
#define ITEM_STACK_QUANTITY_MAX 99
#define INVENTORY_CAPACITY_MAX 250
typedef enum {
INVENTORY_SORT_BY_ID,
+161
View File
@@ -0,0 +1,161 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "item.h"
#include "assert/assert.h"
#include "util/memory.h"
#include "util/string.h"
#include "asset/asset.h"
#include "asset/loader/assetentry.h"
#include "asset/loader/json/assetjsonloader.h"
#include "locale/localemanager.h"
#include "asset/loader/locale/assetlocaleloader.h"
#include "yyjson.h"
#define ITEM_JSON_PATH "item.json"
itemdef_t ITEMS[ITEM_COUNT_MAX];
uint32_t ITEM_COUNT;
itemtype_t ITEM_TYPES[ITEM_TYPE_COUNT_MAX];
uint32_t ITEM_TYPE_COUNT;
errorret_t itemInit(void) {
memoryZero(ITEMS, sizeof(ITEMS));
memoryZero(ITEM_TYPES, sizeof(ITEM_TYPES));
ITEM_COUNT = 0;
ITEM_TYPE_COUNT = 0;
assetentry_t *jsonEntry = assetLock(
ITEM_JSON_PATH, ASSET_LOADER_TYPE_JSON, NULL
);
errorret_t ret = assetRequireLoaded(jsonEntry);
if(errorIsNotOk(ret)) {
assetUnlockEntry(jsonEntry);
errorChain(ret);
}
yyjson_val *root = yyjson_doc_get_root(jsonEntry->data.json);
if(!yyjson_is_arr(root)) {
assetUnlockEntry(jsonEntry);
errorThrow("item.json root must be an array");
}
size_t idx, max;
yyjson_val *entry;
yyjson_arr_foreach(root, idx, max, entry) {
if(ITEM_COUNT >= ITEM_COUNT_MAX - 1) {
assetUnlockEntry(jsonEntry);
errorThrow(
"Too many items defined: exceeds ITEM_COUNT_MAX (%d)",
ITEM_COUNT_MAX
);
}
yyjson_val *idVal = yyjson_obj_get(entry, "id");
yyjson_val *typeVal = yyjson_obj_get(entry, "type");
yyjson_val *nameVal = yyjson_obj_get(entry, "name");
yyjson_val *weightVal = yyjson_obj_get(entry, "weight");
if(!idVal || !yyjson_is_str(idVal)) {
assetUnlockEntry(jsonEntry);
errorThrow("Item entry %zu missing 'id' string", idx);
}
if(!typeVal || !yyjson_is_str(typeVal)) {
assetUnlockEntry(jsonEntry);
errorThrow("Item entry %zu missing 'type' string", idx);
}
if(!nameVal || !yyjson_is_str(nameVal)) {
assetUnlockEntry(jsonEntry);
errorThrow("Item entry %zu missing 'name' string", idx);
}
const char_t *idStr = yyjson_get_str(idVal);
size_t idLen = yyjson_get_len(idVal);
const char_t *typeStr = yyjson_get_str(typeVal);
size_t typeLen = yyjson_get_len(typeVal);
const char_t *nameStr = yyjson_get_str(nameVal);
size_t nameLen = yyjson_get_len(nameVal);
if(idLen >= ITEM_STRING_MAX) {
assetUnlockEntry(jsonEntry);
errorThrow("Item id '%s' exceeds max length", idStr);
}
if(nameLen + 10 >= ITEM_STRING_MAX) {
assetUnlockEntry(jsonEntry);
errorThrow("Item name '%s' exceeds max length", nameStr);
}
if(typeLen >= ITEM_STRING_MAX) {
assetUnlockEntry(jsonEntry);
errorThrow("Item type '%s' exceeds max length", typeStr);
}
itemtypeid_t typeId = itemResolveType(typeStr, typeLen);
if(typeId == ITEM_TYPE_NULL) {
assetUnlockEntry(jsonEntry);
errorThrow(
"Too many item types defined: exceeds ITEM_TYPE_COUNT_MAX (%d)",
ITEM_TYPE_COUNT_MAX
);
}
ITEM_COUNT++;
itemid_t id = (itemid_t)ITEM_COUNT;
itemdef_t *def = &ITEMS[id];
def->id = id;
def->type = typeId;
def->weight = (weightVal && yyjson_is_num(weightVal)) ?
(float_t)yyjson_get_num(weightVal) : 0.0f;
memoryCopy(def->idName, idStr, idLen + 1);
stringFormat(def->name, ITEM_STRING_MAX - 1, "item.%s.name", nameStr);
}
assetUnlockEntry(jsonEntry);
errorOk();
}
itemid_t itemGetIdByName(const char_t *name) {
assertNotNull(name, "Item name cannot be NULL");
for(uint32_t i = 1; i <= ITEM_COUNT; i++) {
if(stringEquals(ITEMS[i].idName, name)) return (itemid_t)i;
}
return ITEM_ID_NULL;
}
errorret_t itemGetName(
const itemid_t item,
char_t *buffer,
const size_t bufferSize
) {
assertTrue(item > ITEM_ID_NULL, "Item ID must not be null");
assertTrue(item <= ITEM_COUNT, "Item ID out of range");
errorChain(assetLocaleGetString(
&LOCALE.entry->data.locale,
ITEMS[item].name,
0,
buffer,
bufferSize
));
errorOk();
}
itemtypeid_t itemResolveType(const char_t *name, const size_t nameLen) {
for(uint32_t i = 1; i <= ITEM_TYPE_COUNT; i++) {
if(stringEquals(ITEM_TYPES[i].name, name)) return (itemtypeid_t)i;
}
if(ITEM_TYPE_COUNT >= ITEM_TYPE_COUNT_MAX - 1) return ITEM_TYPE_NULL;
ITEM_TYPE_COUNT++;
itemtypeid_t typeId = (itemtypeid_t)ITEM_TYPE_COUNT;
ITEM_TYPES[typeId].id = typeId;
memoryCopy(ITEM_TYPES[typeId].name, name, nameLen + 1);
return typeId;
}
-4
View File
@@ -1,4 +0,0 @@
id,type,weight
POTION,MEDICINE,1.0
POTATO,FOOD,0.5
APPLE,FOOD,0.3
1 id type weight
2 POTION MEDICINE 1.0
3 POTATO FOOD 0.5
4 APPLE FOOD 0.3
+79
View File
@@ -0,0 +1,79 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "error/error.h"
#define ITEM_COUNT_MAX 256
#define ITEM_TYPE_COUNT_MAX 16
#define ITEM_STRING_MAX 48
typedef uint16_t itemid_t;
typedef uint8_t itemtypeid_t;
#define ITEM_ID_NULL ((itemid_t)0)
#define ITEM_TYPE_NULL ((itemtypeid_t)0)
typedef struct {
itemid_t id;
itemtypeid_t type;
float_t weight;
char_t idName[ITEM_STRING_MAX];
char_t name[ITEM_STRING_MAX];
} itemdef_t;
typedef struct {
itemtypeid_t id;
char_t name[ITEM_STRING_MAX];
} itemtype_t;
extern itemdef_t ITEMS[ITEM_COUNT_MAX];
extern uint32_t ITEM_COUNT;
extern itemtype_t ITEM_TYPES[ITEM_TYPE_COUNT_MAX];
extern uint32_t ITEM_TYPE_COUNT;
/**
* Loads assets/item.json and parses it into the ITEMS/ITEM_TYPES tables.
* Must be called once, before any other item/backpack function.
*
* @return Any error that occurs (missing/malformed JSON, or too many
* items/types defined for ITEM_COUNT_MAX/ITEM_TYPE_COUNT_MAX).
*/
errorret_t itemInit(void);
/**
* Looks up an item's numeric ID from its JSON "id" string.
*
* @param name The item's string ID (e.g. "POTION"), case-sensitive.
* @return The matching item ID, or ITEM_ID_NULL if not found.
*/
itemid_t itemGetIdByName(const char_t *name);
/**
* Resolves a type name string to its numeric type ID, registering it as
* a new type in ITEM_TYPES if not already known.
*
* @param name The type's string name (e.g. "MEDICINE").
* @param nameLen Length of name, excluding the null terminator.
* @return The resolved type ID, or ITEM_TYPE_NULL if ITEM_TYPE_COUNT_MAX
* would be exceeded.
*/
itemtypeid_t itemResolveType(const char_t *name, const size_t nameLen);
/**
* Gets the localized display name for an item.
*
* @param item The item ID to look up. Must not be ITEM_ID_NULL.
* @param buffer Buffer to write the localized name into.
* @param bufferSize Size of the buffer.
* @return Any error that occurs.
*/
errorret_t itemGetName(
const itemid_t item,
char_t *buffer,
const size_t bufferSize
);
+9 -2
View File
@@ -7,18 +7,25 @@
#include "itemgive.h"
#include "rpg/item/backpack.h"
#include "ui/rpg/uitextboxmain.h"
#include "rpg/item/item.h"
#include "ui/rpg/textbox/uitextboxmain.h"
#include "util/string.h"
#include "error/error.h"
#define ITEM_GIVE_NAME_MAX_CHARS 32
void itemGive(const itemid_t item, const uint8_t quantity) {
backpackAdd(item, quantity);
char_t name[ITEM_GIVE_NAME_MAX_CHARS];
errorCatch(itemGetName(item, name, ITEM_GIVE_NAME_MAX_CHARS));
char_t msg[ITEM_GIVE_MESSAGE_MAX_CHARS];
stringFormat(
msg,
ITEM_GIVE_MESSAGE_MAX_CHARS - 1,
"Received %s x%u",
ITEMS[item].name,
name,
(uint32_t)quantity
);
uiTextboxMainSetText(msg);
+381
View File
@@ -6,6 +6,24 @@
*/
#include "chunk.h"
#include "assert/assert.h"
#include "util/memory.h"
#include "util/string.h"
#include "asset/asset.h"
#include "asset/loader/assetloader.h"
#include "asset/loader/assetentry.h"
#include "console/console.h"
#include "event/event.h"
#include "rpg/entity/entity.h"
#include "rpg/overworld/map.h"
chunk_t CHUNKS[MAP_CHUNK_COUNT];
chunk_t *CHUNK_ORDER[MAP_CHUNK_COUNT];
static chunkpos_t CHUNK_POSITION;
static chunk_t *CHUNK_LOAD_QUEUE[MAP_CHUNK_COUNT];
static uint32_t CHUNK_LOAD_QUEUE_COUNT;
static chunk_t *CHUNK_LOADING;
uint32_t chunkGetTileIndex(const chunkpos_t position) {
return (position.y * CHUNK_WIDTH) + position.x;
@@ -14,3 +32,366 @@ uint32_t chunkGetTileIndex(const chunkpos_t position) {
bool_t chunkPositionIsEqual(const chunkpos_t a, const chunkpos_t b) {
return (a.x == b.x) && (a.y == b.y) && (a.z == b.z);
}
errorret_t chunksLoadGrid(void) {
CHUNK_POSITION = (chunkpos_t){ 0, 0, 0 };
chunkindex_t i = 0;
for(chunkunit_t z = 0; z < MAP_CHUNK_DEPTH; z++) {
for(chunkunit_t y = 0; y < MAP_CHUNK_HEIGHT; y++) {
for(chunkunit_t x = 0; x < MAP_CHUNK_WIDTH; x++) {
chunk_t *chunk = &CHUNKS[i++];
chunk->position = (chunkpos_t){
(chunkunit_t)x, (chunkunit_t)y, (chunkunit_t)z
};
errorChain(chunkLoad(chunk));
}
}
}
chunkRebuildOrder();
errorOk();
}
void chunksUnloadAll(void) {
for(chunkindex_t i = 0; i < MAP_CHUNK_COUNT; i++) {
chunkUnload(&CHUNKS[i]);
}
}
errorret_t chunkPositionSet(const chunkpos_t newPos) {
if(!mapIsLoaded()) errorThrow("No map loaded");
if(chunkPositionIsEqual(newPos, CHUNK_POSITION)) errorOk();
// Separate loaded chunks into "keep" and "free" buckets.
chunkindex_t chunksFreed[MAP_CHUNK_COUNT];
uint32_t freedCount = 0;
// Use a boolean grid so the inner load loop can check O(1).
bool_t posLoaded[MAP_CHUNK_WIDTH][MAP_CHUNK_HEIGHT][MAP_CHUNK_DEPTH];
memoryZero(posLoaded, sizeof(posLoaded));
for(chunkindex_t i = 0; i < MAP_CHUNK_COUNT; i++) {
chunk_t *chunk = &CHUNKS[i];
chunkunit_t rx = chunk->position.x - newPos.x;
chunkunit_t ry = chunk->position.y - newPos.y;
chunkunit_t rz = chunk->position.z - newPos.z;
if(
rx >= 0 && rx < MAP_CHUNK_WIDTH &&
ry >= 0 && ry < MAP_CHUNK_HEIGHT &&
rz >= 0 && rz < MAP_CHUNK_DEPTH
) {
posLoaded[rx][ry][rz] = true;
} else {
chunkUnload(chunk);
chunksFreed[freedCount++] = i;
}
}
for(chunkunit_t z = 0; z < MAP_CHUNK_DEPTH; z++) {
for(chunkunit_t y = 0; y < MAP_CHUNK_HEIGHT; y++) {
for(chunkunit_t x = 0; x < MAP_CHUNK_WIDTH; x++) {
if(posLoaded[x][y][z]) continue;
assertTrue(freedCount > 0, "No free chunk slot available.");
chunk_t *chunk = &CHUNKS[chunksFreed[--freedCount]];
chunk->position = (chunkpos_t){
newPos.x + (chunkunit_t)x,
newPos.y + (chunkunit_t)y,
newPos.z + (chunkunit_t)z
};
errorChain(chunkLoad(chunk));
}
}
}
CHUNK_POSITION = newPos;
chunkRebuildOrder();
errorOk();
}
void chunkUnload(chunk_t *chunk) {
chunkLoadQueueRemove(chunk);
if(CHUNK_LOADING == chunk) CHUNK_LOADING = NULL;
for(uint8_t i = 0; i < CHUNK_ENTITY_COUNT_MAX; i++) {
if(chunk->entities[i] == 0xFF) continue;
entity_t *entity = &ENTITIES[chunk->entities[i]];
if(!entityCanUnload(entity)) {
entitySetChunk(entity, 0xFF);
} else {
entity->type = ENTITY_TYPE_NULL;
}
}
memorySet(chunk->entities, 0xFF, sizeof(chunk->entities));
if(chunk->dataEntry != NULL) {
eventUnsubscribe(&chunk->dataEntry->onLoaded, chunkLoaded);
eventUnsubscribe(&chunk->dataEntry->onError, chunkLoadError);
assetUnlockEntry(chunk->dataEntry);
chunk->dataEntry = NULL;
}
// modelEntries are borrowed pointers, not independently locked - the
// chunk asset entry (released above) is what actually holds the ref on
// each model, so nothing to unlock here, just drop our own copies.
for(uint8_t m = 0; m < chunk->meshCount; m++) {
chunk->modelEntries[m] = NULL;
}
chunk->meshCount = 0;
}
errorret_t chunkLoad(chunk_t *chunk) {
if(!mapIsLoaded()) errorThrow("No map loaded");
chunkLoadQueueRemove(chunk);
if(CHUNK_LOADING == chunk) CHUNK_LOADING = NULL;
if(chunk->dataEntry != NULL) {
eventUnsubscribe(&chunk->dataEntry->onLoaded, chunkLoaded);
eventUnsubscribe(&chunk->dataEntry->onError, chunkLoadError);
assetUnlockEntry(chunk->dataEntry);
chunk->dataEntry = NULL;
}
memorySet(chunk->entities, 0xFF, sizeof(chunk->entities));
chunk->meshCount = 0;
char_t path[MAP_FILE_PATH_MAX + 64];
stringFormat(
path, sizeof(path),
"map/%s/chunks/%d_%d_%d.json",
MAP.name,
(int32_t)chunk->position.x,
(int32_t)chunk->position.y,
(int32_t)chunk->position.z
);
if(!assetFileExists(path)) {
for(uint32_t i = 0; i < CHUNK_TILE_COUNT; i++) {
chunk->tiles[i] = (tile_t){ .shape = TILE_SHAPE_GROUND };
}
errorOk();
}
assertTrue(
CHUNK_LOAD_QUEUE_COUNT < MAP_CHUNK_COUNT,
"Chunk load queue overflow"
);
CHUNK_LOAD_QUEUE[CHUNK_LOAD_QUEUE_COUNT++] = chunk;
chunkLoadNext();
errorOk();
}
void chunkLoadNext(void) {
if(CHUNK_LOADING != NULL) return;
if(CHUNK_LOAD_QUEUE_COUNT == 0) return;
chunk_t *chunk = CHUNK_LOAD_QUEUE[0];
for(uint32_t i = 1; i < CHUNK_LOAD_QUEUE_COUNT; i++) {
CHUNK_LOAD_QUEUE[i - 1] = CHUNK_LOAD_QUEUE[i];
}
CHUNK_LOAD_QUEUE_COUNT--;
CHUNK_LOADING = chunk;
char_t path[MAP_FILE_PATH_MAX + 64];
stringFormat(
path, sizeof(path),
"map/%s/chunks/%d_%d_%d.json",
MAP.name,
(int32_t)chunk->position.x,
(int32_t)chunk->position.y,
(int32_t)chunk->position.z
);
assetentry_t *entry = assetLock(path, ASSET_LOADER_TYPE_CHUNK, NULL);
assertNotNull(entry, "Failed to get chunk asset entry");
chunk->dataEntry = entry;
// The entry may already be resident from an earlier load that hasn't been
// reaped yet - in that case onLoaded/onError already fired once and never
// will again, so handle the terminal state directly instead of waiting on
// a subscription that would never trigger.
if(entry->state == ASSET_ENTRY_STATE_LOADED) {
chunkLoaded(entry, chunk);
return;
}
if(entry->state == ASSET_ENTRY_STATE_ERROR) {
chunkLoadError(entry, chunk);
return;
}
eventSubscribe(&entry->onLoaded, chunkLoaded, chunk);
eventSubscribe(&entry->onError, chunkLoadError, chunk);
}
void chunkLoadQueueRemove(chunk_t *chunk) {
for(uint32_t i = 0; i < CHUNK_LOAD_QUEUE_COUNT; i++) {
if(CHUNK_LOAD_QUEUE[i] != chunk) continue;
for(uint32_t j = i + 1; j < CHUNK_LOAD_QUEUE_COUNT; j++) {
CHUNK_LOAD_QUEUE[j - 1] = CHUNK_LOAD_QUEUE[j];
}
CHUNK_LOAD_QUEUE_COUNT--;
return;
}
}
chunkindex_t chunkGetIndexAt(const chunkpos_t position) {
if(!mapIsLoaded()) return -1;
chunkpos_t relPos = {
position.x - CHUNK_POSITION.x,
position.y - CHUNK_POSITION.y,
position.z - CHUNK_POSITION.z
};
if(
relPos.x < 0 || relPos.y < 0 || relPos.z < 0 ||
relPos.x >= MAP_CHUNK_WIDTH ||
relPos.y >= MAP_CHUNK_HEIGHT ||
relPos.z >= MAP_CHUNK_DEPTH
) {
return -1;
}
return chunkPosToIndex(&relPos);
}
chunk_t *chunkGet(const uint8_t index) {
if(index >= MAP_CHUNK_COUNT) return NULL;
if(!mapIsLoaded()) return NULL;
return CHUNK_ORDER[index];
}
tile_t chunkGetTile(const worldpos_t position) {
if(!mapIsLoaded()) return TILE_NULL;
chunkpos_t chunkPos;
worldPosToChunkPos(&position, &chunkPos);
chunkindex_t chunkIndex = chunkGetIndexAt(chunkPos);
if(chunkIndex == -1) return TILE_NULL;
chunk_t *chunk = chunkGet(chunkIndex);
assertNotNull(chunk, "Chunk pointer cannot be NULL");
chunktileindex_t tileIndex = worldPosToChunkTileIndex(&position);
tile_t tile = chunk->tiles[tileIndex];
if(tile.z != worldPosToChunkLocalZ(&position)) return TILE_NULL;
return tile;
}
bool_t chunkGetWalkableZNear(
const worldunit_t x,
const worldunit_t y,
const worldunit_t nearZ,
worldunit_t *outZ
) {
assertNotNull(outZ, "Output Z pointer cannot be NULL");
const worldunit_t candidates[] = {
nearZ, (worldunit_t)(nearZ + 1), (worldunit_t)(nearZ - 1)
};
for(uint8_t i = 0; i < 3; i++) {
const worldpos_t pos = { x, y, candidates[i] };
if(!tileShapeIsWalkable(chunkGetTile(pos).shape)) continue;
*outZ = candidates[i];
return true;
}
return false;
}
void chunkRebuildOrder(void) {
memoryZero(CHUNK_ORDER, sizeof(CHUNK_ORDER));
for(chunkindex_t i = 0; i < MAP_CHUNK_COUNT; i++) {
chunk_t *chunk = &CHUNKS[i];
const chunkpos_t rel = {
chunk->position.x - CHUNK_POSITION.x,
chunk->position.y - CHUNK_POSITION.y,
chunk->position.z - CHUNK_POSITION.z
};
if(
rel.x < 0 || rel.x >= MAP_CHUNK_WIDTH ||
rel.y < 0 || rel.y >= MAP_CHUNK_HEIGHT ||
rel.z < 0 || rel.z >= MAP_CHUNK_DEPTH
) continue;
CHUNK_ORDER[chunkPosToIndex(&rel)] = chunk;
}
}
void chunkLoadError(void *params, void *user) {
assertNotNull(params, "chunkLoadError: params cannot be NULL");
assertNotNull(user, "chunkLoadError: user cannot be NULL");
assetentry_t *entry = (assetentry_t *)params;
chunk_t *chunk = (chunk_t *)user;
if(chunk->dataEntry != entry) return;
consolePrint(
"Chunk load error: %d %d %d",
(int32_t)chunk->position.x,
(int32_t)chunk->position.y,
(int32_t)chunk->position.z
);
eventUnsubscribe(&entry->onLoaded, chunkLoaded);
eventUnsubscribe(&entry->onError, chunkLoadError);
assetUnlockEntry(chunk->dataEntry);
chunk->dataEntry = NULL;
memorySet(chunk->tiles, 0x00, sizeof(chunk->tiles));
if(CHUNK_LOADING == chunk) CHUNK_LOADING = NULL;
chunkLoadNext();
}
void chunkLoaded(void *params, void *user) {
assertNotNull(params, "chunkLoaded: params cannot be NULL");
assertNotNull(user, "chunkLoaded: user cannot be NULL");
assetentry_t *entry = (assetentry_t *)params;
chunk_t *chunk = (chunk_t *)user;
if(chunk->dataEntry != entry) return;
uint8_t meshCount = entry->data.chunk.meshCount;
memoryCopy(
chunk->tiles,
entry->data.chunk.tiles,
sizeof(chunk->tiles)
);
worldpos_t wp;
chunkPosToWorldPos(&chunk->position, &wp);
vec3 wpf = {
(float_t)wp.x, (float_t)wp.y, (float_t)wp.z * WORLD_LAYER_HEIGHT
};
for(uint8_t m = 0; m < meshCount; m++) {
stringCopy(
chunk->modelNames[m],
entry->data.chunk.modelNames[m],
CHUNK_MESH_NAME_MAX
);
glm_vec3_copy(
entry->data.chunk.meshOffsets[m],
chunk->meshOffsets[m]
);
vec3 scaledOffset = {
chunk->meshOffsets[m][0],
chunk->meshOffsets[m][1],
chunk->meshOffsets[m][2] * WORLD_LAYER_HEIGHT
};
vec3 pos;
glm_vec3_add(wpf, scaledOffset, pos);
glm_translate_make(chunk->meshModels[m], pos);
// Borrow the pointer rather than stealing it - the chunk asset entry
// keeps its own lock on each model (taken once while it loaded) and we
// keep the chunk asset entry itself locked (see below), so the models
// stay valid for as long as this chunk_t is using them. The entry may
// now be reused by a later chunkLoad for a different chunk_t once we
// eventually unlock it in chunkUnload, at which point its modelEntries
// must still be intact for that next reuse to copy from.
chunk->modelEntries[m] = entry->data.chunk.modelEntries[m];
}
eventUnsubscribe(&entry->onLoaded, chunkLoaded);
eventUnsubscribe(&entry->onError, chunkLoadError);
// Deliberately keep chunk->dataEntry locked and set - it is what keeps the
// chunk asset entry (and therefore its model locks) alive for as long as
// this chunk_t is displaying it. Released in chunkUnload instead.
chunk->meshCount = meshCount;
if(CHUNK_LOADING == chunk) CHUNK_LOADING = NULL;
chunkLoadNext();
}
+134 -1
View File
@@ -19,7 +19,7 @@ typedef struct chunk_s {
chunkpos_t position;
tile_t tiles[CHUNK_TILE_COUNT];
assetentry_t *dcfEntry;
assetentry_t *dataEntry;
uint8_t meshCount;
char_t modelNames[CHUNK_MESH_COUNT_MAX][CHUNK_MESH_NAME_MAX];
@@ -30,6 +30,16 @@ typedef struct chunk_s {
uint8_t entities[CHUNK_ENTITY_COUNT_MAX];
} chunk_t;
/** Every chunk slot for the currently loaded map. */
extern chunk_t CHUNKS[MAP_CHUNK_COUNT];
/**
* Chunk pointers arranged by position relative to the currently loaded
* window, indexed via chunkPosToIndex(). NULL where no chunk occupies
* that slot. Rebuilt by chunkRebuildOrder() whenever the window moves.
*/
extern chunk_t *CHUNK_ORDER[MAP_CHUNK_COUNT];
/**
* Gets the tile index for a tile position within a chunk.
*
@@ -46,3 +56,126 @@ uint32_t chunkGetTileIndex(const chunkpos_t position);
* @return true if equal, false otherwise.
*/
bool_t chunkPositionIsEqual(const chunkpos_t a, const chunkpos_t b);
/**
* Resets and starts loading the initial MAP_CHUNK_WIDTH x HEIGHT x DEPTH
* grid of chunks (async, see chunkLoad), anchored at chunk position
* (0,0,0). Does not unload chunks already loaded - call chunksUnloadAll()
* first when switching to a different map.
*
* @return Any error that occurs.
*/
errorret_t chunksLoadGrid(void);
/**
* Unloads every chunk slot in CHUNKS.
*/
void chunksUnloadAll(void);
/**
* Moves the loaded chunk window to be centered around newPos, unloading
* chunks that fall outside the new window and loading any newly exposed
* ones. No-op if newPos matches the currently loaded window.
*
* @param newPos The new chunk position.
* @return An error code.
*/
errorret_t chunkPositionSet(const chunkpos_t newPos);
/**
* Unloads a chunk.
*
* @param chunk The chunk to unload.
*/
void chunkUnload(chunk_t *chunk);
/**
* Loads a chunk. Starts async loading without blocking.
*
* @param chunk The chunk to load.
* @return An error code.
*/
errorret_t chunkLoad(chunk_t *chunk);
/**
* Starts loading the next queued chunk, if no chunk is currently mid-load.
* Called after chunkLoad enqueues a chunk, and again after the
* currently-loading chunk finishes (or is unloaded) to advance the queue.
*/
void chunkLoadNext(void);
/**
* Removes a chunk from the load queue if present. Used when a chunk is
* re-queued or unloaded before its turn to load has come up.
*
* @param chunk The chunk to remove from the load queue.
*/
void chunkLoadQueueRemove(chunk_t *chunk);
/**
* Callback invoked when a chunk JSON asset fails to load. Fills the
* chunk tiles with TILE_SHAPE_GROUND as a fallback.
* Always invoked on the main thread.
*
* @param params The failed assetentry_t.
* @param user The chunk_t that owns the entry.
*/
void chunkLoadError(void *params, void *user);
/**
* Callback invoked when a chunk JSON asset finishes loading.
* Always invoked on the main thread.
*
* @param params The loaded assetentry_t.
* @param user The chunk_t that owns the entry.
*/
void chunkLoaded(void *params, void *user);
/**
* Rebuilds CHUNK_ORDER from the loaded chunks that fall within the
* current render window. Called whenever the chunk position changes.
*/
void chunkRebuildOrder(void);
/**
* Gets the index of a chunk, within the currently loaded window, at the
* given position.
*
* @param position The chunk position.
* @return The index of the chunk, or -1 if out of bounds.
*/
chunkindex_t chunkGetIndexAt(const chunkpos_t position);
/**
* Gets a chunk by its index in CHUNK_ORDER.
*
* @param index The index of the chunk.
* @return A pointer to the chunk.
*/
chunk_t *chunkGet(const uint8_t index);
/**
* Gets the tile at the given world position.
*
* @param position The world position.
* @return The tile at that position, or TILE_NULL if the chunk is unloaded.
*/
tile_t chunkGetTile(const worldpos_t position);
/**
* Finds the closest walkable Z layer to nearZ at the given X/Y. Checks
* nearZ first, then nearZ + 1, then nearZ - 1, since ramps only ever
* change height by one Z layer between adjacent tiles.
*
* @param x The world X coordinate to check.
* @param y The world Y coordinate to check.
* @param nearZ The reference Z layer to search outward from.
* @param outZ Output pointer, set to the resolved Z layer on success.
* @return true if a walkable tile was found, false otherwise.
*/
bool_t chunkGetWalkableZNear(
const worldunit_t x,
const worldunit_t y,
const worldunit_t nearZ,
worldunit_t *outZ
);
+93 -352
View File
@@ -10,39 +10,64 @@
#include "assert/assert.h"
#include "asset/asset.h"
#include "asset/loader/assetloader.h"
#include "asset/loader/assetentry.h"
#include "asset/loader/json/assetjsonloader.h"
#include "console/console.h"
#include "event/event.h"
#include "util/string.h"
#include "rpg/entity/global/entityglobal.h"
#include "rpg/overworld/chunk.h"
#include "rpg/entity/entity.h"
#include "yyjson.h"
map_t MAP;
errorret_t mapInit() {
errorret_t mapInit(const char_t *name) {
errorChain(mapSetMap(name));
errorOk();
}
errorret_t mapSetMap(const char_t *name) {
assertNotNull(name, "Map name cannot be NULL");
assertStrLenMin(name, 1, "Map name cannot be empty");
assertStrLenMax(name, MAP_FILE_PATH_MAX, "Map name too long");
if(mapIsLoaded() && stringEquals(MAP.name, name)) errorOk();
if(mapIsLoaded()) {
chunksUnloadAll();
if(MAP.defEntry != NULL) {
eventUnsubscribe(&MAP.defEntry->onLoaded, mapDefLoaded);
eventUnsubscribe(&MAP.defEntry->onError, mapDefLoadError);
assetUnlockEntry(MAP.defEntry);
MAP.defEntry = NULL;
}
}
memoryZero(&MAP, sizeof(map_t));
stringCopy(MAP.name, name, MAP_FILE_PATH_MAX);
MAP.loaded = true;
MAP.loadPosition = (chunkpos_t){
-(MAP_CHUNK_SKIN),
-(MAP_CHUNK_SKIN),
-(MAP_CHUNK_SKIN)
};
char_t defPath[MAP_FILE_PATH_MAX + 16];
stringFormat(defPath, sizeof(defPath), "map/%s/map.json", MAP.name);
chunkindex_t i = 0;
for(chunkunit_t z = 0; z < MAP_LOADED_CHUNK_DEPTH; z++) {
for(chunkunit_t y = 0; y < MAP_LOADED_CHUNK_HEIGHT; y++) {
for(chunkunit_t x = 0; x < MAP_LOADED_CHUNK_WIDTH; x++) {
chunk_t *chunk = &MAP.chunks[i++];
chunk->position = (chunkpos_t){
MAP.loadPosition.x + (chunkunit_t)x,
MAP.loadPosition.y + (chunkunit_t)y,
MAP.loadPosition.z + (chunkunit_t)z
};
errorChain(mapChunkLoad(chunk));
}
}
assetentry_t *defEntry = assetLock(defPath, ASSET_LOADER_TYPE_JSON, NULL);
assertNotNull(defEntry, "Failed to get map def asset entry");
MAP.defEntry = defEntry;
// The entry may already be resident from an earlier load that hasn't been
// reaped yet - in that case onLoaded/onError already fired once and never
// will again, so handle the terminal state directly instead of waiting on
// a subscription that would never trigger.
if(defEntry->state == ASSET_ENTRY_STATE_LOADED) {
mapDefLoaded(defEntry, NULL);
} else if(defEntry->state == ASSET_ENTRY_STATE_ERROR) {
mapDefLoadError(defEntry, NULL);
} else {
eventSubscribe(&defEntry->onLoaded, mapDefLoaded, NULL);
eventSubscribe(&defEntry->onError, mapDefLoadError, NULL);
}
mapRebuildChunkOrder();
errorChain(chunksLoadGrid());
errorOk();
}
@@ -50,345 +75,61 @@ bool_t mapIsLoaded() {
return MAP.loaded;
}
errorret_t mapPositionSet(const chunkpos_t newPos) {
if(!mapIsLoaded()) errorThrow("No map loaded");
if(chunkPositionIsEqual(newPos, MAP.chunkPosition)) errorOk();
// If the new render window still fits inside the current loaded area,
// just remap chunkOrder — no asset I/O needed.
const chunkpos_t lp = MAP.loadPosition;
if(
newPos.x >= lp.x &&
newPos.y >= lp.y &&
newPos.z >= lp.z &&
newPos.x + MAP_CHUNK_WIDTH <= lp.x + MAP_LOADED_CHUNK_WIDTH &&
newPos.y + MAP_CHUNK_HEIGHT <= lp.y + MAP_LOADED_CHUNK_HEIGHT &&
newPos.z + MAP_CHUNK_DEPTH <= lp.z + MAP_LOADED_CHUNK_DEPTH
) {
MAP.chunkPosition = newPos;
mapRebuildChunkOrder();
errorOk();
}
// Render window fell outside the loaded area — re-centre the load
// window on the new render position (skin buffer on every side).
const chunkpos_t newLoadPos = {
newPos.x - MAP_CHUNK_SKIN,
newPos.y - MAP_CHUNK_SKIN,
newPos.z - MAP_CHUNK_SKIN
};
// Separate loaded chunks into "keep" and "free" buckets.
chunkindex_t chunksFreed[MAP_LOADED_CHUNK_COUNT];
uint32_t freedCount = 0;
// Use a boolean grid so the inner load loop can check O(1).
bool_t posLoaded[MAP_LOADED_CHUNK_WIDTH][MAP_LOADED_CHUNK_HEIGHT]
[MAP_LOADED_CHUNK_DEPTH];
memoryZero(posLoaded, sizeof(posLoaded));
for(chunkindex_t i = 0; i < MAP_LOADED_CHUNK_COUNT; i++) {
chunk_t *chunk = &MAP.chunks[i];
chunkunit_t rx = chunk->position.x - newLoadPos.x;
chunkunit_t ry = chunk->position.y - newLoadPos.y;
chunkunit_t rz = chunk->position.z - newLoadPos.z;
if(
rx >= 0 && rx < MAP_LOADED_CHUNK_WIDTH &&
ry >= 0 && ry < MAP_LOADED_CHUNK_HEIGHT &&
rz >= 0 && rz < MAP_LOADED_CHUNK_DEPTH
) {
posLoaded[rx][ry][rz] = true;
} else {
mapChunkUnload(chunk);
chunksFreed[freedCount++] = i;
}
}
for(chunkunit_t z = 0; z < MAP_LOADED_CHUNK_DEPTH; z++) {
for(chunkunit_t y = 0; y < MAP_LOADED_CHUNK_HEIGHT; y++) {
for(chunkunit_t x = 0; x < MAP_LOADED_CHUNK_WIDTH; x++) {
if(posLoaded[x][y][z]) continue;
assertTrue(freedCount > 0, "No free chunk slot available.");
chunk_t *chunk = &MAP.chunks[chunksFreed[--freedCount]];
chunk->position = (chunkpos_t){
newLoadPos.x + (chunkunit_t)x,
newLoadPos.y + (chunkunit_t)y,
newLoadPos.z + (chunkunit_t)z
};
errorChain(mapChunkLoad(chunk));
}
}
}
MAP.loadPosition = newLoadPos;
MAP.chunkPosition = newPos;
mapRebuildChunkOrder();
errorOk();
}
errorret_t mapUpdate() {
errorOk();
}
errorret_t mapDispose() {
for(chunkindex_t i = 0; i < MAP_LOADED_CHUNK_COUNT; i++) {
mapChunkUnload(&MAP.chunks[i]);
chunksUnloadAll();
if(MAP.defEntry != NULL) {
eventUnsubscribe(&MAP.defEntry->onLoaded, mapDefLoaded);
eventUnsubscribe(&MAP.defEntry->onError, mapDefLoadError);
assetUnlockEntry(MAP.defEntry);
MAP.defEntry = NULL;
}
errorOk();
}
void mapChunkUnload(chunk_t *chunk) {
for(uint8_t i = 0; i < CHUNK_ENTITY_COUNT_MAX; i++) {
if(chunk->entities[i] == 0xFF) continue;
entity_t *entity = &ENTITIES[chunk->entities[i]];
if(!entityCanUnload(entity)) {
entitySetChunk(entity, 0xFF);
} else {
entity->type = ENTITY_TYPE_NULL;
}
}
memorySet(chunk->entities, 0xFF, sizeof(chunk->entities));
if(chunk->dcfEntry != NULL) {
eventUnsubscribe(&chunk->dcfEntry->onLoaded, mapChunkLoaded);
eventUnsubscribe(&chunk->dcfEntry->onError, mapChunkLoadError);
assetUnlockEntry(chunk->dcfEntry);
chunk->dcfEntry = NULL;
}
for(uint8_t m = 0; m < chunk->meshCount; m++) {
if(chunk->modelEntries[m] == NULL) continue;
assetUnlockEntry(chunk->modelEntries[m]);
chunk->modelEntries[m] = NULL;
}
chunk->meshCount = 0;
}
errorret_t mapChunkLoad(chunk_t *chunk) {
if(!mapIsLoaded()) errorThrow("No map loaded");
if(chunk->dcfEntry != NULL) {
eventUnsubscribe(&chunk->dcfEntry->onLoaded, mapChunkLoaded);
eventUnsubscribe(&chunk->dcfEntry->onError, mapChunkLoadError);
assetUnlockEntry(chunk->dcfEntry);
chunk->dcfEntry = NULL;
}
memorySet(chunk->entities, 0xFF, sizeof(chunk->entities));
chunk->meshCount = 0;
char_t name[64];
stringFormat(
name, sizeof(name),
"chunks/%d_%d_%d.dcf",
(int32_t)chunk->position.x,
(int32_t)chunk->position.y,
(int32_t)chunk->position.z
);
if(!assetFileExists(name)) {
for(uint32_t i = 0; i < CHUNK_TILE_COUNT; i++) {
// chunk->tiles[i] = (tile_t){ .shape = TILE_SHAPE_GROUND, .z = 0 };
chunk->tiles[i] = (tile_t){ .shape = TILE_SHAPE_GROUND };
}
errorOk();
}
assetentry_t *entry = assetLock(name, ASSET_LOADER_TYPE_CHUNK, NULL);
assertNotNull(entry, "Failed to get chunk asset entry");
eventSubscribe(&entry->onLoaded, mapChunkLoaded, chunk);
eventSubscribe(&entry->onError, mapChunkLoadError, chunk);
chunk->dcfEntry = entry;
errorOk();
}
chunkindex_t mapGetChunkIndexAt(const chunkpos_t position) {
if(!mapIsLoaded()) return -1;
chunkpos_t relPos = {
position.x - MAP.chunkPosition.x,
position.y - MAP.chunkPosition.y,
position.z - MAP.chunkPosition.z
};
if(
relPos.x < 0 || relPos.y < 0 || relPos.z < 0 ||
relPos.x >= MAP_CHUNK_WIDTH ||
relPos.y >= MAP_CHUNK_HEIGHT ||
relPos.z >= MAP_CHUNK_DEPTH
) {
return -1;
}
return chunkPosToIndex(&relPos);
}
chunk_t *mapGetChunk(const uint8_t index) {
if(index >= MAP_CHUNK_COUNT) return NULL;
if(!mapIsLoaded()) return NULL;
return MAP.chunkOrder[index];
}
tile_t mapGetTile(const worldpos_t position) {
if(!mapIsLoaded()) return TILE_NULL;
chunkpos_t chunkPos;
worldPosToChunkPos(&position, &chunkPos);
chunkindex_t chunkIndex = mapGetChunkIndexAt(chunkPos);
if(chunkIndex == -1) return TILE_NULL;
chunk_t *chunk = mapGetChunk(chunkIndex);
assertNotNull(chunk, "Chunk pointer cannot be NULL");
chunktileindex_t tileIndex = worldPosToChunkTileIndex(&position);
tile_t tile = chunk->tiles[tileIndex];
if(tile.z != worldPosToChunkLocalZ(&position)) return TILE_NULL;
return tile;
}
bool_t mapGetWalkableZNear(
const worldunit_t x,
const worldunit_t y,
const worldunit_t nearZ,
worldunit_t *outZ
) {
assertNotNull(outZ, "Output Z pointer cannot be NULL");
const worldunit_t candidates[] = {
nearZ, (worldunit_t)(nearZ + 1), (worldunit_t)(nearZ - 1)
};
for(uint8_t i = 0; i < 3; i++) {
const worldpos_t pos = { x, y, candidates[i] };
if(!tileShapeIsWalkable(mapGetTile(pos).shape)) continue;
*outZ = candidates[i];
return true;
}
return false;
}
entity_t * mapSpawnEntity(
const entityglobalid_t globalId,
const worldpos_t position
) {
assertTrue(
globalId > ENTITY_GLOBAL_ID_START,
"mapSpawnEntity requires a global ID greater than ENTITY_GLOBAL_ID_START"
);
assertTrue(
globalId < ENTITY_GLOBAL_LIST_COUNT,
"Global ID is out of range for entity global init callbacks"
);
// Already spawned? Reuse the existing entity instead of making a
// duplicate - two entities must never share a global ID.
entity_t *existing = entityGetByGlobalId(globalId);
if(existing != NULL) return existing;
// See if there is a callback for this entity first.
const entityglobaldef_t *def = &ENTITY_GLOBAL_LIST[globalId];
assertNotNull(def, "No global entity definition for this ID");
assertNotNull(def->callback, "No callback registered for this global ID");
// Get available entity.
uint8_t index = entityGetAvailable();
assertTrue(index != 0xFF, "No available entity slots for mapSpawnEntity");
// Get the pointer and do the init.
entity_t *entity = &ENTITIES[index];
entityInit(entity, def->type);
entity->globalId = globalId;
entityPositionSet(entity, position);// Also assigns the entity's chunk.
// Invoke the callback to initialize the entity.
entityglobalcreate_t create = {
.entity = entity,
.position = position
};
def->callback(&create);
return entity;
}
void mapRebuildChunkOrder() {
memoryZero(MAP.chunkOrder, sizeof(MAP.chunkOrder));
for(chunkindex_t i = 0; i < MAP_LOADED_CHUNK_COUNT; i++) {
chunk_t *chunk = &MAP.chunks[i];
const chunkpos_t rel = {
chunk->position.x - MAP.chunkPosition.x,
chunk->position.y - MAP.chunkPosition.y,
chunk->position.z - MAP.chunkPosition.z
};
if(
rel.x < 0 || rel.x >= MAP_CHUNK_WIDTH ||
rel.y < 0 || rel.y >= MAP_CHUNK_HEIGHT ||
rel.z < 0 || rel.z >= MAP_CHUNK_DEPTH
) continue;
MAP.chunkOrder[chunkPosToIndex(&rel)] = chunk;
}
}
void mapChunkLoadError(void *params, void *user) {
assertNotNull(params, "mapChunkLoadError: params cannot be NULL");
assertNotNull(user, "mapChunkLoadError: user cannot be NULL");
chunk_t *chunk = (chunk_t *)user;
if(chunk->dcfEntry != (assetentry_t *)params) return;
consolePrint(
"Chunk load error: %d %d %d",
(int32_t)chunk->position.x,
(int32_t)chunk->position.y,
(int32_t)chunk->position.z
);
assetUnlockEntry(chunk->dcfEntry);
chunk->dcfEntry = NULL;
memorySet(chunk->tiles, 0x00, sizeof(chunk->tiles));
}
void mapChunkLoaded(void *params, void *user) {
assertNotNull(params, "mapChunkLoaded: params cannot be NULL");
assertNotNull(user, "mapChunkLoaded: user cannot be NULL");
void mapDefLoadError(void *params, void *user) {
assertNotNull(params, "mapDefLoadError: params cannot be NULL");
assetentry_t *entry = (assetentry_t *)params;
chunk_t *chunk = (chunk_t *)user;
if(chunk->dcfEntry != entry) return;
// consolePrint(
// "Chunk loaded: %d %d %d",
// (int32_t)chunk->position.x,
// (int32_t)chunk->position.y,
// (int32_t)chunk->position.z
// );
uint8_t meshCount = entry->data.chunk.meshCount;
memoryCopy(
chunk->tiles,
entry->data.chunk.tiles,
sizeof(chunk->tiles)
);
worldpos_t wp;
chunkPosToWorldPos(&chunk->position, &wp);
vec3 wpf = {
(float_t)wp.x, (float_t)wp.y, (float_t)wp.z * WORLD_LAYER_HEIGHT
};
for(uint8_t m = 0; m < meshCount; m++) {
stringCopy(
chunk->modelNames[m],
entry->data.chunk.modelNames[m],
CHUNK_MESH_NAME_MAX
);
glm_vec3_copy(
entry->data.chunk.meshOffsets[m],
chunk->meshOffsets[m]
);
vec3 scaledOffset = {
chunk->meshOffsets[m][0],
chunk->meshOffsets[m][1],
chunk->meshOffsets[m][2] * WORLD_LAYER_HEIGHT
};
vec3 pos;
glm_vec3_add(wpf, scaledOffset, pos);
glm_translate_make(chunk->meshModels[m], pos);
chunk->modelEntries[m] = entry->data.chunk.modelEntries[m];
entry->data.chunk.modelEntries[m] = NULL;
}
assetUnlockEntry(chunk->dcfEntry);
chunk->dcfEntry = NULL;
chunk->meshCount = meshCount;
if(MAP.defEntry != entry) return;
consolePrint("Failed to load map.json for '%s'", MAP.name);
eventUnsubscribe(&entry->onLoaded, mapDefLoaded);
eventUnsubscribe(&entry->onError, mapDefLoadError);
}
void mapDefLoaded(void *params, void *user) {
assertNotNull(params, "mapDefLoaded: params cannot be NULL");
assetentry_t *entry = (assetentry_t *)params;
if(MAP.defEntry != entry) return;
yyjson_val *root = yyjson_doc_get_root(entry->data.json);
yyjson_val *nameVal = yyjson_obj_get(root, "name");
if(!nameVal || !yyjson_is_str(nameVal)) {
consolePrint("map.json for '%s' missing 'name' string", MAP.name);
} else {
const char_t *nameStr = yyjson_get_str(nameVal);
size_t nameLen = yyjson_get_len(nameVal);
if(nameLen >= MAP_DISPLAY_NAME_MAX) {
consolePrint("Map display name '%s' exceeds max length", nameStr);
} else {
memoryCopy(MAP.displayName, nameStr, nameLen + 1);
}
}
yyjson_val *entitiesVal = yyjson_obj_get(root, "entities");
if(entitiesVal && yyjson_is_arr(entitiesVal)) {
size_t entIdx, entMax;
yyjson_val *entObj;
yyjson_arr_foreach(entitiesVal, entIdx, entMax, entObj) {
entity_t *spawned = NULL;
errorCatch(errorPrint(entityCreateFromJson(entObj, &spawned)));
}
}
eventUnsubscribe(&entry->onLoaded, mapDefLoaded);
eventUnsubscribe(&entry->onError, mapDefLoadError);
}
+38 -102
View File
@@ -7,28 +7,48 @@
#pragma once
#include "error/error.h"
#include "rpg/overworld/chunk.h"
#include "rpg/entity/entity.h"
#define MAP_FILE_PATH_MAX 128
#define MAP_FILE_PATH_MAX 32
#define MAP_DISPLAY_NAME_MAX 64
typedef struct assetentry_s assetentry_t;
typedef struct map_s {
char_t name[MAP_FILE_PATH_MAX];
char_t displayName[MAP_DISPLAY_NAME_MAX];
bool_t loaded;
chunk_t chunks[MAP_LOADED_CHUNK_COUNT];
chunk_t *chunkOrder[MAP_CHUNK_COUNT];
chunkpos_t chunkPosition;
chunkpos_t loadPosition;
// Asset lock for the map's map.json, held while its async load is
// pending and for as long as the map stays loaded.
assetentry_t *defEntry;
} map_t;
extern map_t MAP;
/**
* Initializes the map.
* Initializes the map, loading its chunks from beneath the given name's
* asset directory (e.g. "testmap" -> assets/map/testmap/chunks/X_Y_Z.dcf).
*
* @param name The map's directory name, under assets/map/.
* @return An error code.
*/
errorret_t mapInit();
errorret_t mapInit(const char_t *name);
/**
* Switches to a different map, unloading every currently loaded chunk and
* starting an async load of the initial chunk grid (at chunk position
* 0,0,0) plus map.json (-> MAP.displayName), both from beneath the new
* name's asset directory. Once map.json loads, its optional "entities"
* array (see entityCreateFromJson) is spawned; entries that fail to parse
* are logged and skipped rather than failing the whole map load. Returns
* before either finishes loading - callers must not assume
* MAP.displayName, spawned entities, or chunk data is populated yet.
* No-op if name matches the currently loaded map.
*
* @param name The map's directory name, under assets/map/.
* @return An error code.
*/
errorret_t mapSetMap(const char_t *name);
/**
* Checks if a map is loaded.
@@ -52,106 +72,22 @@ errorret_t mapUpdate();
errorret_t mapDispose();
/**
* Sets the map position and updates chunks accordingly.
*
* @param newPos The new chunk position.
* @return An error code.
*/
errorret_t mapPositionSet(const chunkpos_t newPos);
/**
* Unloads a chunk.
*
* @param chunk The chunk to unload.
*/
void mapChunkUnload(chunk_t* chunk);
/**
* Loads a chunk. Starts async loading without blocking.
*
* @param chunk The chunk to load.
* @return An error code.
*/
errorret_t mapChunkLoad(chunk_t* chunk);
/**
* Callback invoked when a chunk DCF asset fails to load. Fills the
* chunk tiles with TILE_SHAPE_GROUND as a fallback.
* Callback invoked when a map's map.json asset fails to load. Leaves
* MAP.displayName empty and logs a console message.
* Always invoked on the main thread.
*
* @param params The failed assetentry_t.
* @param user The chunk_t that owns the entry.
* @param user Unused.
*/
void mapChunkLoadError(void *params, void *user);
void mapDefLoadError(void *params, void *user);
/**
* Callback invoked when a chunk DCF asset finishes loading.
* Callback invoked when a map's map.json asset finishes loading. Parses
* out the "name" string into MAP.displayName, and spawns each entry of
* the optional "entities" array via entityCreateFromJson.
* Always invoked on the main thread.
*
* @param params The loaded assetentry_t.
* @param user The chunk_t that owns the entry.
* @param user Unused.
*/
void mapChunkLoaded(void *params, void *user);
/**
* Rebuilds chunkOrder from the loaded chunks that fall within the
* current render window. Called whenever chunkPosition changes.
*/
void mapRebuildChunkOrder();
/**
* Gets the index of a chunk, within the world, at the given position.
*
* @param position The chunk position.
* @return The index of the chunk, or -1 if out of bounds.
*/
chunkindex_t mapGetChunkIndexAt(const chunkpos_t position);
/**
* Gets a chunk by its index.
*
* @param chunkIndex The index of the chunk.
* @return A pointer to the chunk.
*/
chunk_t * mapGetChunk(const uint8_t chunkIndex);
/**
* Gets the tile at the given world position.
*
* @param position The world position.
* @return The tile at that position, or TILE_NULL if the chunk is unloaded.
*/
tile_t mapGetTile(const worldpos_t position);
/**
* Finds the closest walkable Z layer to nearZ at the given X/Y. Checks
* nearZ first, then nearZ + 1, then nearZ - 1, since ramps only ever
* change height by one Z layer between adjacent tiles.
*
* @param x The world X coordinate to check.
* @param y The world Y coordinate to check.
* @param nearZ The reference Z layer to search outward from.
* @param outZ Output pointer, set to the resolved Z layer on success.
* @return true if a walkable tile was found, false otherwise.
*/
bool_t mapGetWalkableZNear(
const worldunit_t x,
const worldunit_t y,
const worldunit_t nearZ,
worldunit_t *outZ
);
/**
* Spawns a global (persistent) entity into the world at the given position.
* Asserts globalId is greater than ENTITY_GLOBAL_ID_START - use entityInit
* directly for ephemeral, non-global entities.
*
* @param globalId The global entity ID to assign, must be greater than
* ENTITY_GLOBAL_ID_START.
* @param position The world position to spawn the entity at.
* @return Pointer to the spawned entity.
*/
entity_t * mapSpawnEntity(
const entityglobalid_t globalId,
const worldpos_t position
);
void mapDefLoaded(void *params, void *user);
+3 -3
View File
@@ -9,7 +9,7 @@
#include "assert/assert.h"
#include "util/math.h"
#include "util/memory.h"
#include "rpg/overworld/map.h"
#include "rpg/overworld/chunk.h"
maparea_t MAP_AREAS[MAP_AREA_COUNT_MAX];
@@ -73,8 +73,8 @@ bool_t mapAreaIsChunkOverlappingOrInside(
bool_t mapAreaCanUnload(const maparea_t *area) {
assertNotNull(area, "Map area pointer cannot be NULL");
for(chunkindex_t i = 0; i < MAP_LOADED_CHUNK_COUNT; i++) {
if(mapAreaIsChunkOverlappingOrInside(area, &MAP.chunks[i])) return false;
for(chunkindex_t i = 0; i < MAP_CHUNK_COUNT; i++) {
if(mapAreaIsChunkOverlappingOrInside(area, &CHUNKS[i])) return false;
}
return true;
-10
View File
@@ -30,16 +30,6 @@
#define MAP_CHUNK_DEPTH 4
#define MAP_CHUNK_COUNT (MAP_CHUNK_WIDTH * MAP_CHUNK_HEIGHT * MAP_CHUNK_DEPTH)
// Extra chunks loaded on every side beyond the render window.
// The render window can drift MAP_CHUNK_SKIN chunks in any direction
// before a load/unload cycle is triggered.
#define MAP_CHUNK_SKIN 1
#define MAP_LOADED_CHUNK_WIDTH (MAP_CHUNK_WIDTH + MAP_CHUNK_SKIN)
#define MAP_LOADED_CHUNK_HEIGHT (MAP_CHUNK_HEIGHT + MAP_CHUNK_SKIN)
#define MAP_LOADED_CHUNK_DEPTH (MAP_CHUNK_DEPTH + MAP_CHUNK_SKIN)
#define MAP_LOADED_CHUNK_COUNT \
(MAP_LOADED_CHUNK_WIDTH * MAP_LOADED_CHUNK_HEIGHT * MAP_LOADED_CHUNK_DEPTH)
#define ENTITY_COUNT 32
typedef int16_t worldunit_t;
+10 -23
View File
@@ -7,14 +7,13 @@
#include "rpg.h"
#include "entity/entity.h"
#include "rpg/entity/npc/npcpath.h"
#include "rpg/entity/item/entityitem.h"
#include "rpg/overworld/map.h"
#include "rpg/overworld/chunk.h"
#include "rpg/overworld/maparea.h"
#include "rpg/cutscene/cutscenesystem.h"
#include "rpg/cutscene/scene/testcutscene.h"
#include "rpg/item/backpack.h"
#include "rpg/battle/party.h"
#include "ui/rpg/textbox/uitextboxminilist.h"
#include "time/time.h"
#include "rpgcamera.h"
#include "util/memory.h"
@@ -22,6 +21,8 @@
#include "assert/assert.h"
#include "console/console.h"
#include "ui/rpg/uiemoji.h"
void rpgTestAreaCallback(entity_t *entity, const uint8_t trigger) {
consolePrint("rpgTestAreaCallback: trigger=%u", trigger);
}
@@ -34,30 +35,16 @@ errorret_t rpgInit(void) {
partyInit();
cutsceneSystemInit();
errorChain(mapInit());
errorChain(mapInit("testmap"));
rpgCameraInit();
// Init world
errorChain(mapPositionSet((chunkpos_t){ 0, 0, 0 }));
errorChain(chunkPositionSet((chunkpos_t){ 0, 0, 0 }));
// TEST: Create some entities.
uint8_t entIndex = entityGetAvailable();
assertTrue(entIndex != 0xFF, "No available entity slots!.");
entity_t *ent = &ENTITIES[entIndex];
entityInit(ent, ENTITY_TYPE_PLAYER);
entityPositionSet(ent, (worldpos_t){ 10, 2, 0 });// Also assigns the chunk.
RPG_CAMERA.mode = RPG_CAMERA_MODE_FOLLOW_ENTITY;
RPG_CAMERA.followEntity.followEntityId = ent->id;
mapSpawnEntity(3, (worldpos_t){ 8, 8, 1 });
// TEST: Place an item entity.
uint8_t itemEntIndex = entityGetAvailable();
assertTrue(itemEntIndex != 0xFF, "No available entity slots!.");
entity_t *itemEnt = &ENTITIES[itemEntIndex];
entityInit(itemEnt, ENTITY_TYPE_ITEM);
entityItemSet(itemEnt, ITEM_ID_POTION, 1);
entityPositionSet(itemEnt, (worldpos_t){ 12, 2, 0 });
// TEST: Give the player a starting assortment of items.
backpackAdd(itemGetIdByName("POTION"), 5);
backpackAdd(itemGetIdByName("POTATO"), 3);
backpackAdd(itemGetIdByName("APPLE"), 8);
// TEST: Create a test map area.
uint8_t areaIndex = mapAreaAdd(
+70 -1
View File
@@ -7,12 +7,19 @@
#include "rpgcamera.h"
#include "util/memory.h"
#include "util/random.h"
#include "rpg/entity/entity.h"
#include "rpg/overworld/map.h"
#include "rpg/overworld/chunk.h"
#include "assert/assert.h"
#include "time/time.h"
#include "display/screen/screen.h"
static const float_t RPG_CAMERA_SHAKE_AMOUNTS[] = {
0.0f, 0.5f, 1.0f, 2.0f, 3.0f
};
rpgcamera_t RPG_CAMERA;
void rpgCameraInit(void) {
@@ -20,6 +27,13 @@ void rpgCameraInit(void) {
RPG_CAMERA.projectionDirty = true;
}
void rpgCameraShake(uint8_t amount, float_t duration) {
assertTrue(amount <= 4, "Camera shake amount must be between 0 and 4");
RPG_CAMERA.shakeAmount = RPG_CAMERA_SHAKE_AMOUNTS[amount];
RPG_CAMERA.shakeDuration = duration;
RPG_CAMERA.shakeTime = 0.0f;
}
void rpgCameraGetPosition(vec3 out) {
switch(RPG_CAMERA.mode) {
case RPG_CAMERA_MODE_FREE:
@@ -56,7 +70,62 @@ void rpgCameraUpdateProjection(void) {
);
}
void rpgCameraUpdateEye(void) {
float_t fov = glm_rad(RPG_CAMERA_FOV);
float_t pixelsPerUnit = TILE_SIZE_PIXELS;
float_t worldH = (float_t)(SCREEN.height / SCREEN.scale3d) / pixelsPerUnit;
float_t z = (worldH * 0.5f) / tanf(fov * 0.5f);
float_t offset = -24.0f * (worldH / TILE_SIZE_PIXELS);
vec3 target;
rpgCameraGetPosition(target);
glm_vec3_add(target, (vec3){ 0.5f, 0.5f, 0.5f }, target);
if(RPG_CAMERA.shakeTime < RPG_CAMERA.shakeDuration) {
float_t t = 1.0f - (RPG_CAMERA.shakeTime / RPG_CAMERA.shakeDuration);
float_t magnitude = RPG_CAMERA.shakeAmount * t;
target[0] += randomFloat(-magnitude, magnitude);
target[2] += randomFloat(-magnitude, magnitude);
}
glm_lookat(
(vec3){ target[0], target[1] + offset, target[2] + z },
target,
(vec3){ 0, 1, 0 }, // up
RPG_CAMERA.eye
);
}
void rpgCameraToScreen(vec3 worldPos, vec2 out) {
mat4 viewProj;
glm_mat4_mul(RPG_CAMERA.projection, RPG_CAMERA.eye, viewProj);
vec4 viewport = {
0.0f, 0.0f, (float_t)SCREEN.width, (float_t)SCREEN.height
};
vec3 window;
glm_project(worldPos, viewProj, viewport, window);
out[0] = window[0];
out[1] = (float_t)SCREEN.height - window[1];
}
errorret_t rpgCameraUpdate(void) {
if(RPG_CAMERA.shakeTime < RPG_CAMERA.shakeDuration) {
RPG_CAMERA.shakeTime += TIME.delta;
}
// The player entity may spawn asynchronously (e.g. via map.json), so
// start following it as soon as it shows up rather than requiring
// whoever creates it to also wire up the camera.
if(RPG_CAMERA.mode == RPG_CAMERA_MODE_FREE) {
entity_t *player = entityGetByGlobalId(ENTITY_GLOBAL_ID_PLAYER);
if(player != NULL) {
RPG_CAMERA.mode = RPG_CAMERA_MODE_FOLLOW_ENTITY;
RPG_CAMERA.followEntity.followEntityId = player->id;
}
}
if(!mapIsLoaded()) errorOk();
vec3 pos;
@@ -68,7 +137,7 @@ errorret_t rpgCameraUpdate(void) {
.z = (chunkunit_t)floorf(pos[2] / WORLD_LAYER_HEIGHT / CHUNK_DEPTH)
};
errorChain(mapPositionSet((chunkpos_t){
errorChain(chunkPositionSet((chunkpos_t){
.x = chunkPos.x - (MAP_CHUNK_WIDTH / 2),
.y = chunkPos.y - (MAP_CHUNK_HEIGHT / 2),
.z = chunkPos.z - (MAP_CHUNK_DEPTH / 2)
+32
View File
@@ -30,6 +30,10 @@ typedef struct {
mat4 eye;
mat4 projection;
bool_t projectionDirty;
float_t shakeAmount;
float_t shakeDuration;
float_t shakeTime;
} rpgcamera_t;
extern rpgcamera_t RPG_CAMERA;
@@ -60,3 +64,31 @@ errorret_t rpgCameraUpdate(void);
* is recomputed every call.
*/
void rpgCameraUpdateProjection(void);
/**
* Recomputes the camera eye/view matrix from the camera's current mode
* and position, and stores it in RPG_CAMERA.eye. Unlike the projection
* matrix this is never cached, since the camera position can change
* every frame.
*/
void rpgCameraUpdateEye(void);
/**
* Shakes the RPG camera, randomly offsetting its position by a
* decreasing amount over the given duration.
*
* @param amount Shake strength from 0 (no shake) to 4 (three tiles).
* 1 is half a tile, 2 is a full tile, 3 is two tiles, and 4 is three
* tiles.
* @param duration How long the shake lasts, in seconds.
*/
void rpgCameraShake(uint8_t amount, float_t duration);
/**
* Converts a world-space position to screen-space pixel coordinates,
* using the camera's current eye and projection matrices.
*
* @param worldPos The world-space position to convert.
* @param out Output vec2 filled with the screen-space pixel position.
*/
void rpgCameraToScreen(vec3 worldPos, vec2 out);
+1
View File
@@ -11,3 +11,4 @@ target_sources(${DUSK_LIBRARY_TARGET_NAME}
# Subdirs
add_subdirectory(overworld)
add_subdirectory(battle)
+9
View File
@@ -0,0 +1,9 @@
# Copyright (c) 2026 Dominic Masters
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
scenebattle.c
)
+26
View File
@@ -0,0 +1,26 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "scenebattle.h"
#include "rpg/battle/battle.h"
errorret_t sceneBattleInit(scenedata_t *sceneData) {
errorOk();
}
errorret_t sceneBattleUpdate(scenedata_t *sceneData) {
battleUpdate();
errorOk();
}
errorret_t sceneBattleRender(scenedata_t *sceneData) {
errorOk();
}
errorret_t sceneBattleDispose(scenedata_t *sceneData) {
errorOk();
}
+46
View File
@@ -0,0 +1,46 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "scene/scenebase.h"
typedef struct {
} scenebattle_t;
/**
* Initializes the battle scene. The battle itself (BATTLE global) is
* expected to already be started, e.g. by a StartBattle cutscene item.
*
* @param sceneData The scene data used for this scene.
* @return An error if the init failed, or errorOk() if it succeeded.
*/
errorret_t sceneBattleInit(scenedata_t *sceneData);
/**
* Updates the battle scene, ticking the battle simulation.
*
* @param sceneData The scene data used for this scene.
* @return An error if the update failed, or errorOk() if it succeeded.
*/
errorret_t sceneBattleUpdate(scenedata_t *sceneData);
/**
* Renders the battle scene.
*
* @param sceneData The scene data used for this scene.
* @return An error if the render failed, or errorOk() if it succeeded.
*/
errorret_t sceneBattleRender(scenedata_t *sceneData);
/**
* Disposes the battle scene.
*
* @param sceneData The scene data used for this scene.
* @return An error if the dispose failed, or errorOk() if it succeeded.
*/
errorret_t sceneBattleDispose(scenedata_t *sceneData);
+108 -58
View File
@@ -17,13 +17,15 @@
#include "display/spritebatch/spritebatch.h"
#include "display/texture/texture.h"
#include "rpg/overworld/map.h"
#include "rpg/overworld/chunk.h"
#include "rpg/entity/entity.h"
#include "rpg/rpgcamera.h"
#include "asset/loader/assetloader.h"
#include "asset/loader/assetentry.h"
#include "util/memory.h"
errorret_t sceneOverworldInit(scenedata_t *sceneData) {
assertNotNull(sceneData, "Scene data cannot be null");
errorOk();
@@ -31,71 +33,127 @@ errorret_t sceneOverworldInit(scenedata_t *sceneData) {
errorret_t sceneOverworldUpdate(scenedata_t *sceneData) {
assertNotNull(sceneData, "Scene data cannot be null");
errorOk();
}
errorret_t sceneOverworldRender(scenedata_t *sceneData) {
assertNotNull(sceneData, "Scene data cannot be null");
errorChain(displaySetState((displaystate_t){
.flags = DISPLAY_STATE_FLAG_DEPTH_TEST | DISPLAY_STATE_FLAG_CULL
}));
sceneoverworld_t *overworld = &sceneData->overworld;
sceneOverworldCullUpdate(overworld);
mat4 model, eye;
// Overworld camera
errorChain(shaderBind(&SHADER_UNLIT));
errorChain(shaderSetMatrix(
&SHADER_UNLIT, SHADER_UNLIT_MODEL, SCENE.screenIdentity
));
// Model
glm_mat4_identity(model);
errorChain(shaderSetMatrix(&SHADER_UNLIT, SHADER_UNLIT_MODEL, model));
// Camera projection
rpgCameraUpdateProjection();
errorChain(shaderSetMatrix(
&SHADER_UNLIT, SHADER_UNLIT_PROJECTION, RPG_CAMERA.projection
));
// Camera Eye
float_t fov = glm_rad(RPG_CAMERA_FOV);
float_t pixelsPerUnit = TILE_SIZE_PIXELS;
float_t worldH = (float_t)(SCREEN.height / SCREEN.scale3d) / pixelsPerUnit;
float_t z = (worldH * 0.5f) / tanf(fov * 0.5f);
vec3 worldPosVec;
rpgCameraGetPosition(worldPosVec);
float_t offset = -24.0f * (worldH / TILE_SIZE_PIXELS);
rpgCameraUpdateEye();
errorChain(shaderSetMatrix(
&SHADER_UNLIT, SHADER_UNLIT_VIEW, RPG_CAMERA.eye
));
glm_vec3_add(worldPosVec, (vec3){ 0.5f, 0.5f, 0.5f }, worldPosVec);
// Chunk tiles
errorChain(displaySetState((displaystate_t){
.flags = DISPLAY_STATE_FLAG_DEPTH_TEST | DISPLAY_STATE_FLAG_CULL
}));
errorChain(sceneOverworldDrawChunksBase(overworld));
glm_lookat(
(vec3){
worldPosVec[0],
worldPosVec[1] + offset,
worldPosVec[2] + z
},
worldPosVec,
(vec3){ 0, 1, 0 }, // up
eye
);
errorChain(shaderSetMatrix(&SHADER_UNLIT, SHADER_UNLIT_VIEW, eye));
// Base terrain meshes, drawn with normal depth testing.
errorChain(sceneOverworldDrawChunksBase());
// Entities are drawn with depth testing fully disabled so sloped tiles
// (ramps) never clip them; entity-vs-entity overlap falls back to
// array draw order instead of true depth.
// Entities
errorChain(displaySetState((displaystate_t){
.flags = DISPLAY_STATE_FLAG_CULL
}));
// Entities
{
for(uint8_t i = 0; i < ENTITY_COUNT; i++) {
entity_t *ent = &ENTITIES[i];
if(ent->type == ENTITY_TYPE_NULL) continue;
errorChain(sceneOverworldDrawEntity(overworld, ent));
}
// Chunk props
errorChain(displaySetState((displaystate_t){
.flags = DISPLAY_STATE_FLAG_DEPTH_TEST | DISPLAY_STATE_FLAG_CULL
}));
errorChain(sceneOverworldDrawChunksProps(overworld));
// Weather effects
// errorChain(shaderSetMatrix(
// &SHADER_UNLIT, SHADER_UNLIT_PROJECTION, SCENE.screenProj
// ));
// errorChain(shaderSetMatrix(
// &SHADER_UNLIT, SHADER_UNLIT_VIEW, SCENE.screenView
// ));
// errorChain(displaySetState((displaystate_t){
// .flags = DISPLAY_STATE_FLAG_BLEND
// }));
// spritebatchsprite_t skyboxSprite;
// memoryZero(&skyboxSprite, sizeof(spritebatchsprite_t));
// skyboxSprite.max[0] = (float_t)(SCREEN.width / SCREEN.scaleUi);
// skyboxSprite.max[1] = (float_t)(SCREEN.height / SCREEN.scaleUi);
// shadermaterial_t skyboxMaterial = {
// .unlit = { .color = color(0xFF, 0x00, 0x00, 0xFF/2), .texture = NULL }
// };
// errorChain(spriteBatchBuffer(&skyboxSprite, 1, &SHADER_UNLIT, skyboxMaterial));
// errorChain(spriteBatchFlush());
errorOk();
}
void sceneOverworldCullUpdate(sceneoverworld_t *overworld) {
rpgCameraGetPosition(overworld->cullTarget);
const float_t worldH =
(float_t)(SCREEN.height / SCREEN.scale3d) / TILE_SIZE_PIXELS;
const float_t worldW = worldH * SCREEN.aspect;
overworld->cullHalfRangeX =
(worldW * 0.5f) + SCENE_OVERWORLD_CHUNK_CULL_SKIN_X;
overworld->cullHalfRangeY =
(worldH * 0.5f) + SCENE_OVERWORLD_CHUNK_CULL_SKIN_Y;
}
bool_t sceneOverworldChunkShouldRender(
const sceneoverworld_t *overworld,
const chunk_t *chunk
) {
worldpos_t worldPos;
chunkPosToWorldPos(&chunk->position, &worldPos);
const float_t chunkCenterX = (float_t)worldPos.x + (CHUNK_WIDTH * 0.5f);
const float_t chunkCenterY = (float_t)worldPos.y + (CHUNK_HEIGHT * 0.5f);
if(fabsf(overworld->cullTarget[0] - chunkCenterX) >
overworld->cullHalfRangeX) return false;
if(fabsf(overworld->cullTarget[1] - chunkCenterY) >
overworld->cullHalfRangeY) return false;
return true;
}
bool_t sceneOverworldEntityShouldRender(
const sceneoverworld_t *overworld,
const entity_t *ent
) {
if(fabsf(overworld->cullTarget[0] - ent->renderPosition[0]) >
overworld->cullHalfRangeX) return false;
if(fabsf(overworld->cullTarget[1] - ent->renderPosition[1]) >
overworld->cullHalfRangeY) return false;
return true;
}
errorret_t sceneOverworldDrawEntity(
const sceneoverworld_t *overworld,
entity_t *ent
) {
if(!sceneOverworldEntityShouldRender(overworld, ent)) errorOk();
spritebatchsprite_t sprite;
glm_vec3_copy(ent->renderPosition, sprite.min);
@@ -117,26 +175,17 @@ errorret_t sceneOverworldRender(scenedata_t *sceneData) {
shadermaterial_t material = {
.unlit = { .color = color, .texture = NULL }
};
spriteBatchBuffer(&sprite, 1, &SHADER_UNLIT, material);
spriteBatchFlush();
}
}
// Other chunk meshes (trees, buildings, etc), drawn last with normal
// depth testing so they correctly occlude entities standing beneath
// them.
errorChain(displaySetState((displaystate_t){
.flags = DISPLAY_STATE_FLAG_DEPTH_TEST | DISPLAY_STATE_FLAG_CULL
}));
errorChain(sceneOverworldDrawChunksProps());
errorChain(spriteBatchBuffer(&sprite, 1, &SHADER_UNLIT, material));
errorChain(spriteBatchFlush());
errorOk();
}
errorret_t sceneOverworldDrawChunksBase() {
errorret_t sceneOverworldDrawChunksBase(const sceneoverworld_t *overworld) {
for(chunkindex_t i = 0; i < MAP_CHUNK_COUNT; i++) {
chunk_t *chunk = MAP.chunkOrder[i];
chunk_t *chunk = CHUNK_ORDER[i];
if(chunk == NULL) continue;
if(!sceneOverworldChunkShouldRender(overworld, chunk)) continue;
if(chunk->meshCount == 0) continue;
if(chunk->modelEntries[0] == NULL) continue;
if(chunk->modelEntries[0]->state != ASSET_ENTRY_STATE_LOADED) continue;
@@ -169,10 +218,11 @@ errorret_t sceneOverworldDrawChunksBase() {
errorOk();
}
errorret_t sceneOverworldDrawChunksProps() {
errorret_t sceneOverworldDrawChunksProps(const sceneoverworld_t *overworld) {
for(chunkindex_t i = 0; i < MAP_CHUNK_COUNT; i++) {
chunk_t *chunk = MAP.chunkOrder[i];
chunk_t *chunk = CHUNK_ORDER[i];
if(chunk == NULL) continue;
if(!sceneOverworldChunkShouldRender(overworld, chunk)) continue;
for(uint8_t m = 1; m < chunk->meshCount; m++) {
if(chunk->modelEntries[m] == NULL) continue;
+90 -3
View File
@@ -7,11 +7,35 @@
#pragma once
#include "scene/scenebase.h"
#include "rpg/overworld/chunk.h"
#include "rpg/entity/entity.h"
typedef struct {
// Cached per-frame chunk culling bounds, refreshed by
// sceneOverworldCullUpdate() so sceneOverworldChunkShouldRender()
// does not need to recompute them for every chunk.
vec3 cullTarget;
float_t cullHalfRangeX;
float_t cullHalfRangeY;
} sceneoverworld_t;
// Extra world-space margin, in tiles, added on top of the rough
// screen-size skin below - cheap insurance against the approximation
// culling a chunk that is actually still just in view. Y gets its own
// value since the camera's tilt makes the vertical check less exact.
#define SCENE_OVERWORLD_CHUNK_CULL_PADDING_X 8.0f
#define SCENE_OVERWORLD_CHUNK_CULL_PADDING_Y 4.0f
// The camera is tilted between the ground-depth (Y) and height (Z)
// axes, so a chunk's on-screen vertical extent also depends on its Z
// layers. Rather than projecting every corner, fold that into a
// generous skin margin on the depth check.
#define SCENE_OVERWORLD_CHUNK_CULL_SKIN_X \
((CHUNK_WIDTH * 0.5f) + SCENE_OVERWORLD_CHUNK_CULL_PADDING_X)
#define SCENE_OVERWORLD_CHUNK_CULL_SKIN_Y \
((CHUNK_HEIGHT * 0.5f) + (CHUNK_DEPTH * WORLD_LAYER_HEIGHT) + \
SCENE_OVERWORLD_CHUNK_CULL_PADDING_Y)
/**
* Initialises the overworld scene.
*
@@ -28,22 +52,85 @@ errorret_t sceneOverworldInit(scenedata_t *sceneData);
*/
errorret_t sceneOverworldUpdate(scenedata_t *sceneData);
/**
* Refreshes the chunk culling bounds cached on the overworld scene data,
* from the current camera position and screen dimensions. Must be
* called once per frame before sceneOverworldChunkShouldRender().
*
* @param overworld The overworld scene data to update.
*/
void sceneOverworldCullUpdate(sceneoverworld_t *overworld);
/**
* Roughly checks whether a chunk falls within the visible screen area,
* based on chunk size and screen dimensions. Cheap approximation, not
* an exact frustum check - includes a generous skin margin to account
* for the camera's angle tilting height/depth onto the screen's
* vertical axis, so it may pass some chunks that are actually just out
* of view but will never wrongly cull one that is visible.
*
* @param overworld The overworld scene data holding the cached culling
* bounds, as refreshed by sceneOverworldCullUpdate().
* @param chunk The chunk to check.
* @return true if the chunk should be rendered, false otherwise.
*/
bool_t sceneOverworldChunkShouldRender(
const sceneoverworld_t *overworld,
const chunk_t *chunk
);
/**
* Draws the base (tile) mesh of every loaded chunk, with normal depth
* testing. Must be called before entities are rendered.
*
* @param overworld The overworld scene data holding the cached culling
* bounds, as refreshed by sceneOverworldCullUpdate().
* @return An error if drawing failed, or errorOk() on success.
*/
errorret_t sceneOverworldDrawChunksBase();
errorret_t sceneOverworldDrawChunksBase(const sceneoverworld_t *overworld);
/**
* Draws every loaded chunk's additional meshes (trees, buildings, etc),
* with normal depth testing so they correctly occlude entities standing
* beneath them. Must be called after entities are rendered.
*
* @param overworld The overworld scene data holding the cached culling
* bounds, as refreshed by sceneOverworldCullUpdate().
* @return An error if drawing failed, or errorOk() on success.
*/
errorret_t sceneOverworldDrawChunksProps();
errorret_t sceneOverworldDrawChunksProps(const sceneoverworld_t *overworld);
/**
* Roughly checks whether an entity falls within the visible screen
* area. Reuses the same cached chunk culling bounds, since an entity
* is just a point within that same space - deliberately cheap, a
* couple of subtractions and comparisons, since it runs per entity
* every frame and it is not worth spending more math than that to
* avoid drawing one that is slightly off-screen.
*
* @param overworld The overworld scene data holding the cached culling
* bounds, as refreshed by sceneOverworldCullUpdate().
* @param ent The entity to check.
* @return true if the entity should be rendered, false otherwise.
*/
bool_t sceneOverworldEntityShouldRender(
const sceneoverworld_t *overworld,
const entity_t *ent
);
/**
* Draws a single entity as a sprite, colored by its facing direction.
* Skips drawing (without error) if the entity should not render.
*
* @param overworld The overworld scene data holding the cached culling
* bounds, as refreshed by sceneOverworldCullUpdate().
* @param ent The entity to draw.
* @return An error if drawing failed, or errorOk() on success.
*/
errorret_t sceneOverworldDrawEntity(
const sceneoverworld_t *overworld,
entity_t *ent
);
/**
* Renders the overworld scene.
+26 -19
View File
@@ -58,6 +58,23 @@ errorret_t sceneUpdate(void) {
}
errorret_t sceneRender(void) {
// Setup screen matrices for 3D rendering.
glm_mat4_identity(SCENE.screenIdentity);
glm_ortho(
0.0f, (float_t)(SCREEN.width / SCREEN.scaleUi),
(float_t)(SCREEN.height / SCREEN.scaleUi), 0.0f,
0.1f, 100.0f,
SCENE.screenProj
);
glm_lookat(
(vec3){ 0.0f, 0.0f, 1.0f },
(vec3){ 0.0f, 0.0f, 0.0f },
(vec3){ 0.0f, 1.0f, 0.0f },
SCENE.screenView
);
// Scene rendering
if(
SCENE.current != SCENE_TYPE_NULL &&
@@ -67,26 +84,16 @@ errorret_t sceneRender(void) {
}
// UI Rendering
mat4 proj, view, ident;
glm_mat4_identity(ident);
errorChain(shaderBind(&SHADER_UNLIT));
errorChain(shaderSetMatrix(&SHADER_UNLIT, SHADER_UNLIT_MODEL, ident));
glm_ortho(
0.0f, (float_t)(SCREEN.width / SCREEN.scaleUi),
(float_t)(SCREEN.height / SCREEN.scaleUi), 0.0f,
0.1f, 100.0f,
proj
);
errorChain(shaderSetMatrix(&SHADER_UNLIT, SHADER_UNLIT_PROJECTION, proj));
glm_lookat(
(vec3){ 0.0f, 0.0f, 1.0f },
(vec3){ 0.0f, 0.0f, 0.0f },
(vec3){ 0.0f, 1.0f, 0.0f },
view
);
errorChain(shaderSetMatrix(&SHADER_UNLIT, SHADER_UNLIT_VIEW, view));
errorChain(shaderSetMatrix(
&SHADER_UNLIT, SHADER_UNLIT_MODEL, SCENE.screenIdentity
));
errorChain(shaderSetMatrix(
&SHADER_UNLIT, SHADER_UNLIT_PROJECTION, SCENE.screenProj
));
errorChain(shaderSetMatrix(
&SHADER_UNLIT, SHADER_UNLIT_VIEW, SCENE.screenView
));
errorChain(displaySetState((displaystate_t){
.flags = DISPLAY_STATE_FLAG_BLEND
+4
View File
@@ -6,12 +6,16 @@
*/
#pragma once
#include "dusk.h"
#include "scenetype.h"
typedef struct {
scenetype_t current;
scenetype_t next;
scenedata_t data;
mat4 screenProj;
mat4 screenView;
mat4 screenIdentity;
} scene_t;
extern scene_t SCENE;
+7
View File
@@ -16,5 +16,12 @@ scenecallbacks_t SCENE_TYPES[SCENE_TYPE_COUNT] = {
.render = sceneOverworldRender,
.dispose = sceneOverworldDispose
},
[SCENE_TYPE_BATTLE] = {
.init = sceneBattleInit,
.update = sceneBattleUpdate,
.render = sceneBattleRender,
.dispose = sceneBattleDispose
},
};
+3
View File
@@ -8,9 +8,11 @@
#pragma once
#include "scene/scenebase.h"
#include "scene/overworld/sceneoverworld.h"
#include "scene/battle/scenebattle.h"
typedef union scenedata_u {
sceneoverworld_t overworld;
scenebattle_t battle;
} scenedata_t;
typedef errorret_t (*scenecallback_t)(scenedata_t *);
@@ -26,6 +28,7 @@ typedef enum {
SCENE_TYPE_NULL,
SCENE_TYPE_OVERWORLD,
SCENE_TYPE_BATTLE,
SCENE_TYPE_COUNT
} scenetype_t;
+2
View File
@@ -11,3 +11,5 @@ target_sources(${DUSK_LIBRARY_TARGET_NAME}
add_subdirectory(game)
add_subdirectory(settings)
add_subdirectory(battle)
add_subdirectory(backpack)
@@ -3,7 +3,7 @@
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
# Sources
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
uibackpack.c
)

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