Archive eaglerforge-injector (tool, 1.8.8, clean-with-notes)
This commit is contained in:
@@ -0,0 +1,444 @@
|
||||
ModAPI.meta.title("AsyncSink");
|
||||
ModAPI.meta.description("Library for patching and hooking into asynchronous filesystem requests for EaglercraftX.");
|
||||
const asyncSinkIcon = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAASCAYAAABWzo5XAAAAAXNSR0IArs4c6QAAAL9JREFUOE9jZGBg+M9ABcAIMsgtPo3hzZ2zYONEVIxJZu9aOIsBbJCRtTHcEJAgLgBSh82ic0fPIgyCKQAJXrx4EcUsfX19sBiIRrYU5gu4Qchew2cQyHSQYehBgdNruFwEcybMZci+gIcRIa+hhxu6LzBiDZvX0A1BDyuivYbLIJK8pqevjze5GlsbMxAdayCT/PQwDRS2gaQror2m36KH4SqjZybwxEl0gsQWRkM01ogpVQh6jaJihBgXEFIDAAIQ9AFDJlrxAAAAAElFTkSuQmCC";
|
||||
ModAPI.meta.icon(asyncSinkIcon);
|
||||
ModAPI.meta.credits("By ZXMushroom63");
|
||||
(function AsyncSinkFn() {
|
||||
const ResourceLocation = ModAPI.reflect.getClassByName("ResourceLocation").constructors.find(x => x.length === 1);
|
||||
//AsyncSink is a plugin to debug and override asynchronous methods in EaglercraftX
|
||||
async function runtimeComponent() {
|
||||
let booleanResult;
|
||||
|
||||
if (ModAPI.is_1_12) {
|
||||
const _boolRes = ModAPI.reflect.getClassById("net.lax1dude.eaglercraft.internal.teavm.BooleanResult").constructors[0];
|
||||
booleanResult = (b) => _boolRes(b * 1);
|
||||
} else {
|
||||
booleanResult = (b) => ModAPI.hooks.methods.nlevit_BooleanResult__new(b * 1);
|
||||
}
|
||||
|
||||
const wrap = ModAPI.hooks.methods.otji_JSWrapper_wrap;
|
||||
const unwrap = ModAPI.hooks.methods.otji_JSWrapper_unwrap;
|
||||
function getAsyncHandlerName(name) {
|
||||
var suffix = `$AsyncHandlers_${name}$_asyncCall_$`;
|
||||
return ModAPI.hooks._rippedMethodKeys.find(x => x.endsWith(suffix));
|
||||
}
|
||||
var fs_debugging = false;
|
||||
const encoder = new TextEncoder('utf-8');
|
||||
var filesystemPlatform = (ModAPI.hooks.methods.nlevit_IndexedDBFilesystem$AsyncHandlers_readWholeFile || ModAPI.hooks.methods.nleit_IndexedDBFilesystem$AsyncHandlers_readWholeFile) ? true : false;
|
||||
if (!filesystemPlatform) {
|
||||
console.warn("AsyncSink requires EaglercraftX u37 or greater to work! Attempting to run anyway...");
|
||||
}
|
||||
const AsyncSink = {};
|
||||
const originalSuspend = ModAPI.hooks.TeaVMThread.prototype.suspend;
|
||||
AsyncSink.startDebugging = function hookIntoSuspend() {
|
||||
ModAPI.hooks.TeaVMThread.prototype.suspend = function suspend(...args) {
|
||||
console.log("[AsyncSink] Context suspended! Callback: ", args[0]);
|
||||
return originalSuspend.apply(this, args);
|
||||
}
|
||||
}
|
||||
AsyncSink.stopDebugging = function unhookFromSuspend() {
|
||||
ModAPI.hooks.TeaVMThread.prototype.suspend = originalSuspend;
|
||||
}
|
||||
|
||||
AsyncSink.startDebuggingFS = function hookIntoSuspend() {
|
||||
fs_debugging = true;
|
||||
}
|
||||
AsyncSink.stopDebuggingFS = function unhookFromSuspend() {
|
||||
fs_debugging = false;
|
||||
}
|
||||
|
||||
// @type Map<string, ArrayBuffer>
|
||||
AsyncSink.FS = new Map();
|
||||
AsyncSink.L10N = new Map();
|
||||
AsyncSink.FSOverride = new Set();
|
||||
AsyncSink.MIDDLEWARE = [];
|
||||
|
||||
//takes in a ResourceLocation and removes cached data. Use to only reload a specific texture if you know where it is stored.
|
||||
AsyncSink.clearResourcePointer = function clearResourcePointer(resourceLocation) {
|
||||
if (!resourceLocation) {
|
||||
return;
|
||||
}
|
||||
var res = ModAPI.util.wrap((resourceLocation.isModProxy === true) ? resourceLocation.getRef() : resourceLocation);
|
||||
res.cachedPointer = null;
|
||||
res.cachedPointerType = 0;
|
||||
ModAPI.mc.getTextureManager().mapTextureObjects.remove(res.getRef());
|
||||
}
|
||||
AsyncSink.setFile = function setFile(path, data) {
|
||||
if (typeof data === "string") {
|
||||
data = encoder.encode(data).buffer;
|
||||
}
|
||||
AsyncSink.FSOverride.add(path);
|
||||
AsyncSink.FS.set(path, data);
|
||||
return true;
|
||||
}
|
||||
|
||||
AsyncSink.deleteFile = function deleteFile(path) {
|
||||
AsyncSink.FSOverride.delete(path);
|
||||
AsyncSink.FS.delete(path);
|
||||
return true;
|
||||
}
|
||||
|
||||
AsyncSink.hideFile = function hideFile(path) {
|
||||
AsyncSink.FSOverride.add(path);
|
||||
AsyncSink.FS.delete(path);
|
||||
return true;
|
||||
}
|
||||
|
||||
AsyncSink.getFile = function getFile(path) {
|
||||
return AsyncSink.FS.get(path) || new ArrayBuffer(0);
|
||||
}
|
||||
|
||||
AsyncSink.fileExists = function fileExists(path) {
|
||||
return AsyncSink.FS.has(path);
|
||||
}
|
||||
|
||||
var readWholeFileName = getAsyncHandlerName("readWholeFile");
|
||||
var writeWholeFileName = getAsyncHandlerName("writeWholeFile");
|
||||
var deleteFileName = getAsyncHandlerName("deleteFile");
|
||||
var fileExistsName = getAsyncHandlerName("fileExists");
|
||||
|
||||
const originalReadWholeFile = ModAPI.hooks.methods[readWholeFileName];
|
||||
ModAPI.hooks.methods[readWholeFileName] = function (...args) {
|
||||
if (fs_debugging) {
|
||||
console.log("[AsynkSinkFS] File read request sent: " + ModAPI.util.ustr(args[1]));
|
||||
}
|
||||
if (AsyncSink.FSOverride.has(ModAPI.util.ustr(args[1]))) {
|
||||
if (fs_debugging) {
|
||||
console.log("[AsynkSinkFS] Replied with copy from fake filesystem.");
|
||||
}
|
||||
return wrap(AsyncSink.getFile(ModAPI.util.ustr(args[1])));
|
||||
}
|
||||
var ev = { method: "read", file: ModAPI.util.ustr(args[1]), shim: false, shimOutput: new ArrayBuffer() };
|
||||
AsyncSink.MIDDLEWARE.forEach((fn) => { fn(ev) });
|
||||
if (ev.shim) {
|
||||
return wrap(ev.shimOutput);
|
||||
}
|
||||
return originalReadWholeFile.apply(this, args);
|
||||
};
|
||||
|
||||
const originalWriteWholeFile = ModAPI.hooks.methods[writeWholeFileName];
|
||||
ModAPI.hooks.methods[writeWholeFileName] = function (...args) {
|
||||
if (fs_debugging) {
|
||||
console.log("[AsynkSinkFS] File write request sent: " + ModAPI.util.ustr(args[1]), args[2]);
|
||||
}
|
||||
if (AsyncSink.FSOverride.has(ModAPI.util.ustr(args[1]))) {
|
||||
if (fs_debugging) {
|
||||
console.log("[AsynkSinkFS] Writing to fake filesystem.");
|
||||
}
|
||||
AsyncSink.setFile(ModAPI.util.ustr(args[1]), args[2]);
|
||||
return booleanResult(true);
|
||||
}
|
||||
var ev = { method: "write", file: ModAPI.util.ustr(args[1]), data: args[2], shim: false, shimOutput: true };
|
||||
AsyncSink.MIDDLEWARE.forEach((fn) => { fn(ev) });
|
||||
if (ev.shim) {
|
||||
return booleanResult(ev.shimOutput);
|
||||
}
|
||||
return originalWriteWholeFile.apply(this, args);
|
||||
};
|
||||
|
||||
const originalDeleteFile = ModAPI.hooks.methods[deleteFileName];
|
||||
ModAPI.hooks.methods[deleteFileName] = function (...args) {
|
||||
if (fs_debugging) {
|
||||
console.log("[AsynkSinkFS] File delete request sent: " + ModAPI.util.ustr(args[1]));
|
||||
}
|
||||
if (AsyncSink.FSOverride.has(ModAPI.util.ustr(args[1]))) {
|
||||
if (fs_debugging) {
|
||||
console.log("[AsynkSinkFS] Deleting entry from fake filesystem.");
|
||||
}
|
||||
AsyncSink.deleteFile(ModAPI.util.ustr(args[1]));
|
||||
return booleanResult(true);
|
||||
}
|
||||
var ev = { method: "delete", file: ModAPI.util.ustr(args[1]), shim: false, shimOutput: true };
|
||||
AsyncSink.MIDDLEWARE.forEach((fn) => { fn(ev) });
|
||||
if (ev.shim) {
|
||||
return booleanResult(ev.shimOutput);
|
||||
}
|
||||
return originalDeleteFile.apply(this, args);
|
||||
};
|
||||
|
||||
const originalFileExists = ModAPI.hooks.methods[fileExistsName];
|
||||
ModAPI.hooks.methods[fileExistsName] = function (...args) {
|
||||
if (fs_debugging) {
|
||||
console.log("[AsynkSinkFS] File exists request sent: " + ModAPI.util.ustr(args[1]));
|
||||
}
|
||||
if (AsyncSink.FSOverride.has(ModAPI.util.ustr(args[1]))) {
|
||||
if (fs_debugging) {
|
||||
console.log("[AsynkSinkFS] Replying with information from fake filesystem.");
|
||||
}
|
||||
var result = AsyncSink.fileExists(ModAPI.util.ustr(args[1]));
|
||||
return booleanResult(result);
|
||||
}
|
||||
var ev = { method: "exists", file: ModAPI.util.ustr(args[1]), shim: false, shimOutput: true };
|
||||
AsyncSink.MIDDLEWARE.forEach((fn) => { fn(ev) });
|
||||
if (ev.shim) {
|
||||
return booleanResult(ev.shimOutput);
|
||||
}
|
||||
return originalFileExists.apply(this, args);
|
||||
};
|
||||
|
||||
const L10NRead = ModAPI.util.getMethodFromPackage("net.minecraft.util.StatCollector", "translateToLocal");
|
||||
const originalL10NRead = ModAPI.hooks.methods[L10NRead];
|
||||
ModAPI.hooks.methods[L10NRead] = function (...args) {
|
||||
var key = ModAPI.util.ustr(args[0]);
|
||||
if (AsyncSink.L10N.has(key)) {
|
||||
return ModAPI.util.str(AsyncSink.L10N.get(key));
|
||||
}
|
||||
return originalL10NRead.apply(this, args);
|
||||
};
|
||||
|
||||
const L18NFormat = ModAPI.util.getMethodFromPackage("net.minecraft.client.resources.I18n", "format");
|
||||
const originalL18NFormat = ModAPI.hooks.methods[L18NFormat];
|
||||
ModAPI.hooks.methods[L18NFormat] = function (...args) {
|
||||
var key = ModAPI.util.ustr(args[0]);
|
||||
if (AsyncSink.L10N.has(key)) {
|
||||
args[0] = ModAPI.util.str(AsyncSink.L10N.get(key));
|
||||
}
|
||||
return originalL18NFormat.apply(this, args);
|
||||
};
|
||||
|
||||
const LanguageMapTranslate = ModAPI.util.getMethodFromPackage("net.minecraft.util.text.translation.LanguageMap", "tryTranslateKey");
|
||||
const originalLanguageMapTranslate = ModAPI.hooks.methods[LanguageMapTranslate];
|
||||
ModAPI.hooks.methods[LanguageMapTranslate] = function (...args) {
|
||||
var key = ModAPI.util.ustr(args[1]);
|
||||
if (AsyncSink.L10N.has(key)) {
|
||||
args[1] = ModAPI.util.str(AsyncSink.L10N.get(key));
|
||||
}
|
||||
return originalLanguageMapTranslate.apply(this, args);
|
||||
};
|
||||
|
||||
const LanguageMapCheckTranslate = ModAPI.util.getMethodFromPackage("net.minecraft.util.text.translation.LanguageMap", "isKeyTranslated");
|
||||
const originalLanguageMapCheckTranslate = ModAPI.hooks.methods[LanguageMapCheckTranslate];
|
||||
ModAPI.hooks.methods[LanguageMapCheckTranslate] = function (...args) {
|
||||
var key = ModAPI.util.ustr(args[1]);
|
||||
if (AsyncSink.L10N.has(key)) {
|
||||
return 1;
|
||||
}
|
||||
return originalLanguageMapTranslate.apply(this, args);
|
||||
};
|
||||
|
||||
const L10NCheck = ModAPI.util.getMethodFromPackage("net.minecraft.util.StatCollector", "canTranslate");
|
||||
const originalL10NCheck = ModAPI.hooks.methods[L10NCheck];
|
||||
ModAPI.hooks.methods[L10NCheck] = function (...args) {
|
||||
if (AsyncSink.L10N.has(ModAPI.util.ustr(args[0]))) {
|
||||
return 1;
|
||||
}
|
||||
return originalL10NCheck.apply(this, args);
|
||||
};
|
||||
|
||||
globalThis.AsyncSink = AsyncSink;
|
||||
ModAPI.events.newEvent("lib:asyncsink");
|
||||
ModAPI.events.callEvent("lib:asyncsink", {});
|
||||
console.log("[AsyncSink] Loaded!");
|
||||
}
|
||||
runtimeComponent();
|
||||
ModAPI.dedicatedServer.appendCode(runtimeComponent);
|
||||
|
||||
|
||||
async function assureAsyncSinkResources() {
|
||||
const dec = new TextDecoder("utf-8");
|
||||
const enc = new TextEncoder("utf-8");
|
||||
var resourcePackKey = ModAPI.is_1_12 ? "_net_lax1dude_eaglercraft_v1_8_internal_PlatformFilesystem_1_12_2_" : (await indexedDB.databases()).find(x => x?.name?.endsWith("_resourcePacks")).name;
|
||||
const dbRequest = indexedDB.open(resourcePackKey);
|
||||
const db = await promisifyIDBRequest(dbRequest);
|
||||
const transaction = db.transaction(["filesystem"], "readonly");
|
||||
const objectStore = transaction.objectStore("filesystem");
|
||||
var object = (await promisifyIDBRequest(objectStore.get(["resourcepacks/manifest.json"])))?.data;
|
||||
var resourcePackList = object ? JSON.parse(dec.decode(object)) : { resourcePacks: [] };
|
||||
var pack = {
|
||||
domains: ["minecraft", "eagler"],
|
||||
folder: "AsyncSinkLib",
|
||||
name: "AsyncSinkLib",
|
||||
timestamp: Date.now()
|
||||
};
|
||||
if (!Array.isArray(resourcePackList.resourcePacks)) {
|
||||
resourcePackList.resourcePacks = [];
|
||||
}
|
||||
if (resourcePackList.resourcePacks.find(x => x.name === "AsyncSinkLib")) {
|
||||
var idx = resourcePackList.resourcePacks.indexOf(resourcePackList.resourcePacks.find(x => x.name === "AsyncSinkLib"));
|
||||
resourcePackList.resourcePacks[idx] = pack;
|
||||
} else {
|
||||
resourcePackList.resourcePacks.push(pack);
|
||||
}
|
||||
|
||||
const writeableTransaction = db.transaction(["filesystem"], "readwrite");
|
||||
const writeableObjectStore = writeableTransaction.objectStore("filesystem");
|
||||
await promisifyIDBRequest(writeableObjectStore.put({
|
||||
path: "resourcepacks/manifest.json",
|
||||
data: enc.encode(JSON.stringify(resourcePackList)).buffer
|
||||
}));
|
||||
await promisifyIDBRequest(writeableObjectStore.put({
|
||||
path: "resourcepacks/AsyncSinkLib/pack.mcmeta",
|
||||
data: enc.encode(JSON.stringify({
|
||||
"pack": {
|
||||
"pack_format": ModAPI.is_1_12 ? 3 : 1,
|
||||
"description": "AsyncSink Library Resources"
|
||||
}
|
||||
})).buffer
|
||||
}));
|
||||
|
||||
var icon = {
|
||||
path: "resourcepacks/AsyncSinkLib/pack.png",
|
||||
data: await (await fetch(asyncSinkIcon)).arrayBuffer()
|
||||
};
|
||||
|
||||
const imageTransaction = db.transaction(["filesystem"], "readwrite");
|
||||
const imageObjectStore = imageTransaction.objectStore("filesystem");
|
||||
|
||||
await promisifyIDBRequest(imageObjectStore.put(icon));
|
||||
}
|
||||
|
||||
// Client side reminders to enable the AsyncSink Resource Pack
|
||||
var asyncSinkInstallStatus = false;
|
||||
var installMessage = document.createElement("span");
|
||||
installMessage.innerText = "Please enable the AsyncSink resource pack\nIn game, use the .reload_tex command to load textures for modded blocks and items.";
|
||||
installMessage.style = "background-color: rgba(0,0,0,0.7); color: red; position: fixed; top: 0; left: 0; font-family: sans-serif; pointer-events: none; user-select: none;";
|
||||
document.body.appendChild(installMessage);
|
||||
|
||||
assureAsyncSinkResources();
|
||||
setInterval(() => {
|
||||
var resourcePackEntries = ModAPI.mc.mcResourcePackRepository.getRepositoryEntries().getCorrective();
|
||||
var array = resourcePackEntries.array || [resourcePackEntries.element];
|
||||
asyncSinkInstallStatus = array.find(x => ModAPI.util.ustr(x.reResourcePack.resourcePackFile.getRef()) === "AsyncSinkLib") ? true : false;
|
||||
//assureAsyncSinkResources();
|
||||
if (asyncSinkInstallStatus) {
|
||||
installMessage.style.display = "none";
|
||||
} else {
|
||||
installMessage.style.display = "initial";
|
||||
}
|
||||
}, 8000);
|
||||
ModAPI.events.newEvent("custom:asyncsink_reloaded");
|
||||
ModAPI.addEventListener("sendchatmessage", (e) => {
|
||||
if (e.message.toLowerCase().startsWith(".reload_tex")) {
|
||||
e.preventDefault = true;
|
||||
ModAPI.mc.renderItem.itemModelMesher.simpleShapesCache.clear();
|
||||
ModAPI.promisify(ModAPI.mc.refreshResources)().then(() => {
|
||||
ModAPI.events.callEvent("custom:asyncsink_reloaded", {});
|
||||
ModAPI.events.callEvent("lib:asyncsink:registeritems", ModAPI.mc.renderItem);
|
||||
});
|
||||
}
|
||||
});
|
||||
ModAPI.events.newEvent("lib:asyncsink:registeritems");
|
||||
const regItemsName = ModAPI.util.getMethodFromPackage("net.minecraft.client.renderer.entity.RenderItem", "registerItems");
|
||||
const oldRegisterItems = ModAPI.hooks.methods[regItemsName];
|
||||
ModAPI.hooks.methods[regItemsName] = function (...args) {
|
||||
oldRegisterItems.apply(this, args);
|
||||
ModAPI.events.callEvent("lib:asyncsink:registeritems", ModAPI.util.wrap(args[0]));
|
||||
}
|
||||
|
||||
AsyncSink.Audio = {};
|
||||
AsyncSink.Audio.Category = ModAPI.reflect.getClassByName("SoundCategory").staticVariables;
|
||||
AsyncSink.Audio.Objects = [];
|
||||
const SoundHandler_onResourceManagerReload = ModAPI.hooks.methods[ModAPI.util.getMethodFromPackage("net.minecraft.client.audio.SoundHandler", "onResourceManagerReload")];
|
||||
ModAPI.hooks.methods[ModAPI.util.getMethodFromPackage("net.minecraft.client.audio.SoundHandler", "onResourceManagerReload")] = function (...args) {
|
||||
SoundHandler_onResourceManagerReload.apply(this, args);
|
||||
if (ModAPI.util.isCritical()) {
|
||||
return;
|
||||
}
|
||||
var snd = ModAPI.mc.mcSoundHandler;
|
||||
var registry = (snd.sndRegistry || snd.soundRegistry).getCorrective().soundRegistry;
|
||||
console.log("[AsyncSink] Populating sound registry hash map with " + AsyncSink.Audio.Objects.length + " sound effects.");
|
||||
AsyncSink.Audio.Objects.forEach(pair => {
|
||||
registry.put(pair[0], pair[1]);
|
||||
});
|
||||
}
|
||||
|
||||
// key = "mob.entity.say"
|
||||
// values = SoundEntry[]
|
||||
// category: AsyncSink.Audio.Category.*
|
||||
// SoundEntry = {path: String, pitch: 1, volume: 1, streaming: false}
|
||||
const EaglercraftRandom = ModAPI.reflect.getClassByName("EaglercraftRandom").constructors.find(x => x.length === 0);
|
||||
|
||||
function makeSoundEventAccessor(soundpoolentry, weight) {
|
||||
const SoundEventAccessorClass = ModAPI.reflect.getClassByName("SoundEventAccessor").class;
|
||||
var object = new SoundEventAccessorClass;
|
||||
var wrapped = ModAPI.util.wrap(object).getCorrective();
|
||||
wrapped.entry = soundpoolentry;
|
||||
wrapped.weight = weight;
|
||||
return object;
|
||||
}
|
||||
|
||||
function makeSoundEventAccessorComposite(rKey, pitch, volume, category) {
|
||||
const SoundEventAccessorCompositeClass = ModAPI.reflect.getClassByName("SoundEventAccessorComposite").class;
|
||||
var object = new SoundEventAccessorCompositeClass;
|
||||
var wrapped = ModAPI.util.wrap(object).getCorrective();
|
||||
wrapped.soundLocation = rKey;
|
||||
wrapped.eventPitch = pitch;
|
||||
wrapped.eventVolume = volume;
|
||||
wrapped.category = category;
|
||||
wrapped.soundPool = ModAPI.hooks.methods.cgcc_Lists_newArrayList1();
|
||||
wrapped.rnd = EaglercraftRandom();
|
||||
return object;
|
||||
}
|
||||
function makeSoundEventAccessor112(rKey, subttl) {
|
||||
const SoundEventAccessorClass = ModAPI.reflect.getClassByName("SoundEventAccessor").class;
|
||||
var object = new SoundEventAccessorClass;
|
||||
var wrapped = ModAPI.util.wrap(object).getCorrective();
|
||||
wrapped.location = rKey;
|
||||
wrapped.subtitle = ModAPI.util.str(subttl);
|
||||
wrapped.accessorList = ModAPI.hooks.methods.cgcc_Lists_newArrayList0();
|
||||
wrapped.rnd = EaglercraftRandom();
|
||||
return object;
|
||||
}
|
||||
if (ModAPI.is_1_12) {
|
||||
const soundType = ModAPI.reflect.getClassById("net.minecraft.client.audio.Sound$Type").staticVariables.FILE;
|
||||
const mkSound = ModAPI.reflect.getClassById("net.minecraft.client.audio.Sound").constructors[0];
|
||||
const SoundEvent = ModAPI.reflect.getClassById("net.minecraft.util.SoundEvent");
|
||||
const SoundEvents = ModAPI.reflect.getClassById("net.minecraft.init.SoundEvents");
|
||||
|
||||
AsyncSink.Audio.register = function addSfx(key, unused, values, subtitle) {
|
||||
subtitle ||= "(AsyncSink Sound)";
|
||||
if (unused) {
|
||||
console.log("Category is not a property of the sound in 1.12, category for " + key + " will be unused.");
|
||||
}
|
||||
|
||||
const rKey = ResourceLocation(ModAPI.util.str(key));
|
||||
|
||||
const ev = new SoundEvent.class;
|
||||
ev.$soundName = rKey;
|
||||
ModAPI.util.wrap(SoundEvent.staticVariables.REGISTRY).register(ModAPI.keygen.sound(key), rKey, ev);
|
||||
const outObj = SoundEvents.staticMethods.getRegisteredSoundEvent.method(ModAPI.util.str(key));
|
||||
|
||||
var snd = ModAPI.mc.mcSoundHandler.getCorrective();
|
||||
var registry = snd.soundRegistry.soundRegistry;
|
||||
|
||||
|
||||
var soundPool = values.map(se => {
|
||||
return mkSound(ModAPI.util.str(se.path.replace("sounds/", "").replace(".ogg", "")), se.volume, se.pitch, 1, soundType, 1 * se.streaming);
|
||||
});
|
||||
var eventAccessor = makeSoundEventAccessor112(rKey, subtitle);
|
||||
var eventAccessorWrapped = ModAPI.util.wrap(eventAccessor);
|
||||
soundPool.forEach(sound => {
|
||||
eventAccessorWrapped.accessorList.add(sound);
|
||||
});
|
||||
AsyncSink.Audio.Objects.push([rKey, eventAccessor]);
|
||||
registry.put(rKey, eventAccessor);
|
||||
values.map(x => "resourcepacks/AsyncSinkLib/assets/minecraft/" + x.path + ".mcmeta").forEach(x => AsyncSink.setFile(x, new ArrayBuffer(0)));
|
||||
return outObj;
|
||||
}
|
||||
} else {
|
||||
const SoundPoolEntry = ModAPI.reflect.getClassByName("SoundPoolEntry").constructors.find(x => x.length === 4);
|
||||
AsyncSink.Audio.register = function addSfx(key, category, values) {
|
||||
if (!category) {
|
||||
throw new Error("[AsyncSink] Invalid audio category provided: " + category);
|
||||
}
|
||||
var snd = ModAPI.mc.mcSoundHandler;
|
||||
var registry = snd.sndRegistry.soundRegistry;
|
||||
var rKey = ResourceLocation(ModAPI.util.str(key));
|
||||
var soundPool = values.map(se => {
|
||||
var path = ResourceLocation(ModAPI.util.str(se.path));
|
||||
return SoundPoolEntry(path, se.pitch, se.volume, 1 * se.streaming);
|
||||
}).map(spe => {
|
||||
return makeSoundEventAccessor(spe, 1); // 1 = weight
|
||||
});
|
||||
var compositeSound = makeSoundEventAccessorComposite(rKey, 1, 1, category);
|
||||
var compositeSoundWrapped = ModAPI.util.wrap(compositeSound);
|
||||
soundPool.forEach(sound => {
|
||||
compositeSoundWrapped.soundPool.add(sound);
|
||||
});
|
||||
AsyncSink.Audio.Objects.push([rKey, compositeSound]);
|
||||
registry.put(rKey, compositeSound);
|
||||
values.map(x => "resourcepacks/AsyncSinkLib/assets/minecraft/" + x.path + ".mcmeta").forEach(x => AsyncSink.setFile(x, new ArrayBuffer(0)));
|
||||
return soundPool;
|
||||
}
|
||||
}
|
||||
})();
|
||||
@@ -0,0 +1,45 @@
|
||||
//Demo mod showing how to use lib.customitems.js
|
||||
ModAPI.addEventListener("lib:libcustomitems:loaded", () => {
|
||||
console.log("Registered my cool custom item.");
|
||||
LibCustomItems.registerItem({
|
||||
tag: "mymod:test_item_1",
|
||||
base: "magma_cream",
|
||||
name: "Custom Item",
|
||||
qty: 32,
|
||||
useRecipe: true,
|
||||
recipe: [
|
||||
"###",
|
||||
"# #",
|
||||
"###"
|
||||
],
|
||||
recipeLegend: {
|
||||
"#": {
|
||||
"type": "block",
|
||||
"id": "dirt"
|
||||
}
|
||||
},
|
||||
//Optional: onRightClickGround
|
||||
onRightClickGround: `/*/user, world, itemstack, blockpos/*/
|
||||
itemstack.stackSize -= 1;
|
||||
if (itemstack.stackSize < 1) {
|
||||
user.inventory.mainInventory[user.inventory.currentItem] = null;
|
||||
}
|
||||
user.setHealth(2);
|
||||
return true; //PreventDefault
|
||||
`,
|
||||
//Optional: onLeftClickGround
|
||||
onLeftClickGround: `/*/user, world, itemstack, blockpos/*/
|
||||
itemstack.stackSize -= 1;
|
||||
if (itemstack.stackSize < 1) {
|
||||
user.inventory.mainInventory[user.inventory.currentItem] = null;
|
||||
}
|
||||
user.setHealth(20);
|
||||
return true; //PreventDefault
|
||||
`,
|
||||
//Optional: craftingExtra
|
||||
craftingExtra: `/*/itemstack/*/
|
||||
let enchant = ModAPI.reflect.getClassByName("Enchantment").staticMethods.getEnchantmentById.method(5); //ENCHANTMENT_OXYGEN (respiration)
|
||||
itemstack.addEnchantment(enchant);
|
||||
`,
|
||||
});
|
||||
});
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,94 @@
|
||||
(function CustomItemMod() {
|
||||
const itemTexture = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAKZJREFUOE9j/P//PxMDBIBoEP6HREOl4PLIciA2AyPIgMcM//7KgvWSDJjBBpx9/+YvJzc3Sbq12DhB6sEGsJ19/+YnmQawYhigzc7FcPXnN4KugbqAHWQAy9n3b34T4wJkw6EGYLqAoNVQBWS5ANlwZBfAvUCs/0EGkW0AzBKqGoCSDgh5A80F2KMRpAgfAKUT6kcjsfEPUycmKMQgy8AETkgUZWcAS3CPIf4oSPsAAAAASUVORK5CYII=";
|
||||
|
||||
ModAPI.meta.title("Custom Item Mod");
|
||||
ModAPI.meta.icon(itemTexture);
|
||||
ModAPI.meta.description("it's a custom item. what more do you want");
|
||||
ModAPI.meta.credits("By <author_name>");
|
||||
|
||||
function CustomItem() {
|
||||
var creativeMiscTab = ModAPI.reflect.getClassById("net.minecraft.creativetab.CreativeTabs").staticVariables.tabMisc; //chuck it in the miscellaneous category ig
|
||||
var itemClass = ModAPI.reflect.getClassById("net.minecraft.item.Item"); //Get the item class
|
||||
var itemSuper = ModAPI.reflect.getSuper(itemClass, (x) => x.length === 1); //Get the super() function of the item class that has a length of 1
|
||||
function CustomItem() {
|
||||
itemSuper(this); //Use super function to get block properties on this class.
|
||||
this.$setCreativeTab(creativeMiscTab); //Set the creative tab of the item to be the misc tab
|
||||
}
|
||||
ModAPI.reflect.prototypeStack(itemClass, CustomItem); // ModAPI equivalent of `extends` in java
|
||||
CustomItem.prototype.$onItemRightClick = function ($itemstack, $world, $player) { //example of how to override a method
|
||||
//use ModAPI.util.wrap to create a proxy of the player and the world without $ prefixes on the properties and methods
|
||||
var player = ModAPI.util.wrap($player);
|
||||
var world = ModAPI.util.wrap($world);
|
||||
|
||||
if (!world.isRemote) { //If we are on the server
|
||||
// Math.random() returns a number from 0.0 to 1.0, so we subtract 0.5 and then multiply by 2 to make it become -1.0 to 1.0 instead
|
||||
player.motionX += (Math.random() - 0.5) * 3;
|
||||
player.motionZ += (Math.random() - 0.5) * 3;
|
||||
|
||||
player.motionY += Math.random() * 1.5; // gravity is a thing, so no negative numbers here otherwise it'll be boring
|
||||
}
|
||||
|
||||
return $itemstack;
|
||||
}
|
||||
|
||||
// Internal registration function. This will be used to actually register the item on both the client and the server.
|
||||
function internal_reg() {
|
||||
// Construct an instance of the CustomItem, and set it's unlocalized name (translation id)
|
||||
var custom_item = (new CustomItem()).$setUnlocalizedName(
|
||||
ModAPI.util.str("custom_item")
|
||||
);
|
||||
//Register it using ModAPI.keygen() to get the item id.
|
||||
itemClass.staticMethods.registerItem.method(ModAPI.keygen.item("custom_item"), ModAPI.util.str("custom_item"), custom_item);
|
||||
|
||||
//Expose it to ModAPI
|
||||
ModAPI.items["custom_item"] = custom_item;
|
||||
|
||||
//return the instance.
|
||||
return custom_item;
|
||||
}
|
||||
|
||||
//if the item global exists (and it will on the client), register the item and return the registered instance.
|
||||
if (ModAPI.items) {
|
||||
return internal_reg();
|
||||
} else {
|
||||
//Otherwise attatch the registration method to the bootstrap method.
|
||||
ModAPI.addEventListener("bootstrap", internal_reg);
|
||||
}
|
||||
}
|
||||
|
||||
// Run the function when the dedicated server loads.
|
||||
ModAPI.dedicatedServer.appendCode(CustomItem);
|
||||
|
||||
// Run the function on the client
|
||||
var custom_item = CustomItem();
|
||||
|
||||
ModAPI.addEventListener("lib:asyncsink", async () => {
|
||||
ModAPI.addEventListener("lib:asyncsink:registeritems", (renderItem)=>{
|
||||
renderItem.registerItem(custom_item, ModAPI.util.str("custom_item"));
|
||||
});
|
||||
AsyncSink.L10N.set("item.custom_item.name", "Cool Custom Item");
|
||||
AsyncSink.setFile("resourcepacks/AsyncSinkLib/assets/minecraft/models/item/custom_item.json", JSON.stringify(
|
||||
{
|
||||
"parent": "builtin/generated",
|
||||
"textures": {
|
||||
"layer0": "items/custom_item"
|
||||
},
|
||||
"display": {
|
||||
"thirdperson": {
|
||||
"rotation": [ -90, 0, 0 ],
|
||||
"translation": [ 0, 1, -3 ],
|
||||
"scale": [ 0.55, 0.55, 0.55 ]
|
||||
},
|
||||
"firstperson": {
|
||||
"rotation": [ 0, -135, 25 ],
|
||||
"translation": [ 0, 4, 2 ],
|
||||
"scale": [ 1.7, 1.7, 1.7 ]
|
||||
}
|
||||
}
|
||||
}
|
||||
));
|
||||
AsyncSink.setFile("resourcepacks/AsyncSinkLib/assets/minecraft/textures/items/custom_item.png", await (await fetch(
|
||||
itemTexture
|
||||
)).arrayBuffer());
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,237 @@
|
||||
ModAPI.meta.title("WorldEdit");
|
||||
ModAPI.meta.credits("By radmanplays");
|
||||
ModAPI.meta.icon("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAcUlEQVR42mNgoAcw1xT4D8Jka25LVQNjkg2Bac4OlP9fGqFImgHImmHY00z0f4af3H+SDADZDNIc6SwJpjXkuP+THHggm5ENIckrMGeDbIZ5hWgDQJo709XhziYpOpFtJjnuKdaM7OwhYjMIkG0zpQAAtFpjWIvu2dwAAAAASUVORK5CYII=");
|
||||
ModAPI.meta.description("Use //wand, //set and //walls in singleplayer worlds.");
|
||||
ModAPI.addEventListener("lib:libcustomitems:loaded", () => {
|
||||
console.log("Registered worldedit custom items.");
|
||||
LibCustomItems.registerItem({
|
||||
tag: "worldedit:wand",
|
||||
base: "wooden_axe",
|
||||
name: "Wand",
|
||||
qty: 1,
|
||||
recipe: [
|
||||
" ",
|
||||
" # ",
|
||||
" "
|
||||
],
|
||||
recipeLegend: {
|
||||
"#": {
|
||||
"type": "item",
|
||||
"id": "wooden_axe"
|
||||
}
|
||||
},
|
||||
onRightClickGround: `/*/user, world, itemstack, blockpos/*/
|
||||
const prefix = "§7[§4worldedit§7] ";
|
||||
var username = ModAPI.util.str(user.getName());
|
||||
|
||||
globalThis.pos2x = {}
|
||||
globalThis.pos2y = {}
|
||||
globalThis.pos2z = {}
|
||||
|
||||
globalThis.pos2x[username] = blockpos.x
|
||||
globalThis.pos2y[username] = blockpos.y
|
||||
globalThis.pos2z[username] = blockpos.z
|
||||
console.log("rightclick: " + blockpos.x + ", " + blockpos.y + ", " + blockpos.z)
|
||||
// Send chat message to player
|
||||
user.addChatMessage(ModAPI.reflect.getClassById("net.minecraft.util.ChatComponentText").constructors[0](ModAPI.util.str(prefix + "Pos #2 set to: " + blockpos.x + ", " + blockpos.y + ", " + blockpos.z)))
|
||||
return true;
|
||||
`,
|
||||
onLeftClickGround: `/*/user, world, itemstack, blockpos/*/
|
||||
const prefix = "§7[§4worldedit§7] ";
|
||||
var username = ModAPI.util.str(user.getName());
|
||||
|
||||
globalThis.posx = {}
|
||||
globalThis.posy = {}
|
||||
globalThis.posz = {}
|
||||
|
||||
globalThis.posx[username] = blockpos.x
|
||||
globalThis.posy[username] = blockpos.y
|
||||
globalThis.posz[username] = blockpos.z
|
||||
|
||||
// Send chat message to player
|
||||
user.addChatMessage(ModAPI.reflect.getClassById("net.minecraft.util.ChatComponentText").constructors[0](ModAPI.util.str(prefix + "Pos #1 set to: " + blockpos.x + ", " + blockpos.y + ", " + blockpos.z)))
|
||||
return true;
|
||||
`
|
||||
});
|
||||
});
|
||||
|
||||
(() => {
|
||||
PluginAPI.dedicatedServer.appendCode(function () {
|
||||
PluginAPI.addEventListener("processcommand", (event) => {
|
||||
if (!ModAPI.reflect.getClassById("net.minecraft.entity.player.EntityPlayerMP").instanceOf(event.sender.getRef())) {return}
|
||||
const prefix = "§7[§4worldedit§7] ";
|
||||
if (event.command.toLowerCase().startsWith("//wand")) {
|
||||
// Create a new ItemStack for the custom item
|
||||
const ItemStackClass = ModAPI.reflect.getClassById("net.minecraft.item.ItemStack");
|
||||
const itemStack = ItemStackClass.constructors[4](
|
||||
ModAPI.items["wooden_axe"].getRef(), 1
|
||||
);
|
||||
|
||||
// Create NBT data for the item
|
||||
const NBTTagCompoundClass = ModAPI.reflect.getClassById("net.minecraft.nbt.NBTTagCompound");
|
||||
itemStack.$stackTagCompound = NBTTagCompoundClass.constructors[0]();
|
||||
const displayTag = NBTTagCompoundClass.constructors[0]();
|
||||
itemStack.$stackTagCompound.$setTag(ModAPI.util.str("display"), displayTag);
|
||||
|
||||
// Add the enchant effect to the item
|
||||
let enchant = ModAPI.hooks._classMap.nme_Enchantment.staticMethods.getEnchantmentById.method(0);
|
||||
enchant.$effectId = -1;
|
||||
itemStack.$addEnchantment(enchant);
|
||||
|
||||
// Set item name
|
||||
displayTag.$setString(ModAPI.util.str("Name"), ModAPI.util.str("Wand"));
|
||||
|
||||
// Set item lore
|
||||
var loreList = ModAPI.reflect.getClassById("net.minecraft.nbt.NBTTagList").constructors[0]();
|
||||
loreList.$appendTag(ModAPI.reflect.getClassById("net.minecraft.nbt.NBTTagString").constructors.filter(x => { return x.length === 1 })[0](ModAPI.util.str("worldedit:wand")));
|
||||
displayTag.$setTag(ModAPI.util.str("Lore"), loreList);
|
||||
|
||||
// Add the item to the sender's inventory
|
||||
const player = event.sender;
|
||||
player.inventory.addItemStackToInventory(itemStack);
|
||||
|
||||
// Notify the sender
|
||||
const ChatComponentTextClass = ModAPI.reflect.getClassById("net.minecraft.util.ChatComponentText");
|
||||
player.addChatMessage(ChatComponentTextClass.constructors[0](ModAPI.util.str(prefix + "A wand has been added to your inventory!")));
|
||||
player.addChatMessage(ChatComponentTextClass.constructors[0](ModAPI.util.str(prefix + "Left click: select pos #1; Right click: select pos #2")));
|
||||
|
||||
event.preventDefault = true;
|
||||
}
|
||||
var blockPosConstructor = ModAPI.reflect.getClassById("net.minecraft.util.BlockPos").constructors.find((x) => { return x.length === 3 });
|
||||
if (event.command.toLowerCase().startsWith("//set")) {
|
||||
const args = event.command.substring("//set ".length);
|
||||
var username = ModAPI.util.str(event.sender.getName());
|
||||
|
||||
if (args) {
|
||||
const blockTypeName = args
|
||||
const x1 = globalThis.posx[username], y1 = globalThis.posy[username], z1 = globalThis.posz[username];
|
||||
const x2 = globalThis.pos2x[username], y2 = globalThis.pos2y[username], z2 = globalThis.pos2z[username];
|
||||
|
||||
// Validate block and get block type
|
||||
const blockType = ModAPI.blocks[blockTypeName];
|
||||
if (!blockType) {
|
||||
event.sender.addChatMessage(ModAPI.reflect.getClassById("net.minecraft.util.ChatComponentText").constructors[0](ModAPI.util.str(prefix + `Invalid block: ${blockTypeName}`)));
|
||||
event.preventDefault = true;
|
||||
return;
|
||||
}
|
||||
const block = blockType.getDefaultState().getRef();
|
||||
|
||||
// Get min and max coordinates for the fill region
|
||||
const xMin = Math.min(x1, x2), xMax = Math.max(x1, x2);
|
||||
const yMin = Math.min(y1, y2), yMax = Math.max(y1, y2);
|
||||
const zMin = Math.min(z1, z2), zMax = Math.max(z1, z2);
|
||||
|
||||
// Loop through the region and set the blocks
|
||||
for (let x = xMin; x <= xMax; x++) {
|
||||
for (let y = yMin; y <= yMax; y++) {
|
||||
for (let z = zMin; z <= zMax; z++) {
|
||||
const blockPos = blockPosConstructor(x, y, z);
|
||||
event.sender.getServerForPlayer().setBlockState(blockPos, block, 3);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Notify the player that the blocks have been set
|
||||
event.sender.addChatMessage(ModAPI.reflect.getClassById("net.minecraft.util.ChatComponentText").constructors[0](ModAPI.util.str(prefix + `Set blocks to ${blockTypeName}`)));
|
||||
} else{
|
||||
event.sender.addChatMessage(ModAPI.reflect.getClassById("net.minecraft.util.ChatComponentText").constructors[0](ModAPI.util.str(prefix + `Arguments not found!`)));
|
||||
}
|
||||
event.preventDefault = true;
|
||||
}
|
||||
if (event.command.toLowerCase().startsWith("//walls")) {
|
||||
const args = event.command.substring("//walls ".length);
|
||||
var username = ModAPI.util.str(event.sender.getName());
|
||||
|
||||
if (args) {
|
||||
const blockTypeName = args;
|
||||
const x1 = globalThis.posx[username], y1 = globalThis.posy[username], z1 = globalThis.posz[username];
|
||||
const x2 = globalThis.pos2x[username], y2 = globalThis.pos2y[username], z2 = globalThis.pos2z[username];
|
||||
|
||||
// Validate block and get block type
|
||||
const blockType = ModAPI.blocks[blockTypeName];
|
||||
if (!blockType) {
|
||||
event.sender.addChatMessage(ModAPI.reflect.getClassById("net.minecraft.util.ChatComponentText").constructors[0](ModAPI.util.str(prefix + `Invalid block: ${blockTypeName}`)));
|
||||
event.preventDefault = true;
|
||||
return;
|
||||
}
|
||||
const block = blockType.getDefaultState().getRef();
|
||||
|
||||
// Get min and max coordinates for the region
|
||||
const xMin = Math.min(x1, x2), xMax = Math.max(x1, x2);
|
||||
const yMin = Math.min(y1, y2), yMax = Math.max(y1, y2);
|
||||
const zMin = Math.min(z1, z2), zMax = Math.max(z1, z2);
|
||||
|
||||
// Loop through the region and set the walls (exclude interior blocks)
|
||||
for (let x = xMin; x <= xMax; x++) {
|
||||
for (let y = yMin; y <= yMax; y++) {
|
||||
for (let z = zMin; z <= zMax; z++) {
|
||||
if (x === xMin || x === xMax || z === zMin || z === zMax) {
|
||||
const blockPos = blockPosConstructor(x, y, z);
|
||||
event.sender.getServerForPlayer().setBlockState(blockPos, block, 3);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Notify the player that the walls have been set
|
||||
event.sender.addChatMessage(ModAPI.reflect.getClassById("net.minecraft.util.ChatComponentText").constructors[0](ModAPI.util.str(prefix + `Walls set to ${blockTypeName}`)));
|
||||
} else {
|
||||
event.sender.addChatMessage(ModAPI.reflect.getClassById("net.minecraft.util.ChatComponentText").constructors[0](ModAPI.util.str(prefix + `Arguments not found!`)));
|
||||
}
|
||||
event.preventDefault = true;
|
||||
}
|
||||
// "this command was made by EymenWSMC. comments included" - radmanplays
|
||||
if (event.command.toLowerCase().startsWith("//replacenear")) {
|
||||
const args = event.command.split(" ").slice(1);
|
||||
if (args.length < 3) {
|
||||
event.sender.addChatMessage(ModAPI.reflect.getClassById("net.minecraft.util.ChatComponentText").constructors[0](ModAPI.util.str(prefix + "Usage: //replacenear <radius> <targetBlock> <replacementBlock>")));
|
||||
event.preventDefault = true;
|
||||
return;
|
||||
}
|
||||
|
||||
const radius = parseInt(args[0]);
|
||||
const targetBlockName = args[1];
|
||||
const replacementBlockName = args[2];
|
||||
|
||||
const targetBlock = ModAPI.blocks[targetBlockName];
|
||||
const replacementBlock = ModAPI.blocks[replacementBlockName];
|
||||
if (!targetBlock || !replacementBlock) {
|
||||
event.sender.addChatMessage(ModAPI.reflect.getClassById("net.minecraft.util.ChatComponentText").constructors[0](ModAPI.util.str(prefix + "Invalid block names!")));
|
||||
event.preventDefault = true;
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
//Replacing logic
|
||||
const targetBlockState = targetBlock.getDefaultState().getRef();
|
||||
const replacementBlockState = replacementBlock.getDefaultState().getRef();
|
||||
|
||||
const playerPos = event.sender.getPosition();
|
||||
const xStart = Math.floor(playerPos.x - radius);
|
||||
const xEnd = Math.floor(playerPos.x + radius);
|
||||
const yStart = Math.floor(playerPos.y - radius);
|
||||
const yEnd = Math.floor(playerPos.y + radius);
|
||||
const zStart = Math.floor(playerPos.z - radius);
|
||||
const zEnd = Math.floor(playerPos.z + radius);
|
||||
|
||||
//Replace ity with radoius
|
||||
for (let x = xStart; x <= xEnd; x++) {
|
||||
for (let y = yStart; y <= yEnd; y++) {
|
||||
for (let z = zStart; z <= zEnd; z++) {
|
||||
const blockPos = blockPosConstructor(x, y, z);
|
||||
const currentBlock = event.sender.getServerForPlayer().getBlockState(blockPos);
|
||||
|
||||
if (currentBlock.equals(targetBlockState)) {
|
||||
event.sender.getServerForPlayer().setBlockState(blockPos, replacementBlockState, 3);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//Send messages shit
|
||||
event.sender.addChatMessage(ModAPI.reflect.getClassById("net.minecraft.util.ChatComponentText").constructors[0](ModAPI.util.str(prefix + `Replaced ${targetBlockName} with ${replacementBlockName} within radius ${radius}`)));
|
||||
event.preventDefault = true;
|
||||
}
|
||||
});
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,28 @@
|
||||
(function AntiAFKMod() {
|
||||
ModAPI.meta.title("Anti AFK Mod");
|
||||
ModAPI.meta.credits("By ZXMushroom63");
|
||||
ModAPI.meta.description("Type .afk in game chat to toggle the mod");
|
||||
ModAPI.require("player");
|
||||
var active = null;
|
||||
function queueJump() {
|
||||
try {
|
||||
ModAPI.player.jump();
|
||||
} catch (error) {
|
||||
|
||||
}
|
||||
active = setTimeout(queueJump, 15000 + (10000 * Math.random()));
|
||||
}
|
||||
ModAPI.addEventListener("sendchatmessage", (e)=>{
|
||||
if (e.message.toLowerCase() === ".afk") {
|
||||
if (active === null) {
|
||||
queueJump();
|
||||
ModAPI.displayToChat("Activated anti-afk mod!\nI recommend using the sliders mod to decrease your max fps to save battery.");
|
||||
} else {
|
||||
clearTimeout(active);
|
||||
active = null;
|
||||
ModAPI.displayToChat("Deactivated anti-afk mod.");
|
||||
}
|
||||
e.preventDefault = true;
|
||||
}
|
||||
});
|
||||
})();
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,121 @@
|
||||
//THIS IS A DEMO MOD
|
||||
|
||||
|
||||
//nice little utility function to fix the block identity map
|
||||
function fixupBlockIds() {
|
||||
var blockRegistry = ModAPI.util.wrap(ModAPI.reflect.getClassById("net.minecraft.block.Block").staticVariables.blockRegistry).getCorrective();
|
||||
var BLOCK_STATE_IDS = ModAPI.util.wrap(ModAPI.reflect.getClassById("net.minecraft.block.Block").staticVariables.BLOCK_STATE_IDS).getCorrective();
|
||||
blockRegistry.registryObjects.hashTableKToV.forEach(entry => {
|
||||
if (entry) {
|
||||
var block = entry.value;
|
||||
var validStates = block.getBlockState().getValidStates();
|
||||
var stateArray = validStates.array || [validStates.element];
|
||||
stateArray.forEach(iblockstate => {
|
||||
var i = blockRegistry.getIDForObject(block.getRef()) << 4 | block.getMetaFromState(iblockstate.getRef());
|
||||
BLOCK_STATE_IDS.put(iblockstate.getRef(), i);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
function makeSteveBlock() {
|
||||
var blockClass = ModAPI.reflect.getClassById("net.minecraft.block.Block");
|
||||
var blockSuper = ModAPI.reflect.getSuper(blockClass, (x) => x.length === 2);
|
||||
var creativeBlockTab = ModAPI.reflect.getClassById("net.minecraft.creativetab.CreativeTabs").staticVariables.tabBlock;
|
||||
function nmb_BlockSteve() {
|
||||
blockSuper(this, ModAPI.materials.rock.getRef());
|
||||
this.$defaultBlockState = this.$blockState.$getBaseState();
|
||||
this.$setCreativeTab(creativeBlockTab);
|
||||
}
|
||||
ModAPI.reflect.prototypeStack(blockClass, nmb_BlockSteve);
|
||||
globalThis.nmb_BlockSteve = nmb_BlockSteve;
|
||||
}
|
||||
function registerSteveClientSide() {
|
||||
var itemClass = ModAPI.reflect.getClassById("net.minecraft.item.Item");
|
||||
var blockClass = ModAPI.reflect.getClassById("net.minecraft.block.Block");
|
||||
var block_of_steve = (new nmb_BlockSteve()).$setHardness(-1.0).$setStepSound(blockClass.staticVariables.soundTypeGravel).$setUnlocalizedName(
|
||||
ModAPI.util.str("steve")
|
||||
);
|
||||
blockClass.staticMethods.registerBlock0.method(
|
||||
ModAPI.keygen.block("steve"),
|
||||
ModAPI.util.str("steve"),
|
||||
block_of_steve
|
||||
);
|
||||
itemClass.staticMethods.registerItemBlock0.method(block_of_steve);
|
||||
ModAPI.addEventListener("lib:asyncsink", async () => {
|
||||
ModAPI.addEventListener("lib:asyncsink:registeritems", (renderItem)=>{
|
||||
renderItem.registerBlock(block_of_steve, ModAPI.util.str("steve"));
|
||||
});
|
||||
AsyncSink.L10N.set("tile.steve.name", "Block Of Steve");
|
||||
AsyncSink.setFile("resourcepacks/AsyncSinkLib/assets/minecraft/models/block/steve.json", JSON.stringify(
|
||||
{
|
||||
"parent": "block/cube_all",
|
||||
"textures": {
|
||||
"all": "blocks/steve"
|
||||
}
|
||||
}
|
||||
));
|
||||
AsyncSink.setFile("resourcepacks/AsyncSinkLib/assets/minecraft/models/item/steve.json", JSON.stringify(
|
||||
{
|
||||
"parent": "block/steve",
|
||||
"display": {
|
||||
"thirdperson": {
|
||||
"rotation": [10, -45, 170],
|
||||
"translation": [0, 1.5, -2.75],
|
||||
"scale": [0.375, 0.375, 0.375]
|
||||
}
|
||||
}
|
||||
}
|
||||
));
|
||||
AsyncSink.setFile("resourcepacks/AsyncSinkLib/assets/minecraft/blockstates/steve.json", JSON.stringify(
|
||||
{
|
||||
"variants": {
|
||||
"normal": [
|
||||
{ "model": "steve" },
|
||||
]
|
||||
}
|
||||
}
|
||||
));
|
||||
AsyncSink.setFile("resourcepacks/AsyncSinkLib/assets/minecraft/textures/blocks/steve.png", await (await fetch(
|
||||
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAE0SURBVDhPpdO9S8NAHMbxy3sVfJmMg6h7FRXXkkUUX0addSjo4OAfIDqLIoiLi3+BRRx0EIQOnV0EcVAIWkR0KIFgrcEktX6vcXD0nuE+5Afhnhw5bWy4qylaidOfVQhT0zFKYozjBHVdzi3TwCZvteaS/0fLD8oGf5OzTeyxNUyE3Ln2HmGctpuxKuS3wd76CgPHsrEj142NeojCkHsFry+4c3aJ6g1OtlZp0Ok4DD4i+Y2GIZ+DMMAhtw+fHu8xi3IDM9t5YfMQF71dLHo+ZjsfXbh4WtnH0vYaqp/BcXGGM3D7BxiYTi+el8uYZWm2gM/VB/Tfaqje4GB5iga2Jv+sUuUa5/ITmOXq7gbnC+MY1r9QvcHG9AgN0lRex1u/ilr7ehqWvBNZvMlRbESfqNhAiG/Pb1bHXpMbFgAAAABJRU5ErkJggg=="
|
||||
)).arrayBuffer());
|
||||
});
|
||||
ModAPI.blocks["steve"] = block_of_steve;
|
||||
}
|
||||
function registerSteveServerSide() {
|
||||
function fixupBlockIds() {
|
||||
var blockRegistry = ModAPI.util.wrap(ModAPI.reflect.getClassById("net.minecraft.block.Block").staticVariables.blockRegistry).getCorrective();
|
||||
var BLOCK_STATE_IDS = ModAPI.util.wrap(ModAPI.reflect.getClassById("net.minecraft.block.Block").staticVariables.BLOCK_STATE_IDS).getCorrective();
|
||||
blockRegistry.registryObjects.hashTableKToV.forEach(entry => {
|
||||
if (entry) {
|
||||
var block = entry.value;
|
||||
var validStates = block.getBlockState().getValidStates();
|
||||
var stateArray = validStates.array || [validStates.element];
|
||||
stateArray.forEach(iblockstate => {
|
||||
var i = blockRegistry.getIDForObject(block.getRef()) << 4 | block.getMetaFromState(iblockstate.getRef());
|
||||
BLOCK_STATE_IDS.put(iblockstate.getRef(), i);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
var blockClass = ModAPI.reflect.getClassById("net.minecraft.block.Block");
|
||||
var itemClass = ModAPI.reflect.getClassById("net.minecraft.item.Item");
|
||||
ModAPI.addEventListener("bootstrap", () => {
|
||||
var block_of_steve = (new nmb_BlockSteve()).$setHardness(-1.0).$setStepSound(blockClass.staticVariables.soundTypeGravel).$setUnlocalizedName(
|
||||
ModAPI.util.str("steve")
|
||||
);
|
||||
blockClass.staticMethods.registerBlock0.method(
|
||||
ModAPI.keygen.block("steve"), //use blockid 198. MAKE SURE TO CHANGE IF YOU ARE MAKING A MOD USING THIS, MAXIMUM BLOCK ID IS 4095.
|
||||
ModAPI.util.str("steve"),
|
||||
block_of_steve
|
||||
);
|
||||
itemClass.staticMethods.registerItemBlock0.method(block_of_steve);
|
||||
fixupBlockIds();
|
||||
ModAPI.blocks["steve"] = block_of_steve;
|
||||
});
|
||||
}
|
||||
ModAPI.dedicatedServer.appendCode(makeSteveBlock);
|
||||
makeSteveBlock();
|
||||
registerSteveClientSide();
|
||||
fixupBlockIds();
|
||||
|
||||
ModAPI.dedicatedServer.appendCode(registerSteveServerSide);
|
||||
@@ -0,0 +1,111 @@
|
||||
//THIS IS A DEMO MOD
|
||||
|
||||
|
||||
//nice little utility function to fix the block identity map
|
||||
function fixupBlockIds() {
|
||||
var blockRegistry = ModAPI.util.wrap(ModAPI.reflect.getClassById("net.minecraft.block.Block").staticVariables.blockRegistry).getCorrective();
|
||||
var BLOCK_STATE_IDS = ModAPI.util.wrap(ModAPI.reflect.getClassById("net.minecraft.block.Block").staticVariables.BLOCK_STATE_IDS).getCorrective();
|
||||
blockRegistry.registryObjects.hashTableKToV.forEach(entry => {
|
||||
if (entry) {
|
||||
var block = entry.value;
|
||||
var validStates = block.getBlockState().getValidStates();
|
||||
var stateArray = validStates.array || [validStates.element];
|
||||
stateArray.forEach(iblockstate => {
|
||||
var i = blockRegistry.getIDForObject(block.getRef()) << 4 | block.getMetaFromState(iblockstate.getRef());
|
||||
BLOCK_STATE_IDS.put(iblockstate.getRef(), i);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
function registerSteveClientSide() {
|
||||
var creativeBlockTab = ModAPI.reflect.getClassById("net.minecraft.creativetab.CreativeTabs").staticVariables.tabBlock;
|
||||
var itemClass = ModAPI.reflect.getClassById("net.minecraft.item.Item");
|
||||
var blockClass = ModAPI.reflect.getClassById("net.minecraft.block.Block");
|
||||
var constructor = blockClass.constructors.find(x=>x.length === 1);
|
||||
var block_of_steve = constructor(ModAPI.materials.rock.getRef()).$setHardness(-1.0).$setStepSound(blockClass.staticVariables.soundTypeGravel).$setUnlocalizedName(
|
||||
ModAPI.util.str("steve")
|
||||
).$setCreativeTab(creativeBlockTab);
|
||||
blockClass.staticMethods.registerBlock0.method(
|
||||
ModAPI.keygen.block("steve"), //use blockid 198. MAKE SURE TO CHANGE IF YOU ARE MAKING A MOD USING THIS, MAXIMUM BLOCK ID IS 4095.
|
||||
ModAPI.util.str("steve"),
|
||||
block_of_steve
|
||||
);
|
||||
itemClass.staticMethods.registerItemBlock0.method(block_of_steve);
|
||||
|
||||
ModAPI.addEventListener("lib:asyncsink", async () => {
|
||||
ModAPI.addEventListener("lib:asyncsink:registeritems", (renderItem)=>{
|
||||
renderItem.registerBlock(block_of_steve, ModAPI.util.str("steve"));
|
||||
});
|
||||
AsyncSink.L10N.set("tile.steve.name", "Block Of Steve");
|
||||
AsyncSink.setFile("resourcepacks/AsyncSinkLib/assets/minecraft/models/block/steve.json", JSON.stringify(
|
||||
{
|
||||
"parent": "block/cube_all",
|
||||
"textures": {
|
||||
"all": "blocks/steve"
|
||||
}
|
||||
}
|
||||
));
|
||||
AsyncSink.setFile("resourcepacks/AsyncSinkLib/assets/minecraft/models/item/steve.json", JSON.stringify(
|
||||
{
|
||||
"parent": "block/steve",
|
||||
"display": {
|
||||
"thirdperson": {
|
||||
"rotation": [10, -45, 170],
|
||||
"translation": [0, 1.5, -2.75],
|
||||
"scale": [0.375, 0.375, 0.375]
|
||||
}
|
||||
}
|
||||
}
|
||||
));
|
||||
AsyncSink.setFile("resourcepacks/AsyncSinkLib/assets/minecraft/blockstates/steve.json", JSON.stringify(
|
||||
{
|
||||
"variants": {
|
||||
"normal": [
|
||||
{ "model": "steve" },
|
||||
]
|
||||
}
|
||||
}
|
||||
));
|
||||
AsyncSink.setFile("resourcepacks/AsyncSinkLib/assets/minecraft/textures/blocks/steve.png", await (await fetch(
|
||||
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAE0SURBVDhPpdO9S8NAHMbxy3sVfJmMg6h7FRXXkkUUX0addSjo4OAfIDqLIoiLi3+BRRx0EIQOnV0EcVAIWkR0KIFgrcEktX6vcXD0nuE+5Afhnhw5bWy4qylaidOfVQhT0zFKYozjBHVdzi3TwCZvteaS/0fLD8oGf5OzTeyxNUyE3Ln2HmGctpuxKuS3wd76CgPHsrEj142NeojCkHsFry+4c3aJ6g1OtlZp0Ok4DD4i+Y2GIZ+DMMAhtw+fHu8xi3IDM9t5YfMQF71dLHo+ZjsfXbh4WtnH0vYaqp/BcXGGM3D7BxiYTi+el8uYZWm2gM/VB/Tfaqje4GB5iga2Jv+sUuUa5/ITmOXq7gbnC+MY1r9QvcHG9AgN0lRex1u/ilr7ehqWvBNZvMlRbESfqNhAiG/Pb1bHXpMbFgAAAABJRU5ErkJggg=="
|
||||
)).arrayBuffer());
|
||||
});
|
||||
ModAPI.blocks["steve"] = block_of_steve;
|
||||
}
|
||||
function registerSteveServerSide() {
|
||||
function fixupBlockIds() {
|
||||
var blockRegistry = ModAPI.util.wrap(ModAPI.reflect.getClassById("net.minecraft.block.Block").staticVariables.blockRegistry).getCorrective();
|
||||
var BLOCK_STATE_IDS = ModAPI.util.wrap(ModAPI.reflect.getClassById("net.minecraft.block.Block").staticVariables.BLOCK_STATE_IDS).getCorrective();
|
||||
blockRegistry.registryObjects.hashTableKToV.forEach(entry => {
|
||||
if (entry) {
|
||||
var block = entry.value;
|
||||
var validStates = block.getBlockState().getValidStates();
|
||||
var stateArray = validStates.array || [validStates.element];
|
||||
stateArray.forEach(iblockstate => {
|
||||
var i = blockRegistry.getIDForObject(block.getRef()) << 4 | block.getMetaFromState(iblockstate.getRef());
|
||||
BLOCK_STATE_IDS.put(iblockstate.getRef(), i);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
var creativeBlockTab = ModAPI.reflect.getClassById("net.minecraft.creativetab.CreativeTabs").staticVariables.tabBlock;
|
||||
var blockClass = ModAPI.reflect.getClassById("net.minecraft.block.Block");
|
||||
var itemClass = ModAPI.reflect.getClassById("net.minecraft.item.Item");
|
||||
var constructor = blockClass.constructors.find(x=>x.length === 1);
|
||||
ModAPI.addEventListener("bootstrap", () => {
|
||||
var block_of_steve = constructor(ModAPI.materials.rock.getRef()).$setHardness(-1.0).$setStepSound(blockClass.staticVariables.soundTypeGravel).$setUnlocalizedName(
|
||||
ModAPI.util.str("steve")
|
||||
).$setCreativeTab(creativeBlockTab);
|
||||
blockClass.staticMethods.registerBlock0.method(
|
||||
ModAPI.keygen.block("steve"), //use blockid 198. MAKE SURE TO CHANGE IF YOU ARE MAKING A MOD USING THIS, MAXIMUM BLOCK ID IS 4095.
|
||||
ModAPI.util.str("steve"),
|
||||
block_of_steve
|
||||
);
|
||||
itemClass.staticMethods.registerItemBlock0.method(block_of_steve);
|
||||
fixupBlockIds();
|
||||
ModAPI.blocks["steve"] = block_of_steve;
|
||||
});
|
||||
}
|
||||
registerSteveClientSide();
|
||||
fixupBlockIds();
|
||||
ModAPI.dedicatedServer.appendCode(registerSteveServerSide);
|
||||
@@ -0,0 +1,148 @@
|
||||
(function CubeEntity() {
|
||||
ModAPI.meta.title("Cube Entity");
|
||||
ModAPI.meta.version("v0");
|
||||
ModAPI.meta.description("testing custom entities");
|
||||
ModAPI.meta.credits("By ZXMushroom63");
|
||||
function waitForRenderManager() {
|
||||
return new Promise((res, rej)=>{
|
||||
function check() {
|
||||
if (ModAPI.mc.renderManager) {
|
||||
res();
|
||||
} else {
|
||||
setTimeout(check, 1/20);
|
||||
}
|
||||
}
|
||||
check();
|
||||
});
|
||||
}
|
||||
function registerEntity() {
|
||||
// Utils
|
||||
const ResourceLocation = ModAPI.reflect.getClassByName("ResourceLocation").constructors.find(x => x.length === 1);
|
||||
const GlStateManager = Object.fromEntries(Object.values(ModAPI.reflect.getClassByName("GlStateManager").staticMethods).map(x => [x.methodNameShort, x.method]));
|
||||
const IAnimals = ModAPI.reflect.getClassById("net.minecraft.entity.passive.IAnimals");
|
||||
|
||||
// START CUSTOM ENTITY
|
||||
var entityClass = ModAPI.reflect.getClassById("net.minecraft.entity.Entity");
|
||||
var entitySuper = ModAPI.reflect.getSuper(entityClass, (x) => x.length === 2);
|
||||
var nme_EntityCube = function nme_EntityCube($worldIn) {
|
||||
entitySuper(this, $worldIn);
|
||||
this.$preventEntitySpawning = 1;
|
||||
this.$setSize(1, 1);
|
||||
}
|
||||
ModAPI.reflect.prototypeStack(entityClass, nme_EntityCube);
|
||||
|
||||
//Turns out that minecraft 1.8's networking code is really stupid. Notch hardcoded every entity except for ones that implement the IAnimals interface.
|
||||
//I don't know why, and I don't really care either. As long as it works (been working on this for too long, losing sanity)
|
||||
ModAPI.reflect.implements(nme_EntityCube, IAnimals);
|
||||
|
||||
nme_EntityCube.prototype.$canTriggerWalking = function () { return 0 };
|
||||
nme_EntityCube.prototype.$canBePushed = function () { return 1 };
|
||||
nme_EntityCube.prototype.$getCollisionBox = function () { return this.$getEntityBoundingBox() };
|
||||
nme_EntityCube.prototype.$getCollisionBoundingBox = function () { return this.$getEntityBoundingBox() };
|
||||
nme_EntityCube.prototype.$readEntityFromNBT = function (nbtTagCompount) { // Needed, is an abstract method in parent class
|
||||
nbtTagCompount = ModAPI.util.wrap(nbtTagCompount);
|
||||
};
|
||||
nme_EntityCube.prototype.$writeEntityToNBT = function (nbtTagCompount) { // Needed, is an abstract method in parent class
|
||||
nbtTagCompount = ModAPI.util.wrap(nbtTagCompount);
|
||||
};
|
||||
nme_EntityCube.prototype.$entityInit = function () {
|
||||
console.log("Cube entity created!");
|
||||
};
|
||||
// END CUSTOM ENTITY
|
||||
|
||||
|
||||
// START CUSTOM MODEL
|
||||
var ModelRenderer = ModAPI.reflect.getClassById("net.minecraft.client.model.ModelRenderer").constructors.find(x => x.length === 1);
|
||||
var modelBaseClass = ModAPI.reflect.getClassById("net.minecraft.client.model.ModelBase");
|
||||
var modelBaseSuper = ModAPI.reflect.getSuper(modelBaseClass); //while super isn't used when extending this class, java implies the call.
|
||||
var nmcm_ModelCube = function nmcm_ModelCube() {
|
||||
modelBaseSuper(this);
|
||||
this.$textureWidth = 64;
|
||||
this.$textureHeight = 64;
|
||||
this.$cubeRenderer = ModelRenderer(this).$setTextureOffset(0, 0);
|
||||
this.$cubeRenderer.$addBox0(0, 0, 0, 64, 64, 64);
|
||||
this.$cubeRenderer.$setRotationPoint(0, 0, 0);
|
||||
}
|
||||
ModAPI.reflect.prototypeStack(modelBaseClass, nmcm_ModelCube);
|
||||
nmcm_ModelCube.prototype.$render = function ($entity, useless1, useless2, partialTicks, useless3, useless4, degToRad) {
|
||||
this.$cubeRenderer.$render(degToRad);
|
||||
}
|
||||
// END CUSTOM MODEL
|
||||
|
||||
|
||||
// START CUSTOM RENDERER
|
||||
var renderClass = ModAPI.reflect.getClassById("net.minecraft.client.renderer.entity.Render");
|
||||
var renderSuper = ModAPI.reflect.getSuper(renderClass, (x) => x.length === 2);
|
||||
const cubeTextures = ResourceLocation(ModAPI.util.str("textures/entity/cube.png"));
|
||||
var nmcre_RenderCube = function nmcre_RenderCube(renderManager) {
|
||||
renderSuper(this, renderManager);
|
||||
this.$modelCube = new nmcm_ModelCube();
|
||||
this.$shadowSize = 0.5;
|
||||
}
|
||||
ModAPI.reflect.prototypeStack(renderClass, nmcre_RenderCube);
|
||||
nmcre_RenderCube.prototype.$getEntityTexture = function (entity) {
|
||||
return cubeTextures;
|
||||
}
|
||||
const parentDoRender = nmcre_RenderCube.prototype.$doRender;
|
||||
nmcre_RenderCube.prototype.$doRender = function (entity, x, y, z, yaw, pitch) {
|
||||
GlStateManager.pushMatrix();
|
||||
GlStateManager.translate(x + 0.5, y, z + 0.5);
|
||||
GlStateManager.rotate(180 - yaw, 0, 1, 0);
|
||||
GlStateManager.scale(0.25, 0.25, 0.25);
|
||||
this.$bindEntityTexture(entity);
|
||||
this.$modelCube.$render(entity, 0, 0, -0.1, 0, 0, 0.0625);
|
||||
GlStateManager.popMatrix();
|
||||
parentDoRender.apply(this, [entity, x, y, z, yaw, pitch]);
|
||||
}
|
||||
const ID = ModAPI.keygen.entity("cube");
|
||||
ModAPI.reflect.getClassById("net.minecraft.entity.EntityList").staticMethods.addMapping0.method(
|
||||
ModAPI.util.asClass(nme_EntityCube),
|
||||
{
|
||||
$createEntity: function ($worldIn) {
|
||||
return new nme_EntityCube($worldIn);
|
||||
}
|
||||
},
|
||||
ModAPI.util.str("Cube"),
|
||||
ID,
|
||||
0x000000, //egg base
|
||||
0x00FF00 //egg spots
|
||||
);
|
||||
// Note that the spawn egg for this will not work, as spawn eggs only spawn entities that are a subclass of EntityLivingBase
|
||||
console.log(ID);
|
||||
|
||||
ModAPI.addEventListener("lib:asyncsink", async () => {
|
||||
AsyncSink.L10N.set("entity.Cube.name", "Cube (TM)");
|
||||
});
|
||||
|
||||
|
||||
return {
|
||||
EntityCube: nme_EntityCube,
|
||||
ModelCube: nmcm_ModelCube,
|
||||
RenderCube: nmcre_RenderCube,
|
||||
cubeTexture: cubeTextures
|
||||
}
|
||||
}
|
||||
|
||||
ModAPI.dedicatedServer.appendCode(registerEntity);
|
||||
var data = registerEntity();
|
||||
|
||||
ModAPI.addEventListener("lib:asyncsink", async () => {
|
||||
AsyncSink.setFile("resourcepacks/AsyncSinkLib/assets/minecraft/textures/entity/cube.png", await (await fetch(
|
||||
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAAAXNSR0IArs4c6QAAAQBJREFUeF7l0BFzAmAAgOGvKxgMgiAYDIJgEARBEASDQTAIgiAYBEEQBN0NBkEQBEEQBIMgCAZBEAwGgyAIgiAIgiConxE88PJ790RCCNdYCOGeRe/4j4SYDvCgAzzqAHEdIKEDJHWAJx3gWQdI6QBpHeBFB8joAFkdIKcD5HWAgg5Q1AFedYA3HaCkA7zrAGUdoKIDVHWAmg7woQPUdYCGDtDUAVo6QFsH6OgAnzrAlw7Q1QF6OkBfBxjoAEMdYKQDjHWAiQ7wrQNMdYCZDjDXAX50gIUOsNQBVjrArw7wpwP86wBrHWCjA2x1gJ0OsNcBDjrAUQc46QBnHeBiA9wALSueIjTE4PwAAAAASUVORK5CYII="
|
||||
)).arrayBuffer());
|
||||
AsyncSink.hideFile("resourcepacks/AsyncSinkLib/assets/minecraft/textures/entity/cube.png.mcmeta");
|
||||
|
||||
await waitForRenderManager()
|
||||
ModAPI.mc.renderManager.entityRenderMap.put(ModAPI.util.asClass(data.EntityCube), new data.RenderCube(ModAPI.mc.renderManager.getRef()));
|
||||
ModAPI.promisify(ModAPI.mc.renderEngine.bindTexture)(data.cubeTexture).then(() => {
|
||||
console.log("Loaded cube texture into cache.");
|
||||
});
|
||||
});
|
||||
console.log(data);
|
||||
window.temp1 = data;
|
||||
})();
|
||||
//var cube_man = new temp1.EntityCube(ModAPI.mc.theWorld.getRef());
|
||||
//cube_man.$setPosition(-191, 74, 26);
|
||||
//AsyncSink.startDebugging();
|
||||
//AsyncSink.startDebuggingFS();
|
||||
//ModAPI.mc.theWorld.spawnEntityInWorld(cube_man);
|
||||
@@ -0,0 +1,122 @@
|
||||
//THIS IS A DEMO MOD
|
||||
|
||||
|
||||
//nice little utility function to fix the block identity map
|
||||
function fixupBlockIds() {
|
||||
var blockRegistry = ModAPI.util.wrap(ModAPI.reflect.getClassById("net.minecraft.block.Block").staticVariables.blockRegistry).getCorrective();
|
||||
var BLOCK_STATE_IDS = ModAPI.util.wrap(ModAPI.reflect.getClassById("net.minecraft.block.Block").staticVariables.BLOCK_STATE_IDS).getCorrective();
|
||||
blockRegistry.registryObjects.hashTableKToV.forEach(entry => {
|
||||
if (entry) {
|
||||
var block = entry.value;
|
||||
var validStates = block.getBlockState().getValidStates();
|
||||
var stateArray = validStates.array || [validStates.element];
|
||||
stateArray.forEach(iblockstate => {
|
||||
var i = blockRegistry.getIDForObject(block.getRef()) << 4 | block.getMetaFromState(iblockstate.getRef());
|
||||
BLOCK_STATE_IDS.put(iblockstate.getRef(), i);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
function makeSteveBlock() {
|
||||
var blockClass = ModAPI.reflect.getClassById("net.minecraft.block.Block");
|
||||
var blockSuper = ModAPI.reflect.getSuper(blockClass, (x) => x.length === 2);
|
||||
var creativeBlockTab = ModAPI.reflect.getClassById("net.minecraft.creativetab.CreativeTabs").staticVariables.tabBlock;
|
||||
function nmb_BlockSteve() {
|
||||
blockSuper(this, ModAPI.materials.rock.getRef());
|
||||
//this.$defaultBlockState = this.$blockState.$getBaseState(); built-in in 1.12
|
||||
this.$setCreativeTab(creativeBlockTab);
|
||||
}
|
||||
ModAPI.reflect.prototypeStack(blockClass, nmb_BlockSteve);
|
||||
globalThis.nmb_BlockSteve = nmb_BlockSteve;
|
||||
}
|
||||
function registerSteveClientSide() {
|
||||
var itemClass = ModAPI.reflect.getClassById("net.minecraft.item.Item");
|
||||
var blockClass = ModAPI.reflect.getClassById("net.minecraft.block.Block");
|
||||
var block_of_steve = (new nmb_BlockSteve()).$setHardness(-1.0).$setSoundType(ModAPI.blockSounds.PLANT.getRef()).$setUnlocalizedName(
|
||||
ModAPI.util.str("steve")
|
||||
);
|
||||
blockClass.staticMethods.registerBlock0.method(
|
||||
ModAPI.keygen.block("steve"),
|
||||
ModAPI.util.str("steve"),
|
||||
block_of_steve
|
||||
);
|
||||
itemClass.staticMethods.registerItemBlock0.method(block_of_steve);
|
||||
ModAPI.addEventListener("lib:asyncsink", async () => {
|
||||
ModAPI.addEventListener("lib:asyncsink:registeritems", (renderItem)=>{
|
||||
console.log("registered!!");
|
||||
renderItem.registerBlock(block_of_steve, ModAPI.util.str("steve"));
|
||||
});
|
||||
AsyncSink.L10N.set("tile.steve.name", "Block Of Steve");
|
||||
AsyncSink.setFile("resourcepacks/AsyncSinkLib/assets/minecraft/models/block/steve.json", JSON.stringify(
|
||||
{
|
||||
"parent": "block/cube_all",
|
||||
"textures": {
|
||||
"all": "blocks/steve"
|
||||
}
|
||||
}
|
||||
));
|
||||
AsyncSink.setFile("resourcepacks/AsyncSinkLib/assets/minecraft/models/item/steve.json", JSON.stringify(
|
||||
{
|
||||
"parent": "block/steve",
|
||||
"display": {
|
||||
"thirdperson": {
|
||||
"rotation": [10, -45, 170],
|
||||
"translation": [0, 1.5, -2.75],
|
||||
"scale": [0.375, 0.375, 0.375]
|
||||
}
|
||||
}
|
||||
}
|
||||
));
|
||||
AsyncSink.setFile("resourcepacks/AsyncSinkLib/assets/minecraft/blockstates/steve.json", JSON.stringify(
|
||||
{
|
||||
"variants": {
|
||||
"normal": [
|
||||
{ "model": "steve" },
|
||||
]
|
||||
}
|
||||
}
|
||||
));
|
||||
AsyncSink.setFile("resourcepacks/AsyncSinkLib/assets/minecraft/textures/blocks/steve.png", await (await fetch(
|
||||
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAE0SURBVDhPpdO9S8NAHMbxy3sVfJmMg6h7FRXXkkUUX0addSjo4OAfIDqLIoiLi3+BRRx0EIQOnV0EcVAIWkR0KIFgrcEktX6vcXD0nuE+5Afhnhw5bWy4qylaidOfVQhT0zFKYozjBHVdzi3TwCZvteaS/0fLD8oGf5OzTeyxNUyE3Ln2HmGctpuxKuS3wd76CgPHsrEj142NeojCkHsFry+4c3aJ6g1OtlZp0Ok4DD4i+Y2GIZ+DMMAhtw+fHu8xi3IDM9t5YfMQF71dLHo+ZjsfXbh4WtnH0vYaqp/BcXGGM3D7BxiYTi+el8uYZWm2gM/VB/Tfaqje4GB5iga2Jv+sUuUa5/ITmOXq7gbnC+MY1r9QvcHG9AgN0lRex1u/ilr7ehqWvBNZvMlRbESfqNhAiG/Pb1bHXpMbFgAAAABJRU5ErkJggg=="
|
||||
)).arrayBuffer());
|
||||
});
|
||||
ModAPI.blocks["steve"] = block_of_steve;
|
||||
}
|
||||
function registerSteveServerSide() {
|
||||
function fixupBlockIds() {
|
||||
var blockRegistry = ModAPI.util.wrap(ModAPI.reflect.getClassById("net.minecraft.block.Block").staticVariables.blockRegistry).getCorrective();
|
||||
var BLOCK_STATE_IDS = ModAPI.util.wrap(ModAPI.reflect.getClassById("net.minecraft.block.Block").staticVariables.BLOCK_STATE_IDS).getCorrective();
|
||||
blockRegistry.registryObjects.hashTableKToV.forEach(entry => {
|
||||
if (entry) {
|
||||
var block = entry.value;
|
||||
var validStates = block.getBlockState().getValidStates();
|
||||
var stateArray = validStates.array || [validStates.element];
|
||||
stateArray.forEach(iblockstate => {
|
||||
var i = blockRegistry.getIDForObject(block.getRef()) << 4 | block.getMetaFromState(iblockstate.getRef());
|
||||
BLOCK_STATE_IDS.put(iblockstate.getRef(), i);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
var blockClass = ModAPI.reflect.getClassById("net.minecraft.block.Block");
|
||||
var itemClass = ModAPI.reflect.getClassById("net.minecraft.item.Item");
|
||||
ModAPI.addEventListener("bootstrap", () => {
|
||||
var block_of_steve = (new nmb_BlockSteve()).$setHardness(-1.0).$setSoundType(ModAPI.blockSounds.PLANT.getRef()).$setUnlocalizedName(
|
||||
ModAPI.util.str("steve")
|
||||
);
|
||||
blockClass.staticMethods.registerBlock0.method(
|
||||
ModAPI.keygen.block("steve"), //MAXIMUM BLOCK ID IS 4095. keygen method accounts for this
|
||||
ModAPI.util.str("steve"),
|
||||
block_of_steve
|
||||
);
|
||||
itemClass.staticMethods.registerItemBlock0.method(block_of_steve);
|
||||
fixupBlockIds();
|
||||
ModAPI.blocks["steve"] = block_of_steve;
|
||||
});
|
||||
}
|
||||
ModAPI.dedicatedServer.appendCode(makeSteveBlock);
|
||||
makeSteveBlock();
|
||||
registerSteveClientSide();
|
||||
fixupBlockIds();
|
||||
|
||||
ModAPI.dedicatedServer.appendCode(registerSteveServerSide);
|
||||
@@ -0,0 +1,57 @@
|
||||
(function AddDiamondRecipe() {
|
||||
ModAPI.meta.title("DiamondCraftingRecipeMod");
|
||||
ModAPI.meta.description("Adds a crafting recipe to create diamond blocks from dirt.");
|
||||
|
||||
async function addDiamondRecipe() {
|
||||
await new Promise((res, rej) => {
|
||||
if (ModAPI.blocks) {
|
||||
res()
|
||||
} else {
|
||||
ModAPI.addEventListener("bootstrap", res);
|
||||
}
|
||||
});
|
||||
var ObjectClass = ModAPI.reflect.getClassById("java.lang.Object").class;
|
||||
function ToChar(char) {
|
||||
return ModAPI.reflect.getClassById("java.lang.Character").staticMethods.valueOf.method(char[0].charCodeAt(0));
|
||||
}
|
||||
|
||||
// Define the recipe legend to map characters to items
|
||||
var recipeLegend = {
|
||||
"D": {
|
||||
type: "block",
|
||||
id: "dirt" // Using dirt blocks
|
||||
}
|
||||
};
|
||||
|
||||
// Define the crafting grid pattern for the recipe
|
||||
var recipePattern = [
|
||||
"DDD",
|
||||
"DDD",
|
||||
"DDD"
|
||||
];
|
||||
|
||||
// Convert the recipe pattern and legend into the required format
|
||||
var recipeInternal = [];
|
||||
Object.keys(recipeLegend).forEach((key) => {
|
||||
recipeInternal.push(ToChar(key));
|
||||
var ingredient = (recipeLegend[key].type === "block" ? ModAPI.blocks : ModAPI.items)[recipeLegend[key].id].getRef();
|
||||
recipeInternal.push(ingredient);
|
||||
});
|
||||
|
||||
var recipeContents = recipePattern.map(row => ModAPI.util.str(row));
|
||||
var recipe = ModAPI.util.makeArray(ObjectClass, recipeContents.concat(recipeInternal));
|
||||
|
||||
// Define the output item as diamond_block
|
||||
var resultItem = ModAPI.reflect.getClassById("net.minecraft.item.ItemStack").constructors[1](ModAPI.blocks["diamond_block"].getRef(), 1);
|
||||
|
||||
|
||||
|
||||
// Register the recipe with CraftingManager
|
||||
var craftingManager = ModAPI.reflect.getClassById("net.minecraft.item.crafting.CraftingManager").staticMethods.getInstance.method();
|
||||
ModAPI.hooks.methods.nmic_CraftingManager_addRecipe(craftingManager, resultItem, recipe);
|
||||
}
|
||||
|
||||
ModAPI.dedicatedServer.appendCode(addDiamondRecipe);
|
||||
|
||||
addDiamondRecipe();
|
||||
})();
|
||||
@@ -0,0 +1,43 @@
|
||||
(function AddDiamondRecipe() {
|
||||
ModAPI.meta.title("DiamondCraftingRecipeMod 1.12");
|
||||
ModAPI.meta.description("Adds a crafting recipe to create diamond blocks from dirt.");
|
||||
|
||||
async function registerRecipe(isServer) {
|
||||
if (isServer) {
|
||||
await new Promise((res, rej) => {
|
||||
ModAPI.addEventListener("bootstrap", res);
|
||||
});
|
||||
}
|
||||
const parseJson = ModAPI.reflect.getClassByName("JSONObject").constructors.findLast(x => x.length === 1);
|
||||
const CraftingManager = ModAPI.reflect.getClassByName("CraftingManager");
|
||||
const CraftingManagerMethods = CraftingManager.staticMethods;
|
||||
const jsonData = parseJson(ModAPI.util.str(`{
|
||||
"type": "crafting_shaped", ${/*/or crafting_shapeless/*/""}
|
||||
"pattern": [
|
||||
"I I",
|
||||
" i ",
|
||||
"iii"
|
||||
],
|
||||
"key": {
|
||||
"I": {
|
||||
"item": "minecraft:dirt",
|
||||
data: 0 ${/*/data param optional!!!/*/""}
|
||||
},
|
||||
"i": {
|
||||
"item": "minecraft:grass",
|
||||
data: 0 ${/*/data param optional!!!/*/""}
|
||||
}
|
||||
},
|
||||
"result": {
|
||||
"item": "minecraft:diamond",
|
||||
"data": 0,
|
||||
"count": 4
|
||||
}
|
||||
}`.trim()));
|
||||
const recipeObj = CraftingManagerMethods.func_193376_a.method(jsonData); //convert json to an IRecipe
|
||||
CraftingManagerMethods.func_193379_a.method(ModAPI.util.str("coolrecipeid"), recipeObj); //register recipe under resource location
|
||||
}
|
||||
|
||||
ModAPI.dedicatedServer.appendCode(registerRecipe);
|
||||
registerRecipe(false);
|
||||
})();
|
||||
@@ -0,0 +1,143 @@
|
||||
//utility function to return an array of GuiButtons from an array of JS objects, while automatically binding them
|
||||
function button_utility_script(inputArr, bindingClass, actionBindMode) {
|
||||
// By ZXMushroom63
|
||||
// action bind mode:
|
||||
// 0 - bind to the same as the binding class
|
||||
// 1 - do not bind
|
||||
// 2 - bind to GuiScreen
|
||||
actionBindMode ||= 0;
|
||||
var button = ModAPI.reflect.getClassById("net.minecraft.client.gui.GuiButton").constructors.find(x => x.length === 6);
|
||||
var originalActionPerformed = ModAPI.hooks.methods[ModAPI.util.getMethodFromPackage(actionBindMode === 2 ? "net.minecraft.client.gui.GuiScreen" : bindingClass, "actionPerformed")];
|
||||
var originalInit = ModAPI.hooks.methods[ModAPI.util.getMethodFromPackage(bindingClass, "initGui")];
|
||||
var out = inputArr.flatMap(x => {
|
||||
var btn = button(x.uid, x.x, x.y, x.w, x.h, ModAPI.util.str(x.text));
|
||||
return btn;
|
||||
});
|
||||
if (actionBindMode !== 1) {
|
||||
ModAPI.hooks.methods[ModAPI.util.getMethodFromPackage(actionBindMode === 2 ? "net.minecraft.client.gui.GuiScreen" : bindingClass, "actionPerformed")] = function (...args) {
|
||||
var id = ModAPI.util.wrap(args[1]).getCorrective().id;
|
||||
var jsAction = inputArr.find(x => x.uid === id);
|
||||
if (jsAction) {
|
||||
jsAction.click(ModAPI.util.wrap(args[0]));
|
||||
}
|
||||
return originalActionPerformed.apply(this, args);
|
||||
}
|
||||
}
|
||||
ModAPI.hooks.methods[ModAPI.util.getMethodFromPackage(bindingClass, "initGui")] = function (...args) {
|
||||
originalInit.apply(this, args);
|
||||
var gui = ModAPI.util.wrap(args[0]).getCorrective();
|
||||
out.forEach(guiButton => {
|
||||
gui.buttonList.add(guiButton);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
(() => {
|
||||
ModAPI.require("player");
|
||||
var backlog = [];
|
||||
var delayState = false;
|
||||
|
||||
const originalSend = WebSocket.prototype.send;
|
||||
|
||||
//Override WebSocket.send, so when eagler tries to send messages, it runs our code instead
|
||||
Object.defineProperty(WebSocket.prototype, 'send', {
|
||||
configurable: true,
|
||||
enumerable: false,
|
||||
writable: false,
|
||||
value: function (data) {
|
||||
//If blinking, push data to backlog along with it's websocket instance.
|
||||
if (delayState) {
|
||||
backlog.push({ data: data, thisArg: this });
|
||||
} else { //Else send the data as normal
|
||||
originalSend.call(this, data);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
ModAPI.meta.title("Dupe Hunting");
|
||||
ModAPI.meta.description("⚠️Only works over WS, not local. May induce bans.⚠️");
|
||||
ModAPI.meta.credits("by ZXMushroom63");
|
||||
|
||||
var dupeHuntButtons = [{
|
||||
text: "Silently Close",
|
||||
click: () => {
|
||||
ModAPI.minecraft.displayGuiScreen(null);
|
||||
},
|
||||
x: 0,
|
||||
y: 0,
|
||||
w: 100,
|
||||
h: 20,
|
||||
uid: 142715254
|
||||
},
|
||||
{
|
||||
text: "Toggle Delay",
|
||||
click: () => {
|
||||
delayState = !delayState;
|
||||
alert(delayState ? "Delay On" : "Sending Packets...");
|
||||
if (delayState === false) {
|
||||
for (let i = 0; i < backlog.length; i++) {
|
||||
const backlogItem = backlog[i];
|
||||
originalSend.call(backlogItem.thisArg, backlogItem.data);
|
||||
}
|
||||
backlog = [];
|
||||
}
|
||||
},
|
||||
x: 0,
|
||||
y: 20,
|
||||
w: 100,
|
||||
h: 20,
|
||||
uid: 142715253
|
||||
},
|
||||
{
|
||||
text: "Server Close",
|
||||
click: () => {
|
||||
var CloseWindow = ModAPI.reflect.getClassByName("C0DPacketCloseWindow").constructors[0];
|
||||
ModAPI.player.sendQueue.addToSendQueue(CloseWindow(ModAPI.player.openContainer.getCorrective().windowId));
|
||||
},
|
||||
x: 0,
|
||||
y: 40,
|
||||
w: 100,
|
||||
h: 20,
|
||||
uid: 142715252
|
||||
},
|
||||
{
|
||||
text: "Send & Disconnect",
|
||||
click: () => {
|
||||
delayState = false;
|
||||
for (let i = 0; i < backlog.length; i++) {
|
||||
const backlogItem = backlog[i];
|
||||
originalSend.call(backlogItem.thisArg, backlogItem.data);
|
||||
}
|
||||
backlog = [];
|
||||
ModAPI.mc.getNetHandler().getNetworkManager().doClientDisconnect(ModAPI.hooks._classMap[ModAPI.util.getCompiledName("net.minecraft.util.ChatComponentText")].constructors[0](ModAPI.util.str("Dupe Hunting Utils Disconnect")));
|
||||
},
|
||||
x: 0,
|
||||
y: 60,
|
||||
w: 100,
|
||||
h: 20,
|
||||
uid: 142715251
|
||||
},
|
||||
{
|
||||
text: "Use Chat",
|
||||
click: () => {
|
||||
var p = window.prompt("Input chat/command:", "Hello World");
|
||||
if (p) {
|
||||
ModAPI.player.sendChatMessage(ModAPI.util.str(p));
|
||||
}
|
||||
},
|
||||
x: 0,
|
||||
y: 80,
|
||||
w: 100,
|
||||
h: 20,
|
||||
uid: 142715250
|
||||
}];
|
||||
|
||||
[
|
||||
"net.minecraft.client.gui.inventory.GuiInventory",
|
||||
"net.minecraft.client.gui.inventory.GuiContainerCreative",
|
||||
"net.minecraft.client.gui.inventory.GuiBeacon"
|
||||
].forEach(ui => {
|
||||
button_utility_script(dupeHuntButtons, ui, 2);
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,27 @@
|
||||
(() => {
|
||||
ModAPI.meta.title("/ray_trace_test");
|
||||
ModAPI.meta.description("Mod to test server-side raycasting.");
|
||||
ModAPI.meta.credits("By ZXMushroom63");
|
||||
|
||||
PluginAPI.dedicatedServer.appendCode(function () {
|
||||
PluginAPI.addEventListener("processcommand", (event) => {
|
||||
if (event.command.toLowerCase().startsWith("/ray_trace_test")) {
|
||||
if (
|
||||
ModAPI.reflect.getClassById("net.minecraft.entity.player.EntityPlayerMP").instanceOf(event.sender.getRef())
|
||||
) {
|
||||
//raytrace distance = 6
|
||||
//the 0 on the end is for client side view bobbing (frame based). we are on the server so using 0 as default.
|
||||
var movingObjectPosition = event.sender.rayTrace(6, 0).getCorrective();
|
||||
console.log(movingObjectPosition);
|
||||
|
||||
//var hitVec = movingObjectPosition.hitVec;
|
||||
|
||||
event.sender.addChatMessage(ModAPI.reflect.getClassById("net.minecraft.util.ChatComponentText").constructors[0](
|
||||
movingObjectPosition.toString().getRef() //This is a java string, but that's ok since it goes into a java method.
|
||||
));
|
||||
}
|
||||
event.preventDefault = true;
|
||||
}
|
||||
});
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,14 @@
|
||||
(() => {
|
||||
ModAPI.meta.title("Fullscreen Fixer");
|
||||
ModAPI.meta.description("Makes HTML guis still appear in fullscreen.");
|
||||
ModAPI.meta.credits("By ZXMushroom63");
|
||||
|
||||
var oldF11 = HTMLElement.prototype.requestFullscreen;
|
||||
HTMLElement.prototype.requestFullscreen = function () {
|
||||
if (this instanceof HTMLBodyElement) {
|
||||
oldF11.apply(this, []);
|
||||
} else {
|
||||
document.body.requestFullscreen();
|
||||
}
|
||||
}
|
||||
})();
|
||||
@@ -0,0 +1,18 @@
|
||||
(function MinecartSpeedMod() {
|
||||
ModAPI.meta.title("Faster Minecarts");
|
||||
ModAPI.meta.description("Faster minecarts! Use /minecart_speed {factor} to edit the minecart's speed. Carts are very prone to being flung off rails.");
|
||||
ModAPI.meta.credits("By ZXMushroom63");
|
||||
ModAPI.meta.version("v1.0");
|
||||
|
||||
ModAPI.dedicatedServer.appendCode(function () {
|
||||
ModAPI.addEventListener("processcommand", (event) => {
|
||||
if (event.command.toLowerCase().startsWith("/minecart_speed")) {
|
||||
var speed = parseFloat(event.command.substring("/minecart_speed ".length)) || 1;
|
||||
var trueSpeed = speed * 0.4;
|
||||
ModAPI.hooks.methods.nmei_EntityMinecart_getMaximumSpeed = () => trueSpeed;
|
||||
event.sender.addChatMessage(ModAPI.reflect.getClassById("net.minecraft.util.ChatComponentText").constructors[0](ModAPI.util.str("Set minecart speed to "+speed)));
|
||||
event.preventDefault = true;
|
||||
}
|
||||
});
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,7 @@
|
||||
const originalGetBurnTime = ModAPI.hooks.methods[ModAPI.util.getMethodFromPackage("net.minecraft.tileentity.TileEntityFurnace", "getItemBurnTime")];
|
||||
ModAPI.hooks.methods[ModAPI.util.getMethodFromPackage("net.minecraft.tileentity.TileEntityFurnace", "getItemBurnTime")] = function (...args) {
|
||||
if (args[0].$item === ModAPI.items.string.getRef()) {
|
||||
return 50;
|
||||
}
|
||||
return originalGetBurnTime.apply(this, args);
|
||||
};
|
||||
@@ -0,0 +1,44 @@
|
||||
(function grapplehook() {
|
||||
PluginAPI.require("player"); //Require the player
|
||||
globalThis.GrappleHookPlugin = {
|
||||
oldXYZ: [0, 0, 0], //The previous hook position.
|
||||
prev: "NONE", //The previous state
|
||||
scaleH: 0.25, //Used for X and Z velocity
|
||||
scaleV: 0.15, //((Grapple Y) minus (Player Y)) times scaleV
|
||||
lift: 0.4, //Base vertical motion
|
||||
crouchToCancel: true //Whether or not crouching should disable the grappling hook.
|
||||
};
|
||||
PluginAPI.addEventListener("update", () => { //Every client tick
|
||||
var player = ModAPI.player.getCorrective(); //Gets the corrective version of the player object. This removes broken proerty suffixes. You usually don't need this, but in my case, I do.
|
||||
if (!player.fishEntity) { //If the fish hook does not exist.
|
||||
if (GrappleHookPlugin.prev === "GROUND" && (!GrappleHookPlugin.crouchToCancel || !player.isSneaking())) { //If the old state was ground
|
||||
GrappleHookPlugin.prev = "NONE"; //Update the state
|
||||
var mx = GrappleHookPlugin.oldXYZ[0] - player.posX; //Get delta X
|
||||
var my = GrappleHookPlugin.oldXYZ[1] - player.posY; //Get delta Y
|
||||
var mz = GrappleHookPlugin.oldXYZ[2] - player.posZ; //Get delta Z
|
||||
mx *= GrappleHookPlugin.scaleH; //Multiply by horizontal scale
|
||||
my *= GrappleHookPlugin.scaleV; //Multiply by vertical scale
|
||||
mz *= GrappleHookPlugin.scaleH; //Multiply by horizontal scale
|
||||
player.motionX += mx; //Add x motion
|
||||
player.motionY += my + GrappleHookPlugin.lift; //Add y motion, plus base lift.
|
||||
player.motionZ += mz; //Add z motion
|
||||
} else {
|
||||
GrappleHookPlugin.prev = "NONE";
|
||||
}
|
||||
} else if (GrappleHookPlugin.prev === "NONE") { //If the hook exists, but the previous state was NONE, update the state.
|
||||
GrappleHookPlugin.prev = "AIR";
|
||||
}
|
||||
if (
|
||||
player.fishEntity !== undefined && //If the fish hook exists
|
||||
GrappleHookPlugin.prev === "AIR" && //And the hook was previously in the air
|
||||
(player.fishEntity.inGround || player.fishEntity.onGround) //And the hook is in the ground
|
||||
) {
|
||||
GrappleHookPlugin.oldXYZ = [ //Set old grapple hook position
|
||||
player.fishEntity.posX,
|
||||
player.fishEntity.posY,
|
||||
player.fishEntity.posZ,
|
||||
];
|
||||
GrappleHookPlugin.prev = "GROUND";//Update state
|
||||
}
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,137 @@
|
||||
(()=>{
|
||||
const itemTexture = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAADySURBVFhH7ZQxDoMwDEVNr4G6VmJC6mk4Itdh7VpxjsBPDaKVCLZxypInIccg5zs/CVQoKAj8uHLjeETouo6HvlQcU3yJ932PIKkTceRAFH8NA6dE3IzbVogdQBOPtuVXfk5IJ8jWhKY4SxPaQvcmLEWuTUj/A1sqiEEcTQBENDWjvh3mvZtxccLiwMqvE0DrhNUBCCy1KSdAUsPiwFYcpM5ENrYWh3tdI4cT4dk0MSKPXzMSRSC+PMi14mcO4e7esv2iJqyHEGDVPCR6jyMC5luERXOfuoY7QFi8MKsDe6tXk8OBv7Ge/E96DZeKFwoOEE1wUX7TFh5zsgAAAABJRU5ErkJggg==";
|
||||
ModAPI.meta.title("guns");
|
||||
ModAPI.meta.version("v1.0");
|
||||
ModAPI.meta.icon(itemTexture);
|
||||
ModAPI.meta.description("Requires AsyncSink.");
|
||||
|
||||
ModAPI.require("player");
|
||||
|
||||
function PistolItem() {
|
||||
var recoilSpeed = 0; //recoil controller
|
||||
var DamageSourceClass = ModAPI.reflect.getClassByName("DamageSource");
|
||||
var creativeMiscTab = ModAPI.reflect.getClassById("net.minecraft.creativetab.CreativeTabs").staticVariables.tabMisc;
|
||||
var itemClass = ModAPI.reflect.getClassById("net.minecraft.item.Item");
|
||||
var itemSuper = ModAPI.reflect.getSuper(itemClass, (x) => x.length === 1);
|
||||
var nmi_ItemPistol = function nmi_ItemPistol() {
|
||||
itemSuper(this); //Use super function to get block properties on this class.
|
||||
this.$setCreativeTab(creativeMiscTab);
|
||||
}
|
||||
|
||||
ModAPI.addEventListener("update", ()=>{ //recoil update loop (client)
|
||||
ModAPI.player.rotationPitch -= recoilSpeed;
|
||||
recoilSpeed *= 0.7;
|
||||
});
|
||||
|
||||
function entityRayCast(player, world, range) {
|
||||
const HEADSHOT_MAX_DISTANCE_FROM_HEAD = 0.72;
|
||||
var eyePosition = player.getPositionEyes(0.0);
|
||||
var targetPosition = player.rayTrace(range, 0).hitVec;
|
||||
var entities = world.getEntitiesWithinAABBExcludingEntity(
|
||||
player.getRef(),
|
||||
player.getEntityBoundingBox().expand(range, range, range).getRef()
|
||||
).getCorrective().array;
|
||||
var closestEntity = null;
|
||||
var isHeadshot = false;
|
||||
var closestDistance = range;
|
||||
|
||||
// Iterate through all entities to find the one the player is looking at
|
||||
for (var i = 0; i < entities.length; i++) {
|
||||
if (!entities[i]) {
|
||||
continue;
|
||||
}
|
||||
var entity = entities[i];
|
||||
|
||||
// Check if the entity's bounding box intersects with the player's ray
|
||||
var entityBB = entity.getEntityBoundingBox().expand(0.3, 0.3, 0.3);
|
||||
var intercept = entityBB.calculateIntercept(eyePosition.getRef(), targetPosition.getRef());
|
||||
|
||||
if (intercept != null) {
|
||||
var distance = eyePosition.distanceTo(intercept.hitVec.getRef());
|
||||
if (distance < closestDistance) {
|
||||
closestDistance = distance;
|
||||
closestEntity = entity;
|
||||
isHeadshot = entity.getPositionEyes(0.0).distanceTo(intercept.hitVec.getRef()) < HEADSHOT_MAX_DISTANCE_FROM_HEAD;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var rayTraceResult = closestEntity;
|
||||
if (rayTraceResult != null){
|
||||
return {entity: rayTraceResult, headshot: isHeadshot};
|
||||
} else{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
ModAPI.reflect.prototypeStack(itemClass, nmi_ItemPistol);
|
||||
nmi_ItemPistol.prototype.$onItemRightClick = function ($itemstack, $world, $player) {
|
||||
var cactus = DamageSourceClass.staticVariables.cactus;
|
||||
var world = ModAPI.util.wrap($world);
|
||||
var entityplayer = ModAPI.util.wrap($player);
|
||||
var shotentitydata = entityRayCast(entityplayer, world, 16.0);
|
||||
if (shotentitydata != null){
|
||||
if (world.isRemote) {
|
||||
recoilSpeed += 4;
|
||||
} else {
|
||||
shotentitydata.entity.attackEntityFrom(cactus, 10 + (16 * shotentitydata.headshot));
|
||||
if (shotentitydata.headshot) {
|
||||
console.log("H E A D S H O T");
|
||||
}
|
||||
world.playSoundAtEntity(entityplayer.getRef(), ModAPI.util.str("tile.piston.out"), 1.0, 1.8);
|
||||
}
|
||||
} else if (!world.isRemote) {
|
||||
world.playSoundAtEntity(entityplayer.getRef(), ModAPI.util.str("random.click"), 1.0, 1.8);
|
||||
}
|
||||
return $itemstack;
|
||||
}
|
||||
|
||||
function internal_reg() {
|
||||
var pistol_item = (new nmi_ItemPistol()).$setUnlocalizedName(
|
||||
ModAPI.util.str("pistol")
|
||||
).$setMaxStackSize(1);
|
||||
itemClass.staticMethods.registerItem.method(ModAPI.keygen.item("pistol"), ModAPI.util.str("pistol"), pistol_item);
|
||||
ModAPI.items["pistol"] = pistol_item;
|
||||
|
||||
return pistol_item;
|
||||
}
|
||||
|
||||
if (ModAPI.items) {
|
||||
return internal_reg();
|
||||
} else {
|
||||
ModAPI.addEventListener("bootstrap", internal_reg);
|
||||
}
|
||||
}
|
||||
|
||||
ModAPI.dedicatedServer.appendCode(PistolItem);
|
||||
var pistol_item = PistolItem();
|
||||
|
||||
ModAPI.addEventListener("lib:asyncsink", async () => {
|
||||
ModAPI.addEventListener("lib:asyncsink:registeritems", (renderItem)=>{
|
||||
renderItem.registerItem(pistol_item, ModAPI.util.str("pistol"));
|
||||
});
|
||||
AsyncSink.L10N.set("item.pistol.name", "Pistol");
|
||||
AsyncSink.setFile("resourcepacks/AsyncSinkLib/assets/minecraft/models/item/pistol.json", JSON.stringify(
|
||||
{
|
||||
"parent": "builtin/generated",
|
||||
"textures": {
|
||||
"layer0": "items/pistol"
|
||||
},
|
||||
"display": {
|
||||
"thirdperson": {
|
||||
"rotation": [ 5, 80, -45 ],
|
||||
"translation": [ 0, 1, -3 ],
|
||||
"scale": [ 1.0, 1.0, 1.0 ]
|
||||
},
|
||||
"firstperson": {
|
||||
"rotation": [ 0, -135, 25 ],
|
||||
"translation": [ 0, 4, 2 ],
|
||||
"scale": [ 1.8, 1.8, 1.8 ]
|
||||
}
|
||||
}
|
||||
}
|
||||
));
|
||||
AsyncSink.setFile("resourcepacks/AsyncSinkLib/assets/minecraft/textures/items/pistol.png", await (await fetch(
|
||||
itemTexture
|
||||
)).arrayBuffer());
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,184 @@
|
||||
(()=>{
|
||||
const itemTexture = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAADySURBVFhH7ZQxDoMwDEVNr4G6VmJC6mk4Itdh7VpxjsBPDaKVCLZxypInIccg5zs/CVQoKAj8uHLjeETouo6HvlQcU3yJ932PIKkTceRAFH8NA6dE3IzbVogdQBOPtuVXfk5IJ8jWhKY4SxPaQvcmLEWuTUj/A1sqiEEcTQBENDWjvh3mvZtxccLiwMqvE0DrhNUBCCy1KSdAUsPiwFYcpM5ENrYWh3tdI4cT4dk0MSKPXzMSRSC+PMi14mcO4e7esv2iJqyHEGDVPCR6jyMC5luERXOfuoY7QFi8MKsDe6tXk8OBv7Ge/E96DZeKFwoOEE1wUX7TFh5zsgAAAABJRU5ErkJggg==";
|
||||
ModAPI.meta.title("guns");
|
||||
ModAPI.meta.version("v1.0");
|
||||
ModAPI.meta.icon(itemTexture);
|
||||
ModAPI.meta.description("Requires AsyncSink.");
|
||||
|
||||
ModAPI.require("player");
|
||||
|
||||
function PistolItem() {
|
||||
var recoilSpeed = 0; //recoil controller
|
||||
var DamageSourceClass = ModAPI.reflect.getClassByName("DamageSource");
|
||||
var creativeMiscTab = ModAPI.reflect.getClassById("net.minecraft.creativetab.CreativeTabs").staticVariables.tabMisc;
|
||||
var itemClass = ModAPI.reflect.getClassById("net.minecraft.item.Item");
|
||||
var itemSuper = ModAPI.reflect.getSuper(itemClass, (x) => x.length === 1);
|
||||
var nmi_ItemPistol = function nmi_ItemPistol() {
|
||||
itemSuper(this); //Use super function to get block properties on this class.
|
||||
this.$setCreativeTab(creativeMiscTab);
|
||||
}
|
||||
|
||||
ModAPI.addEventListener("update", ()=>{ //recoil update loop (client)
|
||||
ModAPI.player.rotationPitch -= recoilSpeed;
|
||||
recoilSpeed *= 0.7;
|
||||
});
|
||||
|
||||
function entityRayCast(player, world, range) {
|
||||
const HEADSHOT_MAX_DISTANCE_FROM_HEAD = 0.72;
|
||||
var eyePosition = player.getPositionEyes(0.0);
|
||||
var targetPosition = player.rayTrace(range, 0).hitVec;
|
||||
var entities = world.getEntitiesWithinAABBExcludingEntity(
|
||||
player.getRef(),
|
||||
player.getEntityBoundingBox().expand(range, range, range).getRef()
|
||||
).getCorrective().array;
|
||||
var closestEntity = null;
|
||||
var isHeadshot = false;
|
||||
var closestDistance = range;
|
||||
|
||||
// Iterate through all entities to find the one the player is looking at
|
||||
for (var i = 0; i < entities.length; i++) {
|
||||
if (!entities[i]) {
|
||||
continue;
|
||||
}
|
||||
var entity = entities[i];
|
||||
|
||||
// Check if the entity's bounding box intersects with the player's ray
|
||||
var entityBB = entity.getEntityBoundingBox().expand(0.3, 0.3, 0.3);
|
||||
var intercept = entityBB.calculateIntercept(eyePosition.getRef(), targetPosition.getRef());
|
||||
|
||||
if (intercept != null) {
|
||||
var distance = eyePosition.distanceTo(intercept.hitVec.getRef());
|
||||
if (distance < closestDistance) {
|
||||
closestDistance = distance;
|
||||
closestEntity = entity;
|
||||
isHeadshot = entity.getPositionEyes(0.0).distanceTo(intercept.hitVec.getRef()) < HEADSHOT_MAX_DISTANCE_FROM_HEAD;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var rayTraceResult = closestEntity;
|
||||
if (rayTraceResult != null){
|
||||
return {entity: rayTraceResult, headshot: isHeadshot};
|
||||
} else{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
ModAPI.reflect.prototypeStack(itemClass, nmi_ItemPistol);
|
||||
nmi_ItemPistol.prototype.$onItemRightClick = function ($itemstack, $world, $player) {
|
||||
var cactus = DamageSourceClass.staticVariables.cactus;
|
||||
var world = ModAPI.util.wrap($world);
|
||||
var entityplayer = ModAPI.util.wrap($player);
|
||||
var shotentitydata = entityRayCast(entityplayer, world, 16.0);
|
||||
if (shotentitydata != null){
|
||||
if (world.isRemote) {
|
||||
recoilSpeed += 4;
|
||||
} else {
|
||||
shotentitydata.entity.attackEntityFrom(cactus, 10 + (16 * shotentitydata.headshot));
|
||||
if (shotentitydata.headshot) {
|
||||
console.log("H E A D S H O T");
|
||||
}
|
||||
world.playSoundAtEntity(entityplayer.getRef(), ModAPI.util.str("tile.piston.out"), 1.0, 1.8);
|
||||
}
|
||||
} else if (!world.isRemote) {
|
||||
world.playSoundAtEntity(entityplayer.getRef(), ModAPI.util.str("random.click"), 1.0, 1.8);
|
||||
}
|
||||
return $itemstack;
|
||||
}
|
||||
|
||||
async function addGunRecipe(gunItem) {
|
||||
var ObjectClass = ModAPI.reflect.getClassById("java.lang.Object").class;
|
||||
function ToChar(char) {
|
||||
return ModAPI.reflect.getClassById("java.lang.Character").staticMethods.valueOf.method(char[0].charCodeAt(0));
|
||||
}
|
||||
|
||||
// Define the recipe legend to map characters to items
|
||||
var recipeLegend = {
|
||||
"I": {
|
||||
type: "item",
|
||||
id: "iron_ingot" // Using dirt blocks
|
||||
},
|
||||
"C": {
|
||||
type: "block",
|
||||
id: "iron_block" // Using dirt blocks
|
||||
},
|
||||
"Q": {
|
||||
type: "item",
|
||||
id: "gunpowder" // Using dirt blocks
|
||||
},
|
||||
};
|
||||
|
||||
// Define the crafting grid pattern for the recipe
|
||||
var recipePattern = [
|
||||
"IIC",
|
||||
" QI"
|
||||
];
|
||||
|
||||
// Convert the recipe pattern and legend into the required format
|
||||
var recipeInternal = [];
|
||||
Object.keys(recipeLegend).forEach((key) => {
|
||||
recipeInternal.push(ToChar(key));
|
||||
var ingredient = (recipeLegend[key].type === "block" ? ModAPI.blocks : ModAPI.items)[recipeLegend[key].id].getRef();
|
||||
recipeInternal.push(ingredient);
|
||||
});
|
||||
|
||||
var recipeContents = recipePattern.flatMap(row => ModAPI.util.str(row));
|
||||
var recipe = ModAPI.util.makeArray(ObjectClass, recipeContents.concat(recipeInternal));
|
||||
|
||||
var resultItem = ModAPI.reflect.getClassById("net.minecraft.item.ItemStack").constructors[4](gunItem, 1);
|
||||
|
||||
|
||||
// Register the recipe with CraftingManager
|
||||
var craftingManager = ModAPI.reflect.getClassById("net.minecraft.item.crafting.CraftingManager").staticMethods.getInstance.method();
|
||||
ModAPI.hooks.methods.nmic_CraftingManager_addRecipe(craftingManager, resultItem, recipe);
|
||||
}
|
||||
|
||||
function internal_reg() {
|
||||
var pistol_item = (new nmi_ItemPistol()).$setUnlocalizedName(
|
||||
ModAPI.util.str("pistol")
|
||||
).$setMaxStackSize(1);
|
||||
itemClass.staticMethods.registerItem.method(ModAPI.keygen.item("pistol"), ModAPI.util.str("pistol"), pistol_item);
|
||||
ModAPI.items["pistol"] = pistol_item;
|
||||
addGunRecipe(pistol_item);
|
||||
return pistol_item;
|
||||
}
|
||||
|
||||
if (ModAPI.items) {
|
||||
return internal_reg();
|
||||
} else {
|
||||
ModAPI.addEventListener("bootstrap", internal_reg);
|
||||
}
|
||||
}
|
||||
|
||||
ModAPI.dedicatedServer.appendCode(PistolItem);
|
||||
var pistol_item = PistolItem();
|
||||
|
||||
ModAPI.addEventListener("lib:asyncsink", async () => {
|
||||
ModAPI.addEventListener("lib:asyncsink:registeritems", (renderItem)=>{
|
||||
renderItem.registerItem(pistol_item, ModAPI.util.str("pistol"));
|
||||
});
|
||||
AsyncSink.L10N.set("item.pistol.name", "Pistol");
|
||||
AsyncSink.setFile("resourcepacks/AsyncSinkLib/assets/minecraft/models/item/pistol.json", JSON.stringify(
|
||||
{
|
||||
"parent": "builtin/generated",
|
||||
"textures": {
|
||||
"layer0": "items/pistol"
|
||||
},
|
||||
"display": {
|
||||
"thirdperson": {
|
||||
"rotation": [ 5, 80, -45 ],
|
||||
"translation": [ 0, 1, -3 ],
|
||||
"scale": [ 1.0, 1.0, 1.0 ]
|
||||
},
|
||||
"firstperson": {
|
||||
"rotation": [ 0, -135, 25 ],
|
||||
"translation": [ 0, 4, 2 ],
|
||||
"scale": [ 1.8, 1.8, 1.8 ]
|
||||
}
|
||||
}
|
||||
}
|
||||
));
|
||||
AsyncSink.setFile("resourcepacks/AsyncSinkLib/assets/minecraft/textures/items/pistol.png", await (await fetch(
|
||||
itemTexture
|
||||
)).arrayBuffer());
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,40 @@
|
||||
//Metadata for the mod
|
||||
ModAPI.meta.title("SimpleHats");
|
||||
ModAPI.meta.credits("Made with ❤️ by ZXMushroom63");
|
||||
ModAPI.meta.description("Use /hat to wear whatever you are holding!");
|
||||
|
||||
// Run the code on the server
|
||||
ModAPI.dedicatedServer.appendCode(function () {
|
||||
// Find the constructor for the held item change packet that has only one argument.
|
||||
// This will be used to notify the client that their hotbar has been updated.
|
||||
var makePacketItemChange = ModAPI.reflect.getClassByName("S09PacketHeldItemChange").constructors.find(x => x.length === 1);
|
||||
|
||||
// When the server is processing a command
|
||||
ModAPI.addEventListener("processcommand", (event) => {
|
||||
// If the command starts with /hat
|
||||
if (event.command.toLowerCase().startsWith("/hat")) {
|
||||
// Cancel if the sender isn't a player
|
||||
if (!ModAPI.reflect.getClassById("net.minecraft.entity.player.EntityPlayerMP").instanceOf(event.sender.getRef())) { return };
|
||||
|
||||
// Otherwise, get the current held item
|
||||
var heldItem = event.sender.inventory.getCurrentItem();
|
||||
|
||||
// Get the contents of the helmet slot
|
||||
var armorItem = event.sender.inventory.armorInventory[3];
|
||||
|
||||
// Get the inventory index of the current held item
|
||||
var hotbarIdx = event.sender.inventory.currentItem;
|
||||
|
||||
// Set the helmet slot to heldItem.getRef() (raw java object) if heldItem exists, otherwise set it to null
|
||||
event.sender.inventory.armorInventory[3] = heldItem ? heldItem.getRef() : null;
|
||||
|
||||
// Set the hotbar slot to the previous value of the helmet slot
|
||||
event.sender.inventory.mainInventory[hotbarIdx] = armorItem ? armorItem.getRef() : null;
|
||||
|
||||
// Use the sendPacket method to send a item change packet to the client.
|
||||
event.sender.playerNetServerHandler.sendPacket(makePacketItemChange(hotbarIdx));
|
||||
|
||||
event.preventDefault = true;
|
||||
}
|
||||
});
|
||||
});
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,168 @@
|
||||
// Library to make adding custom items with EaglerForgeInjector much easier.
|
||||
(function LibItems() {
|
||||
ModAPI.meta.title("LibCustomItems");
|
||||
ModAPI.meta.credits("By ZXMushroom63");
|
||||
ModAPI.meta.icon("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAQdJREFUOE9jZGBg+M9AAWAEGbBl2QmyjPCJsmAgaABbdybc8F+l01EswmsATONXLi4GYSkpBgZ+foY1O3cyuHWuhhuC1QBkjf///QMrFtHWZmD4+BHDEBQDUGzU1ITb8ubqVZyGoBjwsCONQYqXl0FYU5MBpAlsKxRgM+STUwoDhgG66upgZ4IAuiEooRcXx/DpCRuqAU97shg0jYzgfsVpSFwcg5mZGcOedRewGDBhAgPDokUohsBthmoE8U+dOoXdBfHHjoElUQxB03i9oABspnTJNFQXgARB3oAbwsAAdirMRmSNMFdhTQcwQ/BpxGsAzCUwRSCn4gJE5QV8uQxuAFlZEaoJAKrYrAHl38o6AAAAAElFTkSuQmCC");
|
||||
ModAPI.meta.description("Library to make adding basic custom items easier.");
|
||||
ModAPI.events.newEvent("lib:libcustomitems:loaded");
|
||||
function libServerside() {
|
||||
var packetblockchange = ModAPI.reflect.getClassByName("S23PacketBlockChange").constructors.find(x => { return x.length === 2 });
|
||||
var sendPacket = ModAPI.reflect.getClassByName("NetHandlerPlayServer").methods.sendPacket.method;
|
||||
globalThis.LCI_REGISTRY ||= [];
|
||||
globalThis.LCI_RMBEVENTS ||= {};
|
||||
globalThis.LCI_LMBEVENTS ||= {};
|
||||
globalThis.LCI_RECIPEEVENTS ||= {};
|
||||
globalThis.LCI_ITEMDB ||= {};
|
||||
globalThis.LibCustomItems = {
|
||||
makeItemStack: function makeItemStack(tag) {
|
||||
return globalThis.LCI_ITEMDB[tag] || null;
|
||||
}
|
||||
};
|
||||
var useName = ModAPI.util.getMethodFromPackage("net.minecraft.network.NetHandlerPlayServer", "processPlayerBlockPlacement");
|
||||
var oldUse = ModAPI.hooks.methods[useName];
|
||||
ModAPI.hooks.methods[useName] = function ($this, packet) {
|
||||
if ($this?.$playerEntity?.$inventory && $this.$playerEntity.$inventory.$getCurrentItem()) {
|
||||
var item = $this.$playerEntity.$inventory.$getCurrentItem();
|
||||
if (item.$stackTagCompound && item.$stackTagCompound.$hasKey(ModAPI.util.str("display"), 10)) {
|
||||
var displayTag = item.$stackTagCompound.$getCompoundTag(ModAPI.util.str("display"));
|
||||
if (displayTag.$hasKey(ModAPI.util.str("Lore"), 9)) {
|
||||
var loreTag = displayTag.$getTag(ModAPI.util.str("Lore"));
|
||||
if (loreTag.$tagCount() > 0 && globalThis.LCI_REGISTRY.includes(ModAPI.util.ustr(loreTag.$getStringTagAt(0)))) {
|
||||
var cid = ModAPI.util.ustr(loreTag.$getStringTagAt(0));
|
||||
if (!globalThis.LCI_RMBEVENTS[cid]) {
|
||||
return oldUse.apply(this, [$this, packet]);
|
||||
}
|
||||
var positionTag = Object.keys(packet).filter(x => { return x.startsWith("$position") })[0];
|
||||
if (packet[positionTag].$x === -1 && packet[positionTag].$y === -1 && packet[positionTag].$z === -1) {
|
||||
return 0;
|
||||
}
|
||||
var r = globalThis.LCI_RMBEVENTS[cid].call(globalThis,
|
||||
new Proxy($this.$playerEntity, ModAPI.util.TeaVM_to_Recursive_BaseData_ProxyConf),
|
||||
new Proxy($this.$serverController.$worldServerForDimension($this.$playerEntity.$dimension), ModAPI.util.TeaVM_to_Recursive_BaseData_ProxyConf),
|
||||
new Proxy(item, ModAPI.util.TeaVM_to_Recursive_BaseData_ProxyConf),
|
||||
new Proxy(packet[positionTag], ModAPI.util.TeaVM_to_Recursive_BaseData_ProxyConf));
|
||||
if (!r) {
|
||||
return oldUse.apply(this, [$this, packet]);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return oldUse.apply(this, [$this, packet]);
|
||||
}
|
||||
var digName = ModAPI.util.getMethodFromPackage("net.minecraft.network.NetHandlerPlayServer", "processPlayerDigging");
|
||||
var oldDig = ModAPI.hooks.methods[digName];
|
||||
ModAPI.hooks.methods[digName] = function ($this, packet) {
|
||||
if ($this?.$playerEntity?.$inventory && $this.$playerEntity.$inventory.$getCurrentItem()) {
|
||||
var item = $this.$playerEntity.$inventory.$getCurrentItem();
|
||||
if (item.$stackTagCompound && item.$stackTagCompound.$hasKey(ModAPI.util.str("display"), 10)) {
|
||||
var displayTag = item.$stackTagCompound.$getCompoundTag(ModAPI.util.str("display"));
|
||||
if (displayTag.$hasKey(ModAPI.util.str("Lore"), 9)) {
|
||||
var loreTag = displayTag.$getTag(ModAPI.util.str("Lore"));
|
||||
if (loreTag.$tagCount() > 0 && globalThis.LCI_REGISTRY.includes(ModAPI.util.ustr(loreTag.$getStringTagAt(0)))) {
|
||||
var cid = ModAPI.util.ustr(loreTag.$getStringTagAt(0));
|
||||
if (!globalThis.LCI_LMBEVENTS[cid]) {
|
||||
return oldDig.apply(this, [$this, packet]);
|
||||
}
|
||||
var $status = ModAPI.util.getNearestProperty(packet, "$status");
|
||||
var statusTag = Object.keys(packet[$status]).find(x => { return x.startsWith("$name") });
|
||||
var positionTag = Object.keys(packet).filter(x => { return x.startsWith("$position") })[0];
|
||||
var stat = ModAPI.util.unstr(packet[$status][statusTag]);
|
||||
if (stat === "START_DESTROY_BLOCK") {
|
||||
sendPacket($this, packetblockchange($this.$serverController.$worldServerForDimension($this.$playerEntity.$dimension), packet[positionTag]));
|
||||
}
|
||||
if (stat !== "START_DESTROY_BLOCK") {
|
||||
if (stat === "STOP_DESTROY_BLOCK") {
|
||||
sendPacket($this, packetblockchange($this.$serverController.$worldServerForDimension($this.$playerEntity.$dimension), packet[positionTag]));
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
var r = globalThis.LCI_LMBEVENTS[cid].call(globalThis,
|
||||
new Proxy($this.$playerEntity, ModAPI.util.TeaVM_to_Recursive_BaseData_ProxyConf),
|
||||
new Proxy($this.$serverController.$worldServerForDimension($this.$playerEntity.$dimension), ModAPI.util.TeaVM_to_Recursive_BaseData_ProxyConf),
|
||||
new Proxy(item, ModAPI.util.TeaVM_to_Recursive_BaseData_ProxyConf),
|
||||
new Proxy(packet[positionTag], ModAPI.util.TeaVM_to_Recursive_BaseData_ProxyConf));
|
||||
if (!r) {
|
||||
return oldDig.apply(this, [$this, packet]);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return oldDig.apply(this, [$this, packet]);
|
||||
}
|
||||
}
|
||||
function LCI_registerItem(data) {
|
||||
globalThis.LCI_REGISTRY ||= [];
|
||||
globalThis.LCI_RMBEVENTS ||= {};
|
||||
globalThis.LCI_LMBEVENTS ||= {};
|
||||
globalThis.LCI_RECIPEEVENTS ||= {};
|
||||
globalThis.LCI_ITEMDB ||= {};
|
||||
globalThis.LCI_REGISTRY.push(data.tag);
|
||||
if (data.onRightClickGround) {
|
||||
globalThis.LCI_RMBEVENTS[data.tag] = new Function("user", "world", "itemstack", "blockpos", data.onRightClickGround);
|
||||
}
|
||||
if (data.onLeftClickGround) {
|
||||
globalThis.LCI_LMBEVENTS[data.tag] = new Function("user", "world", "itemstack", "blockpos", data.onLeftClickGround);
|
||||
}
|
||||
if (data.craftingExtra) {
|
||||
globalThis.LCI_RECIPEEVENTS[data.tag] = new Function("itemstack", data.craftingExtra);
|
||||
}
|
||||
var ObjectClass = ModAPI.reflect.getClassById("java.lang.Object").class;
|
||||
function ToChar(char) {
|
||||
return ModAPI.reflect.getClassById("java.lang.Character").staticMethods.valueOf.method(char[0].charCodeAt(0));
|
||||
}
|
||||
ModAPI.dedicatedServer.appendCode(`(function () {
|
||||
function handler() {
|
||||
LCI_registerItem(${JSON.stringify(data)});
|
||||
ModAPI.removeEventListener("tick", handler);
|
||||
}
|
||||
ModAPI.addEventListener("tick", handler);
|
||||
})()`);
|
||||
var recipeInternal = [];
|
||||
Object.keys(data.recipeLegend).forEach((key) => {
|
||||
recipeInternal.push(ToChar(key));
|
||||
var ingredient = null;
|
||||
var schema = data.recipeLegend[key];
|
||||
if (schema.type === "block") {
|
||||
ingredient = ModAPI.blocks[schema.id].getRef();
|
||||
} else {
|
||||
ingredient = ModAPI.items[schema.id].getRef();
|
||||
}
|
||||
recipeInternal.push(ingredient);
|
||||
});
|
||||
var recipeContents = data.recipe.flatMap(x => { return ModAPI.util.str(x) });
|
||||
var recipe = ModAPI.util.makeArray(ObjectClass, recipeContents.concat(recipeInternal));
|
||||
|
||||
var testItem = ModAPI.reflect.getClassById("net.minecraft.item.ItemStack").constructors[4](ModAPI.items[data.base].getRef(), data.qty);
|
||||
testItem.$stackTagCompound = ModAPI.reflect.getClassById("net.minecraft.nbt.NBTTagCompound").constructors[0]();
|
||||
testItem.$stackTagCompound.$setTag(ModAPI.util.str("display"), ModAPI.reflect.getClassById("net.minecraft.nbt.NBTTagCompound").constructors[0]());
|
||||
var displayTag = testItem.$stackTagCompound.$getCompoundTag(ModAPI.util.str("display"));
|
||||
displayTag.$setString(ModAPI.util.str("Name"), ModAPI.util.str(data.name));
|
||||
var lore = ModAPI.reflect.getClassById("net.minecraft.nbt.NBTTagList").constructors[0]();
|
||||
lore.$appendTag(ModAPI.reflect.getClassById("net.minecraft.nbt.NBTTagString").constructors.filter(x => { return x.length === 1 })[0](ModAPI.util.str(data.tag)));
|
||||
displayTag.$setTag(ModAPI.util.str("Lore"), lore);
|
||||
if (globalThis.LCI_RECIPEEVENTS[data.tag]) {
|
||||
globalThis.LCI_RECIPEEVENTS[data.tag](new Proxy(testItem, ModAPI.util.TeaVM_to_Recursive_BaseData_ProxyConf));
|
||||
}
|
||||
globalThis.LCI_ITEMDB[data.tag] = new Proxy(testItem, ModAPI.util.TeaVM_to_Recursive_BaseData_ProxyConf);
|
||||
|
||||
var craftingManager = ModAPI.reflect.getClassById("net.minecraft.item.crafting.CraftingManager").staticMethods.getInstance.method();
|
||||
if((data.useRecipe !== false) || (data.useRecipe !== "false")) {
|
||||
ModAPI.hooks.methods.nmic_CraftingManager_addRecipe(craftingManager, testItem, recipe);
|
||||
}
|
||||
}
|
||||
ModAPI.dedicatedServer.appendCode(libServerside);
|
||||
ModAPI.dedicatedServer.appendCode("globalThis.LCI_registerItem = " + LCI_registerItem.toString());
|
||||
window.LibCustomItems = {};
|
||||
LibCustomItems.registerItem = function register(data) {
|
||||
LCI_registerItem(data);
|
||||
}
|
||||
LibCustomItems.makeItemStack = function makeItemStack(tag) {
|
||||
return globalThis.LCI_ITEMDB[tag] || null;
|
||||
}
|
||||
ModAPI.events.callEvent("lib:libcustomitems:loaded", {});
|
||||
})();
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,8 @@
|
||||
// Use ModAPI.util.getMethodFromPackage to find the internal name of the block destroy effect method
|
||||
// and we replace it with our own function, that does nothing.
|
||||
ModAPI.hooks.methods[
|
||||
ModAPI.util.getMethodFromPackage(
|
||||
"net.minecraft.client.particles.EffectRenderer",
|
||||
"addBlockDestroyEffects"
|
||||
)
|
||||
] = () => {}
|
||||
@@ -0,0 +1,4 @@
|
||||
ModAPI.hooks.methods[ModAPI.util.getMethodFromPackage("net.minecraft.client.particle.EffectRenderer", "renderParticles")] = ()=>{};
|
||||
ModAPI.hooks.methods[ModAPI.util.getMethodFromPackage("net.minecraft.client.particle.EffectRenderer", "addEffect")] = ()=>{};
|
||||
ModAPI.hooks.methods[ModAPI.util.getMethodFromPackage("net.minecraft.client.particle.EffectRenderer", "addBlockDestroyEffects")] = ()=>{};
|
||||
ModAPI.hooks.methods[ModAPI.util.getMethodFromPackage("net.minecraft.client.particle.EffectRenderer", "hasParticlesInAlphaLayer")] = ()=>{return 0};
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,284 @@
|
||||
(function servermod() {
|
||||
ModAPI.meta.title("Server Manager");
|
||||
ModAPI.meta.version("a0");
|
||||
ModAPI.meta.description("_");
|
||||
ModAPI.meta.credits("ZXMushroom63 & radmanplays");
|
||||
|
||||
|
||||
const gui = document.createElement("div");
|
||||
gui.innerText = "EFSERVER CONSOLE";
|
||||
gui.style.background = "black";
|
||||
gui.style.fontFamily = "sans-serif";
|
||||
gui.style.zIndex = 254;
|
||||
gui.style.position = "fixed";
|
||||
gui.style.display = "none";
|
||||
gui.style.height = "calc(100vh - 1rem - 4px)";
|
||||
gui.style.overflowY = "scroll";
|
||||
gui.style.color = "white";
|
||||
gui.style.top = gui.style.left = gui.style.bottom = gui.style.right = 0;
|
||||
document.documentElement.appendChild(gui);
|
||||
|
||||
var cmdbox = document.createElement("input");
|
||||
cmdbox.style.position = "absolute";
|
||||
cmdbox.style.left = "0";
|
||||
cmdbox.style.bottom = "0";
|
||||
cmdbox.style.right = "0";
|
||||
cmdbox.style.position = "inline-block";
|
||||
cmdbox.style.border = "0";
|
||||
cmdbox.style.borderTop = "2px solid white";
|
||||
cmdbox.style.background = "black";
|
||||
cmdbox.style.zIndex = 255;
|
||||
cmdbox.style.color = "white";
|
||||
cmdbox.style.height = "1rem";
|
||||
cmdbox.type = "text";
|
||||
cmdbox.addEventListener("keydown", (e) => {
|
||||
e.stopPropagation();
|
||||
e.stopImmediatePropagation();
|
||||
}, true);
|
||||
cmdbox.addEventListener("keyup", (e) => {
|
||||
e.stopPropagation();
|
||||
e.stopImmediatePropagation();
|
||||
if (e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
toServer("chat", cmdbox.value);
|
||||
cmdbox.value = "";
|
||||
}
|
||||
}, true);
|
||||
document.documentElement.appendChild(cmdbox);
|
||||
|
||||
function worldUpdate() {
|
||||
if (ModAPI.mc && ModAPI.mc.theWorld) {
|
||||
ModAPI.hooks.methods.nmcs_GameSettings_saveOptions = ()=>{};
|
||||
ModAPI.settings.limitFramerate = 1;
|
||||
ModAPI.settings.enableVsync = 0;
|
||||
showgui();
|
||||
openSharedWorld()
|
||||
} else {
|
||||
hidegui();
|
||||
}
|
||||
}
|
||||
|
||||
setInterval(() => {
|
||||
worldUpdate();
|
||||
}, 100);
|
||||
|
||||
function showgui() {
|
||||
gui.style.opacity = "1";
|
||||
gui.style.display = "block";
|
||||
cmdbox.style.opacity = "1";
|
||||
cmdbox.style.display = "block";
|
||||
}
|
||||
function hidegui() {
|
||||
gui.style.opacity = "0";
|
||||
gui.style.display = "none";
|
||||
cmdbox.style.opacity = "0";
|
||||
cmdbox.style.display = "none";
|
||||
}
|
||||
|
||||
function EFB2__defineExecCmdAsGlobal() {
|
||||
var getServer = ModAPI.reflect.getClassById("net.minecraft.server.MinecraftServer").staticMethods.getServer.method;
|
||||
globalThis.efb2__executeCommandAs = function efb2__executeCommandAs($commandsender, command, feedback) {
|
||||
var server = getServer();
|
||||
if (!server) { return };
|
||||
var commandManager = server.$commandManager;
|
||||
|
||||
//lie a bit
|
||||
var x = $commandsender.$canCommandSenderUseCommand;
|
||||
$commandsender.$canCommandSenderUseCommand = () => 1;
|
||||
|
||||
var y = $commandsender.$sendCommandFeedback;
|
||||
$commandsender.$sendCommandFeedback = feedback ? () => 1 : () => 0;
|
||||
|
||||
try {
|
||||
commandManager.$executeCommand($commandsender, ModAPI.util.str(command));
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
|
||||
$commandsender.$canCommandSenderUseCommand = x;
|
||||
$commandsender.$sendCommandFeedback = y;
|
||||
}
|
||||
}
|
||||
ModAPI.dedicatedServer.appendCode(EFB2__defineExecCmdAsGlobal);
|
||||
|
||||
ModAPI.hooks.methods.nmc_LoadingScreenRenderer_eaglerShow = ()=>{};
|
||||
var opening = false;
|
||||
function openSharedWorld() {
|
||||
var platform = ModAPI.reflect.getClassById("net.lax1dude.eaglercraft.v1_8.internal.PlatformWebRTC");
|
||||
if (!opening && ModAPI.mc.theWorld && !ModAPI.hooks.methods.nlevsl_LANServerController_isLANOpen()) {
|
||||
platform.staticVariables.rtcLANServer = ModAPI.reflect.getClassById("net.lax1dude.eaglercraft.v1_8.internal.PlatformWebRTC$LANServer").constructors[0]();
|
||||
var worldName = ModAPI.util.unstr(ModAPI.mc.thePlayer.getName().getRef()) + "'s World";
|
||||
opening = true;
|
||||
ModAPI.promisify(ModAPI.hooks.methods.nlevsl_LANServerController_shareToLAN)({
|
||||
$accept: (status)=>{
|
||||
gui.innerText += "\n" + ModAPI.util.ustr(status);
|
||||
}
|
||||
}, ModAPI.util.str(worldName), 0).then(code => {
|
||||
opening = false;
|
||||
if (code != null) {
|
||||
ModAPI.hooks.methods.nlevs_SingleplayerServerController_configureLAN(ModAPI.mc.playerController.currentGameType.getRef(), 0);
|
||||
var msg = "code: " + ModAPI.util.ustr(code) + " relay: " + ModAPI.util.ustr(ModAPI.hooks.methods.nlevsl_LANServerController_getCurrentURI());
|
||||
alert(msg);
|
||||
gui.innerText += "\n" + msg;
|
||||
}
|
||||
});
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
NETWORKING OPCODES
|
||||
chat - bidirectional, send chat to server/client
|
||||
*/
|
||||
|
||||
function toServer(opcode, data) {
|
||||
client_comms_channel.postMessage({
|
||||
opcode: opcode,
|
||||
audience: "server",
|
||||
data: data,
|
||||
});
|
||||
}
|
||||
|
||||
var token = crypto.randomUUID();
|
||||
const clientMessageHandlers = {
|
||||
chat: function (data) {
|
||||
if (gui.scrollHeight > (innerHeight * 5)) {
|
||||
gui.innerText = "Console cleared. Logs were over 5 pages long.";
|
||||
}
|
||||
gui.innerText += "\n" + data.replaceAll("§r", "");
|
||||
gui.scrollTop = gui.scrollHeight;
|
||||
},
|
||||
};
|
||||
var client_comms_channel = new BroadcastChannel("efserv:" + token);
|
||||
client_comms_channel.addEventListener("message", (ev) => {
|
||||
if (ev.data.audience !== "client") {
|
||||
return;
|
||||
}
|
||||
if (clientMessageHandlers[ev.data.opcode]) {
|
||||
clientMessageHandlers[ev.data.opcode](ev.data.data);
|
||||
}
|
||||
});
|
||||
ModAPI.dedicatedServer.appendCode(
|
||||
`globalThis.efhost_security_token = "${token}";`
|
||||
);
|
||||
ModAPI.dedicatedServer.appendCode(function () {
|
||||
var comms = new BroadcastChannel(
|
||||
"efserv:" + globalThis.efhost_security_token
|
||||
);
|
||||
|
||||
function toClient(opcode, data) {
|
||||
comms.postMessage({
|
||||
opcode: opcode,
|
||||
audience: "client",
|
||||
data: data,
|
||||
});
|
||||
}
|
||||
|
||||
function getHostPlayer() {
|
||||
var host = null;
|
||||
ModAPI.server.getRef().$worldServers.data.forEach((world) => {
|
||||
host ||= world.$playerEntities.$array1.data.find((player) => {
|
||||
if (!player) {
|
||||
return;
|
||||
}
|
||||
var nameKey = ModAPI.util.getNearestProperty(
|
||||
player.$gameProfile,
|
||||
"$name"
|
||||
);
|
||||
return ModAPI.util.ustr(player.$gameProfile[nameKey]) === "HOST";
|
||||
});
|
||||
});
|
||||
return host;
|
||||
}
|
||||
|
||||
const messageHandlers = {
|
||||
chat: function (data) {
|
||||
var host = getHostPlayer();
|
||||
if (!host) {
|
||||
return;
|
||||
}
|
||||
host.$addChatMessage = (comp)=>{toClient("chat", ModAPI.util.ustr(comp.$getUnformattedText()))};
|
||||
efb2__executeCommandAs(getHostPlayer(), data, true);
|
||||
},
|
||||
};
|
||||
|
||||
comms.addEventListener("message", (ev) => {
|
||||
if (ev.data.audience !== "server") {
|
||||
return;
|
||||
}
|
||||
if (messageHandlers[ev.data.opcode]) {
|
||||
messageHandlers[ev.data.opcode](ev.data.data);
|
||||
}
|
||||
});
|
||||
|
||||
var oldLog = ModAPI.hooks.methods.nlevl_Logger_log;
|
||||
ModAPI.hooks.methods.nlevl_Logger_log = function (...args) {
|
||||
toClient("chat", ModAPI.util.ustr(args[2]));
|
||||
return oldLog.apply(this, args);
|
||||
};
|
||||
|
||||
ModAPI.addEventListener("tick", ()=>{
|
||||
var host = ModAPI.util.wrap(getHostPlayer());
|
||||
if (!host) {
|
||||
return;
|
||||
}
|
||||
host.posY = -10;
|
||||
host.posX = 0;
|
||||
host.posZ = 0;
|
||||
host.capabilities.disableDamage = 1;
|
||||
host.capabilities.isCreativeMode = 1;
|
||||
host.capabilities.isFlying = 1;
|
||||
host.motionY = 0;
|
||||
host.motionX = 0;
|
||||
host.motionZ = 0;
|
||||
host.isDead = 0;
|
||||
host.setHealth(20);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
|
||||
function renameButton(array, originalName, newName) {
|
||||
array.find(
|
||||
(x) => ModAPI.util.ustr(x.displayString.getRef()) === originalName
|
||||
).displayString = ModAPI.util.str(newName);
|
||||
}
|
||||
|
||||
const mainmenuinit = ModAPI.hooks.methods.nmcg_GuiMainMenu_initGui;
|
||||
ModAPI.hooks.methods.nmcg_GuiMainMenu_initGui = function (...args) {
|
||||
var result = mainmenuinit.apply(this, args);
|
||||
var wrappedGuiObject = ModAPI.util.wrap(args[0], args[0], false, false);
|
||||
wrappedGuiObject.splashText = ModAPI.util.str("Server Hosting Mode");
|
||||
var btnarray = wrappedGuiObject.buttonList.array1;
|
||||
renameButton(btnarray, "Singleplayer", "Host Server");
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
const GuiSelectWorldinit = ModAPI.hooks.methods.nmcg_GuiSelectWorld_initGui;
|
||||
ModAPI.hooks.methods.nmcg_GuiSelectWorld_initGui = function (...args) {
|
||||
var result = GuiSelectWorldinit.apply(this, args);
|
||||
var wrappedGuiObject = ModAPI.util.wrap(args[0], args[0], false, false);
|
||||
var btnarray = wrappedGuiObject.buttonList.array1.data;
|
||||
//renameButton(btnarray, "Create", "Create Server");
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
const mainmenuactions = ModAPI.hooks.methods.nmcg_GuiMainMenu_actionPerformed;
|
||||
ModAPI.hooks.methods.nmcg_GuiMainMenu_actionPerformed = function (...args) {
|
||||
ModAPI.hooks.methods.nlevp_EaglerProfile_setName(ModAPI.util.str("HOST"));
|
||||
var idKey = ModAPI.util.getNearestProperty(args[1], "$id");
|
||||
var guiButtonid = args[1][idKey];
|
||||
var blockedIds = [2]; // put the blocked/disabled button ids in there
|
||||
if (blockedIds.includes(guiButtonid)) {
|
||||
return 0;
|
||||
}
|
||||
return mainmenuactions.apply(this, args);
|
||||
};
|
||||
|
||||
// disable rendering
|
||||
ModAPI.hooks.methods.nmcr_EntityRenderer_renderWorld = () => { };
|
||||
})();
|
||||
@@ -0,0 +1,47 @@
|
||||
(function Sliders() {
|
||||
ModAPI.meta.title("Sliders");
|
||||
ModAPI.meta.description("Remove the clamping on sliders.");
|
||||
ModAPI.meta.credits("By ZXMushroom63");
|
||||
|
||||
const MathHelper_clamp_float = ModAPI.util.getMethodFromPackage("net.minecraft.util.MathHelper", "clamp_float");
|
||||
const GuiOptionSlider_mouseDragged = ModAPI.util.getMethodFromPackage("net.minecraft.client.gui.GuiOptionSlider", "mouseDragged");
|
||||
const GuiOptionSlider_mousePressed = ModAPI.util.getMethodFromPackage("net.minecraft.client.gui.GuiOptionSlider", "mousePressed");
|
||||
const GameSetting$Options_normalizeValue = ModAPI.util.getMethodFromPackage("net.minecraft.client.settings.GameSettings$Options", "normalizeValue");
|
||||
const GameSetting$Options_snapToStepClamp = ModAPI.util.getMethodFromPackage("net.minecraft.client.settings.GameSettings$Options", "snapToStepClamp");
|
||||
|
||||
const GuiOptionSlider_mouseDragged_fn = ModAPI.hooks.methods[GuiOptionSlider_mouseDragged];
|
||||
const GuiOptionSlider_mousePressed_fn = ModAPI.hooks.methods[GuiOptionSlider_mousePressed];
|
||||
const GameSetting$Options_normalizeValue_fn = ModAPI.hooks.methods[GameSetting$Options_normalizeValue];
|
||||
const GameSetting$Options_snapToStepClamp_fn = ModAPI.hooks.methods[GameSetting$Options_snapToStepClamp];
|
||||
const MathHelper_clamp_float_fn = ModAPI.hooks.methods[MathHelper_clamp_float];
|
||||
|
||||
const fakeClampMethod = (x)=>x;
|
||||
|
||||
ModAPI.hooks.methods[GuiOptionSlider_mouseDragged] = function (...args) {
|
||||
ModAPI.hooks.methods[MathHelper_clamp_float] = fakeClampMethod;
|
||||
var ret = GuiOptionSlider_mouseDragged_fn.apply(this, args);
|
||||
ModAPI.hooks.methods[MathHelper_clamp_float] = MathHelper_clamp_float_fn;
|
||||
return ret;
|
||||
}
|
||||
|
||||
ModAPI.hooks.methods[GuiOptionSlider_mousePressed] = function (...args) {
|
||||
ModAPI.hooks.methods[MathHelper_clamp_float] = fakeClampMethod;
|
||||
var ret = GuiOptionSlider_mousePressed_fn.apply(this, args);
|
||||
ModAPI.hooks.methods[MathHelper_clamp_float] = MathHelper_clamp_float_fn;
|
||||
return ret;
|
||||
}
|
||||
|
||||
ModAPI.hooks.methods[GameSetting$Options_normalizeValue] = function (...args) {
|
||||
ModAPI.hooks.methods[MathHelper_clamp_float] = fakeClampMethod;
|
||||
var ret = GameSetting$Options_normalizeValue_fn.apply(this, args);
|
||||
ModAPI.hooks.methods[MathHelper_clamp_float] = MathHelper_clamp_float_fn;
|
||||
return ret;
|
||||
}
|
||||
|
||||
// ModAPI.hooks.methods[GameSetting$Options_snapToStepClamp] = function (...args) {
|
||||
// ModAPI.hooks.methods[MathHelper_clamp_float] = fakeClampMethod;
|
||||
// var ret = GameSetting$Options_snapToStepClamp_fn.apply(this, args);
|
||||
// ModAPI.hooks.methods[MathHelper_clamp_float] = MathHelper_clamp_float_fn;
|
||||
// return ret;
|
||||
// }
|
||||
})();
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,15 @@
|
||||
(() => {
|
||||
PluginAPI.dedicatedServer.appendCode(function () {
|
||||
PluginAPI.addEventListener("processcommand", (event) => {
|
||||
if (event.command.toLowerCase().startsWith("/talkback")) {
|
||||
var message = event.command.substring("/talkback ".length);
|
||||
if (
|
||||
ModAPI.reflect.getClassById("net.minecraft.entity.player.EntityPlayerMP").instanceOf(event.sender.getRef())
|
||||
) {
|
||||
event.sender.addChatMessage(ModAPI.reflect.getClassById("net.minecraft.util.ChatComponentText").constructors[0](ModAPI.util.str(message.toUpperCase())));
|
||||
}
|
||||
event.preventDefault = true;
|
||||
}
|
||||
});
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,71 @@
|
||||
(() => {
|
||||
ModAPI.meta.title("Timescale Command");
|
||||
ModAPI.meta.description("/timescale 0.5 to halve the speed of time");
|
||||
ModAPI.meta.credits("By ZXMushroom63");
|
||||
globalThis.timeScale = 1n;
|
||||
globalThis.timeScaleDividing = false;
|
||||
PluginAPI.addEventListener("sendchatmessage", (event) => {
|
||||
if (event.message.toLowerCase().startsWith("/timescale")) {
|
||||
var speed = parseFloat(event.message.split(" ")[1]);
|
||||
if (!speed) {
|
||||
globalThis.timeScale = 1n;
|
||||
globalThis.timeScaleDividing = false;
|
||||
PluginAPI.mc.timer.timerSpeed = 1;
|
||||
} else {
|
||||
if (speed < 1) {
|
||||
globalThis.timeScaleDividing = true;
|
||||
globalThis.timeScale = BigInt(Math.round(1 / speed));
|
||||
} else {
|
||||
globalThis.timeScaleDividing = false;
|
||||
globalThis.timeScale = BigInt(Math.round(speed));
|
||||
}
|
||||
PluginAPI.mc.timer.timerSpeed = speed;
|
||||
}
|
||||
PluginAPI.mc.systemTime = PluginAPI.hooks.methods[ModAPI.util.getMethodFromPackage("net.minecraft.client.Minecraft", "getSystemTime")]();
|
||||
PluginAPI.mc.debugUpdateTime = PluginAPI.hooks.methods[ModAPI.util.getMethodFromPackage("net.minecraft.client.Minecraft", "getSystemTime")]() - 1000n;
|
||||
PluginAPI.mc.timer.lastSyncSysClock = PluginAPI.hooks.methods[ModAPI.util.getMethodFromPackage("net.minecraft.client.Minecraft", "getSystemTime")]();
|
||||
PluginAPI.displayToChat("[Timescale] Set world timescale to " + speed.toFixed(2) + ".");
|
||||
}
|
||||
});
|
||||
PluginAPI.dedicatedServer.appendCode(function () {
|
||||
globalThis.timeScale = 1n;
|
||||
globalThis.timeScaleDividing = false;
|
||||
PluginAPI.addEventListener("processcommand", (event) => {
|
||||
if (event.command.toLowerCase().startsWith("/timescale")) {
|
||||
var speed = parseFloat(event.command.split(" ")[1]);
|
||||
if (!speed) {
|
||||
globalThis.timeScale = 1n;
|
||||
globalThis.timeScaleDividing = false;
|
||||
} else {
|
||||
if (speed < 1) {
|
||||
globalThis.timeScaleDividing = true;
|
||||
globalThis.timeScale = BigInt(Math.round(1 / speed));
|
||||
} else {
|
||||
globalThis.timeScaleDividing = false;
|
||||
globalThis.timeScale = BigInt(Math.round(speed));
|
||||
}
|
||||
}
|
||||
if (ModAPI.server) {
|
||||
ModAPI.server.currentTime = PluginAPI.hooks.methods[ModAPI.util.getMethodFromPackage("net.minecraft.server.MinecraftServer", "getCurrentTimeMillis")]();
|
||||
}
|
||||
event.preventDefault = true;
|
||||
}
|
||||
});
|
||||
const original_getCurrentTime = ModAPI.hooks.methods[ModAPI.util.getMethodFromPackage("net.minecraft.server.MinecraftServer", "getCurrentTimeMillis")];
|
||||
PluginAPI.hooks.methods[ModAPI.util.getMethodFromPackage("net.minecraft.server.MinecraftServer", "getCurrentTimeMillis")] = function () {
|
||||
if (globalThis.timeScaleDividing) {
|
||||
return original_getCurrentTime() / globalThis.timeScale;
|
||||
} else {
|
||||
return original_getCurrentTime() * globalThis.timeScale;
|
||||
}
|
||||
};
|
||||
});
|
||||
const original_getSystemTime = ModAPI.hooks.methods[ModAPI.util.getMethodFromPackage("net.minecraft.client.Minecraft", "getSystemTime")];
|
||||
PluginAPI.hooks.methods[ModAPI.util.getMethodFromPackage("net.minecraft.client.Minecraft", "getSystemTime")] = function () {
|
||||
if (globalThis.timeScaleDividing) {
|
||||
return original_getSystemTime() / globalThis.timeScale;
|
||||
} else {
|
||||
return original_getSystemTime() * globalThis.timeScale;
|
||||
}
|
||||
};
|
||||
})();
|
||||
@@ -0,0 +1,126 @@
|
||||
(()=>{
|
||||
const unluckyBlockTexture = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAOhJREFUOE9jnJn2/z8DGvj4koHh9UOIoKg8AwO/OLoKBJ8RZED6LEbcKvDIzEz7z8DY5f//f9lGTANCGTAcxrCaAVUd2IBSg///uy+gSqBr/sJwF+6O7QwqcHaXPxYXgDTDNCArtmXYBtZ4mMELbkCpwX8GjDDwZLjD8IXhFopCkA5s4mAXEBOIMC+BXIbsKnAYEDIAOTywBiI+A0DO5mFQBvsZXTNIjKALQAHHw6CG4mzkZIE3HYAUEjIAHIjY0gGxyRIcjfgMgIUBNv+DLAEbgCspgxTAYgCXAUSnA1xegscCPj8TytoAA5eEOx9BbCgAAAAASUVORK5CYII=";
|
||||
ModAPI.meta.title("Unlucky Blocks");
|
||||
ModAPI.meta.version("v1.0");
|
||||
ModAPI.meta.description("These purple cubes ruined my life. Requires AsyncSink.");
|
||||
ModAPI.meta.credits("By ZXMushroom63");
|
||||
ModAPI.meta.icon(unluckyBlockTexture);
|
||||
|
||||
function UnluckyBlocks() {
|
||||
function fixupBlockIds() {
|
||||
var blockRegistry = ModAPI.util.wrap(ModAPI.reflect.getClassById("net.minecraft.block.Block").staticVariables.blockRegistry).getCorrective();
|
||||
var BLOCK_STATE_IDS = ModAPI.util.wrap(ModAPI.reflect.getClassById("net.minecraft.block.Block").staticVariables.BLOCK_STATE_IDS).getCorrective();
|
||||
blockRegistry.registryObjects.hashTableKToV.forEach(entry => {
|
||||
if (entry) {
|
||||
var block = entry.value;
|
||||
var validStates = block.getBlockState().getValidStates();
|
||||
var stateArray = validStates.array || [validStates.element];
|
||||
stateArray.forEach(iblockstate => {
|
||||
var i = blockRegistry.getIDForObject(block.getRef()) << 4 | block.getMetaFromState(iblockstate.getRef());
|
||||
BLOCK_STATE_IDS.put(iblockstate.getRef(), i);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
var itemClass = ModAPI.reflect.getClassById("net.minecraft.item.Item");
|
||||
var blockClass = ModAPI.reflect.getClassById("net.minecraft.block.Block");
|
||||
var blockSuper = ModAPI.reflect.getSuper(blockClass, (x) => x.length === 2); //Get super function from the block class with a target length of two. ($this (mandatory), material (optional))
|
||||
var creativeBlockTab = ModAPI.reflect.getClassById("net.minecraft.creativetab.CreativeTabs").staticVariables.tabBlock;
|
||||
var breakBlockMethod = blockClass.methods.breakBlock.method;
|
||||
function nmb_BlockUnlucky() {
|
||||
blockSuper(this, ModAPI.materials.rock.getRef()); //Use super function to get block properties on this class.
|
||||
this.$defaultBlockState = this.$blockState.$getBaseState();
|
||||
this.$setCreativeTab(creativeBlockTab);
|
||||
}
|
||||
ModAPI.reflect.prototypeStack(blockClass, nmb_BlockUnlucky);
|
||||
nmb_BlockUnlucky.prototype.$breakBlock = function ($world, $blockpos, $blockstate) {
|
||||
var world = ModAPI.util.wrap($world);
|
||||
var blockpos = ModAPI.util.wrap($blockpos);
|
||||
if (Math.random() < 1) { //was gonna add random events but couldn't be bothered. Enjoy exploding!
|
||||
world.newExplosion(null, blockpos.getX() + 0.5, blockpos.getY() + 0.5,
|
||||
blockpos.getZ() + 0.5, 9, 1, 1);
|
||||
}
|
||||
return breakBlockMethod(this, $world, $blockpos, $blockstate);
|
||||
}
|
||||
|
||||
function internal_reg() {
|
||||
var block_of_unluckiness = (new nmb_BlockUnlucky()).$setHardness(0.0).$setStepSound(blockClass.staticVariables.soundTypePiston).$setUnlocalizedName(
|
||||
ModAPI.util.str("unluckiness")
|
||||
);
|
||||
blockClass.staticMethods.registerBlock0.method(
|
||||
ModAPI.keygen.block("unluckiness"),
|
||||
ModAPI.util.str("unluckiness"),
|
||||
block_of_unluckiness
|
||||
);
|
||||
itemClass.staticMethods.registerItemBlock0.method(block_of_unluckiness);
|
||||
fixupBlockIds();
|
||||
ModAPI.blocks["unluckiness"] = block_of_unluckiness;
|
||||
|
||||
return block_of_unluckiness;
|
||||
}
|
||||
|
||||
const WorldGenMineable = ModAPI.reflect.getClassById("net.minecraft.world.gen.feature.WorldGenMinable").constructors.find(x=>x.length===2);
|
||||
|
||||
const BiomeDecorator_decorate = ModAPI.util.getMethodFromPackage("net.minecraft.world.biome.BiomeDecorator", "decorate");
|
||||
const oldDecorate = ModAPI.hooks.methods[BiomeDecorator_decorate];
|
||||
ModAPI.hooks.methods[BiomeDecorator_decorate] = function ($this, $world, $random, $biomeGenBase, $blockpos) {
|
||||
if (!$this.$currentWorld) {
|
||||
$this.$unluckyBlockGen = WorldGenMineable(ModAPI.blocks.unluckiness.getDefaultState().getRef(), 4);
|
||||
}
|
||||
return oldDecorate.apply(this, [$this, $world, $random, $biomeGenBase, $blockpos]);
|
||||
}
|
||||
|
||||
const BiomeDecorator_generateOres = ModAPI.util.getMethodFromPackage("net.minecraft.world.biome.BiomeDecorator", "generateOres");
|
||||
const oldGenerateOres = ModAPI.hooks.methods[BiomeDecorator_generateOres];
|
||||
ModAPI.hooks.methods[BiomeDecorator_generateOres] = function ($this) {
|
||||
$this.$genStandardOre1(105, $this.$unluckyBlockGen || null, 0, 256);
|
||||
return oldGenerateOres.apply(this, [$this]);
|
||||
}
|
||||
|
||||
if (ModAPI.materials) {
|
||||
return internal_reg();
|
||||
} else {
|
||||
ModAPI.addEventListener("bootstrap", internal_reg);
|
||||
}
|
||||
}
|
||||
ModAPI.dedicatedServer.appendCode(UnluckyBlocks);
|
||||
var block_of_unluckiness = UnluckyBlocks();
|
||||
ModAPI.addEventListener("lib:asyncsink", async () => {
|
||||
ModAPI.addEventListener("lib:asyncsink:registeritems", (renderItem)=>{
|
||||
renderItem.registerBlock(block_of_unluckiness, ModAPI.util.str("unluckiness"));
|
||||
});
|
||||
AsyncSink.L10N.set("tile.unluckiness.name", "Unlucky Block");
|
||||
AsyncSink.setFile("resourcepacks/AsyncSinkLib/assets/minecraft/models/block/unluckiness.json", JSON.stringify(
|
||||
{
|
||||
"parent": "block/cube_all",
|
||||
"textures": {
|
||||
"all": "blocks/unluckiness"
|
||||
}
|
||||
}
|
||||
));
|
||||
AsyncSink.setFile("resourcepacks/AsyncSinkLib/assets/minecraft/models/item/unluckiness.json", JSON.stringify(
|
||||
{
|
||||
"parent": "block/unluckiness",
|
||||
"display": {
|
||||
"thirdperson": {
|
||||
"rotation": [10, -45, 170],
|
||||
"translation": [0, 1.5, -2.75],
|
||||
"scale": [0.375, 0.375, 0.375]
|
||||
}
|
||||
}
|
||||
}
|
||||
));
|
||||
AsyncSink.setFile("resourcepacks/AsyncSinkLib/assets/minecraft/blockstates/unluckiness.json", JSON.stringify(
|
||||
{
|
||||
"variants": {
|
||||
"normal": [
|
||||
{ "model": "unluckiness" },
|
||||
]
|
||||
}
|
||||
}
|
||||
));
|
||||
AsyncSink.setFile("resourcepacks/AsyncSinkLib/assets/minecraft/textures/blocks/unluckiness.png", await (await fetch(
|
||||
unluckyBlockTexture
|
||||
)).arrayBuffer());
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,72 @@
|
||||
// This is an example mod on how to register an item.
|
||||
(()=>{
|
||||
const itemTexture = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAKZJREFUOE9j/P//PxMDBIBoEP6HREOl4PLIciA2AyPIgMcM//7KgvWSDJjBBpx9/+YvJzc3Sbq12DhB6sEGsJ19/+YnmQawYhigzc7FcPXnN4KugbqAHWQAy9n3b34T4wJkw6EGYLqAoNVQBWS5ANlwZBfAvUCs/0EGkW0AzBKqGoCSDgh5A80F2KMRpAgfAKUT6kcjsfEPUycmKMQgy8AETkgUZWcAS3CPIf4oSPsAAAAASUVORK5CYII=";
|
||||
//this texture is REALLY bad, so the item appears 2d in game. (it uses partially transparent pixels around the edges in some spots ;-;)
|
||||
ModAPI.meta.title("Adding items demo.");
|
||||
ModAPI.meta.version("v1.0");
|
||||
ModAPI.meta.icon(itemTexture);
|
||||
ModAPI.meta.description("Requires AsyncSink.");
|
||||
|
||||
function ExampleItem() {
|
||||
var creativeMiscTab = ModAPI.reflect.getClassById("net.minecraft.creativetab.CreativeTabs").staticVariables.tabMisc;
|
||||
var itemClass = ModAPI.reflect.getClassById("net.minecraft.item.Item");
|
||||
var itemSuper = ModAPI.reflect.getSuper(itemClass, (x) => x.length === 1);
|
||||
function nmi_ItemExample() {
|
||||
itemSuper(this); //Use super function to get block properties on this class.
|
||||
this.$setCreativeTab(creativeMiscTab);
|
||||
}
|
||||
ModAPI.reflect.prototypeStack(itemClass, nmi_ItemExample);
|
||||
nmi_ItemExample.prototype.$onItemRightClick = function ($itemstack, $world, $player) { //example of how to override a method
|
||||
return $itemstack;
|
||||
}
|
||||
|
||||
function internal_reg() {
|
||||
var example_item = (new nmi_ItemExample()).$setUnlocalizedName(
|
||||
ModAPI.util.str("exampleitem")
|
||||
);
|
||||
itemClass.staticMethods.registerItem.method(ModAPI.keygen.item("exampleitem"), ModAPI.util.str("exampleitem"), example_item);
|
||||
ModAPI.items["exampleitem"] = example_item;
|
||||
|
||||
return example_item;
|
||||
}
|
||||
|
||||
if (ModAPI.items) {
|
||||
return internal_reg();
|
||||
} else {
|
||||
ModAPI.addEventListener("bootstrap", internal_reg);
|
||||
}
|
||||
}
|
||||
|
||||
ModAPI.dedicatedServer.appendCode(ExampleItem);
|
||||
var example_item = ExampleItem();
|
||||
|
||||
ModAPI.addEventListener("lib:asyncsink", async () => {
|
||||
ModAPI.addEventListener("lib:asyncsink:registeritems", (renderItem)=>{
|
||||
renderItem.registerItem(example_item, ModAPI.util.str("exampleitem"));
|
||||
});
|
||||
AsyncSink.L10N.set("item.exampleitem.name", "Example Item");
|
||||
AsyncSink.setFile("resourcepacks/AsyncSinkLib/assets/minecraft/models/item/exampleitem.json", JSON.stringify(
|
||||
{
|
||||
"parent": "builtin/generated",
|
||||
"textures": {
|
||||
"layer0": "items/exampleitem"
|
||||
},
|
||||
"display": {
|
||||
"thirdperson": {
|
||||
"rotation": [ -90, 0, 0 ],
|
||||
"translation": [ 0, 1, -3 ],
|
||||
"scale": [ 0.55, 0.55, 0.55 ]
|
||||
},
|
||||
"firstperson": {
|
||||
"rotation": [ 0, -135, 25 ],
|
||||
"translation": [ 0, 4, 2 ],
|
||||
"scale": [ 1.7, 1.7, 1.7 ]
|
||||
}
|
||||
}
|
||||
}
|
||||
));
|
||||
AsyncSink.setFile("resourcepacks/AsyncSinkLib/assets/minecraft/textures/items/exampleitem.png", await (await fetch(
|
||||
itemTexture
|
||||
)).arrayBuffer());
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,69 @@
|
||||
// This is an example mod on how to register an item.
|
||||
(()=>{
|
||||
const itemTexture = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAKZJREFUOE9j/P//PxMDBIBoEP6HREOl4PLIciA2AyPIgMcM//7KgvWSDJjBBpx9/+YvJzc3Sbq12DhB6sEGsJ19/+YnmQawYhigzc7FcPXnN4KugbqAHWQAy9n3b34T4wJkw6EGYLqAoNVQBWS5ANlwZBfAvUCs/0EGkW0AzBKqGoCSDgh5A80F2KMRpAgfAKUT6kcjsfEPUycmKMQgy8AETkgUZWcAS3CPIf4oSPsAAAAASUVORK5CYII=";
|
||||
//this texture is REALLY bad, so the item appears 2d in game. (it uses partially transparent pixels around the edges in some spots ;-;)
|
||||
ModAPI.meta.title("Adding items demo.");
|
||||
ModAPI.meta.version("v1.0");
|
||||
ModAPI.meta.icon(itemTexture);
|
||||
ModAPI.meta.description("Requires AsyncSink.");
|
||||
|
||||
function ExampleItem() {
|
||||
var creativeMiscTab = ModAPI.reflect.getClassById("net.minecraft.creativetab.CreativeTabs").staticVariables.MISC;
|
||||
var itemClass = ModAPI.reflect.getClassById("net.minecraft.item.Item");
|
||||
var itemSuper = ModAPI.reflect.getSuper(itemClass, (x) => x.length === 1);
|
||||
function nmi_ItemExample() {
|
||||
itemSuper(this); //Use super function to get block properties on this class.
|
||||
this.$setCreativeTab(creativeMiscTab);
|
||||
}
|
||||
ModAPI.reflect.prototypeStack(itemClass, nmi_ItemExample);
|
||||
|
||||
function internal_reg() {
|
||||
var example_item = (new nmi_ItemExample()).$setUnlocalizedName(
|
||||
ModAPI.util.str("exampleitem")
|
||||
);
|
||||
itemClass.staticMethods.registerItem.method(ModAPI.keygen.item("exampleitem"), ModAPI.util.str("exampleitem"), example_item);
|
||||
ModAPI.items["exampleitem"] = example_item;
|
||||
|
||||
return example_item;
|
||||
}
|
||||
|
||||
if (ModAPI.items) {
|
||||
return internal_reg();
|
||||
} else {
|
||||
ModAPI.addEventListener("bootstrap", internal_reg);
|
||||
}
|
||||
}
|
||||
|
||||
ModAPI.dedicatedServer.appendCode(ExampleItem);
|
||||
var example_item = ExampleItem();
|
||||
|
||||
ModAPI.addEventListener("lib:asyncsink", async () => {
|
||||
ModAPI.addEventListener("lib:asyncsink:registeritems", (renderItem)=>{
|
||||
renderItem.registerItem(example_item, ModAPI.util.str("exampleitem"));
|
||||
});
|
||||
AsyncSink.L10N.set("item.exampleitem.name", "Example Item");
|
||||
AsyncSink.setFile("resourcepacks/AsyncSinkLib/assets/minecraft/models/item/exampleitem.json", JSON.stringify(
|
||||
{
|
||||
"parent": "builtin/generated",
|
||||
"textures": {
|
||||
"layer0": "items/exampleitem"
|
||||
},
|
||||
"display": {
|
||||
"thirdperson": {
|
||||
"rotation": [ -90, 0, 0 ],
|
||||
"translation": [ 0, 1, -3 ],
|
||||
"scale": [ 0.55, 0.55, 0.55 ]
|
||||
},
|
||||
"firstperson": {
|
||||
"rotation": [ 0, -135, 25 ],
|
||||
"translation": [ 0, 4, 2 ],
|
||||
"scale": [ 1.7, 1.7, 1.7 ]
|
||||
}
|
||||
}
|
||||
}
|
||||
));
|
||||
AsyncSink.setFile("resourcepacks/AsyncSinkLib/assets/minecraft/textures/items/exampleitem.png", await (await fetch(
|
||||
itemTexture
|
||||
)).arrayBuffer());
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,22 @@
|
||||
//Metadata about the vclip mod
|
||||
ModAPI.meta.title("Simple VClip Exploit");
|
||||
ModAPI.meta.description("Use .vclip <offset> to vertically phase through blocks.");
|
||||
ModAPI.meta.credits("By ZXMushroom63");
|
||||
|
||||
// Require the player entity
|
||||
ModAPI.require("player");
|
||||
|
||||
//When the player tries to send a chat message to the server
|
||||
ModAPI.addEventListener("sendchatmessage", (ev) => {
|
||||
var msg = ev.message.toLowerCase(); //Get the lowercase version of the command
|
||||
if (msg.startsWith(".vclip")) { //If it starts with .vclip
|
||||
ev.preventDefault = true; //Don't send the chat message to the server
|
||||
var yOffset = 1; //Set the default Y offset to 1. This let's you use .vclip with no arguments to "unstuck" yourself;
|
||||
if (msg.split(" ")[1]) { //If there is a second part to the command
|
||||
yOffset = parseFloat(msg.split(" ")[1]) || 0; //Set the yOffset to that
|
||||
}
|
||||
ModAPI.player.setPosition(ModAPI.player.posX, ModAPI.player.posY
|
||||
+ yOffset, ModAPI.player.posZ); //Set the player's position to their current position plus the y offset.
|
||||
ModAPI.displayToChat("[SimpleVClip] VClipped " + yOffset + " blocks."); //Display information to the client side chat.
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,133 @@
|
||||
(function TreeChopperMod() {
|
||||
ModAPI.meta.title("Vein Miner");
|
||||
ModAPI.meta.description("Vein-mines trees & ores while crouching. Press the 'config' button for settings.");
|
||||
ModAPI.meta.credits("By ZXMushroom63");
|
||||
ModAPI.meta.version("v1.0");
|
||||
globalThis.VEINMINERCONF = {
|
||||
doLogs: true,
|
||||
doOres: true,
|
||||
doGravel: false,
|
||||
doClay: false,
|
||||
};
|
||||
try {
|
||||
Object.assign(conf, JSON.parse(localStorage.getItem("trc_mod::conf") || "{}"));
|
||||
} catch (error) {
|
||||
//swallow
|
||||
}
|
||||
ModAPI.meta.config(() => {
|
||||
var conf = document.createElement("div");
|
||||
conf.innerHTML = `
|
||||
<h1>Vein Miner Settings <a href="javascript:void(0)" onclick="this.parentElement.parentElement.remove()" style="color:red">[X]</a></h1>
|
||||
<sub>Refresh page to apply settings</sub><br>
|
||||
<label>Veinmine Logs: </label><input type=checkbox ${VEINMINERCONF.doLogs ? "checked" : ""} oninput="VEINMINERCONF.doLogs = this.checked; this.parentElement.__save();"></input><br>
|
||||
<label>Veinmine Ores: </label><input type=checkbox ${VEINMINERCONF.doOres ? "checked" : ""} oninput="VEINMINERCONF.doOres = this.checked; this.parentElement.__save();"></input><br>
|
||||
<label>Veinmine Gravel: </label><input type=checkbox ${VEINMINERCONF.doGravel ? "checked" : ""} oninput="VEINMINERCONF.doGravel = this.checked; this.parentElement.__save();"></input><br>
|
||||
<label>Veinmine Clay: </label><input type=checkbox ${VEINMINERCONF.doClay ? "checked" : ""} oninput="VEINMINERCONF.doClay = this.checked; this.parentElement.__save();"></input><br>
|
||||
`;
|
||||
conf.style = "position: fixed; background-color: white; color: black; width: 100vw; height: 100vh; z-index: 256;top:0;left:0;";
|
||||
conf.__save = () => localStorage.setItem("trc_mod::conf", JSON.stringify(VEINMINERCONF));
|
||||
document.body.appendChild(conf);
|
||||
});
|
||||
|
||||
ModAPI.dedicatedServer.appendCode(`globalThis.VEINMINERCONF = ${JSON.stringify(VEINMINERCONF)};`);
|
||||
|
||||
ModAPI.dedicatedServer.appendCode(function () {
|
||||
ModAPI.addEventListener("bootstrap", () => {
|
||||
const axes = [ModAPI.items.iron_axe, ModAPI.items.stone_axe, ModAPI.items.golden_axe, ModAPI.items.wooden_axe, ModAPI.items.diamond_axe].map(x => x.getRef());
|
||||
const logs = ["log", "log2"].map(x => ModAPI.blocks[x].getRef());
|
||||
const targettedBlockIds = [];
|
||||
if (VEINMINERCONF.doLogs) {
|
||||
targettedBlockIds.push("log", "log2");
|
||||
}
|
||||
if (VEINMINERCONF.doOres) {
|
||||
targettedBlockIds.push("coal_ore", "gold_ore", "iron_ore", "lapis_ore", "quartz_ore", "diamond_ore", "emerald_ore", "redstone_ore", "lit_redstone_ore");
|
||||
}
|
||||
if (VEINMINERCONF.doGravel) {
|
||||
targettedBlockIds.push("gravel");
|
||||
}
|
||||
if (VEINMINERCONF.doClay) {
|
||||
targettedBlockIds.push("clay");
|
||||
}
|
||||
console.log(targettedBlockIds);
|
||||
const valid_log_blocks = targettedBlockIds.map(x => ModAPI.blocks[x].getRef());
|
||||
|
||||
function stringifyBlockPos(blockPos) {
|
||||
return blockPos.x + "," + blockPos.y + "," + blockPos.z;
|
||||
}
|
||||
function getNeighbors(blockPos) {
|
||||
return [
|
||||
//direct neighbors
|
||||
blockPos.down(1),
|
||||
blockPos.up(1),
|
||||
blockPos.north(1),
|
||||
blockPos.south(1),
|
||||
blockPos.east(1),
|
||||
blockPos.west(1),
|
||||
|
||||
//edges
|
||||
blockPos.down(1).north(1),
|
||||
blockPos.down(1).south(1),
|
||||
blockPos.down(1).east(1),
|
||||
blockPos.down(1).west(1),
|
||||
blockPos.up(1).north(1),
|
||||
blockPos.up(1).south(1),
|
||||
blockPos.up(1).east(1),
|
||||
blockPos.up(1).west(1),
|
||||
blockPos.north(1).east(1),
|
||||
blockPos.north(1).west(1),
|
||||
blockPos.south(1).east(1),
|
||||
blockPos.south(1).west(1),
|
||||
|
||||
//corners
|
||||
blockPos.down(1).north(1).east(1),
|
||||
blockPos.down(1).north(1).west(1),
|
||||
blockPos.down(1).south(1).east(1),
|
||||
blockPos.down(1).south(1).west(1),
|
||||
blockPos.up(1).north(1).east(1),
|
||||
blockPos.up(1).north(1).west(1),
|
||||
blockPos.up(1).south(1).east(1),
|
||||
blockPos.up(1).south(1).west(1),
|
||||
];
|
||||
}
|
||||
async function getBlockGraph(blockPos, getBlockState, targetType) {
|
||||
const closed = [stringifyBlockPos(blockPos)];
|
||||
const logs = [];
|
||||
const open = [...getNeighbors(blockPos)];
|
||||
const maxIters = 120;
|
||||
var i = 0;
|
||||
while (open.length > 0 && i < maxIters) {
|
||||
const target = open.pop();
|
||||
|
||||
closed.push(stringifyBlockPos(target));
|
||||
|
||||
i++;
|
||||
const iBlockState = await getBlockState(target.getRef());
|
||||
if (iBlockState.block.getRef() === targetType) {
|
||||
logs.push(target);
|
||||
open.push(...getNeighbors(target).filter(x => !closed.includes(stringifyBlockPos(x))));
|
||||
}
|
||||
}
|
||||
return logs;
|
||||
}
|
||||
|
||||
valid_log_blocks.forEach(b => {
|
||||
const originalHarvest = b.$harvestBlock;
|
||||
b.$harvestBlock = function ($theWorld, $player, $blockpos, $blockstate, $tileentity, ...args) {
|
||||
const blockState = ModAPI.util.wrap($blockstate);
|
||||
const player = ModAPI.util.wrap($player);
|
||||
if (player.isSneaking() && !ModAPI.util.isCritical() && !(logs.includes(blockState.block.getRef()) && !axes.includes(player.inventory.mainInventory[player.inventory.currentItem]?.getCorrective()?.item?.getRef()))) {
|
||||
ModAPI.promisify(async () => {
|
||||
var world = ModAPI.util.wrap($theWorld);
|
||||
var harvestCall = ModAPI.promisify(ModAPI.is_1_12 ? player.interactionManager.tryHarvestBlock : player.theItemInWorldManager.tryHarvestBlock);
|
||||
const blocks = await getBlockGraph(ModAPI.util.wrap($blockpos), ModAPI.promisify(world.getBlockState), b);
|
||||
for (let i = 0; i < blocks.length; i++) {
|
||||
await harvestCall(blocks[i].getRef());
|
||||
}
|
||||
})();
|
||||
}
|
||||
originalHarvest.apply(this, [$theWorld, $player, $blockpos, $blockstate, $tileentity, ...args]);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,138 @@
|
||||
(function Waypoints() {
|
||||
ModAPI.meta.title("Waypoints Mod");
|
||||
ModAPI.meta.description("Use /setwp <name> to make a waypoint, and /wp <name> to go to it. /remwp <name> to delete a waypoint. /listwp to list all waypoints.");
|
||||
ModAPI.meta.credits("By blizz828, Block_2222 & ZXMushroom63");
|
||||
|
||||
ModAPI.dedicatedServer.appendCode(async ()=>{ //The mods should probably be running on the server
|
||||
function initDB(dbName, storeName) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = indexedDB.open(dbName, 2);
|
||||
|
||||
request.onupgradeneeded = (event) => {
|
||||
const db = event.target.result;
|
||||
if (!db.objectStoreNames.contains(storeName)) {
|
||||
db.createObjectStore(storeName);
|
||||
}
|
||||
resolve(db);
|
||||
};
|
||||
|
||||
request.onsuccess = (event) => {
|
||||
const db = event.target.result;
|
||||
resolve(db);
|
||||
};
|
||||
|
||||
request.onerror = (event) => {
|
||||
reject('Error opening database: ' + event.target.errorCode);
|
||||
};
|
||||
});
|
||||
}
|
||||
function storeString(dbName, storeName, key, value) {
|
||||
return initDB(dbName, storeName).then((db) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
const transaction = db.transaction(storeName, 'readwrite');
|
||||
const store = transaction.objectStore(storeName);
|
||||
const putRequest = store.put(value, key);
|
||||
|
||||
putRequest.onsuccess = () => {
|
||||
resolve('String stored successfully.');
|
||||
};
|
||||
|
||||
putRequest.onerror = (event) => {
|
||||
reject('Error storing string: ' + event.target.errorCode);
|
||||
};
|
||||
});
|
||||
});
|
||||
}
|
||||
function retrieveString(dbName, storeName, key) {
|
||||
return initDB(dbName, storeName).then((db) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
const transaction = db.transaction(storeName, 'readonly');
|
||||
const store = transaction.objectStore(storeName);
|
||||
const getRequest = store.get(key);
|
||||
|
||||
getRequest.onsuccess = () => {
|
||||
if (getRequest.result !== undefined) {
|
||||
resolve(getRequest.result);
|
||||
} else {
|
||||
resolve('');
|
||||
}
|
||||
};
|
||||
|
||||
getRequest.onerror = (event) => {
|
||||
resolve('');
|
||||
};
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
var data = {};
|
||||
try {
|
||||
data = JSON.parse(await retrieveString("waypoints_db", "waypoints", "waypoints"));
|
||||
} catch(e) {
|
||||
//didn't ask
|
||||
}
|
||||
|
||||
async function saveData() {
|
||||
await storeString("waypoints_db", "waypoints", "waypoints", JSON.stringify(data));
|
||||
}
|
||||
|
||||
|
||||
ModAPI.addEventListener("processcommand", (e)=>{
|
||||
if (!ModAPI.reflect.getClassById("net.minecraft.entity.player.EntityPlayerMP").instanceOf(e.sender.getRef())) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.command.toLowerCase().startsWith("/setwp ") && e.sender.canCommandSenderUseCommand(2, ModAPI.util.str("setwp"))) {
|
||||
e.preventDefault = true;
|
||||
var pos = e.sender.getPosition();
|
||||
var name = ModAPI.util.unstring(e.sender.getName().getRef());
|
||||
var waypointId = e.command.split(" ")[1] || "waypoint";
|
||||
waypointId = waypointId.replace(/[^a-zA-Z0-9_]/gm, "_");
|
||||
if (!data[name]) {
|
||||
data[name] = {};
|
||||
}
|
||||
data[name][waypointId] = [pos.x,pos.y,pos.z,e.sender.dimension];
|
||||
saveData();
|
||||
e.sender.addChatMessage(ModAPI.reflect.getClassById("net.minecraft.util.ChatComponentText").constructors[0](ModAPI.util.str("Set waypoint "+waypointId+".")));
|
||||
}
|
||||
if (e.command.toLowerCase().startsWith("/wp ") && e.sender.canCommandSenderUseCommand(2, ModAPI.util.str("wp"))) {
|
||||
e.preventDefault = true;
|
||||
var name = ModAPI.util.unstring(e.sender.getName().getRef());
|
||||
var waypointId = e.command.split(" ")[1];
|
||||
if (waypointId && Array.isArray(data?.[name]?.[waypointId])) {
|
||||
|
||||
// Wildly important! regular setPosition triggers minecraft's built in anti-cheat and teleports you back in the same tick.
|
||||
if (data?.[name]?.[waypointId]?.[3] && (data?.[name]?.[waypointId]?.[3] !== e.sender.dimension)) {
|
||||
e.sender.travelToDimension(data?.[name]?.[waypointId]?.[3]);
|
||||
}
|
||||
|
||||
e.sender.setPositionAndUpdate(...data?.[name]?.[waypointId]);
|
||||
|
||||
e.sender.addChatMessage(ModAPI.reflect.getClassById("net.minecraft.util.ChatComponentText").constructors[0](ModAPI.util.str("Teleported to waypoint " + waypointId + ".")));
|
||||
} else {
|
||||
e.sender.addChatMessage(ModAPI.reflect.getClassById("net.minecraft.util.ChatComponentText").constructors[0](ModAPI.util.str("No such waypoint.")));
|
||||
}
|
||||
}
|
||||
if (e.command.toLowerCase().startsWith("/remwp ") && e.sender.canCommandSenderUseCommand(2, ModAPI.util.str("remwp"))) {
|
||||
e.preventDefault = true;
|
||||
var name = ModAPI.util.unstring(e.sender.getName().getRef());
|
||||
var waypointId = e.command.split(" ")[1] || "waypoint";
|
||||
if (!data[name]) {
|
||||
data[name] = {};
|
||||
}
|
||||
delete data[name][waypointId];
|
||||
saveData();
|
||||
e.sender.addChatMessage(ModAPI.reflect.getClassById("net.minecraft.util.ChatComponentText").constructors[0](ModAPI.util.str("Removed waypoint "+waypointId+".")));
|
||||
}
|
||||
if ((e.command.toLowerCase() === "/listwp") && e.sender.canCommandSenderUseCommand(2, ModAPI.util.str("listwp"))) {
|
||||
e.preventDefault = true;
|
||||
var name = ModAPI.util.unstring(e.sender.getName().getRef());
|
||||
if (!data[name]) {
|
||||
data[name] = {};
|
||||
}
|
||||
e.sender.addChatMessage(ModAPI.reflect.getClassById("net.minecraft.util.ChatComponentText").constructors[0](ModAPI.util.str("Your waypoints: " + Object.keys(data[name]).join(", "))));
|
||||
}
|
||||
});
|
||||
});
|
||||
})();
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,31 @@
|
||||
(() => {
|
||||
PluginAPI.dedicatedServer.appendCode(function () { //Run this code on the server
|
||||
PluginAPI.addEventListener("processcommand", (event) => { //Command processing event
|
||||
// Check if the sender is a player
|
||||
if (!ModAPI.reflect.getClassById("net.minecraft.entity.player.EntityPlayerMP").instanceOf(event.sender.getRef())) { return; }
|
||||
|
||||
// Check if the command is "/spawnxp"
|
||||
if (event.command.toLowerCase().startsWith("/spawnxp")) {
|
||||
const world = event.sender.getServerForPlayer();
|
||||
const senderPos = event.sender.getPosition();
|
||||
|
||||
// Create an xp orb entity
|
||||
const EntityXP = ModAPI.reflect.getClassByName("EntityXPOrb");
|
||||
const xporb = EntityXP.constructors[0](world.getRef(), senderPos.getX(), senderPos.getY(), senderPos.getZ(), 10);
|
||||
|
||||
// Add the xp orb to the world
|
||||
ModAPI.promisify(ModAPI.hooks.methods.nmw_World_spawnEntityInWorld)(world.getRef(), xporb).then(result => {
|
||||
// Notify the player that the xp orb has been spawned
|
||||
|
||||
// Get the chat component class
|
||||
const ChatComponentTextClass = ModAPI.reflect.getClassById("net.minecraft.util.ChatComponentText");
|
||||
// Construct the chat component and send it to the client.
|
||||
event.sender.addChatMessage(ChatComponentTextClass.constructors[0](ModAPI.util.str("An xp orb has been spawned!")));
|
||||
});
|
||||
|
||||
// Prevent the command from executing further (stops syntax errors / command does not exist errors)
|
||||
event.preventDefault = true;
|
||||
}
|
||||
});
|
||||
});
|
||||
})();
|
||||
Reference in New Issue
Block a user