自定义聊天组件
基本信息
| 属性 | 值 |
|---|---|
| 注册表 | com.gtnewhorizon.gtnhlib.chat.ChatComponentCustomRegistry |
| 基类 | com.gtnewhorizon.gtnhlib.chat.AbstractChatComponentCustom |
| 内置组件 | 5 |
| 注册位置 | CommonProxy.preInit()(CommonProxy.java:88-92) |
| 触发 mixin | Mixins.CUSTOM_CHAT_COMPONENT_REGISTRATION(EARLY,双方) |
功能
让 mod 注册自定义的 IChatComponent 子类,使其能通过 JSON 序列化在客户端与服务端之间传输。1.7.10 的 IChatComponentSerializer 只认 ChatComponentText / ChatComponentTranslation / ChatComponentScore 等固定类型。
AbstractChatComponentCustom
chat/AbstractChatComponentCustom.java,extends ChatComponentStyle,需实现 3 个抽象方法:
| 抽象方法 | 用途 |
|---|---|
serialize() |
序列化为 JsonElement |
deserialize(JsonElement) |
从 JSON 读回 |
getID() |
跨全部 mod 唯一的 id,源码注释要求 “Unique ID across all mods. Make it good!” |
copySelf() |
protected,深拷贝 |
equals / hashCode 被 final 覆写,基于 serialize() 的结果比较而非字段:
return serialize().equals(((AbstractChatComponentCustom) obj).serialize());
createCopy() 同样 final,复制 chat style 与全部 sibling。
内置 5 个组件
CommonProxy.preInit 用方法引用注册(CommonProxy.java:88-92):
| 组件类 | getID() 返回值 |
基类 |
|---|---|---|
ChatComponentNumber |
gtnhlib:ChatComponentNumber |
AbstractChatComponentNumber |
ChatComponentFluid |
gtnhlib:ChatComponentFluid |
AbstractChatComponentNumber |
ChatComponentEnergy |
gtnhlib:ChatComponentEnergy |
ChatComponentNumber |
ChatComponentFluidName |
gtnhlib:ChatComponentFluidName |
AbstractChatComponentBuffer<T> |
ChatComponentItemName |
gtnhlib:ChatComponentItemName |
AbstractChatComponentBuffer<T> |
AbstractChatComponentNumber(chat/customcomponents/AbstractChatComponentNumber.java:12)把"带 GTNHLib 数字格式化的数字"抽象出来 —— 因此这 3 个组件的数值显示受 数字格式化配置 影响。
两个 AbstractChatComponentBuffer<T> 子类用自引用泛型(AbstractChatComponentBuffer<T extends AbstractChatComponentBuffer<T>>)以便方法返回具体类型而不需要强转(AbstractChatComponentBuffer.java:20-22 注释)。
ChatComponentCustomRegistry
| 方法 | 用途 |
|---|---|
register(Supplier<? extends AbstractChatComponentCustom> factory) |
注册工厂 |
get(String id) |
按 id 取实例 |
register 接收 Supplier 而非实例,实现延迟构造。
数值
| 数值名 | 值 |
|---|---|
chat 包类数 |
9(chat/ 2 + customcomponents/ 7) |
| 内置组件数 | 5 |
| 抽象基类数 | 3(AbstractChatComponentCustom、AbstractChatComponentNumber、AbstractChatComponentBuffer) |
register 调用点 |
5(CommonProxy.java:88-92) |
| id 前缀 | 统一为 gtnhlib: |
final 覆写方法 |
3(equals、hashCode、createCopy) |
交互
下游 mod 注册自己的组件:
ChatComponentCustomRegistry.register(MyComponent::new);
id 必须全服唯一 —— 建议沿用 <modid>:<ClassName> 惯例,与 GTNHLib 内置的 5 个保持一致。
序列化/反序列化由 mixins/early/MixinIChatComponentSerializer.java 接入原版 IChatComponentSerializer。因此该 mixin 一旦被移除(它无条件注入,无配置开关),自定义组件将无法跨端传输。