Initial features

main
kalle 2023-04-08 23:48:00 +02:00
commit e256ebfbee
24 changed files with 1003 additions and 0 deletions

4
.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
.idea/
.gradle/
build/
run/

101
build.gradle.kts Normal file
View File

@ -0,0 +1,101 @@
import net.minecrell.pluginyml.bukkit.BukkitPluginDescription
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
kotlin("jvm") version "1.7.0-RC"
id("com.github.johnrengelman.shadow") version "7.1.2"
id("io.papermc.paperweight.userdev") version "1.3.5"
id("xyz.jpenilla.run-paper") version "1.0.6" // Adds runServer and runMojangMappedServer tasks for testing
id("net.minecrell.plugin-yml.bukkit") version "0.5.1"
}
val projectGroup: String by project
val projectVersion: String by project
val mainPackage: String by project
val mainClass: String by project
val paperVersion: String by project
val acfVersion: String by project
val dlibVersion: String by project
group = projectGroup
version = projectVersion
repositories {
mavenLocal()
mavenCentral()
maven("https://papermc.io/repo/repository/maven-public/")
maven("https://repo.aikar.co/content/groups/aikar/")
}
dependencies {
paperDevBundle(paperVersion)
implementation("co.aikar:acf-paper:$acfVersion")
implementation("nl.kallestruik:DLib:$dlibVersion")
implementation("org.jetbrains.kotlin:kotlin-scripting-common")
implementation("org.jetbrains.kotlin:kotlin-scripting-jvm")
implementation("org.jetbrains.kotlin:kotlin-scripting-jvm-host")
testImplementation(kotlin("test"))
}
// Use KSP Generated sources
sourceSets.main {
java.srcDirs("build/generated/ksp/main/kotlin")
}
tasks {
test {
useJUnitPlatform()
}
withType<JavaCompile> {
options.compilerArgs.add("-parameters")
options.isFork = true
options.forkOptions.executable = "javac"
options.encoding = Charsets.UTF_8.name() // We want UTF-8 for everything
// Set the release flag. This configures what version bytecode the compiler will emit, as well as what JDK APIs are usable.
// See https://openjdk.java.net/jeps/247 for more information.
options.release.set(17)
}
withType<KotlinCompile> {
kotlinOptions.jvmTarget = "1.8"
kotlinOptions.javaParameters = true
}
shadowJar {
relocate("co.aikar.commands", "$mainPackage.acf")
relocate("co.aikar.locales", "$mainPackage.locales")
}
withType<Javadoc> {
options.encoding = Charsets.UTF_8.name() // We want UTF-8 for everything
}
processResources {
filteringCharset = Charsets.UTF_8.name() // We want UTF-8 for everything
}
assemble {
dependsOn(reobfJar)
}
}
// Configure plugin.yml generation
bukkit {
load = BukkitPluginDescription.PluginLoadOrder.STARTUP
main = "$mainPackage.$mainClass"
apiVersion = "1.18"
authors = listOf("Kalle \"dragontamerfred\" Struik")
commands {
register("ditems")
}
}

10
gradle.properties Normal file
View File

@ -0,0 +1,10 @@
kotlin.code.style=official
projectGroup=nl.kallestruik
projectName=DItems
projectVersion=1.0
mainPackage=nl.kallestruik.ditems
mainClass=DItems
paperVersion=1.18.2-R0.1-SNAPSHOT
acfVersion=0.5.1-SNAPSHOT
dlibVersion=1.5.0

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

234
gradlew vendored Executable file
View File

@ -0,0 +1,234 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

89
gradlew.bat vendored Normal file
View File

@ -0,0 +1,89 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

9
settings.gradle.kts Normal file
View File

@ -0,0 +1,9 @@
pluginManagement {
repositories {
gradlePluginPortal()
maven("https://papermc.io/repo/repository/maven-public/")
}
}
rootProject.name = "DItems"

View File

@ -0,0 +1,24 @@
package nl.kallestruik.ditems
import co.aikar.commands.BaseCommand
import co.aikar.commands.annotation.CommandAlias
import co.aikar.commands.annotation.Single
import co.aikar.commands.annotation.Subcommand
import org.bukkit.command.CommandSender
import org.bukkit.entity.Player
@CommandAlias("ditems")
class CommandDItems: BaseCommand() {
@Subcommand("give")
fun onGive(player: Player, @Single id: String) {
val item = ItemManager.items[id]?.createItemStack() ?: return
player.inventory.addItem(item)
}
@Subcommand("reload")
fun onReload(sender: CommandSender) {
ItemManager.items.clear()
ItemManager.loadItems(sender)
}
}

View File

@ -0,0 +1,22 @@
package nl.kallestruik.ditems
import co.aikar.commands.PaperCommandManager
import org.bukkit.plugin.java.JavaPlugin
class DItems: JavaPlugin() {
private lateinit var commandManager: PaperCommandManager
override fun onEnable() {
commandManager = PaperCommandManager(this).also {
it.enableUnstableAPI("brigadier")
it.enableUnstableAPI("help")
}
commandManager.registerCommand(CommandDItems())
ItemManager.setup(this)
ItemManager.loadItems()
server.pluginManager.registerEvents(EventListener(this), this)
}
}

View File

@ -0,0 +1,69 @@
package nl.kallestruik.ditems
import nl.kallestruik.ditems.dsl.item.OnBreakBlock
import nl.kallestruik.ditems.dsl.item.OnInventoryClick
import nl.kallestruik.ditems.dsl.item.OnRightClick
import org.bukkit.block.Block
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.block.Action
import org.bukkit.event.block.BlockBreakEvent
import org.bukkit.event.inventory.InventoryClickEvent
import org.bukkit.event.player.PlayerInteractEvent
import java.util.*
class EventListener(
private val plugin: DItems,
): Listener {
@EventHandler
fun onBreakBlock(event: BlockBreakEvent) {
val item = event.player.inventory.itemInMainHand
val customItem = ItemManager.getCustomItem(item) ?: return
val lastTwoTargetBlocks: List<Block> = event.player.getLastTwoTargetBlocks(null, 7)
if (lastTwoTargetBlocks.size != 2 || !lastTwoTargetBlocks[1].type.isOccluding) return
val targetBlock: Block = lastTwoTargetBlocks[1]
val adjacentBlock: Block = lastTwoTargetBlocks[0]
val face = targetBlock.getFace(adjacentBlock) ?: return
// Make sure we don't break blocks other than the one that we intended
if (targetBlock != event.block) return
OnBreakBlock(event, event.block.location, face, item, customItem, plugin).apply(customItem.onBreakBlock)
}
@EventHandler
fun onInventoryInteract(event: InventoryClickEvent) {
val cursor = event.cursor
val clicked = event.currentItem
val cursorCustomItem = cursor?.let { ItemManager.getCustomItem(it) }
if (cursorCustomItem != null)
OnInventoryClick(event, cursor, cursorCustomItem, clicked, plugin).apply(cursorCustomItem.onInventoryClick)
val clickedCustomItem = clicked?.let { ItemManager.getCustomItem(it) }
if (clickedCustomItem != null)
OnInventoryClick(event, clicked, clickedCustomItem, cursor, plugin).apply(clickedCustomItem.onInventoryClick)
}
@EventHandler
fun onRightClick(event: PlayerInteractEvent) {
if (!(event.action == Action.RIGHT_CLICK_AIR || event.action == Action.RIGHT_CLICK_BLOCK)) return
val item = event.player.inventory.getItem(event.hand ?: return)
val customItem = ItemManager.getCustomItem(item) ?: return
if (isOnCooldown(event.player.uniqueId, customItem)) return
OnRightClick(event, event.player, item, customItem, plugin).apply(customItem.onRightClick)
}
fun isOnCooldown(uuid: UUID, item: Item): Boolean {
val cooldown = ItemManager.itemCooldowns[Pair(uuid, item.id)] ?: return false
return System.currentTimeMillis() - cooldown.start < cooldown.length
}
}

View File

@ -0,0 +1,45 @@
package nl.kallestruik.ditems
import net.kyori.adventure.text.Component
import net.kyori.adventure.text.format.TextDecoration
import nl.kallestruik.ditems.dsl.item.ItemAttribute
import nl.kallestruik.ditems.dsl.item.OnBreakBlock
import nl.kallestruik.ditems.dsl.item.OnInventoryClick
import nl.kallestruik.ditems.dsl.item.OnRightClick
import nl.kallestruik.ditems.dsl.exceptions.InvalidItemException
import org.bukkit.Material
import org.bukkit.attribute.AttributeModifier
import org.bukkit.inventory.ItemStack
import org.bukkit.persistence.PersistentDataType
import java.util.*
data class Item(
val id: String,
val name: Component,
val baseItem: Material,
val onBreakBlock: OnBreakBlock.() -> Unit = {},
val onInventoryClick: OnInventoryClick.() -> Unit = {},
val onRightClick: OnRightClick.() -> Unit = {},
val finalizeItemStack: ItemStack.() -> Unit = {},
val attributes: List<ItemAttribute> = emptyList(),
) {
fun createItemStack(): ItemStack {
val stack = ItemStack(baseItem)
stack.editMeta {
it.persistentDataContainer.set(ItemManager.ITEM_ID_KEY, PersistentDataType.STRING, id)
it.displayName(Component.empty().decoration(TextDecoration.ITALIC, false).append(name))
it.attributeModifiers = null
for (attribute in attributes) {
if (attribute.attribute == null)
throw InvalidItemException("Attributes need to at least have a attribute defined!")
it.addAttributeModifier(attribute.attribute!!, AttributeModifier(UUID.randomUUID(), attribute.name, attribute.value, attribute.operation, attribute.slot))
}
}
return stack.apply(finalizeItemStack)
}
}

View File

@ -0,0 +1,6 @@
package nl.kallestruik.ditems
data class ItemCooldown(
val start: Long,
val length: Long,
)

View File

@ -0,0 +1,90 @@
package nl.kallestruik.ditems
import net.kyori.adventure.text.Component
import net.kyori.adventure.text.format.NamedTextColor
import net.kyori.adventure.text.format.TextColor
import nl.kallestruik.ditems.script.DItemsScriptHost
import org.bukkit.Bukkit
import org.bukkit.NamespacedKey
import org.bukkit.command.CommandSender
import org.bukkit.inventory.ItemStack
import org.bukkit.persistence.PersistentDataType
import java.io.File
import java.util.*
import kotlin.script.experimental.api.ScriptDiagnostic
object ItemManager {
val items: MutableMap<String, Item> = mutableMapOf()
val itemCooldowns: MutableMap<Pair<UUID, String>, ItemCooldown> = mutableMapOf()
private lateinit var scriptFolder: File
lateinit var ITEM_ID_KEY: NamespacedKey
fun setup(plugin: DItems) {
this.scriptFolder = File(plugin.dataFolder, "items")
this.scriptFolder.mkdirs()
ITEM_ID_KEY = NamespacedKey(plugin, "custom_item_id")
}
private fun colorForSeverity(severity: ScriptDiagnostic.Severity): TextColor {
return when (severity) {
ScriptDiagnostic.Severity.DEBUG -> NamedTextColor.GRAY
ScriptDiagnostic.Severity.INFO -> NamedTextColor.BLUE
ScriptDiagnostic.Severity.WARNING -> NamedTextColor.YELLOW
ScriptDiagnostic.Severity.ERROR -> NamedTextColor.RED
ScriptDiagnostic.Severity.FATAL -> NamedTextColor.DARK_RED
}
}
fun loadItems(logTarget: CommandSender = Bukkit.getServer().consoleSender) {
val loadStartTime = System.nanoTime()
val scriptFiles = scriptFolder
.listFiles()
?.filter { it.isFile }
?.filter { it.name.endsWith(".ditems.kts") }
?: listOf()
val reports = scriptFiles
.flatMap { DItemsScriptHost.evalFile(it) }
reports
.filter { it.severity > ScriptDiagnostic.Severity.DEBUG }
.forEach {
logTarget.sendMessage(
Component.empty()
.append(Component.text("[${it.severity.name}] ").color(colorForSeverity(it.severity)))
.append(Component.text("(${it.sourcePath}: ${it.location?.start?.line}) "))
.append(Component.text(it.message))
)
}
val loadTime = System.nanoTime() - loadStartTime
val loadTimeString = "%.1f".format(loadTime / 1000000000.0)
logTarget.sendMessage(Component.empty()
.append(Component.text("[DItems] ").color(NamedTextColor.GOLD))
.append(Component.empty().color(NamedTextColor.YELLOW)
.append(Component.text("Loaded "))
.append(Component.text(items.size).color(NamedTextColor.AQUA))
.append(Component.text(" items in "))
.append(Component.empty().color(NamedTextColor.AQUA)
.append(Component.text(loadTimeString))
.append(Component.text("s"))
)
)
)
}
fun getCustomItem(stack: ItemStack): Item? {
val meta = stack.itemMeta ?: return null
val dataContainer = meta.persistentDataContainer
if (!dataContainer.has(ITEM_ID_KEY))
return null
val id = dataContainer.get(ITEM_ID_KEY, PersistentDataType.STRING) ?: return null
return items[id]
}
}

View File

@ -0,0 +1,3 @@
package nl.kallestruik.ditems.dsl.exceptions
class InvalidItemException(override val message: String?): RuntimeException(message)

View File

@ -0,0 +1,13 @@
package nl.kallestruik.ditems.dsl.item
import org.bukkit.attribute.Attribute
import org.bukkit.attribute.AttributeModifier
import org.bukkit.inventory.EquipmentSlot
data class ItemAttribute(
var attribute: Attribute? = null,
var value: Double = 0.0,
var name: String = "",
var operation: AttributeModifier.Operation = AttributeModifier.Operation.ADD_NUMBER,
var slot: EquipmentSlot? = null,
)

View File

@ -0,0 +1,59 @@
package nl.kallestruik.ditems.dsl.item
import net.kyori.adventure.text.Component
import nl.kallestruik.ditems.Item
import nl.kallestruik.ditems.ItemManager
import nl.kallestruik.ditems.dsl.exceptions.InvalidItemException
import org.bukkit.Material
import org.bukkit.inventory.ItemStack
fun item(config: ItemBuilder.() -> Unit): Item {
val item = ItemBuilder().apply(config).build()
ItemManager.items[item.id] = item
return item
}
class ItemBuilder {
var id: String? = null
var name: Component? = null
var baseItem: Material = Material.AIR
private var onBreakBlock: OnBreakBlock.() -> Unit = {}
private var onInventoryClick: OnInventoryClick.() -> Unit = {}
private var onRightClick: OnRightClick.() -> Unit = {}
private var finalizeItemStack: ItemStack.() -> Unit = {}
private val attributes = mutableListOf<ItemAttribute>()
fun onBreakBlock(onBreak: OnBreakBlock.() -> Unit) {
this.onBreakBlock = onBreak
}
fun onInventoryClick(onInventoryClick: OnInventoryClick.() -> Unit) {
this.onInventoryClick = onInventoryClick
}
fun onRightClick(onRightClick: OnRightClick.() -> Unit) {
this.onRightClick = onRightClick
}
fun finalizeItemStack(finalizeItemStack: ItemStack.() -> Unit) {
this.finalizeItemStack = finalizeItemStack
}
fun attribute(itemAttribute: ItemAttribute.() -> Unit) {
attributes += ItemAttribute().apply(itemAttribute)
}
fun build(): Item {
return Item(
id = id ?: throw InvalidItemException("An item needs to have an id!"),
name = name ?: throw InvalidItemException("An item needs to have a name!"),
baseItem = baseItem,
onBreakBlock = onBreakBlock,
onInventoryClick = onInventoryClick,
onRightClick = onRightClick,
finalizeItemStack = finalizeItemStack,
attributes = attributes,
)
}
}

View File

@ -0,0 +1,25 @@
package nl.kallestruik.ditems.dsl.item
import nl.kallestruik.ditems.Item
import org.bukkit.Location
import org.bukkit.block.BlockFace
import org.bukkit.event.block.BlockBreakEvent
import org.bukkit.inventory.ItemStack
import org.bukkit.plugin.java.JavaPlugin
class OnBreakBlock(
val event: BlockBreakEvent,
val pos: Location,
val face: BlockFace,
val itemStack: ItemStack,
val item: Item,
val plugin: JavaPlugin,
) {
fun breakBlock(pos: Location) {
pos.world.getBlockAt(pos).breakNaturally(itemStack)
}
fun relative(x: Int, y: Int, z: Int): Location {
return pos.clone().add(x.toDouble(), y.toDouble(), z.toDouble())
}
}

View File

@ -0,0 +1,14 @@
package nl.kallestruik.ditems.dsl.item
import nl.kallestruik.ditems.Item
import org.bukkit.event.inventory.InventoryClickEvent
import org.bukkit.inventory.ItemStack
import org.bukkit.plugin.java.JavaPlugin
class OnInventoryClick(
val event: InventoryClickEvent,
val itemStack: ItemStack,
val item: Item,
val other: ItemStack?,
val plugin: JavaPlugin,
)

View File

@ -0,0 +1,56 @@
package nl.kallestruik.ditems.dsl.item
import nl.kallestruik.ditems.Item
import nl.kallestruik.ditems.ItemCooldown
import nl.kallestruik.ditems.ItemManager
import org.bukkit.Location
import org.bukkit.entity.*
import org.bukkit.event.player.PlayerInteractEvent
import org.bukkit.inventory.ItemStack
import org.bukkit.plugin.java.JavaPlugin
class OnRightClick(
val event: PlayerInteractEvent,
val player: Player,
val itemStack: ItemStack,
val item: Item,
val plugin: JavaPlugin,
) {
fun summon(where: Location, type: EntityType): Entity {
return player.world.spawn(where, type.entityClass!!)
}
fun shoot(where: Location, type: EntityType, speed: Double): Projectile {
val projectile = summon(where, type) as Projectile
projectile.velocity = player.location.direction.clone().normalize().multiply(speed)
projectile.shooter = player
return projectile
}
fun fireball(where: Location, type: EntityType): Fireball {
val fireball = shoot(where, type, 0.0) as Fireball
fireball.direction = player.location.direction.clone().normalize()
return fireball
}
fun relative(x: Double, y: Double, z: Double): Location {
return player.location.relative(x, y, z)
}
fun forward(amount: Double): Location {
return player.eyeLocation.forward(amount)
}
private fun Location.relative(x: Double, y: Double, z: Double): Location {
return this.clone().add(x, y, z)
}
private fun Location.forward(amount: Double): Location {
return this.clone().add(player.location.direction.clone().normalize().multiply(amount))
}
fun cooldown(ticks: Int) {
player.setCooldown(item.baseItem, ticks)
ItemManager.itemCooldowns[Pair(player.uniqueId, item.id)] = ItemCooldown(System.currentTimeMillis(), ticks * 50L)
}
}

View File

@ -0,0 +1,21 @@
package nl.kallestruik.ditems.dsl.recipe
import org.bukkit.inventory.ShapedRecipe
fun shapedRecipe(config: ShapedRecipeBuilder.() -> Unit): ShapedRecipe {
val recipe = ShapedRecipeBuilder().apply(config).build()
//TODO: Store in recipe manager. And make it.
return recipe
}
class ShapedRecipeBuilder {
fun build(): ShapedRecipe {
//TODO: Get result item in some way. Both vanilla item stacks and custom items need to be supported.
// val recipe = ShapedRecipe()
TODO()
}
}

View File

@ -0,0 +1,71 @@
package nl.kallestruik.ditems.script
import net.kyori.adventure.text.Component
import org.bukkit.Material
import org.bukkit.attribute.Attribute
import org.bukkit.entity.EntityType
import org.bukkit.inventory.EquipmentSlot
import java.io.File
import kotlin.script.experimental.annotations.KotlinScript
import kotlin.script.experimental.api.*
import kotlin.script.experimental.host.FileBasedScriptSource
import kotlin.script.experimental.host.FileScriptSource
import kotlin.script.experimental.jvm.dependenciesFromCurrentContext
import kotlin.script.experimental.jvm.jvm
@KotlinScript(
// File extension for the script type
fileExtension = "ditems.kts",
// Compilation configuration for the script type
compilationConfiguration = DItemsScriptConfiguration::class
)
abstract class DItemsScript
/**
* Import other script(s)
*/
@Target(AnnotationTarget.FILE)
@Repeatable
@Retention(AnnotationRetention.SOURCE)
annotation class Import(vararg val paths: String)
object DItemsScriptConfiguration: ScriptCompilationConfiguration({
jvm {
defaultImports(Material::class, EntityType::class, Component::class, Attribute::class, EquipmentSlot::class)
defaultImports("nl.kallestruik.ditems.dsl.item.item")
refineConfiguration {
onAnnotations(Import::class, handler = DItemsScriptConfigurator())
}
// Extract the whole classpath from context classloader and use it as dependencies
dependenciesFromCurrentContext(wholeClasspath = true)
ide {
acceptedLocations(ScriptAcceptedLocation.Everywhere)
}
}
})
class DItemsScriptConfigurator : RefineScriptCompilationConfigurationHandler {
override operator fun invoke(context: ScriptConfigurationRefinementContext): ResultWithDiagnostics<ScriptCompilationConfiguration> =
processAnnotations(context)
private fun processAnnotations(context: ScriptConfigurationRefinementContext): ResultWithDiagnostics<ScriptCompilationConfiguration> {
val annotations = context.collectedData?.get(ScriptCollectedData.foundAnnotations)?.takeIf { it.isNotEmpty() }
?: return context.compilationConfiguration.asSuccess()
val scriptBaseDir = (context.script as? FileBasedScriptSource)?.file?.parentFile
val importedSources = annotations.flatMap {
(it as? Import)?.paths?.map { sourceName ->
FileScriptSource(scriptBaseDir?.resolve(sourceName) ?: File(sourceName))
} ?: emptyList()
}
return ScriptCompilationConfiguration(context.compilationConfiguration) {
if (importedSources.isNotEmpty()) importScripts.append(importedSources)
}.asSuccess()
}
}

View File

@ -0,0 +1,33 @@
package nl.kallestruik.ditems.script
import nl.kallestruik.ditems.DItems
import java.io.File
import kotlin.script.experimental.api.ScriptDiagnostic
import kotlin.script.experimental.host.toScriptSource
import kotlin.script.experimental.jvm.baseClassLoader
import kotlin.script.experimental.jvm.dependenciesFromCurrentContext
import kotlin.script.experimental.jvm.jvm
import kotlin.script.experimental.jvmhost.BasicJvmScriptingHost
import kotlin.script.experimental.jvmhost.createJvmCompilationConfigurationFromTemplate
import kotlin.script.experimental.jvmhost.createJvmEvaluationConfigurationFromTemplate
object DItemsScriptHost {
fun evalFile(scriptFile: File): List<ScriptDiagnostic> {
val compilationConfiguration = createJvmCompilationConfigurationFromTemplate<DItemsScript> {
jvm {
// Script will have access to everything in the classpath
dependenciesFromCurrentContext(wholeClasspath = true)
}
}
val evaluationConfiguration = createJvmEvaluationConfigurationFromTemplate<DItemsScript> {
jvm {
baseClassLoader.put(DItems::class.java.classLoader)
}
}
val result = BasicJvmScriptingHost().eval(scriptFile.toScriptSource(), compilationConfiguration, evaluationConfiguration)
return result.reports
}
}