Skip to content

Free games for graphing calculators: NumWorks, TI-Nspire CX, Casio fx-CG50 and soon TI-84 Plus CE. Balatro, Celeste, Hollow Knight, Minecraft and more.

Hollow Knight: lifeblood cocoons; a better tile coder

Mason Chen4e764eda2c9f
diff --git a/games/hollowknight/src/data.bin b/games/hollowknight/src/data.bin
index f4b10662..f4cb53ae 100644
Binary files a/games/hollowknight/src/data.bin and b/games/hollowknight/src/data.bin differ
diff --git a/games/hollowknight/src/data.h b/games/hollowknight/src/data.h
index bf3ad534..bdfc48dd 100644
--- a/games/hollowknight/src/data.h
+++ b/games/hollowknight/src/data.h
@@ -155,239 +155,246 @@
#define CLIP_HUD_BLUE_APPEAR 96
#define CLIP_HUD_BLUE_IDLE 97
#define CLIP_HUD_BLUE_BREAK 98
-#define CLIP_HUD_HUD_FRAME 99
-#define CLIP_HUD_HUD_FRAME_IDLE 100
-#define CLIP_HUD_HUD_FRAME_CRACKAPPEAR 101
-#define CLIP_HUD_HUD_FRAME_CRACKED 102
-#define CLIP_HUD_COIN_APPEAR 103
-#define CLIP_HUD_COIN_IDLE 104
-#define CLIP_HUD_COIN_GET 105
-#define CLIP_HUD_SOUL_BURST 106
-#define CLIP_LIQUID_FILL 107
-#define CLIP_LIQUID_IDLE 108
-#define CLIP_LIQUID_SHRINK 109
-#define CLIP_LIQUID_DRAIN 110
-#define CLIP_GEO_SMALL_IDLE 111
-#define CLIP_GEO_SMALL_AIR 112
-#define CLIP_GEO_MED_IDLE 113
-#define CLIP_GEO_MED_AIR 114
-#define CLIP_GEO_LARGE_IDLE 115
-#define CLIP_GEO_LARGE_AIR 116
-#define CLIP_DIALOGUE_ARROW_UP 117
-#define CLIP_DIALOGUE_ARROW_DOWN 118
-#define CLIP_DIALOGUE_STOP_UP 119
-#define CLIP_DIALOGUE_STOP_DOWN 120
-#define CLIP_DIALOGUE_FLEUR_TOP_UP 121
-#define CLIP_DIALOGUE_FLEUR_TOP_DOWN 122
-#define CLIP_DIALOGUE_FLEUR_BOT_UP 123
-#define CLIP_DIALOGUE_FLEUR_BOT_DOWN 124
-#define CLIP_PROMPT_UP 125
-#define CLIP_PROMPT_DOWN 126
-#define CLIP_PROMPT_BLANK 127
-#define CLIP_SHADE_IDLE 128
-#define CLIP_SHADE_STARTLE 129
-#define CLIP_SHADE_FLY 130
-#define CLIP_SHADE_TURNTOFLY 131
-#define CLIP_SHADE_TURNTOIDLE 132
-#define CLIP_SHADE_SLASH_ANTIC 133
-#define CLIP_SHADE_SLASH 134
-#define CLIP_SHADE_SLASH_CD 135
-#define CLIP_SHADE_SLASH_EFFECT 136
-#define CLIP_SHADE_CAST_ANTIC 137
-#define CLIP_SHADE_CAST_CHARGE 138
-#define CLIP_SHADE_CAST 139
-#define CLIP_SHADE_RETREAT_START 140
-#define CLIP_SHADE_RETREAT_END 141
-#define CLIP_SHADE_DEATH_START 142
-#define CLIP_SHADE_DEATH 143
-#define CLIP_SHADE_DEPART 144
-#define CLIP_SHADE_APPEAR 145
-#define CLIP_SHADE_FIREBALL 146
-#define CLIP_SHADE_FIREBALL_END 147
-#define CLIP_SHADE_CAST_RING 148
-#define CLIP_CRAWLER_WALK 149
-#define CLIP_CRAWLER_TURN 150
-#define CLIP_CRAWLER_IDLE 151
-#define CLIP_CRAWLER_DEATH_AIR 152
-#define CLIP_CRAWLER_DEATH_LAND 153
-#define CLIP_BUZZER_CHASE 154
-#define CLIP_BUZZER_IDLE 155
-#define CLIP_BUZZER_STARTLE 156
-#define CLIP_BUZZER_DEATH_AIR 157
-#define CLIP_BUZZER_DEATH_LAND 158
-#define CLIP_BUZZER_FLY 159
-#define CLIP_BUZZER_TURNTOFLY 160
-#define CLIP_BUZZER_TURNTOIDLE 161
-#define CLIP_TIKTIK_DEATH_AIR 162
-#define CLIP_TIKTIK_DEATH_LAND 163
-#define CLIP_TIKTIK_STUN 164
-#define CLIP_TIKTIK_WALK 165
-#define CLIP_GRUZZER_DEATH_AIR 166
-#define CLIP_GRUZZER_DEATH_LAND 167
-#define CLIP_GRUZZER_FLY 168
-#define CLIP_ASPID_DEATH_AIR 169
-#define CLIP_ASPID_FIRE_LONG 170
-#define CLIP_ASPID_FLY 171
-#define CLIP_ASPID_TURNTOFLY 172
-#define CLIP_BALDUR_DEATH_AIR 173
-#define CLIP_BALDUR_DEATH_LAND 174
-#define CLIP_BALDUR_IDLE 175
-#define CLIP_BALDUR_ROLL 176
-#define CLIP_BALDUR_START 177
-#define CLIP_BALDUR_STOP 178
-#define CLIP_ELDERBALDUR_CLOSE1 179
-#define CLIP_ELDERBALDUR_CLOSE2 180
-#define CLIP_ELDERBALDUR_CLOSED 181
-#define CLIP_ELDERBALDUR_DEATH 182
-#define CLIP_ELDERBALDUR_DEATH_STUN 183
-#define CLIP_ELDERBALDUR_HIT 184
-#define CLIP_ELDERBALDUR_IDLE 185
-#define CLIP_ELDERBALDUR_OPEN 186
-#define CLIP_ELDERBALDUR_SHOOT_ANTIC 187
-#define CLIP_ELDERBALDUR_SHOOT_CD 188
-#define CLIP_HUSK_ATTACK_ANTICIPATE 189
-#define CLIP_HUSK_ATTACK_COOLDOWN 190
-#define CLIP_HUSK_ATTACK_LUNGE 191
-#define CLIP_HUSK_DEATH_AIR 192
-#define CLIP_HUSK_DEATH_LAND 193
-#define CLIP_HUSK_IDLE 194
-#define CLIP_HUSK_TURN 195
-#define CLIP_HUSK_WALK 196
-#define CLIP_BARGER_ATTACK_ANTICIPATE 197
-#define CLIP_BARGER_ATTACK_COOLDOWN 198
-#define CLIP_BARGER_ATTACK_LUNGE 199
-#define CLIP_BARGER_DEATH_AIR 200
-#define CLIP_BARGER_DEATH_LAND 201
-#define CLIP_BARGER_IDLE 202
-#define CLIP_BARGER_TURN 203
-#define CLIP_BARGER_WALK 204
-#define CLIP_HORNHEAD_ATTACK_ANTICIPATE 205
-#define CLIP_HORNHEAD_ATTACK_COOLDOWN 206
-#define CLIP_HORNHEAD_ATTACK_LUNGE 207
-#define CLIP_HORNHEAD_DEATH_AIR 208
-#define CLIP_HORNHEAD_DEATH_LAND 209
-#define CLIP_HORNHEAD_IDLE 210
-#define CLIP_HORNHEAD_TURN 211
-#define CLIP_HORNHEAD_WALK 212
-#define CLIP_MOSSRUNNER_ATTACK_ANTICIPATE 213
-#define CLIP_MOSSRUNNER_ATTACK_COOLDOWN 214
-#define CLIP_MOSSRUNNER_ATTACK_LUNGE 215
-#define CLIP_MOSSRUNNER_DEATH_AIR 216
-#define CLIP_MOSSRUNNER_DEATH_LAND 217
-#define CLIP_MOSSRUNNER_IDLE 218
-#define CLIP_MOSSRUNNER_TURN 219
-#define CLIP_MOSSRUNNER_WALK 220
-#define CLIP_LEAPER_ATTACK 221
-#define CLIP_LEAPER_DEATH_AIR 222
-#define CLIP_LEAPER_DEATH_LAND 223
-#define CLIP_LEAPER_IDLE 224
-#define CLIP_LEAPER_LAND 225
-#define CLIP_LEAPER_TURN 226
-#define CLIP_LEAPER_WALK 227
-#define CLIP_GUARD_ANTICIPATE 228
-#define CLIP_GUARD_ATTACK2 229
-#define CLIP_GUARD_DEATH_AIR 230
-#define CLIP_GUARD_DEATH_LAND 231
-#define CLIP_GUARD_DORMANT 232
-#define CLIP_GUARD_IDLE 233
-#define CLIP_GUARD_RUN 234
-#define CLIP_GUARD_STARTLE 235
-#define CLIP_GUARD_STOMP_ANTIC 236
-#define CLIP_GUARD_STOMP_JUMP 237
-#define CLIP_GUARD_STOMP_LAND 238
-#define CLIP_GUARD_STOP_RUN 239
-#define CLIP_GUARD_STOP_WALK 240
-#define CLIP_GUARD_SWIPE 241
-#define CLIP_GUARD_TURN 242
-#define CLIP_GUARD_WAKE 243
-#define CLIP_GUARD_WALK 244
-#define CLIP_FK_ATTACK 245
-#define CLIP_FK_ATTACK_ANTIC 246
-#define CLIP_FK_ATTACK_RECOVER 247
-#define CLIP_FK_BLANK 248
-#define CLIP_FK_BODY 249
-#define CLIP_FK_DEATH_FALL 250
-#define CLIP_FK_DEATH_HEAD_1 251
-#define CLIP_FK_DEATH_HEAD_2 252
-#define CLIP_FK_DEATH_LAND 253
-#define CLIP_FK_DEATH_SPAZ 254
-#define CLIP_FK_IDLE 255
-#define CLIP_FK_JUMP 256
-#define CLIP_FK_JUMP_ANTIC 257
-#define CLIP_FK_JUMP_ATTACK_HIT_1 258
-#define CLIP_FK_JUMP_ATTACK_HIT_2 259
-#define CLIP_FK_JUMP_ATTACK_HIT_3 260
-#define CLIP_FK_JUMP_ATTACK_UP 261
-#define CLIP_FK_LAND 262
-#define CLIP_FK_RAGE 263
-#define CLIP_FK_RUN 264
-#define CLIP_FK_RUN_ANTIC 265
-#define CLIP_FK_STUN_HIT 266
-#define CLIP_FK_STUN_OPEN 267
-#define CLIP_FK_STUN_OPENED 268
-#define CLIP_FK_STUN_RECOVER 269
-#define CLIP_FK_STUN_ROLL 270
-#define CLIP_FK_STUN_ROLL_END 271
-#define CLIP_FK_TURN 272
-#define CLIP_FKHEAD_DEATH_LAND 273
-#define CLIP_FKHEAD_HEAD_HIT 274
-#define CLIP_FKHEAD_HEAD_IDLE 275
-#define CLIP_FKHEAD_HEAD_SPAZ 276
-#define CLIP_HATCHER_DEATH_AIR 277
-#define CLIP_HATCHER_DEATH_LAND 278
-#define CLIP_HATCHER_FIRE 279
-#define CLIP_HATCHER_FLY 280
-#define CLIP_HATCHLING_FLY 281
-#define CLIP_SLUG_BOUNCE 282
-#define CLIP_SLUG_DEATH_AIR 283
-#define CLIP_SLUG_DEATH_LAND 284
-#define CLIP_SLUG_IDLE_TODOWN 285
-#define CLIP_SLUG_IDLE_TOUP 286
-#define CLIP_SLUG_IDLE_UP 287
-#define CLIP_SLUG_RUN 288
-#define CLIP_SLUG_STARTLE 289
-#define CLIP_GFLY_BURST 290
-#define CLIP_GFLY_CHARGE 291
-#define CLIP_GFLY_CHARGE_ANTIC 292
-#define CLIP_GFLY_CHARGE_RECOVER 293
-#define CLIP_GFLY_DEATH 294
-#define CLIP_GFLY_FALL 295
-#define CLIP_GFLY_FLY 296
-#define CLIP_GFLY_GURGLE_LOOP 297
-#define CLIP_GFLY_GURGLE_ONCE 298
-#define CLIP_GFLY_SLAM_DOWN 299
-#define CLIP_GFLY_SLAM_END 300
-#define CLIP_GFLY_SLAM_UP 301
-#define CLIP_GFLY_SLEEP 302
-#define CLIP_GFLY_STOP 303
-#define CLIP_GFLY_WAKE 304
-#define CLIP_GFLY_WIGGLE 305
-#define CLIP_BGATE_BG_OPENED 306
-#define CLIP_BGATE_BG_CLOSE_1 307
-#define CLIP_BGATE_BG_CLOSE_2 308
-#define CLIP_BGATE_BG_OPEN 309
-#define CLIP_BGATE_BG_CLOSED 310
-#define CLIP_BGATE_BONE_GATE_OPENED 311
-#define CLIP_BGATE_BONE_GATE_CLOSE 312
-#define CLIP_BGATE_BONE_GATE_CLOSED 313
-#define CLIP_BGATE_BONE_GATE_OPEN 314
-#define CLIP_DRIP_IDLE 315
-#define CLIP_DRIP_DRIP 316
-#define CLIP_DRIP_FALL 317
-#define CLIP_DRIP_IMPACT 318
-#define CLIP_BULLET_IDLE 319
-#define CLIP_BULLET_IMPACT 320
-#define CLIP_BULLET_SHOCKWAVE_SPURT 321
-#define CLIP_PROP0_WATERFALL_LOOP 322
-#define CLIP_PROP1_TORCH2 323
-#define CLIP_PROP1_TORCH3 324
-#define SPRITE_HERO_LIGHT 1323
-#define SPRITE_DIALOGUE_BACKBOARD 1324
-#define SPRITE_PROMPT_SHADOW 1325
-#define SPRITE_CORPSE_NAIL 1326
-#define SPRITE_FK_BARREL 1327
-#define SPRITE_FK_STAFF 1328
-#define SPRITE_DIGIT0 1515
+#define CLIP_HUD_BLUE_BREAK_FAST 99
+#define CLIP_HUD_HUD_FRAME 100
+#define CLIP_HUD_HUD_FRAME_IDLE 101
+#define CLIP_HUD_HUD_FRAME_CRACKAPPEAR 102
+#define CLIP_HUD_HUD_FRAME_CRACKED 103
+#define CLIP_HUD_COIN_APPEAR 104
+#define CLIP_HUD_COIN_IDLE 105
+#define CLIP_HUD_COIN_GET 106
+#define CLIP_HUD_SOUL_BURST 107
+#define CLIP_LIQUID_FILL 108
+#define CLIP_LIQUID_IDLE 109
+#define CLIP_LIQUID_SHRINK 110
+#define CLIP_LIQUID_DRAIN 111
+#define CLIP_GEO_SMALL_IDLE 112
+#define CLIP_GEO_SMALL_AIR 113
+#define CLIP_GEO_MED_IDLE 114
+#define CLIP_GEO_MED_AIR 115
+#define CLIP_GEO_LARGE_IDLE 116
+#define CLIP_GEO_LARGE_AIR 117
+#define CLIP_DIALOGUE_ARROW_UP 118
+#define CLIP_DIALOGUE_ARROW_DOWN 119
+#define CLIP_DIALOGUE_STOP_UP 120
+#define CLIP_DIALOGUE_STOP_DOWN 121
+#define CLIP_DIALOGUE_FLEUR_TOP_UP 122
+#define CLIP_DIALOGUE_FLEUR_TOP_DOWN 123
+#define CLIP_DIALOGUE_FLEUR_BOT_UP 124
+#define CLIP_DIALOGUE_FLEUR_BOT_DOWN 125
+#define CLIP_PROMPT_UP 126
+#define CLIP_PROMPT_DOWN 127
+#define CLIP_PROMPT_BLANK 128
+#define CLIP_SHADE_IDLE 129
+#define CLIP_SHADE_STARTLE 130
+#define CLIP_SHADE_FLY 131
+#define CLIP_SHADE_TURNTOFLY 132
+#define CLIP_SHADE_TURNTOIDLE 133
+#define CLIP_SHADE_SLASH_ANTIC 134
+#define CLIP_SHADE_SLASH 135
+#define CLIP_SHADE_SLASH_CD 136
+#define CLIP_SHADE_SLASH_EFFECT 137
+#define CLIP_SHADE_CAST_ANTIC 138
+#define CLIP_SHADE_CAST_CHARGE 139
+#define CLIP_SHADE_CAST 140
+#define CLIP_SHADE_RETREAT_START 141
+#define CLIP_SHADE_RETREAT_END 142
+#define CLIP_SHADE_DEATH_START 143
+#define CLIP_SHADE_DEATH 144
+#define CLIP_SHADE_DEPART 145
+#define CLIP_SHADE_APPEAR 146
+#define CLIP_SHADE_FIREBALL 147
+#define CLIP_SHADE_FIREBALL_END 148
+#define CLIP_SHADE_CAST_RING 149
+#define CLIP_CRAWLER_WALK 150
+#define CLIP_CRAWLER_TURN 151
+#define CLIP_CRAWLER_IDLE 152
+#define CLIP_CRAWLER_DEATH_AIR 153
+#define CLIP_CRAWLER_DEATH_LAND 154
+#define CLIP_BUZZER_CHASE 155
+#define CLIP_BUZZER_IDLE 156
+#define CLIP_BUZZER_STARTLE 157
+#define CLIP_BUZZER_DEATH_AIR 158
+#define CLIP_BUZZER_DEATH_LAND 159
+#define CLIP_BUZZER_FLY 160
+#define CLIP_BUZZER_TURNTOFLY 161
+#define CLIP_BUZZER_TURNTOIDLE 162
+#define CLIP_TIKTIK_DEATH_AIR 163
+#define CLIP_TIKTIK_DEATH_LAND 164
+#define CLIP_TIKTIK_STUN 165
+#define CLIP_TIKTIK_WALK 166
+#define CLIP_GRUZZER_DEATH_AIR 167
+#define CLIP_GRUZZER_DEATH_LAND 168
+#define CLIP_GRUZZER_FLY 169
+#define CLIP_ASPID_DEATH_AIR 170
+#define CLIP_ASPID_FIRE_LONG 171
+#define CLIP_ASPID_FLY 172
+#define CLIP_ASPID_TURNTOFLY 173
+#define CLIP_BALDUR_DEATH_AIR 174
+#define CLIP_BALDUR_DEATH_LAND 175
+#define CLIP_BALDUR_IDLE 176
+#define CLIP_BALDUR_ROLL 177
+#define CLIP_BALDUR_START 178
+#define CLIP_BALDUR_STOP 179
+#define CLIP_ELDERBALDUR_CLOSE1 180
+#define CLIP_ELDERBALDUR_CLOSE2 181
+#define CLIP_ELDERBALDUR_CLOSED 182
+#define CLIP_ELDERBALDUR_DEATH 183
+#define CLIP_ELDERBALDUR_DEATH_STUN 184
+#define CLIP_ELDERBALDUR_HIT 185
+#define CLIP_ELDERBALDUR_IDLE 186
+#define CLIP_ELDERBALDUR_OPEN 187
+#define CLIP_ELDERBALDUR_SHOOT_ANTIC 188
+#define CLIP_ELDERBALDUR_SHOOT_CD 189
+#define CLIP_HUSK_ATTACK_ANTICIPATE 190
+#define CLIP_HUSK_ATTACK_COOLDOWN 191
+#define CLIP_HUSK_ATTACK_LUNGE 192
+#define CLIP_HUSK_DEATH_AIR 193
+#define CLIP_HUSK_DEATH_LAND 194
+#define CLIP_HUSK_IDLE 195
+#define CLIP_HUSK_TURN 196
+#define CLIP_HUSK_WALK 197
+#define CLIP_BARGER_ATTACK_ANTICIPATE 198
+#define CLIP_BARGER_ATTACK_COOLDOWN 199
+#define CLIP_BARGER_ATTACK_LUNGE 200
+#define CLIP_BARGER_DEATH_AIR 201
+#define CLIP_BARGER_DEATH_LAND 202
+#define CLIP_BARGER_IDLE 203
+#define CLIP_BARGER_TURN 204
+#define CLIP_BARGER_WALK 205
+#define CLIP_HORNHEAD_ATTACK_ANTICIPATE 206
+#define CLIP_HORNHEAD_ATTACK_COOLDOWN 207
+#define CLIP_HORNHEAD_ATTACK_LUNGE 208
+#define CLIP_HORNHEAD_DEATH_AIR 209
+#define CLIP_HORNHEAD_DEATH_LAND 210
+#define CLIP_HORNHEAD_IDLE 211
+#define CLIP_HORNHEAD_TURN 212
+#define CLIP_HORNHEAD_WALK 213
+#define CLIP_MOSSRUNNER_ATTACK_ANTICIPATE 214
+#define CLIP_MOSSRUNNER_ATTACK_COOLDOWN 215
+#define CLIP_MOSSRUNNER_ATTACK_LUNGE 216
+#define CLIP_MOSSRUNNER_DEATH_AIR 217
+#define CLIP_MOSSRUNNER_DEATH_LAND 218
+#define CLIP_MOSSRUNNER_IDLE 219
+#define CLIP_MOSSRUNNER_TURN 220
+#define CLIP_MOSSRUNNER_WALK 221
+#define CLIP_LEAPER_ATTACK 222
+#define CLIP_LEAPER_DEATH_AIR 223
+#define CLIP_LEAPER_DEATH_LAND 224
+#define CLIP_LEAPER_IDLE 225
+#define CLIP_LEAPER_LAND 226
+#define CLIP_LEAPER_TURN 227
+#define CLIP_LEAPER_WALK 228
+#define CLIP_GUARD_ANTICIPATE 229
+#define CLIP_GUARD_ATTACK2 230
+#define CLIP_GUARD_DEATH_AIR 231
+#define CLIP_GUARD_DEATH_LAND 232
+#define CLIP_GUARD_DORMANT 233
+#define CLIP_GUARD_IDLE 234
+#define CLIP_GUARD_RUN 235
+#define CLIP_GUARD_STARTLE 236
+#define CLIP_GUARD_STOMP_ANTIC 237
+#define CLIP_GUARD_STOMP_JUMP 238
+#define CLIP_GUARD_STOMP_LAND 239
+#define CLIP_GUARD_STOP_RUN 240
+#define CLIP_GUARD_STOP_WALK 241
+#define CLIP_GUARD_SWIPE 242
+#define CLIP_GUARD_TURN 243
+#define CLIP_GUARD_WAKE 244
+#define CLIP_GUARD_WALK 245
+#define CLIP_FK_ATTACK 246
+#define CLIP_FK_ATTACK_ANTIC 247
+#define CLIP_FK_ATTACK_RECOVER 248
+#define CLIP_FK_BLANK 249
+#define CLIP_FK_BODY 250
+#define CLIP_FK_DEATH_FALL 251
+#define CLIP_FK_DEATH_HEAD_1 252
+#define CLIP_FK_DEATH_HEAD_2 253
+#define CLIP_FK_DEATH_LAND 254
+#define CLIP_FK_DEATH_SPAZ 255
+#define CLIP_FK_IDLE 256
+#define CLIP_FK_JUMP 257
+#define CLIP_FK_JUMP_ANTIC 258
+#define CLIP_FK_JUMP_ATTACK_HIT_1 259
+#define CLIP_FK_JUMP_ATTACK_HIT_2 260
+#define CLIP_FK_JUMP_ATTACK_HIT_3 261
+#define CLIP_FK_JUMP_ATTACK_UP 262
+#define CLIP_FK_LAND 263
+#define CLIP_FK_RAGE 264
+#define CLIP_FK_RUN 265
+#define CLIP_FK_RUN_ANTIC 266
+#define CLIP_FK_STUN_HIT 267
+#define CLIP_FK_STUN_OPEN 268
+#define CLIP_FK_STUN_OPENED 269
+#define CLIP_FK_STUN_RECOVER 270
+#define CLIP_FK_STUN_ROLL 271
+#define CLIP_FK_STUN_ROLL_END 272
+#define CLIP_FK_TURN 273
+#define CLIP_FKHEAD_DEATH_LAND 274
+#define CLIP_FKHEAD_HEAD_HIT 275
+#define CLIP_FKHEAD_HEAD_IDLE 276
+#define CLIP_FKHEAD_HEAD_SPAZ 277
+#define CLIP_HATCHER_DEATH_AIR 278
+#define CLIP_HATCHER_DEATH_LAND 279
+#define CLIP_HATCHER_FIRE 280
+#define CLIP_HATCHER_FLY 281
+#define CLIP_HATCHLING_FLY 282
+#define CLIP_SLUG_BOUNCE 283
+#define CLIP_SLUG_DEATH_AIR 284
+#define CLIP_SLUG_DEATH_LAND 285
+#define CLIP_SLUG_IDLE_TODOWN 286
+#define CLIP_SLUG_IDLE_TOUP 287
+#define CLIP_SLUG_IDLE_UP 288
+#define CLIP_SLUG_RUN 289
+#define CLIP_SLUG_STARTLE 290
+#define CLIP_GFLY_BURST 291
+#define CLIP_GFLY_CHARGE 292
+#define CLIP_GFLY_CHARGE_ANTIC 293
+#define CLIP_GFLY_CHARGE_RECOVER 294
+#define CLIP_GFLY_DEATH 295
+#define CLIP_GFLY_FALL 296
+#define CLIP_GFLY_FLY 297
+#define CLIP_GFLY_GURGLE_LOOP 298
+#define CLIP_GFLY_GURGLE_ONCE 299
+#define CLIP_GFLY_SLAM_DOWN 300
+#define CLIP_GFLY_SLAM_END 301
+#define CLIP_GFLY_SLAM_UP 302
+#define CLIP_GFLY_SLEEP 303
+#define CLIP_GFLY_STOP 304
+#define CLIP_GFLY_WAKE 305
+#define CLIP_GFLY_WIGGLE 306
+#define CLIP_BGATE_BG_OPENED 307
+#define CLIP_BGATE_BG_CLOSE_1 308
+#define CLIP_BGATE_BG_CLOSE_2 309
+#define CLIP_BGATE_BG_OPEN 310
+#define CLIP_BGATE_BG_CLOSED 311
+#define CLIP_BGATE_BONE_GATE_OPENED 312
+#define CLIP_BGATE_BONE_GATE_CLOSE 313
+#define CLIP_BGATE_BONE_GATE_CLOSED 314
+#define CLIP_BGATE_BONE_GATE_OPEN 315
+#define CLIP_COCOON_COCOON_IDLE 316
+#define CLIP_COCOON_COCOON_SWEAT 317
+#define CLIP_COCOON_SCUTTLER_LAND 318
+#define CLIP_COCOON_SCUTTLER_RUN 319
+#define CLIP_FX_SPLAT 320
+#define CLIP_FX_SPLAT2 321
+#define CLIP_DRIP_IDLE 322
+#define CLIP_DRIP_DRIP 323
+#define CLIP_DRIP_FALL 324
+#define CLIP_DRIP_IMPACT 325
+#define CLIP_BULLET_IDLE 326
+#define CLIP_BULLET_IMPACT 327
+#define CLIP_BULLET_SHOCKWAVE_SPURT 328
+#define CLIP_PROP0_WATERFALL_LOOP 329
+#define CLIP_PROP1_TORCH2 330
+#define CLIP_PROP1_TORCH3 331
+#define SPRITE_HERO_LIGHT 1360
+#define SPRITE_DIALOGUE_BACKBOARD 1361
+#define SPRITE_PROMPT_SHADOW 1362
+#define SPRITE_CORPSE_NAIL 1363
+#define SPRITE_FK_BARREL 1364
+#define SPRITE_FK_STAFF 1365
+#define SPRITE_DIGIT0 1553
#define STYLE_DIALOGUE 0
#define STYLE_PROMPT 1
#define TEXT_K 1.333333f
@@ -413,7 +420,7 @@
#define EK_SLUG 19
#define EK_GFLY 20
#define NUM_KINDS 21
-#define KIND_TABLE {{0}, {EF_CRAWLER, {-1, 150, 149, -1, -1, -1, -1, -1, -1, -1, -1, 152, 153}}, {EF_BUZZER, {155, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 157, 158}}, {EF_SHADE, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}}, {EF_CLIMBER, {-1, -1, 165, 164, -1, -1, -1, -1, -1, -1, -1, 162, 163}}, {EF_BOUNCER, {-1, -1, -1, 168, -1, -1, -1, -1, -1, -1, -1, 166, 167}}, {EF_SPITTER, {-1, -1, -1, 171, 172, 170, -1, -1, -1, -1, -1, 169, -1}}, {EF_ROLLER, {175, -1, -1, 177, 176, 178, -1, -1, -1, -1, -1, 173, 174}}, {EF_BLOCKER, {185, -1, -1, 181, 186, 179, 180, 187, 188, 184, 183, -1, 182}}, {EF_HUSK, {194, 195, 196, 189, 191, 190, -1, -1, -1, -1, -1, 192, 193}}, {EF_HUSK, {202, 203, 204, 197, 199, 198, -1, -1, -1, -1, -1, 200, 201}}, {EF_HUSK, {210, 211, 212, 205, 207, 206, -1, -1, -1, -1, -1, 208, 209}}, {EF_HUSK, {218, 219, 220, 213, 215, 214, -1, -1, -1, -1, -1, 216, 217}}, {EF_LEAPER, {224, 226, 227, 221, 225, -1, -1, -1, -1, -1, -1, 222, 223}}, {EF_GUARD, {233, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 230, 231}}, {EF_FK, {255, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 253}}, {EF_FKHEAD, {275, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 273}}, {EF_HATCHER, {-1, -1, -1, 280, 279, -1, -1, -1, -1, -1, -1, 277, 278}}, {EF_HATCHLING, {-1, -1, -1, 281, -1, -1, -1, -1, -1, -1, -1, -1, -1}}, {EF_SLUG, {287, -1, -1, 285, 286, 289, 288, 282, -1, -1, -1, 283, 284}}, {EF_GFLY, {302, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}}}
+#define KIND_TABLE {{0}, {EF_CRAWLER, {-1, 151, 150, -1, -1, -1, -1, -1, -1, -1, -1, 153, 154}}, {EF_BUZZER, {156, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 158, 159}}, {EF_SHADE, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}}, {EF_CLIMBER, {-1, -1, 166, 165, -1, -1, -1, -1, -1, -1, -1, 163, 164}}, {EF_BOUNCER, {-1, -1, -1, 169, -1, -1, -1, -1, -1, -1, -1, 167, 168}}, {EF_SPITTER, {-1, -1, -1, 172, 173, 171, -1, -1, -1, -1, -1, 170, -1}}, {EF_ROLLER, {176, -1, -1, 178, 177, 179, -1, -1, -1, -1, -1, 174, 175}}, {EF_BLOCKER, {186, -1, -1, 182, 187, 180, 181, 188, 189, 185, 184, -1, 183}}, {EF_HUSK, {195, 196, 197, 190, 192, 191, -1, -1, -1, -1, -1, 193, 194}}, {EF_HUSK, {203, 204, 205, 198, 200, 199, -1, -1, -1, -1, -1, 201, 202}}, {EF_HUSK, {211, 212, 213, 206, 208, 207, -1, -1, -1, -1, -1, 209, 210}}, {EF_HUSK, {219, 220, 221, 214, 216, 215, -1, -1, -1, -1, -1, 217, 218}}, {EF_LEAPER, {225, 227, 228, 222, 226, -1, -1, -1, -1, -1, -1, 223, 224}}, {EF_GUARD, {234, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 231, 232}}, {EF_FK, {256, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 254}}, {EF_FKHEAD, {276, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 274}}, {EF_HATCHER, {-1, -1, -1, 281, 280, -1, -1, -1, -1, -1, -1, 278, 279}}, {EF_HATCHLING, {-1, -1, -1, 282, -1, -1, -1, -1, -1, -1, -1, -1, -1}}, {EF_SLUG, {288, -1, -1, 286, 287, 290, 289, 283, -1, -1, -1, 284, 285}}, {EF_GFLY, {303, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}}}
#define TXT_PROMPT_LISTEN 0
#define TXT_PROMPT_REST 1
#define TXT_PROMPT_INSPECT 2
diff --git a/games/hollowknight/src/enemy.c b/games/hollowknight/src/enemy.c
index 7925703c..22ada7d1 100644
--- a/games/hollowknight/src/enemy.c
+++ b/games/hollowknight/src/enemy.c
@@ -173,7 +173,7 @@ void geo_fling_at(int type, int n, float x, float y, float smin, float smax, flo
}
/* ObjectBounce: off what it hit, at its speed before, times the bounce factor (and a little chance) */
-static void bounce(Body *b, float pvx, float pvy, int had, float factor) {
+void body_bounce(Body *b, float pvx, float pvy, int had, float factor) {
if (factor < 0 || b->ncontacts <= had) return;
float speed = sqrtf(pvx * pvx + pvy * pvy);
if (speed <= 1) return;
@@ -202,7 +202,7 @@ static void geo_tick(void) {
int had = b.ncontacts;
body_step(&b, DT);
bool hit = b.ncontacts > had;
- if (hit) bounce(&b, pvx, pvy, had, geo_kinds[g->type].bounce);
+ if (hit) body_bounce(&b, pvx, pvy, had, geo_kinds[g->type].bounce);
g->x = b.x, g->y = b.y, g->vx = b.vx, g->vy = b.vy;
g->ncontacts = (uint8_t)(b.ncontacts < GEO_CONTACTS ? b.ncontacts : GEO_CONTACTS);
for (int c = 0; c < g->ncontacts; c++) g->ccol[c] = b.ccol[c], g->cnx[c] = b.cnx[c], g->cny[c] = b.cny[c];
@@ -3779,7 +3779,7 @@ static void gfly_corpse_tick(void) {
float pvx = b->vx, pvy = b->vy;
int had = b->ncontacts;
body_step(b, DT);
- bounce(b, pvx, pvy, had, 0.5f); /* (ObjectBounce) */
+ body_bounce(b, pvx, pvy, had, 0.5f); /* (ObjectBounce) */
gm.banim.events = 0;
anim_update(&gm.banim, DT);
gm.bt += DT;
@@ -4077,12 +4077,12 @@ void enemies_fixed(void) {
e->st = CS_DEATH_ANIM;
if (FSM(e) == EF_HATCHER) hatcher_corpse_smash(e);
} else {
- bounce(&e->body, pvx, pvy, had, cbounce);
+ body_bounce(&e->body, pvx, pvy, had, cbounce);
anim_play(&e->anim, kinds[e->kind].clip[R_DEATH_LAND]);
e->st = CS_LANDED;
}
} else
- bounce(&e->body, pvx, pvy, had, cbounce);
+ body_bounce(&e->body, pvx, pvy, had, cbounce);
if (e->body.y < -10) e->mode = EM_OFF;
}
}
diff --git a/games/hollowknight/src/game.h b/games/hollowknight/src/game.h
index 2bb2c1db..e19ab2c8 100644
--- a/games/hollowknight/src/game.h
+++ b/games/hollowknight/src/game.h
@@ -54,7 +54,7 @@ void save_set_respawn(const char *marker, bool facing_right); /* (Bench Contro
enum { ENT_CAMLOCK = 1, ENT_GATE, ENT_HAZARD_MARKER, ENT_RESPAWN, ENT_HAZARD_TRIGGER, ENT_MASK, ENT_DAMAGE, ENT_SHAPE,
ENT_BOX, ENT_OBJ, ENT_PIECE, ENT_SHADE_MARKER }; /* (shape, box, piece: more of the record before) */
enum { OK_BREAKABLE = 1, OK_ENEMY, OK_GREAT_DOOR, OK_GEO_ROCK, OK_CHEST, OK_BENCH, OK_BATTLE, OK_FK_FLOOR, OK_BGATE,
- OK_ARENA, OK_EVENT, OK_SUMMON, OK_COND, OK_PROP, OK_DRIP }; /* objects (ENT_OBJ's flags) */
+ OK_ARENA, OK_EVENT, OK_SUMMON, OK_COND, OK_PROP, OK_DRIP, OK_COCOON }; /* objects (ENT_OBJ's flags) */
/* an enemy record's s1: starts alert (or first); startles; one of an arena's Pre Battle Enemies; its death counts for its arena; gone once its arena's
* fight is over; spawned by its mother's burster; there only once its arena's fight is over; its FSMs off till near
* the camera (FSMActivator); then its death's effects
@@ -117,6 +117,7 @@ int enemies_nail(const float *pts, int npts, float direction, int damage);
int enemies_touch_hero(float x0, float y0, float x1, float y1, int *side); /* -> its damage, 0: none */
void enemies_hero_leave(void); /* HERO LEAVE (the Knight dead): the shade departs */
/* geo of a size (0 small, 1 medium, 2 large) flung from (x, y), each from a little about it (FlingUtils) */
+void body_bounce(Body *b, float pvx, float pvy, int had, float factor); /* ObjectBounce */
void geo_fling_at(int type, int n, float x, float y, float smin, float smax, float amin, float amax, float spread);
int cardinal(float degrees); /* DirectionUtils.GetCardinalDirection */
const Ent *room_ents(int *n);
@@ -217,6 +218,7 @@ void hero_finished_entering_scene(bool set_hazard_marker);
void hero_leave_scene(int gate); /* LeaveScene: walking, jumping or falling out through the gate */
/* EnterScene: the Knight through the room's entry gate (its record, kind, place, entry offset, G_* flags) after delay */
void hero_enter_scene(int gate_ent, int gate, float gx, float gy, float ox, float oy, uint8_t flags, float delay);
+void hero_add_blue_health(void); /* (a lifeblood mask more) */
void hero_take_damage(int side, int damage, int hazard); /* (side: where the damage comes from, SIDE_LEFT/RIGHT) */
void hero_recoil_unfreeze(void); /* the end of StartRecoil, after the freeze */
void hero_hazard_respawn(void); /* HeroController.HazardRespawn */
diff --git a/games/hollowknight/src/hero.c b/games/hollowknight/src/hero.c
index eb25f32b..e194e7ee 100644
--- a/games/hollowknight/src/hero.c
+++ b/games/hollowknight/src/hero.c
@@ -1236,6 +1236,16 @@ void hero_recoil_unfreeze(void) {
g_hero.cs.recoiling = true;
}
+/* PlayerData.TakeHealth: lifeblood first */
+static void take_health(int damage) {
+ if (g_pd.health_blue > 0) {
+ int rest = damage - g_pd.health_blue;
+ g_pd.health_blue = (int8_t)(g_pd.health_blue > damage ? g_pd.health_blue - damage : 0);
+ if (rest > 0) take_health(rest);
+ } else
+ g_pd.health = (int8_t)(g_pd.health > damage ? g_pd.health - damage : 0);
+}
+
void hero_take_damage(int side, int damage, int hazard) {
Hero *h = &g_hero;
if (damage <= 0) return;
@@ -1245,7 +1255,7 @@ void hero_take_damage(int side, int damage, int hazard) {
cancel_attack();
if (h->cs.recoiling_left || h->cs.recoiling_right) cancel_recoil_horizontal();
if (h->cs.bouncing) cancel_bounce(), h->body.vy = 0;
- g_pd.health = (int8_t)(g_pd.health > damage ? g_pd.health - damage : 0);
+ take_health(damage);
if (g_pd.health == 0) {
hero_die();
return;
@@ -1254,7 +1264,7 @@ void hero_take_damage(int side, int damage, int hazard) {
else if (hazard != HAZ_LAVA) start_recoil(side);
} else if (h->cs.invulnerable && !h->cs.hazard_death && (hazard == HAZ_SPIKES || hazard == HAZ_ACID)) {
/* (spikes and acid hurt even through invulnerability) */
- g_pd.health = (int8_t)(g_pd.health > damage ? g_pd.health - damage : 0);
+ take_health(damage);
if (g_pd.health == 0) hero_die();
else die_from_hazard();
}
@@ -1308,7 +1318,16 @@ void hero_face(bool right) {
else face_left();
}
void hero_gravity(bool on) { affected_by_gravity(on); }
-void hero_max_health(void) { g_pd.health = g_pd.max_health; }
+/* MaxHealth: whole again, the lifeblood gone (UpdateBlueHealth) */
+void hero_max_health(void) {
+ g_pd.health = g_pd.max_health;
+ g_pd.health_blue = 0;
+}
+
+/* ADD BLUE HEALTH (Blue Health Control) */
+void hero_add_blue_health(void) {
+ if (g_pd.health_blue < 8) g_pd.health_blue++;
+}
/* FindGroundPoint: where the Knight stands on the ground below (x, y) (no ground: there) */
float hero_ground_y(float x, float y) {
diff --git a/games/hollowknight/src/hud.c b/games/hollowknight/src/hud.c
index bcc4d096..3647665f 100644
--- a/games/hollowknight/src/hud.c
+++ b/games/hollowknight/src/hud.c
@@ -5,6 +5,7 @@
#define DT 0.02f
#define MAX_MASKS 11
+#define MAX_BLUE 8
/* (Hud Canvas, then Health, Soul Orb, Geo Counter: their places) */
#define CANVAS_X (-8.71f)
@@ -22,6 +23,10 @@
static struct {
Anim mask[MAX_MASKS];
int8_t shown_health; /* what the masks show */
+ /* lifeblood (Blue Health: blue_health_display): each mask's state, its place's number (after the masks) */
+ Anim blue[MAX_BLUE];
+ uint8_t blue_st[MAX_BLUE];
+ int8_t shown_blue;
Anim frame, liquid, coin, burst;
bool burst_on;
float liquid_grey; /* (Liquid Control: grey while it cannot heal) */
@@ -46,9 +51,11 @@ void hud_soul_limiter(bool up) {
hd.burst_on = true;
}
+enum { BL_NONE, BL_APPEAR, BL_IDLE, BL_BREAK };
+
void hud_reset(void) {
memset(&hd, 0, sizeof hd);
- hd.shown_health = -1;
+ hd.shown_health = -1, hd.shown_blue = -1;
hd.scale = 1, hd.scale_t = SCALE_TIME;
anim_play(&hd.frame, g_pd.soul_limited ? CLIP_HUD_HUD_FRAME_CRACKED : CLIP_HUD_HUD_FRAME_IDLE);
anim_play(&hd.liquid, CLIP_LIQUID_IDLE);
@@ -71,6 +78,34 @@ void hud_tick(void) {
anim_update(a, DT);
if (a->events & ANIM_DONE) anim_play(a, a->clip == CLIP_HUD_HEALTH_BREAK ? CLIP_HUD_HEALTH_EMPTY : CLIP_HUD_HEALTH_IDLE);
}
+ /* lifeblood: one more appears after the rest; one lost breaks (all at once, fast, as the Knight is healed full) */
+ int blue = g_pd.health_blue > MAX_BLUE ? MAX_BLUE : g_pd.health_blue;
+ if (hd.shown_blue < 0) {
+ for (int i = 0; i < blue; i++) anim_play(&hd.blue[i], CLIP_HUD_BLUE_IDLE), hd.blue_st[i] = BL_IDLE;
+ hd.shown_blue = (int8_t)blue;
+ }
+ while (hd.shown_blue < blue) {
+ int i = hd.shown_blue++;
+ anim_play_from_frame(&hd.blue[i], CLIP_HUD_BLUE_APPEAR, 0), hd.blue_st[i] = BL_APPEAR;
+ }
+ bool full = blue == 0 && g_pd.health == g_pd.max_health;
+ while (hd.shown_blue > blue) {
+ int i = --hd.shown_blue;
+ anim_play_from_frame(&hd.blue[i], full ? CLIP_HUD_BLUE_BREAK_FAST : CLIP_HUD_BLUE_BREAK, 0), hd.blue_st[i] = BL_BREAK;
+ }
+ for (int i = 0; i < MAX_BLUE; i++) {
+ Anim *a = &hd.blue[i];
+ if (hd.blue_st[i] == BL_NONE) continue;
+ a->events = 0;
+ anim_update(a, DT);
+ if (!(a->events & ANIM_DONE)) continue;
+ if (hd.blue_st[i] == BL_BREAK) hd.blue_st[i] = BL_NONE;
+ else if (hd.blue_st[i] == BL_APPEAR) {
+ /* (Idle, from a frame at random) */
+ anim_play_from_frame(a, CLIP_HUD_BLUE_IDLE, (int)rand_range(0, 26.999f));
+ hd.blue_st[i] = BL_IDLE;
+ }
+ }
hd.frame.events = 0;
anim_update(&hd.frame, DT);
if ((hd.frame.events & ANIM_DONE) && hd.frame.clip == CLIP_HUD_HUD_FRAME_CRACKAPPEAR) anim_play(&hd.frame, CLIP_HUD_HUD_FRAME_CRACKED);
@@ -93,14 +128,16 @@ void hud_tick(void) {
else if (hd.liquid_grey > to) hd.liquid_grey = fmaxf(to, hd.liquid_grey - DT / 0.2f);
}
-static void hud_sprite(int sprite, float x, float y, float sx, uint8_t tint, int clip) {
+static void hud_sprite_s(int sprite, float x, float y, float sx, float sy, uint8_t tint, int clip) {
/* (on the canvas: about its corner, at its scale) */
float k = hd.scale;
Inst in;
- sprite_inst(sprite, CANVAS_X + (x - CANVAS_X) * k, CANVAS_Y + (y - CANVAS_Y) * k, 0, sx * k, k, tint, &in);
+ sprite_inst(sprite, CANVAS_X + (x - CANVAS_X) * k, CANVAS_Y + (y - CANVAS_Y) * k, 0, sx * k, sy * k, tint, &in);
gfx_hud(&in, clip);
}
+static void hud_sprite(int sprite, float x, float y, float sx, uint8_t tint, int clip) { hud_sprite_s(sprite, x, y, sx, 1, tint, clip); }
+
void hud_draw(void) {
if (!hd.started || hd.off) return;
float k = hd.scale;
@@ -117,6 +154,10 @@ void hud_draw(void) {
/* the masks */
int max = g_pd.max_health > MAX_MASKS ? MAX_MASKS : g_pd.max_health;
for (int i = 0; i < max; i++) hud_sprite(hd.mask[i].sprite, HEALTH_X - 10.32f + 0.94f * i, HEALTH_Y + 7.7f, 1, white, 0);
+ for (int i = 0; i < MAX_BLUE; i++)
+ if (hd.blue_st[i] != BL_NONE)
+ hud_sprite_s(hd.blue[i].sprite, HEALTH_X - 10.32f + 0.94f * (max + i), HEALTH_Y + 7.68f, 0.75f / 0.7135f, 0.75f / 0.7135f,
+ white, 0); /* (its frames at the masks' 0.7135) */
/* geo: the coin, the count (TrajanPro, its left at the text's place) */
hud_sprite(hd.coin.sprite, HEALTH_X - 10.33f, HEALTH_Y + 6.61f, 1, white, 0);
char buf[12];
diff --git a/games/hollowknight/src/obj.c b/games/hollowknight/src/obj.c
index 78b608dc..d0c65b2d 100644
--- a/games/hollowknight/src/obj.c
+++ b/games/hollowknight/src/obj.c
@@ -532,12 +532,191 @@ static void drip_draw(const Obj *o, const Ent *e) {
gfx_actor(&in, SORT_KEY(e->group, (int)e->a - 32768));
}
+/* ---------------------------------------------------------------- lifeblood cocoons (HealthCocoon) and their scuttlers
+ * (ScuttlerControl, Health Scuttler): hit, a cocoon breaks and lets out two that run from the Knight; each one hit
+ * gives him a lifeblood mask a moment later */
+#define MAX_SCUTTLERS 4
+enum { CO_IDLE, CO_SWEAT, CO_BROKEN };
+enum { SC_OFF, SC_AIR, SC_LAND, SC_RUN, SC_BOUNCE, SC_DEAD };
+typedef struct {
+ uint8_t st;
+ bool splat_on;
+ Body body;
+ Anim anim, splat;
+ float sx, max_speed, t, born; /* (its scale; Run's top speed; a timer; how long it has been out) */
+} Scuttler;
+static Scuttler scuttlers[MAX_SCUTTLERS];
+static Anim cocoon_fx; /* (a broken cocoon's splat effect: one a room) */
+static bool cocoon_fx_on;
+
+static const Ent *cocoon_splat(const Ent *e) { return e + 1 + e->s1 + e->s0; }
+
+static void cocoon_broken(Obj *o, const Ent *e) {
+ /* SetBroken: its sprite off, the children it hides off, its colliders off */
+ o->state = CO_BROKEN;
+ if (e->group2) group_fade(e->group2, 0, 0);
+ for (int c = e->a; c < e->a + e->group; c++) phys_collider_enable(c, false);
+}
+
+static void cocoon_enter(Obj *o, const Ent *e) {
+ anim_play(&o->anim, CLIP_COCOON_COCOON_IDLE);
+ o->state = CO_IDLE, o->t = rand_range(e->p0, e->p1);
+ if (persist_get(e->persist)) cocoon_broken(o, e);
+}
+
+static void cocoon_hit(Obj *o, const Ent *e) {
+ if (o->state == CO_BROKEN) return;
+ /* (its splat effect on; its cap knocked off away from the Knight; two scuttlers out) */
+ const Ent *sp = cocoon_splat(e);
+ if (sp->p1 >= 0) anim_play_from_frame(&cocoon_fx, (int)sp->p1, 0), cocoon_fx_on = true;
+ float dx = e->x0 - g_hero.body.x, dy = e->y0 - g_hero.body.y, a = atan2f(dy, dx) * 180 / (float)M_PI;
+ for (int i = 0; i < e->s0; i++) piece_fling(e + 1 + e->s1 + i, e->x0, e->y0, 0, a, a, 10, 10, 1);
+ for (int k = 0; k < 2; k++) {
+ Scuttler *s = NULL;
+ for (int i = 0; i < MAX_SCUTTLERS && !s; i++)
+ if (scuttlers[i].st == SC_OFF && !scuttlers[i].splat_on) s = &scuttlers[i];
+ if (!s) break;
+ memset(s, 0, sizeof *s);
+ s->st = SC_AIR;
+ s->sx = rand_range(1.35f, 1.5f), s->max_speed = rand_range(6, 9);
+ Body *b = &s->body;
+ b->x = e->x0 + 0.5f * rand_range(-1, 1), b->y = e->y0 + 0.5f * rand_range(-1, 1);
+ b->oy = -0.06f * s->sx, b->hx = 0.77f / 2 * s->sx, b->hy = 0.89f / 2 * s->sx;
+ b->gravity_scale = 0.6f, b->friction = 0.2828f, b->mask = CF_TERRAIN;
+ float v = rand_range(10, 15), an = rand_range(40, 140) * (float)M_PI / 180;
+ b->vx = cosf(an) * v, b->vy = sinf(an) * v;
+ anim_play(&s->anim, CLIP_COCOON_SCUTTLER_RUN); /* (its default clip) */
+ }
+ cam_shake(SHAKE_ENEMY_KILL);
+ persist_set(e->persist);
+ cocoon_broken(o, e);
+}
+
+static void cocoon_tick(Obj *o, const Ent *e) {
+ if (o->state == CO_IDLE && (o->t -= DT) <= 0) {
+ /* (Animate: its sweat now and then) */
+ anim_play_from_frame(&o->anim, CLIP_COCOON_COCOON_SWEAT, 0);
+ o->state = CO_SWEAT;
+ } else if (o->state == CO_SWEAT && (o->anim.events & ANIM_DONE)) {
+ anim_play(&o->anim, CLIP_COCOON_COCOON_IDLE);
+ o->state = CO_IDLE, o->t = rand_range(e->p0, e->p1);
+ }
+}
+
+static void cocoon_draw(const Obj *o, const Ent *e) {
+ Inst in;
+ const Ent *sp = cocoon_splat(e);
+ if (sp->p0 >= 0) {
+ sprite_inst((int)sp->p0, e->x0 + sp->x0, e->y0 + sp->y0, sp->x1, 1, 1, 0, &in);
+ gfx_actor(&in, SORT_KEY((int)sp->p2, (int)sp->p3));
+ }
+ if (cocoon_fx_on) {
+ sprite_inst(cocoon_fx.sprite, e->x0 + sp->x0, e->y0 + sp->y0, sp->x1 - 0.001f, 1, 1, 0, &in);
+ gfx_actor(&in, SORT_KEY((int)sp->p2, (int)sp->p3));
+ }
+ if (o->state != CO_BROKEN) {
+ sprite_inst(o->anim.sprite, e->x0, e->y0, e->x1, 1, 1, 0, &in);
+ gfx_actor(&in, SORT_KEY(0, 0));
+ }
+}
+
+static void scuttlers_tick(void) {
+ if (cocoon_fx_on) {
+ cocoon_fx.events = 0;
+ anim_update(&cocoon_fx, DT);
+ if (cocoon_fx.events & ANIM_DONE) cocoon_fx_on = false;
+ }
+ for (int i = 0; i < MAX_SCUTTLERS; i++) {
+ Scuttler *s = &scuttlers[i];
+ if (s->splat_on) {
+ s->splat.events = 0;
+ anim_update(&s->splat, DT);
+ if (s->splat.events & ANIM_DONE) s->splat_on = false;
+ }
+ if (s->st == SC_OFF) continue;
+ s->born += DT;
+ if (s->st == SC_DEAD) {
+ /* Heal: a lifeblood mask, 1.2 s after */
+ if ((s->t += DT) >= 1.2f) hero_add_blue_health(), s->st = SC_OFF;
+ continue;
+ }
+ Body *b = &s->body;
+ float pvx = b->vx, pvy = b->vy;
+ int had = b->ncontacts;
+ body_step(b, DT);
+ body_bounce(b, pvx, pvy, had, 0.45f); /* (ObjectBounce) */
+ s->anim.events = 0;
+ anim_update(&s->anim, DT);
+ switch (s->st) {
+ case SC_AIR: {
+ bool ground = false;
+ for (int c = 0; c < b->ncontacts; c++) ground |= b->cny[c] > 0.5f;
+ if (ground) anim_play_from_frame(&s->anim, CLIP_COCOON_SCUTTLER_LAND, 0), s->st = SC_LAND;
+ break;
+ }
+ case SC_LAND:
+ if (s->anim.events & ANIM_DONE) anim_play(&s->anim, CLIP_COCOON_SCUTTLER_RUN), s->st = SC_RUN;
+ break;
+ case SC_RUN: {
+ /* Run: away from the Knight, faster to its top speed */
+ float side = g_hero.body.x - b->x > 0 ? 1.0f : -1.0f, v = b->vx - 0.3f * 1.2f * side;
+ s->sx = fabsf(s->sx) * side;
+ b->vx = v > s->max_speed ? s->max_speed : v < -s->max_speed ? -s->max_speed : v;
+ /* (a wall ahead: Bounce back off it) */
+ float dir = b->vx >= 0 ? 1.0f : -1.0f;
+ if (phys_ray(b->x + b->ox, b->y + b->oy, dir, 0, b->hx + 0.1f, CF_TERRAIN, NULL)) {
+ float a = (dir > 0 ? rand_range(110, 130) : rand_range(50, 70)) * (float)M_PI / 180;
+ b->vx = 5 * cosf(a), b->vy = 5 * sinf(a);
+ s->st = SC_BOUNCE, s->t = 0.5f;
+ }
+ break;
+ }
+ case SC_BOUNCE:
+ if ((s->t -= DT) <= 0) s->st = SC_RUN;
+ break;
+ }
+ if (b->y < -10) s->st = SC_OFF;
+ }
+}
+
+/* (the nail: a scuttler out a quarter second dies, its splat there) */
+static int scuttlers_nail(const float *pts, int npts) {
+ int out = 0;
+ for (int i = 0; i < MAX_SCUTTLERS; i++) {
+ Scuttler *s = &scuttlers[i];
+ if (s->st == SC_OFF || s->st == SC_DEAD || s->born < 0.25f) continue;
+ const Body *b = &s->body;
+ if (!box_meets_shape(b->x + b->ox - b->hx, b->y + b->oy - b->hy, b->x + b->ox + b->hx, b->y + b->oy + b->hy, pts, npts))
+ continue;
+ s->st = SC_DEAD, s->t = 0;
+ anim_play_from_frame(&s->splat, CLIP_FX_SPLAT, 0), s->splat_on = true;
+ }
+ return out;
+}
+
+static void scuttlers_draw(void) {
+ for (int i = 0; i < MAX_SCUTTLERS; i++) {
+ const Scuttler *s = &scuttlers[i];
+ Inst in;
+ if (s->st != SC_OFF && s->st != SC_DEAD) {
+ sprite_inst(s->anim.sprite, s->body.x, s->body.y, 0.005f, s->sx, fabsf(s->sx), 0, &in);
+ gfx_actor(&in, SORT_KEY(0, 0));
+ }
+ if (s->splat_on) {
+ sprite_inst(s->splat.sprite, s->body.x, s->body.y, 0.004f, 1, 1, 0, &in);
+ gfx_actor(&in, SORT_KEY(0, 0));
+ }
+ }
+}
+
/* ---------------------------------------------------------------- the room */
void obj_enter(void) {
nobjs = 0;
phys_colliders_reset();
memset(pieces, 0, sizeof pieces);
memset(swing_hit, 0, sizeof swing_hit);
+ memset(scuttlers, 0, sizeof scuttlers);
+ cocoon_fx_on = false;
int n;
const Ent *es = room_ents(&n);
for (int i = 0; i < n && nobjs < MAX_OBJS; i++) {
@@ -563,6 +742,7 @@ void obj_enter(void) {
else if (o->kind == OK_BGATE) gate_enter(o, &es[i]);
else if (o->kind == OK_PROP && es[i].p2 >= 0) anim_play(&o->anim, (int)es[i].p2);
else if (o->kind == OK_DRIP) drip_enter(o, &es[i]);
+ else if (o->kind == OK_COCOON) cocoon_enter(o, &es[i]);
}
/* (then what sends the gates their events: SendPlaymakerEventOnEnable, the arenas) */
for (int i = 0; i < n; i++)
@@ -590,7 +770,9 @@ void obj_tick(void) {
else if (o->kind == OK_CHEST) chest_tick(o, e);
else if (o->kind == OK_BGATE) gate_tick(o, e);
else if (o->kind == OK_DRIP) drip_tick(o, e);
+ else if (o->kind == OK_COCOON) cocoon_tick(o, e);
}
+ scuttlers_tick();
arena_tick();
pieces_tick();
enemies_update();
@@ -613,12 +795,15 @@ void obj_draw(void) {
prop_draw(o, e);
else if (o->kind == OK_DRIP)
drip_draw(o, e);
+ else if (o->kind == OK_COCOON)
+ cocoon_draw(o, e);
else if (o->kind == OK_BGATE && o->state != GT_GONE) {
sprite_inst(o->anim.sprite, e->x0, e->y0, e->x1, e->y1, e->p0, 0, &in);
gfx_actor(&in, SORT_KEY(0, 0));
}
}
pieces_draw();
+ scuttlers_draw();
enemies_draw();
}
@@ -648,7 +833,9 @@ int obj_nail(const float *pts, int npts, float direction) {
else if (o->kind == OK_GREAT_DOOR) great_door_hit(o, e);
else if (o->kind == OK_GEO_ROCK) georock_hit(o, e, direction);
else if (o->kind == OK_CHEST) chest_hit(o, e);
+ else if (o->kind == OK_COCOON) cocoon_hit(o, e);
}
+ out |= scuttlers_nail(pts, npts);
return out;
}
diff --git a/games/hollowknight/src/tex.c b/games/hollowknight/src/tex.c
index 85ad7168..88176db5 100644
--- a/games/hollowknight/src/tex.c
+++ b/games/hollowknight/src/tex.c
@@ -15,58 +15,120 @@ static uint16_t slot_next[NSLOTS], slot_frame[NSLOTS];
static uint16_t head[NHASH];
static uint16_t frame = 1, hand;
static uint8_t block_buf[BLOCK_TILES * 128];
-#define tcp g_scratch /* TC_CTX4 * 16 */
+#define tcp g_scratch /* TC_N4 */
+_Static_assert(TC_N4 <= sizeof g_scratch / 2, "the tile decoder's probabilities: in g_scratch");
+#define NONE_T 255
/* ---------------------------------------------------------------- the tile decoder (tilecode.h) */
/* one binary step: the range coder's state in locals (rng, code, src), the probability at pr */
#define RC_BIT(pr, bit) \
do { \
uint16_t *pr_ = (pr); \
- uint32_t pv_ = *pr_, bound_ = (rng >> TC_PROB_BITS) * (pv_ >> 4); \
- uint32_t n_ = pv_ & 15, sh_ = n_ + 1 < TC_LIM ? n_ + 1 : TC_LIM, p_ = pv_ >> 4; \
+ uint32_t pv_ = *pr_, p_ = pv_ >> 4, bound_ = (rng >> TC_PROB_BITS) * p_; \
+ uint32_t st_ = tc_state[pv_ & 7], sh_ = st_ >> 4; \
if (code < bound_) rng = bound_, bit = 0, p_ += (4096 - p_) >> sh_; \
else code -= bound_, rng -= bound_, bit = 1, p_ -= p_ >> sh_; \
while (rng < (1u << 24)) rng <<= 8, code = code << 8 | *src++; \
- *pr_ = (uint16_t)(p_ << 4 | (n_ < 15 ? n_ + 1 : 15)); \
+ *pr_ = (uint16_t)(p_ << 4 | (st_ & 15)); \
} while (0)
-/* n tiles of a block, packed (4 bits a texel, or 2 in tiles twice as wide) into out, 128 bytes each */
-static void decode_block(const uint8_t *src, int n, bool two, uint8_t *out) {
- /* the trained probabilities, already packed (pack.py) */
+/* a 4-bit value in 4 binary steps, nodes 1..15 at p + node */
+#define RC_TREE4(p, v) \
+ do { \
+ uint16_t *pt_ = (p); \
+ int b_, n_ = 1; \
+ RC_BIT(pt_ + n_, b_); \
+ n_ = n_ * 2 + b_; \
+ RC_BIT(pt_ + n_, b_); \
+ n_ = n_ * 2 + b_; \
+ RC_BIT(pt_ + n_, b_); \
+ n_ = n_ * 2 + b_; \
+ RC_BIT(pt_ + n_, b_); \
+ n_ = n_ * 2 + b_; \
+ v = n_ - 16; \
+ } while (0)
+
+/* a texel of a packed tile */
+static int texel_at(const uint8_t *t, int x, int y, bool two) {
+ return two ? t[y * 8 + (x >> 2)] >> (x & 3) * 2 & 3 : t[y * 8 + (x >> 1)] >> (x & 1) * 4 & 15;
+}
+
+/* n tiles of a block, packed (4 bits a texel, or 2 in tiles twice as wide) into out, 128 bytes each; left, up: each
+ * tile's neighbors in the block (NONE_T: not there) */
+static void decode_block(const uint8_t *src, int n, bool two, const uint8_t *left, const uint8_t *up, uint8_t *out) {
+ /* the trained probabilities, ready to use (pack.py) */
const uint8_t *prior = section(SEC_PRIOR);
- if (two) memcpy(tcp, prior + TC_CTX4 * 16 * 2, TC_CTX2 * 4 * 2);
- else memcpy(tcp, prior, TC_CTX4 * 16 * 2);
+ if (two) memcpy(tcp, prior + TC_N4 * 2, TC_N2 * 2);
+ else memcpy(tcp, prior, TC_N4 * 2);
uint32_t rng = 0xFFFFFFFFu, code = 0;
- for (int i = 0; i < 5; i++) code = code << 8 | *src++;
- uint8_t img[512];
+ for (int i = 0; i < 4; i++) code = code << 8 | *src++;
+ int w = two ? 32 : 16, s = TC_STRIDE(w);
+ uint8_t img[17 * TC_STRIDE(32)]; /* the row above, then the tile's: 2 texels to the left, 1 to the right */
for (int t = 0; t < n; t++) {
- if (two) {
- for (int y = 0; y < 16; y++)
+ /* the borders: the last 2 columns of the tile to the left, the last row of the one above */
+ const uint8_t *lt = left[t] == NONE_T ? NULL : out + left[t] * 128;
+ const uint8_t *ut = up[t] == NONE_T ? NULL : out + up[t] * 128;
+ for (int y = 0; y < 16; y++) {
+ uint8_t *r = img + (y + 1) * s;
+ r[0] = lt ? (uint8_t)texel_at(lt, w - 2, y, two) : 0;
+ r[1] = lt ? (uint8_t)texel_at(lt, w - 1, y, two) : 0;
+ }
+ int y = 0;
+ if (ut) {
+ for (int x = 0; x < w; x++) img[2 + x] = (uint8_t)texel_at(ut, x, 15, two);
+ img[1] = img[s + 1], img[w + 2] = img[w + 1];
+ } else {
+ /* the top row on its own */
+ uint8_t *r = img + s + 2;
+ for (int x = 0; x < w; x++) {
+ int l = r[x - 1], v, bit;
+ if (two) {
+ uint16_t *p = tcp + tc_c20(l, r[x - 2]);
+ RC_BIT(p, bit);
+ RC_BIT(p + 1 + bit, v);
+ v |= bit << 1;
+ } else {
+ RC_BIT(tcp + tc_f0(l, r[x - 2]), bit);
+ if (!bit) v = l;
+ else RC_TREE4(tcp + tc_tree(l, l), v);
+ }
+ r[x] = (uint8_t)v;
+ }
+ r[w] = r[w - 1];
+ y = 1;
+ }
+ for (; y < 16; y++) {
+ uint8_t *r = img + (y + 1) * s + 2;
+ const uint8_t *a = r - s;
+ if (two)
for (int x = 0; x < 32; x++) {
- int l = tc_left(img, x, y, 32), u = tc_up(img, x, y, l, 32), b0, b1;
- uint16_t *p = tcp + (l * 4 + u) * 4;
- RC_BIT(p + 1, b0);
- RC_BIT(p + 2 + b0, b1);
- img[y * 32 + x] = (uint8_t)(b0 << 1 | b1);
+ uint16_t *p = tcp + tc_c2(r[x - 1], a[x], a[x - 1], a[x + 1]);
+ int b0, b1;
+ RC_BIT(p, b0);
+ RC_BIT(p + 1 + b0, b1);
+ r[x] = (uint8_t)(b0 << 1 | b1);
}
- for (int i = 0; i < 128; i++)
- out[t * 128 + i] = (uint8_t)(img[4 * i] | img[4 * i + 1] << 2 | img[4 * i + 2] << 4 | img[4 * i + 3] << 6);
- } else {
- for (int y = 0; y < 16; y++)
+ else
for (int x = 0; x < 16; x++) {
- int l = tc_left(img, x, y, 16), u = tc_up(img, x, y, l, 16), bit, node = 1;
- uint16_t *p = tcp + (l * 16 + u) * 16;
- RC_BIT(p + node, bit);
- node = node * 2 + bit;
- RC_BIT(p + node, bit);
- node = node * 2 + bit;
- RC_BIT(p + node, bit);
- node = node * 2 + bit;
- RC_BIT(p + node, bit);
- node = node * 2 + bit;
- img[y * 16 + x] = (uint8_t)(node - 16);
+ int l = r[x - 1], u = a[x], v, bit;
+ RC_BIT(tcp + tc_fl(l, u, a[x - 1], a[x + 1], r[x - 2]), bit);
+ if (!bit) v = l;
+ else {
+ if (u != l) RC_BIT(tcp + tc_fu(l, u, a[x - 1]), bit);
+ if (!bit) v = u;
+ else RC_TREE4(tcp + tc_tree(l, u), v);
+ }
+ r[x] = (uint8_t)v;
}
- for (int i = 0; i < 128; i++) out[t * 128 + i] = (uint8_t)(img[2 * i] | img[2 * i + 1] << 4);
+ r[w] = r[w - 1];
+ }
+ for (y = 0; y < 16; y++) {
+ const uint8_t *r = img + (y + 1) * s + 2;
+ uint8_t *o = out + t * 128 + y * 8;
+ if (two)
+ for (int i = 0; i < 8; i++) o[i] = (uint8_t)(r[4 * i] | r[4 * i + 1] << 2 | r[4 * i + 2] << 4 | r[4 * i + 3] << 6);
+ else
+ for (int i = 0; i < 8; i++) o[i] = (uint8_t)(r[2 * i] | r[2 * i + 1] << 4);
}
}
}
@@ -174,6 +236,22 @@ static int stale_slot(void) {
const uint8_t *tex_slot_px(int s) { return slot_px[s]; }
+/* where a block's tiles are (by rank: row by row), and so which of them is each one's left and upper neighbor */
+static void block_geometry(const TexRec *r, int first, int n, uint8_t *left, uint8_t *up) {
+ uint8_t tx[BLOCK_TILES], ty[BLOCK_TILES];
+ int y = 0, i = 0;
+ while (y + 1 < r->th && rd16(row_base(r, y + 1)) <= first) y++;
+ for (int k = rd16(row_base(r, y)); i < n; y++)
+ for (int x = 0; x < r->tw && i < n; x++)
+ if (code_at(row_base(r, y) + 2, x) && k++ >= first) tx[i] = (uint8_t)x, ty[i] = (uint8_t)y, i++;
+ for (i = 0; i < n; i++) {
+ left[i] = i && ty[i - 1] == ty[i] && tx[i - 1] + 1 == tx[i] ? (uint8_t)(i - 1) : NONE_T;
+ up[i] = NONE_T;
+ for (int j = 0; j < i; j++)
+ if (tx[j] == tx[i] && ty[j] + 1 == ty[i]) up[i] = (uint8_t)j;
+ }
+}
+
const uint8_t *tex_tile(uint16_t t, int tx, int ty) {
int s = tex_slot(t, tx, ty);
return s < 0 ? NULL : slot_px[s];
@@ -199,7 +277,9 @@ int tex_slot(uint16_t t, int tx, int ty) {
int ntiles = tex_tiles(r) - first;
if (ntiles > BLOCK_TILES) ntiles = BLOCK_TILES;
const uint8_t *bidx = sec_bidx + 4 * (r->blk_first + blk);
- decode_block(sec_blk + rd32(bidx), ntiles, r->fmt == FMT_ALPHA2, block_buf);
+ uint8_t left[BLOCK_TILES], up[BLOCK_TILES];
+ block_geometry(r, first, ntiles, left, up);
+ decode_block(sec_blk + rd32(bidx), ntiles, r->fmt == FMT_ALPHA2, left, up, block_buf);
g_tex_decodes++;
int want = insert((uint32_t)t << 16 | (uint32_t)rank, block_buf + (rank - first) * bytes, bytes);
slot_frame[want] = frame;
diff --git a/games/hollowknight/src/tilecode.h b/games/hollowknight/src/tilecode.h
index 13c1eb9c..22d7c0e1 100644
--- a/games/hollowknight/src/tilecode.h
+++ b/games/hollowknight/src/tilecode.h
@@ -1,30 +1,53 @@
-/* The scenery tiles' coding: each texel coded in binary steps with the texel to its left and the one above as
- * context, by a range coder. Probabilities start from tables trained on all tiles and adapt quickly within a block.
- * Shared by the game (decoding) and tools/tilecode.c (training, encoding). */
+/* The scenery tiles' coding: a range coder (LZMA's) with adaptive probabilities that start from tables trained on all
+ * tiles, each with how fast it adapts at first. Blocks of tiles are coded on their own.
+ * A texel's context is its neighbors: two to its left, three above (up-left, up, up-right). Across a tile's edges they
+ * are those of the tiles to its left and above when those are in the block (before it), else 0 to the left and above
+ * nothing: the top row is then coded on its own, with the two to the left.
+ * 4 bits: is it the texel to its left? (context: that one, how the others compare), else the one above? (context: the
+ * two, how the one up-left compares), else its value in 4 binary steps (context: the two, in either order).
+ * 2 bits: its value in 2 binary steps, the 4 neighbors as context.
+ * Shared by the game (decoding: tex.c) and tools/tilecode.c (training, encoding). */
#pragma once
#include <stdint.h>
-/* tiles are 16 texels high, 16 wide (4 bits) or 32 (2 bits) */
-#define TC_TILE 16
#define TC_PROB_BITS 12
-#define TC_LIM 4 /* the slowest adaptation (shift) */
-#define TC_N0 1 /* how sure the trained probabilities are at first */
-/* 4-bit tiles: 256 contexts x 16 nodes (1..15 used); 2-bit tiles: 16 contexts x 4 nodes (1..3 used) */
-#define TC_CTX4 256
-#define TC_CTX2 16
+/* the probabilities (uint16), 4-bit tiles */
+#define TC_FL 0 /* "the one to the left": 16 x 64 */
+#define TC_F0 1024 /* ... in a top row on its own: 16 x 2 */
+#define TC_FU 1056 /* "the one above": 240 pairs x 4 */
+#define TC_TREE 2016 /* the value: 136 pairs x 15 nodes */
+#define TC_N4 4056
+/* 2-bit tiles: 256 x 3, then the top row on its own 16 x 3 */
+#define TC_C20 768
+#define TC_N2 816
-/* a probability: 12 bits (of a 0) and a 4-bit count of updates */
-static inline uint16_t tc_pack(int p, int n) { return (uint16_t)(p << 4 | n); }
+/* a tile as coded: rows 3 texels wider than it (2 of the tile to the left, 1 more: a copy of the last), and a row of
+ * the tile above first */
+#define TC_STRIDE(w) ((w) + 3)
-static inline int tc_left(const uint8_t *img, int x, int y, int w) {
- return x ? img[y * w + x - 1] : (y ? img[(y - 1) * w] : 0);
-}
-static inline int tc_up(const uint8_t *img, int x, int y, int left, int w) { return y ? img[(y - 1) * w + x] : left; }
+/* a probability: 12 bits (of a 0), then its state: how much a bit moves it (a shift), and the state after. States 0
+ * and 3 settle at 1/8 and 1/16 */
+static const uint8_t tc_state[8] = {0x11, 0x22, 0x32, 0x14, 0x25, 0x36, 0x46, 0x46};
-static inline void tc_update(uint16_t *pr, int bit) {
- int p = *pr >> 4, n = *pr & 15, sh = n + 1 < TC_LIM ? n + 1 : TC_LIM;
+static inline uint16_t tc_update(uint16_t pv, int bit) {
+ int p = pv >> 4, st = tc_state[pv & 7], sh = st >> 4;
if (!bit) p += (4096 - p) >> sh;
else p -= p >> sh;
- if (n < 15) n++;
- *pr = tc_pack(p, n);
+ return (uint16_t)(p << 4 | (st & 15));
+}
+
+/* contexts, from the neighbors: l, ll to the left, u above, ul, ur above to the left and right */
+static inline int tc_fl(int l, int u, int ul, int ur, int ll) {
+ return TC_FL + (l << 6 | (l == u) | (ul == u) << 1 | (ur == l) << 2 | (ll == l) << 3 | (u == 0) << 4 | (ur == 0) << 5);
+}
+static inline int tc_f0(int l, int ll) { return TC_F0 + (l << 1 | (ll == l)); }
+static inline int tc_fu(int l, int u, int ul) { /* (u != l) */
+ return TC_FU + ((l * 15 + u - (u > l)) << 2 | (ul == l) | (ul == u) << 1);
+}
+static inline int tc_tree(int l, int u) { /* + the node (1..15) */
+ int a = l > u ? l : u, b = l + u - a;
+ return TC_TREE - 1 + (a * (a + 1) / 2 + b) * 15;
}
+/* 2 bits: + 0, then + 1 + the first bit */
+static inline int tc_c2(int l, int u, int ul, int ur) { return (l << 6 | u << 4 | ul << 2 | ur) * 3; }
+static inline int tc_c20(int l, int ll) { return TC_C20 + (l << 2 | ll) * 3; }
diff --git a/games/hollowknight/tests/play.c b/games/hollowknight/tests/play.c
index 2197a4ed..598c8836 100644
--- a/games/hollowknight/tests/play.c
+++ b/games/hollowknight/tests/play.c
@@ -100,7 +100,7 @@ int main(int argc, char **argv) {
printf("%4d keys %02x pos %.3f,%.3f v %.3f,%.3f state %d ground %d jump %d fall %d clip %d frame %d cam %.2f,%.2f\n", tick,
keys, g_hero.body.x, g_hero.body.y, g_hero.body.vx, g_hero.body.vy, g_hero.state, g_hero.cs.on_ground,
g_hero.cs.jumping, g_hero.cs.falling, g_hero.anim.clip, g_hero.anim.frame, g_cam_x, g_cam_y);
- if (trace && getenv("HKSTATS")) printf(" health %d mp %d geo %d\n", g_pd.health, g_pd.mp, (int)g_pd.geo);
+ if (trace && getenv("HKSTATS")) printf(" health %d blue %d mp %d geo %d\n", g_pd.health, g_pd.health_blue, g_pd.mp, (int)g_pd.geo);
if (trace && getenv("ENEMIES")) {
extern void enemies_debug(void);
enemies_debug();
diff --git a/games/hollowknight/tools/actors.py b/games/hollowknight/tools/actors.py
index 652cdf5d..d5c28a5a 100644
--- a/games/hollowknight/tools/actors.py
+++ b/games/hollowknight/tools/actors.py
@@ -101,7 +101,7 @@ ACTORS = {"knight": KNIGHT,
"chest": ("sharedassets6.assets", 1148, None),
# the HUD: drawn by its own camera, 11.48 pixels a unit (scenes: K0), masks at 0.7135
"hud": ("resources.assets", 20665, ["Health Empty", "Health Idle", "Health Break", "Health Refill", "Health Appear",
- "Blue Appear", "Blue Idle", "Blue Break", "HUD Frame", "HUD Frame Idle",
+ "Blue Appear", "Blue Idle", "Blue Break", "Blue Break Fast", "HUD Frame", "HUD Frame Idle",
"HUD Frame CrackAppear", "HUD Frame Cracked", "Coin Appear", "Coin Idle",
"Coin Get", "Soul Burst"]),
"liquid": ("resources.assets", 20843, None),
@@ -119,6 +119,9 @@ ACTORS.update(_enemy_actors())
# battle gates (BG Control: the plain ones and the bone ones)
ACTORS["bgate"] = ("sharedassets9.assets", 197, ["BG Opened", "BG Close 1", "BG Close 2", "BG Open", "BG Closed",
"Bone Gate Opened", "Bone Gate Close", "Bone Gate Closed", "Bone Gate Open"])
+# lifeblood cocoons and their scuttlers (HealthCocoon, ScuttlerControl); effects (splats)
+ACTORS["cocoon"] = ("sharedassets6.assets", 1092, ["Cocoon Idle", "Cocoon Sweat", "Scuttler Land", "Scuttler Run"])
+ACTORS["fx"] = ("resources.assets", 21298, ["Splat", "Splat2"])
# water drips (WaterDrip)
ACTORS["drip"] = ("sharedassets6.assets", 1095, ["Idle", "Drip", "Fall", "Impact"])
PROP_ACTOR = {} # (props' libraries: their actors)
diff --git a/games/hollowknight/tools/ents.py b/games/hollowknight/tools/ents.py
index 5c2a011a..da70ac69 100644
--- a/games/hollowknight/tools/ents.py
+++ b/games/hollowknight/tools/ents.py
@@ -9,7 +9,7 @@ ENT_CAMLOCK, ENT_GATE, ENT_HAZARD_MARKER, ENT_RESPAWN, ENT_HAZARD_TRIGGER, ENT_M
ENT_OBJ, ENT_PIECE, ENT_SHADE_MARKER = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
# objects (ENT_OBJ's flags: src/obj.c)
OK_BREAKABLE, OK_ENEMY, OK_GREAT_DOOR, OK_GEO_ROCK, OK_CHEST, OK_BENCH, OK_BATTLE, OK_FK_FLOOR, OK_BGATE, OK_ARENA, \
- OK_EVENT, OK_SUMMON, OK_COND, OK_PROP, OK_DRIP = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
+ OK_EVENT, OK_SUMMON, OK_COND, OK_PROP, OK_DRIP, OK_COCOON = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16
# the battle gates' events (src/game.h: BG_*)
BG_EVENTS = ["BG CLOSE", "BG QUICK CLOSE", "BG OPEN", "BG QUICK OPEN", "BG DESTROY"]
# battle gates (BG Control: OK_BGATE's s0): closed at first, the bone ones' clips, gone once a PlayerData bool is set
@@ -858,6 +858,39 @@ def room(d, rooms, strings, persist, name, sprites=None, owners=None, rec_base=0
layer, order = _sorting(o)
recs.append(rec(ENT_OBJ, OK_PROP, (o["pos"][0], o["pos"][1], o["pos"][2], sx), (sy, _angle(o), ci, 0),
a=order + 32768, group=layer, s0=sprites.tk2d(*sp) if sp else 0))
+ hc = next((c.get("v") for c in o["c"] if c.get("class") == "HealthCocoon" and c.get("v")), None)
+ if hc is not None:
+ # a lifeblood cocoon: its place, its sweat's waits; its colliders, the children it hides as it breaks (a
+ # group); its hit boxes, its cap (a piece), then its splat (sprite, effect clip, their place and sorting)
+ import actors
+ kids = {by_id[c]["name"]: by_id[c] for c in o.get("children", [])}
+ ref_ids = lambda refs: [r[1] for r in refs or [] if r and r[1] in by_id]
+ hidden = ref_ids(hc.get("disableChildren"))
+ g_hide = new_group(hidden[0]) if hidden else 0
+ for h in hidden[1:]:
+ subtree(h, g_hide)
+ c0, cn = _subcols(d, owners, o["id"]) if owners else (0, 0)
+ hits = _hit_boxes(o, by_id, depth=0)
+ cap = ref_ids([hc.get("cap")]) if hc.get("cap") else []
+ pieces = _pieces(d, o, cap, by_id, sprites)
+ splat, eff = kids.get("Splat Sprite"), kids.get("Splat Effect")
+ sp = _tk2d_sprite(d, splat) if splat else None
+ ean = next((c.get("v") for c in eff["c"] if c.get("class") == "tk2dSpriteAnimator"), None) if eff else None
+ eclip = -1
+ if ean:
+ import tk2d, unity
+ lib = _ref_file(d, ean["library"])
+ eclip = CLIP_INDEX.get(actors.clip_id("fx", unity.S(tk2d.animation(*lib)["clips"][ean["defaultClipId"]]["name"])), -1)
+ layer, order = _sorting(splat) if splat else (0, 0)
+ persistent = any(c.get("class") == "PersistentBoolItem" for c in o["c"])
+ recs.append(rec(ENT_OBJ, OK_COCOON, (o["pos"][0], o["pos"][1], o["pos"][2], 0),
+ (hc.get("waitMin", 2), hc.get("waitMax", 6), 0, 0), a=c0, group=cn, group2=g_hide,
+ persist=persist.id(name, o["path"]) if persistent else NO_PERSIST, s0=len(pieces), s1=len(hits)))
+ recs += [rec(ENT_BOX, fl, box=b) for b, fl in hits]
+ recs += pieces
+ recs.append(rec(ENT_BOX, 0, (splat["lpos"][0] if splat else 0, splat["lpos"][1] if splat else 0,
+ splat["pos"][2] if splat else 0, 0),
+ (sprites.tk2d(*sp) if sp else -1, eclip, layer, order)))
dv = next((c.get("v") for c in o["c"] if c.get("class") == "WaterDrip" and c.get("v")), None)
if dv is not None:
# a water drip: its place, its idle times, fall speed and how far it sinks as it hits
diff --git a/games/hollowknight/tools/pack.py b/games/hollowknight/tools/pack.py
index 1147b6fe..85b4c7af 100644
--- a/games/hollowknight/tools/pack.py
+++ b/games/hollowknight/tools/pack.py
@@ -63,7 +63,6 @@ def _pdf_flags():
BLENDS = {"alpha": 0, "add": 1, "screen": 2, "linearlight": 3, "overlay": 4, "multiply": 5}
F_LIT, F_ROT, F_SOLID, F_DYN, F_GRASS = 8, 16, 32, 64, 128
-TC_N0 = 1 # (src/tilecode.h)
LZ = [{"id": lzma.FILTER_LZMA1, "lc": 0, "lp": 0, "pb": 0, "dict_size": 1 << 16, "preset": 9 | lzma.PRESET_EXTREME}]
@@ -291,15 +290,28 @@ def room_blobs(name, keep, st, tex_id, variant=0):
return body, o_sec, blobs, bytes(cb), b"".join(erecs)
+def tile_blocks(t):
+ """A texture's tiles in blocks: (bits, tiles, per tile the one to its left and the one above in the block (255:
+ none), as src/tex.c finds them)"""
+ pos = [(tx, ty) for ty in range(t.th) for tx in range(t.tw) if not t.empty[ty, tx]]
+ assert len(pos) == t.ntiles
+ out = []
+ for i in range(0, t.ntiles, art.BLOCK_TILES):
+ at = {p: j for j, p in enumerate(pos[i:i + art.BLOCK_TILES])}
+ nb = b"".join(bytes([at.get((tx - 1, ty), 255), at.get((tx, ty - 1), 255)]) for tx, ty in pos[i:i + art.BLOCK_TILES])
+ out.append((t.bits, t.tiles[i:i + art.BLOCK_TILES], nb))
+ return out
+
+
def tilecode(blocks):
"""Trains the tile coder's starting probabilities on every block and encodes them (tools/tilecode.c)."""
import subprocess, tempfile
tmp = tempfile.mkdtemp()
exe = os.path.join(tmp, "tilecode")
- subprocess.check_call(["cc", "-O2", "-o", exe, os.path.join(HERE, "tilecode.c")])
+ subprocess.check_call(["cc", "-O2", "-o", exe, os.path.join(HERE, "tilecode.c"), "-lm"])
job = bytearray(struct.pack("<I", len(blocks)))
- for bits, tiles in blocks:
- job += struct.pack("<BBH", bits, 0, len(tiles)) + b"".join(tiles)
+ for bits, tiles, nb in blocks:
+ job += struct.pack("<BBH", bits, 0, len(tiles)) + nb + b"".join(tiles)
open(os.path.join(tmp, "in.bin"), "wb").write(job)
subprocess.check_call([exe, "train", os.path.join(tmp, "in.bin"), os.path.join(tmp, "prior.bin")])
subprocess.check_call([exe, "encode", os.path.join(tmp, "in.bin"), os.path.join(tmp, "prior.bin"), os.path.join(tmp, "out.bin")])
@@ -349,13 +361,13 @@ def main():
blocks = []
for t in texs:
t.first_block = len(blocks)
- for i in range(0, t.ntiles, art.BLOCK_TILES):
- blocks.append((t.bits, t.tiles[i:i + art.BLOCK_TILES]))
+ if t.ntiles:
+ blocks += tile_blocks(t)
prior, coded = tilecode(blocks)
print("tiles coded %.0fs" % (time.time() - t0), flush=True)
secs = {k: Blob() for k in SECTIONS}
- # the starting probabilities as the game uses them: each with its count (tilecode.h: tc_pack)
- secs["PRIOR"].b += b"".join(struct.pack("<H", v << 4 | TC_N0) for v in struct.unpack("<%dH" % (len(prior) // 2), prior))
+ # the starting probabilities as the game uses them (tilecode.h)
+ secs["PRIOR"].b += prior
tex_id = {}
pal_at = {} # (palettes shared: once each)
nblk = 0
@@ -398,6 +410,7 @@ def main():
secs["BLK"].b += bl
bidx += struct.pack("<I", len(secs["BLK"].b))
texrec += struct.pack("<HHBBBBIII", t.w, t.h, t.tw, t.th, t.fmt, 1 if v.blur else 0, pal_off, map_off, first)
+ secs["BLK"].b += bytes(3) # (the game reads up to 3 bytes past a block)
if os.environ.get("ACTSTATS"):
import collections
tot = collections.Counter()
diff --git a/games/hollowknight/tools/pack.py.orig b/games/hollowknight/tools/pack.py.orig
new file mode 100644
index 00000000..1147b6fe
--- /dev/null
+++ b/games/hollowknight/tools/pack.py.orig
@@ -0,0 +1,519 @@
+"""Hollow Knight for the NumWorks calculator: makes src/data.bin (and src/data.h) from the game's files.
+HOLLOWKNIGHT=<the game's Data folder> python3 pack.py"""
+import os, sys, struct, math, lzma, time, multiprocessing as mp
+import numpy as np
+HERE = os.path.dirname(os.path.abspath(__file__))
+sys.path.insert(0, HERE)
+import unity, scene, visible, art, actors, coll, ents, font, text
+
+SRC = os.path.join(HERE, "..", "src")
+ALL_ROOMS = [l.strip() for l in open(os.path.join(HERE, "rooms.txt")) if l.strip() and not l.startswith("#")]
+# (scenes loaded with others are part of those: two variants of the room, by a PlayerData bool)
+ROOMS = [r for r in ALL_ROOMS if r not in scene.additive_scenes(ALL_ROOMS)]
+VARIANT_ROOMS = [r for r in ROOMS if scene.additive(r)]
+STRINGS = ents.Strings()
+PERSIST = ents.Persist()
+SPRITES = ents.Sprites()
+TEXTS = text.Texts()
+# the prompt markers' labels (Arrow Prompt New's)
+PROMPTS = ["Listen", "Rest", "Inspect", "Enter", "Sit", "Shop", "Travel", "Ascend", "Descend", "Exit", "Accept", "Trade",
+ "Watch", "Challenge"]
+ROOM_DATA = {} # name -> (coll.room's, ents.room's)
+
+
+def room_data(name, variant=0):
+ """A room's ground and objects (once: the objects' sprites go into SPRITES) -> (coll.room's, (records, {(scene,
+ object id): group}), {which: its groups (first, last)}). With the scenes it loads with it: variant 0 has the first's
+ (which 1), variant 1 the alternative's (which 2); the groups of both numbered the same in either, after the room's;
+ (scene, None): the group of a scene's sprites with none of their own."""
+ if (name, variant) not in ROOM_DATA:
+ d = unity.scene(name)
+ st = scene.settings(d)
+ w, h = st["size"] if st["size"] else (40, 24)
+ solid, segs, cols, owners = coll.room(d, w, h)
+ recs, gr = ents.room(d, ROOMS, STRINGS, PERSIST, name, SPRITES, owners)
+ groups = {(name, k): g for k, g in gr.items()}
+ segs, cols, recs = list(segs), list(cols), list(recs)
+ gb = max(gr.values(), default=0)
+ spans = {}
+ for an, flag, val, which in scene.additive(name):
+ da = unity.scene(an)
+ _, asegs, acols, aown = coll.room(da, w, h)
+ ar, ag = ents.room(da, ROOMS, STRINGS, PERSIST, an, SPRITES, aown, rec_base=len(recs), col_base=len(cols),
+ group_base=gb)
+ cond = max(ag.values(), default=gb) + 1
+ groups.update({(an, k): g for k, g in ag.items()})
+ groups[(an, None)] = cond
+ spans[which] = (gb + 1, cond)
+ gb = cond
+ if (which == 1) == (variant == 0):
+ segs += [(x0, y0, x1, y1, ci + len(cols)) for x0, y0, x1, y1, ci in asegs]
+ cols += acols
+ recs += ar
+ assert gb < ents.MAX_GROUPS, (name, gb)
+ ROOM_DATA[(name, variant)] = ((solid, segs, cols, owners), (recs, groups), spans)
+ return ROOM_DATA[(name, variant)]
+
+SECTIONS = ["TEX", "TMAP", "PAL", "BIDX", "BLK", "ROOMS", "RBLOB", "PRIOR", "SOFT", "SPR", "CLIP", "STR", "TEXT", "FONT", "PHASH",
+ "SCOL", "RVAR"]
+
+
+def _pdf_flags():
+ return ents.pd_flags()
+BLENDS = {"alpha": 0, "add": 1, "screen": 2, "linearlight": 3, "overlay": 4, "multiply": 5}
+F_LIT, F_ROT, F_SOLID, F_DYN, F_GRASS = 8, 16, 32, 64, 128
+
+TC_N0 = 1 # (src/tilecode.h)
+LZ = [{"id": lzma.FILTER_LZMA1, "lc": 0, "lp": 0, "pb": 0, "dict_size": 1 << 16, "preset": 9 | lzma.PRESET_EXTREME}]
+
+
+def lz(b):
+ return lzma.compress(b, format=lzma.FORMAT_RAW, filters=LZ)
+
+
+def f16(x):
+ return int(np.array(x, np.float16).view(np.uint16))
+
+
+def i16(x):
+ return max(-32768, min(32767, int(round(x))))
+
+
+def f16s(x):
+ """A half float's bits as a signed 16-bit value (for struct 'h')."""
+ v = f16(x)
+ return v - 65536 if v >= 32768 else v
+
+
+class Blob:
+ def __init__(self):
+ self.b = bytearray()
+
+ def align(self, n=4):
+ while len(self.b) % n:
+ self.b.append(0)
+
+ def add(self, data, align=4):
+ self.align(align)
+ o = len(self.b)
+ self.b += data
+ return o
+
+
+SECTOR = 16.0 # sectors along the room's long camera axis (units)
+GLOBAL_SPAN = 40.0 # instances seen over a longer stretch of camera positions are always kept
+MARGIN = 2.0
+
+
+def inst_record(it, tex_id, tints):
+ """An instance: where, its texture, how it is drawn."""
+ q = it.quad # bl, br, tr, tl (world)
+ tl, tr, bl = q[3], q[2], q[0]
+ flags = BLENDS.get(it.blend, 0)
+ if it.lit:
+ flags |= F_LIT
+ if it.group:
+ flags |= F_DYN # (in a render group: a byte more)
+ if it.grass:
+ flags |= F_GRASS
+ color = it.color
+ if it.solid and it.sprite.name == "black_solid":
+ color = (0, 0, 0, color[3])
+ col = tuple(int(round(min(1, max(0, c)) * 255)) for c in color)
+ if col not in tints:
+ tints.append(col)
+ tint = min(255, tints.index(col))
+ rot = 0
+ if it.solid:
+ flags |= F_SOLID
+ tex = 0xFFFF
+ ax, ay = min(p[0] for p in q), max(p[1] for p in q)
+ a, b = max(p[0] for p in q) - ax, -(ay - min(p[1] for p in q))
+ else:
+ t = tex_id[id(it.variant)]
+ tex, tw, th = t
+ eu = (tr - tl) / tw
+ ev = (bl - tl) / th
+ ax, ay = tl[0], tl[1]
+ a = math.hypot(eu[0], eu[1])
+ ang = math.atan2(eu[1], eu[0])
+ # flips: keep the angle small, put the sign in a
+ if abs(ang) > math.pi / 2:
+ ang = ang - math.pi if ang > 0 else ang + math.pi
+ a = -a
+ c, s_ = math.cos(ang), math.sin(ang)
+ b = ev[0] * -s_ + ev[1] * c # along (-sin, cos)
+ rot = int(round(ang / (2 * math.pi) * 65536))
+ if rot:
+ flags |= F_ROT
+ return (ax, ay, it.z, tex, tint, flags, a, b, rot, it.group)
+
+
+def uvar(u):
+ out = bytearray()
+ while u >= 128:
+ out.append(u & 127 | 128)
+ u >>= 7
+ out.append(u)
+ return out
+
+
+def svar(v):
+ return uvar(v << 1 if v >= 0 else ((-v) << 1) - 1)
+
+
+def sector_stream(recs):
+ """A sector's instances in draw order, each relative to the one before (read in place by room.c):
+ flags, aux (1 tint, 2 same texture, 4 same z, 8|16 b: 0 its own, 1 = a, 2 = -a, 3 same as before, 32 same a,
+ 64 next rank, 128 another sorting layer or order), [rank step - 2], [layer, order], [texture step], [tint],
+ x step, y step, [z step], [a], [b], [angle], [render group (F_DYN)]."""
+ out = bytearray()
+ pr, pt, px, py, pz, pa, pb, pg = -1, 0, 0, 0, 0, 0, 0, None
+ for rank, (ax, ay, z, tex, tint, flags, a, b, rot, rgroup), group in recs:
+ X, Y, Z, A, B = i16(ax * 64), i16(ay * 64), i16(z * 128), f16s(a) & 0xFFFF, f16s(b) & 0xFFFF
+ aux = 0
+ if tint:
+ aux |= 1
+ if tex == pt:
+ aux |= 2
+ if Z == pz:
+ aux |= 4
+ bm = 1 if B == A else 2 if B == A ^ 0x8000 else 3 if B == pb else 0
+ aux |= bm << 3
+ if A == pa:
+ aux |= 32
+ if rank == pr + 1:
+ aux |= 64
+ if group != pg:
+ aux |= 128
+ out += bytes([flags, aux])
+ if not aux & 64:
+ out += uvar(rank - pr - 2)
+ if aux & 128:
+ out += bytes([group[0]]) + svar(group[1])
+ if not aux & 2:
+ out += svar(tex - pt)
+ if tint:
+ out.append(tint)
+ out += svar(X - px) + svar(Y - py)
+ if not aux & 4:
+ out += svar(Z - pz)
+ if not aux & 32:
+ out += struct.pack("<H", A)
+ if bm == 0:
+ out += struct.pack("<H", B)
+ if flags & F_ROT:
+ out += struct.pack("<h", rot)
+ if flags & F_DYN:
+ out.append(rgroup)
+ pr, pt, px, py, pz, pa, pb, pg = rank, tex, X, Y, Z, A, B, group
+ return bytes(out)
+
+
+def room_blobs(name, keep, st, tex_id, variant=0):
+ """A room: its header (kept in RAM) and its instances in sectors (decoded when the camera is near)."""
+ w, h = st["size"] if st["size"] else (40, 24)
+ cx0, cx1, cy0, cy1 = scene.camera_range(st) if st["size"] else (20, 20, 12, 12)
+ axis = 0 if (cx1 - cx0) >= (cy1 - cy0) else 1
+ lo, hi = (cx0, cx1) if axis == 0 else (cy0, cy1)
+ HWU, HHU = scene.VIEW_W / 2 / scene.FOCAL, scene.VIEW_H / 2 / scene.FOCAL
+ (solid, segs, cols, _), (erecs, groups), _ = room_data(name, variant)
+ for it in keep:
+ it.group = groups.get((it.scene, it.obj["id"]), groups.get((it.scene, None), 0) if it.which else 0)
+ tints = [(255, 255, 255, 255)]
+ secs = {}
+ for rank, it in enumerate(keep):
+ rec = inst_record(it, tex_id, tints)
+ q = np.array(it.quad)
+ dist = max(0.5, it.z - scene.CAMZ)
+ half = (HWU if axis == 0 else HHU) * dist
+ p0, p1 = (q[:, 0].min(), q[:, 0].max()) if axis == 0 else (q[:, 1].min(), q[:, 1].max())
+ va, vb = max(lo, p0 - half - MARGIN), min(hi, p1 + half + MARGIN)
+ if it.dynamic or vb - va > GLOBAL_SPAN or vb < va:
+ sec = -1
+ else:
+ sec = int((va - lo) // SECTOR)
+ e = secs.setdefault(sec, [[], 1e9, -1e9])
+ e[0].append((rank, rec, (it.layer, it.order)))
+ e[1] = min(e[1], va)
+ e[2] = max(e[2], vb)
+ order = sorted(secs.keys())
+ luts, sat = scene.grading_luts(st, 64)
+ lut = bytes(int(round(luts[c][i] * 255)) for c in range(3) for i in range(64))
+ bz = st["blur_z"] if st["blur_z"] is not None else 1000.0
+ blobs = []
+ table = bytearray()
+ for k in order:
+ recs, va, vb = secs[k]
+ blobs.append((sector_stream(recs), len(recs)))
+ if k < 0:
+ va, vb = -1e9, 1e9
+ table += struct.pack("<IIHHff", 0, 0, len(recs), 0, va, vb) # (offsets filled in by main)
+ HDR = 84 + 192
+ gw, gh, cells = coll.grid(segs, w, h)
+ hdr = struct.pack("<4H4f4f4fff6HII", 6, len(order), len(tints), axis, w, h, bz, sat, *st["ambient"], 0.0,
+ *st["hero_light"], lo, hi, len(keep), len(segs), len(cols), gw, gh, len(erecs), 0, 0) + lut
+ assert len(hdr) == HDR, len(hdr)
+ body = bytearray(hdr)
+ body += b"".join(struct.pack("<4B", *t) for t in tints)
+ while len(body) % 4:
+ body.append(0)
+ o_sec = len(body)
+ body += table
+ # the ground (read in place): colliders' flags (0: the tilemap's), the tilemap's solid tiles (1 bit each, rows from
+ # the bottom), segments (1/128 unit), their colliders, cells' first entries, entries
+ cb = bytearray(bytes(cols))
+ if len(cb) % 2:
+ cb.append(0)
+ th, tw = solid.shape
+ cb += struct.pack("<HH", tw, th)
+ rowb = (tw + 7) // 8
+ for y in range(th):
+ row = bytearray(rowb)
+ for x in range(tw):
+ if solid[y, x]:
+ row[x >> 3] |= 1 << (x & 7)
+ cb += row
+ if len(cb) % 2:
+ cb.append(0)
+ for x0, y0, x1, y1, ci in segs:
+ cb += struct.pack("<4h", *(i16(c * coll.UNIT) for c in (x0, y0, x1, y1)))
+ cb += bytes(ci for x0, y0, x1, y1, ci in segs)
+ if len(cb) % 2:
+ cb.append(0)
+ first = 0
+ for c in cells:
+ cb += struct.pack("<H", first)
+ first += len(c)
+ cb += struct.pack("<H", first)
+ for c in cells:
+ cb += struct.pack("<%dH" % len(c), *c)
+ return body, o_sec, blobs, bytes(cb), b"".join(erecs)
+
+
+def tilecode(blocks):
+ """Trains the tile coder's starting probabilities on every block and encodes them (tools/tilecode.c)."""
+ import subprocess, tempfile
+ tmp = tempfile.mkdtemp()
+ exe = os.path.join(tmp, "tilecode")
+ subprocess.check_call(["cc", "-O2", "-o", exe, os.path.join(HERE, "tilecode.c")])
+ job = bytearray(struct.pack("<I", len(blocks)))
+ for bits, tiles in blocks:
+ job += struct.pack("<BBH", bits, 0, len(tiles)) + b"".join(tiles)
+ open(os.path.join(tmp, "in.bin"), "wb").write(job)
+ subprocess.check_call([exe, "train", os.path.join(tmp, "in.bin"), os.path.join(tmp, "prior.bin")])
+ subprocess.check_call([exe, "encode", os.path.join(tmp, "in.bin"), os.path.join(tmp, "prior.bin"), os.path.join(tmp, "out.bin")])
+ prior = open(os.path.join(tmp, "prior.bin"), "rb").read()
+ out = open(os.path.join(tmp, "out.bin"), "rb").read()
+ res, p = [], 0
+ for _ in blocks:
+ n = struct.unpack_from("<I", out, p)[0]
+ res.append(out[p + 4:p + 4 + n])
+ p += 4 + n
+ return prior, res
+
+
+def main():
+ t0 = time.time()
+ fp = os.path.join(HERE, "fit.json")
+ if os.path.exists(fp):
+ import json
+ art.FIT.update(json.load(open(fp)))
+ variants, per_room = art.build_variants(ROOMS, visible.compute)
+ print("variants", len(variants), "%.0fs" % (time.time() - t0), flush=True)
+ jobs = [art.Job(v) for v in variants]
+ actors.add_props(ALL_ROOMS)
+ sprites, clips = actors.build()
+ ents.CLIP_INDEX.update({c["id"]: i for i, c in enumerate(clips)})
+ # the rooms' objects, and the sprites they show (after the actors')
+ SPRITES.base = len(sprites)
+ named = actors.named_sprites(SPRITES)
+ prompt_ids = {p: TEXTS.id("Prompts", p.upper(), "PROMPT") for p in PROMPTS}
+ TEXTS.id("Elderbug", "ELDERBUG_INTRO_MAIN") # (until the NPCs: a conversation to try)
+ for r in ROOMS:
+ room_data(r)
+ if r in VARIANT_ROOMS:
+ room_data(r, 1)
+ sprites += actors.unity_sprites(SPRITES.list)
+ # the HUD's geo count: TrajanPro-Bold digits (TextMesh: size 45, character size 1, scale 0.1527)
+ digit_base = len(sprites)
+ digits, digit_adv = font.glyphs("TrajanPro-Bold", "0123456789", 45 * 0.1 * 0.1527 * actors.HUD_K, 1 / actors.HUD_K)
+ sprites += digits
+ print("actor frames", len(sprites), "clips", len(clips), "%.0fs" % (time.time() - t0), flush=True)
+ jobs += [sp["job"] for sp in sprites]
+ with mp.get_context("spawn").Pool(min(4, os.cpu_count() or 1)) as pool:
+ texs = pool.map(art.encode_job, jobs, chunksize=4)
+ # (the actors' textures come after the scenery's)
+ variants = variants + [sp["job"] for sp in sprites]
+ print("textures %.0fs" % (time.time() - t0), flush=True)
+ blocks = []
+ for t in texs:
+ t.first_block = len(blocks)
+ for i in range(0, t.ntiles, art.BLOCK_TILES):
+ blocks.append((t.bits, t.tiles[i:i + art.BLOCK_TILES]))
+ prior, coded = tilecode(blocks)
+ print("tiles coded %.0fs" % (time.time() - t0), flush=True)
+ secs = {k: Blob() for k in SECTIONS}
+ # the starting probabilities as the game uses them: each with its count (tilecode.h: tc_pack)
+ secs["PRIOR"].b += b"".join(struct.pack("<H", v << 4 | TC_N0) for v in struct.unpack("<%dH" % (len(prior) // 2), prior))
+ tex_id = {}
+ pal_at = {} # (palettes shared: once each)
+ nblk = 0
+ texrec = bytearray()
+ for i, (v, t) in enumerate(zip(variants, texs)):
+ tex_id[id(v)] = (i, t.w, t.h)
+ pal_off = 0xFFFFFFFF
+ if t.pal is not None:
+ # (15 colors: RGB565, then alpha; read a byte at a time)
+ pb = b"".join(struct.pack("<HB", (int(r) * 31 + 127) // 255 << 11 | (int(g) * 63 + 127) // 255 << 5 |
+ (int(b) * 31 + 127) // 255, int(a)) for r, g, b, a in t.pal)
+ if pb not in pal_at:
+ pal_at[pb] = secs["PAL"].add(pb, 1)
+ pal_off = pal_at[pb]
+ if t.fmt == art.FMT_SOFTA: # (alpha only: read in place)
+ pal_off = secs["SOFT"].add(t.soft)
+ texrec += struct.pack("<HHBBBBIII", t.w, t.h, 0, 0, t.fmt, 0, pal_off, t.base, 0)
+ continue
+ if t.fmt == art.FMT_SOFT:
+ c = lz(t.soft)
+ pal_off = secs["SOFT"].add(struct.pack("<I", len(c)) + c)
+ texrec += struct.pack("<HHBBBBIII", t.w, t.h, 0, 0, t.fmt, 0, pal_off, t.base, 0)
+ continue
+ # tile map: per row, the rank of its first tile, then 2 bits a tile (0 empty, 1 tile, 3 opaque tile)
+ m = bytearray()
+ rank = 0
+ for ty in range(t.th):
+ m += struct.pack("<H", rank)
+ row = bytearray((t.tw + 3) // 4)
+ for tx in range(t.tw):
+ code = 0 if t.empty[ty, tx] else (3 if t.opaque[ty, tx] else 1)
+ row[tx >> 2] |= code << ((tx & 3) * 2)
+ rank += code != 0
+ m += row
+ map_off = secs["TMAP"].add(bytes(m))
+ bidx = secs["BIDX"].b
+ first = len(bidx) // 4
+ for bl in coded[t.first_block:t.first_block + (t.ntiles + art.BLOCK_TILES - 1) // art.BLOCK_TILES]:
+ bidx += struct.pack("<I", len(secs["BLK"].b))
+ secs["BLK"].b += bl
+ bidx += struct.pack("<I", len(secs["BLK"].b))
+ texrec += struct.pack("<HHBBBBIII", t.w, t.h, t.tw, t.th, t.fmt, 1 if v.blur else 0, pal_off, map_off, first)
+ if os.environ.get("ACTSTATS"):
+ import collections
+ tot = collections.Counter()
+ for j, sp in enumerate(sprites):
+ t = texs[len(variants) - len(sprites) + j]
+ nb = sum(len(b) for b in coded[t.first_block:t.first_block + (t.ntiles + art.BLOCK_TILES - 1) // art.BLOCK_TILES]) if t.fmt not in (art.FMT_SOFTA, art.FMT_SOFT) else len(t.soft or b"")
+ nb += (len(t.pal.tobytes()) if t.pal is not None else 0)
+ tot[str(sp.get("key", ("?",)))[:30].split(",")[0]] += nb
+ for k, v in tot.most_common(40):
+ print("ACT", v, k)
+ secs["TEX"].b += struct.pack("<I", len(variants)) + texrec
+ # actors: each sprite frame's texture and where its top-left corner is (local units), units a texel; the clips
+ first_actor = len(variants) - len(sprites)
+ # (their colliders, as frames set them: 0 none given, 1 none, 2 + an entry: a box or a shape)
+ col_ids, col_entries = {}, []
+ for i, sp in enumerate(sprites):
+ c, cid = sp.get("col"), 0
+ if c and c[0] == "none":
+ cid = 1
+ elif c:
+ b = struct.pack("<BBH4f", 2, 0, 0, *c[1:]) if c[0] == "box" else \
+ struct.pack("<BBH", 3, len(c[1]), 0) + b"".join(struct.pack("<2f", x, y) for x, y in c[1])
+ if b not in col_ids:
+ col_ids[b] = len(col_entries)
+ col_entries.append(b)
+ cid = 2 + col_ids[b]
+ secs["SPR"].b += struct.pack("<HHffff", first_actor + i, cid, sp["lx"], sp["ty"], sp["tu"], sp["tv"])
+ at = 4 + 4 * len(col_entries)
+ secs["SCOL"].b += struct.pack("<I", len(col_entries))
+ for b in col_entries:
+ secs["SCOL"].b += struct.pack("<I", at)
+ at += len(b)
+ for b in col_entries:
+ secs["SCOL"].b += b
+ secs["CLIP"].b += struct.pack("<I", len(clips))
+ frames = []
+ for c in clips:
+ secs["CLIP"].b += struct.pack("<HHfBBH", len(frames), len(c["frames"]), c["fps"], c["wrap"], c["loop"], 0)
+ frames += [sid | (0x8000 if trig else 0) for sid, trig in c["frames"]]
+ secs["CLIP"].b += struct.pack("<%dH" % len(frames), *frames)
+ with open(os.path.join(unity.CACHE, "texnames.txt"), "w") as f:
+ for i, (v, t) in enumerate(zip(variants, texs)):
+ name = v.name if isinstance(v, art.ImageJob) else v.sprite.name
+ f.write("%d %s %.3f %d %d %dx%d %d\n" % (i, name.replace(" ", "_"), getattr(v, "scale", 1.0), v.blur, v.alpha_only,
+ t.w, t.h, t.ntiles))
+ rooms = bytearray(struct.pack("<I", len(ROOMS) + len(VARIANT_ROOMS)))
+ sector_offs, rvar = {}, bytearray(struct.pack("<I", len(VARIANT_ROOMS)))
+ pdf = _pdf_flags()
+ for r in ROOMS + [r + "@1" for r in VARIANT_ROOMS]:
+ base, variant = (r[:-2], 1) if r.endswith("@1") else (r, 0)
+ keep, st = per_room[base]
+ body, o_sec, blobs, ground, recs = room_blobs(base, keep, st, tex_id, variant)
+ struct.pack_into("<I", body, 76, secs["RBLOB"].add(ground))
+ struct.pack_into("<I", body, 80, secs["RBLOB"].add(recs))
+ packed = 0
+ for i, (c, n) in enumerate(blobs):
+ # (a room's variant: the same sectors)
+ off = sector_offs[(base, i)] if variant else secs["RBLOB"].add(c)
+ sector_offs[(base, i)] = off
+ struct.pack_into("<II", body, o_sec + 20 * i, off, len(c))
+ packed += len(c)
+ if variant:
+ # its variants: which entry, by which PlayerData bool, and each one's groups to hide in the other
+ (flag, val), spans = next(((a[1], a[2]) for a in scene.additive(base)), ("", False)), room_data(base)[2]
+ s1, s2 = spans.get(1, (0, 0)), spans.get(2, (0, 0))
+ rvar += struct.pack("<HHHBB4H", ROOMS.index(base), len(ROOMS) + VARIANT_ROOMS.index(base), pdf[flag], val, 0,
+ *s1, *s2)
+ hc = lz(bytes(body))
+ off = secs["RBLOB"].add(hc)
+ assert len(r) < 32, r
+ rooms += struct.pack("<32sIII", base.encode(), off, len(hc), len(body))
+ print("room %-26s %5d instances in %2d sectors, %6d packed, ground %d, recs %d" % (r, len(keep), len(blobs), packed + len(hc), len(ground), len(recs)), flush=True)
+ secs["ROOMS"].b += rooms
+ secs["RVAR"].b += rvar
+ secs["STR"].b += STRINGS.blob()
+ secs["TEXT"].b += TEXTS.blob()
+ secs["FONT"].b += TEXTS.fonts()
+ secs["PHASH"].b += PERSIST.blob()
+ # the file: "HKNW", count, then (offset, size) per section
+ head = struct.pack("<4sI", b"HKNW", len(SECTIONS))
+ pos = len(head) + 8 * len(SECTIONS)
+ table = bytearray()
+ body = bytearray()
+ for k in SECTIONS:
+ while (pos + len(body)) % 4:
+ body.append(0)
+ table += struct.pack("<II", pos + len(body), len(secs[k].b))
+ body += secs[k].b
+ data = head + table + body
+ open(os.path.join(SRC, "data.bin"), "wb").write(data)
+ sizes = {k: len(secs[k].b) for k in SECTIONS}
+ print("data.bin", len(data), sizes, "%.0fs" % (time.time() - t0))
+ with open(os.path.join(SRC, "data.h"), "w") as f:
+ f.write("/* made by tools/pack.py */\n#pragma once\n")
+ for i, k in enumerate(SECTIONS):
+ f.write("#define SEC_%s %d\n" % (k, i))
+ f.write("#define NUM_ROOMS %d\n" % len(ROOMS))
+ for i, r in enumerate(ROOMS):
+ f.write("#define ROOM_%s %d\n" % (r.upper(), i))
+ for i, c in enumerate(clips):
+ f.write("#define %s %d\n" % (c["id"], i))
+ for k, v in named.items():
+ f.write("#define SPRITE_%s %d\n" % (k, v))
+ f.write("#define SPRITE_DIGIT0 %d\n" % digit_base)
+ for i, k in enumerate(text.STYLES):
+ f.write("#define STYLE_%s %d\n" % (k, i))
+ f.write("#define TEXT_K %.6ff\n#define FONT_PHASES %d\n" % (text.TEXT_K, text.PHASES))
+ for i, k in enumerate(actors.ENEMY_KINDS):
+ f.write("#define EK_%s %d\n" % (k[0].upper(), i + 1))
+ f.write("#define NUM_KINDS %d\n" % (len(actors.ENEMY_KINDS) + 1))
+ f.write("#define KIND_TABLE %s\n" % actors.kind_table({c["id"]: i for i, c in enumerate(clips)}))
+ for k, v in prompt_ids.items():
+ f.write("#define TXT_PROMPT_%s %d\n" % (k.upper(), v))
+ f.write("#define PROMPT_SORT %du\n" % ((scene.layer_index(-349214895) << 16) | (1 + 32768)))
+ f.write("#define DIGIT_ADV {%s}\n" % ", ".join("%.4ff" % a for a in digit_adv))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/games/hollowknight/tools/tilecode.c b/games/hollowknight/tools/tilecode.c
index 611e22ab..485ac343 100644
--- a/games/hollowknight/tools/tilecode.c
+++ b/games/hollowknight/tools/tilecode.c
@@ -1,8 +1,10 @@
-/* Scenery tile coding for pack.py: trains the starting probabilities and encodes blocks of tiles.
- * tilecode train IN PRIOR (PRIOR: 256x16 then 16x4 uint16 probabilities)
+/* Scenery tile coding for pack.py (the model: src/tilecode.h): trains the starting probabilities and encodes blocks.
+ * tilecode train IN PRIOR (PRIOR: the tables as the game starts them, TC_N4 then TC_N2 uint16)
* tilecode encode IN PRIOR OUT
- * IN: u32 blocks, then per block: u8 bits (4 or 2), u8 0, u16 tiles, tiles x 256 (or 512, 2 bits) texels (one a byte).
+ * IN: u32 blocks, then per block: u8 bits (4 or 2), u8 0, u16 tiles, per tile the one to its left and the one above in
+ * the block (u8 each, 255: none), then tiles x 256 (or 512, 2 bits) texels (one a byte).
* OUT: per block, u32 size and its bytes. */
+#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -10,7 +12,7 @@
typedef struct {
int bits, n;
- uint8_t *tex;
+ uint8_t *nb, *tex;
} Block;
static Block *blocks;
@@ -29,47 +31,162 @@ static void load(const char *path) {
blocks[i].bits = h[0];
blocks[i].n = h[2] | h[3] << 8;
size_t sz = blocks[i].bits == 2 ? 512 : 256;
+ blocks[i].nb = malloc((size_t)blocks[i].n * 2);
blocks[i].tex = malloc((size_t)blocks[i].n * sz);
+ if (fread(blocks[i].nb, 2, (size_t)blocks[i].n, f) != (size_t)blocks[i].n) exit(1);
if (fread(blocks[i].tex, sz, (size_t)blocks[i].n, f) != (size_t)blocks[i].n) exit(1);
}
fclose(f);
}
-static double cnt4[TC_CTX4][16][2], cnt2[TC_CTX2][4][2];
-static uint16_t prior4[TC_CTX4][16], prior2[TC_CTX2][4];
+/* ---------------------------------------------------------------- the model: a tile's binary steps */
+static void (*code_bit)(int slot, int bit); /* (training: noted; encoding: coded) */
-static void train(void) {
- for (int b = 0; b < nblocks; b++) {
- Block *B = &blocks[b];
- for (int t = 0; t < B->n; t++) {
- int W = B->bits == 2 ? 32 : 16;
- const uint8_t *img = B->tex + (size_t)(W * 16) * t;
- for (int y = 0; y < 16; y++)
- for (int x = 0; x < W; x++) {
- int l = tc_left(img, x, y, W), u = tc_up(img, x, y, l, W), s = img[y * W + x], node = 1;
- if (B->bits == 4) {
- int c = l * 16 + u;
- for (int k = 3; k >= 0; k--) {
- int bit = s >> k & 1;
- cnt4[c][node][bit] += 1;
- node = node * 2 + bit;
- }
- } else {
- int c = l * 4 + u;
- for (int k = 1; k >= 0; k--) {
- int bit = s >> k & 1;
- cnt2[c][node][bit] += 1;
- node = node * 2 + bit;
- }
- }
+static void tree4(int base, int v) {
+ for (int k = 3, node = 1; k >= 0; k--) {
+ int bit = v >> k & 1;
+ code_bit(base + node, bit);
+ node = node * 2 + bit;
+ }
+}
+static void tree2(int base, int v) {
+ code_bit(base, v >> 1);
+ code_bit(base + 1 + (v >> 1), v & 1);
+}
+
+static void code_tile(const Block *B, int t) {
+ int w = B->bits == 2 ? 32 : 16, s = TC_STRIDE(w);
+ const uint8_t *tex = B->tex + (size_t)(w * 16) * t;
+ const uint8_t *lt = B->nb[2 * t] != 255 ? B->tex + (size_t)(w * 16) * B->nb[2 * t] : NULL;
+ const uint8_t *ut = B->nb[2 * t + 1] != 255 ? B->tex + (size_t)(w * 16) * B->nb[2 * t + 1] : NULL;
+ /* the tile in its borders (as the decoder has them: the row above and the copied last column as each row is done) */
+ uint8_t img[17 * TC_STRIDE(32)];
+ memset(img, 0, sizeof img);
+ for (int y = 0; y < 16; y++) {
+ uint8_t *r = img + (y + 1) * s + 2;
+ if (lt) r[-2] = lt[y * w + w - 2], r[-1] = lt[y * w + w - 1];
+ memcpy(r, tex + y * w, (size_t)w);
+ r[w] = r[w - 1];
+ }
+ if (ut) {
+ uint8_t *a = img + 2;
+ memcpy(a, ut + 15 * w, (size_t)w);
+ a[-1] = a[s - 1], a[w] = a[w - 1];
+ }
+ for (int y = 0; y < 16; y++) {
+ const uint8_t *r = img + (y + 1) * s + 2, *a = r - s;
+ for (int x = 0; x < w; x++) {
+ int v = r[x], l = r[x - 1], ll = r[x - 2];
+ if (!y && !ut) { /* the top row on its own */
+ if (w == 32) tree2(tc_c20(l, ll), v);
+ else {
+ code_bit(tc_f0(l, ll), v != l);
+ if (v != l) tree4(tc_tree(l, l), v);
}
+ continue;
+ }
+ int u = a[x], ul = a[x - 1], ur = a[x + 1];
+ if (w == 32) {
+ tree2(tc_c2(l, u, ul, ur), v);
+ continue;
+ }
+ code_bit(tc_fl(l, u, ul, ur, ll), v != l);
+ if (v == l) continue;
+ if (u != l) {
+ code_bit(tc_fu(l, u, ul), v != u);
+ if (v == u) continue;
+ }
+ tree4(tc_tree(l, u), v);
}
}
}
-static int clip_p(double c0, double c1) {
- int p = (int)(4096.0 * (c0 + 0.5) / (c0 + c1 + 1.0) + 0.5);
- return p < 64 ? 64 : p > 4032 ? 4032 : p;
+/* ---------------------------------------------------------------- training */
+/* every binary step, with its table (4-bit tiles' first, then the 2-bit tiles' after TC_N4) */
+#define NSLOTS (TC_N4 + TC_N2)
+static uint16_t *st_slot;
+static uint8_t *st_bit;
+static int *st_block;
+static size_t nst, capst;
+static int cur_block, cur_base;
+
+static void note_bit(int slot, int bit) {
+ if (nst == capst) {
+ capst = capst ? capst * 2 : 1 << 20;
+ st_slot = realloc(st_slot, capst * sizeof *st_slot), st_bit = realloc(st_bit, capst);
+ st_block = realloc(st_block, capst * sizeof *st_block);
+ }
+ st_slot[nst] = (uint16_t)(cur_base + slot), st_bit[nst] = (uint8_t)bit, st_block[nst] = cur_block, nst++;
+}
+
+static double lg[4097];
+
+/* the cost (bits) of a table's steps (bits, each block's first marked) started at p0 in state n0 */
+static double run_cost(const uint8_t *bits, const uint8_t *first, size_t n, int p0, int n0) {
+ double c = 0;
+ uint16_t pv = 0;
+ for (size_t i = 0; i < n; i++) {
+ if (first[i]) pv = (uint16_t)(p0 << 4 | n0);
+ int p = pv >> 4;
+ c += bits[i] ? lg[4096 - p] : lg[p];
+ pv = tc_update(pv, bits[i]);
+ }
+ return c;
+}
+
+static uint16_t prior[NSLOTS];
+
+/* the best p0 for a state n0 (the cost is about convex in p0: a golden section search), and its cost */
+static int best_p0(const uint8_t *bits, const uint8_t *first, size_t n, int n0, double *cost) {
+ int a = 1, b = 4095, c = b - (b - a) * 618 / 1000, d = a + (b - a) * 618 / 1000;
+ double fc = run_cost(bits, first, n, c, n0), fd = run_cost(bits, first, n, d, n0);
+ while (b - a > 8 && c < d) {
+ if (fc < fd) b = d, d = c, fd = fc, c = b - (b - a) * 618 / 1000, fc = run_cost(bits, first, n, c, n0);
+ else a = c, c = d, fc = fd, d = a + (b - a) * 618 / 1000, fd = run_cost(bits, first, n, d, n0);
+ }
+ int best = a;
+ *cost = 1e300;
+ for (int p0 = a; p0 <= b; p0++) {
+ double f = run_cost(bits, first, n, p0, n0);
+ if (f < *cost) *cost = f, best = p0;
+ }
+ return best;
+}
+
+/* each table's start: the probability and state that code its steps in every block best */
+static void train(void) {
+ code_bit = note_bit;
+ for (int b = 0; b < nblocks; b++) {
+ cur_block = b, cur_base = blocks[b].bits == 2 ? TC_N4 : 0;
+ for (int t = 0; t < blocks[b].n; t++) code_tile(&blocks[b], t);
+ }
+ for (int i = 1; i <= 4096; i++) lg[i] = -log2(i / 4096.0);
+ /* the steps by table, in order */
+ size_t *at = calloc(NSLOTS + 1, sizeof *at);
+ for (size_t i = 0; i < nst; i++) at[st_slot[i] + 1]++;
+ for (int s = 0; s < NSLOTS; s++) at[s + 1] += at[s];
+ size_t *pos = malloc(NSLOTS * sizeof *pos);
+ memcpy(pos, at, NSLOTS * sizeof *pos);
+ uint8_t *bits = malloc(nst), *first = malloc(nst);
+ int *last = malloc(NSLOTS * sizeof *last), *k = calloc(NSLOTS, sizeof *k);
+ for (int s = 0; s < NSLOTS; s++) last[s] = -1;
+ for (size_t i = 0; i < nst; i++) {
+ int s = st_slot[i];
+ if (last[s] != st_block[i]) last[s] = st_block[i], k[s] = 0;
+ if (k[s]++ >= 1024) continue; /* (the start long forgotten: the rest costs the same whatever it was) */
+ bits[pos[s]] = st_bit[i], first[pos[s]] = k[s] == 1, pos[s]++;
+ }
+ for (int s = 0; s < NSLOTS; s++) {
+ size_t a = at[s], n = pos[s] - a;
+ prior[s] = (uint16_t)(2048 << 4);
+ if (!n) continue;
+ double best = 1e300, c;
+ for (int n0 = 0; n0 < 7; n0++) {
+ int p0 = best_p0(bits + a, first + a, n, n0, &c);
+ if (c < best) best = c, prior[s] = (uint16_t)(p0 << 4 | n0);
+ }
+ }
+ free(at), free(pos), free(bits), free(first), free(last), free(k);
}
/* ---------------------------------------------------------------- range coder (LZMA's) */
@@ -96,43 +213,37 @@ static void shift_low(void) {
cache_size++;
low = (low & 0x00FFFFFFu) << 8;
}
-static void enc_bit(uint16_t *pr, int bit) {
+
+static uint16_t probs[TC_N4];
+
+static void enc_bit(int slot, int bit) {
+ uint16_t *pr = &probs[slot];
uint32_t bound = (range >> TC_PROB_BITS) * (uint32_t)(*pr >> 4);
if (!bit) range = bound;
else low += bound, range -= bound;
while (range < (1u << 24)) range <<= 8, shift_low();
- tc_update(pr, bit);
+ *pr = tc_update(*pr, bit);
}
-static uint16_t p4[TC_CTX4][16], p2[TC_CTX2][4];
-
static void encode_block(const Block *B) {
low = 0, range = 0xFFFFFFFFu, cache = 0, cache_size = 1, outn = 0;
- for (int c = 0; c < TC_CTX4; c++)
- for (int k = 0; k < 16; k++) p4[c][k] = tc_pack(prior4[c][k], TC_N0);
- for (int c = 0; c < TC_CTX2; c++)
- for (int k = 0; k < 4; k++) p2[c][k] = tc_pack(prior2[c][k], TC_N0);
- for (int t = 0; t < B->n; t++) {
- int W = B->bits == 2 ? 32 : 16;
- const uint8_t *img = B->tex + (size_t)(W * 16) * t;
- for (int y = 0; y < 16; y++)
- for (int x = 0; x < W; x++) {
- int l = tc_left(img, x, y, W), u = tc_up(img, x, y, l, W), s = img[y * W + x], node = 1;
- if (B->bits == 4)
- for (int k = 3; k >= 0; k--) {
- int bit = s >> k & 1;
- enc_bit(&p4[l * 16 + u][node], bit);
- node = node * 2 + bit;
- }
- else
- for (int k = 1; k >= 0; k--) {
- int bit = s >> k & 1;
- enc_bit(&p2[l * 4 + u][node], bit);
- node = node * 2 + bit;
- }
- }
+ if (B->bits == 2) memcpy(probs, prior + TC_N4, TC_N2 * 2);
+ else memcpy(probs, prior, TC_N4 * 2);
+ code_bit = enc_bit;
+ for (int t = 0; t < B->n; t++) code_tile(B, t);
+ /* the end: the value with the most free bytes after it that is in the last range (whatever follows the block
+ * then, it decodes the same: the game reads up to 3 bytes past it) */
+ for (int k = 1; k <= 4; k++) {
+ uint64_t g = 1ull << (32 - 8 * k), v = (low + g - 1) & ~(g - 1);
+ if (v + g <= low + range) {
+ low = v;
+ for (int i = 0; i <= k; i++) shift_low();
+ break;
+ }
}
- for (int i = 0; i < 5; i++) shift_low();
+ /* (the first byte is always 0: not kept) */
+ if (!outn || out[0]) exit(2);
+ memmove(out, out + 1, --outn);
}
int main(int argc, char **argv) {
@@ -140,19 +251,14 @@ int main(int argc, char **argv) {
load(argv[2]);
if (!strcmp(argv[1], "train")) {
train();
- for (int c = 0; c < TC_CTX4; c++)
- for (int k = 0; k < 16; k++) prior4[c][k] = (uint16_t)clip_p(cnt4[c][k][0], cnt4[c][k][1]);
- for (int c = 0; c < TC_CTX2; c++)
- for (int k = 0; k < 4; k++) prior2[c][k] = (uint16_t)clip_p(cnt2[c][k][0], cnt2[c][k][1]);
FILE *f = fopen(argv[3], "wb");
- fwrite(prior4, sizeof prior4, 1, f);
- fwrite(prior2, sizeof prior2, 1, f);
+ fwrite(prior, sizeof prior, 1, f);
fclose(f);
return 0;
}
if (!strcmp(argv[1], "encode") && argc >= 5) {
FILE *f = fopen(argv[3], "rb");
- if (!f || fread(prior4, sizeof prior4, 1, f) != 1 || fread(prior2, sizeof prior2, 1, f) != 1) return 1;
+ if (!f || fread(prior, sizeof prior, 1, f) != 1) return 1;
fclose(f);
FILE *o = fopen(argv[4], "wb");
for (int b = 0; b < nblocks; b++) {