summaryrefslogtreecommitdiff
path: root/src/main/kotlin/io/dico/parcels2/blockvisitor/RegionTraverser.kt
blob: b749b36879fd1a82256fb4f89be603b36a741160 (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
package io.dico.parcels2.blockvisitor

import io.dico.parcels2.util.math.Dimension
import io.dico.parcels2.util.math.Region
import io.dico.parcels2.util.math.Vec3i
import io.dico.parcels2.util.math.clampMax

private typealias Scope = SequenceScope<Vec3i>
/*
class ParcelTraverser(
    val parcelProvider: ParcelProvider,
    val delegate: RegionTraverser,
    scope: CoroutineScope
) : RegionTraverser(), CoroutineScope by scope {

    class OccupiedException(parcelId: ParcelId) : Exception("Parcel $parcelId is occupied")

    /**
     * Traverse the blocks of parcel's land
     * The iterator must be exhausted, else the permit to traverse it will not be reclaimed.
     *
     * @throws OccupiedException if a parcel is maintained with the given parcel id and an
     *   iterator exists for it that has not been exhausted
     */
    fun traverseParcel(parcelId: ParcelId): Iterator<Vec3i> {
        val world = parcelProvider.getWorldById(parcelId.worldId)
            ?: throw IllegalArgumentException()
        val parcel = parcelProvider.getParcelById(parcelId)

        val medium = if (parcel != null) {
            if (parcel.hasBlockVisitors || parcel !is ParcelImpl) {
                throw OccupiedException(parcelId)
            }
            parcel.hasBlockVisitors = true
            TraverserMedium { parcel.hasBlockVisitors = false }
        } else {
            TraverserMedium.DoNothing
        }

        val region = world.blockManager.getRegion(parcelId)
        return traverseRegion(region, world.world.maxHeight, medium)
    }

    override suspend fun Scope.build(region: Region, medium: TraverserMedium) {
        with(delegate) {
            return build(region, medium)
        }
    }

}

@Suppress("FunctionName")
inline fun TraverserMedium(crossinline whenComplete: () -> Unit) =
    object : TraverserMedium {
        override fun iterationCompleted() {
            whenComplete()
        }
    }

/**
 * An object that is able to communicate with an iterator returned by [RegionTraverser]
 *
 */
interface TraverserMedium {

    /**
     * Called by the traverser during first [Iterator.hasNext] call that returns false
     */
    fun iterationCompleted()

    /**
     * The default [TraverserMedium], which does nothing.
     */
    object DoNothing : TraverserMedium {
        override fun iterationCompleted() {}
    }
}*/

sealed class RegionTraverser {

    /**
     * Get an iterator traversing [region] using this traverser.
     * Depending on the implementation, [region] might be traversed in a specific order and direction.
     */
    fun traverseRegion(
        region: Region,
        worldHeight: Int = 256/*,
        medium: TraverserMedium = TraverserMedium.DoNothing*/
    ): Iterator<Vec3i> = iterator { build(validify(region, worldHeight)/*, medium*/) }

    abstract suspend fun Scope.build(region: Region/*, medium: TraverserMedium = TraverserMedium.DoNothing*/)

    companion object {
        val upward = Directional(TraverseDirection(1, 1, 1), TraverseOrderFactory.createWith(Dimension.Y, Dimension.X))
        val downward = Directional(TraverseDirection(1, -1, 1), TraverseOrderFactory.createWith(Dimension.Y, Dimension.X))
        val toClear get() = downward
        val toFill get() = upward

        /**
         * The returned [RegionTraverser] will traverse the regions
         * * below and including absolute level [y] first, in [upward] direction.
         * * above absolute level [y] last, in [downward] direction.
         */
        fun convergingTo(y: Int) = Slicing(y, upward, downward, true)

        /**
         * The returned [RegionTraverser] will traverse the regions
         * * above absolute level [y] first, in [upward] direction.
         * * below and including absolute level [y] second, in [downward] direction.
         */
        fun separatingFrom(y: Int) = Slicing(y, downward, upward, false)

        private fun validify(region: Region, worldHeight: Int): Region {
            if (region.origin.y < 0) {
                val origin = region.origin withY 0
                val size = region.size.withY((region.size.y + region.origin.y).clampMax(worldHeight))
                return Region(origin, size)
            }

            if (region.origin.y + region.size.y > worldHeight) {
                val size = region.size.withY(worldHeight - region.origin.y)
                return Region(region.origin, size)
            }

            return region
        }

    }

    class Directional(
        val direction: TraverseDirection,
        val order: TraverseOrder
    ) : RegionTraverser() {

        private inline fun iterate(max: Int, increasing: Boolean, action: (Int) -> Unit) {
            for (i in 0..max) {
                action(if (increasing) i else max - i)
            }
        }

        override suspend fun Scope.build(region: Region/*, medium: TraverserMedium*/) {
            val order = order
            val (primary, secondary, tertiary) = order.toArray()
            val (origin, size) = region

            val maxOfPrimary = size[primary] - 1
            val maxOfSecondary = size[secondary] - 1
            val maxOfTertiary = size[tertiary] - 1

            val isPrimaryIncreasing = direction.isIncreasing(primary)
            val isSecondaryIncreasing = direction.isIncreasing(secondary)
            val isTertiaryIncreasing = direction.isIncreasing(tertiary)

            iterate(maxOfPrimary, isPrimaryIncreasing) { p ->
                iterate(maxOfSecondary, isSecondaryIncreasing) { s ->
                    iterate(maxOfTertiary, isTertiaryIncreasing) { t ->
                        yield(order.add(origin, p, s, t))
                    }
                }
            }

            /*medium.iterationCompleted()*/
        }

    }

    class Slicing(
        val bottomSectionMaxY: Int,
        val bottomTraverser: RegionTraverser,
        val topTraverser: RegionTraverser,
        val bottomFirst: Boolean = true
    ) : RegionTraverser() {

        private fun slice(region: Region, atY: Int): Pair<Region, Region?> {
            if (atY < region.size.y + 1) {
                val bottom = Region(region.origin, region.size.withY(atY + 1))
                val top = Region(region.origin.withY(atY + 1), region.size.addY(-atY - 1))
                return bottom to top
            }
            return region to null
        }

        override suspend fun Scope.build(region: Region/*, medium: TraverserMedium*/) {
            val (bottom, top) = slice(region, bottomSectionMaxY)

            if (bottomFirst) {
                with(bottomTraverser) { build(bottom) }
                top?.let { with(topTraverser) { build(it) } }
            } else {
                top?.let { with(topTraverser) { build(it) } }
                with(bottomTraverser) { build(bottom) }
            }

            /*medium.iterationCompleted()*/
        }
    }

    /**
     * Returns [Directional] instance that would be responsible for
     * emitting the given position if it is contained in a region.
     * [Directional] instance has a set order and direction
     */
    fun childForPosition(position: Vec3i): Directional {
        var cur = this
        while (true) {
            when (cur) {
                /*is ParcelTraverser -> cur = cur.delegate*/
                is Directional -> return cur
                is Slicing ->
                    cur =
                        if (position.y <= cur.bottomSectionMaxY) cur.bottomTraverser
                        else cur.topTraverser
            }
        }
    }

    /**
     * Returns true if and only if this traverser would visit the given
     * [block] position before the given [current] position.
     * If at least one of [block] and [current] is not contained in a
     * region being traversed the result is undefined.
     */
    fun comesFirst(current: Vec3i, block: Vec3i): Boolean {
        var cur = this
        while (true) {
            when (cur) {
                /*is ParcelTraverser -> cur = cur.delegate*/
                is Directional -> return cur.direction.comesFirst(current, block)
                is Slicing -> {
                    val border = cur.bottomSectionMaxY
                    cur = when {
                        current.y <= border && block.y <= border -> cur.bottomTraverser
                        current.y <= border -> return !cur.bottomFirst
                        block.y <= border -> return cur.bottomFirst
                        else -> cur.topTraverser
                    }
                }
            }
        }
    }

}

object TraverseOrderFactory {
    private fun isSwap(primary: Dimension, secondary: Dimension) = secondary.ordinal != (primary.ordinal + 1) % 3

    fun createWith(primary: Dimension, secondary: Dimension): TraverseOrder {
        // tertiary is implicit
        if (primary == secondary) throw IllegalArgumentException()
        return TraverseOrder(primary, isSwap(primary, secondary))
    }
}

inline class TraverseOrder(val orderNum: Int) {
    constructor(first: Dimension, swap: Boolean)
        : this(if (swap) first.ordinal + 3 else first.ordinal)

    @Suppress("NOTHING_TO_INLINE")
    private inline fun element(index: Int) = Dimension[(orderNum + index) % 3]

    private val swap inline get() = orderNum >= 3

    /**
     * The slowest changing dimension
     */
    val primary: Dimension get() = element(0)

    /**
     * Second slowest changing dimension
     */
    val secondary: Dimension get() = element(if (swap) 2 else 1)

    /**
     * Dimension that changes every block
     */
    val tertiary: Dimension get() = element(if (swap) 1 else 2)

    /**
     * All 3 dimensions in this order
     */
    fun toArray() = arrayOf(primary, secondary, tertiary)

    fun add(vec: Vec3i, p: Int, s: Int, t: Int): Vec3i =
    // optimize this, will be called lots
        when (orderNum) {
            0 -> vec.add(p, s, t) // xyz
            1 -> vec.add(t, p, s) // yzx
            2 -> vec.add(s, t, p) // zxy
            3 -> vec.add(p, t, s) // xzy
            4 -> vec.add(s, p, t) // yxz
            5 -> vec.add(t, s, p) // zyx
            else -> error("Invalid orderNum $orderNum")
        }
}

inline class TraverseDirection(val bits: Int) {
    fun isIncreasing(dimension: Dimension) = (1 shl dimension.ordinal) and bits != 0

    fun comesFirst(current: Vec3i, block: Vec3i, dimension: Dimension): Boolean =
        if (isIncreasing(dimension))
            block[dimension] <= current[dimension]
        else
            block[dimension] >= current[dimension]

    fun comesFirst(current: Vec3i, block: Vec3i) =
        comesFirst(current, block, Dimension.X)
            && comesFirst(current, block, Dimension.Y)
            && comesFirst(current, block, Dimension.Z)

    companion object {
        operator fun invoke(x: Int, y: Int, z: Int) = invoke(Vec3i(x, y, z))

        operator fun invoke(block: Vec3i): TraverseDirection {
            if (block.x == 0 || block.y == 0 || block.z == 0) throw IllegalArgumentException()
            var bits = 0
            if (block.x > 0) bits = bits or 1
            if (block.y > 0) bits = bits or 2
            if (block.z > 0) bits = bits or 4
            return TraverseDirection(bits)
        }
    }

}