Files
src
build.gradle.kts
manifest.kod
settings.gradle.kts
Code
10 633
src/main/kotlin/com/kodari/villager/VillagerManager.kt
package com.kodari.villager
import com.kodari.villager.model.TradeData
import com.kodari.villager.model.VillagerRecord
import net.kyori.adventure.text.Component
import net.kyori.adventure.text.format.NamedTextColor
import net.kyori.adventure.text.format.TextDecoration
import org.bukkit.Bukkit
import org.bukkit.Location
import org.bukkit.Material
import org.bukkit.NamespacedKey
import org.bukkit.World
import org.bukkit.configuration.file.YamlConfiguration
import org.bukkit.entity.Player
import org.bukkit.entity.Villager
import org.bukkit.inventory.ItemStack
import org.bukkit.inventory.MerchantRecipe
import org.bukkit.persistence.PersistentDataType
import java.io.File
import java.util.Locale
import kotlin.math.atan2
import kotlin.math.hypot
class VillagerManager(private val plugin: VillagerPlugin) {
private val records = linkedMapOf<String, VillagerRecord>()
private val viewerEntities = mutableMapOf<java.util.UUID, MutableMap<String, Villager>>()
private val markerKey = NamespacedKey(plugin, "managed-villager")
private val villagerFile = File(plugin.dataFolder, "villagers.yml")
private val colors = linkedMapOf(
"white" to NamedTextColor.WHITE,
"yellow" to NamedTextColor.YELLOW,
"green" to NamedTextColor.GREEN,
"aqua" to NamedTextColor.AQUA,
"blue" to NamedTextColor.BLUE,
"purple" to NamedTextColor.LIGHT_PURPLE,
"red" to NamedTextColor.RED,
"orange" to NamedTextColor.GOLD
)
fun colorNames(): Set<String> = colors.keys
fun get(name: String): VillagerRecord? = records[name.trim().lowercase(Locale.ROOT)]
fun all(): Collection<VillagerRecord> = records.values
fun create(name: String, color: String, location: Location): VillagerRecord? {
val key = name.trim().lowercase(Locale.ROOT)
if (key.isEmpty() || records.containsKey(key)) return null
val colorName = color.lowercase(Locale.ROOT)
if (!colors.containsKey(colorName)) return null
val record = VillagerRecord(key, name.trim(), colorName, false, false, location.clone())
records[key] = record
save()
Bukkit.getOnlinePlayers().forEach { spawnForViewer(it, record) }
return record
}
fun remove(name: String): Boolean {
val record = records.remove(name.trim().lowercase(Locale.ROOT)) ?: return false
viewerEntities.values.forEach { copies -> copies.remove(record.key)?.remove() }
save()
return true
}
fun cycleColor(record: VillagerRecord) {
val names = colors.keys.toList()
val next = (names.indexOf(record.colorName) + 1) % names.size
record.colorName = names[next]
applyAppearance(record)
save()
}
fun toggleBold(record: VillagerRecord) {
record.bold = !record.bold
applyAppearance(record)
save()
}
fun toggleGlowing(record: VillagerRecord) {
record.glowing = !record.glowing
applyAppearance(record)
save()
}
fun addTrade(record: VillagerRecord, trade: TradeData) {
record.trades += trade
applyRecipes(record)
save()
}
fun findByEntity(entity: org.bukkit.entity.Entity): VillagerRecord? {
val key = entity.persistentDataContainer.get(markerKey, PersistentDataType.STRING) ?: return null
return records[key]
}
fun openTrade(player: Player, record: VillagerRecord): Boolean {
val villager = viewerEntities[player.uniqueId]?.get(record.key)
?: spawnForViewer(player, record)
?: return false
player.openMerchant(villager, true)
return true
}
fun spawnForViewer(player: Player, record: VillagerRecord): Villager? {
val existing = viewerEntities[player.uniqueId]?.get(record.key)
if (existing != null && !existing.isDead) return existing
val world = record.location.world ?: return null
val entity = world.spawn(record.location, Villager::class.java)
entity.persistentDataContainer.set(markerKey, PersistentDataType.STRING, record.key)
entity.isInvulnerable = true
entity.isPersistent = true
entity.setAI(false)
entity.setCollidable(false)
entity.setRemoveWhenFarAway(false)
entity.canPickupItems = false
applyAppearance(entity, record)
applyRecipes(entity, record)
Bukkit.getOnlinePlayers().forEach { online ->
if (online.uniqueId == player.uniqueId) {
online.showEntity(plugin, entity)
} else {
online.hideEntity(plugin, entity)
}
}
viewerEntities.getOrPut(player.uniqueId) { mutableMapOf() }[record.key] = entity
return entity
}
fun removeViewer(player: Player) {
viewerEntities.remove(player.uniqueId)?.values?.forEach { it.remove() }
}
fun removeAllEntities() {
viewerEntities.values.forEach { copies -> copies.values.forEach { it.remove() } }
viewerEntities.clear()
}
fun tick() {
viewerEntities.forEach { (viewerId, copies) ->
val viewer = Bukkit.getPlayer(viewerId) ?: return@forEach
copies.forEach { (key, villager) ->
val record = records[key] ?: return@forEach
if (villager.isDead || villager.world != viewer.world) return@forEach
val distanceSquared = villager.location.distanceSquared(viewer.location)
if (distanceSquared > 32.0 * 32.0) return@forEach
val villagerLocation = villager.location
val dx = viewer.location.x - villagerLocation.x
val dy = viewer.eyeLocation.y - villagerLocation.y
val dz = viewer.location.z - villagerLocation.z
val desiredYaw = Math.toDegrees(atan2(-dx, dz)).toFloat()
val horizontalDistance = hypot(dx, dz)
val desiredPitch = (-Math.toDegrees(atan2(dy, horizontalDistance))).toFloat().coerceIn(-45f, 45f)
val yawDifference = ((desiredYaw - villagerLocation.yaw + 540f) % 360f) - 180f
val nextYaw = villagerLocation.yaw + yawDifference.coerceIn(-6f, 6f)
villager.setRotation(nextYaw, desiredPitch)
applyAppearance(villager, record)
}
}
}
fun load() {
if (!villagerFile.exists()) return
val yaml = YamlConfiguration.loadConfiguration(villagerFile)
val section = yaml.getConfigurationSection("villagers") ?: return
section.getKeys(false).forEach { key ->
val path = "villagers.$key"
val world = Bukkit.getWorld(yaml.getString("$path.world") ?: return@forEach) ?: return@forEach
val location = Location(
world,
yaml.getDouble("$path.x"),
yaml.getDouble("$path.y"),
yaml.getDouble("$path.z"),
yaml.getDouble("$path.yaw").toFloat(),
yaml.getDouble("$path.pitch").toFloat()
)
val record = VillagerRecord(
key,
yaml.getString("$path.name") ?: key,
yaml.getString("$path.color")?.lowercase(Locale.ROOT)?.takeIf { colors.containsKey(it) } ?: "white",
yaml.getBoolean("$path.bold"),
yaml.getBoolean("$path.glowing"),
location
)
yaml.getConfigurationSection("$path.trades")?.getKeys(false)?.forEach { index ->
val tradePath = "$path.trades.$index"
val first = yaml.getItemStack("$tradePath.first") ?: return@forEach
val result = yaml.getItemStack("$tradePath.result") ?: return@forEach
record.trades += TradeData(first, yaml.getItemStack("$tradePath.second"), result)
}
records[key] = record
}
Bukkit.getOnlinePlayers().forEach { player -> records.values.forEach { spawnForViewer(player, it) } }
}
fun save() {
plugin.dataFolder.mkdirs()