@tendrock/location-id
Version:
A location id lib under Tendrock ecosystem for Minecraft Bedrock Script API
85 lines (84 loc) • 3.25 kB
JavaScript
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
import { world } from "@minecraft/server";
export class LocationUtils {
static isLid(str) {
return /^[one](f\d+|\d+)_(f\d+|\d+)_(f\d+|\d+)$/g.test(str);
}
static getDimensionShortName(dimension) {
switch (dimension.id) {
case "minecraft:overworld":
return 'o';
case "minecraft:nether":
return 'n';
case "minecraft:the_end":
return 'e';
}
return undefined;
}
static toFixed(num, precision = 2, isFixed = true) {
return isFixed ? num.toFixed(precision) : num;
}
static getLocationId(locationOrId, fixed = false) {
if (typeof locationOrId === 'string') {
if (!this.isLocationId(locationOrId)) {
throw new Error(`Invalid location id: ${locationOrId}`);
}
return locationOrId;
}
const { dimension } = locationOrId, location = __rest(locationOrId, ["dimension"]);
const dimensionShortName = this.getDimensionShortName(dimension);
if (!dimensionShortName) {
throw new Error(`Invalid dimension: ${dimension.id}`);
}
return `${dimensionShortName}${this.toFixed(location.x, 2, fixed)}_${this.toFixed(location.y, 2, fixed)}_${this.toFixed(location.z, 2, fixed)}`.replaceAll('-', 'f');
}
static isLocationId(str) {
return /^[one](f\d+|\d+)_(f\d+|\d+)_(f\d+|\d+)$/g.test(str);
}
static idToVector3(lid) {
const lidSub = lid.substring(1);
const lidSplit = lidSub.replaceAll('f', '-').split('_');
return {
x: Number(lidSplit[0]),
y: Number(lidSplit[1]),
z: Number(lidSplit[2])
};
}
static idToDimension(lid) {
if (!this.isLocationId(lid)) {
throw new Error(`Invalid location id: ${lid}`);
}
const dimensionShortName = lid.substring(0, 1);
switch (dimensionShortName) {
case 'o':
return world.getDimension("minecraft:overworld");
case 'n':
return world.getDimension("minecraft:nether");
case 'e':
return world.getDimension("minecraft:the_end");
default:
throw new Error(`Invalid dimension short name: ${dimensionShortName}`);
}
}
static idToDimensionLocation(lid) {
if (!this.isLocationId(lid))
return {};
return Object.assign({ dimension: this.idToDimension(lid) }, this.idToVector3(lid));
}
static getDimensionLocation(locationOrId) {
if (typeof locationOrId === 'string') {
return this.idToDimensionLocation(locationOrId);
}
return locationOrId;
}
}