diff --git a/lib/FormAPI-JS.js b/lib/FormAPI-JS.js index eeb8a69..7dfe46d 100644 --- a/lib/FormAPI-JS.js +++ b/lib/FormAPI-JS.js @@ -1,4 +1,4 @@ -const getNextCallbackId = ll.import("GMLIB_FormAPI", "getNextFormCallbackId"); +// const getNextCallbackId = ll.import("GMLIB_FormAPI", "getNextFormCallbackId"); class ServerSettingForm { constructor() { diff --git a/lib/GMLIB_API-JS.d.ts b/lib/GMLIB_API-JS.d.ts index 4d6982e..eece4f8 100644 --- a/lib/GMLIB_API-JS.d.ts +++ b/lib/GMLIB_API-JS.d.ts @@ -1054,6 +1054,289 @@ declare class UserCache { static getAllPlayerInfo(): { Xuid: String; Uuid: string; Name: string; }[] } +type PacketDataItem = ( + { + id: number, + type: 0x0 | 0x1 | 0x2 | 0x3 | 0x7, + value: number + } + | { + id: number, + type: 0x4, + value: string + } + | { + id: number, + type: 0x5, + value: NbtCompound + } + | { + id: number, + type: 0x6 | 0x8, + value: IntPos | FloatPos + } +); + +type PacketData = ( + | { type: "", value: PacketData | PacketData[] } + | { type: "Item", value: Item } + | { type: "CompoundTag", value: NbtCompound } + | { + type: "DataItem", + value: PacketDataItem[], + } + | { + type: "ActorLink", + value: { + mA: number, + mB: number, + mType: number, + mImmediate: boolean, + mPassengerInitiated: boolean, + }, + } + | { type: "Vec3" | "BlockPos", value: FloatPos | IntPos } + | { type: "Vec2", value: DirectionAngle } + | { type: "String" | "Uuid", value: string } + | { type: "Bool", value: boolean } + | { + type: + "PacketHeader" + | "Byte" + | "Double" + | "Float" + | "SignedBigEndianInt" + | "SignedInt" + | "SignedInt64" + | "SignedShort" + | "UnsignedChar" + | "UnsignedInt" + | "UnsignedInt64" + | "UnsignedShort" + | "UnsignedVarInt" + | "UnsignedVarInt64" + | "VarInt" + | "VarInt64", + value: number, + } +); + +/** 二进制流数据包类 */ +declare class GMLIB_BinaryStream { + /** 数据包ID */ + #id: number; + /** 数据包是否被销毁 */ + #destroy: boolean; + + constructor( + /** 数据包数据 */ + data: PacketData[]? + ); + + /** 发送数据包 */ + sendTo( + /** 要发送数据包的玩家对象 */ + player: Player, + /** 数据包发送后是否销毁 */ + free: boolean = true + ): GMLIB_BinaryStream; + + /** 发送数据包到玩家数组 */ + sendToPlayers( + /** 要发送数据包的玩家对象数组 */ + players: Player[], + /** 数据包发送后是否销毁 */ + free: boolean = true + ): GMLIB_BinaryStream; + + /** 发送数据包到所有玩家 */ + sendToAll( + /** 数据包发送后是否销毁 */ + free: boolean = true + ): GMLIB_BinaryStream; + + /** 发送数据包到维度 */ + sendToDimension( + /** 维度ID */ + dimid: number, + /** 数据包发送后是否销毁 */ + free: boolean = true + ): GMLIB_BinaryStream; + + /** 销毁数据包 */ + destroy(): GMLIB_BinaryStream; + + /** 数据包是否已被销毁 */ + isDestroy(): boolean; + + /** 重置数据包 */ + reset(): GMLIB_BinaryStream; + + /** 转换成字符串 */ + toString(): string; + + /** 写入数据 */ + write( + /** 数据 */ + data: PacketData | PacketData[]? + ): GMLIB_BinaryStream; + + /** 写入数据包头部 */ + writePacketHeader( + /** 数据包ID */ + id: number + ): GMLIB_BinaryStream; + + /** 写入UUID */ + writeUuid( + /** UUID */ + value: string + ): GMLIB_BinaryStream; + + /** 写入物品 */ + writeItem( + /** 物品对象 */ + value: Item + ): GMLIB_BinaryStream; + + /** 写入NBT */ + writeCompoundTag( + /** NBT */ + value: NbtCompound + ): GMLIB_BinaryStream; + + /** */ + writeDataItem( + /** 数据项 */ + value: PacketDataItem[] + ): GMLIB_BinaryStream; + + writeActorLink( + /** 数据项 */ + value: { "mA": number, "mB": number, "mType": number, "mImmediate": boolean, "mPassengerInitiated": boolean } + ): GMLIB_BinaryStream; + + /** 写入浮点数坐标对象 */ + writeVec3( + /** 浮点数坐标对象 */ + value: FloatPos + ): GMLIB_BinaryStream; + + /** 写入整数坐标对象 */ + writeBlockPos( + /** 整数坐标对象 */ + value: IntPos + ): GMLIB_BinaryStream; + + /** */ + writeVec2( + /** 数据 */ + value: { "x": number, "z": number } + ): GMLIB_BinaryStream; + + /** 写入字符串 */ + writeString( + /** 字符串 */ + value: string + ): GMLIB_BinaryStream; + + /** 写入布尔值 */ + writeBool( + /** 布尔值 */ + value: boolean + ): GMLIB_BinaryStream; + + /** 写入字节 */ + writeByte( + /** 字节 */ + value: number + ): GMLIB_BinaryStream; + + /** 写入(双精度)浮点数 */ + writeDouble( + /** 浮点数 */ + value: number + ): GMLIB_BinaryStream; + + /** 写入(单精度)浮点数 */ + writeFloat( + /** 浮点数 */ + value: number + ): GMLIB_BinaryStream; + + /** */ + writeSignedBigEndianInt( + /** 数值 */ + value: number + ): GMLIB_BinaryStream; + + /** */ + writeSignedInt( + /** 数值 */ + value: number + ): GMLIB_BinaryStream; + + /** 写入 */ + writeSignedInt64( + /** 数值 */ + value: number + ): GMLIB_BinaryStream; + + /** */ + writeSignedShort( + /** 数值 */ + value: number + ): GMLIB_BinaryStream; + + /** */ + writeUnsignedChar( + /** 数值 */ + value: number + ): GMLIB_BinaryStream; + + /** */ + writeUnsignedInt( + /** 数值 */ + value: number + ): GMLIB_BinaryStream; + + /** */ + writeUnsignedInt64( + /** 数值 */ + value: number + ): GMLIB_BinaryStream; + + /** */ + writeUnsignedShort( + /** 数值 */ + value: number + ): GMLIB_BinaryStream; + + /** */ + writeUnsignedVarInt( + /** 数值 */ + value: number + ): GMLIB_BinaryStream; + + /** */ + writeUnsignedVarInt64( + /** 数值 */ + value: number + ): GMLIB_BinaryStream; + + /** */ + writeVarInt( + /** 数值 */ + value: number + ): GMLIB_BinaryStream; + + /** */ + writeVarInt64( + /** 数值 */ + value: number + ): GMLIB_BinaryStream; +} + interface Player { /** (GMLIB)转换成实体对象 */ toEntity(): Entity; @@ -1081,7 +1364,7 @@ interface Player { /** (GMLIB)获取玩家的rumtimeId */ getRuntimeId(): number; - /** (GMLIB)获取玩家饱食度 */ + /** (GMLIB)获取玩家饥饿值 */ getHungry(): number; /** (GMLIB)获取玩家盔甲覆盖百分比 */ diff --git a/lib/GMLIB_API-JS.js b/lib/GMLIB_API-JS.js index 23d32b1..1a34e4c 100644 --- a/lib/GMLIB_API-JS.js +++ b/lib/GMLIB_API-JS.js @@ -316,7 +316,7 @@ const GMLIB_API = { getItemCanPlaceOn: ll.import("GMLIB_API", "getItemCanPlaceOn"), /** 设置物品冒险模式下能放置在什么方块上 @type {function(Item,Array.):void} */ setItemCanPlaceOn: ll.import("GMLIB_API", "setItemCanPlaceOn"), - /** 获取玩家饱食度 @type {function(Player):number} */ + /** 获取玩家饥饿值 @type {function(Player):number} */ getPlayerHungry: ll.import("GMLIB_API", "getPlayerHungry"), /** 获取玩家盔甲覆盖百分比 @type {function(Player):number} */ getPlayerArmorCoverPercentage: ll.import("GMLIB_API", "getPlayerArmorCoverPercentage"), @@ -374,7 +374,61 @@ const GMLIB_API = { getDefaultGameMode: ll.import("GMLIB_API", "getDefaultGameMode"), /** 设置默认游戏模式 @type {function(mode):void} */ setDefaultGameMode: ll.import("GMLIB_API", "setDefaultGameMode"), -} +}; + +/** LRCA的二进制流数据包导出接口 */ +const GMLIB_BinaryStream_API = { + /** 创建二进制流数据包 @type {function():number} */ + create: ll.import("GMLIB_BinaryStream_API", "create"), + /** 发送二进制流数据包 @type {function(number,player):void} */ + sendTo: ll.import("GMLIB_BinaryStream_API", "sendTo"), + /** 销毁二进制流数据包 @type {function(number):void} */ + destroy: ll.import("GMLIB_BinaryStream_API", "destroy"), + /** 重置二进制流数据包 @type {function(number):void} */ + reset: ll.import("GMLIB_BinaryStream_API", "reset"), + /** 写入二进制流数据包头部 @type {function(number, number):void} */ + writePacketHeader: ll.import("GMLIB_BinaryStream_API", "writePacketHeader"), + /** 写入UUID @type {function(number, string):void} */ + writeUuid: ll.import("GMLIB_BinaryStream_API", "writeUuid"), + /** 写入物品 @type {function(number, Item):void} */ + writeItem: ll.import("GMLIB_BinaryStream_API", "writeItem"), + /** 写入NBT @type {function(NbtCompound, Item):void} */ + writeCompoundTag: ll.import("GMLIB_BinaryStream_API", "writeCompoundTag"), + /** 写入字符串 @type {function(number, string):void} */ + writeString: ll.import("GMLIB_BinaryStream_API", "writeString"), + /** 写入布尔值 @type {function(number, boolean):void} */ + writeBool: ll.import("GMLIB_BinaryStream_API", "writeBool"), + /** 写入字节 @type {function(number, number):void} */ + writeByte: ll.import("GMLIB_BinaryStream_API", "writeByte"), + /** 写入双精度浮点数 @type {function(number, number):void} */ + writeDouble: ll.import("GMLIB_BinaryStream_API", "writeDouble"), + /** 写入浮点数 @type {function(number, number):void} */ + writeFloat: ll.import("GMLIB_BinaryStream_API", "writeFloat"), + /** @type {function(number, number):void} */ + writeSignedBigEndianInt: ll.import("GMLIB_BinaryStream_API", "writeSignedBigEndianInt"), + /** @type {function(number, number):void} */ + writeSignedInt: ll.import("GMLIB_BinaryStream_API", "writeSignedInt"), + /** @type {function(number, number):void} */ + writeSignedInt64: ll.import("GMLIB_BinaryStream_API", "writeSignedInt64"), + /** @type {function(number, number):void} */ + writeSignedShort: ll.import("GMLIB_BinaryStream_API", "writeSignedShort"), + /** @type {function(number, number):void} */ + writeUnsignedChar: ll.import("GMLIB_BinaryStream_API", "writeUnsignedChar"), + /** @type {function(number, number):void} */ + writeUnsignedInt: ll.import("GMLIB_BinaryStream_API", "writeUnsignedInt"), + /** @type {function(number, number):void} */ + writeUnsignedInt64: ll.import("GMLIB_BinaryStream_API", "writeUnsignedInt64"), + /** @type {function(number, number):void} */ + writeUnsignedShort: ll.import("GMLIB_BinaryStream_API", "writeUnsignedShort"), + /** @type {function(number, number):void} */ + writeUnsignedVarInt: ll.import("GMLIB_BinaryStream_API", "writeUnsignedVarInt"), + /** @type {function(number, number):void} */ + writeUnsignedVarInt64: ll.import("GMLIB_BinaryStream_API", "writeUnsignedVarInt64"), + /** @type {function(number, number):void} */ + writeVarInt: ll.import("GMLIB_BinaryStream_API", "writeVarInt"), + /** @type {function(number, number):void} */ + writeVarInt64: ll.import("GMLIB_BinaryStream_API", "writeVarInt64"), +}; /** 静态悬浮字类列表 @type {Map} */ const mStaticFloatingTextMap = new Map(); @@ -2052,6 +2106,420 @@ class UserCache { } }; +/** 二进制数据包API类 */ +class GMLIB_BinaryStream { + + /** 数据包ID @type {number} */ + #id = null; + /** 数据包是否被销毁 @type {boolean} */ + #destroy = false; + + /** + * 创建二进制流数据包 + * @param {{"type":string,"value":any}[]?} value 写入数据 + * @returns {GMLIB_BinaryStream} + */ + constructor(value) { + this.#id = GMLIB_BinaryStream_API.create(); + if (Array.isArray(value)) this.write(value); + } + + /** + * 发送数据包 + * @param {Player} player 玩家 + * @param {boolean} [free=true] 发送后销毁数据包 + * @returns {GMLIB_BinaryStream} + */ + sendTo(player, free = true) { + if (this.#destroy) throw new Error("The BinaryStream has been destroyed"); + GMLIB_BinaryStream_API.sendTo(this.#id, player); + if (free) this.destroy(); + return this; + } + + /** + * 发送数据包到玩家 + * @param {Player[]} players 玩家对象数组 + * @param {boolean} free 发送后销毁数据包 + * @returns {GMLIB_BinaryStream} + */ + sendToPlayers(players, free = true) { + if (this.#destroy) throw new Error("The BinaryStream has been destroyed"); + players.forEach(player => this.sendTo(player, false)); + if (free) this.destroy(); + return this; + } + + /** + * 发送数据包到所有玩家 + * @param {boolean} [free=true] 发送后销毁数据包 + * @returns {GMLIB_BinaryStream} + */ + sendToAll(free = true) { + if (this.#destroy) throw new Error("The BinaryStream has been destroyed"); + mc.getOnlinePlayers().forEach(player => this.sendTo(player, false)); + if (free) this.destroy(); + return this; + } + + /** + * 发送数据包到维度 + * @param {number} dimid 维度ID + * @param {boolean} [free=true] 发送后销毁数据包 + * @returns {GMLIB_BinaryStream} + */ + sendToDimension(dimid, free = true) { + if (this.#destroy) throw new Error("The BinaryStream has been destroyed"); + mc.getOnlinePlayers().filter(player => player.pos.dimid === dimid).forEach(player => this.sendTo(player, false)); + if (free) this.destroy(); + return this; + } + + /** + * 销毁数据包 + * @returns {GMLIB_BinaryStream} + */ + destroy() { + GMLIB_BinaryStream_API.destroy(this.#id); + this.#destroy = true; + return this; + } + + /** + * 数据包是否已被销毁 + * @returns {boolean} + */ + isDestroy() { + return this.#destroy; + } + + /** + * 重置数据包 + * @returns {GMLIB_BinaryStream} + */ + reset() { + GMLIB_BinaryStream_API.reset(this.#id); + this.#destroy = false; + return this; + } + + /** + * 转换成字符串 + * @returns {string} 字符串 + */ + toString(){ + return `` + } + + /** + * 写入数据 + * @param {{"type":string,"value":any}[]|{"type":string,"value":any}} value 数据 + * @returns {GMLIB_BinaryStream} + */ + write(value) { + if (this.#destroy) throw new Error("The BinaryStream has been destroyed"); + if (Array.isArray(value)) value.forEach(v => this.write(v)); + if (value?.type != null && value?.value != null) this[`write${value.type}`]?.(value.value); + return this; + } + + /** + * 写入数据包头部 + * @param {number} id 数据包ID + * @returns {GMLIB_BinaryStream} + */ + writePacketHeader(id) { + if (this.#destroy) throw new Error("The BinaryStream has been destroyed"); + GMLIB_BinaryStream_API.writePacketHeader(this.#id, id); + return this; + } + + /** + * 写入UUID + * @param {string} value UUID + * @returns {GMLIB_BinaryStream} + */ + writeUuid(value) { + if (this.#destroy) throw new Error("The BinaryStream has been destroyed"); + GMLIB_BinaryStream_API.writeUuid(this.#id, value); + return this; + } + + /** + * 写入物品 + * @param {Item} value 物品 + * @returns {GMLIB_BinaryStream} + */ + writeItem(value) { + if (this.#destroy) throw new Error("The BinaryStream has been destroyed"); + GMLIB_BinaryStream_API.writeItem(this.#id, value); + return this; + } + + /** + * 写入NBT + * @param {NbtCompound} value NBT + * @returns {GMLIB_BinaryStream} + */ + writeCompoundTag(value) { + if (this.#destroy) throw new Error("The BinaryStream has been destroyed"); + GMLIB_BinaryStream_API.writeCompoundTag(this.#id, value); + return this; + } + + /** + * @param {{"id":number,"type":number,"value":string|IntPos|FloatPos|number|NbtCompound}[]} value 数据 + * @returns {GMLIB_BinaryStream} + */ + writeDataItem(value) { + if (this.#destroy) throw new Error("The BinaryStream has been destroyed"); + this.writeUnsignedVarInt(value.length); + for (const data of value) { + this.writeUnsignedVarInt(data.id); + this.writeUnsignedVarInt(data.type); + switch (data.type) { + case 0: this.writeByte(data.value); break; + case 1: this.writeSignedShort(data.value); break; + case 2: this.writeSignedInt(data.value); break; + case 3: this.writeFloat(data.value); break; + case 4: this.writeString(data.value); break; + case 5: this.writeCompoundTag(data.value); break; + case 6: this.writeBlockPos(data.value); break; + case 7: this.writeSignedInt64(data.value); break; + case 8: this.writeVec3(data.value); break; + default: throw new Error("Unknown data type"); + } + } + return this; + } + + /** + * @param {{"mA":number,"mB":number,"mType":number,"mImmediate":boolean,"mPassengerInitiated":boolean}} value 数据 + * @returns {GMLIB_BinaryStream} + */ + writeActorLink(value) { + this.writeVarInt64(value.mA); + this.writeVarInt64(value.mB); + this.writeUnsignedChar(value.mType); + this.writeBool(value.mImmediate); + this.writeBool(value.mPassengerInitiated); + return this; + } + + /** + * 写入字符串 + * @param {string} value 字符串 + * @returns {GMLIB_BinaryStream} + */ + writeString(value) { + if (this.#destroy) throw new Error("The BinaryStream has been destroyed"); + GMLIB_BinaryStream_API.writeString(this.#id, value); + return this; + } + + /** + * 写入布尔值 + * @param {boolean} value 布尔值 + * @returns {GMLIB_BinaryStream} + */ + writeBool(value) { + if (this.#destroy) throw new Error("The BinaryStream has been destroyed"); + GMLIB_BinaryStream_API.writeBool(this.#id, value); + return this; + } + + /** + * 写入字节 + * @param {number} value 字节 + * @returns {GMLIB_BinaryStream} + */ + writeByte(value) { + if (this.#destroy) throw new Error("The BinaryStream has been destroyed"); + GMLIB_BinaryStream_API.writeByte(this.#id, value); + return this; + } + + /** + * 写入(双精度)浮点数 + * @param {number} value 浮点数 + * @returns {GMLIB_BinaryStream} + */ + writeDouble(value) { + if (this.#destroy) throw new Error("The BinaryStream has been destroyed"); + GMLIB_BinaryStream_API.writeDouble(this.#id, value); + return this; + } + + /** + * 写入(单精度)浮点数 + * @param {number} value 浮点数 + * @returns {GMLIB_BinaryStream} + */ + writeFloat(value) { + if (this.#destroy) throw new Error("The BinaryStream has been destroyed"); + GMLIB_BinaryStream_API.writeFloat(this.#id, value); + return this; + } + + /** + * 写入浮点数坐标对象 + * @param {FloatPos} value 浮点数坐标对象 + * @returns {GMLIB_BinaryStream} + */ + writeVec3({ x, y, z }) { + if (this.#destroy) throw new Error("The BinaryStream has been destroyed"); + this.writeFloat(x); + this.writeFloat(y); + this.writeFloat(z); + return this; + } + + /** + * 写入整数坐标对象 + * @param {IntPos} value 整数坐标对象 + * @returns {GMLIB_BinaryStream} + */ + writeBlockPos({ x, y, z }) { + if (this.#destroy) throw new Error("The BinaryStream has been destroyed"); + this.writeVarInt(x); + this.writeUnsignedVarInt(y); + this.writeVarInt(z); + return this; + } + + /** + * + * @param {{"x":number,"z":number}} value 数值 + * @returns {GMLIB_BinaryStream} + */ + writeVec2({ x, z }) { + if (this.#destroy) throw new Error("The BinaryStream has been destroyed"); + this.writeFloat(x); + this.writeFloat(z); + return this; + } + + /** + * @param {number} value 数值 + * @returns {GMLIB_BinaryStream} + */ + writeSignedBigEndianInt(value) { + if (this.#destroy) throw new Error("The BinaryStream has been destroyed"); + GMLIB_BinaryStream_API.writeSignedBigEndianInt(this.#id, value); + return this; + } + + /** + * @param {number} value 数值 + * @returns {GMLIB_BinaryStream} + */ + writeSignedInt(value) { + if (this.#destroy) throw new Error("The BinaryStream has been destroyed"); + GMLIB_BinaryStream_API.writeSignedInt(this.#id, value); + return this; + } + + /** + * @param {number} value 数值 + * @returns {GMLIB_BinaryStream} + */ + writeSignedInt64(value) { + if (this.#destroy) throw new Error("The BinaryStream has been destroyed"); + GMLIB_BinaryStream_API.writeSignedInt64(this.#id, value); + return this; + } + + /** + * @param {number} value 数值 + * @returns {GMLIB_BinaryStream} + */ + writeSignedShort(value) { + if (this.#destroy) throw new Error("The BinaryStream has been destroyed"); + GMLIB_BinaryStream_API.writeSignedShort(this.#id, value); + return this; + } + + /** + * @param {number} value 数值 + * @returns {GMLIB_BinaryStream} + */ + writeUnsignedChar(value) { + if (this.#destroy) throw new Error("The BinaryStream has been destroyed"); + GMLIB_BinaryStream_API.writeUnsignedChar(this.#id, value); + return this; + } + + /** + * @param {number} value 数值 + * @returns {GMLIB_BinaryStream} + */ + writeUnsignedInt(value) { + if (this.#destroy) throw new Error("The BinaryStream has been destroyed"); + GMLIB_BinaryStream_API.writeUnsignedInt(this.#id, value); + return this; + } + + /** + * @param {number} value 数值 + * @returns {GMLIB_BinaryStream} + */ + writeUnsignedInt64(value) { + if (this.#destroy) throw new Error("The BinaryStream has been destroyed"); + GMLIB_BinaryStream_API.writeUnsignedInt64(this.#id, value); + return this; + } + + /** + * @param {number} value 数值 + * @returns {GMLIB_BinaryStream} + */ + writeUnsignedShort(value) { + if (this.#destroy) throw new Error("The BinaryStream has been destroyed"); + GMLIB_BinaryStream_API.writeUnsignedShort(this.#id, value); + return this; + } + + /** + * @param {number} value 数值 + * @returns {GMLIB_BinaryStream} + */ + writeUnsignedVarInt(value) { + if (this.#destroy) throw new Error("The BinaryStream has been destroyed"); + GMLIB_BinaryStream_API.writeUnsignedVarInt(this.#id, value); + return this; + } + + /** + * @param {number} value 数值 + * @returns {GMLIB_BinaryStream} + */ + writeUnsignedVarInt64(value) { + if (this.#destroy) throw new Error("The BinaryStream has been destroyed"); + GMLIB_BinaryStream_API.writeUnsignedVarInt64(this.#id, value); + return this; + } + + /** + * @param {number} value 数值 + * @returns {GMLIB_BinaryStream} + */ + writeVarInt(value) { + if (this.#destroy) throw new Error("The BinaryStream has been destroyed"); + GMLIB_BinaryStream_API.writeVarInt(this.#id, value); + return this; + } + + /** + * @param {number} value 数值 + * @returns {GMLIB_BinaryStream} + */ + writeVarInt64(value) { + if (this.#destroy) throw new Error("The BinaryStream has been destroyed"); + GMLIB_BinaryStream_API.writeVarInt64(this.#id, value); + return this; + } +} + LLSE_Player.prototype.toEntity = /** * 获取实体对象 @@ -2470,7 +2938,7 @@ LLSE_Item.prototype.setCanPlaceOn = LLSE_Player.prototype.getHungry = /** - * 获取玩家饱食度 + * 获取玩家饥饿值 * @returns {number} */ function () { @@ -2661,5 +3129,6 @@ module.exports = { JsonI18n, Version, I18nAPI, - UserCache + UserCache, + GMLIB_BinaryStream }; \ No newline at end of file diff --git a/src/BinaryStreamApi.cpp b/src/BinaryStreamApi.cpp new file mode 100644 index 0000000..5309fed --- /dev/null +++ b/src/BinaryStreamApi.cpp @@ -0,0 +1,80 @@ +#include "Global.h" +using namespace ll::hash_utils; + +class LegacyScriptBinaryStreamManager { +private: + int64 mNextBinaryStreamId = 0; + std::unordered_map> mBinaryStream; + +public: + uint getNextId() { return mNextBinaryStreamId++; } + + void cretateBinaryStream(uint id) { mBinaryStream[id] = std::make_shared(); } + + void removeBinaryStream(uint64 id) { mBinaryStream.erase(id); } + + std::shared_ptr getBinaryStream(uint64 id) { + return mBinaryStream.contains(id) ? mBinaryStream.at(id) : nullptr; + } + +public: + static LegacyScriptBinaryStreamManager& getInstance() { + static std::unique_ptr instance; + if (!instance) instance = std::make_unique(); + return *instance; + } +}; + +#define BinaryStreamManager LegacyScriptBinaryStreamManager::getInstance() +#define EXPORTAPI(funcName, type, fuc) \ + RemoteCall::exportAs("GMLIB_BinaryStream_API", funcName, [](uint64 id, type value) -> void { \ + auto bs = BinaryStreamManager.getBinaryStream(id); \ + if (bs != nullptr) fuc; \ + }) + +template +struct Info; +template +struct Info { + using ArgT = A; +}; +#define EXPORTAPI2(T) EXPORTAPI(#T, Info::ArgT, bs->T(value)) + +void Export_BinaryStream_API() { + RemoteCall::exportAs("GMLIB_BinaryStream_API", "create", []() -> uint64 { + auto id = BinaryStreamManager.getNextId(); + BinaryStreamManager.cretateBinaryStream(id); + return id; + }); + RemoteCall::exportAs("GMLIB_BinaryStream_API", "reset", [](uint64 id) -> void { + if (BinaryStreamManager.getBinaryStream(id) == nullptr) BinaryStreamManager.cretateBinaryStream(id); + else BinaryStreamManager.getBinaryStream(id)->reset(); + }); + RemoteCall::exportAs("GMLIB_BinaryStream_API", "sendTo", [](uint64 id, Player* player) -> void { + if (auto bs = BinaryStreamManager.getBinaryStream(id); bs != nullptr) bs->sendTo(*player); + }); + RemoteCall::exportAs("GMLIB_BinaryStream_API", "destroy", [](uint64 id) -> void { + BinaryStreamManager.removeBinaryStream(id); + }); + EXPORTAPI("writePacketHeader", int, bs->writePacketHeader((MinecraftPacketIds)value)); + EXPORTAPI("writeUuid", std::string const&, bs->writeUuid(mce::UUID::fromString(value))); + EXPORTAPI("writeItem", ItemStack*, bs->writeType(NetworkItemStackDescriptor(*value))); + EXPORTAPI("writeString", std::string const&, bs->writeString(value)); + EXPORTAPI("writeCompoundTag", CompoundTag*, bs->writeCompoundTag(*value)); + EXPORTAPI2(writeBool); + EXPORTAPI2(writeByte); + EXPORTAPI2(writeDouble); + EXPORTAPI2(writeFloat); + EXPORTAPI2(writeSignedBigEndianInt); + EXPORTAPI2(writeSignedInt); + EXPORTAPI2(writeSignedInt64); + EXPORTAPI2(writeSignedShort); + EXPORTAPI2(writeUnsignedChar); + EXPORTAPI2(writeUnsignedInt); + EXPORTAPI2(writeUnsignedInt64); + EXPORTAPI2(writeUnsignedShort); + EXPORTAPI2(writeUnsignedVarInt); + EXPORTAPI2(writeUnsignedVarInt64); + EXPORTAPI2(writeVarInt); + EXPORTAPI2(writeVarInt64); +} \ No newline at end of file diff --git a/src/CompatibilityApi.cpp b/src/CompatibilityApi.cpp index 7f46029..ebf5bdf 100644 --- a/src/CompatibilityApi.cpp +++ b/src/CompatibilityApi.cpp @@ -1,9 +1,5 @@ #include "Global.h" -#include "mc/world/item/Item.h" -#include "mc/world/item/enchanting/EnchantUtils.h" -#include "mc/world/level/block/Block.h" #include -#include bool isInteger(const std::string& str) { std::regex pattern("^[+-]?\\d+$"); @@ -11,82 +7,69 @@ bool isInteger(const std::string& str) { } ActorUniqueID parseScriptUniqueID(std::string const& uniqueId) { - if (!isInteger(uniqueId)) { - return ActorUniqueID::INVALID_ID; - } - return ActorUniqueID(std::stoll(uniqueId)); + return isInteger(uniqueId) ? ActorUniqueID(std::stoll(uniqueId)) : ActorUniqueID::INVALID_ID; } void Export_Compatibility_API() { RemoteCall::exportAs("GMLIB_API", "unregisterRecipe", [](std::string const& id) -> bool { - auto level = world::Level::getInstance(); - if (!level) { - return false; - } - return recipe::RecipeRegistry::unregisterRecipe(id); + return gmlib::world::Level::getInstance().has_value() ? gmlib::mod::recipe::RecipeRegistry::unregisterRecipe(id) : false; }); RemoteCall::exportAs("GMLIB_API", "setCustomPackPath", [](std::string const& path) -> void { - AddonsLoader::addCustomPackPath(path); + gmlib::tools::AddonsLoader::addCustomPackPath(path); }); - RemoteCall::exportAs("GMLIB_API", "getServerMspt", []() -> float { - auto level = world::Level::getInstance(); - if (!level) { - return 0.0f; - } - return level->getServerMspt(); + RemoteCall::exportAs("GMLIB_API", "getServerMspt", []() -> double { + return gmlib::world::Level::getInstance() + .transform([](gmlib::world::Level& level) -> double { return level.getServerMspt(); }) + .value_or(0.0); }); RemoteCall::exportAs("GMLIB_API", "getServerCurrentTps", []() -> float { - auto level = world::Level::getInstance(); - if (!level) { - return 0.0f; - } - return level->getServerCurrentTps(); + return gmlib::world::Level::getInstance() + .transform([](gmlib::world::Level& level) -> float { return level.getServerCurrentTps(); }) + .value_or(0.0); }); - RemoteCall::exportAs("GMLIB_API", "getServerAverageTps", []() -> float { - auto level = world::Level::getInstance(); - if (!level) { - return 0.0f; - } - return level->getServerAverageTps(); + RemoteCall::exportAs("GMLIB_API", "getServerAverageTps", []() -> double { + return gmlib::world::Level::getInstance() + .transform([](gmlib::world::Level& level) -> double { return level.getServerAverageTps(); }) + .value_or(0.0); }); RemoteCall::exportAs("GMLIB_API", "getAllPlayerUuids", []() -> std::vector { std::vector result; - std::vector uuids = world::Player::getAllUuids(); - for (auto& uuid : uuids) { + for (auto& uuid : gmlib::world::Player::getAllUuids()) { result.push_back(uuid.asString()); } return result; }); - RemoteCall::exportAs("GMLIB_API", "getPlayerNbt", [](std::string const& uuid) -> std::unique_ptr<::CompoundTag> { - auto uid = mce::UUID::fromString(uuid); - return std::move(world::Player::getPlayerNbt(uid)); + RemoteCall::exportAs("GMLIB_API", "getPlayerNbt", [](std::string const& uuid) -> std::unique_ptr { + return std::move(gmlib::world::Player::getPlayerNbt(mce::UUID::fromString(uuid))); }); RemoteCall::exportAs( "GMLIB_API", "setPlayerNbt", - [](std::string const& uuid, ::CompoundTag* nbt, bool forceCreate) -> bool { - auto uid = mce::UUID::fromString(uuid); - auto nbtt = world::CompoundTag(*nbt); - return world::Player::setPlayerNbt(uid, nbtt, forceCreate); + [](std::string const& uuid, CompoundTag* nbt, bool forceCreate) -> bool { + return gmlib::world::Player::setPlayerNbt( + mce::UUID::fromString(uuid), + (gmlib::world::CompoundTag&)*nbt, + forceCreate + ); } ); RemoteCall::exportAs( "GMLIB_API", "setPlayerNbtTags", - [](std::string const& uuid, ::CompoundTag* nbt, std::vector tags) -> bool { - auto uid = mce::UUID::fromString(uuid); - auto nbtt = world::CompoundTag(*nbt); - return world::Player::setPlayerNbtTags(uid, nbtt, tags); + [](std::string const& uuid, CompoundTag* nbt, std::vector tags) -> bool { + return gmlib::world::Player::setPlayerNbtTags( + mce::UUID::fromString(uuid), + (gmlib::world::CompoundTag&)*nbt, + tags + ); } ); RemoteCall::exportAs("GMLIB_API", "deletePlayerNbt", [](std::string const& uuid) -> bool { - auto uid = mce::UUID::fromString(uuid); - return world::Player::deletePlayerNbt(uid); + return gmlib::world::Player::deletePlayerNbt(mce::UUID::fromString(uuid)); }); RemoteCall::exportAs("GMLIB_API", "getAllExperiments", []() -> std::vector { - auto list = world::Level::getAllExperiments(); std::vector result; - for (auto& key : list) { + for (auto& key : gmlib::world::Level::getAllExperiments()) { result.push_back((int)key); } return result; @@ -102,104 +85,113 @@ void Export_Compatibility_API() { "GMLIB_API", "createFloatingText", [](std::pair pos, std::string const& text, bool papi) -> int { - auto& manager = FloatingTextManager::getInstance(); - auto ft = manager.createStatic(text, pos.first, pos.second, papi); - manager.add(ft); + auto ft = gmlib::tools::FloatingTextManager::createStatic(text, pos.first, pos.second, papi); + gmlib::tools::FloatingTextManager::getInstance().add(ft); return ft->getRuntimeID(); } ); RemoteCall::exportAs("GMLIB_API", "setFloatingTextData", [](int id, std::string const& text) -> bool { - if (auto ft = FloatingTextManager::getInstance().getFloatingText(id)) { - ft->setText(text); - return true; - } - return false; + return gmlib::tools::FloatingTextManager::getInstance() + .getFloatingText(id) + .transform([&text](gmlib::tools::FloatingTextBase& ft) -> bool { + ft.setText(text); + return true; + }) + .has_value(); }); RemoteCall::exportAs("GMLIB_API", "deleteFloatingText", [](int id) -> bool { - return FloatingTextManager::getInstance().remove(id); + return gmlib::tools::FloatingTextManager::getInstance().remove(id); }); - RemoteCall::exportAs("GMLIB_API", "sendFloatingTextToPlayer", [](int id, ::Player* pl) -> bool { - if (auto ft = FloatingTextManager::getInstance().getFloatingText(id)) { - ft->sendTo(*pl); - return true; - } - return false; + RemoteCall::exportAs("GMLIB_API", "sendFloatingTextToPlayer", [](int id, Player* pl) -> bool { + return gmlib::tools::FloatingTextManager::getInstance() + .getFloatingText(id) + .transform([&pl](gmlib::tools::FloatingTextBase& ft) -> bool { + ft.sendTo(*pl); + return true; + }) + .has_value(); }); RemoteCall::exportAs("GMLIB_API", "sendFloatingText", [](int id) -> bool { - if (auto ft = FloatingTextManager::getInstance().getFloatingText(id)) { - ft->sendToClients(); - return true; - } - return false; + return gmlib::tools::FloatingTextManager::getInstance() + .getFloatingText(id) + .transform([](gmlib::tools::FloatingTextBase& ft) -> bool { + ft.sendToClients(); + return true; + }) + .has_value(); }); - RemoteCall::exportAs("GMLIB_API", "removeFloatingTextFromPlayer", [](int id, ::Player* pl) -> bool { - if (auto ft = FloatingTextManager::getInstance().getFloatingText(id)) { - ft->removeFrom(*pl); - return true; - } - return false; + RemoteCall::exportAs("GMLIB_API", "removeFloatingTextFromPlayer", [](int id, Player* pl) -> bool { + return gmlib::tools::FloatingTextManager::getInstance() + .getFloatingText(id) + .transform([&pl](gmlib::tools::FloatingTextBase& ft) -> bool { + ft.removeFrom(*pl); + return true; + }) + .has_value(); }); RemoteCall::exportAs("GMLIB_API", "removeFloatingText", [](int id) -> bool { - if (auto ft = FloatingTextManager::getInstance().getFloatingText(id)) { - ft->removeFromClients(); - return true; - } - return false; + return gmlib::tools::FloatingTextManager::getInstance() + .getFloatingText(id) + .transform([](gmlib::tools::FloatingTextBase& ft) -> bool { + ft.removeFromClients(); + return true; + }) + .has_value(); }); - RemoteCall::exportAs("GMLIB_API", "updateClientFloatingTextData", [](int id, ::Player* pl) -> bool { - if (auto ft = FloatingTextManager::getInstance().getFloatingText(id)) { - ft->update(*pl); - return true; - } - return false; + RemoteCall::exportAs("GMLIB_API", "updateClientFloatingTextData", [](int id, Player* pl) -> bool { + return gmlib::tools::FloatingTextManager::getInstance() + .getFloatingText(id) + .transform([&pl](gmlib::tools::FloatingTextBase& ft) -> bool { + ft.update(*pl); + return true; + }) + .has_value(); }); RemoteCall::exportAs("GMLIB_API", "updateAllClientsFloatingTextData", [](int id) -> bool { - if (auto ft = FloatingTextManager::getInstance().getFloatingText(id)) { - ft->updateClients(); - return true; - } - return false; + return gmlib::tools::FloatingTextManager::getInstance() + .getFloatingText(id) + .transform([](gmlib::tools::FloatingTextBase& ft) -> bool { + ft.updateClients(); + return true; + }) + .has_value(); }); RemoteCall::exportAs("GMLIB_API", "isVersionMatched", [](int a, int b, int c) -> bool { - auto version = Version(a, b, c, "", ""); - return LIB_VERSION >= version; + return LIB_VERSION >= gmlib::Version(a, b, c, "", ""); }); RemoteCall::exportAs("GMLIB_API", "getVersion_LRCA", []() -> std::string { return LIB_VERSION.asString(); }); RemoteCall::exportAs("GMLIB_API", "getVersion_GMLIB", []() -> std::string { - return Version::getLibVersionString(); + return gmlib::Version::getLibVersionString(); }); RemoteCall::exportAs( "GMLIB_API", "resourcePackDefaultTranslate", - [](std::string const& key, std::vector params) -> std::string { return I18nAPI::get(key, params); } + [](std::string const& key, std::vector params) -> std::string { + return gmlib::world::I18nAPI::get(key, params); + } ); RemoteCall::exportAs( "GMLIB_API", "resourcePackTranslate", [](std::string const& key, std::vector params, std::string const& code) -> std::string { - return I18nAPI::get(key, params, code); + return gmlib::world::I18nAPI::get(key, params, code); } ); RemoteCall::exportAs("GMLIB_API", "chooseResourcePackI18nLanguage", [](std::string const& code) -> void { - if (world::Level::getInstance()) { - I18nAPI::chooseLanguage(code); + if (gmlib::world::Level::getInstance()) { + gmlib::world::I18nAPI::chooseLanguage(code); } }); RemoteCall::exportAs("GMLIB_API", "getResourcePackI18nLanguage", []() -> std::string { - if (world::Level::getInstance()) { - return I18nAPI::getCurrentLanguageCode(); - } - return "unknown"; + return gmlib::world::Level::getInstance().has_value() ? gmlib::world::I18nAPI::getCurrentLanguageCode() : "unknown"; }); RemoteCall::exportAs("GMLIB_API", "getSupportedLanguages", []() -> std::vector { - if (world::Level::getInstance()) { - return I18nAPI::getSupportedLanguageCodes(); - } - return {}; + return gmlib::world::Level::getInstance() ? gmlib::world::I18nAPI::getSupportedLanguageCodes() + : std::vector(); }); RemoteCall::exportAs("GMLIB_API", "loadLanguage", [](std::string const& code, std::string const& lang) -> void { - if (world::Level::getInstance()) { - I18nAPI::loadLanguage(code, lang); + if (gmlib::world::Level::getInstance()) { + gmlib::world::I18nAPI::loadLanguage(code, lang); } }); RemoteCall::exportAs( @@ -207,281 +199,211 @@ void Export_Compatibility_API() { "updateOrCreateLanguageFile", [](std::string const& code, std::unordered_map lang, std::string const& path ) -> void { - if (world::Level::getInstance()) { - I18nAPI::updateOrCreateLanguageFile(path, code, lang); + if (gmlib::world::Level::getInstance()) { + gmlib::world::I18nAPI::updateOrCreateLanguageFile(path, code, lang); } } ); RemoteCall::exportAs("GMLIB_API", "loadLanguagePath", [](std::string const& path) -> void { - if (world::Level::getInstance()) { - I18nAPI::loadLanguagesFromDirectory(path); + if (gmlib::world::Level::getInstance()) { + gmlib::world::I18nAPI::loadLanguagesFromDirectory(path); } }); RemoteCall::exportAs("GMLIB_API", "getPlayerPosition", [](std::string const& uuid) -> std::pair { - auto uid = mce::UUID::fromString(uuid); - auto pos = world::Player::getPlayerPosition(uid); - if (pos.has_value()) { - return pos.value(); - } - return { - {0, 0, 0}, - -1 - }; + return gmlib::world::Player::getPlayerPosition(mce::UUID::fromString(uuid)) + .value_or(std::pair({0, 0, 0}, -1)); }); RemoteCall::exportAs( "GMLIB_API", "setPlayerPosition", [](std::string const& uuid, std::pair pos) -> bool { - auto uid = mce::UUID::fromString(uuid); - return world::Player::setPlayerPosition(uid, pos.first, pos.second); + return gmlib::world::Player::setPlayerPosition(mce::UUID::fromString(uuid), pos.first, pos.second); } ); RemoteCall::exportAs("GMLIB_API", "playerHasScore", [](std::string const& uuid, std::string const& obj) -> bool { - auto uid = mce::UUID::fromString(uuid); - if (auto result = world::Player::getPlayerScore(uid, obj)) { - return true; - } - return false; + return gmlib::world::Player::getPlayerScore(mce::UUID::fromString(uuid), obj).has_value(); }); RemoteCall::exportAs("GMLIB_API", "getPlayerScore", [](std::string const& uuid, std::string const& obj) -> int { - auto uid = mce::UUID::fromString(uuid); - if (auto result = world::Player::getPlayerScore(uid, obj)) { - return result.value(); - } - return 0; + return gmlib::world::Player::getPlayerScore(mce::UUID::fromString(uuid), obj).value_or(0); }); RemoteCall::exportAs( "GMLIB_API", "addPlayerScore", [](std::string const& uuid, std::string const& obj, int value) -> bool { - auto uid = mce::UUID::fromString(uuid); - if (auto res = world::Player::setPlayerScore(uid, obj, value, PlayerScoreSetFunction::Add)) { - return true; - } - return false; + return gmlib::world::Player::setPlayerScore( + mce::UUID::fromString(uuid), + obj, + value, + PlayerScoreSetFunction::Add + ) + .has_value(); } ); RemoteCall::exportAs( "GMLIB_API", "reducePlayerScore", [](std::string const& uuid, std::string const& obj, int value) -> bool { - auto uid = mce::UUID::fromString(uuid); - if (auto res = world::Player::setPlayerScore(uid, obj, value, PlayerScoreSetFunction::Subtract)) { - return true; - } - return false; + return gmlib::world::Player::setPlayerScore(mce::UUID::fromString(uuid), obj, value, PlayerScoreSetFunction::Subtract).has_value(); } ); RemoteCall::exportAs( "GMLIB_API", "setPlayerScore", [](std::string const& uuid, std::string const& obj, int value) -> bool { - auto uid = mce::UUID::fromString(uuid); - if (auto res = world::Player::setPlayerScore(uid, obj, value)) { - return true; - } - return false; + return gmlib::world::Player::setPlayerScore(mce::UUID::fromString(uuid), obj, value).has_value(); } ); RemoteCall::exportAs("GMLIB_API", "resetPlayerScore", [](std::string const& uuid, std::string const& obj) -> bool { - auto uid = mce::UUID::fromString(uuid); - return world::Player::resetPlayerScore(uid, obj); + return gmlib::world::Player::resetPlayerScore(mce::UUID::fromString(uuid), obj); }); RemoteCall::exportAs("GMLIB_API", "resetPlayerScores", [](std::string const& uuid) -> bool { - auto uid = mce::UUID::fromString(uuid); - return world::Player::resetPlayerScore(uid); + return gmlib::world::Player::resetPlayerScore(mce::UUID::fromString(uuid)); }); RemoteCall::exportAs( "GMLIB_API", "entityHasScore", [](std::string const& uniqueId, std::string const& obj) -> bool { - auto auid = parseScriptUniqueID(uniqueId); - if (auto result = world::Scoreboard::getInstance()->getScore(obj, auid)) { - return true; - } - return false; + return gmlib::world::Scoreboard::getInstance()->getScore(obj, parseScriptUniqueID(uniqueId)).has_value(); } ); RemoteCall::exportAs("GMLIB_API", "getEntityScore", [](std::string const& uniqueId, std::string const& obj) -> int { - auto auid = parseScriptUniqueID(uniqueId); - if (auto result = world::Scoreboard::getInstance()->getScore(obj, auid)) { - return result.value(); - } - return 0; + return gmlib::world::Scoreboard::getInstance()->getScore(obj, parseScriptUniqueID(uniqueId)).value_or(0); }); RemoteCall::exportAs( "GMLIB_API", "addEntityScore", [](std::string const& uniqueId, std::string const& obj, int value) -> bool { - auto auid = parseScriptUniqueID(uniqueId); - if (auto res = world::Scoreboard::getInstance()->setScore(obj, auid, value, PlayerScoreSetFunction::Add)) { - return true; - } - return false; + return gmlib::world::Scoreboard::getInstance() + ->setScore(obj, parseScriptUniqueID(uniqueId), value, PlayerScoreSetFunction::Add) + .has_value(); } ); RemoteCall::exportAs( "GMLIB_API", "reduceEntityScore", [](std::string const& uniqueId, std::string const& obj, int value) -> bool { - auto auid = parseScriptUniqueID(uniqueId); - if (auto res = - world::Scoreboard::getInstance()->setScore(obj, auid, value, PlayerScoreSetFunction::Subtract)) { - return true; - } - return false; + return gmlib::world::Scoreboard::getInstance() + ->setScore(obj, parseScriptUniqueID(uniqueId), value, PlayerScoreSetFunction::Subtract) + .has_value(); } ); RemoteCall::exportAs( "GMLIB_API", "setEntityScore", [](std::string const& uniqueId, std::string const& obj, int value) -> bool { - auto auid = parseScriptUniqueID(uniqueId); - if (auto res = world::Scoreboard::getInstance()->setScore(obj, auid, value)) { - return true; - } - return false; + return gmlib::world::Scoreboard::getInstance()->setScore(obj, parseScriptUniqueID(uniqueId), value).has_value(); } ); RemoteCall::exportAs( "GMLIB_API", "resetEntityScore", [](std::string const& uniqueId, std::string const& obj) -> bool { - auto auid = parseScriptUniqueID(uniqueId); - return world::Scoreboard::getInstance()->resetScore(obj, auid); + return gmlib::world::Scoreboard::getInstance()->resetScore(obj, parseScriptUniqueID(uniqueId)); } ); RemoteCall::exportAs("GMLIB_API", "resetEntityScores", [](std::string const& uniqueId) -> bool { - auto auid = parseScriptUniqueID(uniqueId); - return world::Scoreboard::getInstance()->resetScore(auid); + return gmlib::world::Scoreboard::getInstance()->resetScore(parseScriptUniqueID(uniqueId)); }); RemoteCall::exportAs( "GMLIB_API", "fakePlayerHasScore", [](std::string const& name, std::string const& obj) -> bool { - if (auto result = world::Scoreboard::getInstance()->getScore(obj, name)) { - return true; - } - return false; + return gmlib::world::Scoreboard::getInstance()->getScore(obj, name).has_value(); } ); RemoteCall::exportAs("GMLIB_API", "getFakePlayerScore", [](std::string const& name, std::string const& obj) -> int { - if (auto result = world::Scoreboard::getInstance()->getScore(obj, name)) { - return result.value(); - } - return 0; + return gmlib::world::Scoreboard::getInstance()->getScore(obj, name).value_or(0); }); RemoteCall::exportAs( "GMLIB_API", "addFakePlayerScore", [](std::string const& name, std::string const& obj, int value) -> bool { - if (auto res = world::Scoreboard::getInstance()->setScore(obj, name, value, PlayerScoreSetFunction::Add)) { - return true; - } - return false; + return gmlib::world::Scoreboard::getInstance()->setScore(obj, name, value, PlayerScoreSetFunction::Add).has_value(); } ); RemoteCall::exportAs( "GMLIB_API", "reduceFakePlayerScore", [](std::string const& name, std::string const& obj, int value) -> bool { - if (auto res = - world::Scoreboard::getInstance()->setScore(obj, name, value, PlayerScoreSetFunction::Subtract)) { - return true; - } - return false; + return gmlib::world::Scoreboard::getInstance() + ->setScore(obj, name, value, PlayerScoreSetFunction::Subtract) + .has_value(); } ); RemoteCall::exportAs( "GMLIB_API", "setFakePlayerScore", [](std::string const& name, std::string const& obj, int value) -> bool { - if (auto res = world::Scoreboard::getInstance()->setScore(obj, name, value)) { - return true; - } - return false; + return gmlib::world::Scoreboard::getInstance()->setScore(obj, name, value).has_value(); } ); RemoteCall::exportAs( "GMLIB_API", "resetFakePlayerScore", [](std::string const& name, std::string const& obj) -> bool { - return world::Scoreboard::getInstance()->resetScore(obj, name); + return gmlib::world::Scoreboard::getInstance()->resetScore(obj, name); } ); RemoteCall::exportAs("GMLIB_API", "resetFakePlayerScores", [](std::string const& name) -> bool { - return world::Scoreboard::getInstance()->resetScore(name); + return gmlib::world::Scoreboard::getInstance()->resetScore(name); }); RemoteCall::exportAs("GMLIB_API", "addObjective", [](std::string const& obj) -> bool { - if (auto res = world::Scoreboard::getInstance()->addObjective(obj)) { - return true; - } - return false; + return gmlib::world::Scoreboard::getInstance()->addObjective(obj).has_value(); }); RemoteCall::exportAs( "GMLIB_API", "addObjectiveWithDisplayName", [](std::string const& obj, std::string const& displayName) -> bool { - if (auto res = world::Scoreboard::getInstance()->addObjective(obj, displayName)) { - return true; - } - return false; + return gmlib::world::Scoreboard::getInstance()->addObjective(obj, displayName).has_value(); } ); RemoteCall::exportAs("GMLIB_API", "getDisplayName", [](std::string const& obj) -> std::string { - if (auto result = world::Scoreboard::getInstance()->getObjectiveDisplayName(obj)) { - return result.value(); - } - return ""; + return gmlib::world::Scoreboard::getInstance()->getObjectiveDisplayName(obj).value_or(""); }); RemoteCall::exportAs( "GMLIB_API", "setDisplayName", [](std::string const& obj, std::string const& displayName) -> bool { - return world::Scoreboard::getInstance()->setObjectiveDisplayName(obj, displayName); + return gmlib::world::Scoreboard::getInstance()->setObjectiveDisplayName(obj, displayName); } ); RemoteCall::exportAs("GMLIB_API", "removeObjective", [](std::string const& obj) -> bool { - return world::Scoreboard::getInstance()->removeObjective(obj); + return gmlib::world::Scoreboard::getInstance()->removeObjective(obj); }); RemoteCall::exportAs( "GMLIB_API", "setDisplayObjective", [](std::string const& obj, std::string const& slot, int order) -> void { - return world::Scoreboard::getInstance()->setObjectiveDisplay(obj, slot, (ObjectiveSortOrder)order); + return gmlib::world::Scoreboard::getInstance()->setObjectiveDisplay(obj, slot, (ObjectiveSortOrder)order); } ); RemoteCall::exportAs("GMLIB_API", "clearDisplayObjective", [](std::string const& slot) -> void { - return world::Scoreboard::getInstance()->clearObjectiveDisplay(slot); + return gmlib::world::Scoreboard::getInstance()->clearObjectiveDisplay(slot); }); RemoteCall::exportAs("GMLIB_API", "getAllObjectives", []() -> std::vector { - auto objs = world::Scoreboard::getInstance()->getObjectives(); std::vector result; - for (auto& obj : objs) { + for (auto& obj : gmlib::world::Scoreboard::getInstance()->getObjectives()) { result.push_back(obj->getName()); } return result; }); RemoteCall::exportAs("GMLIB_API", "getAllScoreboardPlayers", []() -> std::vector { - auto uuids = world::Scoreboard::getInstance()->getAllPlayerUuids(); std::vector result; - for (auto& uuid : uuids) { + for (auto& uuid : gmlib::world::Scoreboard::getInstance()->getAllPlayerUuids()) { result.push_back(uuid.asString()); } return result; }); RemoteCall::exportAs("GMLIB_API", "getAllScoreboardFakePlayers", []() -> std::vector { - auto names = world::Scoreboard::getInstance()->getAllFakePlayers(); std::vector result; - for (auto& name : names) { + for (auto& name : gmlib::world::Scoreboard::getInstance()->getAllFakePlayers()) { result.push_back(name); } return result; }); RemoteCall::exportAs("GMLIB_API", "getAllScoreboardEntities", []() -> std::vector { - auto uniqueIds = world::Scoreboard::getInstance()->getAllEntities(); std::vector result; - for (auto& uniqueId : uniqueIds) { + for (auto& uniqueId : gmlib::world::Scoreboard::getInstance()->getAllEntities()) { result.push_back(std::to_string(uniqueId.id)); } return result; @@ -491,63 +413,53 @@ void Export_Compatibility_API() { "getAllTrackedTargets", []() -> std::vector> { std::vector> result; - auto uuids = world::Scoreboard::getInstance()->getAllPlayerUuids(); - for (auto& uuid : uuids) { - std::unordered_map data; - data["Type"] = "Player"; - data["Uuid"] = uuid.asString(); - result.push_back(data); + for (auto& uuid : gmlib::world::Scoreboard::getInstance()->getAllPlayerUuids()) { + result.push_back({ + {"Type", "Player" }, + {"Uuid", uuid.asString()} + }); } - auto names = world::Scoreboard::getInstance()->getAllFakePlayers(); - for (auto& name : names) { - std::unordered_map data; - data["Type"] = "FakePlayer"; - data["Name"] = name; - result.push_back(data); + for (auto& name : gmlib::world::Scoreboard::getInstance()->getAllFakePlayers()) { + result.push_back({ + {"Type", "FakePlayer"}, + {"Name", name } + }); } - auto uniqueIds = world::Scoreboard::getInstance()->getAllEntities(); - for (auto& uniqueId : uniqueIds) { - std::unordered_map data; - data["Type"] = "Entity"; - data["UniqueId"] = std::to_string(uniqueId.id); - result.push_back(data); + for (auto& uniqueId : gmlib::world::Scoreboard::getInstance()->getAllEntities()) { + result.push_back({ + {"Type", "Entity" }, + {"UniqueId", std::to_string(uniqueId.id)} + }); } return result; } ); - RemoteCall::exportAs("GMLIB_API", "getPlayerFromUuid", [](std::string const& uuid) -> ::Player* { + RemoteCall::exportAs("GMLIB_API", "getPlayerFromUuid", [](std::string const& uuid) -> Player* { return ll::service::getLevel()->getPlayer(mce::UUID::fromString(uuid)); }); - RemoteCall::exportAs("GMLIB_API", "getPlayerFromUniqueId", [](std::string const& uniqueId) -> ::Actor* { - auto auid = parseScriptUniqueID(uniqueId); - return ll::service::getLevel()->getPlayer(auid); + RemoteCall::exportAs("GMLIB_API", "getPlayerFromUniqueId", [](std::string const& uniqueId) -> Actor* { + return ll::service::getLevel()->getPlayer(parseScriptUniqueID(uniqueId)); }); - RemoteCall::exportAs("GMLIB_API", "getEntityFromUniqueId", [](std::string const& uniqueId) -> ::Actor* { - auto auid = parseScriptUniqueID(uniqueId); - return ll::service::getLevel()->fetchEntity(auid); + RemoteCall::exportAs("GMLIB_API", "getEntityFromUniqueId", [](std::string const& uniqueId) -> Actor* { + return ll::service::getLevel()->fetchEntity(parseScriptUniqueID(uniqueId)); }); RemoteCall::exportAs("GMLIB_API", "getWorldSpawn", []() -> std::pair { - return {world::Level::getInstance()->getWorldSpawn(), 0}; + return {gmlib::world::Level::getInstance()->getWorldSpawn(), 0}; }); RemoteCall::exportAs("GMLIB_API", "setWorldSpawn", [](std::pair pos) -> bool { - if (pos.second != 0) { - return false; - } - world::Level::getInstance()->setWorldSpawn(pos.first); + if (pos.second != 0) return false; + gmlib::world::Level::getInstance()->setWorldSpawn(pos.first); return true; }); - RemoteCall::exportAs("GMLIB_API", "getPlayerSpawnPoint", [](::Player* pl) -> std::pair { - auto player = (world::Player*)pl; - auto res = player->getSpawnPoint(); + RemoteCall::exportAs("GMLIB_API", "getPlayerSpawnPoint", [](Player* pl) -> std::pair { + auto res = ((gmlib::world::Player*)pl)->getSpawnPoint(); return {res.first, res.second}; }); - RemoteCall::exportAs("GMLIB_API", "setPlayerSpawnPoint", [](::Player* pl, std::pair pos) -> void { - auto player = (world::Player*)pl; - player->setSpawnPoint(pos.first, pos.second); + RemoteCall::exportAs("GMLIB_API", "setPlayerSpawnPoint", [](Player* pl, std::pair pos) -> void { + ((gmlib::world::Player*)pl)->setSpawnPoint(pos.first, pos.second); }); - RemoteCall::exportAs("GMLIB_API", "clearPlayerSpawnPoint", [](::Player* pl) -> void { - auto player = (world::Player*)pl; - player->clearSpawnPoint(); + RemoteCall::exportAs("GMLIB_API", "clearPlayerSpawnPoint", [](Player* pl) -> void { + ((gmlib::world::Player*)pl)->clearSpawnPoint(); }); RemoteCall::exportAs( "GMLIB_API", @@ -560,71 +472,62 @@ void Export_Compatibility_API() { } ); RemoteCall::exportAs("GMLIB_API", "getXuidByUuid", [](std::string const& uuid) -> std::string { - auto uid = mce::UUID::fromString(uuid); - auto result = UserCache::getXuidByUuid(uid); - return result ? result.value() : ""; - }); - RemoteCall::exportAs("GMLIB_API", "getNameByUuid", [](std::string const& uuid) -> std::string { - auto uid = mce::UUID::fromString(uuid); - auto result = UserCache::getNameByUuid(uid); - return result ? result.value() : ""; - }); - RemoteCall::exportAs("GMLIB_API", "getUuidByXuid", [](std::string const& xuid) -> std::string { - auto result = UserCache::getUuidByXuid(xuid); - return result ? result.value().asString() : ""; - }); - RemoteCall::exportAs("GMLIB_API", "getNameByXuid", [](std::string const& xuid) -> std::string { - auto result = UserCache::getNameByXuid(xuid); - return result ? result.value() : ""; + return gmlib::tools::UserCache::getXuidByUuid(mce::UUID::fromString(uuid)).value_or(""); }); RemoteCall::exportAs("GMLIB_API", "getXuidByName", [](std::string const& name) -> std::string { - auto result = UserCache::getXuidByName(name); - return result ? result.value() : ""; + return gmlib::tools::UserCache::getXuidByName(name).value_or(""); + }); + RemoteCall::exportAs("GMLIB_API", "getNameByUuid", [](std::string const& uuid) -> std::string { + return gmlib::tools::UserCache::getNameByUuid(mce::UUID::fromString(uuid)).value_or(""); + }); + RemoteCall::exportAs("GMLIB_API", "getNameByXuid", [](std::string const& xuid) -> std::string { + return gmlib::tools::UserCache::getNameByXuid(xuid).value_or(""); + }); + RemoteCall::exportAs("GMLIB_API", "getUuidByXuid", [](std::string const& xuid) -> std::string { + return gmlib::tools::UserCache::getUuidByXuid(xuid) + .transform([](mce::UUID&& uuid) -> std::string { return uuid.asString(); }) + .value_or(""); }); RemoteCall::exportAs("GMLIB_API", "getUuidByName", [](std::string const& name) -> std::string { - auto result = UserCache::getUuidByName(name); - return result ? result.value().asString() : ""; - }); - RemoteCall::exportAs("GMLIB_API", "getUuidByName", [](std::string const& name) -> std::string { - auto result = UserCache::getUuidByName(name); - return result ? result.value().asString() : ""; + return gmlib::tools::UserCache::getUuidByName(name) + .transform([](mce::UUID&& uuid) -> std::string { return uuid.asString(); }) + .value_or(""); }); RemoteCall::exportAs( "GMLIB_API", "getAllPlayerInfo", []() -> std::vector> { std::vector> result; - UserCache::forEach([&result](const UserCache::UserCacheEntry& entry) { - std::unordered_map info; - info["Name"] = entry.mName; - info["Xuid"] = entry.mXuid; - info["Uuid"] = entry.mUuid.asString(); - result.push_back(info); + gmlib::tools::UserCache::forEach([&result](const gmlib::tools::UserCache::UserCacheEntry& entry) -> void { + result.push_back({ + {"Name", entry.mName }, + {"Xuid", entry.mXuid }, + {"Uuid", entry.mUuid.asString()} + }); }); return result; } ); RemoteCall::exportAs("GMLIB_API", "getBlockRuntimeId", [](std::string const& blockName, short legacyData) -> uint { - if (auto block = Block::tryGetFromRegistry(blockName, legacyData)) { - return block->getRuntimeId(); - } - return 0; + return Block::tryGetFromRegistry(blockName, legacyData) + .transform([](const Block& block) -> uint { return block.getRuntimeId(); }) + .value_or(0); }); RemoteCall::exportAs("GMLIB_API", "getBlockTranslateKey", [](Block const* block) -> std::string { return block->buildDescriptionId(); }); - RemoteCall::exportAs("GMLIB_API", "getItemTranslateKey", [](::ItemStack* item) -> std::string { + RemoteCall::exportAs("GMLIB_API", "getItemTranslateKey", [](ItemStack* item) -> std::string { return item->getDescriptionId(); }); - RemoteCall::exportAs("GMLIB_API", "getEntityTranslateKey", [](::Actor* entity) -> std::string { + RemoteCall::exportAs("GMLIB_API", "getEntityTranslateKey", [](Actor* entity) -> std::string { return entity->getEntityLocNameString(); }); RemoteCall::exportAs( "GMLIB_API", "readNbtFromFile", - [](std::string const& path, bool isBinary) -> std::unique_ptr<::CompoundTag> { - if (auto nbt = world::CompoundTag::readFromFile(path, isBinary)) { - return std::make_unique<::CompoundTag>(nbt.value()); + [](std::string const& path, bool isBinary) -> std::unique_ptr { + if (auto nbt = gmlib::world::CompoundTag::readFromFile(path, isBinary)) { + return std::make_unique(nbt.value()); } return nullptr; } @@ -632,33 +535,33 @@ void Export_Compatibility_API() { RemoteCall::exportAs( "GMLIB_API", "saveNbtToFile", - [](std::string const& path, ::CompoundTag* nbt, bool isBinary) -> bool { - return world::CompoundTag::saveToFile(path, *nbt, isBinary); + [](std::string const& path, CompoundTag* nbt, bool isBinary) -> bool { + return gmlib::world::CompoundTag::saveToFile(path, *nbt, isBinary); } ); RemoteCall::exportAs("GMLIB_API", "getBlockDestroySpeed", [](Block const* block) -> float { return block->getDestroySpeed(); }); - RemoteCall::exportAs("GMLIB_API", "getDestroyBlockSpeed", [](::ItemStack const* item, Block const* block) -> float { + RemoteCall::exportAs("GMLIB_API", "getDestroyBlockSpeed", [](ItemStack const* item, Block const* block) -> float { return item->getDestroySpeed(*block); }); RemoteCall::exportAs( "GMLIB_API", "playerDestroyBlock", - [](Block const* block, std::pair pos, ::Player* player) -> void { + [](Block const* block, std::pair pos, Player* player) -> void { return block->playerDestroy(*player, pos.first); } ); - RemoteCall::exportAs("GMLIB_API", "itemCanDestroyBlock", [](::ItemStack const* item, Block const* block) -> bool { + RemoteCall::exportAs("GMLIB_API", "itemCanDestroyBlock", [](ItemStack const* item, Block const* block) -> bool { return item->canDestroy(block); }); - RemoteCall::exportAs("GMLIB_API", "itemCanDestroyInCreative", [](::ItemStack const* item) -> bool { + RemoteCall::exportAs("GMLIB_API", "itemCanDestroyInCreative", [](ItemStack const* item) -> bool { if (auto itemDef = item->getItem()) { return itemDef->canDestroyInCreative(); } return false; }); - RemoteCall::exportAs("GMLIB_API", "itemCanDestroySpecial", [](::ItemStack const* item, Block const* block) -> bool { + RemoteCall::exportAs("GMLIB_API", "itemCanDestroySpecial", [](ItemStack const* item, Block const* block) -> bool { return item->canDestroySpecial(*block); }); RemoteCall::exportAs("GMLIB_API", "blockCanDropWithAnyTool", [](Block const* block) -> bool { @@ -670,66 +573,68 @@ void Export_Compatibility_API() { RemoteCall::exportAs( "GMLIB_API", "blockPlayerWillDestroy", - [](Block const* block, ::Player* player, std::pair pos) -> bool { + [](Block const* block, Player* player, std::pair pos) -> bool { return block->playerWillDestroy(*player, pos.first); } ); - RemoteCall::exportAs("GMLIB_API", "playerAttack", [](::Player* player, ::Actor* entity) -> bool { + RemoteCall::exportAs("GMLIB_API", "playerAttack", [](Player* player, Actor* entity) -> bool { return player->attack(*entity, ActorDamageCause::EntityAttack); }); - RemoteCall::exportAs("GMLIB_API", "playerPullInEntity", [](::Player* player, ::Actor* entity) -> bool { + RemoteCall::exportAs("GMLIB_API", "playerPullInEntity", [](Player* player, Actor* entity) -> bool { return player->pullInEntity(*entity); }); RemoteCall::exportAs("GMLIB_API", "getBlockTranslateKeyFromName", [](std::string const& blockName) -> std::string { - if (auto block = Block::tryGetFromRegistry(blockName)) { - return block->buildDescriptionId(); - } - return "tile.unknown.name"; + return Block::tryGetFromRegistry(blockName) + .transform([](const Block& block) -> std::string { return block.buildDescriptionId(); }) + .value_or("tile.unknown.name"); }); RemoteCall::exportAs( "GMLIB_API", "getBlockLightEmission", [](std::string const& blockName, short legacyData) -> char { - if (auto block = Block::tryGetFromRegistry(blockName, legacyData)) { - return (char)block->getLightEmission().value; - } - return -1; + return Block::tryGetFromRegistry(blockName) + .transform([](const Block& block) -> char { return (char)block.getLightEmission().value; }) + .value_or(-1); } ); RemoteCall::exportAs( "GMLIB_API", "getGameRules", []() -> std::vector> { - auto gameRules = ll::service::getLevel()->getGameRules().getRules(); std::vector> result; - for (auto& gameRule : gameRules) { - std::unordered_map data; - data["Name"] = gameRule.getName(); + for (auto& gameRule : ll::service::getLevel()->getGameRules().getRules()) { switch (gameRule.getType()) { case GameRule::Type::Bool: - data["Type"] = "Bool"; - data["Value"] = std::to_string(gameRule.getBool()); + result.push_back({ + {"Name", gameRule.getName() }, + {"Type", "Bool" }, + {"Value", std::to_string(gameRule.getBool())} + }); break; case GameRule::Type::Float: - data["Type"] = "Float"; - data["Value"] = std::to_string(gameRule.getFloat()); + result.push_back({ + {"Name", gameRule.getName() }, + {"Type", "Float" }, + {"Value", std::to_string(gameRule.getFloat())} + }); break; case GameRule::Type::Int: - data["Type"] = "Int"; - data["Value"] = std::to_string(gameRule.getInt()); + result.push_back({ + {"Name", gameRule.getName() }, + {"Type", "Int" }, + {"Value", std::to_string(gameRule.getInt())} + }); break; case GameRule::Type::Invalid: break; } - result.push_back(data); } return result; } ); - RemoteCall::exportAs("GMLIB_API", "getLegalEnchants", [](::ItemStack const* item) -> std::vector { - std::vector enchants = EnchantUtils::getLegalEnchants(item->getItem()); + RemoteCall::exportAs("GMLIB_API", "getLegalEnchants", [](ItemStack const* item) -> std::vector { std::vector result; - for (auto& enchant : enchants) { + for (auto& enchant : EnchantUtils::getLegalEnchants(item->getItem())) { result.push_back(Enchant::getEnchant((Enchant::Type)enchant)->getStringId()); } return result; @@ -743,34 +648,24 @@ void Export_Compatibility_API() { RemoteCall::exportAs( "GMLIB_API", "applyEnchant", - [](::ItemStack const* item, std::string const& typeName, int level, bool allowNonVanilla) -> bool { + [](ItemStack* item, std::string const& typeName, int level, bool allowNonVanilla) -> bool { return EnchantUtils::applyEnchant( - *(const_cast<::ItemStack*>(item)), + *item, Enchant::getEnchantTypeFromName(HashedString(typeName)), level, allowNonVanilla ); } ); - RemoteCall::exportAs("GMLIB_API", "removeEnchants", [](::ItemStack const* item) -> void { - EnchantUtils::removeEnchants((::ItemStack&)*item); + RemoteCall::exportAs("GMLIB_API", "removeEnchants", [](ItemStack* item) -> void { + EnchantUtils::removeEnchants(*item); }); - RemoteCall::exportAs("GMLIB_API", "hasEnchant", [](::ItemStack const* item, std::string const& typeName) -> bool { - return EnchantUtils::hasEnchant( - Enchant::getEnchantTypeFromName(HashedString(typeName)), - *(const_cast<::ItemStack*>(item)) - ); + RemoteCall::exportAs("GMLIB_API", "hasEnchant", [](ItemStack* item, std::string const& typeName) -> bool { + return EnchantUtils::hasEnchant(Enchant::getEnchantTypeFromName(HashedString(typeName)), *item); + }); + RemoteCall::exportAs("GMLIB_API", "getEnchantLevel", [](ItemStack* item, std::string const& typeName) -> int { + return EnchantUtils::getEnchantLevel(Enchant::getEnchantTypeFromName(HashedString(typeName)), *item); }); - RemoteCall::exportAs( - "GMLIB_API", - "getEnchantLevel", - [](::ItemStack const* item, std::string const& typeName) -> int { - return EnchantUtils::getEnchantLevel( - Enchant::getEnchantTypeFromName(HashedString(typeName)), - *(const_cast<::ItemStack*>(item)) - ); - } - ); RemoteCall::exportAs( "GMLIB_API", "getEnchantNameAndLevel", @@ -781,44 +676,44 @@ void Export_Compatibility_API() { RemoteCall::exportAs( "GMLIB_API", "dropPlayerItem", - [](::Player* player, ::ItemStack const* item, bool randomly) -> bool { return player->drop(*item, randomly); } + [](Player* player, ItemStack const* item, bool randomly) -> bool { return player->drop(*item, randomly); } ); - RemoteCall::exportAs("GMLIB_API", "getPlayerRuntimeId", [](::Player* player) -> uint64 { + RemoteCall::exportAs("GMLIB_API", "getPlayerRuntimeId", [](Player* player) -> uint64 { return player->getRuntimeID().id; }); - RemoteCall::exportAs("GMLIB_API", "getEntityRuntimeId", [](::Actor* entity) -> uint64 { + RemoteCall::exportAs("GMLIB_API", "getEntityRuntimeId", [](Actor* entity) -> uint64 { return entity->getRuntimeID().id; }); - RemoteCall::exportAs("GMLIB_API", "getEntityNameTag", [](::Actor* entity) -> std::string { + RemoteCall::exportAs("GMLIB_API", "getEntityNameTag", [](Actor* entity) -> std::string { return entity->getNameTag(); }); - RemoteCall::exportAs("GMLIB_API", "ItemisUnbreakable", [](::ItemStack const* item) -> bool { - return ((world::ItemStack*)item)->isUnbreakable(); + RemoteCall::exportAs("GMLIB_API", "ItemisUnbreakable", [](ItemStack const* item) -> bool { + return ((gmlib::world::ItemStack*)item)->isUnbreakable(); }); - RemoteCall::exportAs("GMLIB_API", "setItemUnbreakable", [](::ItemStack const* item, bool value) -> void { - ((world::ItemStack*)item)->setUnbreakable(value); + RemoteCall::exportAs("GMLIB_API", "setItemUnbreakable", [](ItemStack const* item, bool value) -> void { + ((gmlib::world::ItemStack*)item)->setUnbreakable(value); }); - RemoteCall::exportAs("GMLIB_API", "getItemShouldKeepOnDeath", [](::ItemStack const* item) -> bool { - return ((world::ItemStack*)item)->getShouldKeepOnDeath(); + RemoteCall::exportAs("GMLIB_API", "getItemShouldKeepOnDeath", [](ItemStack const* item) -> bool { + return ((gmlib::world::ItemStack*)item)->getShouldKeepOnDeath(); }); - RemoteCall::exportAs("GMLIB_API", "setItemShouldKeepOnDeath", [](::ItemStack const* item, bool value) -> void { - ((world::ItemStack*)item)->setShouldKeepOnDeath(value); + RemoteCall::exportAs("GMLIB_API", "setItemShouldKeepOnDeath", [](ItemStack const* item, bool value) -> void { + ((gmlib::world::ItemStack*)item)->setShouldKeepOnDeath(value); }); - RemoteCall::exportAs("GMLIB_API", "getItemLockMode", [](::ItemStack const* item) -> int { - return (int)((world::ItemStack*)item)->getItemLockMode(); + RemoteCall::exportAs("GMLIB_API", "getItemLockMode", [](ItemStack const* item) -> int { + return (int)((gmlib::world::ItemStack*)item)->getItemLockMode(); }); - RemoteCall::exportAs("GMLIB_API", "setItemLockMode", [](::ItemStack const* item, int value) -> void { - ((world::ItemStack*)item)->setItemLockMode((::ItemLockMode)value); + RemoteCall::exportAs("GMLIB_API", "setItemLockMode", [](ItemStack const* item, int value) -> void { + ((gmlib::world::ItemStack*)item)->setItemLockMode((ItemLockMode)value); }); - RemoteCall::exportAs("GMLIB_API", "getItemRepairCost", [](::ItemStack const* item) -> int { + RemoteCall::exportAs("GMLIB_API", "getItemRepairCost", [](ItemStack const* item) -> int { return item->getBaseRepairCost(); }); - RemoteCall::exportAs("GMLIB_API", "setItemRepairCost", [](::ItemStack const* item, int cost) -> void { - (*(const_cast<::ItemStack*>(item))).setRepairCost(cost); + RemoteCall::exportAs("GMLIB_API", "setItemRepairCost", [](ItemStack* item, int cost) -> void { + (*item).setRepairCost(cost); }); - RemoteCall::exportAs("GMLIB_API", "getItemCanDestroy", [](::ItemStack const* item) -> std::vector { + RemoteCall::exportAs("GMLIB_API", "getItemCanDestroy", [](ItemStack const* item) -> std::vector { std::vector result = {}; - for (auto& block : ((world::ItemStack*)item)->getCanDestroy()) { + for (auto& block : ((gmlib::world::ItemStack*)item)->getCanDestroy()) { result.push_back(block->getTypeName()); } return result; @@ -826,13 +721,13 @@ void Export_Compatibility_API() { RemoteCall::exportAs( "GMLIB_API", "setItemCanDestroy", - [](::ItemStack const* item, std::vector blocks) -> void { - ((world::ItemStack*)item)->setCanDestroy(blocks); + [](ItemStack const* item, std::vector blocks) -> void { + ((gmlib::world::ItemStack*)item)->setCanDestroy(blocks); } ); - RemoteCall::exportAs("GMLIB_API", "getItemCanPlaceOn", [](::ItemStack const* item) -> std::vector { + RemoteCall::exportAs("GMLIB_API", "getItemCanPlaceOn", [](ItemStack const* item) -> std::vector { std::vector result = {}; - for (auto& block : ((world::ItemStack*)item)->getCanPlaceOn()) { + for (auto& block : ((gmlib::world::ItemStack*)item)->getCanPlaceOn()) { result.push_back(block->getTypeName()); } return result; @@ -840,51 +735,47 @@ void Export_Compatibility_API() { RemoteCall::exportAs( "GMLIB_API", "setItemCanPlaceOn", - [](::ItemStack const* item, std::vector blocks) -> void { - ((world::ItemStack*)item)->setCanPlaceOn(blocks); + [](ItemStack const* item, std::vector blocks) -> void { + ((gmlib::world::ItemStack*)item)->setCanPlaceOn(blocks); } ); - RemoteCall::exportAs("GMLIB_API", "getPlayerHungry", [](::Player* player) -> float { - return player->getMutableAttribute(::Player::HUNGER)->getCurrentValue(); + RemoteCall::exportAs("GMLIB_API", "getPlayerHungry", [](Player* player) -> float { + return player->getMutableAttribute(Player::HUNGER)->getCurrentValue(); }); - RemoteCall::exportAs("GMLIB_API", "getPlayerArmorCoverPercentage", [](::Player* player) -> float { + RemoteCall::exportAs("GMLIB_API", "getPlayerArmorCoverPercentage", [](Player* player) -> float { return player->getArmorCoverPercentage(); }); - RemoteCall::exportAs("GMLIB_API", "getPlayerArmorValue", [](::Player* player) -> int { + RemoteCall::exportAs("GMLIB_API", "getPlayerArmorValue", [](Player* player) -> int { return player->getArmorValue(); }); - RemoteCall::exportAs("GMLIB_API", "getEntityOwnerUniqueId", [](::Actor* entity) -> int64 { + RemoteCall::exportAs("GMLIB_API", "getEntityOwnerUniqueId", [](Actor* entity) -> int64 { return entity->getOwnerId().id; }); - RemoteCall::exportAs("GMLIB_API", "getItemCategoryName", [](::ItemStack const* item) -> std::string { + RemoteCall::exportAs("GMLIB_API", "getItemCategoryName", [](ItemStack const* item) -> std::string { return item->getCategoryName(); }); - RemoteCall::exportAs("GMLIB_API", "getItemCustomName", [](::ItemStack const* item) -> std::string { + RemoteCall::exportAs("GMLIB_API", "getItemCustomName", [](ItemStack const* item) -> std::string { return item->getCustomName(); }); - RemoteCall::exportAs("GMLIB_API", "getItemEffecName", [](::ItemStack const* item) -> std::string { + RemoteCall::exportAs("GMLIB_API", "getItemEffecName", [](ItemStack const* item) -> std::string { return item->getEffectName(); }); - RemoteCall::exportAs("GMLIB_API", "itemIsFood", [](::ItemStack const* item) -> bool { + RemoteCall::exportAs("GMLIB_API", "itemIsFood", [](ItemStack const* item) -> bool { if (auto itemDef = item->getItem()) { return itemDef->isFood(); } return false; }); - RemoteCall::exportAs( - "GMLIB_API", - "setPlayerUIItem", - [](::Player* player, int slot, ::ItemStack const* item) -> void { - player->setPlayerUIItem((PlayerUISlot)slot, *item); - } - ); - RemoteCall::exportAs("GMLIB_API", "getPlayerUIItem", [](::Player* player, int slot) -> ::ItemStack* { - return const_cast<::ItemStack*>(&player->getPlayerUIItem((PlayerUISlot)slot)); + RemoteCall::exportAs("GMLIB_API", "setPlayerUIItem", [](Player* player, int slot, ItemStack const* item) -> void { + player->setPlayerUIItem((PlayerUISlot)slot, *item); + }); + RemoteCall::exportAs("GMLIB_API", "getPlayerUIItem", [](Player* player, int slot) -> ItemStack* { + return const_cast(&player->getPlayerUIItem((PlayerUISlot)slot)); }); RemoteCall::exportAs( "GMLIB_API", "sendInventorySlotPacket", - [](::Player* player, int containerId, int slot, ::ItemStack const* item) -> void { + [](Player* player, int containerId, int slot, ItemStack const* item) -> void { InventorySlotPacket((ContainerID)containerId, slot, *item).sendTo(*player); } ); @@ -892,70 +783,66 @@ void Export_Compatibility_API() { return magic_enum::enum_name(container->getContainerType()).data(); }); RemoteCall::exportAs("GMLIB_API", "hasPlayerNbt", [](std::string const& uuid) -> bool { - auto uid = mce::UUID::fromString(uuid); - return world::Player::getPlayerNbt(uid) ? true : false; + return gmlib::world::Player::getPlayerNbt(mce::UUID::fromString(uuid)) != nullptr; }); - RemoteCall::exportAs("GMLIB_API", "getItemMaxCount", [](::ItemStack const* item) -> int { + RemoteCall::exportAs("GMLIB_API", "getItemMaxCount", [](ItemStack const* item) -> int { return item->getMaxStackSize(); }); - RemoteCall::exportAs("GMLIB_API", "entityHasFamily", [](::Actor* entity, std::string const& family) -> bool { + RemoteCall::exportAs("GMLIB_API", "entityHasFamily", [](Actor* entity, std::string const& family) -> bool { return entity->hasFamily(HashedString(family)); }); - RemoteCall::exportAs( - "GMLIB_API", - "getPlayerDestroyBlockProgress", - [](::Player* player, Block const* block) -> float { return player->getDestroyProgress(*block); } - ); - RemoteCall::exportAs("GMLIB_API", "getEntityEffectVisible", [](::Actor* entity, int effectId) -> bool { + RemoteCall::exportAs("GMLIB_API", "getPlayerDestroyBlockProgress", [](Player* player, Block const* block) -> float { + return player->getDestroyProgress(*block); + }); + RemoteCall::exportAs("GMLIB_API", "getEntityEffectVisible", [](Actor* entity, int effectId) -> bool { if (auto effect = entity->getEffect(effectId)) { return effect->mEffectVisible; } return 0; }); - RemoteCall::exportAs("GMLIB_API", "getEntityEffectDuration", [](::Actor* entity, int effectId) -> int { + RemoteCall::exportAs("GMLIB_API", "getEntityEffectDuration", [](Actor* entity, int effectId) -> int { if (auto effect = entity->getEffect(effectId)) { return effect->mDuration; } return 0; }); - RemoteCall::exportAs("GMLIB_API", "getEntityEffectDurationEasy", [](::Actor* entity, int effectId) -> int { + RemoteCall::exportAs("GMLIB_API", "getEntityEffectDurationEasy", [](Actor* entity, int effectId) -> int { if (auto effect = entity->getEffect(effectId)) { return effect->mDurationEasy; } return 0; }); - RemoteCall::exportAs("GMLIB_API", "getEntityEffectDurationHard", [](::Actor* entity, int effectId) -> int { + RemoteCall::exportAs("GMLIB_API", "getEntityEffectDurationHard", [](Actor* entity, int effectId) -> int { if (auto effect = entity->getEffect(effectId)) { return effect->mDurationHard; } return 0; }); - RemoteCall::exportAs("GMLIB_API", "getEntityEffectDurationNormal", [](::Actor* entity, int effectId) -> int { + RemoteCall::exportAs("GMLIB_API", "getEntityEffectDurationNormal", [](Actor* entity, int effectId) -> int { if (auto effect = entity->getEffect(effectId)) { return effect->mDurationNormal; } return 0; }); - RemoteCall::exportAs("GMLIB_API", "getEntityEffectAmplifier", [](::Actor* entity, int effectId) -> int { + RemoteCall::exportAs("GMLIB_API", "getEntityEffectAmplifier", [](Actor* entity, int effectId) -> int { if (auto effect = entity->getEffect(effectId)) { return effect->mAmplifier; } return 0; }); - RemoteCall::exportAs("GMLIB_API", "getEntityEffectAmbient", [](::Actor* entity, int effectId) -> bool { + RemoteCall::exportAs("GMLIB_API", "getEntityEffectAmbient", [](Actor* entity, int effectId) -> bool { if (auto effect = entity->getEffect(effectId)) { return effect->mAmbient; } return 0; }); - RemoteCall::exportAs("GMLIB_API", "entityHasEffect", [](::Actor* entity, int effectId) -> int { + RemoteCall::exportAs("GMLIB_API", "entityHasEffect", [](Actor* entity, int effectId) -> int { return entity->hasEffect(*MobEffect::getById(effectId)); }); RemoteCall::exportAs("GMLIB_API", "getGameDifficulty", []() -> int { - if (auto level = ll::service::getLevel()) { - return (int)level->getDifficulty(); - } - return -1; + return ll::service::getLevel().transform( + [](Level& level) -> int { return (int)level.getDifficulty(); } + ).value_or(-1); }); RemoteCall::exportAs("GMLIB_API", "setGameDifficulty", [](int difficulty) -> void { if (auto level = ll::service::getLevel()) { @@ -963,10 +850,7 @@ void Export_Compatibility_API() { } }); RemoteCall::exportAs("GMLIB_API", "getDefaultGameMode", []() -> int { - if (auto level = ll::service::getLevel()) { - return (int)level->getDefaultGameType(); - } - return -1; + return ll::service::getLevel().transform([](Level& level) -> int { return (int)level.getDefaultGameType(); }).value_or(-1); }); RemoteCall::exportAs("GMLIB_API", "setDefaultGameMode", [](int gameMode) -> void { if (auto level = ll::service::getLevel()) { @@ -976,19 +860,14 @@ void Export_Compatibility_API() { RemoteCall::exportAs( "GMLIB_API", "registerCustomShapelessRecipe", - [](std::string const& recipe_id, std::vector ingredients, ::ItemStack* result) -> void { - auto level = world::Level::getInstance(); - if (!level) { - return; - } + [](std::string const& recipe_id, std::vector ingredients, ItemStack* result) -> void { + if (!gmlib::world::Level::getInstance().has_value()) return; std::vector types; char rt = 'A'; for (auto& ing : ingredients) { - auto key = Recipes::Type(ing, rt, 1, 0); - types.push_back(key); - rt++; + types.emplace_back(ing, rt++, 1, 0); } - recipe::RecipeRegistry::registerShapelessCraftingTableRecipe(recipe_id, types, *result); + gmlib::mod::recipe::RecipeRegistry::registerShapelessCraftingTableRecipe(recipe_id, types, *result); } ); RemoteCall::exportAs( @@ -997,19 +876,14 @@ void Export_Compatibility_API() { [](std::string const& recipe_id, std::vector shape, std::vector ingredients, - ::ItemStack* result) -> void { - auto level = world::Level::getInstance(); - if (!level) { - return; - } + ItemStack* result) -> void { + if (!gmlib::world::Level::getInstance().has_value()) return; std::vector types; char rt = 'A'; for (auto& ing : ingredients) { - auto key = Recipes::Type(ing, rt, 1, 0); - types.push_back(key); - rt++; + types.emplace_back(ing, rt++, 1, 0); } - recipe::RecipeRegistry::registerShapedCraftingTableRecipe(recipe_id, shape, types, *result); + gmlib::mod::recipe::RecipeRegistry::registerShapedCraftingTableRecipe(recipe_id, shape, types, *result); } ); } \ No newline at end of file diff --git a/src/Entry.cpp b/src/Entry.cpp index 1329b8d..fc029ec 100644 --- a/src/Entry.cpp +++ b/src/Entry.cpp @@ -16,11 +16,12 @@ bool LegacyRemoteCallApi::load() { Export_Compatibility_API(); ExportPAPI(); Export_Event_API(); + Export_BinaryStream_API(); Export_Form_API(); logger.info("GMLIB-LegacyRemoteCallApi Loaded!"); logger.info( "Loaded Version: {} with {}", - fmt::format(fg(fmt::color::pink), "GMLIB-" + Version::getLibVersionString()), + fmt::format(fg(fmt::color::pink), "GMLIB-" + gmlib::Version::getLibVersionString()), fmt::format(fg(fmt::color::light_green), "GMLIB-LegacyRemoteCallApi-" + LIB_VERSION.asString()) ); logger.info("Author: GroupMountain"); @@ -34,4 +35,4 @@ bool LegacyRemoteCallApi::disable() { return true; } } // namespace gmlib -LL_REGISTER_MOD(LegacyRemoteCallApi, LegacyRemoteCallApi::getInstance()); +LL_REGISTER_MOD(GMLIB::LegacyRemoteCallApi, GMLIB::LegacyRemoteCallApi::getInstance()); diff --git a/src/EventAPI.cpp b/src/EventAPI.cpp index 6939a0f..50cbb4b 100644 --- a/src/EventAPI.cpp +++ b/src/EventAPI.cpp @@ -1,6 +1,4 @@ #include "Global.h" -#include "ll/api/event/EventBus.h" -#include "mc/world/inventory/network/ItemStackRequestActionTransferBase.h" using namespace ll::hash_utils; class LegacyScriptEventManager { @@ -15,7 +13,7 @@ public: } void emplaceListener(std::string const& scriptEventId, ll::event::ListenerPtr listenerPtr) { - mEventListeners[doHash(scriptEventId)] = listenerPtr; + mEventListeners[doHash(scriptEventId)] = std::move(listenerPtr); } void removeListener(std::string const& scriptEventId) { @@ -72,7 +70,7 @@ void Export_Event_API() { std::string const& clientXuid), (ev.getRealName(), ev.getUuid().asString(), ev.getServerAuthXuid(), ev.getClientAuthXuid()), logger.error("Event \"onClientLogin\" cannot be intercepted"), - ); + ) } case doHash("onWeatherChange"): { REGISTER_EVENT_LISTEN( @@ -80,91 +78,91 @@ void Export_Event_API() { (int lightningLevel, int rainLevel, int lightningLast, int rainLast), (ev.getLightningLevel(), ev.getRainLevel(), ev.getLightningLastTick(), ev.getRainingLastTick()), ev.cancel(), - ); + ) } case doHash("onMobPick"): { REGISTER_EVENT_LISTEN( gmlib::event::entity::MobPickupItemBeforeEvent, - (::Actor * mob, ::Actor * item), - (&ev.self(), (::Actor*)&ev.getItemActor()), + (Actor * mob, Actor * item), + (&ev.self(), (Actor*)&ev.getItemActor()), ev.cancel(), - ); + ) } case doHash("onItemTrySpawn"): { REGISTER_EVENT_LISTEN( gmlib::event::entity::ItemActorSpawnBeforeEvent, - (const ::ItemStack* item, std::pair position, int64 spawnerUniqueId), + (const ItemStack* item, std::pair position, int64 spawnerUniqueId), (&ev.getItem(), {ev.getPosition(), ev.getBlockSource().getDimensionId().id}, ev.getSpawner().has_value() ? ev.getSpawner()->getOrCreateUniqueID().id : -1), ev.cancel(), - ); + ) } case doHash("onItemSpawned"): { REGISTER_EVENT_LISTEN( gmlib::event::entity::ItemActorSpawnAfterEvent, - (const ::ItemStack* item, ::Actor* itemActor, std::pair position, int64 spawnerUniqueId), + (const ItemStack* item, Actor* itemActor, std::pair position, int64 spawnerUniqueId), (&ev.getItem(), - (::Actor*)&ev.getItemActor(), + (Actor*)&ev.getItemActor(), {ev.getPosition(), ev.getBlockSource().getDimensionId().id}, ev.getSpawner().has_value() ? ev.getSpawner()->getOrCreateUniqueID().id : -1), logger.error("Event \"onItemSpawned\" cannot be intercepted"), - ); + ) } case doHash("onEntityTryChangeDim"): { REGISTER_EVENT_LISTEN( gmlib::event::entity::ActorChangeDimensionBeforeEvent, - (::Actor * entity, int toDimId), + (Actor * entity, int toDimId), (&ev.self(), ev.getToDimensionId()), ev.cancel(), - ); + ) } case doHash("onLeaveBed"): { REGISTER_EVENT_LISTEN( gmlib::event::player::PlayerStopSleepBeforeEvent, - (::Player * pl), + (Player * pl), (&ev.self()), ev.cancel(), - ); + ) } case doHash("onDeathMessage"): { REGISTER_EVENT_LISTEN( gmlib::event::entity::DeathMessageAfterEvent, - (std::string const& message, std::vector, ::Actor* dead), + (std::string const& message, std::vector, Actor* dead), (ev.getDeathMessage().first, ev.getDeathMessage().second, &ev.self()), logger.error("Event \"onDeathMessage\" cannot be intercepted"), - ); + ) } case doHash("onMobHurted"): { REGISTER_EVENT_LISTEN( gmlib::event::entity::MobHurtAfterEvent, - (::Actor * mob, ::Actor * source, float damage, int cause), + (Actor * mob, Actor * source, float damage, int cause), (&ev.self(), source, ev.getDamage(), (int)damageSource.getCause()), logger.error("Event \"onMobHurted\" cannot be intercepted"), auto& damageSource = ev.getSource(); - ::Actor* source = nullptr; + Actor* source = nullptr; if (damageSource.isEntitySource()) { auto uniqueId = damageSource.getDamagingEntityUniqueID(); source = ll::service::getLevel()->fetchEntity(uniqueId); if (source->getOwner()) source = source->getOwner(); } - ); + ) } case doHash("onEndermanTake"): { REGISTER_EVENT_LISTEN( gmlib::event::entity::EndermanTakeBlockBeforeEvent, - (::Actor * mob), + (Actor * mob), (&ev.self()), ev.cancel(), - ); + ) } case doHash("onEntityChangeDim"): { REGISTER_EVENT_LISTEN( gmlib::event::entity::ActorChangeDimensionAfterEvent, - (::Actor * mob, int fromDimId), + (Actor * mob, int fromDimId), (&ev.self(), ev.getFromDimensionId()), logger.error("Event \"onEntityChangeDim\" cannot be intercepted"), - ); + ) } case doHash("onDragonRespawn"): { REGISTER_EVENT_LISTEN( @@ -177,18 +175,18 @@ void Export_Event_API() { case doHash("onProjectileTryCreate"): { REGISTER_EVENT_LISTEN( gmlib::event::entity::ProjectileCreateBeforeEvent, - (::Actor * mob, int64 uniqueId), + (Actor * mob, int64 uniqueId), (&ev.self(), ev.getShooter() ? ev.getShooter()->getOrCreateUniqueID().id : -1), ev.cancel(), - ); + ) } case doHash("onProjectileCreate"): { REGISTER_EVENT_LISTEN( gmlib::event::entity::ProjectileCreateAfterEvent, - (::Actor * mob, int64 uniqueId), + (Actor * mob, int64 uniqueId), (&ev.self(), ev.getShooter() ? ev.getShooter()->getOrCreateUniqueID().id : -1), logger.error("Event \"onProjectileCreate\" cannot be intercepted"), - ); + ) } case doHash("onSpawnWanderingTrader"): { REGISTER_EVENT_LISTEN( @@ -196,32 +194,39 @@ void Export_Event_API() { (std::pair pos), ({ev.getPos(), ev.getRegion().getDimensionId()}), ev.cancel(), - ); + ) } case doHash("onHandleRequestAction"): { - REGISTER_EVENT_LISTEN(gmlib::event::player::HandleRequestActionBeforeEvent, - (::Player * player, - std::string const& actionType, - int count, - std::string const& sourceContainerNetId, - int sourceSlot, - std::string const& destinationContainerNetId, - int destinationSlot), - ((::Player*)&ev.self(), - magic_enum::enum_name(requestAction->mActionType).data(), - (int)requestAction->mAmount, - magic_enum::enum_name(requestAction->mSrc.mOpenContainerNetId).data(), - (int)requestAction->mSrc.mSlot, - magic_enum::enum_name(requestAction->mDst.mOpenContainerNetId).data(), - (int)requestAction->mDst.mSlot), - ev.cancel(), - auto requestAction = (ItemStackRequestActionTransferBase*)&ev.getRequestAction(); - ); + // clang-format off + REGISTER_EVENT_LISTEN( + gmlib::event::player::HandleRequestActionBeforeEvent, + ( + Player * player, + std::string const& actionType, + int count, + std::string const& sourceContainerNetId, + int sourceSlot, + std::string const& destinationContainerNetId, + int destinationSlot + ), + ( + (Player*)&ev.self(), + magic_enum::enum_name(requestAction.mActionType).data(), + (int)requestAction.mAmount, + magic_enum::enum_name(requestAction.mSrc.mOpenContainerNetId).data(), + (int)requestAction.mSrc.mSlot, + magic_enum::enum_name(requestAction.mDst.mOpenContainerNetId).data(), + (int)requestAction.mDst.mSlot + ), + ev.cancel(), + auto& requestAction = (ItemStackRequestActionTransferBase&)ev.getRequestAction(); + ) + // clang-format on } case doHash("onSendContainerClosePacket"): { REGISTER_EVENT_LISTEN( - event::packet::ContainerClosePacketSendAfterEvent, - (::Player * player, int ContainerNetId), + gmlib::event::packet::ContainerClosePacketSendAfterEvent, + (Player * player, int ContainerNetId), (ev.getServerNetworkHandler() .getServerPlayer(ev.getNetworkIdentifier(), ev.getPacket().mClientSubId), (int)ev.getPacket().mContainerId), @@ -234,7 +239,7 @@ void Export_Event_API() { (), (), logger.error("Event \"onServerStopping\" cannot be intercepted"), - ); + ) } default: return false; diff --git a/src/FormAPI.cpp b/src/FormAPI.cpp index 88477ba..399f190 100644 --- a/src/FormAPI.cpp +++ b/src/FormAPI.cpp @@ -1,21 +1,18 @@ #include "Global.h" -#include "gmlib/world/Player.h" -using namespace gmlib::form; using namespace ll::hash_utils; class LegacyScriptFormManager { private: int64 mNextFormCallbackId = 0; int64 mNextFormId = 0; - std::unordered_map> mNpcDialogueForms; + std::unordered_map> mNpcDialogueForms; // std::unordered_map> mChestForms; public: - std::string getNextFormCallbackId() { - mNextFormCallbackId++; - return "GMLIB_EVENT_" + std::to_string(mNextFormCallbackId); - } + // std::string getNextFormCallbackId() { + // return "GMLIB_FormApi_" + std::to_string(mNextFormCallbackId++); + // } int64 getNextFormId() { mNextFormId++; @@ -24,7 +21,7 @@ public: int64 createNpcDialogueForm(std::string const& npcName, std::string const& sceneName, std::string const& dialogue) { auto formId = LegacyScriptFormManager::getInstance().getNextFormId(); - auto formPtr = std::make_unique(npcName, sceneName, dialogue); + auto formPtr = std::make_unique(npcName, sceneName, dialogue); mNpcDialogueForms[formId] = std::move(formPtr); return formId; } @@ -37,7 +34,7 @@ public: return false; } - optional_ref getNpcDialogueForm(int64 formId) { + optional_ref getNpcDialogueForm(int64 formId) { if (mNpcDialogueForms.contains(formId)) { return mNpcDialogueForms[formId].get(); } @@ -85,60 +82,20 @@ public: auto const& detector = RemoteCall::importAs("GMLIB_FORM_CALLBACK", detectorId); \ return detector(&pl); \ } else { \ - ServerSettingForm::removeElement(result); \ + gmlib::form::ServerSettingForm::removeElement(result); \ } \ } catch (...) {} \ return false; \ } -#define CALLBACK_TYPE_STRING \ - [callbackId, result](::Player& pl, std::string const& data) { \ +#define CALLBACK_TYPE(type) \ + [callbackId, result](Player& pl, type data) { \ try { \ if (RemoteCall::hasFunc("GMLIB_FORM_CALLBACK", callbackId)) { \ - auto const& callback = \ - RemoteCall::importAs("GMLIB_FORM_CALLBACK", callbackId); \ + auto const& callback = RemoteCall::importAs("GMLIB_FORM_CALLBACK", callbackId); \ callback(&pl, data); \ } else { \ - ServerSettingForm::removeElement(result); \ - } \ - } catch (...) {} \ - } - -#define CALLBACK_TYPE_BOOL \ - [callbackId, result](::Player& pl, bool data) { \ - try { \ - if (RemoteCall::hasFunc("GMLIB_FORM_CALLBACK", callbackId)) { \ - auto const& callback = RemoteCall::importAs("GMLIB_FORM_CALLBACK", callbackId); \ - callback(&pl, data); \ - } else { \ - ServerSettingForm::removeElement(result); \ - } \ - } catch (...) {} \ - } - -#define CALLBACK_TYPE_DOUBLE \ - [callbackId, result](::Player& pl, double data) { \ - try { \ - if (RemoteCall::hasFunc("GMLIB_FORM_CALLBACK", callbackId)) { \ - auto const& callback = \ - RemoteCall::importAs("GMLIB_FORM_CALLBACK", callbackId); \ - callback(&pl, data); \ - } else { \ - ServerSettingForm::removeElement(result); \ - } \ - } catch (...) {} \ - } - - -#define CALLBACK_TYPE_LONG \ - [callbackId, result](::Player& pl, int64 data) { \ - try { \ - if (RemoteCall::hasFunc("GMLIB_FORM_CALLBACK", callbackId)) { \ - auto const& callback = \ - RemoteCall::importAs("GMLIB_FORM_CALLBACK", callbackId); \ - callback(&pl, data); \ - } else { \ - ServerSettingForm::removeElement(result); \ + gmlib::form::ServerSettingForm::removeElement(result); \ } \ } catch (...) {} \ } @@ -156,50 +113,46 @@ public: void Export_Form_API() { //////////////////////////////// Form Manager ///////////////////////////////// - RemoteCall::exportAs("GMLIB_FormAPI", "getNextFormCallbackId", []() -> std::string { - return LegacyScriptFormManager::getInstance().getNextFormCallbackId(); - }); + // RemoteCall::exportAs("GMLIB_FormAPI", "getNextFormCallbackId", []() -> std::string { + // return LegacyScriptFormManager::getInstance().getNextFormCallbackId(); + // }); ////////////////////////////// ServerSettingForm ////////////////////////////// RemoteCall::exportAs("GMLIB_ServerSettingForm", "getDefaultPriority", []() -> int { - return ServerSettingForm::getDefaultPriority(); + return gmlib::form::ServerSettingForm::getDefaultPriority(); }); - RemoteCall::exportAs("GMLIB_ServerSettingForm", "hasTitle", []() -> bool { return ServerSettingForm::hasTitle(); }); + RemoteCall::exportAs("GMLIB_ServerSettingForm", "hasTitle", []() -> bool { return gmlib::form::ServerSettingForm::hasTitle(); }); RemoteCall::exportAs("GMLIB_ServerSettingForm", "getTitle", []() -> std::string { - return ServerSettingForm::getTitle(); + return gmlib::form::ServerSettingForm::getTitle(); }); - RemoteCall::exportAs("GMLIB_ServerSettingForm", "setTitle", [](std::string const& title, bool forceModify) -> bool { - return ServerSettingForm::setTitle(title, forceModify); + RemoteCall::exportAs("GMLIB_gmlib::form::ServerSettingForm", "setTitle", [](std::string const& title, bool forceModify) -> bool { + return gmlib::form::ServerSettingForm::setTitle(title, forceModify); }); - RemoteCall::exportAs("GMLIB_ServerSettingForm", "hasIcon", []() -> bool { return ServerSettingForm::hasIcon(); }); - RemoteCall::exportAs("GMLIB_ServerSettingForm", "getIconData", []() -> std::string { - if (auto data = ServerSettingForm::getIconData()) { - return data.value(); - } - return ""; + RemoteCall::exportAs("GMLIB_gmlib::form::ServerSettingForm", "hasIcon", []() -> bool { return gmlib::form::ServerSettingForm::hasIcon(); }); + RemoteCall::exportAs("GMLIB_gmlib::form::ServerSettingForm", "getIconData", []() -> std::string { + return gmlib::form::ServerSettingForm::getIconData().value_or(""); }); - RemoteCall::exportAs("GMLIB_ServerSettingForm", "getIconType", []() -> int { - if (auto type = ServerSettingForm::getIconType()) { - return (int)type.value(); - } - return -1; + RemoteCall::exportAs("GMLIB_gmlib::form::ServerSettingForm", "getIconType", []() -> int { + return gmlib::form::ServerSettingForm::getIconType() + .transform([](gmlib::form::IconType&& type) -> int { return (int)type; }) + .value_or(-1); }); RemoteCall::exportAs( - "GMLIB_ServerSettingForm", + "GMLIB_gmlib::form::ServerSettingForm", "setIcon", [](std::string const& title, uchar type, bool forceModify) -> bool { - return ServerSettingForm::setIcon(title, IconType(type), forceModify); + return gmlib::form::ServerSettingForm::setIcon(title, gmlib::form::IconType(type), forceModify); } ); RemoteCall::exportAs( - "GMLIB_ServerSettingForm", + "GMLIB_gmlib::form::ServerSettingForm", "addLabel", [](std::string const& text, std::string const& detectorId, int priority) -> uint { - uint result = ServerSettingForm::addLabel(text, PLAYER_DETECROR, priority); + uint result = gmlib::form::ServerSettingForm::addLabel(text, PLAYER_DETECROR, priority); return result; } ); RemoteCall::exportAs( - "GMLIB_ServerSettingForm", + "GMLIB_gmlib::form::ServerSettingForm", "addInput", [](std::string const& text, std::string const& placeholder, @@ -207,11 +160,11 @@ void Export_Form_API() { std::string const& callbackId, std::string const& detectorId, int priority) -> uint { - uint result = ServerSettingForm::addInput( + uint result = gmlib::form::ServerSettingForm::addInput( text, placeholder, defaultVal, - CALLBACK_TYPE_STRING, + CALLBACK_TYPE(std::string const&), PLAYER_DETECROR, priority ); @@ -219,19 +172,19 @@ void Export_Form_API() { } ); RemoteCall::exportAs( - "GMLIB_ServerSettingForm", + "GMLIB_gmlib::form::ServerSettingForm", "addToggle", [](std::string const& text, bool defaultVal, std::string const& callbackId, std::string const& detectorId, int priority) -> uint { - uint result = ServerSettingForm::addToggle(text, defaultVal, CALLBACK_TYPE_BOOL, PLAYER_DETECROR, priority); + uint result = gmlib::form::ServerSettingForm::addToggle(text, defaultVal, CALLBACK_TYPE(bool), PLAYER_DETECROR, priority); return result; } ); RemoteCall::exportAs( - "GMLIB_ServerSettingForm", + "GMLIB_gmlib::form::ServerSettingForm", "addDropdown", [](std::string const& text, std::vector options, @@ -239,11 +192,11 @@ void Export_Form_API() { std::string const& callbackId, std::string const& detectorId, int priority) -> uint { - uint result = ServerSettingForm::addDropdown( + uint result = gmlib::form::ServerSettingForm::addDropdown( text, options, defaultVal, - CALLBACK_TYPE_LONG, + CALLBACK_TYPE(int64), PLAYER_DETECROR, priority ); @@ -251,7 +204,7 @@ void Export_Form_API() { } ); RemoteCall::exportAs( - "GMLIB_ServerSettingForm", + "GMLIB_gmlib::form::ServerSettingForm", "addSlider", [](std::string const& text, double min, @@ -261,13 +214,13 @@ void Export_Form_API() { std::string const& callbackId, std::string const& detectorId, int priority) -> uint { - uint result = ServerSettingForm::addSlider( + uint result = gmlib::form::ServerSettingForm::addSlider( text, min, max, step, defaultVal, - CALLBACK_TYPE_DOUBLE, + CALLBACK_TYPE(double), PLAYER_DETECROR, priority ); @@ -275,7 +228,7 @@ void Export_Form_API() { } ); RemoteCall::exportAs( - "GMLIB_ServerSettingForm", + "GMLIB_gmlib::form::ServerSettingForm", "addStepSlider", [](std::string const& text, std::vector steps, @@ -283,19 +236,19 @@ void Export_Form_API() { std::string const& callbackId, std::string const& detectorId, int priority) -> uint { - uint result = ServerSettingForm::addStepSlider( + uint result = gmlib::form::ServerSettingForm::addStepSlider( text, steps, defaultVal, - CALLBACK_TYPE_LONG, + CALLBACK_TYPE(int64), PLAYER_DETECROR, priority ); return result; } ); - RemoteCall::exportAs("GMLIB_ServerSettingForm", "removeElement", [](uint id) -> bool { - return ServerSettingForm::removeElement(id); + RemoteCall::exportAs("GMLIB_gmlib::form::ServerSettingForm", "removeElement", [](uint id) -> bool { + return gmlib::form::ServerSettingForm::removeElement(id); }); ////////////////////////////// NpcDialogueForm ////////////////////////////// RemoteCall::exportAs( diff --git a/src/Global.h b/src/Global.h index 07da7b7..c522f31 100644 --- a/src/Global.h +++ b/src/Global.h @@ -1,19 +1,15 @@ #pragma once -#include #include -using namespace gmlib; -using namespace world; -using namespace mod; -using namespace tools; +#include #define PLUGIN_NAME fmt::format(fg(fmt::color::light_green), "GMLIB-LRCA") #define LIB_VERSION_MAJOR 0 #define LIB_VERSION_MINOR 13 -#define LIB_VERSION_PATCH 4 +#define LIB_VERSION_PATCH 3 -#define LIB_VERSION Version(LIB_VERSION_MAJOR, LIB_VERSION_MINOR, LIB_VERSION_PATCH) +#define LIB_VERSION gmlib::Version(LIB_VERSION_MAJOR, LIB_VERSION_MINOR, LIB_VERSION_PATCH) extern ll::Logger logger; @@ -22,4 +18,5 @@ extern void Export_Legacy_GMLib_ServerAPI(); extern void Export_Compatibility_API(); extern void ExportPAPI(); extern void Export_Event_API(); -extern void Export_Form_API(); \ No newline at end of file +extern void Export_BinaryStream_API(); +extern void Export_Form_API(); diff --git a/src/LegacyModApi.cpp b/src/LegacyModApi.cpp index 0fefa0d..7c6dbba 100644 --- a/src/LegacyModApi.cpp +++ b/src/LegacyModApi.cpp @@ -3,13 +3,8 @@ std::unordered_set HardCodedKeys = {"AlwaysUnlocked", "PlayerHasManyItems", "PlayerInWater", "None"}; std::variant> makeRecipeUnlockingKey(std::string const& key) { - if (HardCodedKeys.count(key)) { - return key; - } - std::vector result; - auto item = RecipeIngredient(key, 0, 1); - result.emplace_back(item); - return result; + if (HardCodedKeys.count(key)) return key; + return std::vector({RecipeIngredient(key, 0, 1)}); } void Export_Legacy_GMLib_ModAPI() { @@ -22,18 +17,17 @@ void Export_Legacy_GMLib_ModAPI() { std::string const& result, int count, std::string const& unlock) -> void { - auto level = world::Level::getInstance(); - if (!level) { - return; - } + if (!gmlib::world::Level::getInstance().has_value()) return; std::vector types; for (auto ing : ingredients) { - auto key = RecipeIngredient(ing, 0, 1); - types.push_back(key); + types.emplace_back(ing, 0, 1); } - auto res = RecipeIngredient(result, 0, count); - auto unl = makeRecipeUnlockingKey(unlock); - recipe::JsonRecipeRegistry::registerShapelessCraftingTableRecipe(recipe_id, types, res, unl); + gmlib::mod::recipe::JsonRecipeRegistry::registerShapelessCraftingTableRecipe( + recipe_id, + types, + RecipeIngredient(result, 0, count), + makeRecipeUnlockingKey(unlock) + ); } ); RemoteCall::exportAs( @@ -45,18 +39,18 @@ void Export_Legacy_GMLib_ModAPI() { std::string const& result, int count, std::string const& unlock) -> void { - auto level = world::Level::getInstance(); - if (!level) { - return; - } + if (!gmlib::world::Level::getInstance().has_value()) return; std::vector types; for (auto ing : ingredients) { - auto key = RecipeIngredient(ing, 0, 1); - types.push_back(key); + types.push_back(RecipeIngredient(ing, 0, 1)); } - auto res = RecipeIngredient(result, 0, count); - auto unl = makeRecipeUnlockingKey(unlock); - recipe::JsonRecipeRegistry::registerShapedCraftingTableRecipe(recipe_id, shape, types, res, unl); + gmlib::mod::recipe::JsonRecipeRegistry::registerShapedCraftingTableRecipe( + recipe_id, + shape, + types, + RecipeIngredient(result, 0, count), + makeRecipeUnlockingKey(unlock) + ); } ); RemoteCall::exportAs( @@ -66,13 +60,13 @@ void Export_Legacy_GMLib_ModAPI() { std::string const& input, std::string const& output, std::vector tags) -> void { - auto level = world::Level::getInstance(); - if (!level) { - return; - } - auto inp = RecipeIngredient(input, 0, 1); - auto outp = RecipeIngredient(output, 0, 1); - recipe::JsonRecipeRegistry::registerFurnaceRecipe(recipe_id, inp, outp, tags); + if (!gmlib::world::Level::getInstance().has_value()) return; + gmlib::mod::recipe::JsonRecipeRegistry::registerFurnaceRecipe( + recipe_id, + RecipeIngredient(input, 0, 1), + RecipeIngredient(output, 0, 1), + tags + ); } ); RemoteCall::exportAs( @@ -80,12 +74,13 @@ void Export_Legacy_GMLib_ModAPI() { "registerBrewingMixRecipe", [](std::string const& recipe_id, std::string const& input, std::string const& output, std::string const& reagent ) -> void { - auto level = world::Level::getInstance(); - if (!level) { - return; - } - auto rea = RecipeIngredient(reagent, 0, 1); - recipe::JsonRecipeRegistry::registerBrewingMixRecipe(recipe_id, input, output, rea); + if (!gmlib::world::Level::getInstance().has_value()) return; + gmlib::mod::recipe::JsonRecipeRegistry::registerBrewingMixRecipe( + recipe_id, + input, + output, + RecipeIngredient(reagent, 0, 1) + ); } ); RemoteCall::exportAs( @@ -93,14 +88,13 @@ void Export_Legacy_GMLib_ModAPI() { "registerBrewingContainerRecipe", [](std::string const& recipe_id, std::string const& input, std::string const& output, std::string const& reagent ) -> void { - auto level = world::Level::getInstance(); - if (!level) { - return; - } - auto inp = RecipeIngredient(input, 0, 1); - auto outp = RecipeIngredient(output, 0, 1); - auto rea = RecipeIngredient(reagent, 0, 1); - recipe::JsonRecipeRegistry::registerBrewingContainerRecipe(recipe_id, inp, outp, rea); + if (!gmlib::world::Level::getInstance().has_value()) return; + gmlib::mod::recipe::JsonRecipeRegistry::registerBrewingContainerRecipe( + recipe_id, + RecipeIngredient(input, 0, 1), + RecipeIngredient(output, 0, 1), + RecipeIngredient(reagent, 0, 1) + ); } ); RemoteCall::exportAs( @@ -111,11 +105,14 @@ void Export_Legacy_GMLib_ModAPI() { std::string const& base, std::string const& addition, std::string const& result) -> void { - auto level = world::Level::getInstance(); - if (!level) { - return; - } - recipe::JsonRecipeRegistry::registerSmithingTransformRecipe(recipe_id, smithing_template, base, addition, result); + if (!gmlib::world::Level::getInstance().has_value()) return; + gmlib::mod::recipe::JsonRecipeRegistry::registerSmithingTransformRecipe( + recipe_id, + smithing_template, + base, + addition, + result + ); } ); RemoteCall::exportAs( @@ -125,11 +122,13 @@ void Export_Legacy_GMLib_ModAPI() { std::string const& smithing_template, std::string const& base, std::string const& addition) -> void { - auto level = world::Level::getInstance(); - if (!level) { - return; - } - recipe::JsonRecipeRegistry::registerSmithingTrimRecipe(recipe_id, smithing_template, base, addition); + if (!gmlib::world::Level::getInstance().has_value()) return; + gmlib::mod::recipe::JsonRecipeRegistry::registerSmithingTrimRecipe( + recipe_id, + smithing_template, + base, + addition + ); } ); RemoteCall::exportAs( @@ -141,50 +140,49 @@ void Export_Legacy_GMLib_ModAPI() { std::string const& output, int output_data, int output_count) -> void { - auto level = world::Level::getInstance(); - if (!level) { - return; - } - auto inp = RecipeIngredient(input, 0, 1); - auto outp = RecipeIngredient(output, 0, 1); - recipe::JsonRecipeRegistry::registerStoneCutterRecipe(recipe_id, inp, outp); + if (!gmlib::world::Level::getInstance().has_value()) return; + gmlib::mod::recipe::JsonRecipeRegistry::registerStoneCutterRecipe( + recipe_id, + RecipeIngredient(input, 0, 1), + RecipeIngredient(output, 0, 1) + ); } ); // 错误方块清理 RemoteCall::exportAs("GMLib_ModAPI", "setUnknownBlockCleaner", []() -> void { - VanillaFix::setAutoCleanUnknownBlockEnabled(); + gmlib::tools::VanillaFix::setAutoCleanUnknownBlockEnabled(); }); // 实验性 RemoteCall::exportAs("GMLib_ModAPI", "registerExperimentsRequire", [](int experiment_id) -> void { - auto list = world::Level::getAllExperiments(); + auto list = gmlib::world::Level::getAllExperiments(); std::unordered_set set(list.begin(), list.end()); if (set.contains((AllExperiments)experiment_id)) { - world::Level::addExperimentsRequire((AllExperiments)experiment_id); + gmlib::world::Level::addExperimentsRequire((AllExperiments)experiment_id); } else { ll::Logger("Server").error("Experiment ID '{}' does not exist!", experiment_id); } }); RemoteCall::exportAs("GMLib_ModAPI", "setExperimentEnabled", [](int experiment_id, bool value) -> void { - if (world::Level::getInstance()) { - auto list = world::Level::getAllExperiments(); + if (gmlib::world::Level::getInstance()) { + auto list = gmlib::world::Level::getAllExperiments(); std::unordered_set set(list.begin(), list.end()); if (set.contains((AllExperiments)experiment_id)) { - world::Level::getInstance()->setExperimentEnabled(((AllExperiments)experiment_id), value); + gmlib::world::Level::getInstance()->setExperimentEnabled(((AllExperiments)experiment_id), value); } else ll::Logger("Server").error("Experiment ID '{}' does not exist!", experiment_id); } }); RemoteCall::exportAs("GMLib_ModAPI", "getExperimentEnabled", [](int experiment_id) -> bool { - if (world::Level::getInstance()) { - auto list = world::Level::getAllExperiments(); + if (gmlib::world::Level::getInstance()) { + auto list = gmlib::world::Level::getAllExperiments(); std::unordered_set set(list.begin(), list.end()); if (set.contains((AllExperiments)experiment_id)) { - return world::Level::getInstance()->getExperimentEnabled(((AllExperiments)experiment_id)); - } else { - ll::Logger("Server").error("Experiment ID '{}' does not exist!", experiment_id); - return false; + return gmlib::world::Level::getInstance()->getExperimentEnabled(((AllExperiments)experiment_id)); } + ll::Logger("Server").error("Experiment ID '{}' does not exist!", experiment_id); } return false; }); - RemoteCall::exportAs("GMLib_ModAPI", "setFixI18nEnabled", []() -> void { VanillaFix::setFixI18nEnabled(); }); + RemoteCall::exportAs("GMLib_ModAPI", "setFixI18nEnabled", []() -> void { + gmlib::tools::VanillaFix::setFixI18nEnabled(); + }); } \ No newline at end of file diff --git a/src/LegacyServerApi.cpp b/src/LegacyServerApi.cpp index 060e52b..c6ee4e6 100644 --- a/src/LegacyServerApi.cpp +++ b/src/LegacyServerApi.cpp @@ -2,81 +2,78 @@ void Export_Legacy_GMLib_ServerAPI() { RemoteCall::exportAs("GMLib_ServerAPI", "setEducationFeatureEnabled", []() -> void { - world::Level::tryEnableEducationEdition(); + gmlib::world::Level::tryEnableEducationEdition(); }); RemoteCall::exportAs("GMLib_ServerAPI", "registerAbilityCommand", []() -> void { - world::Level::tryRegisterAbilityCommand(); + gmlib::world::Level::tryRegisterAbilityCommand(); }); RemoteCall::exportAs("GMLib_ServerAPI", "setEnableAchievement", []() -> void { - world::Level::setForceAchievementsEnabled(); + gmlib::world::Level::setForceAchievementsEnabled(); + }); + RemoteCall::exportAs("GMLib_ServerAPI", "setForceTrustSkins", []() -> void { + gmlib::world::Level::trustAllSkins(); }); - RemoteCall::exportAs("GMLib_ServerAPI", "setForceTrustSkins", []() -> void { world::Level::trustAllSkins(); }); RemoteCall::exportAs("GMLib_ServerAPI", "enableCoResourcePack", []() -> void { - world::Level::requireServerResourcePackAndAllowClientResourcePack(); + gmlib::world::Level::requireServerResourcePackAndAllowClientResourcePack(); }); RemoteCall::exportAs("GMLib_ServerAPI", "getLevelName", []() -> std::string { - if (auto level = world::Level::getInstance()) { - return level->getLevelName(); - } - return {}; + return gmlib::world::Level::getInstance() + .transform([](gmlib::world::Level& level) -> std::string { return level.getLevelName(); }) + .value_or(""); }); RemoteCall::exportAs("GMLib_ServerAPI", "setLevelName", [](std::string const& name) -> void { - if (auto level = world::Level::getInstance()) { + if (auto level = gmlib::world::Level::getInstance()) { level->setLevelName(name); } }); RemoteCall::exportAs("GMLib_ServerAPI", "getLevelSeed", []() -> std::string { - if (auto level = world::Level::getInstance()) { - return std::to_string(level->getSeed()); - } - return {}; + return gmlib::world::Level::getInstance() + .transform([](gmlib::world::Level& level) -> std::string { return std::to_string(level.getSeed()); }) + .value_or(""); }); RemoteCall::exportAs("GMLib_ServerAPI", "setFakeSeed", [](int64_t seed) -> void { - return world::Level::setFakeSeed(seed); + return gmlib::world::Level::setFakeSeed(seed); }); RemoteCall::exportAs( "GMLib_ServerAPI", "spawnEntity", - [](std::pair pos, std::string const& name) -> ::Actor* { - return world::Spawner::spawnEntity(pos.first, pos.second, name).as_ptr(); + [](std::pair pos, std::string const& name) -> Actor* { + return gmlib::world::Spawner::spawnEntity(pos.first, pos.second, name).as_ptr(); } ); RemoteCall::exportAs( "GMLib_ServerAPI", "shootProjectile", - [](::Actor* owner, std::string const& name, float speed, float offset) -> ::Actor* { - auto ac = (world::Actor*)owner; + [](Actor* owner, std::string const& name, float speed, float offset) -> Actor* { + auto ac = (gmlib::world::Actor*)owner; return ac->shootProjectile(name, speed, offset).as_ptr(); } ); RemoteCall::exportAs( "GMLib_ServerAPI", "throwEntity", - [](::Actor* owner, ::Actor* actor, float speed, float offset) -> bool { - auto ac = (world::Actor*)owner; + [](Actor* owner, Actor* actor, float speed, float offset) -> bool { + auto ac = (gmlib::world::Actor*)owner; return ac->throwEntity(*actor, speed, offset); } ); - RemoteCall::exportAs("GMLib_ServerAPI", "PlayerToEntity", [](::Player* player) -> ::Actor* { - return (::Actor*)player; - }); + RemoteCall::exportAs("GMLib_ServerAPI", "PlayerToEntity", [](Player* player) -> Actor* { return (Actor*)player; }); RemoteCall::exportAs( "GMLib_ServerAPI", "addFakeList", [](const std::string& name, const std::string& xuid) -> bool { - return FakeList::addFakeList(name, xuid, ActorUniqueID(-1)); + return gmlib::tools::FakeList::addFakeList(name, xuid, ActorUniqueID(-1)); } ); RemoteCall::exportAs("GMLib_ServerAPI", "removeFakeList", [](const std::string& nameOrXuid) -> bool { - return FakeList::removeFakeList(nameOrXuid); + return gmlib::tools::FakeList::removeFakeList(nameOrXuid); }); RemoteCall::exportAs("GMLib_ServerAPI", "removeAllFakeList", []() -> void { - return FakeList::removeAllFakeLists(); + return gmlib::tools::FakeList::removeAllFakeLists(); }); RemoteCall::exportAs("GMLib_ServerAPI", "getMaxPlayers", []() -> int { - if (auto level = world::Level::getInstance()) { - return level->getMaxPlayerCount(); - } - return {}; + return gmlib::world::Level::getInstance() + .transform([](gmlib::world::Level& level) -> int { return level.getMaxPlayerCount(); }) + .value_or(0); }); } diff --git a/src/PlaceholderApi.cpp b/src/PlaceholderApi.cpp index 69a487b..6aeab2f 100644 --- a/src/PlaceholderApi.cpp +++ b/src/PlaceholderApi.cpp @@ -13,9 +13,11 @@ bool isParameters(std::string const& str) { return std::regex_search(removeBrackets(str), reg); } -std::string GetValue(std::string const& from) { return PlaceholderAPI::getValue(from); } +std::string GetValue(std::string const& from) { return gmlib::tools::PlaceholderAPI::getValue(from); } -std::string GetValueWithPlayer(std::string const& key, ::Player* player) { return PlaceholderAPI::getValue(key, player); } +std::string GetValueWithPlayer(std::string const& key, Player* player) { + return gmlib::tools::PlaceholderAPI::getValue(key, player); +} bool registerPlayerPlaceholder( std::string const& PluginName, @@ -23,20 +25,24 @@ bool registerPlayerPlaceholder( std::string const& PAPIName ) { if (RemoteCall::hasFunc(PluginName, FuncName)) { - PlaceholderAPI::unregisterPlaceholder(PAPIName); + gmlib::tools::PlaceholderAPI::unregisterPlaceholder(PAPIName); if (isParameters(PAPIName)) { - auto Call = RemoteCall::importAs)>( + auto Call = RemoteCall::importAs)>( PluginName, FuncName ); - PlaceholderAPI::registerPlayerPlaceholder( + gmlib::tools::PlaceholderAPI::registerPlayerPlaceholder( PAPIName, - [Call](::Player* sp, std::unordered_map map) { return Call(sp, map); }, + [Call](Player* sp, std::unordered_map map) { return Call(sp, map); }, PluginName ); } else { - auto Call = RemoteCall::importAs(PluginName, FuncName); - PlaceholderAPI::registerPlayerPlaceholder(PAPIName, [Call](::Player* sp) { return Call(sp); }, PluginName); + auto Call = RemoteCall::importAs(PluginName, FuncName); + gmlib::tools::PlaceholderAPI::registerPlayerPlaceholder( + PAPIName, + [Call](Player* sp) { return Call(sp); }, + PluginName + ); } return true; } @@ -49,18 +55,18 @@ bool registerServerPlaceholder( std::string const& PAPIName ) { if (RemoteCall::hasFunc(PluginName, FuncName)) { - PlaceholderAPI::unregisterPlaceholder(PAPIName); + gmlib::tools::PlaceholderAPI::unregisterPlaceholder(PAPIName); if (isParameters(PAPIName)) { auto Call = RemoteCall::importAs)>(PluginName, FuncName); - PlaceholderAPI::registerServerPlaceholder( + gmlib::tools::PlaceholderAPI::registerServerPlaceholder( PAPIName, [Call](std::unordered_map map) { return Call(map); }, PluginName ); } else { auto Call = RemoteCall::importAs(PluginName, FuncName); - PlaceholderAPI::registerServerPlaceholder(PAPIName, [Call]() { return Call(); }, PluginName); + gmlib::tools::PlaceholderAPI::registerServerPlaceholder(PAPIName, [Call]() { return Call(); }, PluginName); } return true; } @@ -74,13 +80,22 @@ bool registerStaticPlaceholder( int num ) { if (RemoteCall::hasFunc(PluginName, FuncName)) { - PlaceholderAPI::unregisterPlaceholder(PAPIName); + gmlib::tools::PlaceholderAPI::unregisterPlaceholder(PAPIName); if (isParameters(PAPIName)) { auto Call = RemoteCall::importAs(PluginName, FuncName); if (num == -1) { - PlaceholderAPI::registerStaticPlaceholder(PAPIName, [Call] { return Call(); }, PluginName); + gmlib::tools::PlaceholderAPI::registerStaticPlaceholder( + PAPIName, + [Call] { return Call(); }, + PluginName + ); } else { - PlaceholderAPI::registerStaticPlaceholder(PAPIName, num, [Call] { return Call(); }, PluginName); + gmlib::tools::PlaceholderAPI::registerStaticPlaceholder( + PAPIName, + num, + [Call] { return Call(); }, + PluginName + ); } } return true; @@ -88,15 +103,15 @@ bool registerStaticPlaceholder( return false; } -std::string translateStringWithPlayer(std::string const& str, ::Player* pl) { - return PlaceholderAPI::translateString(str, pl); +std::string translateStringWithPlayer(std::string const& str, Player* pl) { + return gmlib::tools::PlaceholderAPI::translateString(str, pl); } -std::string translateString(std::string const& str) { return PlaceholderAPI::translateString(str); } +std::string translateString(std::string const& str) { return gmlib::tools::PlaceholderAPI::translateString(str); } -bool unRegisterPlaceholder(std::string const& str) { return PlaceholderAPI::unregisterPlaceholder(str); } +bool unRegisterPlaceholder(std::string const& str) { return gmlib::tools::PlaceholderAPI::unregisterPlaceholder(str); } -std::vector getAllPAPI() { return PlaceholderAPI::getAllPAPI(); } +std::vector getAllPAPI() { return gmlib::tools::PlaceholderAPI::getAllPAPI(); } } // namespace PAPIRemoteCall