-
Notifications
You must be signed in to change notification settings - Fork 11
/
level.go
825 lines (793 loc) · 25.4 KB
/
level.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
// Copyright 2021 Google LLC
//
// Licensed under the Apache Livense, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package level
import (
"fmt"
"strconv"
"strings"
"github.com/fardog/tmx"
"github.com/mitchellh/hashstructure/v2"
"github.com/divVerent/aaaaxy/internal/flag"
"github.com/divVerent/aaaaxy/internal/log"
m "github.com/divVerent/aaaaxy/internal/math"
"github.com/divVerent/aaaaxy/internal/splash"
"github.com/divVerent/aaaaxy/internal/version"
"github.com/divVerent/aaaaxy/internal/vfs"
)
var (
debugCheckTnihSigns = flag.Bool("debug_check_tnih_signs", false, "if set, we verify that all checkpoints have a TnihSign")
)
// Level is a parsed form of a loaded level.
type Level struct {
Player *Spawnable
Checkpoints map[string]*Spawnable
TnihSignsByCheckpoint map[string][]*Spawnable
CheckpointLocations *CheckpointLocations
CheckpointLocationsHash uint64
SaveGameVersion int
CreditsMusic string
Hash uint64 `hash:"-"`
tiles []LevelTile
width int
}
// Tile returns the tile at the given position.
func (l *Level) Tile(pos m.Pos) *LevelTile {
i := pos.X + pos.Y*l.width
t := &l.tiles[i]
if !t.Valid {
return nil
}
return t
}
// setTile sets the tile at the given position.
func (l *Level) setTile(pos m.Pos, t *LevelTile) {
i := pos.X + pos.Y*l.width
l.tiles[i] = *t
}
// ForEachTile iterates over all tiles in the level.
func (l *Level) ForEachTile(f func(pos m.Pos, t *LevelTile)) {
for i := range l.tiles {
f(m.Pos{X: i % l.width, Y: i / l.width}, &l.tiles[i])
}
}
// LevelTile is a single tile in the level.
type LevelTile struct {
Tile Tile
WarpZones []*WarpZone
Valid bool
}
// WarpZone represents a warp tile. Whenever anything enters this tile, it gets
// moved to "to" and the direction transformed by "transform". For the game to
// work, every warpZone must be paired with an exact opposite elsewhere. This
// is ensured at load time. Warpzones can be temporarily toggled by name; this
// state is lost on checkpoint restore.
type WarpZone struct {
Name string
Invert bool
Switchable bool
PrevTile m.Pos
ToTile m.Pos
Transform m.Orientation
}
// SaveGameDataV1 is a not-yet-hashed SaveGame.
type SaveGameDataV1 struct {
State map[EntityID]PersistentState `hash:"-"`
GameVersion string
LevelVersion int
LevelHash uint64
}
// SaveGame is the data structure we save game state with.
// It contains all needed (in addition to loading the level) to reset to the last visited checkpoint.
// Separate hashes govern the info parts and the state itself so demo regression testing can work across version changes.
type SaveGame struct {
SaveGameDataV1
InfoHash uint64
StateHash uint64
// Legacy hash for v0 save games.
Hash uint64 `json:",omitempty"`
}
// SaveGameData is a not-yet-hashed SaveGame.
type SaveGameData struct {
State map[EntityID]PersistentState
LevelVersion int
LevelHash uint64
}
// SaveGame returns the current state as a SaveGame.
func (l *Level) SaveGame() (*SaveGame, error) {
if l.SaveGameVersion != 1 {
return nil, fmt.Errorf("please FIXME! On the next SaveGameVersion, please remove the SaveGameData v0 support, make all uint64 hashes `json:\",string\"`, and remove this check too")
}
save := &SaveGame{
SaveGameDataV1: SaveGameDataV1{
State: map[EntityID]PersistentState{},
GameVersion: version.Revision(),
LevelVersion: l.SaveGameVersion,
LevelHash: l.Hash,
},
}
saveOne := func(sp *Spawnable) {
if len(sp.PersistentState) > 0 {
save.State[sp.ID] = sp.PersistentState
}
}
l.ForEachTile(func(_ m.Pos, tile *LevelTile) {
for _, sp := range tile.Tile.Spawnables {
saveOne(sp)
}
})
saveOne(l.Player)
var err error
save.StateHash, err = hashstructure.Hash(save.State, hashstructure.FormatV2, nil)
if err != nil {
return nil, err
}
save.InfoHash, err = hashstructure.Hash(save.SaveGameDataV1, hashstructure.FormatV2, nil)
if err != nil {
return nil, err
}
return save, nil
}
// Clone clones the given Level to a new Level struct sharing no persistent state data.
func (l *Level) Clone() *Level {
// First make a shallow copy.
out := new(Level)
*out = *l
// Now "deepen" all that's needed. This means all Spawnable objects.
// As they heavily alias each other, keep a map so the aliasing stays intact.
clones := map[*Spawnable]*Spawnable{}
clone := func(sp *Spawnable) *Spawnable {
cloned := clones[sp]
if cloned == nil {
cloned = sp.Clone()
clones[sp] = cloned
}
return cloned
}
out.Player = clone(out.Player)
out.Checkpoints = make(map[string]*Spawnable, len(l.Checkpoints))
for cp, cpSp := range l.Checkpoints {
out.Checkpoints[cp] = clone(cpSp)
}
out.TnihSignsByCheckpoint = make(map[string][]*Spawnable, len(l.TnihSignsByCheckpoint))
for cp, signs := range l.TnihSignsByCheckpoint {
outSigns := make([]*Spawnable, len(signs))
out.TnihSignsByCheckpoint[cp] = outSigns
for i, sign := range signs {
outSigns[i] = clone(sign)
}
}
out.tiles = make([]LevelTile, len(l.tiles))
for i := range l.tiles {
tile := &l.tiles[i]
outTile := &out.tiles[i]
*outTile = *tile
outTile.Tile.Spawnables = make([]*Spawnable, len(tile.Tile.Spawnables))
for i, sp := range tile.Tile.Spawnables {
outTile.Tile.Spawnables[i] = clone(sp)
}
}
return out
}
// LoadGame loads the given SaveGame into the map.
// Note that when this returns an error, the SaveGame might have been partially loaded and the world may need to be reset.
func (l *Level) LoadGame(save *SaveGame) error {
if save.Hash != 0 && save.InfoHash == 0 && save.StateHash == 0 {
saveV0 := &SaveGameData{
State: save.State,
LevelVersion: save.LevelVersion,
LevelHash: save.LevelHash,
}
saveHash, err := hashstructure.Hash(saveV0, hashstructure.FormatV2, nil)
if err != nil {
return err
}
if saveHash != save.Hash {
return fmt.Errorf("someone tampered with the save game: got %v, want %v", saveHash, save.Hash)
}
} else {
infoHash, err := hashstructure.Hash(save.SaveGameDataV1, hashstructure.FormatV2, nil)
if err != nil {
return err
}
if infoHash != save.InfoHash {
return fmt.Errorf("someone tampered with the save game info")
}
stateHash, err := hashstructure.Hash(save.State, hashstructure.FormatV2, nil)
if err != nil {
return err
}
if stateHash != save.StateHash {
return fmt.Errorf("someone tampered with the save game state")
}
}
if save.GameVersion != version.Revision() {
log.Warningf("save game does not match game version: got %v, want %v", save.GameVersion, version.Revision())
}
if save.LevelVersion != l.SaveGameVersion {
return fmt.Errorf("save game does not match level version: got %v, want %v", save.LevelVersion, l.SaveGameVersion)
}
if save.LevelHash != l.Hash {
log.Warningf("save game does not match level hash: got %v, want %v; trying to load anyway", save.LevelHash, l.Hash)
}
loadOne := func(sp *Spawnable) {
// Do not reallocate the map! Works better with already loaded entities.
for key := range sp.PersistentState {
delete(sp.PersistentState, key)
}
for key, value := range save.State[sp.ID] {
sp.PersistentState[key] = value
}
}
l.ForEachTile(func(_ m.Pos, tile *LevelTile) {
for _, sp := range tile.Tile.Spawnables {
loadOne(sp)
}
})
loadOne(l.Player)
return nil
}
func (l *Level) applyTileMod(startTile, endTile m.Pos, mods map[string]string) {
var add, remove Contents
switch mods["object_solid"] {
case "true":
add |= ObjectSolidContents
case "false":
remove |= ObjectSolidContents
}
switch mods["opaque"] {
case "true":
add |= OpaqueContents
case "false":
remove |= OpaqueContents
}
switch mods["player_solid"] {
case "true":
add |= PlayerSolidContents
case "false":
remove |= PlayerSolidContents
}
switch mods["solid"] {
case "true":
add |= SolidContents
case "false":
remove |= SolidContents
}
for y := startTile.Y; y <= endTile.Y; y++ {
for x := startTile.X; x <= endTile.X; x++ {
t := l.Tile(m.Pos{X: x, Y: y})
if t == nil {
continue
}
t.Tile.Contents |= add
t.Tile.Contents &= ^remove
}
}
}
func FetchTileset(ts *tmx.TileSet) error {
if ts.Source != "" {
r, err := vfs.LoadPath("tiles", ts.Source)
if err != nil {
return fmt.Errorf("could not open tileset: %w", err)
}
defer r.Close()
decoded, err := tmx.DecodeTileset(r)
if err != nil {
return fmt.Errorf("could not decode tileset: %w", err)
}
decoded.FirstGlobalID = ts.FirstGlobalID
decoded.Source = ts.Source
*ts = *decoded
}
if ts.TileWidth != TileSize || ts.TileHeight != TileSize {
return fmt.Errorf("unsupported tileset: got tile size %dx%d, want %dx%d", ts.TileWidth, ts.TileHeight, TileSize, TileSize)
}
// ts.Spacing, ts.Margin, ts.TileCount, ts.Columns doesn't matter (we only support multi image tilesets).
if ts.ObjectAlignment != "topleft" {
return fmt.Errorf("unsupported tileset: got objectalignment %q, want topleft", ts.ObjectAlignment)
}
// ts.Properties doesn't matter.
if ts.TileOffset.X != 0 || ts.TileOffset.Y != 0 {
return fmt.Errorf("unsupported tileset: got a tile offset")
}
if ts.Image.Source != "" {
return fmt.Errorf("unsupported tileset: got single image, want image collection")
}
// ts.TerrainTypes doesn't matter (editor only).
// ts.Tiles used later.
return nil
}
func parseTmx(t *tmx.Map) (*Level, error) {
if t.Orientation != "orthogonal" {
return nil, fmt.Errorf("unsupported map: got orientation %q, want orthogonal", t.Orientation)
}
// t.RenderOrder doesn't matter.
// t.Width, t.Height used later.
if t.TileWidth != TileSize || t.TileHeight != TileSize {
return nil, fmt.Errorf("unsupported map: got tile size %dx%d, want %dx%d", t.TileWidth, t.TileHeight, TileSize, TileSize)
}
// t.HexSideLength doesn't matter.
// t.StaggerAxis doesn't matter.
// t.StaggerIndex doesn't matter.
// t.BackgroundColor doesn't matter.
// t.NextObjectID doesn't matter.
// t.TileSets used later.
// t.Properties used later.
if len(t.Layers) != 1 {
return nil, fmt.Errorf("unsupported map: got %d layers, want 1", len(t.Layers))
}
// t.ObjectGroups used later.
if len(t.ImageLayers) != 0 {
return nil, fmt.Errorf("unsupported map: got %d image layers, want 0", len(t.ImageLayers))
}
for i := range t.TileSets {
err := FetchTileset(&t.TileSets[i])
if err != nil {
return nil, fmt.Errorf("unsupported map: failed to decode tileset %d: %w", i, err)
}
}
layer := &t.Layers[0]
if layer.X != 0 || layer.Y != 0 {
return nil, fmt.Errorf("unsupported map: layer has been shifted")
}
// layer.Width, layer.Height used later.
// layer.Opacity, layer.Visible not used (we allow it though as it may help in the editor).
if layer.OffsetX != 0 || layer.OffsetY != 0 {
return nil, fmt.Errorf("unsupported map: layer has an offset")
}
// layer.Properties not used.
// layer.RawData not used.
tds, err := layer.TileDefs(t.TileSets)
if err != nil {
return nil, fmt.Errorf("invalid map layer: %w", err)
}
saveGameVersion, err := t.Properties.Int("save_game_version")
if err != nil {
return nil, fmt.Errorf("unsupported map: could not read save_game_version: %w", err)
}
var creditsMusic string
if prop := t.Properties.WithName("credits_music"); prop != nil {
creditsMusic = prop.Value
}
var checkpointLocationsHash uint64
if prop := t.Properties.WithName("checkpoint_locations_hash"); prop != nil {
_, err := fmt.Sscanf(prop.Value, "%d", &checkpointLocationsHash)
if err != nil {
return nil, fmt.Errorf("unsupported map: could not parse checkpoint_locations_hash")
}
}
level := Level{
Checkpoints: map[string]*Spawnable{},
TnihSignsByCheckpoint: map[string][]*Spawnable{},
CheckpointLocationsHash: checkpointLocationsHash,
SaveGameVersion: int(saveGameVersion),
CreditsMusic: creditsMusic,
tiles: make([]LevelTile, layer.Width*layer.Height),
width: layer.Width,
}
var tnihSigns []*Spawnable
checkpoints := map[EntityID]*Spawnable{}
for i, td := range tds {
if td.Nil {
continue
}
if td.Tile == nil {
return nil, fmt.Errorf("invalid tiledef: %v [%s]", td, td.TileSet.Source)
}
// td.Tile.Probability not used (editor only).
// td.Tile.Properties used later.
// td.Tile.Image used later.
if len(td.Tile.Animation) != 0 {
return nil, fmt.Errorf("unsupported tileset: got an animation")
}
if len(td.Tile.ObjectGroup.Objects) != 0 {
return nil, fmt.Errorf("unsupported tileset: got objects in a tile")
}
// td.Tile.RawTerrainType not used (editor only).
pos := m.Pos{X: i % layer.Width, Y: i / layer.Width}
orientation := m.Identity()
if td.HorizontallyFlipped {
orientation = m.FlipX().Concat(orientation)
}
if td.VerticallyFlipped {
orientation = m.FlipY().Concat(orientation)
}
if td.DiagonallyFlipped {
orientation = m.FlipD().Concat(orientation)
}
properties := map[string]string{}
for i := range td.Tile.Properties {
prop := &td.Tile.Properties[i]
properties[prop.Name] = prop.Value
}
var contents Contents
if properties["solid"] != "false" {
contents |= SolidContents
}
if properties["opaque"] != "false" {
contents |= OpaqueContents
}
imgSrc := td.Tile.Image.Source
imgSrcByOrientation, err := ParseImageSrcByOrientation(imgSrc, properties)
if err != nil {
return nil, fmt.Errorf("invalid map: %w", err)
}
level.setTile(pos, &LevelTile{
Tile: Tile{
Contents: contents,
LevelPos: pos,
ImageSrc: imgSrc,
imageSrcByOrientation: imgSrcByOrientation,
Orientation: orientation,
},
Valid: true,
})
}
type RawWarpZone struct {
StartTile, EndTile m.Pos
Orientation m.Orientation
Invert bool
Switchable bool
}
warpZones := map[string][]*RawWarpZone{}
for i := range t.ObjectGroups {
og := &t.ObjectGroups[i]
// og.Name, og.Color not used (editor only).
if og.X != 0 || og.Y != 0 {
return nil, fmt.Errorf("unsupported map: object group has been shifted")
}
// og.Width, og.Height not used.
// og.Opacity, og.Visible not used (we allow it though as it may help in the editor).
if og.OffsetX != 0 || og.OffsetY != 0 {
return nil, fmt.Errorf("unsupported map: object group has an offset")
}
// og.DrawOrder not used (we use our own z index).
// og.Properties not used.
for j := range og.Objects {
o := &og.Objects[j]
// o.ObjectID used later.
properties := map[string]string{}
if o.Name != "" {
properties["name"] = o.Name
}
// o.X, o.Y, o.Width, o.Height used later.
if o.Rotation != 0 {
return nil, fmt.Errorf("unsupported map: object %v has a rotation (maybe implement this?)", o.ObjectID)
}
if o.GlobalID != 0 {
var tile *tmx.Tile
for k := range t.TileSets {
ts := &t.TileSets[k]
tile = ts.TileWithID(o.GlobalID.TileID(ts))
if tile != nil {
break
}
}
if tile == nil {
return nil, fmt.Errorf("unsupported map: object %v references nonexisting tile %d", o.ObjectID, o.GlobalID)
}
if tile.Type == "" {
properties["type"] = "Sprite"
} else {
properties["type"] = tile.Type
}
properties["image_dir"] = "tiles"
properties["image"] = tile.Image.Source
for k := range tile.Properties {
prop := &tile.Properties[k]
properties[prop.Name] = prop.Value
}
}
// o.Visible not used (we allow it though as it may help in the editor).
if o.Polygons != nil {
return nil, fmt.Errorf("unsupported map: object %v has polygons", o.ObjectID)
}
if o.Polylines != nil {
return nil, fmt.Errorf("unsupported map: object %v has polylines", o.ObjectID)
}
if o.Image.Source != "" {
properties["type"] = "Sprite"
properties["image_dir"] = "sprites"
properties["image"] = o.Image.Source
}
if o.Type != "" {
properties["type"] = o.Type
}
for k := range o.Properties {
prop := &o.Properties[k]
properties[prop.Name] = prop.Value
}
// o.RawExtra not used.
entRect := m.Rect{
Origin: m.Pos{
X: int(o.X),
Y: int(o.Y),
},
Size: m.Delta{
DX: int(o.Width),
DY: int(o.Height),
},
}
var spawnTilesGrowth m.Delta
if s, found := properties["spawn_tiles_growth"]; found {
_, err := fmt.Sscanf(s, "%d %d", &spawnTilesGrowth.DX, &spawnTilesGrowth.DY)
if err != nil {
return nil, fmt.Errorf("failed to parse spawn_tiles_growth: %w", err)
}
}
startTile := entRect.Origin.Div(TileSize)
endTile := entRect.OppositeCorner().Div(TileSize)
spawnRect := entRect.Grow(spawnTilesGrowth)
spawnStartTile := spawnRect.Origin.Div(TileSize)
spawnEndTile := spawnRect.OppositeCorner().Div(TileSize)
orientation := m.Identity()
if orientationProp := properties["orientation"]; orientationProp != "" {
orientation, err = m.ParseOrientation(orientationProp)
if err != nil {
return nil, fmt.Errorf("invalid orientation: %w", err)
}
}
if properties["type"] == "WarpZone" {
// WarpZones must be paired by name.
name := properties["name"]
invert := properties["invert"] == "true" // Default false.
switchable := properties["switchable"] == "true" // Default false.
warpZones[name] = append(warpZones[name], &RawWarpZone{
StartTile: startTile,
EndTile: endTile,
Orientation: orientation,
Switchable: switchable,
Invert: invert,
})
continue
}
ent := Spawnable{
ID: EntityID(o.ObjectID),
LevelPos: startTile,
RectInTile: m.Rect{
Origin: entRect.Origin.Sub(
startTile.Mul(TileSize).Delta(m.Pos{})),
Size: entRect.Size,
},
SpawnableProps: SpawnableProps{
EntityType: properties["type"],
Orientation: orientation,
Properties: properties,
PersistentState: PersistentState{},
SpawnTilesGrowth: spawnTilesGrowth,
},
}
if properties["type"] == "_TileMod" {
level.applyTileMod(startTile, endTile, properties)
// Do not link to tiles.
continue
}
if properties["type"] == "Player" {
level.Player = &ent
level.Checkpoints[""] = &ent
// Do not link to tiles.
continue
}
if properties["type"] == "Checkpoint" || properties["type"] == "CheckpointTarget" {
level.Checkpoints[properties["name"]] = &ent
checkpoints[ent.ID] = &ent
// These do get linked.
}
if properties["type"] == "TnihSign" {
tnihSigns = append(tnihSigns, &ent)
// These do get linked.
}
for y := spawnStartTile.Y; y <= spawnEndTile.Y; y++ {
for x := spawnStartTile.X; x <= spawnEndTile.X; x++ {
pos := m.Pos{X: x, Y: y}
levelTile := level.Tile(pos)
if levelTile == nil {
return nil, fmt.Errorf("invalid entity location: outside map bounds: %v in %v", pos, ent)
}
levelTile.Tile.Spawnables = append(levelTile.Tile.Spawnables, &ent)
}
}
}
}
for _, sign := range tnihSigns {
id, err := strconv.Atoi(sign.Properties["reached_from"])
if err != nil {
return nil, fmt.Errorf("invalid TnihSign: reached_from not set: %v: %w", sign, err)
}
cp := checkpoints[EntityID(id)]
if cp == nil {
return nil, fmt.Errorf("invalid TnihSign: checkpoint ID %v not found", id)
}
name := cp.Properties["name"]
level.TnihSignsByCheckpoint[name] = append(level.TnihSignsByCheckpoint[name], sign)
}
for name, cpSp := range level.Checkpoints {
if name == "" {
// This isn't a real CP.
continue
}
if *debugCheckTnihSigns {
got := len(level.TnihSignsByCheckpoint[name]) != 0
want := cpSp.Properties["tnih_sign_expected"] != "false" // default true
if !got && want {
log.Fatalf("note: checkpoint %v has no TnihSign - intended?", name)
}
if got && !want {
log.Fatalf("note: checkpoint %v unexpectedly has TnihSign - intended?", name)
}
}
}
warpnames := make([]string, 0, len(warpZones))
for warpname := range warpZones {
warpnames = append(warpnames, warpname)
}
for _, warpname := range warpnames {
warppair := warpZones[warpname]
if len(warppair) != 2 {
return nil, fmt.Errorf("unpaired WarpZone %q: got %d, want 2", warpname, len(warppair))
}
for a := 0; a < 2; a++ {
from := warppair[a]
to := warppair[1-a]
// Warp orientation: right = direction to walk the warp, down = orientation (for mirroring).
// Transform is identity transform iff the warps are reverse in right and identical in down.
// T = to * flipx * from^-1
// T' = from * flipx * to^-1
// T T' = id
transform := to.Orientation.Concat(m.FlipX()).Concat(from.Orientation.Inverse())
fromCenter2 := from.StartTile.Add(from.EndTile.Delta(m.Pos{}))
toCenter2 := to.StartTile.Add(to.EndTile.Delta(m.Pos{}))
for fromy := from.StartTile.Y; fromy <= from.EndTile.Y; fromy++ {
for fromx := from.StartTile.X; fromx <= from.EndTile.X; fromx++ {
fromPos := m.Pos{X: fromx, Y: fromy}
prevPos := fromPos.Add(from.Orientation.Apply(m.West()))
fromPos2 := fromPos.Add(fromPos.Delta(m.Pos{}))
toPos2 := toCenter2.Add(transform.Apply(fromPos2.Delta(fromCenter2)))
toPos := toPos2.Div(2).Add(to.Orientation.Apply(m.West()))
levelTile := level.Tile(fromPos)
if levelTile == nil {
return nil, fmt.Errorf("invalid WarpZone location: outside map bounds: %v in %v", fromPos, warppair)
}
toTile := level.Tile(toPos)
if toTile == nil {
return nil, fmt.Errorf("invalid WarpZone destination location: outside map bounds: %v in %v", toPos, warppair)
}
levelTile.WarpZones = append(levelTile.WarpZones, &WarpZone{
Name: warpname,
Invert: from.Invert,
Switchable: from.Switchable,
PrevTile: prevPos,
ToTile: toPos,
Transform: transform,
})
}
}
}
}
return &level, nil
}
type Loader struct {
filename string
skipCheckpointLocations bool
skipComparingCheckpointLocations bool
level *Level
tmxData *tmx.Map
}
func NewLoader(filename string) *Loader {
return &Loader{filename: filename}
}
func (l *Loader) SkipCheckpointLocations(s bool) *Loader {
l.skipCheckpointLocations = s
return l
}
func (l *Loader) SkipComparingCheckpointLocations(s bool) *Loader {
l.skipComparingCheckpointLocations = s
return l
}
func (l *Loader) Level() *Level {
return l.level
}
func (l *Loader) Load() (*Level, error) {
_, err := splash.RunImmediately("loading level", l.LoadStepwise)
return l.level, err
}
// LoadStepwise loads a level in steps.
func (l *Loader) LoadStepwise(s *splash.State) (splash.Status, error) {
status, err := s.Enter("loading level file", "could not load level file", splash.Single(func() error {
r, err := vfs.Load("maps", l.filename+".tmx")
if err != nil {
return fmt.Errorf("could not open map: %w", err)
}
defer r.Close()
t, err := tmx.Decode(r)
if err != nil {
return fmt.Errorf("invalid map: %w", err)
}
l.tmxData = t
return nil
}))
if status != splash.Continue {
return status, err
}
status, err = s.Enter("parsing level data", "could not parse level data", splash.Single(func() error {
level, err := parseTmx(l.tmxData)
if err != nil {
return err
}
l.level = level
return nil
}))
if status != splash.Continue {
return status, err
}
if !l.skipCheckpointLocations {
status, err = s.Enter("loading checkpoints", "could not load checkpoint locations", splash.Single(func() error {
var err error
l.level.CheckpointLocations, err = l.level.LoadCheckpointLocations(l.filename)
if err != nil {
return err
}
h, err := hashstructure.Hash(l.level.CheckpointLocations, hashstructure.FormatV2, nil)
if err != nil {
return err
}
if !l.skipComparingCheckpointLocations {
if h != l.level.CheckpointLocationsHash {
return fmt.Errorf("checkpoint location hash mismatch: got %v, want %v - may need to update level file?", h, l.level.CheckpointLocationsHash)
}
}
return nil
}))
if status != splash.Continue {
return status, err
}
}
status, err = s.Enter("hashing level", "could not hash level", splash.Single(func() error {
var err error
l.level.Hash, err = hashstructure.Hash(l.level, hashstructure.FormatV2, nil)
return err
}))
if status != splash.Continue {
return status, err
}
return splash.Continue, nil
}
// VerifyHash returns an error if the level hash changed.
func (l *Level) VerifyHash() error {
hash, err := hashstructure.Hash(l, hashstructure.FormatV2, nil)
if err != nil {
return fmt.Errorf("could not hash level: %w", err)
}
if hash != l.Hash {
log.Fatalf("could not verify")
return fmt.Errorf("level hash mismatch: got %v, want %v", hash, l.Hash)
}
return nil
}
// ParseImageSrcByOrientation parses the imgSrcByOrientation map.
func ParseImageSrcByOrientation(defaultSrc string, properties map[string]string) (map[m.Orientation]string, error) {
imgSrcByOrientation := map[m.Orientation]string{}
for propName, propValue := range properties {
if oStr := strings.TrimPrefix(propName, "img."); oStr != propName {
o, err := m.ParseOrientation(oStr)
if err != nil {
return nil, fmt.Errorf("could not parse orientation tile: %w", err)
}
if o == m.Identity() && propValue != defaultSrc {
return nil, fmt.Errorf("unrotated image isn't same as img: got %q, want %q", propValue, defaultSrc)
}
imgSrcByOrientation[o] = propValue
}
}
return imgSrcByOrientation, nil
}