-
Notifications
You must be signed in to change notification settings - Fork 139
/
world.go
1374 lines (1222 loc) · 39.6 KB
/
world.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
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 world
import (
"errors"
"github.com/df-mc/goleveldb/leveldb"
"math/rand"
"sync"
"time"
"github.com/df-mc/atomic"
"github.com/df-mc/dragonfly/server/block/cube"
"github.com/df-mc/dragonfly/server/event"
"github.com/df-mc/dragonfly/server/internal/sliceutil"
"github.com/df-mc/dragonfly/server/world/chunk"
"github.com/go-gl/mathgl/mgl64"
"github.com/google/uuid"
"golang.org/x/exp/maps"
"slices"
)
// World implements a Minecraft world. It manages all aspects of what players can see, such as blocks,
// entities and particles.
// World generally provides a synchronised state: All entities, blocks and players usually operate in this
// world, so World ensures that all its methods will always be safe for simultaneous calls.
// A nil *World is safe to use but not functional.
type World struct {
conf Config
ra cube.Range
// advance is a bool that specifies if this World should advance the current tick, time and weather saved in the
// Settings struct held by the World.
advance bool
o sync.Once
set *Settings
handler atomic.Value[Handler]
weather
ticker
lastPos ChunkPos
lastChunk *Column
closing chan struct{}
running sync.WaitGroup
chunkMu sync.Mutex
// chunks holds a cache of chunks currently loaded. These chunks are cleared from this map after some time
// of not being used.
chunks map[ChunkPos]*Column
entityMu sync.RWMutex
// entities holds a map of entities currently loaded and the last ChunkPos that the Entity was in.
// These are tracked so that a call to RemoveEntity can find the correct entity.
entities map[Entity]ChunkPos
r *rand.Rand
updateMu sync.Mutex
// scheduledUpdates is a map of tick time values indexed by the block position at which an update is
// scheduled. If the current tick exceeds the tick value passed, the block update will be performed
// and the entry will be removed from the map.
scheduledUpdates map[cube.Pos]int64
neighbourUpdates []neighbourUpdate
viewersMu sync.Mutex
viewers map[*Loader]Viewer
}
// New creates a new initialised world. The world may be used right away, but it will not be saved or loaded
// from files until it has been given a different provider than the default. (NopProvider)
// By default, the name of the world will be 'World'.
func New() *World {
var conf Config
return conf.New()
}
// Name returns the display name of the world. Generally, this name is displayed at the top of the player list
// in the pause screen in-game.
// If a provider is set, the name will be updated according to the name that it provides.
func (w *World) Name() string {
w.set.Lock()
defer w.set.Unlock()
return w.set.Name
}
// Dimension returns the Dimension assigned to the World in world.New. The sky colour and behaviour of a variety of
// world features differ based on the Dimension assigned to a World.
func (w *World) Dimension() Dimension {
if w == nil {
return nopDim{}
}
return w.conf.Dim
}
// Range returns the range in blocks of the World (min and max). It is equivalent to calling World.Dimension().Range().
func (w *World) Range() cube.Range {
if w == nil {
return cube.Range{}
}
return w.ra
}
// EntityRegistry returns the EntityRegistry that was passed to the World's
// Config upon construction.
func (w *World) EntityRegistry() EntityRegistry {
return w.conf.Entities
}
// Block reads a block from the position passed. If a chunk is not yet loaded at that position, the chunk is
// loaded, or generated if it could not be found in the world save, and the block returned. Chunks will be
// loaded synchronously.
func (w *World) Block(pos cube.Pos) Block {
if w == nil || pos.OutOfBounds(w.Range()) {
// Fast way out.
return air()
}
c := w.chunk(chunkPosFromBlockPos(pos))
defer c.Unlock()
rid := c.Block(uint8(pos[0]), int16(pos[1]), uint8(pos[2]), 0)
if nbtBlocks[rid] {
// The block was also a block entity, so we look it up in the block entity map.
if nbtB, ok := c.BlockEntities[pos]; ok {
return nbtB
}
}
b, _ := BlockByRuntimeID(rid)
return b
}
// Biome reads the biome at the position passed. If a chunk is not yet loaded at that position, the chunk is
// loaded, or generated if it could not be found in the world save, and the biome returned. Chunks will be
// loaded synchronously.
func (w *World) Biome(pos cube.Pos) Biome {
if w == nil || pos.OutOfBounds(w.Range()) {
// Fast way out.
return ocean()
}
c := w.chunk(chunkPosFromBlockPos(pos))
defer c.Unlock()
id := int(c.Biome(uint8(pos[0]), int16(pos[1]), uint8(pos[2])))
b, ok := BiomeByID(id)
if !ok {
w.conf.Log.Errorf("could not find biome by ID %v", id)
}
return b
}
// blockInChunk reads a block from the world at the position passed. The block is assumed to be in the chunk
// passed, which is also assumed to be locked already or otherwise not yet accessible.
func (w *World) blockInChunk(c *Column, pos cube.Pos) Block {
if pos.OutOfBounds(w.Range()) {
// Fast way out.
return air()
}
rid := c.Block(uint8(pos[0]), int16(pos[1]), uint8(pos[2]), 0)
if nbtBlocks[rid] {
// The block was also a block entity, so we look it up in the block entity map.
if b, ok := c.BlockEntities[pos]; ok {
return b
}
}
b, _ := BlockByRuntimeID(rid)
return b
}
// HighestLightBlocker gets the Y value of the highest fully light blocking block at the x and z values
// passed in the world.
func (w *World) HighestLightBlocker(x, z int) int {
if w == nil {
return w.Range()[0]
}
c := w.chunk(ChunkPos{int32(x >> 4), int32(z >> 4)})
defer c.Unlock()
return int(c.HighestLightBlocker(uint8(x), uint8(z)))
}
// HighestBlock looks up the highest non-air block in the world at a specific x and z in the world. The y
// value of the highest block is returned, or 0 if no blocks were present in the column.
func (w *World) HighestBlock(x, z int) int {
if w == nil {
return w.Range()[0]
}
c := w.chunk(ChunkPos{int32(x >> 4), int32(z >> 4)})
defer c.Unlock()
return int(c.HighestBlock(uint8(x), uint8(z)))
}
// highestObstructingBlock returns the highest block in the world at a given x and z that has at least a solid top or
// bottom face.
func (w *World) highestObstructingBlock(x, z int) int {
if w == nil {
return 0
}
yHigh := w.HighestBlock(x, z)
for y := yHigh; y >= w.Range()[0]; y-- {
pos := cube.Pos{x, y, z}
m := w.Block(pos).Model()
if m.FaceSolid(pos, cube.FaceUp, w) || m.FaceSolid(pos, cube.FaceDown, w) {
return y
}
}
return w.Range()[0]
}
// SetOpts holds several parameters that may be set to disable updates in the World of different kinds as a result of
// a call to SetBlock.
type SetOpts struct {
// DisableBlockUpdates makes SetBlock not update any neighbouring blocks as a result of the SetBlock call.
DisableBlockUpdates bool
// DisableLiquidDisplacement disables the displacement of liquid blocks to the second layer (or back to the first
// layer, if it already was on the second layer). Disabling this is not strongly recommended unless performance is
// very important or where it is known no liquid can be present anyway.
DisableLiquidDisplacement bool
}
// SetBlock writes a block to the position passed. If a chunk is not yet loaded at that position, the chunk is
// first loaded or generated if it could not be found in the world save.
// SetBlock panics if the block passed has not yet been registered using RegisterBlock().
// Nil may be passed as the block to set the block to air.
//
// A SetOpts struct may be passed to additionally modify behaviour of SetBlock, specifically to improve performance
// under specific circumstances. Nil should be passed where performance is not essential, to make sure the world is
// updated adequately.
//
// SetBlock should be avoided in situations where performance is critical when needing to set a lot of blocks
// to the world. BuildStructure may be used instead.
func (w *World) SetBlock(pos cube.Pos, b Block, opts *SetOpts) {
if w == nil || pos.OutOfBounds(w.Range()) {
// Fast way out.
return
}
if opts == nil {
opts = &SetOpts{}
}
x, y, z := uint8(pos[0]), int16(pos[1]), uint8(pos[2])
c := w.chunk(chunkPosFromBlockPos(pos))
rid := BlockRuntimeID(b)
var before uint32
if rid != airRID && !opts.DisableLiquidDisplacement {
before = c.Block(x, y, z, 0)
}
c.modified = true
c.SetBlock(x, y, z, 0, rid)
if nbtBlocks[rid] {
c.BlockEntities[pos] = b
} else {
delete(c.BlockEntities, pos)
}
viewers := slices.Clone(c.viewers)
if !opts.DisableLiquidDisplacement {
var secondLayer Block
if rid == airRID {
if li := c.Block(x, y, z, 1); li != airRID {
c.SetBlock(x, y, z, 0, li)
c.SetBlock(x, y, z, 1, airRID)
secondLayer = air()
b, _ = BlockByRuntimeID(li)
}
} else if liquidDisplacingBlocks[rid] && liquidBlocks[before] {
l, _ := BlockByRuntimeID(before)
if b.(LiquidDisplacer).CanDisplace(l.(Liquid)) {
c.SetBlock(x, y, z, 1, before)
secondLayer = l
}
}
c.Unlock()
if secondLayer != nil {
for _, viewer := range viewers {
viewer.ViewBlockUpdate(pos, secondLayer, 1)
}
}
} else {
c.Unlock()
}
for _, viewer := range viewers {
viewer.ViewBlockUpdate(pos, b, 0)
}
if !opts.DisableBlockUpdates {
w.doBlockUpdatesAround(pos)
}
}
// SetBiome sets the biome at the position passed. If a chunk is not yet loaded at that position, the chunk is
// first loaded or generated if it could not be found in the world save.
func (w *World) SetBiome(pos cube.Pos, b Biome) {
if w == nil || pos.OutOfBounds(w.Range()) {
// Fast way out.
return
}
c := w.chunk(chunkPosFromBlockPos(pos))
defer c.Unlock()
c.modified = true
c.SetBiome(uint8(pos[0]), int16(pos[1]), uint8(pos[2]), uint32(b.EncodeBiome()))
}
// BuildStructure builds a Structure passed at a specific position in the world. Unlike SetBlock, it takes a
// Structure implementation, which provides blocks to be placed at a specific location.
// BuildStructure is specifically tinkered to be able to process a large batch of chunks simultaneously and
// will do so within much less time than separate SetBlock calls would.
// The method operates on a per-chunk basis, setting all blocks within a single chunk part of the structure
// before moving on to the next chunk.
func (w *World) BuildStructure(pos cube.Pos, s Structure) {
if w == nil {
return
}
dim := s.Dimensions()
width, height, length := dim[0], dim[1], dim[2]
maxX, maxY, maxZ := pos[0]+width, pos[1]+height, pos[2]+length
for chunkX := pos[0] >> 4; chunkX <= maxX>>4; chunkX++ {
for chunkZ := pos[2] >> 4; chunkZ <= maxZ>>4; chunkZ++ {
// We approach this on a per-chunk basis, so that we can keep only one chunk in memory at a time
// while not needing to acquire a new chunk lock for every block. This also allows us not to send
// block updates, but instead send a single chunk update once.
chunkPos := ChunkPos{int32(chunkX), int32(chunkZ)}
c := w.chunk(chunkPos)
f := func(x, y, z int) Block {
actual := cube.Pos{pos[0] + x, pos[1] + y, pos[2] + z}
if actual[0]>>4 == chunkX && actual[2]>>4 == chunkZ {
return w.blockInChunk(c, actual)
}
return w.Block(actual)
}
baseX, baseZ := chunkX<<4, chunkZ<<4
subs := c.Sub()
for i, sub := range subs {
baseY := (i + (w.Range()[0] >> 4)) << 4
if baseY>>4 < pos[1]>>4 {
continue
} else if baseY >= maxY {
break
}
for localY := 0; localY < 16; localY++ {
yOffset := baseY + localY
if yOffset > w.Range()[1] || yOffset >= maxY {
// We've hit the height limit for blocks.
break
} else if yOffset < w.Range()[0] || yOffset < pos[1] {
// We've got a block below the minimum, but other blocks might still reach above
// it, so don't break but continue.
continue
}
for localX := 0; localX < 16; localX++ {
xOffset := baseX + localX
if xOffset < pos[0] || xOffset >= maxX {
continue
}
for localZ := 0; localZ < 16; localZ++ {
zOffset := baseZ + localZ
if zOffset < pos[2] || zOffset >= maxZ {
continue
}
b, liq := s.At(xOffset-pos[0], yOffset-pos[1], zOffset-pos[2], f)
if b != nil {
rid := BlockRuntimeID(b)
sub.SetBlock(uint8(xOffset), uint8(yOffset), uint8(zOffset), 0, rid)
nbtPos := cube.Pos{xOffset, yOffset, zOffset}
if nbtBlocks[rid] {
c.BlockEntities[nbtPos] = b
} else {
delete(c.BlockEntities, nbtPos)
}
}
if liq != nil {
sub.SetBlock(uint8(xOffset), uint8(yOffset), uint8(zOffset), 1, BlockRuntimeID(liq))
} else if len(sub.Layers()) > 1 {
sub.SetBlock(uint8(xOffset), uint8(yOffset), uint8(zOffset), 1, airRID)
}
}
}
}
}
c.SetBlock(0, 0, 0, 0, c.Block(0, 0, 0, 0)) // Make sure the heightmap is recalculated.
c.modified = true
// After setting all blocks of the structure within a single chunk, we show the new chunk to all
// viewers once, and unlock it.
for _, viewer := range c.viewers {
viewer.ViewChunk(chunkPos, c.Chunk, c.BlockEntities)
}
c.Unlock()
}
}
}
// Liquid attempts to return any liquid block at the position passed. This liquid may be in the foreground or
// in any other layer.
// If found, the liquid is returned. If not, the bool returned is false and the liquid is nil.
func (w *World) Liquid(pos cube.Pos) (Liquid, bool) {
if w == nil || pos.OutOfBounds(w.Range()) {
// Fast way out.
return nil, false
}
c := w.chunk(chunkPosFromBlockPos(pos))
defer c.Unlock()
x, y, z := uint8(pos[0]), int16(pos[1]), uint8(pos[2])
id := c.Block(x, y, z, 0)
b, ok := BlockByRuntimeID(id)
if !ok {
w.conf.Log.Errorf("failed getting liquid: cannot get block by runtime ID %v", id)
return nil, false
}
if liq, ok := b.(Liquid); ok {
return liq, true
}
id = c.Block(x, y, z, 1)
b, ok = BlockByRuntimeID(id)
if !ok {
w.conf.Log.Errorf("failed getting liquid: cannot get block by runtime ID %v", id)
return nil, false
}
liq, ok := b.(Liquid)
return liq, ok
}
// SetLiquid sets the liquid at a specific position in the world. Unlike SetBlock, SetLiquid will not
// overwrite any existing blocks. It will instead be in the same position as a block currently there, unless
// there already is a liquid at that position, in which case it will be overwritten.
// If nil is passed for the liquid, any liquid currently present will be removed.
func (w *World) SetLiquid(pos cube.Pos, b Liquid) {
if w == nil || pos.OutOfBounds(w.Range()) {
// Fast way out.
return
}
chunkPos := chunkPosFromBlockPos(pos)
c := w.chunk(chunkPos)
if b == nil {
w.removeLiquids(c, pos)
c.Unlock()
w.doBlockUpdatesAround(pos)
return
}
x, y, z := uint8(pos[0]), int16(pos[1]), uint8(pos[2])
if !replaceable(w, c, pos, b) {
if displacer, ok := w.blockInChunk(c, pos).(LiquidDisplacer); !ok || !displacer.CanDisplace(b) {
c.Unlock()
return
}
}
rid := BlockRuntimeID(b)
if w.removeLiquids(c, pos) {
c.SetBlock(x, y, z, 0, rid)
for _, v := range c.viewers {
v.ViewBlockUpdate(pos, b, 0)
}
} else {
c.SetBlock(x, y, z, 1, rid)
for _, v := range c.viewers {
v.ViewBlockUpdate(pos, b, 1)
}
}
c.modified = true
c.Unlock()
w.doBlockUpdatesAround(pos)
}
// removeLiquids removes any liquid blocks that may be present at a specific block position in the chunk
// passed.
// The bool returned specifies if no blocks were left on the foreground layer.
func (w *World) removeLiquids(c *Column, pos cube.Pos) bool {
x, y, z := uint8(pos[0]), int16(pos[1]), uint8(pos[2])
noneLeft := false
if noLeft, changed := w.removeLiquidOnLayer(c.Chunk, x, y, z, 0); noLeft {
if changed {
for _, v := range c.viewers {
v.ViewBlockUpdate(pos, air(), 0)
}
}
noneLeft = true
}
if _, changed := w.removeLiquidOnLayer(c.Chunk, x, y, z, 1); changed {
for _, v := range c.viewers {
v.ViewBlockUpdate(pos, air(), 1)
}
}
return noneLeft
}
// removeLiquidOnLayer removes a liquid block from a specific layer in the chunk passed, returning true if
// successful.
func (w *World) removeLiquidOnLayer(c *chunk.Chunk, x uint8, y int16, z, layer uint8) (bool, bool) {
id := c.Block(x, y, z, layer)
b, ok := BlockByRuntimeID(id)
if !ok {
w.conf.Log.Errorf("failed removing liquids: cannot get block by runtime ID %v", id)
return false, false
}
if _, ok := b.(Liquid); ok {
c.SetBlock(x, y, z, layer, airRID)
return true, true
}
return id == airRID, false
}
// additionalLiquid checks if the block at a position has additional liquid on another layer and returns the
// liquid if so.
func (w *World) additionalLiquid(pos cube.Pos) (Liquid, bool) {
if pos.OutOfBounds(w.Range()) {
// Fast way out.
return nil, false
}
c := w.chunk(chunkPosFromBlockPos(pos))
id := c.Block(uint8(pos[0]), int16(pos[1]), uint8(pos[2]), 1)
c.Unlock()
b, ok := BlockByRuntimeID(id)
if !ok {
w.conf.Log.Errorf("failed getting liquid: cannot get block by runtime ID %v", id)
return nil, false
}
liq, ok := b.(Liquid)
return liq, ok
}
// Light returns the light level at the position passed. This is the highest of the sky and block light.
// The light value returned is a value in the range 0-15, where 0 means there is no light present, whereas
// 15 means the block is fully lit.
func (w *World) Light(pos cube.Pos) uint8 {
if w == nil || pos[1] < w.Range()[0] {
// Fast way out.
return 0
}
if pos[1] > w.Range()[1] {
// Above the rest of the world, so full skylight.
return 15
}
c := w.chunk(chunkPosFromBlockPos(pos))
defer c.Unlock()
return c.Light(uint8(pos[0]), int16(pos[1]), uint8(pos[2]))
}
// SkyLight returns the skylight level at the position passed. This light level is not influenced by blocks
// that emit light, such as torches or glowstone. The light value, similarly to Light, is a value in the
// range 0-15, where 0 means no light is present.
func (w *World) SkyLight(pos cube.Pos) uint8 {
if w == nil || pos[1] < w.Range()[0] {
// Fast way out.
return 0
}
if pos[1] > w.Range()[1] {
// Above the rest of the world, so full skylight.
return 15
}
c := w.chunk(chunkPosFromBlockPos(pos))
defer c.Unlock()
return c.SkyLight(uint8(pos[0]), int16(pos[1]), uint8(pos[2]))
}
// Time returns the current time of the world. The time is incremented every 1/20th of a second, unless
// World.StopTime() is called.
func (w *World) Time() int {
if w == nil {
return 0
}
w.set.Lock()
defer w.set.Unlock()
return int(w.set.Time)
}
// SetTime sets the new time of the world. SetTime will always work, regardless of whether the time is stopped
// or not.
func (w *World) SetTime(new int) {
if w == nil {
return
}
w.set.Lock()
w.set.Time = int64(new)
w.set.Unlock()
viewers, _ := w.allViewers()
for _, viewer := range viewers {
viewer.ViewTime(new)
}
}
// StopTime stops the time in the world. When called, the time will no longer cycle and the world will remain
// at the time when StopTime is called. The time may be restarted by calling World.StartTime().
// StopTime will not do anything if the time is already stopped.
func (w *World) StopTime() {
w.enableTimeCycle(false)
}
// StartTime restarts the time in the world. When called, the time will start cycling again and the day/night
// cycle will continue. The time may be stopped again by calling World.StopTime().
// StartTime will not do anything if the time is already started.
func (w *World) StartTime() {
w.enableTimeCycle(true)
}
// enableTimeCycle enables or disables the time cycling of the World.
func (w *World) enableTimeCycle(v bool) {
if w == nil {
return
}
w.set.Lock()
defer w.set.Unlock()
w.set.TimeCycle = v
}
// Temperature returns the temperature in the World at a specific position. Higher altitudes and different biomes
// influence the temperature returned.
func (w *World) Temperature(pos cube.Pos) float64 {
const (
tempDrop = 1.0 / 600
seaLevel = 64
)
diff := pos[1] - seaLevel
if diff < 0 {
diff = 0
}
return w.Biome(pos).Temperature() - float64(diff)*tempDrop
}
// AddParticle spawns a particle at a given position in the world. Viewers that are viewing the chunk will be
// shown the particle.
func (w *World) AddParticle(pos mgl64.Vec3, p Particle) {
if w == nil {
return
}
p.Spawn(w, pos)
for _, viewer := range w.Viewers(pos) {
viewer.ViewParticle(pos, p)
}
}
// PlaySound plays a sound at a specific position in the world. Viewers of that position will be able to hear
// the sound if they're close enough.
func (w *World) PlaySound(pos mgl64.Vec3, s Sound) {
ctx := event.C()
if w.Handler().HandleSound(ctx, s, pos); ctx.Cancelled() {
return
}
for _, viewer := range w.Viewers(pos) {
viewer.ViewSound(pos, s)
}
}
var (
worldsMu sync.RWMutex
// entityWorlds holds a list of all entities added to a world. It may be used to look up the world that an
// entity is currently in.
entityWorlds = map[Entity]*World{}
)
// AddEntity adds an entity to the world at the position that the entity has. The entity will be visible to
// all viewers of the world that have the chunk of the entity loaded.
// If the chunk that the entity is in is not yet loaded, it will first be loaded.
// If the entity passed to AddEntity is currently in a world, it is first removed from that world.
func (w *World) AddEntity(e Entity) {
if w == nil {
return
}
// Remove the Entity from any previous World it might be in.
e.World().RemoveEntity(e)
add(e, w)
chunkPos := chunkPosFromVec3(e.Position())
w.entityMu.Lock()
w.entities[e] = chunkPos
w.entityMu.Unlock()
c := w.chunk(chunkPos)
c.Entities = append(c.Entities, e)
viewers := slices.Clone(c.viewers)
c.Unlock()
for _, v := range viewers {
// We show the entity to all viewers currently in the chunk that the entity is spawned in.
showEntity(e, v)
}
w.Handler().HandleEntitySpawn(e)
}
// add maps an Entity to a World in the entityWorlds map.
func add(e Entity, w *World) {
worldsMu.Lock()
entityWorlds[e] = w
worldsMu.Unlock()
}
// RemoveEntity removes an entity from the world that is currently present in it. Any viewers of the entity
// will no longer be able to see it.
// RemoveEntity operates assuming the position of the entity is the same as where it is currently in the
// world. If it can not find it there, it will loop through all entities and try to find it.
// RemoveEntity assumes the entity is currently loaded and in a loaded chunk. If not, the function will not do
// anything.
func (w *World) RemoveEntity(e Entity) {
if w == nil {
return
}
w.entityMu.Lock()
chunkPos, found := w.entities[e]
w.entityMu.Unlock()
if !found {
// The entity currently isn't in this world.
return
}
w.Handler().HandleEntityDespawn(e)
worldsMu.Lock()
delete(entityWorlds, e)
worldsMu.Unlock()
c, ok := w.chunkFromCache(chunkPos)
if !ok {
// The chunk wasn't loaded, so we can't remove any entity from the chunk.
return
}
c.Entities = sliceutil.DeleteVal(c.Entities, e)
viewers := slices.Clone(c.viewers)
c.Unlock()
w.entityMu.Lock()
delete(w.entities, e)
w.entityMu.Unlock()
for _, v := range viewers {
v.HideEntity(e)
}
}
// EntitiesWithin does a lookup through the entities in the chunks touched by the BBox passed, returning all
// those which are contained within the BBox when it comes to their position.
func (w *World) EntitiesWithin(box cube.BBox, ignored func(Entity) bool) []Entity {
if w == nil {
return nil
}
// Make an estimate of 16 entities on average.
m := make([]Entity, 0, 16)
minPos, maxPos := chunkPosFromVec3(box.Min()), chunkPosFromVec3(box.Max())
for x := minPos[0]; x <= maxPos[0]; x++ {
for z := minPos[1]; z <= maxPos[1]; z++ {
c, ok := w.chunkFromCache(ChunkPos{x, z})
if !ok {
// The chunk wasn't loaded, so there are no entities here.
continue
}
entities := slices.Clone(c.Entities)
c.Unlock()
for _, entity := range entities {
if ignored != nil && ignored(entity) {
continue
}
if box.Vec3Within(entity.Position()) {
// The entity position was within the BBox, so we add it to the slice to return.
m = append(m, entity)
}
}
}
}
return m
}
// Entities returns a list of all entities currently added to the World.
func (w *World) Entities() []Entity {
if w == nil {
return nil
}
w.entityMu.RLock()
defer w.entityMu.RUnlock()
m := make([]Entity, 0, len(w.entities))
for e := range w.entities {
m = append(m, e)
}
return m
}
// OfEntity attempts to return a world that an entity is currently in. If the entity was not currently added
// to a world, the world returned is nil and the bool returned is false.
func OfEntity(e Entity) (*World, bool) {
worldsMu.RLock()
w, ok := entityWorlds[e]
worldsMu.RUnlock()
return w, ok
}
// Spawn returns the spawn of the world. Every new player will by default spawn on this position in the world
// when joining.
func (w *World) Spawn() cube.Pos {
if w == nil {
return cube.Pos{}
}
w.set.Lock()
s := w.set.Spawn
w.set.Unlock()
if s[1] > w.Range()[1] {
s[1] = w.highestObstructingBlock(s[0], s[2]) + 1
}
return s
}
// SetSpawn sets the spawn of the world to a different position. The player will be spawned in the center of
// this position when newly joining.
func (w *World) SetSpawn(pos cube.Pos) {
if w == nil {
return
}
w.set.Lock()
w.set.Spawn = pos
w.set.Unlock()
viewers, _ := w.allViewers()
for _, viewer := range viewers {
viewer.ViewWorldSpawn(pos)
}
}
// PlayerSpawn returns the spawn position of a player with a UUID in this World.
func (w *World) PlayerSpawn(uuid uuid.UUID) cube.Pos {
if w == nil {
return cube.Pos{}
}
pos, exist, err := w.conf.Provider.LoadPlayerSpawnPosition(uuid)
if err != nil {
w.conf.Log.Errorf("failed to get player spawn: %v", err)
return w.Spawn()
}
if !exist {
return w.Spawn()
}
return pos
}
// SetPlayerSpawn sets the spawn position of a player with a UUID in this World. If the player has a spawn in the world,
// the player will be teleported to this location on respawn.
func (w *World) SetPlayerSpawn(uuid uuid.UUID, pos cube.Pos) {
if w == nil {
return
}
if err := w.conf.Provider.SavePlayerSpawnPosition(uuid, pos); err != nil {
w.conf.Log.Errorf("failed to set player spawn: %v", err)
}
}
// DefaultGameMode returns the default game mode of the world. When players join, they are given this game
// mode.
// The default game mode may be changed using SetDefaultGameMode().
func (w *World) DefaultGameMode() GameMode {
if w == nil {
return GameModeSurvival
}
w.set.Lock()
defer w.set.Unlock()
return w.set.DefaultGameMode
}
// SetTickRange sets the range in chunks around each Viewer that will have the chunks (their blocks and entities)
// ticked when the World is ticked.
func (w *World) SetTickRange(v int) {
if w == nil {
return
}
w.set.Lock()
defer w.set.Unlock()
w.set.TickRange = int32(v)
}
// tickRange returns the tick range around each Viewer.
func (w *World) tickRange() int {
w.set.Lock()
defer w.set.Unlock()
return int(w.set.TickRange)
}
// SetDefaultGameMode changes the default game mode of the world. When players join, they are then given that
// game mode.
func (w *World) SetDefaultGameMode(mode GameMode) {
if w == nil {
return
}
w.set.Lock()
defer w.set.Unlock()
w.set.DefaultGameMode = mode
}
// Difficulty returns the difficulty of the world. Properties of mobs in the world and the player's hunger
// will depend on this difficulty.
func (w *World) Difficulty() Difficulty {
if w == nil {
return DifficultyNormal
}
w.set.Lock()
defer w.set.Unlock()
return w.set.Difficulty
}
// SetDifficulty changes the difficulty of a world.
func (w *World) SetDifficulty(d Difficulty) {
if w == nil {
return
}
w.set.Lock()
defer w.set.Unlock()
w.set.Difficulty = d
}
// ScheduleBlockUpdate schedules a block update at the position passed after a specific delay. If the block at
// that position does not handle block updates, nothing will happen.
func (w *World) ScheduleBlockUpdate(pos cube.Pos, delay time.Duration) {
if w == nil || pos.OutOfBounds(w.Range()) {
return
}
w.updateMu.Lock()
defer w.updateMu.Unlock()
if _, exists := w.scheduledUpdates[pos]; exists {
return
}
w.set.Lock()
t := w.set.CurrentTick
w.set.Unlock()
w.scheduledUpdates[pos] = t + delay.Nanoseconds()/int64(time.Second/20)
}
// doBlockUpdatesAround schedules block updates directly around and on the position passed.
func (w *World) doBlockUpdatesAround(pos cube.Pos) {
if w == nil || pos.OutOfBounds(w.Range()) {
return
}
changed := pos
w.updateMu.Lock()
w.updateNeighbour(pos, changed)
pos.Neighbours(func(pos cube.Pos) {
w.updateNeighbour(pos, changed)
}, w.Range())
w.updateMu.Unlock()
}
// neighbourUpdate represents a position that needs to be updated because of a neighbour that changed.
type neighbourUpdate struct {
pos, neighbour cube.Pos
}
// updateNeighbour ticks the position passed as a result of the neighbour passed being updated.
func (w *World) updateNeighbour(pos, changedNeighbour cube.Pos) {
w.neighbourUpdates = append(w.neighbourUpdates, neighbourUpdate{pos: pos, neighbour: changedNeighbour})
}
// Handle changes the current Handler of the world. As a result, events called by the world will call
// handlers of the Handler passed.
// Handle sets the world's Handler to NopHandler if nil is passed.
func (w *World) Handle(h Handler) {
if w == nil {
return
}
if h == nil {
h = NopHandler{}
}
w.handler.Store(h)
}
// Viewers returns a list of all viewers viewing the position passed. A viewer will be assumed to be watching
// if the position is within one of the chunks that the viewer is watching.
func (w *World) Viewers(pos mgl64.Vec3) (viewers []Viewer) {
if w == nil {
return nil
}
c, ok := w.chunkFromCache(chunkPosFromVec3(pos))
if !ok {
return nil
}
defer c.Unlock()
return slices.Clone(c.viewers)
}
// PortalDestination returns the destination world for a portal of a specific Dimension. If no destination World could
// be found, the current World is returned.
func (w *World) PortalDestination(dim Dimension) *World {
if w.conf.PortalDestination == nil {
return w
}