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

import io.dico.parcels2.storage.SerializableParcel
import io.dico.parcels2.storage.SerializableWorld
import io.dico.parcels2.storage.Storage
import io.dico.parcels2.util.Vec2i
import io.dico.parcels2.util.doAwait
import io.dico.parcels2.util.floor
import kotlinx.coroutines.experimental.launch
import org.bukkit.Bukkit
import org.bukkit.Location
import org.bukkit.World
import org.bukkit.WorldCreator
import org.bukkit.block.Block
import org.bukkit.entity.Entity
import org.bukkit.entity.Player
import java.util.*
import kotlin.coroutines.experimental.buildIterator
import kotlin.coroutines.experimental.buildSequence
import kotlin.reflect.jvm.javaMethod
import kotlin.reflect.jvm.kotlinFunction

class Worlds(val plugin: ParcelsPlugin) {
    val worlds: Map<String, ParcelWorld> get() = _worlds
    private val _worlds: MutableMap<String, ParcelWorld> = HashMap()

    fun getWorld(name: String): ParcelWorld? = _worlds[name]

    fun getWorld(world: World): ParcelWorld? = getWorld(world.name)

    fun getParcelAt(block: Block): Parcel? = getParcelAt(block.world, block.x, block.z)

    fun getParcelAt(player: Player): Parcel? = getParcelAt(player.location)

    fun getParcelAt(location: Location): Parcel? = getParcelAt(location.world, location.x.floor(), location.z.floor())

    fun getParcelAt(world: World, x: Int, z: Int): Parcel? = getParcelAt(world.name, x, z)

    fun getParcelAt(world: String, x: Int, z: Int): Parcel? {
        with(getWorld(world) ?: return null) {
            return generator.parcelAt(x, z)
        }
    }

    init {
        val function = ::loadWorlds
        function.javaMethod!!.kotlinFunction
    }

    operator fun SerializableParcel.invoke(): Parcel? {
        return world()?.parcelByID(pos)
    }

    operator fun SerializableWorld.invoke(): ParcelWorld? {
        return world?.let { getWorld(it) }
    }

    fun loadWorlds(options: Options) {
        for ((worldName, worldOptions) in options.worlds.entries) {
            val world: ParcelWorld
            try {

                world = ParcelWorld(
                    worldName,
                    worldOptions,
                    worldOptions.generator.getGenerator(this, worldName),
                    plugin.storage)

            } catch (ex: Exception) {
                ex.printStackTrace()
                continue
            }

            _worlds.put(worldName, world)

            if (Bukkit.getWorld(worldName) == null) {
                plugin.doAwait {
                    cond = {
                        try {
                            // server.getDefaultGameMode() throws an error before any worlds are initialized.
                            // createWorld() below calls that method.
                            // Plugin needs to load on STARTUP for generators to be registered correctly.
                            // Means we need to await the initial worlds getting loaded.

                            plugin.server.defaultGameMode; true
                        } catch (ex: Throwable) {
                            false
                        }
                    }

                    onSuccess = {
                        val bworld = WorldCreator(worldName).generator(world.generator).createWorld()
                        val spawn = world.generator.getFixedSpawnLocation(bworld, null)
                        bworld.setSpawnLocation(spawn.x.floor(), spawn.y.floor(), spawn.z.floor())
                    }
                }
            }

        }

    }
}

interface ParcelProvider {

    fun parcelAt(x: Int, z: Int): Parcel?

    fun parcelAt(vec: Vec2i): Parcel? = parcelAt(vec.x, vec.z)

    fun parcelAt(loc: Location): Parcel? = parcelAt(loc.x.floor(), loc.z.floor())

    fun parcelAt(entity: Entity): Parcel? = parcelAt(entity.location)

    fun parcelAt(block: Block): Parcel? = parcelAt(block.x, block.z)
}

class ParcelWorld constructor(val name: String,
                              val options: WorldOptions,
                              val generator: ParcelGenerator,
                              val storage: Storage) : ParcelProvider by generator, ParcelContainer {
    val world: World by lazy {
        Bukkit.getWorld(name) ?: throw NullPointerException("World $name does not appear to be loaded")
    }
    val container: ParcelContainer = DefaultParcelContainer(this, storage)

    override fun parcelByID(x: Int, z: Int): Parcel? {
        return container.parcelByID(x, z)
    }

    override fun nextEmptyParcel(): Parcel? {
        return container.nextEmptyParcel()
    }

    fun parcelByID(id: Vec2i): Parcel? = parcelByID(id.x, id.z)

    fun enforceOptionsIfApplicable() {
        val world = world
        val options = options
        if (options.dayTime) {
            world.setGameRuleValue("doDaylightCycle", "false")
            world.setTime(6000)
        }

        if (options.noWeather) {
            world.setStorm(false)
            world.setThundering(false)
            world.weatherDuration = Integer.MAX_VALUE
        }

        world.setGameRuleValue("doTileDrops", "${options.doTileDrops}")
    }

}

interface ParcelContainer {

    fun parcelByID(x: Int, z: Int): Parcel?

    fun nextEmptyParcel(): Parcel?

}

typealias ParcelContainerFactory = (ParcelWorld) -> ParcelContainer

class DefaultParcelContainer(private val world: ParcelWorld,
                             private val storage: Storage) : ParcelContainer {
    private var parcels: Array<Array<Parcel>>

    init {
        parcels = initArray(world.options.axisLimit, world)
    }

    fun resizeIfSizeChanged() {
        if (parcels.size / 2 != world.options.axisLimit) {
            resize(world.options.axisLimit)
        }
    }

    fun resize(axisLimit: Int) {
        parcels = initArray(axisLimit, world, this)
    }

    fun initArray(axisLimit: Int, world: ParcelWorld, cur: DefaultParcelContainer? = null): Array<Array<Parcel>> {
        val arraySize = 2 * axisLimit + 1
        return Array(arraySize) {
            val x = it - axisLimit
            Array(arraySize) {
                val z = it - axisLimit
                cur?.parcelByID(x, z) ?: Parcel(world, Vec2i(x, z))
            }
        }
    }

    override fun parcelByID(x: Int, z: Int): Parcel? {
        return parcels.getOrNull(x + world.options.axisLimit)?.getOrNull(z + world.options.axisLimit)
    }

    override fun nextEmptyParcel(): Parcel? {
        return walkInCircle().find { it.owner == null }
    }

    private fun walkInCircle(): Iterable<Parcel> = Iterable {
        buildIterator {
            val center = world.options.axisLimit
            for (radius in 0..center) {
                var x = center - radius; var z = center - radius
                repeat(radius * 2) { yield(parcels[x++][z]) }
                repeat(radius * 2) { yield(parcels[x][z++]) }
                repeat(radius * 2) { yield(parcels[x--][z]) }
                repeat(radius * 2) { yield(parcels[x][z--]) }
            }
        }
    }

    fun allParcels(): Sequence<Parcel> = buildSequence {
        for (array in parcels) {
            yieldAll(array.iterator())
        }
    }

    fun loadAllData() {
        val channel = storage.readParcelData(allParcels(), 100)
        launch(storage.asyncDispatcher) {
            for ((parcel, data) in channel) {
                data?.let { parcel.copyDataIgnoringDatabase(it) }
            }
        }
    }

}