CloudWorks API
统一模组开发接口 — 为 NeoForge 1.21.1 模组提供标准化功能,包括耐久方块系统、配方解析和控制台日志捕获。
版本:1.1.0-1.21.1 | 平台:NeoForge 1.21.1 | Java 21
目录
- 快速开始
- DurableBlock — 耐久方块系统
- RecipeParser — 配方解析
- ConsoleSeeker — 控制台日志捕获
- 调试命令
- 模块架构
- 许可证
快速开始
添加依赖
将以下内容添加到你的 build.gradle 中:
repositories {
maven { url = 'https://your-maven-repo' }
}
dependencies {
implementation 'com.cloudworks:CloudWorksAPI:1.1.0-1.21.1'
}
可选依赖:Jade 模组集成
如果你需要为耐久方块显示 Jade 耐久度信息,请添加 Jade API 依赖:
repositories {
maven { url = "https://api.modrinth.com/maven" }
}
dependencies {
compileOnly "maven.modrinth:jade:15.10.5+neoforge"
}
启用模块
CloudWorks API 使用注解按需激活模块。请将相应的注解添加到你的主模组类中:
@Mod("your_mod_id")
@CloudworksRecipeParser // 启用 RecipeParser 模块
@CloudWorksConsoleSeeker // 启用 ConsoleSeeker + API
public class YourMod {
public YourMod(IEventBus modEventBus) {
// ...
}
}
- 带有注解:强制启用该模块,忽略配置文件中的开关
- 没有注解:由配置文件控制
- 每个模块可以独立启用/禁用,彼此之间无依赖关系
DurableBlock — 耐久方块系统
核心概念
DurableBlock 提供了一个完整的耐久方块系统,允许方块拥有耐久度值、伤害抗性以及自动恢复能力。
与传统解决方案不同,该系统不依赖 BlockEntity。相反,它使用 LivingEntity 的子类(DurableBlockEntity)来存储耐久度数据并接收伤害。这种设计结合了 BlockEntity 的数据持久性和 LivingEntity 的可攻击性。
架构
DurableBlock (方块)
│ 放置时生成实体
│ 属性:最大耐久度、基础抗性、特定类型抗性
▼
DurableBlockEntity (LivingEntity)
│ 仅服务端实体 (clientTrackingRange=0)
│ 绑定到方块坐标 (boundPos),每 tick 验证方块是否存在
│ 耐久度计算、伤害处理、NBT 持久化
│
├── 正常流程:耐久度归零 → 破坏方块 → 自我销毁
└── PersistentDurableBlockEntity (子类)
└── 防作弊保护:拦截即死攻击 → 损失 20% 耐久度
核心类
| 类名 |
职责 |
DurableBlock |
耐久方块基类,定义耐久度属性和抗性参数,管理实体生成 |
DurableBlockEntity |
方块实体替代方案 (LivingEntity),处理伤害、耐久度计算、数据持久化 |
PersistentDurableBlock |
持久型耐久方块,继承自 DurableBlock,使用 PersistentDurableBlockEntity |
PersistentDurableBlockEntity |
持久型实体,拦截即死攻击,将其转换为耐久度损失 |
DurableBlockDamageType |
伤害类型枚举 (EXPLOSION / PHYSICAL / MAGIC) |
用法
基础耐久方块
public class MyConcreteBlock extends DurableBlock {
public MyConcreteBlock() {
super(Properties.of()
.strength(3.0f)
.requiresCorrectToolForDrops(),
200, // maxBlockDurability: 最大耐久度
2, // baseResistance: 固定伤害减免
0.3f, // explosionResistance: 爆炸伤害减免 (0.0 ~ 1.0)
0.5f, // physicalResistance: 物理伤害减免 (0.0 ~ 1.0)
0.1f, // magicResistance: 魔法伤害减免 (0.0 ~ 1.0)
0 // recoveryRate: 每秒自动恢复量 (0 = 无恢复)
);
}
}
持久型耐久方块(含防作弊保护)
public class MyPersistentBlock extends PersistentDurableBlock {
public MyPersistentBlock() {
super(Properties.of().strength(3.0f),
200, 2, 0.3f, 0.5f, 0.1f, 0);
}
}
伤害计算
实际伤害 = max(0, 原始伤害 - 基础抗性) × (1 - 类型抗性)
- 基础抗性:从原始伤害中直接扣除的固定数值(最低为 0)
- 类型抗性:根据伤害类型(爆炸/物理/魔法)应用相应的减免比例
- 伤害类型分类:
- 爆炸:TNT、苦力怕、末影水晶、床/重生锚爆炸
- 物理:近战攻击、箭矢、三叉戟、投射物
- 魔法:药水、龙息、凋灵效果、虚空伤害、火焰/闪电
仅服务端实体
耐久方块实体注册时使用了 clientTrackingRange(0),这意味着该实体仅存在于服务端。客户端不知道该实体的存在。这带来了以下好处:
- 玩家无法近战攻击该实体:客户端没有目标;方块只能通过挖掘破坏
- 不会阻碍方块交互:不会阻止在上方放置方块或左键挖掘
- 生物和远程攻击正常工作:凋灵、僵尸和远程攻击仍可在服务端对该实体造成伤害
- 无需同步:不存在客户端/服务端实体数据同步问题
防作弊保护(持久型)
PersistentDurableBlockEntity 使用多层拦截机制来抵抗即死攻击:
remove() 拦截:检查 internalRemoval 标志;外部调用将导致 20% 耐久度损耗
setHealth() 拦截:防止外部操作将生命值归零
setPose() 拦截:防止进入 Pose.DYING(濒死)状态
hurt() 检测:检查 instant_kill_weapon 标签,取消即死武器的伤害事件
dead 状态修正:每 tick 检查和修正 dead 字段
- 无敌帧:每次受击后有 3 tick 的无敌时间,限制每秒最多受到 5 次伤害
即死武器标签
cloudworks_api:instant_kill_weapon 物品标签用于标记即死武器。当持有带有该标签物品的实体进行攻击时,PersistentDurableBlockEntity 将直接取消伤害事件。
默认内容:
{
"values": [
"avaritia:infinity_sword"
]
}
整合包作者可以通过数据包向此标签中添加更多武器。
生命周期管理
- 方块放置:
DurableBlock.setPlacedBy() 在方块位置生成实体
- 方块破坏:实体不再因方块破坏事件而被移除;它自行管理其生命周期
- Tick 验证:实体每 tick 检查其绑定的方块是否仍然存在;如果不存在,则自我销毁
- 耐久耗尽:
onDurabilityZero() 破坏方块并移除实体
- NBT 持久化:通过
addAdditionalSaveData / readAdditionalSaveData 将耐久数据保存到区块中
绑定位置机制
每个实体都在 boundPos 中存储其绑定的方块位置。当实体因任何原因即将消失时,它会摧毁该位置的方块。同时,它每 tick 检查该位置的方块是否仍然存在且符合预期类型;如果不符,则移除自身。这种设计防止了实体的碰撞箱延伸到相邻方块区域从而错误删除其他实体的 bug。
Jade 模组集成
DurableBlock 内置了 Jade 集成 (DurableBlockJadePlugin),可在 Jade 工具提示中显示方块耐久度信息:
- 在方块名称下方一行显示
Durability: current / max(耐久度:当前 / 最大)
- 当前耐久度显示两位小数
- 由于实体采用仅服务端的方法,耐久度数据通过
IServerDataProvider 在服务端收集,并通过 Jade 的数据包同步到客户端
碰撞箱设计
实体碰撞箱大小为 1.02×1.02(略大于 1×1 的方块),中心位于方块中心(y+0.5),向六个方向各延伸 0.01 个方块。这使得生物可以从任何方向攻击实体,而实体不会阻碍方块的放置或移动。
RecipeParser — 配方解析
核心概念
配方解析流程:
Recipe JSON --> serializeRecipe() --> JsonElement
|
v
DSL Template (.rpml) --> TemplateParser --> TemplateNode (AST)
|
v
RecipeExtractor.extract()
|
v
RecipeData
(Ingredient[], Product[])
- 序列化:通过 Minecraft Codec 将配方序列化为 JSON
- 模板解析:将
.rpml DSL 模板解析为 AST
- 数据提取:根据 AST 从 JSON 中提取结构化数据
核心类
| 类 |
职责 |
RecipeParser |
单例核心,管理模板加载、配方解析和流体传输 |
RecipeParserAPI |
静态外观类,向外暴露所有 API |
RecipeData |
解析结果,包含 inputs 和 outputs |
Ingredient |
输入材料:id, count, unit, type |
Product |
输出产物:id, count, unit, type, rate (概率) |
API 参考
所有 API 均通过 RecipeParserAPI 静态方法调用。
基本查询
| 方法 |
描述 |
getRecipeData(ResourceLocation, RecipeManager) |
解析单个配方 |
getRecipeDataBatch(Collection, RecipeManager) |
批量解析配方 |
isRecipeParsable(ResourceLocation, RecipeManager) |
检查配方是否可解析 |
getParsableRecipes(String modId, String recipeType, RecipeManager) |
获取给定类型的所有可解析配方 |
高级查询
// 查找产生目标的配方
List<RecipeParseResult> parseProduceRecipe(
ResourceLocation targetId, // 目标物品/流体 ID
QueryMode mode, // ITEM 或 FLUID
RecipeManager recipeManager
)
// 查找以目标为输入的配方
List<RecipeParseResult> parseUsageRecipe(
ResourceLocation targetId,
QueryMode mode,
RecipeManager recipeManager
)
| mode |
匹配逻辑 (produce) |
匹配逻辑 (usage) |
ITEM |
匹配直接输出 + 流体转物品的传输 |
匹配 unit=item 的原料 |
FLUID |
匹配流体输出 + 反向传输匹配 |
匹配 unit=fluid 的原料 |
异步 API 方法
所有异步 API 均通过 RecipeParserAPI 静态方法调用。繁重的配方扫描和解析工作在专用工作线程上运行(AsyncRecipeParser 线程池,2 个守护线程),结果通过 MinecraftServer 回调传回服务器线程。
RecipeParserAPI.parseProduceRecipeAsync(
ResourceLocation.parse("minecraft:oak_planks"),
QueryMode.ITEM,
recipeManager,
results -> {
// 此回调在服务器线程上运行 -- 安全地操作 Minecraft 对象
for (RecipeParseResult r : results) {
sendSuccess("Found recipe: " + r.getRecipeId());
}
},
errorMsg -> sendFailure("Query failed: " + errorMsg),
server
);
异步方法签名:
| 方法 |
描述 |
getRecipeDataAsync(id, mgr, cb, err, server) |
异步解析单个配方 |
getRecipeDataBatchAsync(ids, mgr, cb, err, server) |
异步批量解析配方 |
parseProduceRecipeAsync(id, mode, mgr, cb, err, server) |
异步查找产出配方 |
parseUsageRecipeAsync(id, mode, mgr, cb, err, server) |
异步查找使用配方 |
数据模型
原料 (Ingredient)
| 字段 |
类型 |
描述 |
id |
String |
物品/流体/标签 ID |
count |
double |
数量 |
unit |
String |
"item" / "fluid" |
type |
String |
"solid" / "tag" / "fluid" |
产物 (Product)
| 字段 |
类型 |
描述 |
id |
String |
产物 ID |
count |
double |
数量 |
unit |
String |
"item" / "fluid" |
type |
String |
"solid" / "tag" / "fluid" |
rate |
double |
产出概率 (0.0 ~ 1.0,默认为 1.0) |
DSL 配方模板
配方模板(.rpml 文件)位于 cloudworks/recipe_parser/templates/,命名格式为 {modid}_{recipetype}.rpml。
标记类型
| 标记 |
语法 |
描述 |
input |
<input,id=foo,count=1,unit=item,type=solid> |
声明输入原料 |
output |
<output,id=bar,count=1,unit=item,type=solid> |
声明输出产物 |
object |
<object,id=myObj> |
声明 JSON 对象节点 |
key |
<key,id=myKey> |
动态 JSON 键遍历 |
io_attribute |
<count,output_id=bar> |
向标记注入属性 |
symbol |
<symbol,id=sym,input_id=keyIng> |
声明形状合成符号 |
patternline |
<patternline,id=line> |
声明形状合成图案行 |
duplicate |
<duplicate,id=dupX,structure=X> |
声明可重复的 JSON 对象结构 |
script |
<script,set_global_fluid_transfer=true> |
全局设置脚本 |
optional |
<optional,id=opt> |
可选字段 |
variable |
<variable,id=var> |
变量引用 |
模板示例
原版合成台(形状合成)
{
"type": "minecraft:crafting_shaped",
<script,set_global_fluid_transfer=true,set_global_default_transfer_rate=250>
"pattern": [
<patternline,id=line>
],
"key": <object,id=keyObj>
<key,id=key>
<object,id=keyIng>
"item": <input,id=keyIng,count=1,unit=item,type=solid>
"tag": <input,id=keyIng,count=1,unit=item,type=tag>
<symbol,id=sym,input_id=keyIng>
<count,id=keyIng_count,input_id=keyIng>
<patternline,id=line,input_id=sym>
"result": <object,id=res>
"count": <count,output_id=res>
"id": <type,output_id=res>
"item": <output,id=res,count=1,unit=item,type=solid>
原版合成台(无形状合成)
{
"type": "minecraft:crafting_shapeless",
"ingredients": [
<object,id=ingStruct>
"item": <input,id=ingItem,count=1,unit=item,type=solid>
"tag": <input,id=ingItem,count=1,unit=item,type=tag>
<count,id=ingCount,input_id=ingItem>
<duplicate,id=ingStruct>
],
"result": <object,id=res>
"count": <count,output_id=res>
"id": <type,output_id=res>
"item": <output,id=res,count=1,unit=item,type=solid>
流体转物品转换
当配方输出流体时,它可以转换为等效的物品,从而允许通过物品 ID 来查找该配方。
转换逻辑: 总流体量 (mB) ÷ rate → 取整(按轮次策略)× 单位产物数量
全局设置(在模板中通过 <script> 配置):
| 参数 |
类型 |
默认值 |
描述 |
global_fluid_transfer |
boolean |
false |
是否启用流体转物品转换 |
global_default_transfer_rate |
double |
100 |
多少 mB 转换为 1 个物品 |
global_default_transfer_result |
string |
null |
默认转换结果的物品 ID |
global_default_transfer_extra_input |
map |
{} |
额外原料 |
global_default_transfer_float_round |
enum |
default |
round_up / round_down / default |
global_enable_template_config |
boolean |
true |
是否启用外部模板配置文件 |
配方级配置 (cloudworks/recipe_parser/templates_config/{modid}_{recipetype}.json):
{
"recipe:id": {
"enable_transfer": true,
"transfer_blacklist": ["fluid:to_skip"],
"methods": [{
"rate": 100,
"round": "default",
"extra_input": {"minecraft:item": 1},
"result": {"minecraft:output_item": 2}
}]
}
}
模板更新机制
cloudworks/recipe_parser/config.json:
{
"version": "1.1.0-1.21.1",
"enable_update": true,
"force_update": false,
"update_ignore": ["minecraft_crafting.rpml"]
}
force_update=true → 跳过所有检查,释放所有文件
enable_update=false → 跳过更新
version 匹配 → 跳过更新
- 否则 → 更新版本,发布排除
update_ignore 中文件的其余文件
ConsoleSeeker — 控制台日志捕获
ConsoleSeeker 实时将控制台日志输出到游戏聊天框,并提供完整的事件管道,供下游模组过滤和处理日志。
启用方式
@CloudWorksConsoleSeeker // 强制启用 ConsoleSeeker + API
或在 cloudworks/console_seeker/config.json 中配置:
{
"enable_module": true,
"enable_api": false,
"enable_command_for_any_operator": true,
"list_type": "whitelist",
"player_list": [],
"max_log_length": 150,
"enable_timestamp": false
}
| 字段 |
类型 |
默认值 |
描述 |
enable_module |
boolean |
true |
是否启用 ConsoleSeeker 模组 |
enable_api |
boolean |
false |
是否启用事件 API(注解可覆盖此设置) |
enable_command_for_any_operator |
boolean |
true |
是否允许所有 OP 使用命令 |
list_type |
string |
"whitelist" |
"whitelist"(白名单)/ "blacklist"(黑名单) |
player_list |
string[] |
[] |
玩家名称列表 |
max_log_length |
int |
150 |
最大日志长度(0 = 不截断) |
enable_timestamp |
boolean |
false |
是否显示时间戳 |
架构
Log4j2 Logger
│
▼
ChatAppender (Log4j2 Appender)
│ 过滤 [CHAT] 子串
▼
LogToChatManager
│ 按日志级别和玩家订阅进行过滤
▼
ConsoleSeekerEventManager
│ 内部过滤器单元 → 收集 tagSet
▼
NeoForge EVENT_BUS
│ 分发 ConsoleSeekerInfoEvent / WarnEvent / ErrorEvent
▼
ExternalLogFilter (由下游模组订阅)
│ 匹配 tagSet → parse() → onReceive()
▼
下游模组自定义逻辑
事件管道
针对不同日志级别的三个独立事件管道:
| 事件类 |
日志级别 |
ConsoleSeekerInfoEvent |
INFO |
ConsoleSeekerWarnEvent |
WARN |
ConsoleSeekerErrorEvent |
ERROR |
所有事件均继承自 ConsoleSeekerLogEvent,包含以下字段:
| 字段 |
类型 |
描述 |
loggerName |
String |
记录器名称 |
level |
Level |
日志级别 |
message |
String |
格式化后的消息(已移除 ANSI 颜色代码) |
timestamp |
long |
Unix 时间戳(毫秒) |
threadName |
String |
线程名称 |
thrownString |
String |
异常堆栈跟踪(无异常时为 null) |
tagSet |
Set<DirectedDeliveryTag> |
定向投递标签集 |
内部过滤器(主动过滤)
通过 ConsoleSeekerEventManager 注册内部过滤器单元,使 ConsoleSeeker 主动过滤日志:
// 实现 InternalFilterUnit 接口
InternalFilterUnit myUnit = new InternalFilterUnit() {
public DirectedDeliveryTag getTag() {
return new DirectedDeliveryTag("mymod", "cpu_alert");
}
public boolean test(LogEvent event) {
return event.getLoggerName().startsWith("com.example");
}
};
// 注册到内部过滤器单元列表
ConsoleSeekerEventManager.addInternalFilterUnit(myUnit);
过滤规则:
- 空列表 → 所有日志事件直接发布,tagSet 为空
- 非空列表 → 至少有一个单元通过才能发布;将通过单元的标签收集到 tagSet 中
- 所有单元均失败 → 事件被丢弃
定向投递标签
使用 "modid:tagName" 格式以防止跨模组冲突:
// 创建标签
DirectedDeliveryTag tag = new DirectedDeliveryTag("mymod", "cpu_alert");
// 匹配规则:空标签匹配所有内容,非空标签需完全匹配
tag.matches(otherTag);
外部过滤器(被动过滤)
下游模组扩展 ExternalLogFilter<T> 以实现自定义日志解析:
public class MyCpuFilter extends ExternalLogFilter<Integer> {
public MyCpuFilter() {
super(new DirectedDeliveryTag("mymod", "cpu_alert"));
}
@Override
protected Integer parse(ConsoleSeekerLogEvent event) {
// 自定义解析逻辑
return Integer.parseInt(event.getMessage());
}
@Override
protected void onReceive(Integer value) {
// 处理解析结果
System.out.println("CPU usage: " + value);
}
}
// 注册以开始接收事件
MyCpuFilter filter = new MyCpuFilter();
filter.register();
工作流程:
- 将事件的
tagSet 与过滤器的标签进行匹配(交集匹配,空标签集匹配所有内容)
parse() 将原始事件转换为自定义类型(默认返回原始日志字符串)
onReceive() 处理解析后的结果
调试命令
命令前缀:/cloudworks。需要 OP 等级 4(部分命令)。
配方模块
/cloudworks recipe parse produce item [id] — 查询生成指定物品的配方
/cloudworks recipe parse produce liquid [id] — 查询生成指定流体的配方
/cloudworks recipe parse usage item [id] — 查询使用指定物品的配方
/cloudworks recipe parse usage liquid [id] — 查询使用指定流体的配方
/cloudworks recipe parsebatch <modid> <type> — 批量解析
/cloudworks recipe listtemplates — 列出已加载的模板
控制台模块
/cloudworks console <info|warn|error> <on|off> — 切换聊天中的日志输出
/cloudworks config console player_list add <player_name> — 添加玩家到列表
/cloudworks config console player_list remove <player_name> — 从列表中移除玩家
/cloudworks config console player_list query — 查看玩家列表
状态查询
/cloudworks status — 查看所有模块状态
输出内容包括:RecipeParser 模板数量、ConsoleSeeker 启用的级别/API 状态/过滤器单元数量。
模块架构
src/main/java/com/cloudworks/api/
├── CloudWorksAPI.java # NeoForge 模组入口点
├── annotation/
│ ├── CloudworksRecipeParser.java # 启用 RecipeParser
│ └── CloudWorksConsoleSeeker.java # 启用 ConsoleSeeker
├── command/
│ └── DebugCommand.java # 统一的调试命令入口
│
├── durableblock/ # DurableBlock 模块
│ ├── DurableBlock.java # 耐久方块基类
│ ├── DurableBlockEntity.java # 方块实体替换(LivingEntity)
│ ├── PersistentDurableBlock.java # 持久化耐久方块
│ ├── PersistentDurableBlockEntity.java # 代码游戏保护实体
│ ├── DurableBlockDamageType.java # 伤害类型枚举
│ └── jade/
│ └── DurableBlockJadePlugin.java # Jade 模组集成插件
│
├── recipeparser/ # RecipeParser 模块
│ ├── RecipeParser.java # 核心单例
│ ├── RecipeParserAPI.java # 静态 API 外观
│ ├── AsyncRecipeParser.java # 异步线程池
│ ├── ApiSelfTest.java # 自动测试
│ ├── DebugOutputWriter.java # 调试 JSON 导出
│ ├── dsl/ # DSL 模板引擎
│ │ ├── Template.java, TemplateNode.java
│ │ ├── TemplateParser.java, TemplateTokenizer.java
│ │ ├── TemplateValidator.java, RecipeExtractor.java
│ │ ├── GlobalSettings.java, TemplateConfig.java
│ │ └── ...
│ └── model/ # 数据模型
│ ├── RecipeData.java, Ingredient.java, Product.java
│ └── QueryMode.java, RecipeParseResult.java
│
└── consoleseeker/ # ConsoleSeeker 模块
├── ChatAppender.java # Log4j2 Appender
├── LogToChatManager.java # 日志转聊天管理器
├── ConsoleSeekerConfig.java # 配置文件管理
├── ConsoleSeekerEventManager.java # 事件管道核心
├── ConsoleSeekerCommand.java # 命令处理器
├── InternalFilterUnit.java # 内部过滤器单元接口
├── ExternalLogFilter.java # 外部过滤器抽象类
├── DirectedDeliveryTag.java # 定向投递标签
├── LogFilter.java # 日志工具(截断/去色)
└── event/ # 事件类
├── ConsoleSeekerLogEvent.java # 基础事件类
├── ConsoleSeekerInfoEvent.java
├── ConsoleSeekerWarnEvent.java
└── ConsoleSeekerErrorEvent.java
许可证
本项目在 GNU 通用公共许可证 v3.0 下开源。完整文本请参阅 LICENSE。
CloudWorks API — 统一模组开发接口
版权所有 (C) 2026 CloudWorks Team
本程序是自由软件:您可以根据自由软件基金会发布的 GNU 通用公共许可证( either version 3 of the License, or (at your option) any later version.)的条款重新分发和/或修改它。
本程序的发布希望它能有所帮助,但不做任何保证;甚至不包括对适销性或特定用途适用性的隐含保证。有关更多细节,请参阅 GNU 通用公共许可证。
您应该已经随本程序收到了一份 GNU 通用公共许可证的副本。如果没有,请参阅 。
CloudWorks API
Unified Mod Development Interface — Provides standardized capabilities for NeoForge 1.21.1 mods, including a durable block system, recipe parsing, and console log capture.
Version: 1.1.0-1.21.1 | Platform: NeoForge 1.21.1 | Java 21
Table of Contents
- Quick Start
- DurableBlock — Durable Block System
- RecipeParser — Recipe Parsing
- ConsoleSeeker — Console Log Capture
- Debug Commands
- Module Architecture
- License
Quick Start
Adding the Dependency
Add the following to your build.gradle:
repositories {
maven { url = 'https://your-maven-repo' }
}
dependencies {
implementation 'com.cloudworks:CloudWorksAPI:1.1.0-1.21.1'
}
Optional Dependency: Jade Mod Integration
If you need Jade durability display for durable blocks, add the Jade API dependency:
repositories {
maven { url = "https://api.modrinth.com/maven" }
}
dependencies {
compileOnly "maven.modrinth:jade:15.10.5+neoforge"
}
Enabling Modules
CloudWorks API uses annotations to activate modules on demand. Add the corresponding annotation to your main mod class:
@Mod("your_mod_id")
@CloudworksRecipeParser // Enables the RecipeParser module
@CloudWorksConsoleSeeker // Enables ConsoleSeeker + API
public class YourMod {
public YourMod(IEventBus modEventBus) {
// ...
}
}
- With annotation: Forces the module to be enabled, ignoring the config file switch
- Without annotation: Controlled by the config file
- Each module can be independently enabled/disabled with no dependencies on each other
DurableBlock — Durable Block System
Core Concept
DurableBlock provides a complete durable block system that allows blocks to have durability values, damage resistance, and automatic recovery.
Unlike traditional solutions, this system does not rely on BlockEntity. Instead, it uses a LivingEntity subclass (DurableBlockEntity) to store durability data and receive damage. This design combines the data persistence of BlockEntity with the attackability of LivingEntity.
Architecture
DurableBlock (Block)
│ Spawns entity on placement
│ Properties: maxDurability, baseResistance, type-specific resistances
▼
DurableBlockEntity (LivingEntity)
│ Server-side only entity (clientTrackingRange=0)
│ Bound to block coordinates (boundPos), validates block existence every tick
│ Durability calculation, damage handling, NBT persistence
│
├── Normal flow: durability reaches zero → breaks block → self-destructs
└── PersistentDurableBlockEntity (subclass)
└── Code game protection: intercepts instant-kill attacks → 20% durability loss
Core Classes
| Class |
Responsibility |
DurableBlock |
Durable block base class, defines durability attributes and resistance parameters, manages entity spawning |
DurableBlockEntity |
Block entity replacement (LivingEntity), handles damage, durability calculation, data persistence |
PersistentDurableBlock |
Persistent durable block, extends DurableBlock, uses PersistentDurableBlockEntity |
PersistentDurableBlockEntity |
Persistent entity, intercepts instant-kill attacks, converts to durability loss |
DurableBlockDamageType |
Damage type enum (EXPLOSION / PHYSICAL / MAGIC) |
Usage
Basic Durable Block
public class MyConcreteBlock extends DurableBlock {
public MyConcreteBlock() {
super(Properties.of()
.strength(3.0f)
.requiresCorrectToolForDrops(),
200, // maxBlockDurability: Maximum durability
2, // baseResistance: Flat damage reduction
0.3f, // explosionResistance: Explosion damage reduction (0.0 ~ 1.0)
0.5f, // physicalResistance: Physical damage reduction (0.0 ~ 1.0)
0.1f, // magicResistance: Magic damage reduction (0.0 ~ 1.0)
0 // recoveryRate: Auto-recovery per second (0 = none)
);
}
}
Persistent Durable Block (with Code Game Protection)
public class MyPersistentBlock extends PersistentDurableBlock {
public MyPersistentBlock() {
super(Properties.of().strength(3.0f),
200, 2, 0.3f, 0.5f, 0.1f, 0);
}
}
Damage Calculation
actualDamage = max(0, rawDamage - baseResistance) × (1 - typeResistance)
- Base Resistance: Flat reduction from raw damage (minimum 0)
- Type Resistance: Applies the corresponding reduction ratio based on damage type (explosion/physical/magic)
- Damage Type Classification:
- Explosion: TNT, creepers, end crystals, bed/respawn anchor explosions
- Physical: Melee attacks, arrows, tridents, projectiles
- Magic: Potions, dragon breath, wither effect, void damage, fire/lightning
Server-Side Only Entity
Durable block entities are registered with clientTrackingRange(0), meaning the entity exists only on the server. The client has no knowledge of the entity's existence. This provides the following benefits:
- Players cannot melee-attack the entity: No target on the client side; the block can only be mined
- No block interaction obstruction: Does not prevent placing blocks on top or left-click mining
- Mob and ranged attacks work normally: Withers, zombies, and ranged attacks can still damage the entity on the server
- No synchronization needed: No client/server entity data synchronization issues
Code Game Protection (Persistent)
PersistentDurableBlockEntity uses a multi-layer interception mechanism to resist instant-kill attacks:
remove() Interception: Checks internalRemoval flag; external calls trigger 20% durability loss instead
setHealth() Interception: Prevents external health zeroing
setPose() Interception: Prevents Pose.DYING state
hurt() Detection: Checks instant_kill_weapon tag, cancels instant-kill weapon damage events
dead State Correction: Checks and corrects the dead field every tick
- Invulnerability Frames: 3 ticks of invulnerability after each hit, limiting hits to 5 per second
Instant-Kill Weapon Tag
The cloudworks_api:instant_kill_weapon item tag marks instant-kill weapons. When an entity holding a tagged item attacks, PersistentDurableBlockEntity will cancel the damage event directly.
Default contents:
{
"values": [
"avaritia:infinity_sword"
]
}
Modpack authors can add more weapons to this tag via datapack.
Lifecycle Management
- Block Placement:
DurableBlock.setPlacedBy() spawns the entity at the block position
- Block Breaking: The entity is no longer removed by block break events; it manages its own lifecycle
- Tick Validation: The entity checks every tick whether its bound block still exists; if not, self-destructs
- Durability Depletion:
onDurabilityZero() breaks the block and removes the entity
- NBT Persistence: Durability data is saved to chunks via
addAdditionalSaveData / readAdditionalSaveData
Bound Position Mechanism
Each entity stores its bound block position in boundPos. When the entity is about to disappear for any reason, it destroys the block at that position. Simultaneously, it checks every tick whether the block at that position still exists and matches the expected type; if not, it removes itself. This design prevents the bug where an entity's collision box extending into adjacent block areas would incorrectly delete other entities.
Jade Mod Integration
DurableBlock includes built-in Jade integration (DurableBlockJadePlugin) that displays block durability information in Jade tooltips:
- Displays
Durability: current / max on the line below the block name
- Current durability shows 2 decimal places
- Since the entity uses the server-side only approach, durability data is collected server-side via
IServerDataProvider and synced to the client via Jade's data packets
Collision Box Design
The entity collision box is 1.02×1.02 (slightly larger than a 1×1 block), centered at the block center (y+0.5), extending 0.01 blocks on all six sides. This allows mobs to attack the entity from any side while the entity does not obstruct block placement or movement.
RecipeParser — Recipe Parsing
Core Concepts
Recipe parsing flow:
Recipe JSON --> serializeRecipe() --> JsonElement
|
v
DSL Template (.rpml) --> TemplateParser --> TemplateNode (AST)
|
v
RecipeExtractor.extract()
|
v
RecipeData
(Ingredient[], Product[])
- Serialize: Serialize the recipe to JSON via the Minecraft Codec
- Template Parse: Parse the
.rpml DSL template into an AST
- Data Extract: Extract structured data from JSON according to the AST
Core Classes
| Class |
Responsibility |
RecipeParser |
Singleton core, manages template loading, recipe parsing, and fluid transfer |
RecipeParserAPI |
Static facade class, exposes all APIs externally |
RecipeData |
Parse result, contains inputs and outputs |
Ingredient |
Input material: id, count, unit, type |
Product |
Output product: id, count, unit, type, rate (probability) |
API Reference
All APIs are called via RecipeParserAPI static methods.
Basic Queries
| Method |
Description |
getRecipeData(ResourceLocation, RecipeManager) |
Parse a single recipe |
getRecipeDataBatch(Collection, RecipeManager) |
Batch parse recipes |
isRecipeParsable(ResourceLocation, RecipeManager) |
Check if a recipe is parsable |
getParsableRecipes(String modId, String recipeType, RecipeManager) |
Get all parsable recipes of a given type |
Advanced Queries
// Find recipes that produce the target
List<RecipeParseResult> parseProduceRecipe(
ResourceLocation targetId, // Target item/fluid ID
QueryMode mode, // ITEM or FLUID
RecipeManager recipeManager
)
// Find recipes that use the target as input
List<RecipeParseResult> parseUsageRecipe(
ResourceLocation targetId,
QueryMode mode,
RecipeManager recipeManager
)
| mode |
Match Logic (produce) |
Match Logic (usage) |
ITEM |
Matches direct output + fluid-to-item transfer |
Matches ingredients where unit=item |
FLUID |
Matches fluid outputs + reverse transfer matches |
Matches ingredients where unit=fluid |
Async API Methods
All async APIs are called via RecipeParserAPI static methods. Heavy recipe scanning and parsing work runs on dedicated worker threads (AsyncRecipeParser thread pool, 2 daemon threads), and results are delivered back to the server thread via MinecraftServer callback.
RecipeParserAPI.parseProduceRecipeAsync(
ResourceLocation.parse("minecraft:oak_planks"),
QueryMode.ITEM,
recipeManager,
results -> {
// This callback runs on the server thread -- safe to manipulate Minecraft objects
for (RecipeParseResult r : results) {
sendSuccess("Found recipe: " + r.getRecipeId());
}
},
errorMsg -> sendFailure("Query failed: " + errorMsg),
server
);
Async method signatures:
| Method |
Description |
getRecipeDataAsync(id, mgr, cb, err, server) |
Asynchronously parse a single recipe |
getRecipeDataBatchAsync(ids, mgr, cb, err, server) |
Asynchronously batch parse recipes |
parseProduceRecipeAsync(id, mode, mgr, cb, err, server) |
Asynchronously find producing recipes |
parseUsageRecipeAsync(id, mode, mgr, cb, err, server) |
Asynchronously find usage recipes |
Data Models
Ingredient
| Field |
Type |
Description |
id |
String |
Item/fluid/tag ID |
count |
double |
Quantity |
unit |
String |
"item" / "fluid" |
type |
String |
"solid" / "tag" / "fluid" |
Product
| Field |
Type |
Description |
id |
String |
Product ID |
count |
double |
Quantity |
unit |
String |
"item" / "fluid" |
type |
String |
"solid" / "tag" / "fluid" |
rate |
double |
Output probability (0.0 ~ 1.0, default 1.0) |
DSL Recipe Templates
Recipe templates (.rpml files) are located in cloudworks/recipe_parser/templates/, named in the format {modid}_{recipetype}.rpml.
Marker Types
| Marker |
Syntax |
Description |
input |
<input,id=foo,count=1,unit=item,type=solid> |
Declares an input ingredient |
output |
<output,id=bar,count=1,unit=item,type=solid> |
Declares an output product |
object |
<object,id=myObj> |
Declares a JSON object node |
key |
<key,id=myKey> |
Dynamic JSON key traversal |
io_attribute |
<count,output_id=bar> |
Injects attributes into markers |
symbol |
<symbol,id=sym,input_id=keyIng> |
Declares a shaped crafting symbol |
patternline |
<patternline,id=line> |
Declares a shaped crafting pattern row |
duplicate |
<duplicate,id=dupX,structure=X> |
Declares a repeatable JSON object structure |
script |
<script,set_global_fluid_transfer=true> |
Global settings script |
optional |
<optional,id=opt> |
Optional field |
variable |
<variable,id=var> |
Variable reference |
Template Examples
Vanilla Crafting Table (Shaped)
{
"type": "minecraft:crafting_shaped",
<script,set_global_fluid_transfer=true,set_global_default_transfer_rate=250>
"pattern": [
<patternline,id=line>
],
"key": <object,id=keyObj>
<key,id=key>
<object,id=keyIng>
"item": <input,id=keyIng,count=1,unit=item,type=solid>
"tag": <input,id=keyIng,count=1,unit=item,type=tag>
<symbol,id=sym,input_id=keyIng>
<count,id=keyIng_count,input_id=keyIng>
<patternline,id=line,input_id=sym>
"result": <object,id=res>
"count": <count,output_id=res>
"id": <type,output_id=res>
"item": <output,id=res,count=1,unit=item,type=solid>
Vanilla Crafting Table (Shapeless)
{
"type": "minecraft:crafting_shapeless",
"ingredients": [
<object,id=ingStruct>
"item": <input,id=ingItem,count=1,unit=item,type=solid>
"tag": <input,id=ingItem,count=1,unit=item,type=tag>
<count,id=ingCount,input_id=ingItem>
<duplicate,id=ingStruct>
],
"result": <object,id=res>
"count": <count,output_id=res>
"id": <type,output_id=res>
"item": <output,id=res,count=1,unit=item,type=solid>
Fluid-to-Item Transfer
When a recipe outputs fluid, it can be converted to an equivalent item, allowing the recipe to be found via item ID as well.
Transfer Logic: Total fluid (mB) ÷ rate → rounded (per round strategy) × per-unit product quantity
Global Settings (configured via <script> in templates):
| Parameter |
Type |
Default |
Description |
global_fluid_transfer |
boolean |
false |
Whether to enable fluid-to-item transfer |
global_default_transfer_rate |
double |
100 |
How many mB convert to 1 item |
global_default_transfer_result |
string |
null |
Default transfer result item ID |
global_default_transfer_extra_input |
map |
{} |
Extra ingredients |
global_default_transfer_float_round |
enum |
default |
round_up / round_down / default |
global_enable_template_config |
boolean |
true |
Whether to enable external template config files |
Recipe-Level Config (cloudworks/recipe_parser/templates_config/{modid}_{recipetype}.json):
{
"recipe:id": {
"enable_transfer": true,
"transfer_blacklist": ["fluid:to_skip"],
"methods": [{
"rate": 100,
"round": "default",
"extra_input": {"minecraft:item": 1},
"result": {"minecraft:output_item": 2}
}]
}
}
Template Update Mechanism
cloudworks/recipe_parser/config.json:
{
"version": "1.1.0-1.21.1",
"enable_update": true,
"force_update": false,
"update_ignore": ["minecraft_crafting.rpml"]
}
force_update=true → Skip all checks, release all files
enable_update=false → Skip update
version matches → Skip update
- Otherwise → Update version, release files excluding those in
update_ignore
ConsoleSeeker — Console Log Capture
ConsoleSeeker outputs console logs to the in-game chat in real-time and provides a complete event pipeline for downstream mods to filter and process logs.
Enabling
@CloudWorksConsoleSeeker // Forces ConsoleSeeker + API to be enabled
Or configure in cloudworks/console_seeker/config.json:
{
"enable_module": true,
"enable_api": false,
"enable_command_for_any_operator": true,
"list_type": "whitelist",
"player_list": [],
"max_log_length": 150,
"enable_timestamp": false
}
| Field |
Type |
Default |
Description |
enable_module |
boolean |
true |
Whether to enable the ConsoleSeeker module |
enable_api |
boolean |
false |
Whether to enable the event API (annotations override this) |
enable_command_for_any_operator |
boolean |
true |
Whether to allow all OPs to use commands |
list_type |
string |
"whitelist" |
"whitelist" / "blacklist" |
player_list |
string[] |
[] |
Player name list |
max_log_length |
int |
150 |
Maximum log length (0 = no truncation) |
enable_timestamp |
boolean |
false |
Whether to show timestamps |
Architecture
Log4j2 Logger
│
▼
ChatAppender (Log4j2 Appender)
│ Filters [CHAT] substring
▼
LogToChatManager
│ Filters by log level and player subscription
▼
ConsoleSeekerEventManager
│ Internal filter units → collects tagSet
▼
NeoForge EVENT_BUS
│ Dispatches ConsoleSeekerInfoEvent / WarnEvent / ErrorEvent
▼
ExternalLogFilter (subscribed by downstream mods)
│ Matches tagSet → parse() → onReceive()
▼
Downstream mod custom logic
Event Pipeline
Three independent event pipelines for different log levels:
| Event Class |
Log Level |
ConsoleSeekerInfoEvent |
INFO |
ConsoleSeekerWarnEvent |
WARN |
ConsoleSeekerErrorEvent |
ERROR |
All events inherit from ConsoleSeekerLogEvent with the following fields:
| Field |
Type |
Description |
loggerName |
String |
Logger name |
level |
Level |
Log level |
message |
String |
Formatted message (ANSI color codes removed) |
timestamp |
long |
Unix timestamp (milliseconds) |
threadName |
String |
Thread name |
thrownString |
String |
Exception stack trace (null if no exception) |
tagSet |
Set<DirectedDeliveryTag> |
Directed delivery tag set |
Internal Filters (Active Filtering)
Register internal filter units via ConsoleSeekerEventManager to have ConsoleSeeker actively filter logs:
// Implement the InternalFilterUnit interface
InternalFilterUnit myUnit = new InternalFilterUnit() {
public DirectedDeliveryTag getTag() {
return new DirectedDeliveryTag("mymod", "cpu_alert");
}
public boolean test(LogEvent event) {
return event.getLoggerName().startsWith("com.example");
}
};
// Register to the internal filter unit list
ConsoleSeekerEventManager.addInternalFilterUnit(myUnit);
Filter Rules:
- Empty list → All log events are published directly, tagSet is empty
- Non-empty list → At least one unit must pass to publish; collects tags from passing units into tagSet
- All units fail → Event is discarded
Directed Delivery Tags
Uses the "modid:tagName" format to prevent cross-mod conflicts:
// Create a tag
DirectedDeliveryTag tag = new DirectedDeliveryTag("mymod", "cpu_alert");
// Matching rules: empty tag matches everything, non-empty tag requires exact match
tag.matches(otherTag);
External Filters (Passive Filtering)
Downstream mods extend ExternalLogFilter<T> for custom log parsing:
public class MyCpuFilter extends ExternalLogFilter<Integer> {
public MyCpuFilter() {
super(new DirectedDeliveryTag("mymod", "cpu_alert"));
}
@Override
protected Integer parse(ConsoleSeekerLogEvent event) {
// Custom parsing logic
return Integer.parseInt(event.getMessage());
}
@Override
protected void onReceive(Integer value) {
// Handle the parsed result
System.out.println("CPU usage: " + value);
}
}
// Register to start receiving events
MyCpuFilter filter = new MyCpuFilter();
filter.register();
Workflow:
- Match the event's
tagSet against the filter's tag (intersection matches, empty tag set matches everything)
parse() converts the raw event to a custom type (returns the raw log string by default)
onReceive() processes the parsed result
Debug Commands
Command prefix: /cloudworks. Requires OP level 4 (some commands).
Recipe Module
/cloudworks recipe parse produce item [id] — Query recipes producing the specified item
/cloudworks recipe parse produce liquid [id] — Query recipes producing the specified fluid
/cloudworks recipe parse usage item [id] — Query recipes using the specified item
/cloudworks recipe parse usage liquid [id] — Query recipes using the specified fluid
/cloudworks recipe parsebatch <modid> <type> — Batch parse
/cloudworks recipe listtemplates — List loaded templates
Console Module
/cloudworks console <info|warn|error> <on|off> — Toggle log output to chat
/cloudworks config console player_list add <player_name> — Add player to list
/cloudworks config console player_list remove <player_name> — Remove player from list
/cloudworks config console player_list query — View player list
Status Query
/cloudworks status — View all module status
Output includes: RecipeParser template count, ConsoleSeeker enabled levels/API status/filter unit count.
Module Architecture
src/main/java/com/cloudworks/api/
├── CloudWorksAPI.java # NeoForge mod entry point
├── annotation/
│ ├── CloudworksRecipeParser.java # Enables RecipeParser
│ └── CloudWorksConsoleSeeker.java # Enables ConsoleSeeker
├── command/
│ └── DebugCommand.java # Unified debug command entry
│
├── durableblock/ # DurableBlock module
│ ├── DurableBlock.java # Durable block base class
│ ├── DurableBlockEntity.java # Block entity replacement (LivingEntity)
│ ├── PersistentDurableBlock.java # Persistent durable block
│ ├── PersistentDurableBlockEntity.java # Code game protection entity
│ ├── DurableBlockDamageType.java # Damage type enum
│ └── jade/
│ └── DurableBlockJadePlugin.java # Jade mod integration plugin
│
├── recipeparser/ # RecipeParser module
│ ├── RecipeParser.java # Core singleton
│ ├── RecipeParserAPI.java # Static API facade
│ ├── AsyncRecipeParser.java # Async thread pool
│ ├── ApiSelfTest.java # Auto-test
│ ├── DebugOutputWriter.java # Debug JSON export
│ ├── dsl/ # DSL template engine
│ │ ├── Template.java, TemplateNode.java
│ │ ├── TemplateParser.java, TemplateTokenizer.java
│ │ ├── TemplateValidator.java, RecipeExtractor.java
│ │ ├── GlobalSettings.java, TemplateConfig.java
│ │ └── ...
│ └── model/ # Data models
│ ├── RecipeData.java, Ingredient.java, Product.java
│ └── QueryMode.java, RecipeParseResult.java
│
└── consoleseeker/ # ConsoleSeeker module
├── ChatAppender.java # Log4j2 Appender
├── LogToChatManager.java # Log-to-chat manager
├── ConsoleSeekerConfig.java # Config file management
├── ConsoleSeekerEventManager.java # Event pipeline core
├── ConsoleSeekerCommand.java # Command handler
├── InternalFilterUnit.java # Internal filter unit interface
├── ExternalLogFilter.java # External filter abstract class
├── DirectedDeliveryTag.java # Directed delivery tag
├── LogFilter.java # Log utility (truncation/color removal)
└── event/ # Event classes
├── ConsoleSeekerLogEvent.java # Base event class
├── ConsoleSeekerInfoEvent.java
├── ConsoleSeekerWarnEvent.java
└── ConsoleSeekerErrorEvent.java
License
This project is open-sourced under the GNU General Public License v3.0. See LICENSE for the full text.
CloudWorks API — Unified Mod Development Interface
Copyright (C) 2026 CloudWorks Team
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see .
评论 0
登录后参与评分
还没有评论,来抢沙发吧