Update formatting

This commit is contained in:
Jakob K
2021-05-15 21:26:10 +02:00
parent ddc576a394
commit fa8fa9ae96
71 changed files with 203 additions and 249 deletions

View File

@@ -7,6 +7,7 @@ import net.md_5.bungee.api.chat.*
import net.md_5.bungee.api.chat.hover.content.Entity import net.md_5.bungee.api.chat.hover.content.Entity
import net.md_5.bungee.api.chat.hover.content.Item import net.md_5.bungee.api.chat.hover.content.Item
import net.md_5.bungee.api.chat.hover.content.Text import net.md_5.bungee.api.chat.hover.content.Text
import java.awt.Color
inline fun chatComponent(builder: KSpigotComponentBuilder.() -> Unit): Array<out BaseComponent> { inline fun chatComponent(builder: KSpigotComponentBuilder.() -> Unit): Array<out BaseComponent> {
return KSpigotComponentBuilder().apply(builder).create() return KSpigotComponentBuilder().apply(builder).create()
@@ -14,7 +15,7 @@ inline fun chatComponent(builder: KSpigotComponentBuilder.() -> Unit): Array<out
class KSpigotComponentBuilder { class KSpigotComponentBuilder {
private val components = ArrayList<BaseComponent>() private val components = ArrayList<BaseComponent>()
// COMPONENTS
inline fun text(text: String, builder: TextComponent.() -> Unit = { }) { inline fun text(text: String, builder: TextComponent.() -> Unit = { }) {
this += TextComponent(text).apply(builder) this += TextComponent(text).apply(builder)
} }
@@ -41,7 +42,7 @@ class KSpigotComponentBuilder {
) { ) {
this += TranslatableComponent(translatable, with).apply(builder) this += TranslatableComponent(translatable, with).apply(builder)
} }
// SPECIAL
fun legacyText(text: String, color: ChatColor = ChatColor.WHITE, builder: BaseComponent.() -> Unit = { }) { fun legacyText(text: String, color: ChatColor = ChatColor.WHITE, builder: BaseComponent.() -> Unit = { }) {
this += TextComponent.fromLegacyText(text, color).onEach { it.apply(builder) } this += TextComponent.fromLegacyText(text, color).onEach { it.apply(builder) }
} }
@@ -56,10 +57,7 @@ class KSpigotComponentBuilder {
fun create() = components.toTypedArray() fun create() = components.toTypedArray()
} }
/*
* BASE COMPONENT
*/
// extensions
inline fun BaseComponent.hoverEventText(builder: KSpigotComponentBuilder.() -> Unit) { inline fun BaseComponent.hoverEventText(builder: KSpigotComponentBuilder.() -> Unit) {
hoverEvent = HoverEvent(HoverEvent.Action.SHOW_TEXT, Text(KSpigotComponentBuilder().apply(builder).create())) hoverEvent = HoverEvent(HoverEvent.Action.SHOW_TEXT, Text(KSpigotComponentBuilder().apply(builder).create()))
} }
@@ -75,8 +73,7 @@ fun BaseComponent.hoverEventEntity(type: String, id: String, baseComponent: Base
fun BaseComponent.clickEvent(action: ClickEvent.Action, value: String) { fun BaseComponent.clickEvent(action: ClickEvent.Action, value: String) {
clickEvent = ClickEvent(action, value) clickEvent = ClickEvent(action, value)
} }
/*
* GLOBAL SHORTCUTS
*/
fun col(hex: String): ChatColor = ChatColor.of(hex) fun col(hex: String): ChatColor = ChatColor.of(hex)
fun col(rgb: Int): ChatColor = ChatColor.of(Color(rgb))

View File

@@ -76,7 +76,9 @@ internal abstract class PlayerInput<T>(
timeoutSeconds: Int, timeoutSeconds: Int,
) { ) {
private var received = false private var received = false
protected abstract val inputListeners: List<Listener> protected abstract val inputListeners: List<Listener>
protected fun onReceive(input: T?) { protected fun onReceive(input: T?) {
if (!received) { if (!received) {
inputListeners.forEach { it.unregister() } inputListeners.forEach { it.unregister() }

View File

@@ -41,6 +41,7 @@ internal class PlayerInputAnvilInv(
) )
.text("${KColors.ORANGERED}$startText") .text("${KColors.ORANGERED}$startText")
.open(player) .open(player)
override val inputListeners = listOf( override val inputListeners = listOf(
listen<InventoryClickEvent> { listen<InventoryClickEvent> {
if (it.clickedInventory == anvilInv.inventory) if (it.clickedInventory == anvilInv.inventory)

View File

@@ -46,6 +46,7 @@ internal abstract class PlayerInputBook<T>(
} }
abstract fun loadBookContent(bookMeta: BookMeta): T abstract fun loadBookContent(bookMeta: BookMeta): T
override val inputListeners = listOf( override val inputListeners = listOf(
listen<PlayerEditBookEvent> { listen<PlayerEditBookEvent> {
val meta = it.newBookMeta val meta = it.newBookMeta
@@ -63,7 +64,9 @@ internal abstract class PlayerInputBook<T>(
companion object { companion object {
val idKey = NamespacedKey(KSpigotMainInstance, "kspigot_bookinput_id") val idKey = NamespacedKey(KSpigotMainInstance, "kspigot_bookinput_id")
internal val usedIDs = ArrayList<Int>() internal val usedIDs = ArrayList<Int>()
fun getID(): Int { fun getID(): Int {
var returnID = (0..Int.MAX_VALUE).random() var returnID = (0..Int.MAX_VALUE).random()
while (usedIDs.contains(returnID)) returnID = (0..Int.MAX_VALUE).random() while (usedIDs.contains(returnID)) returnID = (0..Int.MAX_VALUE).random()

View File

@@ -14,7 +14,6 @@ internal class PlayerInputChat(
timeoutSeconds: Int, timeoutSeconds: Int,
question: String, question: String,
) : PlayerInput<String>(player, callback, timeoutSeconds) { ) : PlayerInput<String>(player, callback, timeoutSeconds) {
init { init {
player.sendMessage("${KColors.ORANGERED}$question") player.sendMessage("${KColors.ORANGERED}$question")
} }

View File

@@ -9,27 +9,50 @@ interface NBTDataType<T> {
fun writeToCompound(key: String, data: T, compound: NBTTagCompound) fun writeToCompound(key: String, data: T, compound: NBTTagCompound)
companion object { companion object {
val COMPOUND = nbtDataType<NBTData, NBTTagCompound>({ NBTData(it) }, val COMPOUND = nbtDataType<NBTData, NBTTagCompound>(
{ key, data, compound -> compound.set(key, data.nbtTagCompound) }) { NBTData(it) },
val BYTE = { key, data, compound -> compound.set(key, data.nbtTagCompound) }
nbtDataType<Byte, NBTTagByte>({ it.asByte() }, { key, data, compound -> compound.setByte(key, data) }) )
val BYTE_ARRAY = nbtDataType<ByteArray, NBTTagByteArray>({ it.bytes }, val BYTE = nbtDataType<Byte, NBTTagByte>(
{ key, data, compound -> compound.setByteArray(key, data) }) { it.asByte() },
val DOUBLE = nbtDataType<Double, NBTTagDouble>({ it.asDouble() }, { key, data, compound -> compound.setByte(key, data) }
{ key, data, compound -> compound.setDouble(key, data) }) )
val FLOAT = val BYTE_ARRAY = nbtDataType<ByteArray, NBTTagByteArray>(
nbtDataType<Float, NBTTagFloat>({ it.asFloat() }, { key, data, compound -> compound.setFloat(key, data) }) { it.bytes },
val INT = nbtDataType<Int, NBTTagInt>({ it.asInt() }, { key, data, compound -> compound.setInt(key, data) }) { key, data, compound -> compound.setByteArray(key, data) }
val INT_ARRAY = nbtDataType<IntArray, NBTTagIntArray>({ it.ints }, )
{ key, data, compound -> compound.setIntArray(key, data) }) val DOUBLE = nbtDataType<Double, NBTTagDouble>(
val LONG = { it.asDouble() },
nbtDataType<Long, NBTTagLong>({ it.asLong() }, { key, data, compound -> compound.setLong(key, data) }) { key, data, compound -> compound.setDouble(key, data) }
val LONG_ARRAY = nbtDataType<LongArray, NBTTagLongArray>({ it.longs }, )
{ key, data, compound -> compound.set(key, NBTTagLongArray(data)) }) val FLOAT = nbtDataType<Float, NBTTagFloat>(
val SHORT = { it.asFloat() },
nbtDataType<Short, NBTTagShort>({ it.asShort() }, { key, data, compound -> compound.setShort(key, data) }) { key, data, compound -> compound.setFloat(key, data) }
val STRING = nbtDataType<String, NBTTagString>({ it.asString() }, )
{ key, data, compound -> compound.setString(key, data) }) val INT = nbtDataType<Int, NBTTagInt>(
{ it.asInt() },
{ key, data, compound -> compound.setInt(key, data) }
)
val INT_ARRAY = nbtDataType<IntArray, NBTTagIntArray>(
{ it.ints },
{ key, data, compound -> compound.setIntArray(key, data) }
)
val LONG = nbtDataType<Long, NBTTagLong>(
{ it.asLong() },
{ key, data, compound -> compound.setLong(key, data) }
)
val LONG_ARRAY = nbtDataType<LongArray, NBTTagLongArray>(
{ it.longs },
{ key, data, compound -> compound.set(key, NBTTagLongArray(data)) }
)
val SHORT = nbtDataType<Short, NBTTagShort>(
{ it.asShort() },
{ key, data, compound -> compound.setShort(key, data) }
)
val STRING = nbtDataType<String, NBTTagString>(
{ it.asString() },
{ key, data, compound -> compound.setString(key, data) }
)
} }
} }

View File

@@ -1,5 +1,7 @@
package net.axay.kspigot.extensions.bukkit package net.axay.kspigot.extensions.bukkit
// FROM BUNGEE COLOR // FROM BUNGEE COLOR
/** /**
* Returns the corresponding Bukkit Color object. * Returns the corresponding Bukkit Color object.
*/ */
@@ -12,7 +14,9 @@ val net.md_5.bungee.api.ChatColor.bukkitColor
*/ */
val net.md_5.bungee.api.ChatColor.javaAwtColor: java.awt.Color val net.md_5.bungee.api.ChatColor.javaAwtColor: java.awt.Color
get() = color get() = color
// FROM BUKKIT COLOR // FROM BUKKIT COLOR
/** /**
* Returns the corresponding Bungee Color object. * Returns the corresponding Bungee Color object.
*/ */
@@ -24,7 +28,9 @@ val org.bukkit.Color.bungeeColor: net.md_5.bungee.api.ChatColor
*/ */
val org.bukkit.Color.javaAwtColor: java.awt.Color val org.bukkit.Color.javaAwtColor: java.awt.Color
get() = java.awt.Color(asRGB()) get() = java.awt.Color(asRGB())
// FROM JAVA AWT COLOR // FROM JAVA AWT COLOR
/** /**
* Returns the corresponding Bukkit Color object. * Returns the corresponding Bukkit Color object.
*/ */
@@ -36,7 +42,9 @@ val java.awt.Color.bukkitColor
*/ */
val java.awt.Color.bungeeColor: net.md_5.bungee.api.ChatColor val java.awt.Color.bungeeColor: net.md_5.bungee.api.ChatColor
get() = net.md_5.bungee.api.ChatColor.of(this) get() = net.md_5.bungee.api.ChatColor.of(this)
// FROM BUKKIT CHAT COLOR // FROM BUKKIT CHAT COLOR
/** /**
* Returns the corresponding Bukkit Color object. * Returns the corresponding Bukkit Color object.
*/ */

View File

@@ -14,11 +14,6 @@ import org.bukkit.entity.*
import org.bukkit.inventory.EquipmentSlot import org.bukkit.inventory.EquipmentSlot
import org.bukkit.inventory.ItemStack import org.bukkit.inventory.ItemStack
/**
* Checks if the entity is completely in water.
*/
val LivingEntity.isInWater: Boolean get() = isFeetInWater && isHeadInWater
/** /**
* Checks if the entities' head is in water. * Checks if the entities' head is in water.
*/ */

View File

@@ -32,6 +32,7 @@ data class SimpleChunkLocation(
val x: Int, val x: Int,
val z: Int, val z: Int,
) )
// CONVERTER // CONVERTER
fun Location.toSimple() = SimpleLocation3D(x, y, z) fun Location.toSimple() = SimpleLocation3D(x, y, z)
fun Chunk.toSimple() = SimpleChunkLocation(x, z) fun Chunk.toSimple() = SimpleChunkLocation(x, z)

View File

@@ -14,8 +14,10 @@ class SimpleLocationPair(loc1: Location, loc2: Location) {
if (it == loc2.worldOrException) it if (it == loc2.worldOrException) it
else throw IllegalArgumentException("The given locations worlds are not the same!") else throw IllegalArgumentException("The given locations worlds are not the same!")
} }
val minSimpleLoc = SimpleLocation3D(min(loc1.x, loc2.x), min(loc1.y, loc2.y), min(loc1.z, loc2.z)) val minSimpleLoc = SimpleLocation3D(min(loc1.x, loc2.x), min(loc1.y, loc2.y), min(loc1.z, loc2.z))
val maxSimpleLoc = SimpleLocation3D(max(loc1.x, loc2.x), max(loc1.y, loc2.y), max(loc1.z, loc2.z)) val maxSimpleLoc = SimpleLocation3D(max(loc1.x, loc2.x), max(loc1.y, loc2.y), max(loc1.z, loc2.z))
fun isInArea( fun isInArea(
loc: Location, loc: Location,
check3d: Boolean = true, check3d: Boolean = true,
@@ -59,11 +61,16 @@ class LocationArea(loc1: Location, loc2: Location) {
field = value field = value
simpleLocationPair = SimpleLocationPair(loc1, value) simpleLocationPair = SimpleLocationPair(loc1, value)
} }
var simpleLocationPair = SimpleLocationPair(loc1, loc2); private set var simpleLocationPair = SimpleLocationPair(loc1, loc2); private set
val world: World get() = simpleLocationPair.world val world: World get() = simpleLocationPair.world
val minLoc: Location get() = simpleLocationPair.minSimpleLoc.withWorld(simpleLocationPair.world) val minLoc: Location get() = simpleLocationPair.minSimpleLoc.withWorld(simpleLocationPair.world)
val maxLoc: Location get() = simpleLocationPair.maxSimpleLoc.withWorld(simpleLocationPair.world) val maxLoc: Location get() = simpleLocationPair.maxSimpleLoc.withWorld(simpleLocationPair.world)
val touchedChunks: Set<Chunk> get() = simpleLocationPair.touchedSimpleChunks.mapTo(HashSet()) { it.withWorld(world) } val touchedChunks: Set<Chunk> get() = simpleLocationPair.touchedSimpleChunks.mapTo(HashSet()) { it.withWorld(world) }
fun isInArea( fun isInArea(
loc: Location, loc: Location,
check3d: Boolean = true, check3d: Boolean = true,

View File

@@ -36,6 +36,7 @@ infix fun Location.reduceZ(distance: Number) = subtract(0.0, 0.0, distance)
infix fun Location.reduceXY(distance: Number) = subtract(distance, distance, 0.0) infix fun Location.reduceXY(distance: Number) = subtract(distance, distance, 0.0)
infix fun Location.reduceYZ(distance: Number) = subtract(0.0, distance, distance) infix fun Location.reduceYZ(distance: Number) = subtract(0.0, distance, distance)
infix fun Location.reduceXZ(distance: Number) = subtract(distance, 0.0, distance) infix fun Location.reduceXZ(distance: Number) = subtract(distance, 0.0, distance)
// extensions // extensions
fun Location.add(x: Number, y: Number, z: Number) = add(x.toDouble(), y.toDouble(), z.toDouble()) fun Location.add(x: Number, y: Number, z: Number) = add(x.toDouble(), y.toDouble(), z.toDouble())
fun Location.subtract(x: Number, y: Number, z: Number) = subtract(x.toDouble(), y.toDouble(), z.toDouble()) fun Location.subtract(x: Number, y: Number, z: Number) = subtract(x.toDouble(), y.toDouble(), z.toDouble())
@@ -83,9 +84,11 @@ infix fun Location.increase(loc: Location) = add(loc)
infix fun Location.reduce(loc: Location) = subtract(loc) infix fun Location.reduce(loc: Location) = subtract(loc)
infix fun Location.increase(loc: SimpleLocation3D) = add(loc.x, loc.y, loc.z) infix fun Location.increase(loc: SimpleLocation3D) = add(loc.x, loc.y, loc.z)
infix fun Location.reduce(loc: SimpleLocation3D) = subtract(loc.x, loc.y, loc.z) infix fun Location.reduce(loc: SimpleLocation3D) = subtract(loc.x, loc.y, loc.z)
/* /*
* VECTOR * VECTOR
*/ */
val Vector.isFinite: Boolean get() = x.isFinite() && y.isFinite() && z.isFinite() val Vector.isFinite: Boolean get() = x.isFinite() && y.isFinite() && z.isFinite()
// fast construct // fast construct

View File

@@ -23,6 +23,7 @@ fun buildCounterMessageCallback(
StringBuilder().apply { StringBuilder().apply {
if (beforeTime != null) if (beforeTime != null)
append(beforeTime) append(beforeTime)
val hourTime = (curSeconds / 3600) val hourTime = (curSeconds / 3600)
val minuteTime = ((curSeconds % 3600) / 60) val minuteTime = ((curSeconds % 3600) / 60)
val secondsTime = (curSeconds % 60) val secondsTime = (curSeconds % 60)

View File

@@ -39,6 +39,7 @@ abstract class GUI<T : ForInventory>(
* all instances. * all instances.
*/ */
abstract fun closeGUI() abstract fun closeGUI()
protected fun unregisterAndClose() { protected fun unregisterAndClose() {
getAllInstances().forEach { getAllInstances().forEach {
it.bukkitInventory.closeForViewers() it.bukkitInventory.closeForViewers()
@@ -58,7 +59,9 @@ class GUIShared<T : ForInventory>(
} }
override fun getInstance(player: Player) = singleInstance override fun getInstance(player: Player) = singleInstance
override fun getAllInstances() = _singleInstance?.let { listOf(it) } ?: emptyList() override fun getAllInstances() = _singleInstance?.let { listOf(it) } ?: emptyList()
override fun closeGUI() { override fun closeGUI() {
unregisterAndClose() unregisterAndClose()
_singleInstance = null _singleInstance = null
@@ -71,10 +74,12 @@ class GUIIndividual<T : ForInventory>(
resetOnQuit: Boolean, resetOnQuit: Boolean,
) : GUI<T>(guiData) { ) : GUI<T>(guiData) {
private val playerInstances = HashMap<Player, GUIInstance<T>>() private val playerInstances = HashMap<Player, GUIInstance<T>>()
override fun getInstance(player: Player) = override fun getInstance(player: Player) =
playerInstances[player] ?: createInstance(player) playerInstances[player] ?: createInstance(player)
override fun getAllInstances() = playerInstances.values override fun getAllInstances() = playerInstances.values
private fun createInstance(player: Player) = private fun createInstance(player: Player) =
GUIInstance(this, player).apply { GUIInstance(this, player).apply {
playerInstances[player] = this playerInstances[player] = this
@@ -82,6 +87,7 @@ class GUIIndividual<T : ForInventory>(
} }
fun deleteInstance(player: Player) = playerInstances.remove(player)?.unregister() fun deleteInstance(player: Player) = playerInstances.remove(player)?.unregister()
override fun closeGUI() { override fun closeGUI() {
unregisterAndClose() unregisterAndClose()
playerInstances.clear() playerInstances.clear()
@@ -107,8 +113,11 @@ class GUIInstance<T : ForInventory>(
holder: Player?, holder: Player?,
) { ) {
internal val bukkitInventory = gui.data.guiType.createBukkitInv(holder, gui.data.title) internal val bukkitInventory = gui.data.guiType.createBukkitInv(holder, gui.data.title)
private val currentElements = HashSet<GUIElement<*>>() private val currentElements = HashSet<GUIElement<*>>()
internal var isInMove: Boolean = false internal var isInMove: Boolean = false
var currentPageInt: Int = gui.data.defaultPage; private set var currentPageInt: Int = gui.data.defaultPage; private set
val currentPage val currentPage
get() = getPage(currentPageInt) get() = getPage(currentPageInt)

View File

@@ -5,15 +5,17 @@ import org.bukkit.inventory.ItemStack
abstract class GUISlot<T : ForInventory> { abstract class GUISlot<T : ForInventory> {
abstract fun onClick(clickEvent: GUIClickEvent<T>) abstract fun onClick(clickEvent: GUIClickEvent<T>)
} }
// ELEMENT
abstract class GUIElement<T : ForInventory> : GUISlot<T>() { abstract class GUIElement<T : ForInventory> : GUISlot<T>() {
abstract fun getItemStack(slot: Int): ItemStack abstract fun getItemStack(slot: Int): ItemStack
final override fun onClick(clickEvent: GUIClickEvent<T>) { final override fun onClick(clickEvent: GUIClickEvent<T>) {
clickEvent.guiInstance.gui.data.generalOnClick?.invoke(clickEvent) clickEvent.guiInstance.gui.data.generalOnClick?.invoke(clickEvent)
onClickElement(clickEvent) onClickElement(clickEvent)
} }
protected abstract fun onClickElement(clickEvent: GUIClickEvent<T>) protected abstract fun onClickElement(clickEvent: GUIClickEvent<T>)
internal open fun startUsing(gui: GUIInstance<*>) {} internal open fun startUsing(gui: GUIInstance<*>) {}
internal open fun stopUsing(gui: GUIInstance<*>) {} internal open fun stopUsing(gui: GUIInstance<*>) {}
} }

View File

@@ -8,6 +8,7 @@ import org.bukkit.inventory.Inventory
object GUIHolder : AutoCloseable { object GUIHolder : AutoCloseable {
private val registered = HashMap<Inventory, GUIInstance<ForInventory>>() private val registered = HashMap<Inventory, GUIInstance<ForInventory>>()
fun register(guiInstance: GUIInstance<ForInventory>) { fun register(guiInstance: GUIInstance<ForInventory>) {
registered[guiInstance.bukkitInventory] = guiInstance registered[guiInstance.bukkitInventory] = guiInstance
} }
@@ -39,6 +40,7 @@ object GUIHolder : AutoCloseable {
val inv = it.inventory val inv = it.inventory
val gui = registered[inv] ?: return@listen val gui = registered[inv] ?: return@listen
val player = it.playerOrCancel ?: return@listen val player = it.playerOrCancel ?: return@listen
var ifCancel = false var ifCancel = false
for (slotIndex in it.inventorySlots) { for (slotIndex in it.inventorySlots) {

View File

@@ -7,6 +7,7 @@ import net.axay.kspigot.languageextensions.kotlinextensions.MinMaxPair
// INVENTORY // INVENTORY
data class InventoryDimensions(val width: Int, val height: Int) { data class InventoryDimensions(val width: Int, val height: Int) {
val slotAmount = width * height val slotAmount = width * height
val invSlots by lazy { val invSlots by lazy {
ArrayList<InventorySlot>().apply { ArrayList<InventorySlot>().apply {
(1..height).forEach { row -> (1..height).forEach { row ->
@@ -60,6 +61,7 @@ data class InventorySlot(val row: Int, val slotInRow: Int) : Comparable<Inventor
interface InventorySlotCompound<out T : ForInventory> { interface InventorySlotCompound<out T : ForInventory> {
fun withInvType(invType: GUIType<T>): Collection<InventorySlot> fun withInvType(invType: GUIType<T>): Collection<InventorySlot>
fun realSlotsWithInvType(invType: GUIType<T>) = fun realSlotsWithInvType(invType: GUIType<T>) =
withInvType(invType).mapNotNull { it.realSlotIn(invType.dimensions) } withInvType(invType).mapNotNull { it.realSlotIn(invType.dimensions) }
} }
@@ -70,6 +72,7 @@ open class SingleInventorySlot<T : ForInventory> internal constructor(
constructor(row: Int, slotInRow: Int) : this(InventorySlot(row, slotInRow)) constructor(row: Int, slotInRow: Int) : this(InventorySlot(row, slotInRow))
private val slotAsList = listOf(inventorySlot) private val slotAsList = listOf(inventorySlot)
override fun withInvType(invType: GUIType<T>) = slotAsList override fun withInvType(invType: GUIType<T>) = slotAsList
} }
@@ -194,8 +197,10 @@ class InventoryCornerSlots<T : ForInventory> internal constructor(
class InventoryAllSlots<T : ForInventory> : InventorySlotCompound<T> { class InventoryAllSlots<T : ForInventory> : InventorySlotCompound<T> {
override fun withInvType(invType: GUIType<T>) = invType.dimensions.invSlots override fun withInvType(invType: GUIType<T>) = invType.dimensions.invSlots
} }
// SLOT TYPE SAFETY // SLOT TYPE SAFETY
// COLUMNS
// columns
interface ForColumnOne : ForInventoryWidthThree, ForInventoryWidthFive, ForInventoryWidthNine interface ForColumnOne : ForInventoryWidthThree, ForInventoryWidthFive, ForInventoryWidthNine
interface ForColumnTwo : ForInventoryWidthThree, ForInventoryWidthFive, ForInventoryWidthNine interface ForColumnTwo : ForInventoryWidthThree, ForInventoryWidthFive, ForInventoryWidthNine
interface ForColumnThree : ForInventoryWidthThree, ForInventoryWidthFive, ForInventoryWidthNine interface ForColumnThree : ForInventoryWidthThree, ForInventoryWidthFive, ForInventoryWidthNine
@@ -205,7 +210,7 @@ interface ForColumnSix : ForInventoryWidthNine
interface ForColumnSeven : ForInventoryWidthNine interface ForColumnSeven : ForInventoryWidthNine
interface ForColumnEight : ForInventoryWidthNine interface ForColumnEight : ForInventoryWidthNine
interface ForColumnNine : ForInventoryWidthNine interface ForColumnNine : ForInventoryWidthNine
// ROWS // rows
interface ForRowOne : ForInventoryOneByNine, ForInventoryTwoByNine, ForInventoryThreeByNine, ForInventoryFourByNine, interface ForRowOne : ForInventoryOneByNine, ForInventoryTwoByNine, ForInventoryThreeByNine, ForInventoryFourByNine,
ForInventoryFiveByNine, ForInventorySixByNine ForInventoryFiveByNine, ForInventorySixByNine
@@ -216,22 +221,19 @@ interface ForRowThree : ForInventoryThreeByNine, ForInventoryFourByNine, ForInve
interface ForRowFour : ForInventoryFourByNine, ForInventoryFiveByNine, ForInventorySixByNine interface ForRowFour : ForInventoryFourByNine, ForInventoryFiveByNine, ForInventorySixByNine
interface ForRowFive : ForInventoryFiveByNine, ForInventorySixByNine interface ForRowFive : ForInventoryFiveByNine, ForInventorySixByNine
interface ForRowSix : ForInventorySixByNine interface ForRowSix : ForInventorySixByNine
// edge cases:
// EDGE CASES: // row one
// ROW ONE
interface ForRowOneSlotOneToThree : ForRowOne, ForInventoryOneByFive, ForInventoryThreeByThree interface ForRowOneSlotOneToThree : ForRowOne, ForInventoryOneByFive, ForInventoryThreeByThree
interface ForRowOneSlotFourToFive : ForRowOne, ForInventoryOneByFive interface ForRowOneSlotFourToFive : ForRowOne, ForInventoryOneByFive
// row two
// ROW TWO
interface ForRowTwoSlotOneToThree : ForRowTwo, ForInventoryThreeByThree interface ForRowTwoSlotOneToThree : ForRowTwo, ForInventoryThreeByThree
// row three
// ROW THREE
interface ForRowThreeSlotOneToThree : ForRowThree, ForInventoryThreeByThree interface ForRowThreeSlotOneToThree : ForRowThree, ForInventoryThreeByThree
// complete rows (including the edge cases)
// COMPLETE ROWS (including the edge cases)
interface ForCompleteRowOne : ForRowOne, ForRowOneSlotOneToThree, ForRowOneSlotFourToFive interface ForCompleteRowOne : ForRowOne, ForRowOneSlotOneToThree, ForRowOneSlotFourToFive
interface ForCompleteRowTwo : ForRowTwo, ForRowTwoSlotOneToThree interface ForCompleteRowTwo : ForRowTwo, ForRowTwoSlotOneToThree
interface ForCompleteRowThree : ForRowThree, ForRowThreeSlotOneToThree interface ForCompleteRowThree : ForRowThree, ForRowThreeSlotOneToThree
object Slots { object Slots {
// ROW ONE // ROW ONE
val RowOneSlotOne = SingleInventorySlot<ForRowOneSlotOneToThree>(1, 1) val RowOneSlotOne = SingleInventorySlot<ForRowOneSlotOneToThree>(1, 1)

View File

@@ -32,6 +32,7 @@ class GUIType<in T : ForInventory>(
} }
} }
} }
// INVENTORY TYPE SAFETY // INVENTORY TYPE SAFETY
interface ForInventory interface ForInventory
interface ForInventoryThreeByThree : ForInventoryThreeByNine interface ForInventoryThreeByThree : ForInventoryThreeByNine
@@ -42,8 +43,7 @@ interface ForInventoryThreeByNine : ForInventoryFourByNine
interface ForInventoryFourByNine : ForInventoryFiveByNine interface ForInventoryFourByNine : ForInventoryFiveByNine
interface ForInventoryFiveByNine : ForInventorySixByNine interface ForInventoryFiveByNine : ForInventorySixByNine
interface ForInventorySixByNine : ForInventory interface ForInventorySixByNine : ForInventory
interface ForEveryInventory interface ForEveryInventory : ForInventoryOneByNine, ForInventoryTwoByNine, ForInventoryThreeByNine,
: ForInventoryOneByNine, ForInventoryTwoByNine, ForInventoryThreeByNine,
ForInventoryFourByNine, ForInventoryFiveByNine, ForInventorySixByNine, ForInventoryFourByNine, ForInventoryFiveByNine, ForInventorySixByNine,
ForInventoryThreeByThree, ForInventoryOneByFive ForInventoryThreeByThree, ForInventoryOneByFive

View File

@@ -10,9 +10,11 @@ class GUISpaceCompoundElement<T : ForInventory, E> internal constructor(
private val compound: AbstractGUISpaceCompound<T, E>, private val compound: AbstractGUISpaceCompound<T, E>,
) : GUIElement<T>() { ) : GUIElement<T>() {
override fun getItemStack(slot: Int) = compound.getItemStack(slot) override fun getItemStack(slot: Int) = compound.getItemStack(slot)
override fun onClickElement(clickEvent: GUIClickEvent<T>) { override fun onClickElement(clickEvent: GUIClickEvent<T>) {
compound.onClickElement(clickEvent) compound.onClickElement(clickEvent)
} }
// the following two methods register and unregister the instance // the following two methods register and unregister the instance
// for each compound element, but that is ok because it gets // for each compound element, but that is ok because it gets
// added/removed to/from a HashSet // added/removed to/from a HashSet
@@ -44,12 +46,19 @@ abstract class AbstractGUISpaceCompound<T : ForInventory, E> internal constructo
private val onClick: ((GUIClickEvent<T>, E) -> Unit)?, private val onClick: ((GUIClickEvent<T>, E) -> Unit)?,
) { ) {
private val content = ArrayList<E>() private val content = ArrayList<E>()
private var currentContent: List<E> = emptyList() private var currentContent: List<E> = emptyList()
private val internalSlots: MutableList<Int> = ArrayList() private val internalSlots: MutableList<Int> = ArrayList()
private var scrollProgress: Int = 0 private var scrollProgress: Int = 0
private var contentSort: () -> Unit = { } private var contentSort: () -> Unit = { }
private val registeredGUIs = HashSet<GUIInstance<*>>() private val registeredGUIs = HashSet<GUIInstance<*>>()
private fun contentAtSlot(slot: Int) = currentContent.getOrNull(internalSlots.indexOf(slot)) private fun contentAtSlot(slot: Int) = currentContent.getOrNull(internalSlots.indexOf(slot))
private fun recalculateCurrentContent() { private fun recalculateCurrentContent() {
if (scrollProgress > content.size) if (scrollProgress > content.size)
throw IllegalStateException("The scrollProgress is greater than the content size.") throw IllegalStateException("The scrollProgress is greater than the content size.")
@@ -83,6 +92,7 @@ abstract class AbstractGUISpaceCompound<T : ForInventory, E> internal constructo
} }
internal abstract fun handleScrollEndReached(newProgress: Int, internalSlotsSize: Int, contentSize: Int): Boolean internal abstract fun handleScrollEndReached(newProgress: Int, internalSlotsSize: Int, contentSize: Int): Boolean
internal fun getItemStack(slot: Int): ItemStack { internal fun getItemStack(slot: Int): ItemStack {
return contentAtSlot(slot)?.let { return@let iconGenerator.invoke(it) } return contentAtSlot(slot)?.let { return@let iconGenerator.invoke(it) }
?: ItemStack(Material.AIR) ?: ItemStack(Material.AIR)

View File

@@ -6,15 +6,11 @@ import org.bukkit.inventory.ItemFlag
import org.bukkit.inventory.ItemStack import org.bukkit.inventory.ItemStack
import org.bukkit.inventory.meta.ItemMeta import org.bukkit.inventory.meta.ItemMeta
/*
ITEM STACK
*/
// creation
/** /**
* Creates a new [ItemStack] and opens a builder for it. * Creates a new [ItemStack] and opens a builder for it.
*/ */
inline fun itemStack(material: Material, builder: ItemStack.() -> Unit) = ItemStack(material).apply(builder) inline fun itemStack(material: Material, builder: ItemStack.() -> Unit) = ItemStack(material).apply(builder)
// extensions
/** /**
* Opens a builder with the current meta. * Opens a builder with the current meta.
* @param T the specific type of the meta * @param T the specific type of the meta
@@ -44,10 +40,7 @@ inline fun <reified T : ItemMeta> ItemStack.setMeta(builder: T.() -> Unit) {
/** @see setMeta */ /** @see setMeta */
@JvmName("simpleSetMeta") @JvmName("simpleSetMeta")
inline fun ItemStack.setMeta(builder: ItemMeta.() -> Unit) = setMeta<ItemMeta>(builder) inline fun ItemStack.setMeta(builder: ItemMeta.() -> Unit) = setMeta<ItemMeta>(builder)
/*
ITEM META
*/
// creation
/** /**
* Creates new a [ItemMeta] instance of the given material and opens a builder for it. * Creates new a [ItemMeta] instance of the given material and opens a builder for it.
* @param T the specific type of the meta * @param T the specific type of the meta
@@ -60,7 +53,7 @@ inline fun <reified T : ItemMeta> itemMeta(material: Material, builder: T.() ->
/** @see itemMeta */ /** @see itemMeta */
@JvmName("simpleItemMeta") @JvmName("simpleItemMeta")
inline fun itemMeta(material: Material, builder: ItemMeta.() -> Unit) = itemMeta<ItemMeta>(material, builder) inline fun itemMeta(material: Material, builder: ItemMeta.() -> Unit) = itemMeta<ItemMeta>(material, builder)
// extensions
/** /**
* Sets the lore (description) of the item. * Sets the lore (description) of the item.
*/ */

View File

@@ -2,10 +2,12 @@ package net.axay.kspigot.languageextensions.kotlinextensions
import java.io.File import java.io.File
internal fun File.createIfNotExists(): Boolean { fun File.createIfNotExists(): Boolean {
return if (!exists()) { return if (!exists()) {
if (!parentFile.exists()) if (!parentFile.exists())
parentFile.mkdirs() parentFile.mkdirs()
createNewFile() if (isDirectory)
mkdir()
else createNewFile()
} else true } else true
} }

View File

@@ -1,5 +1,7 @@
package net.axay.kspigot.languageextensions.kotlinextensions package net.axay.kspigot.languageextensions.kotlinextensions
internal inline fun <T, R> Lazy<T>.ifInitialized(block: (T) -> R) = if (isInitialized()) block(value) else null internal inline fun <T, R> Lazy<T>.ifInitialized(block: (T) -> R) = if (isInitialized()) block(value) else null
internal val <T> Lazy<T>.valueIfInitialized get() = ifInitialized { value } internal val <T> Lazy<T>.valueIfInitialized get() = ifInitialized { value }
internal fun Lazy<AutoCloseable>.closeIfInitialized() = ifInitialized { value.close() } internal fun Lazy<AutoCloseable>.closeIfInitialized() = ifInitialized { value.close() }

View File

@@ -1,12 +0,0 @@
package net.axay.kspigot.languageextensions.kotlinextensions
internal fun stringBuilder(builder: StringBuilder.() -> Unit) = StringBuilder().apply(builder).toString()
inline fun multiLine(builder: MultiLineBuilder.() -> Unit) = MultiLineBuilder().apply(builder).build()
class MultiLineBuilder {
private val stringBuilder = StringBuilder()
operator fun String.unaryPlus() {
stringBuilder.appendLine(this)
}
fun build() = stringBuilder.toString()
}

View File

@@ -1,13 +0,0 @@
package net.axay.kspigot.main
import com.google.gson.Gson
import com.google.gson.GsonBuilder
object ValueHolder {
private val gsonBuilder by lazy {
GsonBuilder()
}
private val gson: Gson by lazy { gsonBuilder.create() }
private val gsonPretty: Gson by lazy { gsonBuilder.setPrettyPrinting().create() }
fun getGson(pretty: Boolean = false) = if (pretty) gsonPretty else gson
}

View File

@@ -8,6 +8,7 @@ abstract class ChainedRunnablePart<T, R>(
val sync: Boolean, val sync: Boolean,
) { ) {
var next: ChainedRunnablePart<R, *>? = null var next: ChainedRunnablePart<R, *>? = null
protected abstract fun invoke(data: T): R protected abstract fun invoke(data: T): R
/** /**
@@ -79,6 +80,7 @@ class ChainedRunnablePartFirst<R>(
sync: Boolean, sync: Boolean,
) : ChainedRunnablePart<Unit, R>(sync) { ) : ChainedRunnablePart<Unit, R>(sync) {
override fun execute() = start(Unit) override fun execute() = start(Unit)
override fun <E : Exception> executeCatchingImpl( override fun <E : Exception> executeCatchingImpl(
exceptionClass: KClass<E>, exceptionClass: KClass<E>,
exceptionSync: Boolean, exceptionSync: Boolean,
@@ -94,6 +96,7 @@ class ChainedRunnablePartThen<T, R>(
val previous: ChainedRunnablePart<*, T>, val previous: ChainedRunnablePart<*, T>,
) : ChainedRunnablePart<T, R>(sync) { ) : ChainedRunnablePart<T, R>(sync) {
override fun execute() = previous.execute() override fun execute() = previous.execute()
override fun <E : Exception> executeCatchingImpl( override fun <E : Exception> executeCatchingImpl(
exceptionClass: KClass<E>, exceptionClass: KClass<E>,
exceptionSync: Boolean, exceptionSync: Boolean,

View File

@@ -24,10 +24,12 @@ object ItemMetaSerializer : KSerializerForBukkit<ItemMeta>(ItemMeta::class)
object ItemStackSerializer : KSerializerForBukkit<ItemStack>(ItemStack::class) object ItemStackSerializer : KSerializerForBukkit<ItemStack>(ItemStack::class)
object LocationSerializer : KSerializerForBukkit<Location>(Location::class) object LocationSerializer : KSerializerForBukkit<Location>(Location::class)
object VectorSerializer : KSerializerForBukkit<Vector>(Vector::class) object VectorSerializer : KSerializerForBukkit<Vector>(Vector::class)
open class KSerializerForBukkit<T : ConfigurationSerializable>( open class KSerializerForBukkit<T : ConfigurationSerializable>(
private val kClass: KClass<T>, private val kClass: KClass<T>,
) : KSerializer<T> { ) : KSerializer<T> {
override val descriptor = ByteArraySerializer().descriptor override val descriptor = ByteArraySerializer().descriptor
override fun serialize(encoder: Encoder, value: T) { override fun serialize(encoder: Encoder, value: T) {
val bytes = ByteArrayOutputStream() val bytes = ByteArrayOutputStream()
BukkitObjectOutputStream(bytes).use { BukkitObjectOutputStream(bytes).use {

View File

@@ -1,26 +0,0 @@
package net.axay.kspigot.serialization
import net.axay.kspigot.main.ValueHolder
interface SpigotSerializable<T> {
/**
* Converts this serializable object
* into the corresponding spigot object.
*/
fun toSpigot(): T
}
interface SpigotSerializableCompanion<T>
/**
* @return A json string.
*/
fun SpigotSerializable<*>.serialize(pretty: Boolean = true): String = ValueHolder.getGson(pretty).toJson(this)
/**
* Deserializes the given json string and
* returns the deserialized object.
*/
@Suppress("unused")
inline fun <reified T> SpigotSerializableCompanion<T>.deserialize(json: String): T =
ValueHolder.getGson().fromJson(json, T::class.java)

View File

@@ -1,26 +0,0 @@
@file:Suppress("MemberVisibilityCanBePrivate")
package net.axay.kspigot.serialization.serializables
import net.axay.kspigot.serialization.SpigotSerializable
import net.axay.kspigot.serialization.SpigotSerializableCompanion
import org.bukkit.Location
data class SerializableLocation(
val world: SerializableWorld?,
val x: Double,
val y: Double,
val z: Double,
val direction: SerializableVector,
) : SpigotSerializable<Location> {
companion object : SpigotSerializableCompanion<SerializableLocation>
constructor(loc: Location) : this(loc.world?.let { SerializableWorld(it) },
loc.x,
loc.y,
loc.z,
SerializableVector(loc.direction))
override fun toSpigot() = Location(world?.toSpigot(), x, y, z)
.apply { direction = this@SerializableLocation.direction.toSpigot() }
}

View File

@@ -1,19 +0,0 @@
@file:Suppress("MemberVisibilityCanBePrivate")
package net.axay.kspigot.serialization.serializables
import net.axay.kspigot.serialization.SpigotSerializable
import net.axay.kspigot.serialization.SpigotSerializableCompanion
import org.bukkit.util.Vector
data class SerializableVector(
val x: Double,
val y: Double,
val z: Double,
) : SpigotSerializable<Vector> {
companion object : SpigotSerializableCompanion<SerializableVector>
constructor(vec: Vector) : this(vec.x, vec.y, vec.z)
override fun toSpigot() = Vector(x, y, z)
}

View File

@@ -1,19 +0,0 @@
@file:Suppress("MemberVisibilityCanBePrivate")
package net.axay.kspigot.serialization.serializables
import net.axay.kspigot.serialization.SpigotSerializable
import net.axay.kspigot.serialization.SpigotSerializableCompanion
import org.bukkit.Bukkit
import org.bukkit.World
class SerializableWorld(
val name: String,
) : SpigotSerializable<World> {
companion object : SpigotSerializableCompanion<World>
constructor(world: World) : this(world.name)
override fun toSpigot() = Bukkit.getWorld(name)
?: throw NullPointerException("The world \"$name\" does not exist")
}

View File

@@ -10,6 +10,7 @@ import org.bukkit.entity.EntityType
private fun circleEdgeLocations(radius: Number) = HashSet<SimpleLocation2D>().apply { private fun circleEdgeLocations(radius: Number) = HashSet<SimpleLocation2D>().apply {
val currentRadius = radius.toDouble() val currentRadius = radius.toDouble()
var d = -currentRadius var d = -currentRadius
var x = currentRadius var x = currentRadius
var y = 0 var y = 0
@@ -40,6 +41,7 @@ private fun MutableSet<SimpleLocation2D>.addSimpleLoc2D(first: Number, second: N
abstract class Circle(val radius: Number) { abstract class Circle(val radius: Number) {
protected abstract val data: StructureData protected abstract val data: StructureData
val fillLocations by lazy { val fillLocations by lazy {
var currentRadius = radius.toDouble() var currentRadius = radius.toDouble()
@@ -66,8 +68,10 @@ abstract class Circle(val radius: Number) {
val edgeLocations by lazy { val edgeLocations by lazy {
circleEdgeLocations(radius) circleEdgeLocations(radius)
} }
val filledStructure by lazy { structure(true) } val filledStructure by lazy { structure(true) }
val edgeStructure by lazy { structure(false) } val edgeStructure by lazy { structure(false) }
fun structure(filled: Boolean) = Structure( fun structure(filled: Boolean) = Structure(
HashSet<SingleStructureData>().apply { HashSet<SingleStructureData>().apply {
val locations = if (filled) fillLocations else edgeLocations val locations = if (filled) fillLocations else edgeLocations

View File

@@ -28,9 +28,6 @@ data class Structure(
constructor(vararg structureDataSets: Set<SingleStructureData>) constructor(vararg structureDataSets: Set<SingleStructureData>)
: this(structureDataSets.flatMapTo(HashSet()) { it }) : this(structureDataSets.flatMapTo(HashSet()) { it })
} }
/*
* Structure data implementations.
*/
data class StructureDataMaterial( data class StructureDataMaterial(
val material: Material, val material: Material,

View File

@@ -30,8 +30,7 @@ fun LocationArea.loadStructure(includeBlocks: Boolean = true, includeEntities: B
* Sorted by their coordinates. * Sorted by their coordinates.
*/ */
val LocationArea.fillBlocks: Set<Block> val LocationArea.fillBlocks: Set<Block>
get() get() = LinkedHashSet<Block>().apply {
= LinkedHashSet<Block>().apply {
(minLoc.blockX until maxLoc.blockX + 1).forEach { x -> (minLoc.blockX until maxLoc.blockX + 1).forEach { x ->
(minLoc.blockY until maxLoc.blockY + 1).forEach { y -> (minLoc.blockY until maxLoc.blockY + 1).forEach { y ->
(minLoc.blockZ until maxLoc.blockZ + 1).forEach { z -> (minLoc.blockZ until maxLoc.blockZ + 1).forEach { z ->
@@ -45,8 +44,7 @@ val LocationArea.fillBlocks: Set<Block>
* @return All entities in the given [LocationArea]. * @return All entities in the given [LocationArea].
*/ */
val LocationArea.entities: Set<Entity> val LocationArea.entities: Set<Entity>
get() get() = HashSet<Entity>().apply {
= HashSet<Entity>().apply {
touchedChunks.forEach { touchedChunks.forEach {
it.entities.forEach { en -> it.entities.forEach { en ->
if (simpleLocationPair.isInArea(en.location)) if (simpleLocationPair.isInArea(en.location))

View File

@@ -17,6 +17,7 @@ object KSpigotFirework {
class KSpigotFireworkBuilder { class KSpigotFireworkBuilder {
val effects = ArrayList<FireworkEffect>() val effects = ArrayList<FireworkEffect>()
var power: Int? = null var power: Int? = null
inline fun effect(builder: FireworkEffectBuilder.() -> Unit) { inline fun effect(builder: FireworkEffectBuilder.() -> Unit) {
effects += FireworkEffectBuilder().apply(builder).fireworkEffect effects += FireworkEffectBuilder().apply(builder).fireworkEffect
} }
@@ -32,9 +33,11 @@ class KSpigotFireworkBuilder {
class FireworkEffectBuilder { class FireworkEffectBuilder {
private val fireworkBuilder = FireworkEffect.builder() private val fireworkBuilder = FireworkEffect.builder()
var type: FireworkEffect.Type? = null var type: FireworkEffect.Type? = null
var trail: Boolean? = null var trail: Boolean? = null
var flicker: Boolean? = null var flicker: Boolean? = null
fun fade(vararg colors: Color) { fun fade(vararg colors: Color) {
fireworkBuilder.withFade(*colors) fireworkBuilder.withFade(*colors)
} }

View File

@@ -33,7 +33,7 @@ fun PersistentDataHolder.unmark(key: String) {
* this objects' markings. * this objects' markings.
*/ */
fun PersistentDataHolder.hasMark(key: String) = persistentDataContainer.has(markerKey(key), PersistentDataType.BYTE) fun PersistentDataHolder.hasMark(key: String) = persistentDataContainer.has(markerKey(key), PersistentDataType.BYTE)
// quick access for ItemStacks
/** @see PersistentDataHolder.mark */ /** @see PersistentDataHolder.mark */
fun ItemStack.mark(key: String) = meta { mark(key) } fun ItemStack.mark(key: String) = meta { mark(key) }