aboutsummaryrefslogtreecommitdiff
path: root/internal/world/world.go
blob: c8270b19b4993eccdb7b5bdd5a24c77c0db8a3cb (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
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
package world

import (
	"fmt"
	"math/rand"
	"os"
	"path/filepath"
	"sort"
	"strings"
	"sync"

	"gopkg.in/yaml.v3"
)

const DropDespawnTicks = 1000
const ReserveTicks = 100

type GroundItemInfo struct {
	ItemID       string
	Quantity     int
	ReservedFor  string
	ReserveTimer int
}

type groundEntry struct {
	itemID       string
	quantity     int
	isSpawn      bool
	respawnTimer int // >0 = counting down to respawn
	respawnQty   int
	respawnDelay int
	despawnTimer int // >0 = counting down to despawn (dropped items)
	reservedFor  string
	reserveTimer int // >0 = counting down reservation
}

type World struct {
	dataDir     string
	mu          sync.Mutex
	groundItems map[int][]*groundEntry
	seeded      map[int]bool
	objStates   map[string]*ObjState
	objMoves    []ObjMove
}

type ObjMove struct {
	DefID     string
	Name      string
	FromRoom  int
	ToRoom    int
}

type ObjState struct {
	Depleted      bool
	DepleteTimer  int
	DefID         string
	Name          string
	Index         int
	RoomID        int
	JustRespawned bool
	WanderRooms   []int
	WanderInterval int
	WanderCounter int
	SharedMax     int
	SharedTimer   int
}

func (w *World) ObjStateKey(roomID int, defID string, index int) string {
	return fmt.Sprintf("%d:%s:%d", roomID, defID, index)
}

func (w *World) objStateKey(roomID int, defID string, index int) string {
	return w.ObjStateKey(roomID, defID, index)
}

func (w *World) EnsureObjectStates(roomID int, defIDs []string) {
	w.mu.Lock()
	defer w.mu.Unlock()
	if w.objStates == nil {
		w.objStates = make(map[string]*ObjState)
	}
	counts := make(map[string]int)
	for _, defID := range defIDs {
		idx := counts[defID]
		counts[defID]++
		key := w.objStateKey(roomID, defID, idx)
		if _, exists := w.objStates[key]; !exists {
			w.objStates[key] = &ObjState{
				DefID:  defID,
				Name:   defID,
				Index:  idx,
				RoomID: roomID,
			}
		}
	}
}

func (w *World) GetObjState(roomID int, defID string, index int) *ObjState {
	w.mu.Lock()
	defer w.mu.Unlock()
	if w.objStates == nil {
		return nil
	}
	return w.objStates[w.objStateKey(roomID, defID, index)]
}

func (w *World) GetObjStateByKey(key string) *ObjState {
	w.mu.Lock()
	defer w.mu.Unlock()
	if w.objStates == nil {
		return nil
	}
	return w.objStates[key]
}

func (w *World) AllObjInstances(roomID int) []ObjState {
	w.mu.Lock()
	defer w.mu.Unlock()
	var out []ObjState
	for _, st := range w.objStates {
		if st.RoomID == roomID {
			out = append(out, *st)
		}
	}
	sort.Slice(out, func(i, j int) bool {
		if out[i].DefID != out[j].DefID {
			return out[i].DefID < out[j].DefID
		}
		return out[i].Index < out[j].Index
	})
	return out
}

func (w *World) FindObjInstances(roomID int, name string) []ObjState {
	w.mu.Lock()
	defer w.mu.Unlock()
	var out []ObjState
	lower := strings.ToLower(name)
	for key, st := range w.objStates {
		if st.RoomID != roomID {
			continue
		}
		if !wordMatchesObj(lower, st.DefID, st.Name) {
			continue
		}
		out = append(out, ObjState{
			DefID:        st.DefID,
			Name:         st.Name,
			Index:        st.Index,
			RoomID:       st.RoomID,
			Depleted:     st.Depleted,
			DepleteTimer: st.DepleteTimer,
			SharedMax:    st.SharedMax,
			SharedTimer:  st.SharedTimer,
		})
		_ = key
	}
	sort.Slice(out, func(i, j int) bool {
		if out[i].DefID != out[j].DefID {
			return out[i].DefID < out[j].DefID
		}
		return out[i].Index < out[j].Index
	})
	return out
}

func wordMatchesObj(lower, defID, objName string) bool {
	if WordPrefixMatch(lower, objName) {
		return true
	}
	nameWords := strings.Fields(strings.ToLower(objName))
	inputWords := strings.Fields(strings.ToLower(lower))

	// Check defID as whole (bidirectional)
	if strings.HasPrefix(strings.ToLower(defID), lower) || strings.HasPrefix(lower, strings.ToLower(defID)) {
		return true
	}
	// Check each defID part (split by underscore) against each input word (bidirectional)
	for _, part := range strings.Split(defID, "_") {
		for _, iw := range inputWords {
			pl := strings.ToLower(part)
			if strings.HasPrefix(pl, iw) || strings.HasPrefix(iw, pl) {
				return true
			}
		}
	}
	_ = nameWords
	return false
}

func (w *World) SetObjName(roomID int, defID string, name string) {
	w.mu.Lock()
	defer w.mu.Unlock()
	for key, st := range w.objStates {
		if st.RoomID == roomID && st.DefID == defID {
			st.Name = name
		}
		_ = key
	}
}

func (w *World) SetObjWander(roomID int, defID string, rooms []int, interval int) {
	w.mu.Lock()
	defer w.mu.Unlock()
	for key, st := range w.objStates {
		if st.RoomID == roomID && st.DefID == defID {
			st.WanderRooms = rooms
			st.WanderInterval = interval
		}
		_ = key
	}
}

func (w *World) SetObjSharedDeplete(roomID int, defID string, max int) {
	w.mu.Lock()
	defer w.mu.Unlock()
	for key, st := range w.objStates {
		if st.RoomID == roomID && st.DefID == defID && st.SharedMax == 0 {
			st.SharedMax = max
			st.SharedTimer = max
		}
		_ = key
	}
}

func (w *World) AllSharedObjStates() []*ObjState {
	w.mu.Lock()
	defer w.mu.Unlock()
	var out []*ObjState
	for _, st := range w.objStates {
		if st.SharedMax > 0 {
			out = append(out, st)
		}
	}
	return out
}

func (w *World) SetObjDepleted(roomID int, defID string, index int, delay int) {
	w.mu.Lock()
	defer w.mu.Unlock()
	key := w.objStateKey(roomID, defID, index)
	if st, ok := w.objStates[key]; ok {
		st.Depleted = true
		st.DepleteTimer = delay
	}
}

func New(dataDir string) *World {
	return &World{
		dataDir:     dataDir,
		groundItems: make(map[int][]*groundEntry),
		seeded:      make(map[int]bool),
		objStates:   make(map[string]*ObjState),
	}
}

func (w *World) LoadRoom(id int) (*Room, error) {
	path := filepath.Join(w.dataDir, "rooms", fmt.Sprintf("%d.yaml", id))
	data, err := os.ReadFile(path)
	if err != nil {
		return nil, fmt.Errorf("read room %d: %w", id, err)
	}
	var room Room
	if err := yaml.Unmarshal(data, &room); err != nil {
		return nil, fmt.Errorf("parse room %d: %w", id, err)
	}
	room.ID = id
	if room.Exits == nil {
		room.Exits = make(map[ExitDir]ExitDef)
	}
	if room.Spawns == nil {
		room.Spawns = make([]SpawnDef, 0)
	}
	if room.Mobs == nil {
		room.Mobs = make([]RoomMob, 0)
	}
	return &room, nil
}

func (w *World) ResolveExit(input string) ExitDir {
	if dir, ok := ExitAliases[strings.ToLower(input)]; ok {
		return dir
	}
	canon := ExitDir(strings.ToLower(input))
	switch canon {
	case North, South, East, West, Up, Down:
		return canon
	}
	return ""
}

func (w *World) GroundItemsDetailed(roomID int) []GroundItemInfo {
	w.mu.Lock()
	defer w.mu.Unlock()
	var out []GroundItemInfo
	for _, e := range w.groundItems[roomID] {
		if e.quantity <= 0 {
			continue
		}
		info := GroundItemInfo{
			ItemID:   e.itemID,
			Quantity: e.quantity,
		}
		if e.reserveTimer > 0 && e.reservedFor != "" {
			info.ReservedFor = e.reservedFor
			info.ReserveTimer = e.reserveTimer
		}
		out = append(out, info)
	}
	return out
}

func (w *World) GroundItems(roomID int) map[string]int {
	w.mu.Lock()
	defer w.mu.Unlock()
	out := make(map[string]int)
	for _, e := range w.groundItems[roomID] {
		if e.quantity > 0 {
			out[e.itemID] += e.quantity
		}
	}
	return out
}

func (w *World) AddReservedGroundItem(roomID int, itemID string, qty int, owner string) {
	w.mu.Lock()
	defer w.mu.Unlock()
	e := &groundEntry{
		itemID:       itemID,
		quantity:     qty,
		despawnTimer: DropDespawnTicks,
		reservedFor:  owner,
		reserveTimer: ReserveTicks,
	}
	w.groundItems[roomID] = append(w.groundItems[roomID], e)
}

func (w *World) AddGroundItem(roomID int, itemID string, qty int) {
	w.mu.Lock()
	defer w.mu.Unlock()
	for _, e := range w.groundItems[roomID] {
		if e.quantity > 0 && strings.EqualFold(e.itemID, itemID) &&
			(e.reserveTimer <= 0 || e.reservedFor == "") {
			e.quantity += qty
			e.despawnTimer = DropDespawnTicks
			return
		}
	}
	e := &groundEntry{
		itemID:       itemID,
		quantity:     qty,
		despawnTimer: DropDespawnTicks,
	}
	w.groundItems[roomID] = append(w.groundItems[roomID], e)
}

func (w *World) RemoveReservedGroundItem(roomID int, itemID string, qty int, owner string) (int, bool) {
	w.mu.Lock()
	defer w.mu.Unlock()
	removed := 0
	remaining := qty
	for _, e := range w.groundItems[roomID] {
		if remaining <= 0 {
			break
		}
		if !strings.EqualFold(e.itemID, itemID) {
			continue
		}
		if e.quantity <= 0 {
			continue
		}
		if e.reserveTimer > 0 && e.reservedFor != "" && e.reservedFor != owner {
			return removed, false
		}
		take := e.quantity
		if take > remaining {
			take = remaining
		}
		e.quantity -= take
		removed += take
		remaining -= take
		if e.isSpawn && e.quantity <= 0 && e.respawnDelay > 0 {
			e.respawnTimer = e.respawnDelay
		}
	}
	return removed, true
}

func (w *World) RemoveGroundItem(roomID int, itemID string, qty int) int {
	w.mu.Lock()
	defer w.mu.Unlock()

	removed := 0
	remaining := qty

	for _, e := range w.groundItems[roomID] {
		if remaining <= 0 {
			break
		}
		if !strings.EqualFold(e.itemID, itemID) {
			continue
		}
		if e.quantity <= 0 {
			continue
		}
		take := e.quantity
		if take > remaining {
			take = remaining
		}
		e.quantity -= take
		removed += take
		remaining -= take

		if e.isSpawn && e.quantity <= 0 && e.respawnDelay > 0 {
			e.respawnTimer = e.respawnDelay
		}
	}
	return removed
}

func (w *World) SeedGroundItems(roomID int) {
	w.mu.Lock()
	if w.seeded[roomID] {
		w.mu.Unlock()
		return
	}
	w.seeded[roomID] = true
	w.mu.Unlock()

	room, err := w.LoadRoom(roomID)
	if err != nil {
		return
	}

	w.mu.Lock()
	defer w.mu.Unlock()

	for _, s := range room.Spawns {
		merged := false
		for _, e := range w.groundItems[roomID] {
			if e.quantity > 0 && strings.EqualFold(e.itemID, s.ItemID) &&
				(e.reserveTimer <= 0 || e.reservedFor == "") {
				e.quantity += s.Quantity
				e.respawnQty += s.Quantity
				e.isSpawn = true
				e.respawnDelay = s.RespawnTicks
				merged = true
				break
			}
		}
		if !merged {
			e := &groundEntry{
				itemID:       s.ItemID,
				quantity:     s.Quantity,
				isSpawn:      true,
				respawnDelay: s.RespawnTicks,
				respawnQty:   s.Quantity,
			}
			w.groundItems[roomID] = append(w.groundItems[roomID], e)
		}
	}
}

func (w *World) Tick() {
	w.mu.Lock()
	defer w.mu.Unlock()

	for _, entries := range w.groundItems {
		for _, e := range entries {
		if e.respawnTimer > 0 {
			e.respawnTimer--
			if e.respawnTimer <= 0 {
				e.quantity = e.respawnQty
				for _, other := range entries {
					if other != e && other.quantity > 0 && strings.EqualFold(other.itemID, e.itemID) &&
						(other.reserveTimer <= 0 || other.reservedFor == "") {
						e.quantity += other.quantity
						other.quantity = 0
					}
				}
			}
		}
			if e.despawnTimer > 0 {
				e.despawnTimer--
				if e.despawnTimer <= 0 {
					e.quantity = 0
				}
			}
			if e.reserveTimer > 0 {
				e.reserveTimer--
				if e.reserveTimer <= 0 {
					e.reservedFor = ""
				}
			}
		}
	}

	for _, st := range w.objStates {
		if st.Depleted && st.DepleteTimer > 0 {
			st.DepleteTimer--
			if st.DepleteTimer <= 0 {
				st.Depleted = false
				st.JustRespawned = true
				if st.SharedMax > 0 {
					st.SharedTimer = st.SharedMax
				}
			}
		}
	}
}

func (w *World) FlushObjRespawns() []ObjState {
	w.mu.Lock()
	defer w.mu.Unlock()
	var out []ObjState
	for _, st := range w.objStates {
		if st.JustRespawned {
			out = append(out, *st)
			st.JustRespawned = false
		}
	}
	return out
}

func (w *World) TickObjWander() {
	w.mu.Lock()
	defer w.mu.Unlock()
	var moves []struct {
		st     *ObjState
		toRoom int
	}
	for _, st := range w.objStates {
		if len(st.WanderRooms) == 0 || st.WanderInterval <= 0 {
			continue
		}
		st.WanderCounter++
		if st.WanderCounter >= st.WanderInterval {
			st.WanderCounter = 0
			toRoom := st.WanderRooms[rand.Intn(len(st.WanderRooms))]
			if toRoom == st.RoomID {
				continue
			}
			moves = append(moves, struct {
				st     *ObjState
				toRoom int
			}{st, toRoom})
		}
	}
	for _, m := range moves {
		oldKey := w.objStateKey(m.st.RoomID, m.st.DefID, m.st.Index)
		fromRoom := m.st.RoomID
		m.st.RoomID = m.toRoom
		newKey := w.objStateKey(m.st.RoomID, m.st.DefID, m.st.Index)
		delete(w.objStates, oldKey)
		w.objStates[newKey] = m.st
		w.objMoves = append(w.objMoves, ObjMove{
			DefID:    m.st.DefID,
			Name:     m.st.Name,
			FromRoom: fromRoom,
			ToRoom:   m.toRoom,
		})
	}
}

func (w *World) FlushObjMoves() []ObjMove {
	w.mu.Lock()
	defer w.mu.Unlock()
	out := w.objMoves
	w.objMoves = nil
	return out
}