一款面向开发者与数据包制作者的模组。从 JSON 文件中读取自定义公式,并通过游戏内命令传入的参数对其进行求值:
/formula <namespace:name> <参数...>
或 Java 方法。
支持的操作
算术运算符: +、-、*、/、%(向下取整余数:a - floor(a / b) * b)
双参数公式: min(x, y)、max(x, y)、pow(x, y)、log(x, y)(以 x 为底 y 的对数)、div(x, y)(向负无穷取整的除法)
单参数公式: round(x)、floor(x)、ceil(x)、abs(x)、exp(x)、trunc(x)(向零取整)
三角函数公式: sin(x)、cos(x)、tan(x)、asin(x)、acos(x)、atan(x)
特殊函数 — rem(x, y): 返回余数 x - floor(x / y) * y,并同时将商 floor(x / y) 写回至 x。请注意,如果你编写 #a = rem(#a, #b),赋值语句 #a = ... 会用返回值(即余数)覆盖 rem 刚刚存入 #a 的商,因此最终 #a 中保存的是余数而非商。
支持无需括号的负号:-3、-x、-min(a, b)、1 + -x 均可正常工作。
性能
公式在加载时会被预编译为经过优化的基于栈的字节码虚拟机。简短的公式(包含 4 个或更少的运算)可从循环展开和超级指令合并中受益(例如,变量-变量二元运算会变成单个操作码)。常量折叠会在编译时应用。在典型桌面 JVM 上的基准测试结果如下:
- 简单算术运算:每次评估约 9 纳秒
- 链式条件判断(3 个分支):每次评估约 15 纳秒
- 连续步骤(3 步):每次评估约 14 纳秒
- 带舍入的三角函数:每次评估约 40 纳秒
在实际使用中,即使进行 300 万次调用也只需不到 120 毫秒。性能无需担心。
客户端安装
本模组在客户端是可选的。如果你只需要服务器端计算,则无需在客户端安装。如果你需要在 UI 元素中显示数值,请在客户端安装以本地提供公式。当另一个需要双方支持(例如 Tinkers' Armor Extension)且与本模组深度集成的模组出现时,本模组将成为传递依赖项,因此也必须安装在客户端上。
面向开发者
- 通过
FormulaManager.getOrNull(ResourceLocation) 访问已加载的公式,并使用 formula.accept(double...) 进行评估。
- 使用
FormulaBuilder 以编程方式构建公式 JSON。公式会在启动时从 data/<namespace>/formula/ 加载。
面向数据包创作者
使用 /formula 命令在游戏内评估带有参数的公式。这取代了原本需要数十条指令才能完成的计分板计算,只需一次调用即可实现,显著提升了数据包的运行性能与可读性。
JSON 格式参考
简单公式
{
"inputs": ["result", "left", "right"],
"formula": "#result = #left + #right * 2"
}
顺序步骤 (Sequential Steps)
{
"inputs": ["a", "b", "c"],
"formula": [
"#a = #b + #c",
"#b = #a * #c",
"#a = #b + 1"
]
}
条件分支 (If/Else Branching)
{
"inputs": ["score", "kills", "deaths"],
"formula": {
"if": "#kills > #deaths",
"formula": "#score = #kills * 3 - #deaths * 2",
"else": "#score = max(0, #kills - #deaths)"
}
}
条件链 (Conditional Chain: if / else-if / else)
{
"inputs": ["result", "value"],
"formula": {
"chain": [
{"condition": "#value >= 100", "formula": "#result = #value * 2"},
{"condition": "#value >= 50", "formula": "#result = #value * 1.5"},
{"condition": "#value >= 10", "formula": "#result = #value"}
],
"default": "#result = 0"
}
}
混合嵌套 (Mixed Nesting: 顺序 + 条件)
{
"inputs": ["result", "base", "modifier"],
"caches": ["scaled"],
"formula": [
"#scaled = log(2, #base + 1)",
{
"chain": [
{"condition": "#modifier > 10", "formula": "#result = #scaled * #modifier * 2"},
{"condition": "#modifier > 0", "formula": "#result = #scaled * #modifier"}
],
"default": "#result = #scaled"
}
]
}
显式输出槽位 (Explicit Output Slot)
默认情况下,最后一步的结果将被返回。使用 "output" 可指定不同的变量:
{
"inputs": ["dummy", "x", "y"],
"caches": ["tmp", "extra"],
"output": "#extra",
"formula": [
"#tmp = #x * #y",
"#dummy = #tmp + #x",
"#extra = #tmp * 2 + #y"
]
}
数值模式 (Numeric Mode: 缩写形式)
{
"input": 3,
"cache": 2,
"output": "#4",
"formula": [
"#0 = #1 + #2",
"#3 = #0 * #1",
"#4 = #3 + #2"
]
}
FormulaBuilder — 开发者指南
FormulaBuilder 是一个用于在 Java 中生成公式 JSON 的流畅 API(Fluent API)。它会自动为命名变量添加 # 前缀。
I. 快速入门
// 命名变量 — 自动添加 # 前缀。"result = x + y" 变为 "#result = #x + #y"
String json = FormulaBuilder
.inputs("result", "x", "y")
.flat("result = x + y + 2")
.build();
// 数值模式 — 手动编写 #
String json = FormulaBuilder
.input(3)
.flat("#0 = #1 + #2 + 2")
.build();
II. 定义输入 (Inputs)
// 命名输入(推荐)— 自动添加 # 前缀
FormulaBuilder.inputs("result", "amount", "tick")
// 数值输入 — 需手动编写 #0、#1、#2
FormulaBuilder.input(3)
III. 定义缓存 (Caches: 中间变量)
// 命名缓存 — 自动添加 # 前缀
.caches("tmp1", "tmp2") // 生成 "caches": ["tmp1","tmp2"]
// 数值缓存 — 需手动编写 #3、#4
.cache(2) // 生成 "cache": 2
IV. 输出字段 (Output Field)
.output("#result") // 指定要返回的变量
// 如果省略,则返回最后一步的结果。
V. 公式形状
flat — 单个公式字符串。返回 FormulaBuilder。
.flat("result = x + y + 2")
array — 顺序步骤。每个步骤可以读取之前步骤的结果。返回 FormulaBuilder。
.array(
"a = b + c",
"b = a * 2"
)
ifelse — 单个 if/else 简写形式。返回 FormulaBuilder。
.ifelse(
"kills > deaths", // 条件
"score = kills * 3", // 为真分支
"score = deaths" // 否则分支
)
mixed() — 进入 MixedBlock<P>。条目按顺序执行,可以包含扁平公式、内联条件和嵌套块。调用 .exit() 返回到父上下文(即 P 类型参数)。
b.inputs("a", "b").mixed()
.flat("a = b + 1") // 普通公式
.cond("b > 10", "a = b * 2") // 内联条件快捷方式
.exit() // 返回 FormulaBuilder
.build();
在 MixedBlock 内部,以下方法可用:
.flat(String) — 单个公式
.array(String...) — 顺序公式
.cond(String condition, String formula) — 内联条件快捷方式
.cond(String condition) — 进入 CondBlock<MixedBlock<P>> 以处理复杂主体
.ifelse(String cond, String ifTrue, String ifFalse) — if/else 简写
.chain() — 进入 ChainBlock<MixedBlock<P>>
.mixed() — 进入嵌套的 MixedBlock<MixedBlock<P>>
cond(String) — 进入 CondBlock<P>,表示单个 {"condition":..., "formula":...} 条目。支持 .flat()、.array()、.mixed()。.exit() 返回到父级。
b.inputs("a", "b").mixed()
.cond("b > 10").mixed() // 通过嵌套 mixed 处理复杂主体
.flat("a = b * 2")
.flat("a = a + 1")
.exit() // 退出嵌套 mixed
.exit() // 退出 CondBlock,回到 MixedBlock
.exit()
.build();
chain() — 进入 ChainBlock<P>。条件从上到下测试;第一个匹配项执行。如果没有匹配项,则执行 def 分支。.exit() 返回到父级。
b.inputs("result", "value").chain()
.cond("value >= 100", "result = value * 2") // 内联: cond(c, f)
.cond("value >= 50").mixed() // 具有复杂主体的 CondBlock
.flat("result = value * 1.5")
.exit()
.def("result = 0") // 默认分支
.exit()
.build();
在 ChainBlock 内部,以下方法可用:
.cond(String condition, String formula) — 内联条件快捷方式
.cond(String condition) — 进入 CondBlock<ChainBlock<P>>
.def(String formula) — 作为默认的单个公式
.defArray(String... formulas) — 作为默认的顺序公式
.defMixed() — 作为默认进入 MixedBlock<ChainBlock<P>>
VI. 嵌套块摘要
| 入口点 |
返回 |
可用方法 |
Exit 返回 |
.mixed() |
MixedBlock<P> |
.flat() .array() .cond() .ifelse() .chain() .mixed() |
P |
.cond(String) |
CondBlock<P> |
.flat() .array() .mixed() |
P |
.chain() |
ChainBlock<P> |
.cond() .def() .defArray() .defMixed() |
P |
参数化 P 类型在编译时跟踪父上下文 —— .exit() 始终返回正确的父类型,无需强制转换。
VII. 构建输出
.build() // 返回 String — 格式化 JSON,用于写入文件
.buildFormula() // 返回 JsonFormula — 用于代码中的直接求值
VIII. 自动 # 前缀规则
声明 inputs("result","x","y") 后,这些字符串会自动处理:
| 输入 |
输出 |
"result = x + y" |
"#result = #x + #y" |
"max(0, min(1, x))" |
"max(0, min(1, #x))" |
"x >= 10" (条件) |
"#x >= 10" |
当已存在时,不会再次添加 # 前缀:"#result = #x + #y" 保持不变,数字引用如 "#0 = #1 + #2" 也不受影响。
重要提示: 不要将变量命名为公式名称(避免使用 min、max、pow、log 等作为变量标识符)。
IX. JSON 格式对应关系
| 构建器方法 |
生成的 JSON |
.flat("x") |
"formula": "..." |
.array("a","b") |
"formula": ["...", "..."] |
.chain() ... .exit() |
"formula": {"chain": [...], "default": ...} |
.ifelse(c,a,b) |
"formula": {"if": "...", "formula": ..., "else": ...} |
.output("x") |
"output": "#x" |
.inputs("a","b") |
"inputs": ["a", "b"] |
.input(3) |
"input": 3 |
.caches("a","b") |
"caches": ["a", "b"] |
.cache(2) |
"cache": 2 |
X. 典型用例
// 基本算术运算
FormulaBuilder.inputs("r", "a", "b")
.flat("r = a + b * 2")
.build();
// 带有缓存的顺序计算
FormulaBuilder.inputs("r", "base", "mod")
.caches("logval")
.array(
"logval = log(2, base + 1)",
"r = logval * mod"
)
.build();
// 多条件链
FormulaBuilder.inputs("result", "val").chain()
.cond("val >= 100", "result = val * 2")
.cond("val >= 50", "result = val")
.def("result = 0")
.exit().build();
// If/else 简写
FormulaBuilder.inputs("score", "kills", "deaths")
.ifelse(
"kills > deaths",
"score = kills * 3 - deaths * 2",
"score = max(0, kills - deaths)"
)
.build();
// 数字模式(无命名变量)
FormulaBuilder.input(3).cache(1).output("#3")
.array(
"#0 = #1 + #2",
"#3 = #0 * 2 + #1"
)
.build();
// 带有条件和链的混合块
FormulaBuilder.inputs("a", "b", "c").mixed()
.flat("a = b + c")
.cond("b > 10", "a = a * 2")
.chain()
.cond("a > 100", "a = 100")
.def("a = a")
.exit()
.exit().build();
A mod for developers and datapack creators. Reads custom formulas from JSON files and evaluates them with parameters passed via the in-game command:
/formula <namespace:name> <parameters...>
or Java method.
Supported Operations
Arithmetic operators: +, -, *, /, % (floor remainder: a - floor(a / b) * b)
Two-argument formulas: min(x, y), max(x, y), pow(x, y), log(x, y) (logarithm base x of y), div(x, y) (floor division toward negative infinity)
One-argument formulas: round(x), floor(x), ceil(x), abs(x), exp(x), trunc(x) (truncation toward zero)
Trigonometric formulas: sin(x), cos(x), tan(x), asin(x), acos(x), atan(x)
Special — rem(x, y): Returns the remainder x - floor(x / y) * y and simultaneously writes the quotient floor(x / y) back into x. Note that if you write #a = rem(#a, #b), the assignment #a = ... will overwrite the quotient that rem just stored into #a with the return value (the remainder), so #a ends up holding the remainder, not the quotient.
Unary minus is supported without requiring parentheses: -3, -x, -min(a, b), 1 + -x all work.
Performance
Formulas are pre-compiled at load time into an optimized stack-based bytecode VM. Short formulas (4 or fewer operations) benefit from loop unrolling and super-instruction merging (e.g., variable-variable binary operations become single opcodes). Constant folding is applied at compile time. Benchmarks on a typical desktop JVM:
- Simple arithmetic: ~9 ns per evaluation
- Chained conditionals (3 branches): ~15 ns per evaluation
- Sequential steps (3 steps): ~14 ns per evaluation
- Trigonometric with rounding: ~40 ns per evaluation
In practice, even 3 million calls complete in under 120 ms. Performance is not a concern.
Client-Side Installation
This mod is optional on the client. If you only need server-side computation, client installation is unnecessary. If you need to display values in UI elements, install on the client to provide the formulas locally. When another mod that requires both sides (e.g. Tinkers' Armor Extension) deeply integrates this mod, this mod becomes a transitive dependency and must be installed on the client as well.
For Developers
- Access loaded formulas via
FormulaManager.getOrNull(ResourceLocation) and evaluate with formula.accept(double...).
- Use
FormulaBuilder to programmatically construct formula JSON. Formulas are loaded from data/<namespace>/formula/ at startup.
For Data Pack Creators
Use the /formula command to evaluate formulas with parameters in-game. This replaces scoreboard-based computations that would require dozens of commands with a single call, significantly improving datapack performance and readability.
JSON Format Reference
Simple Formula
{
"inputs": ["result", "left", "right"],
"formula": "#result = #left + #right * 2"
}
Sequential Steps
{
"inputs": ["a", "b", "c"],
"formula": [
"#a = #b + #c",
"#b = #a * #c",
"#a = #b + 1"
]
}
If/Else Branching
{
"inputs": ["score", "kills", "deaths"],
"formula": {
"if": "#kills > #deaths",
"formula": "#score = #kills * 3 - #deaths * 2",
"else": "#score = max(0, #kills - #deaths)"
}
}
Conditional Chain (if / else-if / else)
{
"inputs": ["result", "value"],
"formula": {
"chain": [
{"condition": "#value >= 100", "formula": "#result = #value * 2"},
{"condition": "#value >= 50", "formula": "#result = #value * 1.5"},
{"condition": "#value >= 10", "formula": "#result = #value"}
],
"default": "#result = 0"
}
}
Mixed Nesting (Sequential + Conditional)
{
"inputs": ["result", "base", "modifier"],
"caches": ["scaled"],
"formula": [
"#scaled = log(2, #base + 1)",
{
"chain": [
{"condition": "#modifier > 10", "formula": "#result = #scaled * #modifier * 2"},
{"condition": "#modifier > 0", "formula": "#result = #scaled * #modifier"}
],
"default": "#result = #scaled"
}
]
}
Explicit Output Slot
By default the result of the last step is returned. Use "output" to specify a different variable:
{
"inputs": ["dummy", "x", "y"],
"caches": ["tmp", "extra"],
"output": "#extra",
"formula": [
"#tmp = #x * #y",
"#dummy = #tmp + #x",
"#extra = #tmp * 2 + #y"
]
}
Numeric Mode (Abbreviated)
{
"input": 3,
"cache": 2,
"output": "#4",
"formula": [
"#0 = #1 + #2",
"#3 = #0 * #1",
"#4 = #3 + #2"
]
}
FormulaBuilder — Developer Guide
FormulaBuilder is a fluent API for generating formula JSON in Java. It automatically adds the # prefix to named variables.
I. Quick Start
// Named variables — automatic # prefix. "result = x + y" becomes "#result = #x + #y"
String json = FormulaBuilder
.inputs("result", "x", "y")
.flat("result = x + y + 2")
.build();
// Numeric mode — write # manually
String json = FormulaBuilder
.input(3)
.flat("#0 = #1 + #2 + 2")
.build();
II. Defining Inputs
// Named inputs (recommended) — automatic # prefix
FormulaBuilder.inputs("result", "amount", "tick")
// Numeric input — generates "input": 3; write #0, #1, #2 manually
FormulaBuilder.input(3)
III. Defining Caches (Intermediate Variables)
// Named caches — automatic # prefix
.caches("tmp1", "tmp2") // generates "caches": ["tmp1","tmp2"]
// Numeric caches — write #3, #4 manually
.cache(2) // generates "cache": 2
IV. Output Field
.output("#result") // specify which variable to return
// If omitted, the last step's result is returned.
V. Formula Shapes
flat — Single formula string. Returns FormulaBuilder.
.flat("result = x + y + 2")
array — Sequential steps. Each step can read results of previous steps. Returns FormulaBuilder.
.array(
"a = b + c",
"b = a * 2"
)
ifelse — Single if/else shorthand. Returns FormulaBuilder.
.ifelse(
"kills > deaths", // condition
"score = kills * 3", // if-true branch
"score = deaths" // else branch
)
mixed() — Enters a MixedBlock<P>. Entries execute sequentially and can include flat formulas, inline conditions, and nested blocks. Call .exit() to return to the parent context (the P type parameter).
b.inputs("a", "b").mixed()
.flat("a = b + 1") // plain formula
.cond("b > 10", "a = b * 2") // inline condition shortcut
.exit() // return to FormulaBuilder
.build();
Inside a MixedBlock, the following methods are available:
.flat(String) — single formula
.array(String...) — sequential formulas
.cond(String condition, String formula) — inline condition shortcut
.cond(String condition) — enters a CondBlock<MixedBlock<P>> for a complex body
.ifelse(String cond, String ifTrue, String ifFalse) — if/else shorthand
.chain() — enters a ChainBlock<MixedBlock<P>>
.mixed() — enters a nested MixedBlock<MixedBlock<P>>
cond(String) — Enters a CondBlock<P> representing a single {"condition":..., "formula":...} entry. Supports .flat(), .array(), .mixed(). .exit() returns to the parent.
b.inputs("a", "b").mixed()
.cond("b > 10").mixed() // complex body via nested mixed
.flat("a = b * 2")
.flat("a = a + 1")
.exit() // exit nested mixed
.exit() // exit CondBlock, back to MixedBlock
.exit()
.build();
chain() — Enters a ChainBlock<P>. Conditions are tested top-to-bottom; the first match executes. If none match, the def branch executes. .exit() returns to the parent.
b.inputs("result", "value").chain()
.cond("value >= 100", "result = value * 2") // inline: cond(c, f)
.cond("value >= 50").mixed() // CondBlock with complex body
.flat("result = value * 1.5")
.exit()
.def("result = 0") // default branch
.exit()
.build();
Inside a ChainBlock, the following methods are available:
.cond(String condition, String formula) — inline condition shortcut
.cond(String condition) — enters a CondBlock<ChainBlock<P>>
.def(String formula) — single formula as default
.defArray(String... formulas) — sequential formulas as default
.defMixed() — enters a MixedBlock<ChainBlock<P>> as default
VI. Nested Block Summary
| Entry Point |
Returns |
Available Methods |
Exit Returns |
.mixed() |
MixedBlock<P> |
.flat() .array() .cond() .ifelse() .chain() .mixed() |
P |
.cond(String) |
CondBlock<P> |
.flat() .array() .mixed() |
P |
.chain() |
ChainBlock<P> |
.cond() .def() .defArray() .defMixed() |
P |
The parameterized P type tracks the parent context at compile time — .exit() always returns the correct parent type without casting.
VII. Building Output
.build() // Returns String — formatted JSON, for writing to files
.buildFormula() // Returns JsonFormula — for direct evaluation in code
VIII. Automatic # Prefix Rules
After declaring inputs("result","x","y"), these strings are processed automatically:
| Input |
Output |
"result = x + y" |
"#result = #x + #y" |
"max(0, min(1, x))" |
"max(0, min(1, #x))" |
"x >= 10" (condition) |
"#x >= 10" |
The # prefix is NOT added again when already present: "#result = #x + #y" stays as-is, and numeric references like "#0 = #1 + #2" are unaffected.
Important: Do not name variables after formula names (avoid min, max, pow, log, etc. as variable identifiers).
IX. JSON Format Correspondence
| Builder Method |
Generated JSON |
.flat("x") |
"formula": "..." |
.array("a","b") |
"formula": ["...", "..."] |
.chain() ... .exit() |
"formula": {"chain": [...], "default": ...} |
.ifelse(c,a,b) |
"formula": {"if": "...", "formula": ..., "else": ...} |
.output("x") |
"output": "#x" |
.inputs("a","b") |
"inputs": ["a", "b"] |
.input(3) |
"input": 3 |
.caches("a","b") |
"caches": ["a", "b"] |
.cache(2) |
"cache": 2 |
X. Typical Use Cases
// Basic arithmetic
FormulaBuilder.inputs("r", "a", "b")
.flat("r = a + b * 2")
.build();
// Sequential computation with cache
FormulaBuilder.inputs("r", "base", "mod")
.caches("logval")
.array(
"logval = log(2, base + 1)",
"r = logval * mod"
)
.build();
// Multi-condition chain
FormulaBuilder.inputs("result", "val").chain()
.cond("val >= 100", "result = val * 2")
.cond("val >= 50", "result = val")
.def("result = 0")
.exit().build();
// If/else shorthand
FormulaBuilder.inputs("score", "kills", "deaths")
.ifelse(
"kills > deaths",
"score = kills * 3 - deaths * 2",
"score = max(0, kills - deaths)"
)
.build();
// Numeric mode (no named variables)
FormulaBuilder.input(3).cache(1).output("#3")
.array(
"#0 = #1 + #2",
"#3 = #0 * 2 + #1"
)
.build();
// Mixed block with condition and chain
FormulaBuilder.inputs("a", "b", "c").mixed()
.flat("a = b + c")
.cond("b > 10", "a = a * 2")
.chain()
.cond("a > 100", "a = 100")
.def("a = a")
.exit()
.exit().build();
评论 0
登录后参与评分
还没有评论,来抢沙发吧