aboutsummaryrefslogtreecommitdiff
path: root/internal/admin/api_map.go
blob: e0476b3a26f43dabc384aa608595db725b52f1be (plain)
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
package admin

import (
	"log"
	"net/http"
	"os"
	"path/filepath"
	"sort"
	"strconv"

	"thehouseoficarus/internal/world"
)

func (s *AdminServer) handleMap(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, `{"error":"method not allowed"}`, http.StatusMethodNotAllowed)
		return
	}

	zStr := r.URL.Query().Get("z")
	z, err := strconv.Atoi(zStr)
	if err != nil {
		z = 0
	}

	dir := r.URL.Query().Get("dir")
	seed := s.cfg.StartingRoom
	if dir != "" {
		if low, ok := findLowestLoadableRoom(s, dir); ok {
			seed = low
		}
	}

	g := world.BuildGrid(seed, func(id int) (*world.Room, bool) {
		room, err := s.world.LoadRoom(id)
		if err != nil {
			log.Printf("map: BuildGrid failed to load room %d: %v", id, err)
			return nil, false
		}
		return room, true
	}, nil, func(gc world.GridConflict) {
		if gc.Kind == "overlap" {
			log.Printf("map: grid overlap: room %d wants cell %v already held by %d (via %d->%s)",
				gc.Target, gc.Want, gc.Occupier, gc.From, gc.Dir)
		}
	})

	// Discover all rooms reachable from the seed (including ones dropped by grid overlaps).
	reachable := map[int]bool{seed: true}
	queue := []int{seed}
	for len(queue) > 0 {
		id := queue[0]
		queue = queue[1:]
		room, err := s.world.LoadRoom(id)
		if err != nil {
			continue
		}
		for _, exit := range room.Exits {
			if exit.Room > 0 && !reachable[exit.Room] {
				reachable[exit.Room] = true
				queue = append(queue, exit.Room)
			}
		}
	}

	// Place any reachable room missing from the grid at a nearby free cell.
	for id := range reachable {
		if _, ok := g.Coord[id]; ok {
			continue
		}
		room, err := s.world.LoadRoom(id)
		if err != nil {
			continue
		}
		// Try adjacent to a connected neighbour already on grid.
		for _, exit := range room.Exits {
			if exit.Room <= 0 {
				continue
			}
			nc, ok := g.Coord[exit.Room]
			if !ok {
				continue
			}
			for dx := -1; dx <= 1; dx++ {
				for dy := -1; dy <= 1; dy++ {
					if dx == 0 && dy == 0 {
						continue
					}
					want := [3]int{nc[0] + dx, nc[1] + dy, nc[2]}
					if _, used := g.RoomAt[want]; !used {
						g.Coord[id] = want
						g.RoomAt[want] = id
						goto placed
					}
				}
			}
		}
		// Fallback: scan a generous rectangle for a free cell.
		for sx := -10; sx <= 10; sx++ {
			for sy := -10; sy <= 10; sy++ {
				want := [3]int{sx, sy, z}
				if _, used := g.RoomAt[want]; !used {
					g.Coord[id] = want
					g.RoomAt[want] = id
					goto placed
				}
			}
		}
	placed:
	}

	type RoomEntry struct {
		ID    int    `json:"id"`
		X     int    `json:"x"`
		Y     int    `json:"y"`
		Name  string `json:"name"`
		Color string `json:"color"`
	}

	type LinkEntry struct {
		From          int    `json:"from"`
		To            int    `json:"to"`
		Dir           string `json:"dir"`
		Bidirectional bool   `json:"bidirectional"`
	}

	type UDLink struct {
		From int `json:"from"`
		To   int `json:"to"`
	}

	roomData := make(map[int]*world.Room)
	var rooms []RoomEntry

	minX, maxX := 0, 0
	minY, maxY := 0, 0
	first := true

	for rid, coord := range g.Coord {
		if coord[2] != z {
			continue
		}

		r, err := s.world.LoadRoom(rid)
		if err != nil {
			continue
		}
		roomData[rid] = r

		rooms = append(rooms, RoomEntry{
			ID:    rid,
			X:     coord[0],
			Y:     coord[1],
			Name:  r.Name,
			Color: r.Color,
		})

		if first {
			minX, maxX = coord[0], coord[0]
			minY, maxY = coord[1], coord[1]
			first = false
		} else {
			if coord[0] < minX {
				minX = coord[0]
			}
			if coord[0] > maxX {
				maxX = coord[0]
			}
			if coord[1] < minY {
				minY = coord[1]
			}
			if coord[1] > maxY {
				maxY = coord[1]
			}
		}
	}

	var links []LinkEntry
	var upLinks []UDLink
	var downLinks []UDLink

	seenLinks := make(map[string]bool)
	for rid, room := range roomData {
		c := g.Coord[rid]
		for dir, exit := range room.Exits {
			target := exit.Room
			if target <= 0 {
				continue
			}
			targetCoord, ok := g.Coord[target]
			if !ok {
				continue
			}

			if targetCoord[2] > c[2] {
				upLinks = append(upLinks, UDLink{From: rid, To: target})
				continue
			}
			if targetCoord[2] < c[2] {
				downLinks = append(downLinks, UDLink{From: rid, To: target})
				continue
			}

			if dir == world.Up || dir == world.Down {
				continue
			}

			if _, onZ := roomData[target]; !onZ {
				continue
			}

			bidirectional := false
			if targetRoom, ok := roomData[target]; ok {
				if oppExit, ok := targetRoom.Exits[world.OppositeExit[dir]]; ok && oppExit.Room == rid {
					bidirectional = true
				}
			}

			key := linkKey(rid, target)
			if bidirectional && seenLinks[key] {
				continue
			}
			seenLinks[key] = true

			links = append(links, LinkEntry{
				From:          rid,
				To:            target,
				Dir:           string(dir),
				Bidirectional: bidirectional,
			})
		}
	}

	writeJSON(w, map[string]any{
		"rooms":        rooms,
		"links":        links,
		"upLinks":      upLinks,
		"downLinks":    downLinks,
		"dir":          getRoomDir(s, seed),
		"seed":         seed,
		"disconnected": findDisconnectedRooms(s, dir, seed, g),
		"bounds": map[string]int{
			"minX": minX,
			"maxX": maxX,
			"minY": minY,
			"maxY": maxY,
		},
	})
}

func getRoomDir(s *AdminServer, roomID int) string {
	path, ok := s.world.GetRoomPath(roomID)
	if !ok {
		return ""
	}
	rel, err := filepath.Rel(filepath.Join(s.dataDir, "rooms"), filepath.Dir(path))
	if err != nil || rel == "." {
		return ""
	}
	return rel
}

func linkKey(a, b int) string {
	if a < b {
		return strconv.Itoa(a) + "-" + strconv.Itoa(b)
	}
	return strconv.Itoa(b) + "-" + strconv.Itoa(a)
}

func findLowestLoadableRoom(s *AdminServer, dir string) (int, bool) {
	base := filepath.Join(s.dataDir, "rooms", dir)
	entries, err := os.ReadDir(base)
	if err != nil {
		return 0, false
	}
	var ids []int
	for _, e := range entries {
		if e.IsDir() || filepath.Ext(e.Name()) != ".yaml" {
			continue
		}
		name := e.Name()
		id, err := strconv.Atoi(name[:len(name)-5])
		if err != nil || id <= 0 {
			continue
		}
		ids = append(ids, id)
	}
	sort.Ints(ids)
	for _, id := range ids {
		if _, err := s.world.LoadRoom(id); err == nil {
			return id, true
		}
		log.Printf("map: seed candidate room %d in dir %s is not loadable, skipping", id, dir)
	}
	return 0, false
}

func findDisconnectedRooms(s *AdminServer, dir string, seed int, g world.RoomGrid) []map[string]any {
	var result []map[string]any
	scanDir := dir
	if scanDir == "" {
		scanDir = getRoomDir(s, seed)
	}
	allIDs := listRoomIDsInDir(s, scanDir)
	for _, id := range allIDs {
		if _, inGrid := g.Coord[id]; inGrid {
			continue
		}
		room, err := s.world.LoadRoom(id)
		if err != nil {
			continue
		}
		result = append(result, map[string]any{
			"id":   id,
			"name": room.Name,
		})
	}
	return result
}

func listRoomIDsInDir(s *AdminServer, dir string) []int {
	base := filepath.Join(s.dataDir, "rooms")
	walkRoot := base
	if dir != "" {
		walkRoot = filepath.Join(base, dir)
	}
	var ids []int
	filepath.WalkDir(walkRoot, func(path string, d os.DirEntry, err error) error {
		if err != nil || d.IsDir() || filepath.Ext(d.Name()) != ".yaml" {
			return nil
		}
		name := d.Name()
		id, convErr := strconv.Atoi(name[:len(name)-5])
		if convErr == nil && id > 0 {
			ids = append(ids, id)
		}
		return nil
	})
	return ids
}

func (s *AdminServer) handleNextRoomID(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, `{"error":"method not allowed"}`, http.StatusMethodNotAllowed)
		return
	}
	fromStr := r.URL.Query().Get("from")
	fromID := 0
	if fromStr != "" {
		fromID, _ = strconv.Atoi(fromStr)
	}
	id, _, err := nextRoomIDInDir(s.dataDir, fromID)
	if err != nil {
		writeJSON(w, map[string]any{"error": err.Error()})
		return
	}
	writeJSON(w, map[string]any{"id": id})
}