
〚 ⤓ Modrinth / ⤓ Spigot / ⤓ Jenkins 开发构建 / GitHub 源代码 / Javadocs / Discord 〛
关于 BKCommonLib
BKCommonLib 是一款适用于 Paper/Spigot/Bukkit 服务器的插件和库,其中包含大量实用工具、API、框架以及对性能至关重要的代码。它旨在消除插件本身对 Minecraft 服务器代码(即 NMS)的依赖,从而提高其稳定性。
这意味着当 Minecraft 更新时,只需更新此库即可。使用它的插件通常不再需要更新,除非为了与 BKCommonLib 本身保持兼容。
兼容服务器
- Spigot, PaperMC, Pufferfish, Purpur, Tuinity, TacoSpigot
- 上述服务器的其他大多数分支也应该能正常工作
- Forge Paper 混合版,存在一定限制:
- Mohist 1.12.2 和 1.16.5
- Magma 1.12.2
- Arclight 1.12.2, 1.15.2, 1.16.5 和 1.18.2
- CatServer 1.12.2
向后兼容
最新版本的 BKCommonLib 兼容 所有 1.8 及以上版本的 Minecraft。这意味着 BKCommonLib 1.19 版本可以在 Spigot 1.12.2、Paper 1.16.5、Pufferfish 1.18.2 等服务器上运行。
不要为旧版本的 Minecraft 安装旧版本的 BKCommonLib。
支持
如果 Minecraft 刚刚更新,或者 Spottedleaf 在 Paper 中引入了一些突破性的优化,你可能会发现 BKCommonLib 停止工作。Bergerkiller 可能正在处理这个问题,并且我们的构建服务器上可能已经有修复该问题的开发构建版本:
开发构建:
请通过 GitHub Issue Tracker 向我们报告任何问题,或加入我们的 Discord 服务器 以获取帮助。我们也欢迎针对旧服务器版本的问题报告。
教程和示例项目稍显不足,但你可以在 Discord 上询问 API 相关帮助。我们会提供帮助。
功能
包含 Mountiplex 通用 Java 反射库
Mountiplex 是 BKCommonLib 能够同时支持如此多的不同 Minecraft 服务器版本甚至 Forge 的核心所在。它将 ASM、Javassist 和 Objenesis 的优势与 模板引擎 相结合,以便在运行时生成兼容的代码。为了实现这一点,它支持用于宏、反射和重映射的模板声明,并将其转化为编译时生成的接口。
这意味着你不必为每种不同的 paper/spigot/forge/版本组合以及人们创建的数百万个分支编译不同的类。如果有人更改了某些内容,只需添加一个 #if - #endif 块即可!
这是一个各种数据包模板的示例,以展示这种方法的力量
- 使用 Handles、反射和模板引擎进行运行时类生成
- 动态类型/名称重映射以支持 forge/多版本/Mojang Mappings
- 解析版本字符串并进行比较。也可以在模板内部使用。
- 检测类型、方法和字段的存在性,并生成适当的兼容实现
- 在代码中的任何位置使用 #require 访问私有成员并使用 #name 调用它们
- Maven Mojo 任务用于生成接口或将块注释转换为字符串(jdk8 多行字符串反向支持)
- 类型转换
包含 Cloud 命令框架
BKCommonLib 包含了 Cloud 命令框架。使用注解或构建器模式编写清晰的命令,完整支持建议补全、权限处理和本地化。
BKCommonLib 添加了一些默认实用程序,使您能够更快地为 Paper/Spigot 服务器设置环境。
PluginBase 框架
PluginBase 是一个插件可以实现的基类,替代 JavaPlugin,提供了许多便捷功能的访问权限:
- 原生支持此 插件预加载器
- 当其他插件启用时的回调,用于处理软依赖逻辑的动态加载/卸载
- 读取 plugin.yml 以存储自定义元数据
- 验证插件的所有依赖项实际上都已启用
- 简单的辅助方法来注册(数据包)监听器
- plugin.yml 的 classdepend 功能:从其他插件加载类,而无需确保该插件在你的插件之前加载
- 默认命令处理器以读取插件版本和构建号
- 权限 API
- 允许人们设置插件,而无需权限管理器,使用简单的 OP 规则
- 非常基本的基于枚举/静态的权限 API,用于存储你的权限常量
- 添加对 * 通配符的支持,无论使用什么权限管理器(或无)
- 使用 PermissionDefaults.yml 使默认(op/not_op/false/true)用户可配置
- 当玩家缺乏权限时抛出/处理异常
- 本地化 API
- 非常基本的基于枚举/静态的本地化 API
- 自动生成一个用户可以自定义的 Localization.yml
- 支持使用 %0% %1% 等占位符
SoftDependency Library
SoftDependency 是一个简单的库,使得延迟处理第三方软依赖的启用和禁用变得更加容易。
请参阅项目 GitHub 页面以获取更多信息。此库默认包含在 BKCommonLib 中,无需阴影处理或重定位。依赖管理无需在 onEnable() 中调用任何方法即可处理。
示例
public class MyPlugin extends JavaPlugin {
private final SoftDependency<MyDependencyPlugin> myDependency = new SoftDependency<MyDependencyPlugin>(this, "my_dependency") {
@Override
protected MyDependencyPlugin initialize(Plugin plugin) {
return MyDependencyPlugin.class.cast(plugin);
}
@Override
protected void onEnable() {
getLogger().info("Support for MyDependency enabled!");
}
@Override
protected void onDisable() {
getLogger().info("Support for MyDependency disabled!");
}
};
// 可以在任何地方使用 myDependency.get(),如果启用则返回非空值。
}
Server Events
如果使用 Paper 服务器,则默认为 Paper 实现。也使事件在非 Paper 服务器上可用。
- 区块加载/卸载实体事件
- CreaturePreSpawnEvent
- Entity Add/Remove(FromWorld)/RemoveFromServer 事件
- MultiBlockChangeEvent(WorldEdit 集成)
YAML Configuration
Bukkit 的配置 API 糟透了。它很慢,默认值需要在资源中进行阴影处理,并且与节点和列表一起工作很麻烦。BKCommonLib 的 YAML 库改变了这一切:
- 仅使用 SnakeYAML 进行数据<>文本序列化
- 高效的内存存储模型
- 带有默认值的 get 操作类似于 python 的 setdefault。轻松创建默认配置!
- 为每个键支持注释头,包括文件本身的全球头
- 默认情况下禁用 SnakeYAML 的文档大小限制
- 自动将旧版 Minecraft 聊天样式字符转换为 & 并转换回来
- 完全禁用锚点并有一些格式解析放松
- 干净地获取和设置枚举,存储为用户可读的字符串
- 高效的节点列表、节点克隆、迭代
- ItemStack 反序列化的多版本支持
- 注册更改监听器:当节点或嵌套节点被修改时调用回调
- 快速自动保存功能
- 通过缓存过去的文本来表示最小化序列化开销
- 保存时异步写入文件
- 文件上的全局锁会在 save() 仍然挂起时阻止未来的 load()
- 适用于大文件存储 / NoSQL 数据库式访问
示例
FileConfiguration config = new FileConfiguration(myPlugin, "file.yml");
config.load();
config.setHeader("This is the header at the top of the file");
config.addHeader("This adds a new line");
config.setHeader("coolName", "\nSets the cool name. Empty whitespace above.");
config.addHeader("coolName", "Yup, this is on a new line too");
String coolName = config.get("coolName", "DefaultCoolName");
config.setHeader("stuff", "\nThis is some stuff");
ConfigurationNode stuff = config.getNode("stuff");
boolean stuffEnabled = stuff.get("enabled", false);
int stuffCount = stuff.get("count", 0);
// Clone the stuff settings, modify, show yaml
ConfigurationNode stuffCopy = stuff.clone();
stuffCopy.set("count", 20);
System.out.println(stuffCopy.toString());
config.save(); // Non-blocking!
NBT - CommonTag API
提供与服务器内部 NBT Tag 库的接口。在与 Minecraft Server API 交互时广泛使用。
- NBT 的简单用户友好包装器
- 在服务器的实际内部 NBT 库上运行,因此与服务器交互时无需复制
- 从(压缩)字节数据序列化/反序列化 - 读取服务器 .dat 文件
- 读取和修改物品的 NBT
- 读取和修改玩家档案、level.dat 或像 Mob Potion Effects 这样的晦涩事物
ForcedChunk - Chunk load tickets / Chunk Loader
无需阻塞主线程即可轻松加载区块,并保持其加载状态。当需要让区块持续加载以更新其中的实体,或加载区块以处理其中的方块数据时,这一点尤为重要。使用非常简单。
- 异步加载区块
- 保持特定区域的区块处于加载状态
- 支持为同一区块创建多个加载票证(ticket)
- 通过对象追踪加载票证,实现 RAII AutoCloseable 机制
- 可以从其他线程创建/关闭票证
- 可指定半径。半径为 2+ 时允许实体进行 tick 更新。
示例
final ForcedChunk chunk = ForcedChunk.load(world, chunk_x, chunk_z);
chunk.getChunkAsync().thenAccept(chunk -> {
// 操作该区块
for (BlockState state : chunk.getBlockStates()) {
System.out.println(state);
}
// 释放区块票证。如果不释放,区块将保持加载状态。
chunk.close();
});
区块未来提供者 (Chunk Future Provider)
通过 Java CompletableFuture API 提供 区块加载与卸载(实体)Bukkit 事件。无需编写自定义的 EventHandler 处理队列,即可在特定区块加载或卸载时执行逻辑。可以在刚刚加载的区块再次卸载时清理工作,或者在所有相邻区块都加载完毕后在该区块中执行任务。旨在防止同步加载区块,从而避免对服务器性能造成负面影响。
当 futures 的前提条件结束时,它们会自动取消。例如,如果等待所有邻居区块加载完成的 future 的中心区块被卸载,则该 future 会被取消。
建议用例:发现多块结构、读取告示牌的红石状态、生成自定义实体或启动世界事件
示例
private ChunkFutureProvider provider; // = ChunkFutureProvider.of(myPlugin);
@EventHandler
public void onChunkLoad(ChunkLoadEvent event) {
// 当该区块及其全部 8 个相邻区块加载完成后,在该区块中执行任务
// 如果输入区块卸载,此 future 将被取消。
provider.whenAllNeighboursLoaded(event.getChunk(),
ChunkNeighbourList.neighboursOf(event.getChunk(), 1))
.thenAccept(this::doWorkInChunk);
}
public void doWorkInChunk(Chunk chunk) {
// 检查方块状态,可能会进入相邻区块内部
// 我们知道邻居区块也已加载,因此无需同步加载区块!太棒了!
}
方块工具类 (Block Utilities)
离线方块/世界 (Offline Block/World)
- 在插件中存储方块/世界,而无需担心内存泄漏
- 通过 UUID 追踪世界,并在不通过 HashMap 查找的情况下访问已加载的 World
- 追踪离线方块,高效地将其转换为已加载的 Bukkit Blocks
- OfflineWorld 兼容 identity hashmaps
- OfflineBlock 可安全地用作 hashmap 中的键
告示牌变更追踪器 (SignChangeTracker)
- 定期调用 update() 即可知晓告示牌是否发生任何更改
- 无需昂贵的方块实体/方块数据查找即可知道告示牌是否已更改
- 知晓告示牌是否被移除/卸载
- 能够检测来自(告示牌编辑)插件和 /data 命令的更改
- 若与区块未来提供者结合使用,可实现强大的全服告示牌追踪功能
方块数据 (BlockData)
- 替换 Bukkit 的 BlockData API 以支持跨版本兼容
- 快速获取/设置世界中的 BlockData
- 访问方块属性,如透明度、发光性、不透明面、渲染选项(地图显示)、Bukkit 类型等
- 提供对传统 Material Bukkit API 的访问权限。新增对新方块类型的支持。(遗留支持)
带有地图显示的交互式 Minecraft 地图
Bukkit 的地图 API 非常糟糕。BKCommonLib 提供了更好的解决方案。
- 将 2D/3D 内容绘制到 Minecraft 地图或纹理缓冲区上
- 每个地图显示都拥有自己的事件循环/事件回调,如 onTick()
- 使用物品元数据自动加载。创建物品即可完成设置!
- 自动为你分配地图 ID
- 原生支持画框平铺——用于大型图像显示
- 基于科学依据的 RGB -> 地图颜色转换
- 支持渲染 Minecraft 资产(方块、物品)和资源包
- 颜色混合、深度缓冲、256 层画布图层
- 处理画框的左/右键点击,并提供点击像素坐标
- 小部件 (Widgets)
- 使用载具转向控件进行控制(W/A/S/D/空格/潜行)
- 内置菜单导航/焦点/激活逻辑
- 自动追踪需要重绘的区域
- 内置按钮、文本、标签页视图等多种小部件和菜单
实体控制器 (Entity Controllers)
通过在运行时扩展服务器 Entity 类,此 API 使得完全改变服务器上实体的行为成为可能。这是 TrainCarts 运行的核心机制。
- 可以重写实体的 onTick() 以运行自定义例程
- 运行实体的 onMove() 或省略它,处理方块和实体碰撞
- 在运行时热替换现有实体为具有自定义行为的实体,同时保持数据一致性
- 重写实体网络同步(数据包)
协议 API (Protocol API)
提供一个相当完整的多版本兼容 Packet API,特别适用于创建 虚假实体。
- 如果已安装 ProtocolLib,则自动使用它
- Packet 监听器和监控器。修改数据包、取消数据包。
- 发送数据包,可选择绕过监听器
EntityUtil.getUniqueEntityId() 用于生成虚假实体
- 许多数据包拥有完整的 API 来修改其内部字段,跨版本兼容
- 实体移动数据包包含 x/y/z/yaw/pitch 的协议转换
- DataWatcher:实体元数据数据包可以完全检查/修改/创建
- 生成盔甲架(armorstand),控制姿态和外观
- VehicleMountController 可将一个实体作为另一个实体的乘客或旁观者处理。支持乱序的生成/销毁数据包。
Java 工具类
集合 (Collections)
- 访问 FastUtil 的 Int/LongHashMap 集合
- 隐式共享集合(并发写入时复制)
- 不可变的缓存集合(安全地处理数百万玩家组)
- Octree / DoubleOctree - 将地图数据映射到 3D 空间,高效查询立方体区域
- FastTrackedUpdateSet
- 高效请求或取消针对接收者的更新
- 高效迭代需要更新的条目(例如从任务中)
- SortedIdentityCache
- 将一个集合类型映射到另一个并缓存映射结果
- 跟踪元素何时从第三方集合中添加或移除
- 在同步时针对迭代/元素顺序进行了高度优化
- BlockFaceSet - 以集合形式存储 BlockFace 值
数学 (Math)
- 3D 变换 - 带有 yaw/pitch/roll 旋转转换的 Quaternion 和 Matrix4x4
- 可旋转的 3D 包围盒及命中测试
- IntVector2(区块坐标)和 IntVector3(方块坐标)
- BlockFace 逻辑/旋转/数学运算
- 向量数学
- 快速三角函数
LogicUtil
- 可用于抛出异常的消费者/供应者函数式接口
- Java 8 Stream API 辅助方法
- 处理 CompletableFutures 的辅助方法
- 克隆集合,运行时解析类型的克隆
- synchronizeCopyOnWrite - 更新不可变映射/性能缓存
通用 I/O
- Hastebin 上传/下载客户端
- ByteArrayIOStream - Byte Array <> Stream API
- Bit Packet/IO-streams - 编码/解码比特流
- AsyncTextWriter - yaml 使用,异步文本编码并写入文件,配合 Future 使用
LibraryComponent
- 跟踪插件的逻辑并按正确顺序启用/禁用它们
- 根据条件启用不同的组件,例如服务器版本
- 错误处理
杂项
实用类中还隐藏着许多更多功能。请四处探索。
- 高效迭代世界/区块(方块)实体,无需创建垃圾数组或列表副本
- ChatText:简单的聊天组件 API
- HumanHand:以跨版本兼容的方式支持副手和使用中的物品
- 库存工具
- 将输入文本解析为数字、材质等
- 注销事件监听器
- 读取当前服务器刻数(tick value)
- 主线程任务委派与同步
- 供开发者使用:DebugUtil 可在运行时修改行为/参数
- 检查连接玩家的 Minecraft 游戏版本(ViaVersion / ProtocolSupport)
- SignEditDialog
- 向玩家显示弹窗以输入告示牌的四行文本
- 指定告示牌的初始文本
- 不需要实际的告示牌方块
依赖信息
想在您的项目中使用 BKCommonLib?请使用以下仓库和依赖信息。请根据需要更新版本号。
想使用内置的 Cloud Command Framework?请遵循这些说明以正确重定位您的导入语句。
Maven
<repositories>
<repository>
<id>MG-Dev Jenkins CI Maven Repository</id>
<url>https://ci.mg-dev.eu/plugin/repository/everything</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.bergerkiller.bukkit</groupId>
<artifactId>BKCommonLib</artifactId>
<version>1.20.2-v1</version>
<scope>provided</scope>
</dependency>
</dependencies>
Gradle (实验性)
repositories {
maven {
url = 'https://ci.mg-dev.eu/plugin/repository/everything'
}
}
dependencies {
compileOnly 'com.bergerkiller.bukkit:BKCommonLib:1.20.2-v1'
}
构建 BKCommonLib
若要自行构建 BKCommonLib,您需要先运行 Build Tools。否则测试将会失败,Maven 也会报错。编译过程中不会链接任何实际的服务端代码,因此该依赖类型为 test。
您无需构建 Spigot 即可将 BKCommonLib 作为依赖使用,但如果您运行单元测试,则可能需要构建 Spigot。
许可证
Bergerkiller(项目所有者)通常允许人们从库中复制粘贴代码并将其用于自己的插件中。请勿复制像 Map Display API 这样复杂的框架,否则您将难以成功,且最终结果很可能导致与 BKCommonLib 本身的不兼容。
如果您不确定,请在我们的 Discord 服务器中询问。
BKCommonLib 阴影化(shades in)/使用了以下库,可能适用进一步的许可证条款:
MIT 许可证,这里是一些无聊的法律免责声明,以免我被起诉
MIT 许可证
版权所有 (C) 2013-2015 bergerkiller 版权所有 (C) 2016-2022 Berger Healer
特此免费授予任何获得本软件及其相关文档文件(“软件”)副本的人,在不受限制的情况下处理本软件的权限,包括但不限于使用、复制、修改、合并、发布、分发和/或再许可本软件的权利,并允许向其提供本软件的人员这样做,但需满足以下条件:
上述版权声明和本许可声明应包含在本软件的所有副本或重要部分中。
本软件按“原样”提供,不提供任何形式的明示或暗示担保,包括但不限于适销性、特定用途适用性和非侵权性的担保。在任何情况下,作者或版权持有人均不对因软件或其使用或其他交易引起的任何索赔、损害或其他责任负责,无论是在合同诉讼、侵权行为还是其他方面,无论是否源于软件的使用或其他交易。
捐赠
如果您真的喜欢我的工作并希望给予一些回报,请随时通过下方的按钮向我发送小额 PayPal 捐款。谢谢! :)

〚 ⤓ Modrinth / ⤓ Spigot / ⤓ Jenkins Dev Builds / Source on GitHub / Javadocs / Discord 〛
About BKCommonLib
BKCommonLib is a Paper/Spigot/Bukkit server plugin and library which houses a large selection of utilities, API's, frameworks and performance-critical code. It was made to eliminate all use of Minecraft Server Code (aka NMS) from plugins themselves, improving their stability.
It made it so that when Minecraft updates, only this library has to be updated. Plugins using it generally don't require updates anymore, except to stay compatible with BKCommonLib itself.
Compatible Servers
- Spigot, PaperMC, Pufferfish, Purpur, Tuinity, TacoSpigot
- Most other forks of the above should work fine
- Forge Paper hybrids, with limitations:
- Mohist 1.12.2 and 1.16.5
- Magma 1.12.2
- Arclight 1.12.2, 1.15.2, 1.16.5 and 1.18.2
- CatServer 1.12.2
Backwards-Compatible
The latest version of BKCommonLib is compatible with all Minecraft versions 1.8 and above. This means version 1.19 of BKCommonLib should work on Spigot 1.12.2, Paper 1.16.5, Pufferfish 1.18.2 and so on.
Do not install an older version of BKCommonLib for older versions of Minecraft.
Support
If Minecraft just updated or Spottedleaf made some ground-breaking optimizations in Paper, you might find that BKCommonLib stops working. Bergerkiller is probably on the case, and there might already be development builds available that fix your problem over at our build server:
Development Builds:
Report any problems to us on the GitHub Issue Tracker or join our Discord Server for assistance. Issue reports for older server versions are welcome too.
Tutorials and example projects are lacking a bit, but you can ask for API help on the discord. We'll help.
Features
Includes Mountiplex General Purpose Java Reflection Library
Mountiplex is core to BKCommonLib's ability to support so many different Minecraft Server versions and even forge at the same time. It combines the strengths of ASM, Javassist and Objenesis with a Template Engine to generate compatible code at runtime. To achieve this it supports template declarations for macros, reflection and remapping and molds this into a compiletime-generated interface.
This means you don't have to compile different classes for every different permutation of paper/spigot/forge/version and the millions of forks people create. If someone changes something, add an #if - #endif block and you're set!
Here is an example template for various packets to demonstrate the power of this approach
- At-runtime class generation with Handles, reflection, template engine
- Dynamic type/name remapping to support forge/multi-version/Mojang Mappings
- Parse version strings, compare them. Also inside templates.
- Detect existence of types, methods and fields and generate an appropriate compatible implementation
- Access private members with #require and call them with #name anywhere in the code
- Maven Mojo tasks to generate the interfaces or convert block comments into strings (jdk8 multiline string back-support)
- Type Conversion
Includes Cloud Command Framework
BKCommonLib includes the Cloud Command Framework. Write clean commands with annotations or builder pattern, complete with suggestions, permission handling and localization.
BKCommonLib adds a few default utilities to get set up for Paper/Spigot servers even faster.
PluginBase Framework
PluginBase is a base class plugins can implement instead of JavaPlugin that provides access to a lot of convenient features:
- Native support for this Plugin Preloader
- Callbacks for when other plugins enable, to handle dynamic loading/unloading of soft dependency logic
- Read the plugin.yml to store custom metadata
- Validates that all dependencies of the plugin are actually enabled
- Simple helper methods to register (packet) listeners
- Plugin.yml classdepend feature: load classes from other plugins without requiring that plugin loads before yours
- Default command handlers to read the plugin version and build number
- Permission API
- Allows people to set up a plugin without requiring a permission manager, with simple OP rules
- Very basic enum/static based Permission API to store your permission constants
- Adds support for * wildcard, regardless of what permission manager (or none) is used
- Makes the default (op/not_op/false/true) user-configurable using PermissionDefaults.yml
- Throw/handle an exception when a player lacks permission
- Localization API
- Very basic enum/static based Localization API
- Automatically generates a Localization.yml that users can customize
- Supports placeholders using %0% %1% etc.
SoftDependency Library
SoftDependency is a simple library that makes it easier to lazily handle third-party soft dependencies enabling and disabling.
See the Project GitHub page for more information. This library is included in BKCommonLib by default, no shading or relocating required. Dependency management is handled without having to call any methods from your onEnable().
Example
public class MyPlugin extends JavaPlugin {
private final SoftDependency<MyDependencyPlugin> myDependency = new SoftDependency<MyDependencyPlugin>(this, "my_dependency") {
@Override
protected MyDependencyPlugin initialize(Plugin plugin) {
return MyDependencyPlugin.class.cast(plugin);
}
@Override
protected void onEnable() {
getLogger().info("Support for MyDependency enabled!");
}
@Override
protected void onDisable() {
getLogger().info("Support for MyDependency disabled!");
}
};
// Can use myDependency.get() anywhere, returns non-null if enabled.
}
Server Events
Defaults to the Paper implementation if a Paper server is used. Makes the event available on non-Paper servers as well.
- Chunk Load/Unload Entities event
- CreaturePreSpawnEvent
- Entity Add/Remove(FromWorld)/RemoveFromServer events
- MultiBlockChangeEvent (WorldEdit integration)
YAML Configuration
Bukkit's Configuration API is dreadful. It's slow, defaults require shading in resources and working with nodes and lists is cumbersome. BKCommonLib's YAML library changes all of that:
- Uses SnakeYAML only for data<>text serialization
- Efficient memory storage model
- Get with a default value acts like python's setdefault. Easy default configurations!
- Supports comment headers for every key, including a global header for the file itself
- Disables SnakeYAML's document size limitations by default
- Automatically converts legacy Minecraft chat style characters to & and back
- Completely disables anchors and has some format parsing relaxations
- Cleanly get and set enums, stored as user-readable strings
- Efficient node lists, node cloning, iteration
- Multi-version support for ItemStack de-serialization
- Register change listeners: callback is called when a node or nested node is modified
- Fast Auto-Save functionality
- Minimizes serialization overhead by caching past text representations
- Asynchronous writing to file when saving
- Global lock on the file blocks a future load() if a save() is still pending
- Suitable for large file storage / NoSQL database-like access
Example
FileConfiguration config = new FileConfiguration(myPlugin, "file.yml");
config.load();
config.setHeader("This is the header at the top of the file");
config.addHeader("This adds a new line");
config.setHeader("coolName", "\nSets the cool name. Empty whitespace above.");
config.addHeader("coolName", "Yup, this is on a new line too");
String coolName = config.get("coolName", "DefaultCoolName");
config.setHeader("stuff", "\nThis is some stuff");
ConfigurationNode stuff = config.getNode("stuff");
boolean stuffEnabled = stuff.get("enabled", false);
int stuffCount = stuff.get("count", 0);
// Clone the stuff settings, modify, show yaml
ConfigurationNode stuffCopy = stuff.clone();
stuffCopy.set("count", 20);
System.out.println(stuffCopy.toString());
config.save(); // Non-blocking!
NBT - CommonTag API
Comes with an interface to the server's internal NBT Tag library. Used extensively when interfacing with Minecraft Server API's.
- Simple user-friendly wrapper for NBT
- Operates on the server's actual internal NBT library, so no copying when interacting with the server
- Serialize/Deserialize from/to (compressed) byte data - read server .dat files
- Read and Modify NBT of items
- Read and Modify Player Profiles, level.dat or esoteric things like Mob Potion Effects
ForcedChunk - Chunk load tickets / Chunk Loader
Makes it easy to load a chunk without stalling the main thread, and keep it loaded. Important when chunks must stay loaded to tick entities inside or to load chunks to process block data inside. Very easy to use.
- Asynchronous chunk loading
- Keep a chunk area loaded
- Supports multiple chunk load tickets for the same chunk
- Track load tickets with objects, RAII AutoCloseable
- Tickets can be created/closed from other threads
- Radius can be specified. Radius of 2+ will allow for entities to be ticked.
Example
final ForcedChunk chunk = ForcedChunk.load(world, chunk_x, chunk_z);
chunk.getChunkAsync().thenAccept(chunk -> {
// Work with the chunk
for (BlockState state : chunk.getBlockStates()) {
System.out.println(state);
}
// Release the chunk ticket. Could keep it around and the chunk stays loaded.
chunk.close();
});
Chunk Future Provider
Makes the Chunk Load and Unload (Entities) Bukkit Events available through a Java CompletableFuture API. Execute logic when a particular chunk is loaded or unloaded without writing your own EventHandler processing queues. Clean up work when a chunk that just loaded, unloads again. Or perform work in a Chunk once all neighbouring chunks are loaded, too. Aims to prevent synchronous loading of chunks, which negatively impact server performance.
Futures are automatically cancelled when the premise for them is ended. For example, a future waiting for all the neighbours of a chunk to be loaded is cancelled if the chunk at the center of it is unloaded.
Suggested use cases: discovering multi-block structures, reading redstone state of signs, spawn custom entities or start world events
Example
private ChunkFutureProvider provider; // = ChunkFutureProvider.of(myPlugin);
@EventHandler
public void onChunkLoad(ChunkLoadEvent event) {
// When the chunk and all its 8 neighbours are loaded, do work in the chunk
// If the input chunk unloads, this future is cancelled.
provider.whenAllNeighboursLoaded(event.getChunk(),
ChunkNeighbourList.neighboursOf(event.getChunk(), 1))
.thenAccept(this::doWorkInChunk);
}
public void doWorkInChunk(Chunk chunk) {
// Check block states, possibly entering inside neighbouring chunks
// We know neighbours are loaded too, so no sync chunk loading! Yay!
}
Block Utilities
Offline Block/World
- Store blocks/worlds in your plugin without risking memory leaks
- Track worlds by UUIDs and access the loaded World without HashMap lookups
- Track offline blocks, efficiently convert them to loaded Bukkit Blocks
- OfflineWorld is compatible with identity hashmaps
- OfflineBlock can be safely used as a key in hashmaps
SignChangeTracker
- Routinely call update() and you know whether any change to the sign occurred
- Knows whether the sign changed without an expensive lookup of the block entity / block data
- Know whether the sign was removed/unloaded
- Will detect changes from (sign edit) plugins and the /data command
- Powerful server-wide sign tracking if combined with the chunk future provider
BlockData
- Replaces Bukkit's BlockData API for cross-version support
- Fast getting/setting of BlockData in a World
- Access block properties like opacity, emission, opaque faces, render options (map displays), Bukkit types
- Provides access to the legacy Material Bukkit API. Adds support for new block types. (Legacy support)
Interactive Minecraft Maps with Map Displays
Bukkit's Map API is awful. BKCommonLib does it better.
- Draw 2D/3D contents onto Minecraft maps or texture buffers
- Every map display comes with its own event loop / event callbacks like onTick()
- Automatically loaded up using Item Metadata. Create an item and you're done!
- Automatically assigns Map Ids for you
- Supports ItemFrame tiling natively - large image displays
- Scientifically-backed RGB -> Map Color conversion
- Supports rendering of Minecraft assets (blocks, items) and Resource packs
- Color blending, depth buffer, 256 canvas layers
- Left/right-click handling of item frames with clicked pixel coordinates provided
- Widgets
- Uses vehicle steering controls to control (W/A/S/D/Space/Sneak)
- Built-in menu navigation / focus / activation logic
- Automatically tracks clip areas that need redrawing for you
- Comes with buttons, text, tab view and more built-in widgets and menus
Entity Controllers
By extending server Entity classes at runtime, this API makes it possible to completely alter the behavior of entities on the server. This is core to how TrainCarts operates.
- The entity onTick() can be overrided to run your own routines
- Run entity onMove() or omit it, handle block and entity collisions
- Hotswap existing entities at runtime with custom behavior while keeping data consistent
- Override entity network synchronization (packets)
Protocol API
Provides a fairly complete Multi-Version compatible Packet API, particularly geared towards creating fake entities.
- If installed, uses ProtocolLib automatically
- Packet Listeners and Monitors. Modify packets, cancel packets.
- Send packets, with the option to bypass listeners
EntityUtil.getUniqueEntityId() to spawn fake entities
- Lots of packets have a full API to modify fields inside, cross-version compatible
- Entity Movement packets include protocol conversion of the x/y/z/yaw/pitch
- DataWatcher: Entity metadata packet can be fully inspected/modified/created
- Spawn armorstands, control pose and appearance
- VehicleMountController to put one entity as passenger of another, or spectate. Handles out-of-order spawn/destroy packets.
Java Utilities
Collections
- Access to FastUtil's Int/LongHashMap collections
- Implicitly shared collections (copy on concurrent write)
- Immutable cached collections (safely work with millions of sets of players)
- Octree / DoubleOctree - Map data to 3D space, query cuboids efficiently
- FastTrackedUpdateSet
- Efficiently request or cancel an update for a recipient
- Efficiently iterate those that need to update (from a task, for example)
- SortedIdentityCache
- Map one collection type to another and cache the mapped results
- Track when elements are added or removed from a third-party collection
- Heavily optimized for iteration / element order when synchronizing
- BlockFaceSet - Store BlockFace values, in a set
Math
- 3D Transformation - Quaternion and Matrix4x4 with yaw/pitch/roll rotation conversions
- 3D Rotatable Bounding Box with hit-testing
- IntVector2 (chunk coordinates) and IntVector3 (block coordinates)
- BlockFace logic/rotation/maths
- Vector maths
- Fast Trigonometric functions
LogicUtil
- Functional interfaces for consumers/suppliers which can throw
- Helper methods for Java 8 Stream API
- Helper methods for working with CompletableFutures
- Cloning collections, cloning with type resolved at runtime
- synchronizeCopyOnWrite - updating an immutable mapping / performance caches
General I/O
- Hastebin uploader/downloader client
- ByteArrayIOStream - Byte Array <> Stream API
- Bit Packet/IO-streams - encode/decode a bitstream
- AsyncTextWriter - used by yaml, asynchronous encoding of text and writing to file, with future
LibraryComponent
- Track logic of your plugin and enable/disable them in the correct order
- Enable different components based on conditions, such as server version
- Error handling
Miscellaneous
There are many more features hidden inside utility classes. Look around.
- Efficiently iterate world/chunk (block) entities without creating garbage arrays or list copies
- ChatText: Simple Chat Component API
- HumanHand: Support off-hand and held items in a cross-version compatible way
- Inventory utilities
- Parsing of input text into numbers, materials and more
- Deregister event listeners
- Read the current server tick value
- Main thread Task delegation and synchronization
- For developers: DebugUtil to modify behavior/parameters at runtime
- Check the game version of a connected player (ViaVersion / ProtocolSupport)
- SignEditDialog
- Show a popup to a Player to input the 4 lines of text of a sign
- Specify the initial text on the sign
- No actual sign block required
Dependency Information
Want to use BKCommonLib in your own projects? Use the following repository and dependency information. Remember to update the version as necessary.
Want to use the included Cloud Command Framework? Follow these instructions to properly relocate your imports.
Maven
<repositories>
<repository>
<id>MG-Dev Jenkins CI Maven Repository</id>
<url>https://ci.mg-dev.eu/plugin/repository/everything</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.bergerkiller.bukkit</groupId>
<artifactId>BKCommonLib</artifactId>
<version>1.20.2-v1</version>
<scope>provided</scope>
</dependency>
</dependencies>
Gradle (Experimental)
repositories {
maven {
url = 'https://ci.mg-dev.eu/plugin/repository/everything'
}
}
dependencies {
compileOnly 'com.bergerkiller.bukkit:BKCommonLib:1.20.2-v1'
}
Building BKCommonLib
To build BKCommonLib yourself you will need to run Build Tools beforehand. Otherwise tests will fail and maven will complain. No actual server code is linked during compiling, hence the dependency is type test.
You do not need to build Spigot to use BKCommonLib as a dependency, but you might need to if you run unit tests.
License
Bergerkiller, the project owner, is generally fine with people copy-pasting code from the library and using it in their own plugins. Please do not copy complicated frameworks like the Map Display API, you will fail and the end-result will probably end up causing incompatiblities with BKCommonLib itself.
If you're unsure, ask in our Discord server.
BKCommonLib shades in/uses the following libraries, further License conditions may apply:
MIT License, Boring stuff here just so I don't get sued
MIT License
Copyright (C) 2013-2015 bergerkiller Copyright (C) 2016-2022 Berger Healer
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, and/or sublicense the Software,
and to permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Donate
If you really like my work and want to give something in return, feel free to donate something small to me over PayPal using the button down below. Thank you! :)
评论 0
登录后参与评分
还没有评论,来抢沙发吧