-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
1491 lines (1329 loc) · 37.7 KB
/
server.go
File metadata and controls
1491 lines (1329 loc) · 37.7 KB
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
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"fmt"
"math"
"math/rand"
"net"
"sort"
"sync"
"time"
)
type Server struct {
World *World // The authoritative world
Clients map[string]*ClientConnection
ClientsMu sync.RWMutex
PacketCh chan PacketWrapper
Shutdown chan bool
Done chan bool
// Initial player state (Loaded from save)
InitialPosX, InitialPosY, InitialPosZ float64
HasSavedPos bool
LastSentPos map[string][3]float64
LastSentMeta map[string]int32
SavePath string
PendingChunks map[chunkKey][]string
Listener net.Listener
}
type lastPos struct {
x, y, z float64
}
type ClientConnection struct {
Name string
Conn net.Conn
Send chan Packet // Buffer for outgoing packets
KnownChunks map[chunkKey]bool
LastChunkX int
LastChunkZ int
}
type PacketWrapper struct {
Packet Packet
From string
}
func NewServer(savePath string) *Server {
world := NewFlatWorld()
// Authoritative Load (MUST BE BEFORE STARTING WORKERS)
hasPos, px, py, pz, _ := LoadWorld(savePath, world)
// Set save path for chunk loading in background workers
world.SavePath = savePath
// Now we can start the workers with the correct seed
fmt.Printf("Server: Authoritative Seed Loaded: %d\n", world.seed)
fmt.Printf("Server: Authoritative Seed Loaded: %d\n", world.seed)
world.StartBackend()
InitRecipes()
s := &Server{
World: world,
Clients: make(map[string]*ClientConnection),
PacketCh: make(chan PacketWrapper, 1024),
Shutdown: make(chan bool),
Done: make(chan bool),
InitialPosX: px,
InitialPosY: py,
InitialPosZ: pz,
HasSavedPos: hasPos,
LastSentPos: make(map[string][3]float64),
LastSentMeta: make(map[string]int32),
SavePath: savePath,
PendingChunks: make(map[chunkKey][]string),
}
if !hasPos && len(world.entities) == 0 {
// Spawn a starter pig
p := &PigEntity{
BaseEntity: BaseEntity{
UUID: "Piggy-01",
Type: EntityPig,
X: 8,
Y: float64(world.HeightAt(8, 20)) + 1,
Z: 20,
},
}
s.SpawnEntity(p)
}
return s
}
func (s *Server) Stop() {
if s.Shutdown != nil {
select {
case <-s.Shutdown:
// Already closed
default:
close(s.Shutdown)
}
}
}
func (s *Server) Start() {
fmt.Println("Server starting...")
ticker := time.NewTicker(50 * time.Millisecond) // 20 TPS
defer ticker.Stop()
for {
select {
case <-s.Shutdown:
s.Save()
close(s.Done)
return
case <-ticker.C:
s.Tick()
case wrap := <-s.PacketCh:
s.HandlePacket(wrap)
}
}
}
func (s *Server) Save() {
fmt.Println("Server: Saving world state...")
// 0. Close listener if active
if s.Listener != nil {
s.Listener.Close()
}
// 1. Save Chunks
if err := SaveWorldChunks(s.SavePath, s.World); err != nil {
fmt.Printf("Server Save Chunks Error: %v\n", err)
}
// 2. Save Entities
if err := SaveEntities(s.SavePath, s.World); err != nil {
fmt.Printf("Server Save Entities Error: %v\n", err)
}
// 3. Save Player (Authoritative)
// Find the player entity to save
s.World.entitiesMu.RLock()
var player *PlayerEntity
for _, e := range s.World.entities {
if p, ok := e.(*PlayerEntity); ok {
// For singleplayer/host, we pick the first player or specific one if we knew the name.
// Currently we save to 'player.bin' which implies single player.
player = p
break
}
}
s.World.entitiesMu.RUnlock()
if player != nil {
// Serialize Hotbar
hotbarBytes := make([]byte, 9)
for i := 0; i < 9; i++ {
hotbarBytes[i] = byte(player.Inventory.Slots[i].ID)
}
fmt.Printf("Saving Player: %s at %.2f, %.2f, %.2f (Seed: %d)\n", player.UUID, player.X, player.Y, player.Z, s.World.seed)
if err := SavePlayerState(s.SavePath, float32(player.X), float32(player.Y), float32(player.Z), player.SelectedSlot, hotbarBytes, s.World.seed); err != nil {
fmt.Printf("Server Save Player Error: %v\n", err)
}
} else {
// Fallback if no player entity found (e.g. just started server and quit)
if err := SavePlayerState(s.SavePath, float32(s.InitialPosX), float32(s.InitialPosY), float32(s.InitialPosZ), 0, make([]byte, 9), s.World.seed); err != nil {
fmt.Printf("Server Save Player Fallback Error: %v\n", err)
}
}
fmt.Println("Server: World saved successfully.")
}
func (s *Server) Tick() {
s.World.ProcessGenResults()
s.processPendingChunks()
s.UpdateEntities()
// Garbage Collect Chunks
// Radius 24 (generous buffer)
// Only if single player or simple check
// For robust MP: Check against ALL players.
// Accessing s.Clients requires Lock.
s.ClientsMu.RLock()
var playerPositions [][2]int
for _, c := range s.Clients {
playerPositions = append(playerPositions, [2]int{c.LastChunkX, c.LastChunkZ})
}
s.ClientsMu.RUnlock()
if len(playerPositions) > 0 {
// Define unload callback to notify clients (Optional, but good for sync)
onUnload := func(cx, cz int) {
s.Broadcast(&PacketUnloadChunk{CX: int32(cx), CZ: int32(cz)})
key := chunkKey{X: cx, Z: cz}
// Crucial: Tell server to forget that clients know this chunk.
// So next time they come close, we resend it.
s.ClientsMu.RLock()
for _, c := range s.Clients {
delete(c.KnownChunks, key)
}
s.ClientsMu.RUnlock()
}
// Custom Unload Logic for Multiplayer support
// We can't use World.UnloadChunks because it supports only one center.
// We implement a custom loop here.
unloadRadiusSq := 24 * 24
s.World.chunksMu.Lock() // We need Lock to delete
// Note: Iterating map with Lock is blocking, but necessary for delete.
// To optimize: RLock first to find candidates, then Lock to delete?
// Map iteration is safe with RLock? Yes.
toRemove := make([]chunkKey, 0)
for key := range s.World.chunks {
// Check if chunk is far from ALL players
keep := false
for _, pos := range playerPositions {
dx := key.X - pos[0]
dz := key.Z - pos[1]
if dx*dx+dz*dz <= unloadRadiusSq {
keep = true
break
}
}
if !keep {
// Also check if it's pending?
// s.PendingChunks contains keys waiting for dispatch.
// If we unload it, we might break pending logic.
// PendingChunks keys allow us to keep duplicates?
// Let's check s.PendingChunks (it's on Server struct, not World).
// We should not unload if pending.
// But PendingChunks map usage creates race if not locked?
// PendingChunks is accessed in Tick (single thread? No, Tick is sequential).
// Tick -> processPendingChunks. So safe from Tick.
// But SendChunksAround (from Packet) writes it using ClientsMu? No, SendChunksAround writes PendingChunks.
// SendChunksAround is called from HandlePacket (channel consumer in Start).
// Tick is called from Ticker in Start.
// They are SEQUENTIAL in the main select loop of Start!
// So PendingChunks access is safe WITHOUT lock.
isPending := false
if _, ok := s.PendingChunks[key]; ok {
isPending = true
}
if !isPending {
toRemove = append(toRemove, key)
}
}
}
// Delete chunks
for _, key := range toRemove {
chunk := s.World.chunks[key]
// SAVE BEFORE UNLOAD
if chunk.dirty {
if err := SaveChunk(s.SavePath, chunk, key.X, key.Z); err != nil {
fmt.Printf("Error saving chunk %d,%d during unload: %v\n", key.X, key.Z, err)
}
}
delete(s.World.chunks, key)
// Safe Free (using our new thread-safe freeChunk)
// We are holding chunksMu.Lock.
// freeChunk acquires chunk.mu.Lock.
// This is safe (Map -> Chunk order).
// BUT: freeChunk calls w.chunkPool.Put(c).
// IMPORTANT: We must unlock chunksMu before calling freeChunk?
// The original UnloadChunks (in world_core.go) calls freeChunk INSIDE chunksMu.Lock loop?
// Let's check step 309.
// UnloadChunks: w.chunksMu.Lock(); ... w.freeChunk(chunk); ... w.chunksMu.Unlock().
// Yes.
// freeChunk: c.mu.Lock(); ... c.mu.Unlock().
// So we hold Map Lock, take Chunk Lock.
// Correct order.
chunk.mu.Lock()
s.World.chunkPool.Put(chunk)
chunk.mu.Unlock()
if onUnload != nil {
onUnload(key.X, key.Z)
}
}
s.World.chunksMu.Unlock()
}
}
func (s *Server) SendInventory(player *PlayerEntity) {
// Sync entire inventory to client
// We MUST send empty slots (ID=0) too, otherwise client won't know items were consumed!
for i, item := range player.Inventory.Slots {
p := &PacketInventoryUpdate{
SlotID: int32(i),
ItemID: item.ID,
Count: item.Count,
}
s.BroadcastTo(player.UUID, p)
}
}
func (s *Server) UpdateEntities() {
s.World.TickEntities()
// Handle Item Pickup & Remove dead entities
s.World.entitiesMu.Lock()
var toRemove []string
// Collect Players for distance check
var players []*PlayerEntity
for _, e := range s.World.entities {
if p, ok := e.(*PlayerEntity); ok {
players = append(players, p)
}
}
for _, e := range s.World.entities {
// Item Pickup Logic
if item, ok := e.(*ItemEntity); ok && !item.Dead && item.PickupDelay <= 0 {
for _, player := range players {
// Distance Check (Radius 1.5)
dx := player.X - item.X
dy := player.Y - item.Y
dz := player.Z - item.Z
distSq := dx*dx + dy*dy + dz*dz
if distSq < 2.25 {
// Try add to inventory
rem := player.Inventory.Add(int32(item.ItemID), int32(item.Count))
if rem < int32(item.Count) {
// Some or all picked up
// Sync Inventory
s.SendInventory(player)
if rem == 0 {
item.Dead = true
} else {
item.Count = int(rem)
// Update count for others
meta := int32(item.ItemID) | (int32(item.Count) << 8)
s.Broadcast(&PacketEntityMeta{
EntityID: item.GetUUID(),
Metadata: meta,
})
}
}
}
}
}
if item, ok := e.(*ItemEntity); ok && item.Dead {
toRemove = append(toRemove, e.GetUUID())
}
}
for _, uuid := range toRemove {
for i, e := range s.World.entities {
if e.GetUUID() == uuid {
s.World.entities = append(s.World.entities[:i], s.World.entities[i+1:]...)
break
}
}
s.Broadcast(&PacketEntityDespawn{EntityID: uuid})
delete(s.LastSentPos, uuid)
delete(s.LastSentMeta, uuid)
}
s.World.entitiesMu.Unlock()
s.World.entitiesMu.RLock()
defer s.World.entitiesMu.RUnlock()
for _, e := range s.World.entities {
if e.IsDirty() {
x, y, z := e.GetPosition()
// Threshold check
last, ok := s.LastSentPos[e.GetUUID()]
dx := x - last[0]
dy := y - last[1]
dz := z - last[2]
distSq := dx*dx + dy*dy + dz*dz
if !ok || distSq > 0.0025 { // > 0.05 units
yaw, pitch := e.GetRotation()
move := &PacketEntityMove{
EntityID: e.GetUUID(),
X: x,
Y: y,
Z: z,
Yaw: yaw,
Pitch: pitch,
}
s.Broadcast(move)
s.LastSentPos[e.GetUUID()] = [3]float64{x, y, z}
}
// Update metadata for items (count changed)
if item, ok := e.(*ItemEntity); ok {
meta := int32(item.ItemID) | (int32(item.Count) << 8)
lastMeta, hasLast := s.LastSentMeta[e.GetUUID()]
if !hasLast || lastMeta != meta {
s.Broadcast(&PacketEntityMeta{
EntityID: e.GetUUID(),
Metadata: meta,
})
s.LastSentMeta[e.GetUUID()] = meta
}
}
e.ClearDirty()
}
}
}
func (s *Server) StartTCP(addr string) error {
ln, err := net.Listen("tcp", addr)
if err != nil {
return err
}
s.Listener = ln
fmt.Printf("Server listening on %s\n", addr)
go s.Start()
for {
conn, err := ln.Accept()
if err != nil {
// Check if this is a shutdown
select {
case <-s.Shutdown:
// Silent exit on shutdown
return nil
default:
fmt.Printf("Accept error: %v\n", err)
continue
}
}
go s.handleNewConnection(conn)
}
}
func (s *Server) handleNewConnection(conn net.Conn) {
fmt.Printf("New connection from %s\n", conn.RemoteAddr())
// We don't know the name yet, wait for login
pkt, err := ReadPacket(conn)
if err != nil {
conn.Close()
return
}
login, ok := pkt.(*PacketLogin)
if !ok {
conn.Close()
return
}
name := login.Username
s.ClientsMu.Lock()
if old, exists := s.Clients[name]; exists {
old.Conn.Close()
}
cc := &ClientConnection{
Name: name,
Conn: conn,
Send: make(chan Packet, 4096), // Increased buffer for chunk bursts
KnownChunks: make(map[chunkKey]bool),
}
s.Clients[name] = cc
s.ClientsMu.Unlock()
// Start Writer Loop
go func() {
for p := range cc.Send {
if err := WritePacket(cc.Conn, p); err != nil {
fmt.Printf("Write error to %s: %v\n", name, err)
break
}
}
cc.Conn.Close()
}()
// Feed login to dispatcher
s.PacketCh <- PacketWrapper{Packet: pkt, From: name}
// Reader Loop
for {
p, err := ReadPacket(conn)
if err != nil {
fmt.Printf("Client %s disconnected: %v\n", name, err)
break
}
s.PacketCh <- PacketWrapper{Packet: p, From: name}
}
s.ClientsMu.Lock()
delete(s.Clients, name)
s.ClientsMu.Unlock()
}
func (s *Server) Broadcast(p Packet) {
s.ClientsMu.RLock()
defer s.ClientsMu.RUnlock()
for _, c := range s.Clients {
// Non-blocking for global broadcast to prevent one laggy client from stalling server
select {
case c.Send <- p:
default:
// fmt.Println("Dropped broadcast packet to", c.Name)
}
}
}
func (s *Server) BroadcastTo(name string, p Packet) {
s.ClientsMu.RLock()
defer s.ClientsMu.RUnlock()
if c, ok := s.Clients[name]; ok {
// Blocking send for critical per-user data (Chunks)
// With 4096 buffer, this should rarely block unless client is dead
c.Send <- p
}
}
func (s *Server) SpawnEntity(e Entity) {
s.World.entitiesMu.Lock()
s.World.entities = append(s.World.entities, e)
s.World.entitiesMu.Unlock()
x, y, z := e.GetPosition()
yaw, pitch := e.GetRotation()
meta := int32(0)
if item, ok := e.(*ItemEntity); ok {
meta = int32(item.ItemID) | (int32(item.Count) << 8)
}
s.Broadcast(&PacketEntitySpawn{
EntityID: e.GetUUID(),
Type: e.GetType(),
X: x,
Y: y,
Z: z,
Yaw: yaw,
Pitch: pitch,
Metadata: meta,
})
}
func (s *Server) HandlePacket(wrap PacketWrapper) {
pkt := wrap.Packet
// client := s.Clients[wrap.From]
switch p := pkt.(type) {
case *PacketLogin:
fmt.Printf("Client %s logged in on protocol %d (Seed: %d)\n", p.Username, p.ProtocolVersion, s.World.seed)
// Update packet with server seed so client can sync if desired
p.Seed = s.World.seed
// Register Client if not exists
s.ClientsMu.Lock()
if _, ok := s.Clients[p.Username]; !ok {
conn := &ClientConnection{
Name: p.Username,
Send: make(chan Packet, 128),
KnownChunks: make(map[chunkKey]bool),
}
s.Clients[p.Username] = conn
}
s.ClientsMu.Unlock()
// 1. Send Initial Chunks (Radius 16)
s.SendChunksAround(p.Username, 0, 0, 16)
// 2. Send Spawn Point
var spawnX, spawnY, spawnZ float64
if s.HasSavedPos {
spawnX, spawnY, spawnZ = s.InitialPosX, s.InitialPosY, s.InitialPosZ
} else {
sx, sz, ok := findLandSpawn(s.World, 0, 0, 16)
if !ok {
sx, sz = 0, 0
}
spawnX, spawnY, spawnZ = float64(sx), float64(s.World.HeightAt(sx, sz))+2.0, float64(sz)
}
s.ClientsMu.RLock()
client, ok := s.Clients[p.Username]
s.ClientsMu.RUnlock()
if ok {
client.Send <- &PacketSpawnPoint{
X: spawnX,
Y: spawnY,
Z: spawnZ,
}
}
// 3. Send Existing Entities
s.World.entitiesMu.RLock()
for _, e := range s.World.entities {
if e.GetUUID() == p.Username {
continue
} // Skip self if represented as entity
ex, ey, ez := e.GetPosition()
eyaw, epitch := e.GetRotation()
meta := int32(0)
if item, ok := e.(*ItemEntity); ok {
meta = int32(item.ItemID) | (int32(item.Count) << 8)
}
s.ClientsMu.RLock()
client, ok := s.Clients[p.Username]
s.ClientsMu.RUnlock()
if ok {
client.Send <- &PacketEntitySpawn{
EntityID: e.GetUUID(),
Type: e.GetType(),
X: ex,
Y: ey,
Z: ez,
Yaw: eyaw,
Pitch: epitch,
Metadata: meta,
}
}
}
s.World.entitiesMu.RUnlock()
// 4. Register new player as entity and broadcast to others
// Check if entity already exists (rejoining)
var exists bool
s.World.entitiesMu.RLock()
for _, e := range s.World.entities {
if e.GetUUID() == p.Username {
exists = true
break
}
}
s.World.entitiesMu.RUnlock()
if !exists {
playerEnt := &PlayerEntity{
BaseEntity: BaseEntity{
UUID: p.Username, Type: EntityPlayer,
X: spawnX, Y: spawnY, Z: spawnZ,
},
}
s.SpawnEntity(playerEnt)
} else {
fmt.Printf("Player %s rejoining existing entity\n", p.Username)
}
case *PacketGameMode:
// Switch GameMode
s.World.entitiesMu.RLock()
var player *PlayerEntity
for _, e := range s.World.entities {
if pEnt, ok := e.(*PlayerEntity); ok && pEnt.UUID == wrap.From {
player = pEnt
break
}
}
s.World.entitiesMu.RUnlock()
if player != nil {
player.GameMode = p.Mode
fmt.Printf("Player %s switched to GameMode %d\n", wrap.From, p.Mode)
// Echo back to confirm (or broadcast if others need to know)
s.BroadcastTo(wrap.From, p)
}
case *PacketPlayerMove:
// Update player position in ServerWorld for saving
s.InitialPosX = p.X
s.InitialPosY = p.Y
s.InitialPosZ = p.Z
s.HasSavedPos = true
// Update Player Entity in world for broadcasting
s.World.entitiesMu.RLock()
for _, e := range s.World.entities {
if e.GetUUID() == wrap.From {
e.SetPosition(p.X, p.Y, p.Z)
e.SetRotation(p.Yaw, p.Pitch)
break
}
}
s.World.entitiesMu.RUnlock()
cx := int(math.Floor(p.X / 16.0))
cz := int(math.Floor(p.Z / 16.0))
s.ClientsMu.RLock()
client, ok := s.Clients[wrap.From]
s.ClientsMu.RUnlock()
if ok {
if cx != client.LastChunkX || cz != client.LastChunkZ {
client.LastChunkX = cx
client.LastChunkZ = cz
s.SendChunksAround(client.Name, cx, cz, 16)
}
}
case *PacketBlockInteract:
// Check for specific block interactions (e.g. Workbench)
blockID := s.World.BlockAt(int(p.X), int(p.Y), int(p.Z))
// If Workbench, send OpenWindow
if blockID == blockCraftingTable {
// Send OpenWindow packet
s.ClientsMu.RLock()
client, ok := s.Clients[wrap.From]
s.ClientsMu.RUnlock()
if ok {
// WindowID 1, Type 1 (Workbench) - Type 0 is Inventory/Hand
// Wait, let's use Type=1 for Workbench as per plan
client.Send <- &PacketOpenWindow{
WindowID: 1,
WindowType: 1, // 1 = Workbench
}
}
}
case *PacketCraft:
// Handle Crafting Request
s.World.entitiesMu.RLock()
var player *PlayerEntity
for _, e := range s.World.entities {
if e.GetUUID() == wrap.From {
player = e.(*PlayerEntity)
break
}
}
s.World.entitiesMu.RUnlock()
if player != nil {
// 1. Get Recipe
if p.RecipeID < 0 || int(p.RecipeID) >= len(RecipeRegistry) {
return
}
recipe := RecipeRegistry[p.RecipeID]
// 2. Check Ingredients
if player.Inventory.ConsumeItems(recipe.Ingredients) {
// 3. Add Result
rem := player.Inventory.Add(recipe.Result.ID, recipe.Result.Count)
if rem > 0 {
// Drop remaining if full
// Handle overflow (drop item entity)
drop := &ItemEntity{
BaseEntity: BaseEntity{
Type: EntityItem,
X: player.X,
Y: player.Y + 1.5,
Z: player.Z,
},
ItemID: byte(recipe.Result.ID),
Count: int(rem),
}
// Random velocity?
s.SpawnEntity(drop)
}
// 4. Sync Inventory
s.SendInventory(player)
}
}
case *PacketChat:
// Clean message
msg := p.Message
if len(msg) > 0 {
if msg[0] == '/' {
s.handleCommand(wrap.From, msg)
} else {
// Broadcast
formatted := fmt.Sprintf("<%s> %s", wrap.From, msg)
fmt.Println("Chat: " + formatted)
s.Broadcast(&PacketChat{Message: formatted})
}
}
case *PacketBlockChange:
// Attempt to place/break block
s.World.entitiesMu.RLock()
var player *PlayerEntity
for _, e := range s.World.entities {
if e.GetUUID() == wrap.From {
player = e.(*PlayerEntity)
break
}
}
s.World.entitiesMu.RUnlock()
if player == nil {
return
}
if p.BlockID != blockAir {
// Placement Logic
if player.GameMode == ModeSurvival {
// 1. Try to consume from selected slot FIRST
consumed := false
slotIdx := player.SelectedSlot
if slotIdx >= 0 && slotIdx < 36 {
slot := &player.Inventory.Slots[slotIdx]
if slot.ID == int32(p.BlockID) && slot.Count > 0 {
slot.Count--
if slot.Count == 0 {
slot.ID = 0
}
consumed = true
}
}
// 2. Fallback to general consume if not found in hand
if !consumed {
if !player.Inventory.Consume(int32(p.BlockID), 1) {
// Failed to consume (cheating? lag?), revert client block
fmt.Printf("Player %s tried to place Block %d without item.\n", wrap.From, p.BlockID)
s.BroadcastTo(wrap.From, &PacketBlockChange{X: p.X, Y: p.Y, Z: p.Z, BlockID: blockAir})
return
}
}
// Sync Inventory
s.SendInventory(player)
}
} else {
// Block Break Logic (Mining)
// Check drops BEFORE setting to Air
oldBlockID := s.World.BlockAt(int(p.X), int(p.Y), int(p.Z))
if oldBlockID != blockAir {
blockDef := GetBlock(oldBlockID)
// 1. Determine Held Tool
var toolDef *BlockDef
slotIdx := player.SelectedSlot
if slotIdx >= 0 && slotIdx < 36 {
itemID := player.Inventory.Slots[slotIdx].ID
if itemID != 0 {
toolDef = GetBlock(byte(itemID))
}
}
// 2. Check Compatibility
canHarvest := true
if blockDef.RequiredMaterial > MatNone {
// Requires specific tier
hasCorrectTool := false
hasCorrectTier := false
if toolDef != nil {
if toolDef.ToolType == blockDef.EffectiveTool {
hasCorrectTool = true
}
if toolDef.ToolMaterial >= blockDef.RequiredMaterial {
hasCorrectTier = true
}
}
if !hasCorrectTool || !hasCorrectTier {
canHarvest = false
}
} else if blockDef.EffectiveTool != ToolNone {
// "Soft" requirement?
// In MC, if effective tool is defined but material is None, usually means "Faster with tool, but drops by hand (Wood/Dirt)".
// But some blocks (Snow?) require shovel to drop?
// For now, if RequiredMaterial is None, we assume "Always Drop" unless explicitly restricted.
// Let's stick to "RequiredMaterial > MatNone" means "Strict"
}
// 3. Drop Item
if canHarvest && player.GameMode == ModeSurvival {
dropID := blockDef.DropItem
if dropID == 0 {
dropID = blockDef.ID // Drop self by default
}
count := blockDef.DropCount
if count <= 0 {
count = 1
}
if dropID != 0 {
// Spawn Item Entity
// Random velocity
rng := rand.New(rand.NewSource(time.Now().UnixNano()))
vx := (rng.Float64() - 0.5) * 0.1
vz := (rng.Float64() - 0.5) * 0.1
vy := 0.2 // Slight pop up
item := &ItemEntity{
BaseEntity: BaseEntity{
UUID: fmt.Sprintf("drop-%d-%d", time.Now().UnixNano(), rand.Int()),
Type: EntityItem,
X: float64(p.X) + 0.5,
Y: float64(p.Y) + 0.3,
Z: float64(p.Z) + 0.5,
},
ItemID: dropID,
Count: count,
Vx: vx,
Vy: vy,
Vz: vz,
PickupDelay: 0.5, // Reduced delay for mined items
Age: 0,
}
s.SpawnEntity(item)
}
}
}
}
// Apply block change to World
// Validation logic would go here
fmt.Printf("Server: Block set at %d %d %d\n", p.X, p.Y, p.Z)
s.World.SetBlockAt(int(p.X), int(p.Y), int(p.Z), p.BlockID)
// Broadcast to all clients (including sender for confirmation, or skip sender)
// For now, simple echo to prove it works
s.Broadcast(p)
case *PacketUnloadChunk:
s.ClientsMu.RLock()
client, ok := s.Clients[wrap.From]
s.ClientsMu.RUnlock()
if ok {
key := chunkKey{X: int(p.CX), Z: int(p.CZ)}
delete(client.KnownChunks, key)
}
case *PacketInventoryUpdate:
// Client synced inventory (Creative Pick or Sync)
s.World.entitiesMu.RLock()
var player *PlayerEntity
for _, e := range s.World.entities {
if e.GetUUID() == wrap.From {
player = e.(*PlayerEntity)
break
}
}
s.World.entitiesMu.RUnlock()
if player != nil {
// Handle Cursor Update (Slot -1)
if p.SlotID == -1 {
// Only allow arbitrary cursor setting in Creative Mode?
// For now let's allow it generally or check GameMode if strict.
// Since we use this for robust sync, let's allow it.
player.CursorItem = Item{ID: p.ItemID, Count: p.Count}
} else if p.SlotID >= 0 && p.SlotID < 36 {
player.Inventory.Slots[p.SlotID] = Item{ID: p.ItemID, Count: p.Count}
// fmt.Printf("Server: Updated slot %d for %s to %d:%d\n", p.SlotID, wrap.From, p.ItemID, p.Count)
}
}
case *PacketSlotChange:
s.World.entitiesMu.RLock()
var player *PlayerEntity
for _, e := range s.World.entities {
if e.GetUUID() == wrap.From {
player = e.(*PlayerEntity)
break
}
}
s.World.entitiesMu.RUnlock()
if player != nil {
if p.Slot >= 0 && p.Slot < 9 {
player.SelectedSlot = int(p.Slot)
}
}
case *PacketClickWindow:
s.World.entitiesMu.RLock()
var player *PlayerEntity
for _, e := range s.World.entities {
if e.GetUUID() == wrap.From {
player = e.(*PlayerEntity)
break
}
}
s.World.entitiesMu.RUnlock()
if player != nil {
if p.IsCreative {
// Creative Pick (Client authority for palette acts as "spawn item")
// We trust the client is picking a valid block from palette.
// Put it in Cursor? Or directly in Slot?
// Usually Creative Pick puts directly in Slot (handled by InventoryUpdate for legacy)
// But let's support "Pick to Cursor" -> "Place in Slot".
// For now, let's assume Creative Palette pickup sends specific slot update.