-
Notifications
You must be signed in to change notification settings - Fork 140
/
liquid.go
342 lines (315 loc) · 10.6 KB
/
liquid.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
package block
import (
"github.com/df-mc/dragonfly/server/block/cube"
"github.com/df-mc/dragonfly/server/entity"
"github.com/df-mc/dragonfly/server/event"
"github.com/df-mc/dragonfly/server/item/tool"
"github.com/df-mc/dragonfly/server/world"
"github.com/go-gl/mathgl/mgl64"
"math"
"math/rand"
"sync"
)
// LiquidRemovable represents a block that may be removed by a liquid flowing into it. When this happens, the
// block's drops are dropped at the position if HasLiquidDrops returns true.
type LiquidRemovable interface {
HasLiquidDrops() bool
}
// tickLiquid ticks the liquid block passed at a specific position in the world. Depending on the surroundings
// and the liquid block, the liquid will either spread or decrease in depth. Additionally, the liquid might
// be turned into a solid block if a different liquid is next to it.
func tickLiquid(b world.Liquid, pos cube.Pos, w *world.World) {
if !source(b) && !sourceAround(b, pos, w) {
if b.LiquidDepth()-4 <= 0 {
w.SetLiquid(pos, nil)
return
}
w.SetLiquid(pos, b.WithDepth(b.LiquidDepth()-2*b.SpreadDecay(), false))
return
}
displacer, _ := w.Block(pos).(world.LiquidDisplacer)
canFlowBelow := canFlowInto(b, w, pos.Add(cube.Pos{0, -1}), false)
if b.LiquidFalling() && !canFlowBelow {
b = b.WithDepth(8, true)
} else if canFlowBelow {
below := pos.Add(cube.Pos{0, -1})
if displacer == nil || !displacer.SideClosed(pos, below, w) {
flowInto(b.WithDepth(8, true), pos, below, w, true)
}
}
depth, decay := b.LiquidDepth(), b.SpreadDecay()
if depth <= decay {
// Current depth is smaller than the decay, so spreading will result in nothing.
return
}
if source(b) || !canFlowBelow {
paths := calculateLiquidPaths(b, pos, w, displacer)
if len(paths) == 0 {
spreadOutwards(b, pos, w, displacer)
return
}
smallestLen := len(paths[0])
for _, path := range paths {
if len(path) <= smallestLen {
flowInto(b, pos, path[0], w, false)
}
}
}
}
// source checks if a liquid is a source block.
func source(b world.Liquid) bool {
return b.LiquidDepth() == 8 && !b.LiquidFalling()
}
// spreadOutwards spreads the liquid outwards into the horizontal directions.
func spreadOutwards(b world.Liquid, pos cube.Pos, w *world.World, displacer world.LiquidDisplacer) {
pos.Neighbours(func(neighbour cube.Pos) {
if neighbour[1] == pos[1] {
if displacer == nil || !displacer.SideClosed(pos, neighbour, w) {
flowInto(b, pos, neighbour, w, false)
}
}
})
}
// sourceAround checks if there is a source in the blocks around the position passed.
func sourceAround(b world.Liquid, pos cube.Pos, w *world.World) (sourcePresent bool) {
pos.Neighbours(func(neighbour cube.Pos) {
if neighbour[1] == pos[1]-1 {
// We don't care about water below this one.
return
}
side, ok := w.Liquid(neighbour)
if !ok || side.LiquidType() != b.LiquidType() {
return
}
if displacer, ok := w.Block(neighbour).(world.LiquidDisplacer); ok && displacer.SideClosed(neighbour, pos, w) {
// The side towards this liquid was closed, so this cannot function as a source for this
// liquid.
return
}
if neighbour[1] == pos[1]+1 || source(side) || side.LiquidDepth() > b.LiquidDepth() {
sourcePresent = true
}
})
return
}
// flowInto makes the liquid passed flow into the position passed in a world. If successful, the block at that
// position will be broken and the liquid with a lower depth will replace it.
func flowInto(b world.Liquid, src, pos cube.Pos, w *world.World, falling bool) bool {
newDepth := b.LiquidDepth() - b.SpreadDecay()
if falling {
newDepth = b.LiquidDepth()
}
if newDepth <= 0 && !falling {
return false
}
existing := w.Block(pos)
if existingLiquid, alsoLiquid := existing.(world.Liquid); alsoLiquid && existingLiquid.LiquidType() == b.LiquidType() {
if existingLiquid.LiquidDepth() >= newDepth || existingLiquid.LiquidFalling() {
// The existing liquid had a higher depth than the one we're propagating or it was falling
// (basically considered full depth), so no need to continue.
return true
}
ctx := event.C()
w.Handler().HandleLiquidFlow(ctx, src, pos, b.WithDepth(newDepth, falling), existing)
ctx.Continue(func() {
w.SetLiquid(pos, b.WithDepth(newDepth, falling))
})
return true
} else if alsoLiquid {
existingLiquid.Harden(pos, w, &src)
return false
}
if _, ok := existing.(world.LiquidDisplacer); ok {
if _, ok := w.Liquid(pos); ok {
// We've got a liquid displacer and it's got a liquid within it, so we can't flow into this.
return false
}
}
removable, ok := existing.(LiquidRemovable)
if !ok {
// Can't flow into this block.
return false
}
if _, air := existing.(Air); !air {
w.BreakBlockWithoutParticles(pos)
}
if removable.HasLiquidDrops() {
if b, ok := existing.(Breakable); ok {
for _, d := range b.BreakInfo().Drops(tool.None{}) {
itemEntity := entity.NewItem(d, pos.Vec3Centre())
itemEntity.SetVelocity(mgl64.Vec3{rand.Float64()*0.2 - 0.1, 0.2, rand.Float64()*0.2 - 0.1})
w.AddEntity(itemEntity)
}
} else {
panic("liquid drops should always implement breakable")
}
}
ctx := event.C()
w.Handler().HandleLiquidFlow(ctx, src, pos, b.WithDepth(newDepth, falling), existing)
ctx.Continue(func() {
w.SetLiquid(pos, b.WithDepth(newDepth, falling))
})
return true
}
// liquidPath represents a path to an empty lower block or a block that can be flown into by a liquid, which
// the liquid tends to flow into. All paths with the lowest length will be filled with water.
type liquidPath []cube.Pos
// calculateLiquidPaths calculates paths in the world that the liquid passed can flow in to reach lower
// grounds, starting at the position passed.
// If none of these paths can be found, the returned slice has a length of 0.
func calculateLiquidPaths(b world.Liquid, pos cube.Pos, w *world.World, displacer world.LiquidDisplacer) []liquidPath {
queue := liquidQueuePool.Get().(*liquidQueue)
defer func() {
queue.Reset()
liquidQueuePool.Put(queue)
}()
queue.PushBack(liquidNode{x: pos[0], z: pos[2], depth: int8(b.LiquidDepth())})
decay := int8(b.SpreadDecay())
paths := make([]liquidPath, 0, 3)
first := true
for {
if queue.Len() == 0 {
break
}
node := queue.Front()
neighA, neighB, neighC, neighD := node.neighbours(decay * 2)
if !first || (displacer == nil || !displacer.SideClosed(pos, cube.Pos{neighA.x, pos[1], neighA.z}, w)) {
if spreadNeighbour(b, pos, w, neighA, queue) {
queue.shortestPath = neighA.Len()
paths = append(paths, neighA.Path(pos))
}
}
if !first || (displacer == nil || !displacer.SideClosed(pos, cube.Pos{neighB.x, pos[1], neighB.z}, w)) {
if spreadNeighbour(b, pos, w, neighB, queue) {
queue.shortestPath = neighB.Len()
paths = append(paths, neighB.Path(pos))
}
}
if !first || (displacer == nil || !displacer.SideClosed(pos, cube.Pos{neighC.x, pos[1], neighC.z}, w)) {
if spreadNeighbour(b, pos, w, neighC, queue) {
queue.shortestPath = neighC.Len()
paths = append(paths, neighC.Path(pos))
}
}
if !first || (displacer == nil || !displacer.SideClosed(pos, cube.Pos{neighD.x, pos[1], neighD.z}, w)) {
if spreadNeighbour(b, pos, w, neighD, queue) {
queue.shortestPath = neighD.Len()
paths = append(paths, neighD.Path(pos))
}
}
first = false
}
return paths
}
// spreadNeighbour attempts to spread a path node into the neighbour passed. Note that this does not spread
// the liquid, it only spreads the node used to calculate flow paths.
func spreadNeighbour(b world.Liquid, src cube.Pos, w *world.World, node liquidNode, queue *liquidQueue) bool {
if node.depth+3 <= 0 {
// Depth has reached zero or below, can't spread any further.
return false
}
if node.Len() > queue.shortestPath {
// This path is longer than any existing path, so don't spread any further.
return false
}
pos := cube.Pos{node.x, src[1], node.z}
if !canFlowInto(b, w, pos, true) {
// Can't flow into this block, can't spread any further.
return false
}
pos[1]--
if canFlowInto(b, w, pos, false) {
return true
}
queue.PushBack(node)
return false
}
// canFlowInto checks if a liquid can flow into the block present in the world at a specific block position.
func canFlowInto(b world.Liquid, w *world.World, pos cube.Pos, sideways bool) bool {
bl := w.Block(pos)
if _, air := bl.(Air); air {
// Fast route for air: A type assert to a concrete type is much faster than a type assert to an interface.
return true
}
if _, ok := b.(LiquidRemovable); ok {
if liq, ok := bl.(world.Liquid); ok && sideways {
if (liq.LiquidDepth() == 8 && !liq.LiquidFalling()) || liq.LiquidType() != b.LiquidType() {
// Can't flow into a liquid if it has a depth of 8 or if it doesn't have the same type.
return false
}
}
return true
}
return false
}
// liquidNode represents a position that is part of a flow path for a liquid.
type liquidNode struct {
x, z int
depth int8
previous *liquidNode
}
// neighbours returns the four horizontal neighbours of the node with decreased depth.
func (node liquidNode) neighbours(decay int8) (a, b, c, d liquidNode) {
return liquidNode{x: node.x - 1, z: node.z, depth: node.depth - decay, previous: &node},
liquidNode{x: node.x + 1, z: node.z, depth: node.depth - decay, previous: &node},
liquidNode{x: node.x, z: node.z - 1, depth: node.depth - decay, previous: &node},
liquidNode{x: node.x, z: node.z + 1, depth: node.depth - decay, previous: &node}
}
// Len returns the length of the path created by the node.
func (node liquidNode) Len() int {
i := 1
for {
if node.previous == nil {
return i - 1
}
//noinspection GoAssignmentToReceiver
node = *node.previous
i++
}
}
// Path converts the liquid node into a path.
func (node liquidNode) Path(src cube.Pos) liquidPath {
l := node.Len()
path := make(liquidPath, l)
i := l - 1
for {
if node.previous == nil {
return path
}
path[i] = cube.Pos{node.x, src[1], node.z}
//noinspection GoAssignmentToReceiver
node = *node.previous
i--
}
}
// liquidQueuePool is use to re-use liquid node queues.
var liquidQueuePool = sync.Pool{
New: func() interface{} {
return &liquidQueue{
nodes: make([]liquidNode, 0, 64),
shortestPath: math.MaxInt8,
}
},
}
// liquidQueue represents a queue that may be used to push nodes into and take them out of it.
type liquidQueue struct {
nodes []liquidNode
i int
shortestPath int
}
func (q *liquidQueue) PushBack(node liquidNode) {
q.nodes = append(q.nodes, node)
}
func (q *liquidQueue) Front() liquidNode {
v := q.nodes[q.i]
q.i++
return v
}
func (q *liquidQueue) Len() int {
return len(q.nodes) - q.i
}
func (q *liquidQueue) Reset() {
q.nodes = q.nodes[:0]
q.i = 0
q.shortestPath = math.MaxInt8
}