diff --git a/.vitepress/config.mts b/.vitepress/config.mts index 08a5e0f7f..1d21e8d9f 100644 --- a/.vitepress/config.mts +++ b/.vitepress/config.mts @@ -1,8 +1,11 @@ import snippetPlugin from "markdown-it-vuepress-code-snippet-enhanced"; import defineVersionedConfig from "vitepress-versioning-plugin"; -import { loadLocales } from "./i18n"; +import { getLocalisedSidebar, loadLocales, processExistingEntries } from "./i18n"; import { transformItems, transformPageData } from "./transform"; +import { DefaultTheme } from "vitepress"; +import { readdirSync } from "node:fs"; +import { resolve } from "node:path"; // https://vitepress.dev/reference/site-config // https://www.npmjs.com/package/vitepress-versioning-plugin @@ -51,10 +54,15 @@ export default defineVersionedConfig( transformPageData, versioning: { - latestVersion: "1.20.4", + latestVersion: "1.21", rewrites: { localePrefix: "translated", }, + sidebars: { + sidebarContentProcessor(sidebar: DefaultTheme.SidebarMulti) { + return processExistingEntries(sidebar); + }, + } }, }, __dirname diff --git a/.vitepress/i18n.ts b/.vitepress/i18n.ts index 202b75b90..79f4ffed1 100644 --- a/.vitepress/i18n.ts +++ b/.vitepress/i18n.ts @@ -1,6 +1,6 @@ import { existsSync, readdirSync, readFileSync } from "fs"; import { resolve } from "path/posix"; -import { LocaleConfig } from "vitepress"; +import { DefaultTheme, LocaleConfig } from "vitepress"; import DevelopSidebar from "./sidebars/develop"; import PlayersSidebar from "./sidebars/players"; @@ -34,6 +34,75 @@ export const getWebsiteResolver = (localeFolder: string) => export const getSidebarResolver = (localeFolder: string) => getTranslationsResolver(localeFolder, "sidebar_translations.json"); +export function processExistingEntries(sidebar: DefaultTheme.SidebarMulti): DefaultTheme.SidebarMulti { + // Get locales from __dirname/../translated/* folder names. + const localeFolders = readdirSync(resolve(__dirname, "..", "translated"), { withFileTypes: true }) + .filter((dirent) => dirent.isDirectory()) + .map((dirent) => dirent.name); + + // Get all versioning entries that match / + // aka, does not match /players or /develop or /develop or /players + + const keys = Object.keys(sidebar); + const versionedEntries = keys.filter((key) => { + return !key.includes("/players") && !key.includes("/develop") && localeFolders.some((locale) => key.includes(locale)); + }); + + const versionsMet = new Set(); + // Now, ensure that //players and //develop are included in the sidebar. Use /players and /develop as the key. + for (const entry of versionedEntries) { + const split = entry.split("/"); + const locale = split[1]; + const version = split[2]; + + versionsMet.add(version); + + const playersToCopy = JSON.parse(JSON.stringify(sidebar[`/${version}/players/`])); + const developToCopy = JSON.parse(JSON.stringify(sidebar[`/${version}/develop/`])); + + sidebar[`/${locale}/${version}/players/`] = getLocalisedSidebar(playersToCopy, locale); + sidebar[`/${locale}/${version}/develop/`] = getLocalisedSidebar(developToCopy, locale); + + // Delete the original entry. + delete sidebar[entry]; + } + + for (const version of versionsMet) { + // @ts-ignore + sidebar[`/${version}/players/`] = getLocalisedSidebar(sidebar[`/${version}/players/`], "root"); + // @ts-ignore + sidebar[`/${version}/develop/`] = getLocalisedSidebar(sidebar[`/${version}/develop/`], "root"); + } + + return sidebar; +} + +export function getLocalisedSidebar( + sidebar: Fabric.SidebarItem[], + localeCode: string +): Fabric.SidebarItem[] { + const sidebarResolver = getSidebarResolver(localeCode); + const localisedSidebar = JSON.parse(JSON.stringify(sidebar)); + + for (const item of localisedSidebar) { + if (item.translatable === false) { + continue; + } + + item.text = sidebarResolver(item.text); + + if (item.link && localeCode !== "root" && item.process !== false) { + item.link = `/${localeCode}${item.link}`; + } + + if (item.items) { + item.items = getLocalisedSidebar(item.items, localeCode); + } + } + + return localisedSidebar; +} + /** * Generates translated sidebars for a given root directory and sidebars. * @@ -41,36 +110,10 @@ export const getSidebarResolver = (localeFolder: string) => * @param dirname - The root directory to generate translated sidebars for. * @returns An object containing translated sidebars, keyed by locale URL. */ -function generateTranslatedSidebars( +export function generateTranslatedSidebars( sidebars: { [url: string]: Fabric.SidebarItem[] }, dirname: string ): { [localeUrl: string]: Fabric.SidebarItem[] } { - function getLocalisedSidebar( - sidebar: Fabric.SidebarItem[], - localeCode: string - ): Fabric.SidebarItem[] { - const sidebarResolver = getSidebarResolver(localeCode); - const localisedSidebar = JSON.parse(JSON.stringify(sidebar)); - - for (const item of localisedSidebar) { - if (item.translatable === false) { - continue; - } - - item.text = sidebarResolver(item.text); - - if (item.link && localeCode !== "root" && item.process !== false) { - item.link = `/${localeCode}${item.link}`; - } - - if (item.items) { - item.items = getLocalisedSidebar(item.items, localeCode); - } - } - - return localisedSidebar; - } - const translatedSidebars: { [key: string]: Fabric.SidebarItem[] } = {}; for (const key of Object.keys(sidebars)) { @@ -117,6 +160,7 @@ function generateTranslatedThemeConfig(localeCode: string): Fabric.ThemeConfig { if (localeCode === "root") { return null; } else { + // @ts-ignore return crowdinOverrides[localeCode] ?? localeCode.split("_")[0]; } }; @@ -313,8 +357,8 @@ export function loadLocales(dirname: string): LocaleConfig { language === region.toLowerCase() ? localeNameInEnglish.of(language)! : localeNameInEnglish.of(language)! + - " - " + - regionNameInEnglish.of(region); + " - " + + regionNameInEnglish.of(region); const localisedName = localeNameInLocale.of(language)![0].toUpperCase() + diff --git a/.vitepress/sidebars/versioned/.gitkeep b/.vitepress/sidebars/versioned/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/.vitepress/sidebars/versioned/1.20.4.json b/.vitepress/sidebars/versioned/1.20.4.json new file mode 100644 index 000000000..d3515813c --- /dev/null +++ b/.vitepress/sidebars/versioned/1.20.4.json @@ -0,0 +1,264 @@ +{ + "/players/": [ + { + "text": "players.title", + "link": "/players/", + "items": [ + { + "text": "players.faq", + "link": "/players/faq" + }, + { + "text": "players.installingJava", + "collapsed": true, + "items": [ + { + "text": "players.installingJava.windows", + "link": "/players/installing-java/windows" + }, + { + "text": "players.installingJava.macOS", + "link": "https://fabricmc.net/wiki/player:tutorials:java:mac", + "process": false + }, + { + "text": "players.installingJava.linux", + "link": "/players/installing-java/linux" + } + ] + }, + { + "text": "players.installingFabric", + "link": "/players/installing-fabric" + }, + { + "text": "players.findingMods", + "link": "/players/finding-mods" + }, + { + "text": "players.installingMods", + "link": "/players/installing-mods" + }, + { + "text": "players.troubleshooting", + "items": [ + { + "text": "players.troubleshooting.uploadingLogs", + "link": "/players/troubleshooting/uploading-logs" + }, + { + "text": "players.troubleshooting.crashReports", + "link": "/players/troubleshooting/crash-reports" + } + ] + }, + { + "text": "players.updatingFabric", + "link": "/players/updating-fabric" + } + ] + } + ], + "/develop/": [ + { + "text": "develop.title", + "link": "/develop/", + "collapsed": false, + "items": [ + { + "text": "Fabric API GitHub", + "translatable": false, + "link": "https://github.com/FabricMC/fabric" + }, + { + "text": "Yarn GitHub", + "translatable": false, + "link": "https://github.com/FabricMC/yarn" + }, + { + "text": "Loom GitHub", + "translatable": false, + "link": "https://github.com/FabricMC/fabric-loom" + } + ] + }, + { + "text": "develop.gettingStarted", + "collapsed": false, + "items": [ + { + "text": "develop.gettingStarted.introduction", + "link": "/develop/getting-started/introduction-to-fabric-and-modding" + }, + { + "text": "develop.gettingStarted.devEnvSetup", + "link": "/develop/getting-started/setting-up-a-development-environment" + }, + { + "text": "develop.gettingStarted.creatingProject", + "link": "/develop/getting-started/creating-a-project" + }, + { + "text": "develop.gettingStarted.projectStructure", + "link": "/develop/getting-started/project-structure" + }, + { + "text": "develop.gettingStarted.launchGame", + "link": "/develop/getting-started/launching-the-game" + } + ] + }, + { + "text": "develop.items", + "collapsed": true, + "items": [ + { + "text": "develop.items.first-item", + "link": "/develop/items/first-item" + }, + { + "text": "develop.items.food", + "link": "/develop/items/food" + }, + { + "text": "develop.items.custom-tools", + "link": "/develop/items/custom-tools" + }, + { + "text": "develop.items.custom-armor", + "link": "/develop/items/custom-armor" + }, + { + "text": "develop.items.custom-item-groups", + "link": "/develop/items/custom-item-groups" + }, + { + "text": "develop.items.custom-item-interactions", + "link": "/develop/items/custom-item-interactions" + }, + { + "text": "develop.items.potions", + "link": "/develop/items/potions" + } + ] + }, + { + "text": "develop.blocks", + "collapsed": true, + "items": [ + { + "text": "develop.blocks.first-block", + "link": "/develop/blocks/first-block" + }, + { + "text": "develop.blocks.blockstates", + "link": "/develop/blocks/blockstates" + } + ] + }, + { + "text": "develop.entities", + "collapsed": true, + "items": [ + { + "text": "develop.entities.effects", + "link": "/develop/entities/effects" + }, + { + "text": "develop.entities.damage-types", + "link": "/develop/entities/damage-types" + } + ] + }, + { + "text": "develop.sounds", + "collapsed": true, + "items": [ + { + "text": "develop.sounds.using-sounds", + "link": "/develop/sounds/using-sounds" + }, + { + "text": "develop.sounds.custom", + "link": "/develop/sounds/custom" + } + ] + }, + { + "text": "develop.commands", + "collapsed": true, + "items": [ + { + "text": "develop.commands.basics", + "link": "/develop/commands/basics" + }, + { + "text": "develop.commands.arguments", + "link": "/develop/commands/arguments" + }, + { + "text": "develop.commands.suggestions", + "link": "/develop/commands/suggestions" + } + ] + }, + { + "text": "develop.rendering", + "collapsed": true, + "items": [ + { + "text": "develop.rendering.basicConcepts", + "link": "/develop/rendering/basic-concepts" + }, + { + "text": "develop.rendering.drawContext", + "link": "/develop/rendering/draw-context" + }, + { + "text": "develop.rendering.hud", + "link": "/develop/rendering/hud" + }, + { + "text": "develop.rendering.gui", + "items": [ + { + "text": "develop.rendering.gui.customScreens", + "link": "/develop/rendering/gui/custom-screens" + }, + { + "text": "develop.rendering.gui.customWidgets", + "link": "/develop/rendering/gui/custom-widgets" + } + ] + }, + { + "text": "develop.rendering.particles", + "items": [ + { + "text": "develop.rendering.particles.creatingParticles", + "link": "/develop/rendering/particles/creating-particles" + } + ] + } + ] + }, + { + "text": "develop.misc", + "collapsed": true, + "items": [ + { + "text": "develop.misc.codecs", + "link": "/develop/codecs" + }, + { + "text": "develop.misc.events", + "link": "/develop/events" + }, + { + "text": "develop.misc.text-and-translations", + "link": "/develop/text-and-translations" + } + ] + } + ] +} \ No newline at end of file diff --git a/.vitepress/theme/components/VersionReminder.vue b/.vitepress/theme/components/VersionReminder.vue new file mode 100644 index 000000000..bdaf7d157 --- /dev/null +++ b/.vitepress/theme/components/VersionReminder.vue @@ -0,0 +1,143 @@ + + + + + \ No newline at end of file diff --git a/.vitepress/theme/index.ts b/.vitepress/theme/index.ts index 81dee428f..d28165214 100644 --- a/.vitepress/theme/index.ts +++ b/.vitepress/theme/index.ts @@ -10,6 +10,7 @@ import NotFoundComponent from "./components/NotFoundComponent.vue"; import AuthorsComponent from "./components/AuthorsComponent.vue"; import DownloadEntry from './components/DownloadEntry.vue'; import ColorSwatch from './components/ColorSwatch.vue'; +import VersionReminder from './components/VersionReminder.vue'; import VideoPlayer from './components/VideoPlayer.vue'; import "./style.css"; @@ -26,6 +27,8 @@ export default { }, Layout() { const children = { + "doc-before": () => h(VersionReminder), + "aside-outline-before": () => h(VersionReminder), "aside-outline-after": () => h(AuthorsComponent), "layout-top": () => h(BannerComponent), }; diff --git a/.vitepress/update.ts b/.vitepress/update.ts new file mode 100644 index 000000000..e90d8367f --- /dev/null +++ b/.vitepress/update.ts @@ -0,0 +1,112 @@ +import prompts from "prompts"; +import fs from "node:fs" +import * as glob from "glob" +import players from "./sidebars/players"; +import develop from "./sidebars/develop"; + +(async () => { + // Determine old minecraft version by reading /reference/latest/build.gradle's `def minecraftVersion = "XXXX"` line. + const buildGradle = fs.readFileSync("./reference/latest/build.gradle", "utf-8"); + // @ts-ignore + const oldVersion = buildGradle.match(/def minecraftVersion = "([^"]+)"/)[1]; + + const newVersion = await (await prompts({ + type: 'text', + name: 'version', + message: 'Enter the new Minecraft version.' + })).version; + + console.log("Fetching Yarn version for Minecraft " + newVersion + "..."); + const yarnVersions: any[] = await (await fetch(`https://meta.fabricmc.net/v2/versions/yarn/${newVersion}`)).json() as any[]; + const yarnVersion = yarnVersions.find(v => v.stable)?.version; + if (!yarnVersion) { + console.error("No stable Yarn version found for Minecraft " + newVersion.version); + process.exit(1); + } + console.log("Found Yarn version " + yarnVersion); + + console.log("Fetching Fabric API version for Minecraft " + newVersion + "..."); + const fabricApiVersions: any[] = await (await fetch(`https://api.modrinth.com/v2/project/fabric-api/version?loaders=["fabric"]&game_versions=["${newVersion}"]&featured=true`)).json() as any[]; + const fabricApiVersion = fabricApiVersions[0]?.version_number; + if (!fabricApiVersion) { + console.error("No Fabric API version found for Minecraft " + newVersion); + process.exit(1); + } + console.log("Found Fabric API version " + fabricApiVersion); + + console.log("Copying latest -> " + oldVersion + "..."); + + // Copy ./reference/latest/** -> ./refrence/oldVersion/** + fs.cpSync("./reference/latest", "./reference/" + oldVersion, { recursive: true }); + + // Update build.gradle in latest with new versions. + // def minecraftVersion = "XXX" + // def yarnVersion = "XXXXX" + // def fabricApiVersion = "XXXX" + const newBuildGrade = buildGradle + .replace(/def minecraftVersion = "([^"]+)"/, `def minecraftVersion = "${newVersion}"`) + .replace(/def yarnVersion = "([^"]+)"/, `def yarnVersion = "${yarnVersion}"`) + .replace(/def fabricApiVersion = "([^"]+)"/, `def fabricApiVersion = "${fabricApiVersion}"`); + + fs.writeFileSync("./reference/latest/build.gradle", newBuildGrade); + + // Add `include "{oldVersion}"` to the end of settings.gradle + const settingsGradle = fs.readFileSync("./reference/settings.gradle", "utf-8"); + const newSettingsGradle = settingsGradle + `\ninclude "${oldVersion}"`; + fs.writeFileSync("./reference/settings.gradle", newSettingsGradle); + + console.log("Refrence mod has been bumped successfully."); + console.log("Migrating content to versioned/" + oldVersion + "..."); + + // Move all markdown files except README.md to versions/oldVersion + const markdownFiles = glob.sync("**/*.md", { ignore: [ + "README.md", + "contributing.md", + "versions/**/*.md", + "node_modules/**/*", + ]}); + + // Copy into versions/oldVersion and respect the directory structure. + for (const file of markdownFiles) { + const oldPath = "./" + file; + const newPath = "./versions/" + oldVersion + "/" + file; + fs.cpSync(oldPath, newPath); + } + + console.log("Migration complete.") + console.log("Migration sidebars...") + + const versionedSidebar = { + '/players/': players, + '/develop/': develop + }; + + fs.writeFileSync("./.vitepress/sidebars/versioned/" + oldVersion + ".json", JSON.stringify(versionedSidebar, null, 2)); + + console.log("Migrated sidebars.") + + // console.log("Copying translations...") + // // Copy translated/**/*.md -> versions/oldVersion/translated/**/*.md + // const translatedFiles = glob.sync("translated/**/*.md"); + // for (const file of translatedFiles) { + // const oldPath = "./" + file; + // const newPath = "./versions/" + oldVersion + "/" + file; + // fs.cpSync(oldPath, newPath); + // } + + console.log("Updating internal links..."); + + // Get all markdown files within versions/oldVersion + const versionedMarkdownFiles = glob.sync(`versions/${oldVersion}/**/*.md`); + // Process all content + for (const file of versionedMarkdownFiles) { + const content = fs.readFileSync(file, "utf-8"); + + // Replace all instances of @/reference/latest/ with @/reference/oldVersion/ + const newContent = content.replace(/@\/reference\/latest\//g, `@/reference/${oldVersion}/`); + fs.writeFileSync(file, newContent); + } + + console.log("Updated internal links."); + console.log("DONE! Make sure that the changes are correct before committing."); +})(); \ No newline at end of file diff --git a/develop/items/custom-armor.md b/develop/items/custom-armor.md index 4ac1bc6ca..6f4a29fcd 100644 --- a/develop/items/custom-armor.md +++ b/develop/items/custom-armor.md @@ -9,105 +9,87 @@ authors: Armor provides the player with increased defense against attacks from mobs and other players. -## Creating an Armor Material {#creating-an-armor-material} +## Creating an Armor Materials Class {#creating-an-armor-materials-class} -::: info -If you plan to make multiple armor materials, consider using an `Enum` to store them. Vanilla does this in the `ArmorMaterials` class, which stores all the armor materials that are used in the game. - -This class can also be used to determine your armor material's properties in relation to vanilla armor materials. -::: - -All armor items - like tools - have an armor material. - -The armor material tells the game what protection and durability the armor item should have depending on the slot. - -You'll need to create a class that inherits `ArmorMaterial`, like so: - -@[code transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/item/armor/GuiditeArmorMaterial.java) - -The following methods will have to be implemented as well - these methods tell the game vital information on your armor items: - -- ### Durability - `getDurability(ArmorItem.Type type)` - - Returns the durability for a specific armor type - in hit points. - - The hit points specify the amount of hits the armor item can take before breaking. +Just like items and blocks, armor materials need to be registered. We will create a `ModArmorMaterials` class to store our custom armor materials for the sake of organization. - **Example** +You will need to add a static `initialize()` method to this class, and call it from your mod's entrypoint so that the materials are registered. - @[code transcludeWith=:::2](@/reference/latest/src/main/java/com/example/docs/item/armor/GuiditeArmorMaterial.java) +```java +// Within the ModArmorMaterials class +public static void initialize() {}; +``` -- #### Protection - `getProtection(ArmorItem.Type type)` - - Returns the protection value for a specific armor type. - - Usually this is always the same, regardless of your armor material. - - **Example** - - @[code transcludeWith=:::3](@/reference/latest/src/main/java/com/example/docs/item/armor/GuiditeArmorMaterial.java) - -- #### Enchantability - `getEnchantability()` - - How easy is it to get better and higher level enchantments with this item? +::: warning +Make sure to call this method **before** you register your items, as the materials will need to be registered before the items can be created. +::: - **Example** +```java +@Override +public void onInitialize() { + ModArmorMaterials.initialize(); +} +``` - @[code transcludeWith=:::4](@/reference/latest/src/main/java/com/example/docs/item/armor/GuiditeArmorMaterial.java) +--- -- #### Equip Sound - `getEquipsound()` +Within this `ModArmorMaterials` class, you will need to create a static method which will register the armor material. This method should return a registry entry of the material, as this entry will be used by the ArmorItem constructor to create the armor items. - What sound should be played when the armor is equipped? +@[code transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/item/armor/ModArmorMaterials.java) - **Example** +## Armor Material Properties {#armor-material-properties} - @[code transcludeWith=:::5](@/reference/latest/src/main/java/com/example/docs/item/armor/GuiditeArmorMaterial.java) +::: tip +If you're struggling to gauge a good value for any of these properties, consider looking at the vanilla armor materials in the `ArmorMaterials` class. +::: -- #### Repair Ingredient - `getRepairIngredient()` +When creating an armor material, you will need to define the following properties: - What item or items can be used in an anvil to repair the armor items? +### Defense Points {#defense-points} - **Example** +::: warning +Ensure you assign a value to each type of armor piece you plan to create and register as an item. If you make an item for an armor piece without a set defense point value, the game will crash. +::: - @[code transcludeWith=:::6](@/reference/latest/src/main/java/com/example/docs/item/armor/GuiditeArmorMaterial.java) +The `defensePoints` map is used to define the number of defense points that each armor piece will provide. The higher the number, the more protection the armor piece will provide. The map should contain an entry for each armor piece type. -- #### Name - `getName()` +### Enchantability {#enchantability} - The name of the armor material - must be lowercase. +The `enchantability` property defines how easily the armor can be enchanted. The higher the number, the more enchantments the armor can receive. - **Example** +### Equip Sound {#equip-sound} - @[code transcludeWith=:::7](@/reference/latest/src/main/java/com/example/docs/item/armor/GuiditeArmorMaterial.java) +The `equipSound` property is the sound that will play when the armor is equipped. This sound should be a registry entry of a `SoundEvent`. Consider taking a look at the [Custom Sound Events](../sounds/custom) page if you are considering creating custom sounds rather than relying on vanilla sounds within the `SoundEvents` class. -- #### Toughness - `getToughness()` +### Repair Ingredient(s) {#repair-ingredient} - How much protection should be given for high-damage attacks? +The `repairIngredientSupplier` property is a supplier of an `Ingredient` that is used to repair the armor. This ingredient can pretty much be anything, it's recommended to set it to be the same as the material's crafting ingredient used to actually craft the armor items. - For reference, everything except diamond (`2.0F`) and netherite (`4.0F`) have a toughness of zero. +### Toughness {#toughness} - **Example** +The `toughness` property defines how much damage the armor will absorb. The higher the number, the more damage the armor will absorb. - @[code transcludeWith=:::8](@/reference/latest/src/main/java/com/example/docs/item/armor/GuiditeArmorMaterial.java) +### Knockback Resistance {#knockback-resistance} -- #### Knockback Resistance - `getKnockbackResistance()` +The `knockbackResistance` property defines how much knockback the player will reflect when hit. The higher the number, the less knockback the player will receive. - How much knockback resistance should the armor give the entity? +### Dyeable {#dyeable} - **Example** +The `dyeable` property is a boolean that defines whether the armor can be dyed. If set to `true`, the armor can be dyed using dyes in a crafting table. - @[code transcludeWith=:::9](@/reference/latest/src/main/java/com/example/docs/item/armor/GuiditeArmorMaterial.java) +If you do choose to make your armor dyeable, your armor layer and item textures must be **designed to be dyed**, as the dye will overlay the texture, not replace it. Take a look at the vanilla leather armor for an example, the textures are grayscale and the dye is applied as an overlay, causing the armor to change color. -## Creating an Instance of the ArmorMaterial {#creating-an-instance-of-the-armormaterial} +## Registering the Armor Material {#registering-the-armor-material} -To use the armor material with the armor items, you'll need to create an instance of it - similar to a tool material: +Now that you've created a utility method which can be used to register armor materials, you can register your custom armor materials as a static field in the `ModArmorMaterials` class. -@[code transcludeWith=:::_10](@/reference/latest/src/main/java/com/example/docs/item/armor/GuiditeArmorMaterial.java) +For this example, we'll be creative Guidite armor, with the following properties: -You can place this instance in the armor material class itself. +@[code transcludeWith=:::2](@/reference/latest/src/main/java/com/example/docs/item/armor/ModArmorMaterials.java) ## Creating the Armor Items {#creating-the-armor-items} -Now that you've created an instance of the material, you can create the armor items in your `ModItems` class: +Now that you've registered the material, you can create the armor items in your `ModItems` class: Obviously, an armor set doesn't need every type to be satisfied, you can have a set with just boots, or leggings etc. - the vanilla turtle shell helmet is a good example of an armor set with missing slots. @@ -148,14 +130,12 @@ When an entity wears your armor, currently the missing texture will appear: ![Broken armor model on player](/assets/develop/items/armor_2.png). -This is because all armor textures are hardcoded by vanilla, to create our own, we'll have to place the texture in the vanilla armor texture folder. - There are two layers for the armor texture, both must be present. Since the armor material name in our case is `guidite`, the locations of the textures will be: -- `assets/minecraft/textures/models/armor/guidite_layer_1.png` -- `assets/minecraft/textures/models/armor/guidite_layer_2.png` +- `assets//textures/models/armor/guidite_layer_1.png` +- `assets//textures/models/armor/guidite_layer_2.png` diff --git a/develop/items/custom-tools.md b/develop/items/custom-tools.md index bd8b27e18..9e538888f 100644 --- a/develop/items/custom-tools.md +++ b/develop/items/custom-tools.md @@ -49,16 +49,30 @@ The tool material tells the game the following information: @[code transcludeWith=:::4](@/reference/latest/src/main/java/com/example/docs/item/tool/GuiditeMaterial.java) -- ### Mining Level - `getMiningLevel()` {#mining-level} +- ### Inverse Tag - `getMiningLevel()` {#inverse-tag} - What blocks can be broken by this tool? Can it mine diamonds? + The inverse tag shows what the tool _**cannot**_ mine. For instance, using the `BlockTags.INCORRECT_FOR_WOODEN_TOOL` tag stops the tool from mining certain blocks: - A mining level of 3+ is needed to require obsidian whilst a level of 2 is required to mine diamonds. + ```json + { + "values": [ + "#minecraft:needs_diamond_tool", + "#minecraft:needs_iron_tool", + "#minecraft:needs_stone_tool" + ] + } + ``` + + This means the tool can't mine blocks that need a diamond, iron, or stone tool. **Example** + We'll use the iron tool tag. This stops Guidite tools from mining blocks that require a stronger tool than iron. + @[code transcludeWith=:::5](@/reference/latest/src/main/java/com/example/docs/item/tool/GuiditeMaterial.java) + You can use `TagKey.of(...)` to create a custom tag key if you want to use a custom tag. + - ### Enchantability - `getEnchantability()` {#enchantability} How easy is it to get better and higher level enchantments with this item? For reference, Gold has an enchantability of 22 whilst Netherite has an enchantability of 15. @@ -81,7 +95,7 @@ Once you have created your tool material and tweaked it to your likings, you can ## Creating Tool Items {#creating-tool-items} -Using the same way you registered your first item, you should register each tool similarly: +Using the same utility function as in the [Creating Your First Item](./first-item) guide, you can create your tool items: @[code transcludeWith=:::7](@/reference/latest/src/main/java/com/example/docs/item/ModItems.java) diff --git a/develop/items/potions.md b/develop/items/potions.md index 1cddcec2f..df4bf6bef 100644 --- a/develop/items/potions.md +++ b/develop/items/potions.md @@ -14,63 +14,38 @@ as items through various other game mechanics. ## Custom Potions {#custom-potions} -Adding a potion follows a similar path as adding an item. You will create an instance of your potion and register it by -calling `BrewingRecipeRegistry.registerPotionRecipe`. - -::: info -When Fabric API is present, `BrewingRecipeRegistry.registerPotionRecipe` is made accessible through an Access Widener. -::: +Just like items and blocks, potions need to be registered. ### Creating the Potion {#creating-the-potion} Let's start by declaring a field to store your `Potion` instance. We will be directly using the initializer class to hold this. -@[code lang=java transclude={18-27}](@/reference/latest/src/main/java/com/example/docs/potion/FabricDocsReferencePotions.java) +@[code lang=java transclude={21-29}](@/reference/latest/src/main/java/com/example/docs/potion/FabricDocsReferencePotions.java) We pass an instance of `StatusEffectInstance`, which takes 3 parameters: -- `StatusEffect type` - An effect. We use our custom effect here. Alternatively you can access vanilla effects - through `net.minecraft.entity.effect.StatusEffects`. +- `RegistryEntry type` - An effect. We use our custom effect here. Alternatively you can access vanilla effects + through vanilla's `StatusEffects` class. - `int duration` - Duration of the effect in game ticks. - `int amplifier` - An amplifier for the effect. For example, Haste II would have an amplifier of 1. ::: info -To create your own effect, please see the [Effects](../entities/effects) guide. +To create your own potion effect, please see the [Effects](../entities/effects) guide. ::: ### Registering the Potion {#registering-the-potion} -In our initializer, we call `BrewingRecipeRegistry.registerPotionRecipe`. +In our initializer, we will use the `FabricBrewingRecipeRegistryBuilder.BUILD` event to register our potion using the `BrewingRecipeRegistry.registerPotionRecipe` method. -@[code lang=java transclude={30-30}](@/reference/latest/src/main/java/com/example/docs/potion/FabricDocsReferencePotions.java) +@[code lang=java transclude={33-42}](@/reference/latest/src/main/java/com/example/docs/potion/FabricDocsReferencePotions.java) `registerPotionRecipe` takes 3 parameters: -- `Potion input` - The starting potion. Usually this can be a Water Bottle or an Awkward Potion. +- `RegistryEntry input` - The starting potion's registry entry. Usually this can be a Water Bottle or an Awkward Potion. - `Item item` - The item which is the main ingredient of the potion. -- `Potion output` - The resultant potion. - -If you use Fabric API, the mixin invoker is not necessary and a direct call -to `BrewingRecipeRegistry.registerPotionRecipe` can be done. - -The full example: - -@[code lang=java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/potion/FabricDocsReferencePotions.java) +- `RegistryEntry output` - The resultant potion's registry entry. Once registered, you can brew a Tater potion using a potato. ![Effect in player inventory](/assets/develop/tater-potion.png) - -::: info Registering Potions Using an `Ingredient` - -With the help of Fabric API, it's possible to register a potion using an `Ingredient` instead of an `Item` using ` -net.fabricmc.fabric.api.registry.FabricBrewingRecipeRegistry`. -::: - -### Registering the Potion Without Fabric API {#registering-the-potion-without-fabric-api} - -Without Fabric API, `BrewingRecipeRegistry.registerPotionRecipe` will be private. In order to access this method, use -the following mixin invoker or use an Access Widener. - -@[code lang=java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/mixin/potion/BrewingRecipeRegistryInvoker.java) diff --git a/develop/rendering/basic-concepts.md b/develop/rendering/basic-concepts.md index fcc509434..cc1921c8a 100644 --- a/develop/rendering/basic-concepts.md +++ b/develop/rendering/basic-concepts.md @@ -26,11 +26,11 @@ The `Tessellator` is the main class used to render things in Minecraft. It is a The `BufferBuilder` is the class used to format and upload rendering data to OpenGL. It is used to create a buffer, which is then uploaded to OpenGL to draw. -The `Tessellator` is used to create a `BufferBuilder`, which is used to format and upload rendering data to OpenGL. You can create a `BufferBuilder` using `Tessellator.getBuffer()`. +The `Tessellator` is used to create a `BufferBuilder`, which is used to format and upload rendering data to OpenGL. ### Initializing the `BufferBuilder` {#initializing-the-bufferbuilder} -Before you can write anything to the `BufferBuilder`, you must initialize it. This is done using `BufferBuilder.begin(...)`, which takes in a `VertexFormat` and a draw mode. +Before you can write anything to the `BufferBuilder`, you must initialize it. This is done using `Tessellator#begin(...)` method, which takes in a `VertexFormat` and a draw mode and returns a `BufferBuilder`. #### Vertex Formats {#vertex-formats} @@ -76,7 +76,7 @@ Once the `BufferBuilder` is initialized, you can write data to it. The `BufferBuilder` allows us to construct our buffer, vertex by vertex. To add a vertex, we use the `buffer.vertex(matrix, float, float, float)` method. The `matrix` parameter is the transformation matrix, which we'll discuss in more detail later. The three float parameters represent the (x, y, z) coordinates of the vertex position. -This method returns a vertex builder, which we can use to specify additional information for the vertex. It's crucial to follow the order of our defined `VertexFormat` when adding this information. If we don't, OpenGL might not interpret our data correctly. After we've finished building a vertex, we call the `.next()` method. This finalizes the current vertex and prepares the builder for the next one. +This method returns a vertex builder, which we can use to specify additional information for the vertex. It's crucial to follow the order of our defined `VertexFormat` when adding this information. If we don't, OpenGL might not interpret our data correctly. After we've finished building a vertex, just continue adding more vertices and data to the buffer until you're done. It's also worth understanding the concept of culling. Culling is the process of removing faces of a 3D shape that aren't visible from the viewer's perspective. If the vertices for a face are specified in the wrong order, the face might not render correctly due to culling. diff --git a/develop/rendering/hud.md b/develop/rendering/hud.md index e5832a3b0..ec1dc4e35 100644 --- a/develop/rendering/hud.md +++ b/develop/rendering/hud.md @@ -21,9 +21,9 @@ You should check out the [Draw Context](./draw-context) page to learn more about ### DeltaTick {#deltatick} -The `deltaTick` parameter is the time since the last frame, in seconds. This can be used to make animations and other time-based effects. +The `deltaTick` refers to the time since the last frame, in seconds. This can be used to make animations and other time-based effects. -For example, let's say you want to lerp a color over time. You can use the `deltaTick` parameter to do this: +For example, let's say you want to lerp a color over time. You can use the `deltaTickManager` to get the deltaTick, and store it over time to lerp the color: @[code lang=java transcludeWith=:::1](@/reference/latest/src/client/java/com/example/docs/rendering/HudRenderingEntrypoint.java) diff --git a/develop/text-and-translations.md b/develop/text-and-translations.md index 32fe7b5b6..00546a061 100644 --- a/develop/text-and-translations.md +++ b/develop/text-and-translations.md @@ -63,7 +63,7 @@ The language file, `en_us.json`, looks like the following: -As mentioned before, you can serialize text to JSON using the following serializer class: +As mentioned before, you can serialize text to JSON using the text codec. For more information on codecs, see the [Codec](./codecs) page. @[code transcludeWith=:::1](@/reference/latest/src/client/java/com/example/docs/rendering/TextTests.java) @@ -71,7 +71,7 @@ This produces JSON that can be used datapacks, commands and other places that ac ## Deserializing Text {#deserializing-text} -Furthermore, to deserialize a JSON text object into an actual `Text` class, you can use the `fromJson` method: +Furthermore, to deserialize a JSON text object into an actual `Text` class, again, use the codec. @[code transcludeWith=:::2](@/reference/latest/src/client/java/com/example/docs/rendering/TextTests.java) diff --git a/package-lock.json b/package-lock.json index 7db0fe066..73ce284c3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -15,10 +15,15 @@ "vue": "^3.4.27" }, "devDependencies": { + "@types/glob": "^8.1.0", "@types/node": "^20.14.5", + "@types/prompts": "^2.4.9", + "glob": "^10.4.2", "markdownlint": "^0.34.0", "markdownlint-rule-search-replace": "^1.2.0", - "markdownlint-rule-titlecase": "^0.1.0" + "markdownlint-rule-titlecase": "^0.1.0", + "prompts": "^2.4.2", + "ts-node": "^10.9.2" }, "optionalDependencies": { "@rollup/rollup-linux-x64-gnu": "4.18.0" @@ -28,7 +33,6 @@ "version": "1.9.3", "resolved": "https://registry.npmjs.org/@algolia/autocomplete-core/-/autocomplete-core-1.9.3.tgz", "integrity": "sha512-009HdfugtGCdC4JdXUbVJClA0q0zh24yyePn+KUGk3rP7j8FEe/m5Yo/z65gn6nP/cM39PxpzqKrL7A6fP6PPw==", - "license": "MIT", "dependencies": { "@algolia/autocomplete-plugin-algolia-insights": "1.9.3", "@algolia/autocomplete-shared": "1.9.3" @@ -38,7 +42,6 @@ "version": "1.9.3", "resolved": "https://registry.npmjs.org/@algolia/autocomplete-plugin-algolia-insights/-/autocomplete-plugin-algolia-insights-1.9.3.tgz", "integrity": "sha512-a/yTUkcO/Vyy+JffmAnTWbr4/90cLzw+CC3bRbhnULr/EM0fGNvM13oQQ14f2moLMcVDyAx/leczLlAOovhSZg==", - "license": "MIT", "dependencies": { "@algolia/autocomplete-shared": "1.9.3" }, @@ -50,7 +53,6 @@ "version": "1.9.3", "resolved": "https://registry.npmjs.org/@algolia/autocomplete-preset-algolia/-/autocomplete-preset-algolia-1.9.3.tgz", "integrity": "sha512-d4qlt6YmrLMYy95n5TB52wtNDr6EgAIPH81dvvvW8UmuWRgxEtY0NJiPwl/h95JtG2vmRM804M0DSwMCNZlzRA==", - "license": "MIT", "dependencies": { "@algolia/autocomplete-shared": "1.9.3" }, @@ -63,165 +65,148 @@ "version": "1.9.3", "resolved": "https://registry.npmjs.org/@algolia/autocomplete-shared/-/autocomplete-shared-1.9.3.tgz", "integrity": "sha512-Wnm9E4Ye6Rl6sTTqjoymD+l8DjSTHsHboVRYrKgEt8Q7UHm9nYbqhN/i0fhUYA3OAEH7WA8x3jfpnmJm3rKvaQ==", - "license": "MIT", "peerDependencies": { "@algolia/client-search": ">= 4.9.1 < 6", "algoliasearch": ">= 4.9.1 < 6" } }, "node_modules/@algolia/cache-browser-local-storage": { - "version": "4.23.3", - "resolved": "https://registry.npmjs.org/@algolia/cache-browser-local-storage/-/cache-browser-local-storage-4.23.3.tgz", - "integrity": "sha512-vRHXYCpPlTDE7i6UOy2xE03zHF2C8MEFjPN2v7fRbqVpcOvAUQK81x3Kc21xyb5aSIpYCjWCZbYZuz8Glyzyyg==", - "license": "MIT", + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@algolia/cache-browser-local-storage/-/cache-browser-local-storage-4.24.0.tgz", + "integrity": "sha512-t63W9BnoXVrGy9iYHBgObNXqYXM3tYXCjDSHeNwnsc324r4o5UiVKUiAB4THQ5z9U5hTj6qUvwg/Ez43ZD85ww==", "dependencies": { - "@algolia/cache-common": "4.23.3" + "@algolia/cache-common": "4.24.0" } }, "node_modules/@algolia/cache-common": { - "version": "4.23.3", - "resolved": "https://registry.npmjs.org/@algolia/cache-common/-/cache-common-4.23.3.tgz", - "integrity": "sha512-h9XcNI6lxYStaw32pHpB1TMm0RuxphF+Ik4o7tcQiodEdpKK+wKufY6QXtba7t3k8eseirEMVB83uFFF3Nu54A==", - "license": "MIT" + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@algolia/cache-common/-/cache-common-4.24.0.tgz", + "integrity": "sha512-emi+v+DmVLpMGhp0V9q9h5CdkURsNmFC+cOS6uK9ndeJm9J4TiqSvPYVu+THUP8P/S08rxf5x2P+p3CfID0Y4g==" }, "node_modules/@algolia/cache-in-memory": { - "version": "4.23.3", - "resolved": "https://registry.npmjs.org/@algolia/cache-in-memory/-/cache-in-memory-4.23.3.tgz", - "integrity": "sha512-yvpbuUXg/+0rbcagxNT7un0eo3czx2Uf0y4eiR4z4SD7SiptwYTpbuS0IHxcLHG3lq22ukx1T6Kjtk/rT+mqNg==", - "license": "MIT", + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@algolia/cache-in-memory/-/cache-in-memory-4.24.0.tgz", + "integrity": "sha512-gDrt2so19jW26jY3/MkFg5mEypFIPbPoXsQGQWAi6TrCPsNOSEYepBMPlucqWigsmEy/prp5ug2jy/N3PVG/8w==", "dependencies": { - "@algolia/cache-common": "4.23.3" + "@algolia/cache-common": "4.24.0" } }, "node_modules/@algolia/client-account": { - "version": "4.23.3", - "resolved": "https://registry.npmjs.org/@algolia/client-account/-/client-account-4.23.3.tgz", - "integrity": "sha512-hpa6S5d7iQmretHHF40QGq6hz0anWEHGlULcTIT9tbUssWUriN9AUXIFQ8Ei4w9azD0hc1rUok9/DeQQobhQMA==", - "license": "MIT", + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@algolia/client-account/-/client-account-4.24.0.tgz", + "integrity": "sha512-adcvyJ3KjPZFDybxlqnf+5KgxJtBjwTPTeyG2aOyoJvx0Y8dUQAEOEVOJ/GBxX0WWNbmaSrhDURMhc+QeevDsA==", "dependencies": { - "@algolia/client-common": "4.23.3", - "@algolia/client-search": "4.23.3", - "@algolia/transporter": "4.23.3" + "@algolia/client-common": "4.24.0", + "@algolia/client-search": "4.24.0", + "@algolia/transporter": "4.24.0" } }, "node_modules/@algolia/client-analytics": { - "version": "4.23.3", - "resolved": "https://registry.npmjs.org/@algolia/client-analytics/-/client-analytics-4.23.3.tgz", - "integrity": "sha512-LBsEARGS9cj8VkTAVEZphjxTjMVCci+zIIiRhpFun9jGDUlS1XmhCW7CTrnaWeIuCQS/2iPyRqSy1nXPjcBLRA==", - "license": "MIT", + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@algolia/client-analytics/-/client-analytics-4.24.0.tgz", + "integrity": "sha512-y8jOZt1OjwWU4N2qr8G4AxXAzaa8DBvyHTWlHzX/7Me1LX8OayfgHexqrsL4vSBcoMmVw2XnVW9MhL+Y2ZDJXg==", "dependencies": { - "@algolia/client-common": "4.23.3", - "@algolia/client-search": "4.23.3", - "@algolia/requester-common": "4.23.3", - "@algolia/transporter": "4.23.3" + "@algolia/client-common": "4.24.0", + "@algolia/client-search": "4.24.0", + "@algolia/requester-common": "4.24.0", + "@algolia/transporter": "4.24.0" } }, "node_modules/@algolia/client-common": { - "version": "4.23.3", - "resolved": "https://registry.npmjs.org/@algolia/client-common/-/client-common-4.23.3.tgz", - "integrity": "sha512-l6EiPxdAlg8CYhroqS5ybfIczsGUIAC47slLPOMDeKSVXYG1n0qGiz4RjAHLw2aD0xzh2EXZ7aRguPfz7UKDKw==", - "license": "MIT", + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@algolia/client-common/-/client-common-4.24.0.tgz", + "integrity": "sha512-bc2ROsNL6w6rqpl5jj/UywlIYC21TwSSoFHKl01lYirGMW+9Eek6r02Tocg4gZ8HAw3iBvu6XQiM3BEbmEMoiA==", "dependencies": { - "@algolia/requester-common": "4.23.3", - "@algolia/transporter": "4.23.3" + "@algolia/requester-common": "4.24.0", + "@algolia/transporter": "4.24.0" } }, "node_modules/@algolia/client-personalization": { - "version": "4.23.3", - "resolved": "https://registry.npmjs.org/@algolia/client-personalization/-/client-personalization-4.23.3.tgz", - "integrity": "sha512-3E3yF3Ocr1tB/xOZiuC3doHQBQ2zu2MPTYZ0d4lpfWads2WTKG7ZzmGnsHmm63RflvDeLK/UVx7j2b3QuwKQ2g==", - "license": "MIT", + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@algolia/client-personalization/-/client-personalization-4.24.0.tgz", + "integrity": "sha512-l5FRFm/yngztweU0HdUzz1rC4yoWCFo3IF+dVIVTfEPg906eZg5BOd1k0K6rZx5JzyyoP4LdmOikfkfGsKVE9w==", "dependencies": { - "@algolia/client-common": "4.23.3", - "@algolia/requester-common": "4.23.3", - "@algolia/transporter": "4.23.3" + "@algolia/client-common": "4.24.0", + "@algolia/requester-common": "4.24.0", + "@algolia/transporter": "4.24.0" } }, "node_modules/@algolia/client-search": { - "version": "4.23.3", - "resolved": "https://registry.npmjs.org/@algolia/client-search/-/client-search-4.23.3.tgz", - "integrity": "sha512-P4VAKFHqU0wx9O+q29Q8YVuaowaZ5EM77rxfmGnkHUJggh28useXQdopokgwMeYw2XUht49WX5RcTQ40rZIabw==", - "license": "MIT", + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@algolia/client-search/-/client-search-4.24.0.tgz", + "integrity": "sha512-uRW6EpNapmLAD0mW47OXqTP8eiIx5F6qN9/x/7HHO6owL3N1IXqydGwW5nhDFBrV+ldouro2W1VX3XlcUXEFCA==", "dependencies": { - "@algolia/client-common": "4.23.3", - "@algolia/requester-common": "4.23.3", - "@algolia/transporter": "4.23.3" + "@algolia/client-common": "4.24.0", + "@algolia/requester-common": "4.24.0", + "@algolia/transporter": "4.24.0" } }, "node_modules/@algolia/logger-common": { - "version": "4.23.3", - "resolved": "https://registry.npmjs.org/@algolia/logger-common/-/logger-common-4.23.3.tgz", - "integrity": "sha512-y9kBtmJwiZ9ZZ+1Ek66P0M68mHQzKRxkW5kAAXYN/rdzgDN0d2COsViEFufxJ0pb45K4FRcfC7+33YB4BLrZ+g==", - "license": "MIT" + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@algolia/logger-common/-/logger-common-4.24.0.tgz", + "integrity": "sha512-LLUNjkahj9KtKYrQhFKCzMx0BY3RnNP4FEtO+sBybCjJ73E8jNdaKJ/Dd8A/VA4imVHP5tADZ8pn5B8Ga/wTMA==" }, "node_modules/@algolia/logger-console": { - "version": "4.23.3", - "resolved": "https://registry.npmjs.org/@algolia/logger-console/-/logger-console-4.23.3.tgz", - "integrity": "sha512-8xoiseoWDKuCVnWP8jHthgaeobDLolh00KJAdMe9XPrWPuf1by732jSpgy2BlsLTaT9m32pHI8CRfrOqQzHv3A==", - "license": "MIT", + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@algolia/logger-console/-/logger-console-4.24.0.tgz", + "integrity": "sha512-X4C8IoHgHfiUROfoRCV+lzSy+LHMgkoEEU1BbKcsfnV0i0S20zyy0NLww9dwVHUWNfPPxdMU+/wKmLGYf96yTg==", "dependencies": { - "@algolia/logger-common": "4.23.3" + "@algolia/logger-common": "4.24.0" } }, "node_modules/@algolia/recommend": { - "version": "4.23.3", - "resolved": "https://registry.npmjs.org/@algolia/recommend/-/recommend-4.23.3.tgz", - "integrity": "sha512-9fK4nXZF0bFkdcLBRDexsnGzVmu4TSYZqxdpgBW2tEyfuSSY54D4qSRkLmNkrrz4YFvdh2GM1gA8vSsnZPR73w==", - "license": "MIT", - "dependencies": { - "@algolia/cache-browser-local-storage": "4.23.3", - "@algolia/cache-common": "4.23.3", - "@algolia/cache-in-memory": "4.23.3", - "@algolia/client-common": "4.23.3", - "@algolia/client-search": "4.23.3", - "@algolia/logger-common": "4.23.3", - "@algolia/logger-console": "4.23.3", - "@algolia/requester-browser-xhr": "4.23.3", - "@algolia/requester-common": "4.23.3", - "@algolia/requester-node-http": "4.23.3", - "@algolia/transporter": "4.23.3" + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@algolia/recommend/-/recommend-4.24.0.tgz", + "integrity": "sha512-P9kcgerfVBpfYHDfVZDvvdJv0lEoCvzNlOy2nykyt5bK8TyieYyiD0lguIJdRZZYGre03WIAFf14pgE+V+IBlw==", + "dependencies": { + "@algolia/cache-browser-local-storage": "4.24.0", + "@algolia/cache-common": "4.24.0", + "@algolia/cache-in-memory": "4.24.0", + "@algolia/client-common": "4.24.0", + "@algolia/client-search": "4.24.0", + "@algolia/logger-common": "4.24.0", + "@algolia/logger-console": "4.24.0", + "@algolia/requester-browser-xhr": "4.24.0", + "@algolia/requester-common": "4.24.0", + "@algolia/requester-node-http": "4.24.0", + "@algolia/transporter": "4.24.0" } }, "node_modules/@algolia/requester-browser-xhr": { - "version": "4.23.3", - "resolved": "https://registry.npmjs.org/@algolia/requester-browser-xhr/-/requester-browser-xhr-4.23.3.tgz", - "integrity": "sha512-jDWGIQ96BhXbmONAQsasIpTYWslyjkiGu0Quydjlowe+ciqySpiDUrJHERIRfELE5+wFc7hc1Q5hqjGoV7yghw==", - "license": "MIT", + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@algolia/requester-browser-xhr/-/requester-browser-xhr-4.24.0.tgz", + "integrity": "sha512-Z2NxZMb6+nVXSjF13YpjYTdvV3032YTBSGm2vnYvYPA6mMxzM3v5rsCiSspndn9rzIW4Qp1lPHBvuoKJV6jnAA==", "dependencies": { - "@algolia/requester-common": "4.23.3" + "@algolia/requester-common": "4.24.0" } }, "node_modules/@algolia/requester-common": { - "version": "4.23.3", - "resolved": "https://registry.npmjs.org/@algolia/requester-common/-/requester-common-4.23.3.tgz", - "integrity": "sha512-xloIdr/bedtYEGcXCiF2muajyvRhwop4cMZo+K2qzNht0CMzlRkm8YsDdj5IaBhshqfgmBb3rTg4sL4/PpvLYw==", - "license": "MIT" + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@algolia/requester-common/-/requester-common-4.24.0.tgz", + "integrity": "sha512-k3CXJ2OVnvgE3HMwcojpvY6d9kgKMPRxs/kVohrwF5WMr2fnqojnycZkxPoEg+bXm8fi5BBfFmOqgYztRtHsQA==" }, "node_modules/@algolia/requester-node-http": { - "version": "4.23.3", - "resolved": "https://registry.npmjs.org/@algolia/requester-node-http/-/requester-node-http-4.23.3.tgz", - "integrity": "sha512-zgu++8Uj03IWDEJM3fuNl34s746JnZOWn1Uz5taV1dFyJhVM/kTNw9Ik7YJWiUNHJQXcaD8IXD1eCb0nq/aByA==", - "license": "MIT", + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@algolia/requester-node-http/-/requester-node-http-4.24.0.tgz", + "integrity": "sha512-JF18yTjNOVYvU/L3UosRcvbPMGT9B+/GQWNWnenIImglzNVGpyzChkXLnrSf6uxwVNO6ESGu6oN8MqcGQcjQJw==", "dependencies": { - "@algolia/requester-common": "4.23.3" + "@algolia/requester-common": "4.24.0" } }, "node_modules/@algolia/transporter": { - "version": "4.23.3", - "resolved": "https://registry.npmjs.org/@algolia/transporter/-/transporter-4.23.3.tgz", - "integrity": "sha512-Wjl5gttqnf/gQKJA+dafnD0Y6Yw97yvfY8R9h0dQltX1GXTgNs1zWgvtWW0tHl1EgMdhAyw189uWiZMnL3QebQ==", - "license": "MIT", + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@algolia/transporter/-/transporter-4.24.0.tgz", + "integrity": "sha512-86nI7w6NzWxd1Zp9q3413dRshDqAzSbsQjhcDhPIatEFiZrL1/TjnHL8S7jVKFePlIMzDsZWXAXwXzcok9c5oA==", "dependencies": { - "@algolia/cache-common": "4.23.3", - "@algolia/logger-common": "4.23.3", - "@algolia/requester-common": "4.23.3" + "@algolia/cache-common": "4.24.0", + "@algolia/logger-common": "4.24.0", + "@algolia/requester-common": "4.24.0" } }, "node_modules/@babel/parser": { "version": "7.24.7", "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.24.7.tgz", "integrity": "sha512-9uUYRm6OqQrCqQdG1iCBwBPZgN8ciDBro2nIOFaiRz1/BCxaI7CNvQbDHvsArAC7Tw9Hda/B3U+6ui9u4HWXPw==", - "license": "MIT", "bin": { "parser": "bin/babel-parser.js" }, @@ -229,17 +214,27 @@ "node": ">=6.0.0" } }, + "node_modules/@cspotcode/source-map-support": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz", + "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==", + "dev": true, + "dependencies": { + "@jridgewell/trace-mapping": "0.3.9" + }, + "engines": { + "node": ">=12" + } + }, "node_modules/@docsearch/css": { "version": "3.6.0", "resolved": "https://registry.npmjs.org/@docsearch/css/-/css-3.6.0.tgz", - "integrity": "sha512-+sbxb71sWre+PwDK7X2T8+bhS6clcVMLwBPznX45Qu6opJcgRjAp7gYSDzVFp187J+feSj5dNBN1mJoi6ckkUQ==", - "license": "MIT" + "integrity": "sha512-+sbxb71sWre+PwDK7X2T8+bhS6clcVMLwBPznX45Qu6opJcgRjAp7gYSDzVFp187J+feSj5dNBN1mJoi6ckkUQ==" }, "node_modules/@docsearch/js": { "version": "3.6.0", "resolved": "https://registry.npmjs.org/@docsearch/js/-/js-3.6.0.tgz", "integrity": "sha512-QujhqINEElrkIfKwyyyTfbsfMAYCkylInLYMRqHy7PHc8xTBQCow73tlo/Kc7oIwBrCLf0P3YhjlOeV4v8hevQ==", - "license": "MIT", "dependencies": { "@docsearch/react": "3.6.0", "preact": "^10.0.0" @@ -249,7 +244,6 @@ "version": "3.6.0", "resolved": "https://registry.npmjs.org/@docsearch/react/-/react-3.6.0.tgz", "integrity": "sha512-HUFut4ztcVNmqy9gp/wxNbC7pTOHhgVVkHVGCACTuLhUKUhKAF9KYHJtMiLUJxEqiFLQiuri1fWF8zqwM/cu1w==", - "license": "MIT", "dependencies": { "@algolia/autocomplete-core": "1.9.3", "@algolia/autocomplete-preset-algolia": "1.9.3", @@ -284,7 +278,6 @@ "cpu": [ "ppc64" ], - "license": "MIT", "optional": true, "os": [ "aix" @@ -300,7 +293,6 @@ "cpu": [ "arm" ], - "license": "MIT", "optional": true, "os": [ "android" @@ -316,7 +308,6 @@ "cpu": [ "arm64" ], - "license": "MIT", "optional": true, "os": [ "android" @@ -332,7 +323,6 @@ "cpu": [ "x64" ], - "license": "MIT", "optional": true, "os": [ "android" @@ -348,7 +338,6 @@ "cpu": [ "arm64" ], - "license": "MIT", "optional": true, "os": [ "darwin" @@ -364,7 +353,6 @@ "cpu": [ "x64" ], - "license": "MIT", "optional": true, "os": [ "darwin" @@ -380,7 +368,6 @@ "cpu": [ "arm64" ], - "license": "MIT", "optional": true, "os": [ "freebsd" @@ -396,7 +383,6 @@ "cpu": [ "x64" ], - "license": "MIT", "optional": true, "os": [ "freebsd" @@ -412,7 +398,6 @@ "cpu": [ "arm" ], - "license": "MIT", "optional": true, "os": [ "linux" @@ -428,7 +413,6 @@ "cpu": [ "arm64" ], - "license": "MIT", "optional": true, "os": [ "linux" @@ -444,7 +428,6 @@ "cpu": [ "ia32" ], - "license": "MIT", "optional": true, "os": [ "linux" @@ -460,7 +443,6 @@ "cpu": [ "loong64" ], - "license": "MIT", "optional": true, "os": [ "linux" @@ -476,7 +458,6 @@ "cpu": [ "mips64el" ], - "license": "MIT", "optional": true, "os": [ "linux" @@ -492,7 +473,6 @@ "cpu": [ "ppc64" ], - "license": "MIT", "optional": true, "os": [ "linux" @@ -508,7 +488,6 @@ "cpu": [ "riscv64" ], - "license": "MIT", "optional": true, "os": [ "linux" @@ -524,7 +503,6 @@ "cpu": [ "s390x" ], - "license": "MIT", "optional": true, "os": [ "linux" @@ -540,7 +518,6 @@ "cpu": [ "x64" ], - "license": "MIT", "optional": true, "os": [ "linux" @@ -556,7 +533,6 @@ "cpu": [ "x64" ], - "license": "MIT", "optional": true, "os": [ "netbsd" @@ -572,7 +548,6 @@ "cpu": [ "x64" ], - "license": "MIT", "optional": true, "os": [ "openbsd" @@ -588,7 +563,6 @@ "cpu": [ "x64" ], - "license": "MIT", "optional": true, "os": [ "sunos" @@ -604,7 +578,6 @@ "cpu": [ "arm64" ], - "license": "MIT", "optional": true, "os": [ "win32" @@ -620,7 +593,6 @@ "cpu": [ "ia32" ], - "license": "MIT", "optional": true, "os": [ "win32" @@ -636,7 +608,6 @@ "cpu": [ "x64" ], - "license": "MIT", "optional": true, "os": [ "win32" @@ -645,11 +616,56 @@ "node": ">=12" } }, + "node_modules/@isaacs/cliui": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", + "integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==", + "dev": true, + "dependencies": { + "string-width": "^5.1.2", + "string-width-cjs": "npm:string-width@^4.2.0", + "strip-ansi": "^7.0.1", + "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", + "wrap-ansi": "^8.1.0", + "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "engines": { + "node": ">=6.0.0" + } + }, "node_modules/@jridgewell/sourcemap-codec": { "version": "1.4.15", "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz", - "integrity": "sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==", - "license": "MIT" + "integrity": "sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz", + "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==", + "dev": true, + "dependencies": { + "@jridgewell/resolve-uri": "^3.0.3", + "@jridgewell/sourcemap-codec": "^1.4.10" + } + }, + "node_modules/@pkgjs/parseargs": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz", + "integrity": "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==", + "dev": true, + "optional": true, + "engines": { + "node": ">=14" + } }, "node_modules/@rollup/rollup-android-arm-eabi": { "version": "4.18.0", @@ -658,7 +674,6 @@ "cpu": [ "arm" ], - "license": "MIT", "optional": true, "os": [ "android" @@ -671,7 +686,6 @@ "cpu": [ "arm64" ], - "license": "MIT", "optional": true, "os": [ "android" @@ -684,7 +698,6 @@ "cpu": [ "arm64" ], - "license": "MIT", "optional": true, "os": [ "darwin" @@ -697,7 +710,6 @@ "cpu": [ "x64" ], - "license": "MIT", "optional": true, "os": [ "darwin" @@ -710,7 +722,6 @@ "cpu": [ "arm" ], - "license": "MIT", "optional": true, "os": [ "linux" @@ -723,7 +734,6 @@ "cpu": [ "arm" ], - "license": "MIT", "optional": true, "os": [ "linux" @@ -736,7 +746,6 @@ "cpu": [ "arm64" ], - "license": "MIT", "optional": true, "os": [ "linux" @@ -749,7 +758,6 @@ "cpu": [ "arm64" ], - "license": "MIT", "optional": true, "os": [ "linux" @@ -762,7 +770,6 @@ "cpu": [ "ppc64" ], - "license": "MIT", "optional": true, "os": [ "linux" @@ -775,7 +782,6 @@ "cpu": [ "riscv64" ], - "license": "MIT", "optional": true, "os": [ "linux" @@ -788,7 +794,6 @@ "cpu": [ "s390x" ], - "license": "MIT", "optional": true, "os": [ "linux" @@ -801,7 +806,6 @@ "cpu": [ "x64" ], - "license": "MIT", "optional": true, "os": [ "linux" @@ -814,7 +818,6 @@ "cpu": [ "x64" ], - "license": "MIT", "optional": true, "os": [ "linux" @@ -827,7 +830,6 @@ "cpu": [ "arm64" ], - "license": "MIT", "optional": true, "os": [ "win32" @@ -840,7 +842,6 @@ "cpu": [ "ia32" ], - "license": "MIT", "optional": true, "os": [ "win32" @@ -853,50 +854,77 @@ "cpu": [ "x64" ], - "license": "MIT", "optional": true, "os": [ "win32" ] }, "node_modules/@shikijs/core": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/@shikijs/core/-/core-1.7.0.tgz", - "integrity": "sha512-O6j27b7dGmJbR3mjwh/aHH8Ld+GQvA0OQsNO43wKWnqbAae3AYXrhFyScHGX8hXZD6vX2ngjzDFkZY5srtIJbQ==", - "license": "MIT" + "version": "1.10.1", + "resolved": "https://registry.npmjs.org/@shikijs/core/-/core-1.10.1.tgz", + "integrity": "sha512-qdiJS5a/QGCff7VUFIqd0hDdWly9rDp8lhVmXVrS11aazX8LOTRLHAXkkEeONNsS43EcCd7gax9LLoOz4vlFQA==" }, "node_modules/@shikijs/transformers": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/@shikijs/transformers/-/transformers-1.7.0.tgz", - "integrity": "sha512-QX3TP+CS4yYLt4X4Dk7wT0MsC7yweTYHMAAKY+ay+uuR9yRdFae/h+hivny2O+YixJHfZl57xtiZfWSrHdyVhQ==", - "license": "MIT", + "version": "1.10.1", + "resolved": "https://registry.npmjs.org/@shikijs/transformers/-/transformers-1.10.1.tgz", + "integrity": "sha512-0gLtcFyi6R6zcUkFajUEp1Qiv7lHBSFgOz4tQvS8nFsYCQSLI1/9pM+Me8jEIPXv7XLKAoUjw6InL+Sv+BHw/A==", "dependencies": { - "shiki": "1.7.0" + "shiki": "1.10.1" } }, + "node_modules/@tsconfig/node10": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.11.tgz", + "integrity": "sha512-DcRjDCujK/kCk/cUe8Xz8ZSpm8mS3mNNpta+jGCA6USEDfktlNvm1+IuZ9eTcDbNk41BHwpHHeW+N1lKCz4zOw==", + "dev": true + }, + "node_modules/@tsconfig/node12": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/@tsconfig/node12/-/node12-1.0.11.tgz", + "integrity": "sha512-cqefuRsh12pWyGsIoBKJA9luFu3mRxCA+ORZvA4ktLSzIuCUtWVxGIuXigEwO5/ywWFMZ2QEGKWvkZG1zDMTag==", + "dev": true + }, + "node_modules/@tsconfig/node14": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@tsconfig/node14/-/node14-1.0.3.tgz", + "integrity": "sha512-ysT8mhdixWK6Hw3i1V2AeRqZ5WfXg1G43mqoYlM2nc6388Fq5jcXyr5mRsqViLx/GJYdoL0bfXD8nmF+Zn/Iow==", + "dev": true + }, + "node_modules/@tsconfig/node16": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@tsconfig/node16/-/node16-1.0.4.tgz", + "integrity": "sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA==", + "dev": true + }, "node_modules/@types/estree": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.5.tgz", - "integrity": "sha512-/kYRxGDLWzHOB7q+wtSUQlFrtcdUccpfy+X+9iMBpHK8QLLhx2wIPYuS5DYtR9Wa/YlZAbIovy7qVdB1Aq6Lyw==", - "license": "MIT" + "integrity": "sha512-/kYRxGDLWzHOB7q+wtSUQlFrtcdUccpfy+X+9iMBpHK8QLLhx2wIPYuS5DYtR9Wa/YlZAbIovy7qVdB1Aq6Lyw==" + }, + "node_modules/@types/glob": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/@types/glob/-/glob-8.1.0.tgz", + "integrity": "sha512-IO+MJPVhoqz+28h1qLAcBEH2+xHMK6MTyHJc7MTnnYb6wsoLR29POVGJ7LycmVXIqyy/4/2ShP5sUwTXuOwb/w==", + "dev": true, + "dependencies": { + "@types/minimatch": "^5.1.2", + "@types/node": "*" + } }, "node_modules/@types/linkify-it": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/@types/linkify-it/-/linkify-it-5.0.0.tgz", - "integrity": "sha512-sVDA58zAw4eWAffKOaQH5/5j3XeayukzDk+ewSsnv3p4yJEZHCCzMDiZM8e0OUrRvmpGZ85jf4yDHkHsgBNr9Q==", - "license": "MIT" + "integrity": "sha512-sVDA58zAw4eWAffKOaQH5/5j3XeayukzDk+ewSsnv3p4yJEZHCCzMDiZM8e0OUrRvmpGZ85jf4yDHkHsgBNr9Q==" }, "node_modules/@types/lodash": { - "version": "4.17.5", - "resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.17.5.tgz", - "integrity": "sha512-MBIOHVZqVqgfro1euRDWX7OO0fBVUUMrN6Pwm8LQsz8cWhEpihlvR70ENj3f40j58TNxZaWv2ndSkInykNBBJw==", - "license": "MIT" + "version": "4.17.6", + "resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.17.6.tgz", + "integrity": "sha512-OpXEVoCKSS3lQqjx9GGGOapBeuW5eUboYHRlHP9urXPX25IKZ6AnP5ZRxtVf63iieUbsHxLn8NQ5Nlftc6yzAA==" }, "node_modules/@types/markdown-it": { "version": "14.1.1", "resolved": "https://registry.npmjs.org/@types/markdown-it/-/markdown-it-14.1.1.tgz", "integrity": "sha512-4NpsnpYl2Gt1ljyBGrKMxFYAYvpqbnnkgP/i/g+NLpjEUa3obn1XJCur9YbEXKDAkaXqsR1LbDnGEJ0MmKFxfg==", - "license": "MIT", "dependencies": { "@types/linkify-it": "^5", "@types/mdurl": "^2" @@ -905,30 +933,42 @@ "node_modules/@types/mdurl": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/@types/mdurl/-/mdurl-2.0.0.tgz", - "integrity": "sha512-RGdgjQUZba5p6QEFAVx2OGb8rQDL/cPRG7GiedRzMcJ1tYnUANBncjbSB1NRGwbvjcPeikRABz2nshyPk1bhWg==", - "license": "MIT" + "integrity": "sha512-RGdgjQUZba5p6QEFAVx2OGb8rQDL/cPRG7GiedRzMcJ1tYnUANBncjbSB1NRGwbvjcPeikRABz2nshyPk1bhWg==" + }, + "node_modules/@types/minimatch": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/@types/minimatch/-/minimatch-5.1.2.tgz", + "integrity": "sha512-K0VQKziLUWkVKiRVrx4a40iPaxTUefQmjtkQofBkYRcoaaL/8rhwDWww9qWbrgicNOgnpIsMxyNIUM4+n6dUIA==", + "dev": true }, "node_modules/@types/node": { - "version": "20.14.6", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.14.6.tgz", - "integrity": "sha512-JbA0XIJPL1IiNnU7PFxDXyfAwcwVVrOoqyzzyQTyMeVhBzkJVMSkC1LlVsRQ2lpqiY4n6Bb9oCS6lzDKVQxbZw==", + "version": "20.14.9", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.14.9.tgz", + "integrity": "sha512-06OCtnTXtWOZBJlRApleWndH4JsRVs1pDCc8dLSQp+7PpUpX3ePdHyeNSFTeSe7FtKyQkrlPvHwJOW3SLd8Oyg==", "devOptional": true, - "license": "MIT", "dependencies": { "undici-types": "~5.26.4" } }, + "node_modules/@types/prompts": { + "version": "2.4.9", + "resolved": "https://registry.npmjs.org/@types/prompts/-/prompts-2.4.9.tgz", + "integrity": "sha512-qTxFi6Buiu8+50/+3DGIWLHM6QuWsEKugJnnP6iv2Mc4ncxE4A/OJkjuVOA+5X0X1S/nq5VJRa8Lu+nwcvbrKA==", + "dev": true, + "dependencies": { + "@types/node": "*", + "kleur": "^3.0.3" + } + }, "node_modules/@types/web-bluetooth": { "version": "0.0.20", "resolved": "https://registry.npmjs.org/@types/web-bluetooth/-/web-bluetooth-0.0.20.tgz", - "integrity": "sha512-g9gZnnXVq7gM7v3tJCWV/qw7w+KeOlSHAhgF9RytFyifW6AF61hdT2ucrYhPq9hLs5JIryeupHV3qGk95dH9ow==", - "license": "MIT" + "integrity": "sha512-g9gZnnXVq7gM7v3tJCWV/qw7w+KeOlSHAhgF9RytFyifW6AF61hdT2ucrYhPq9hLs5JIryeupHV3qGk95dH9ow==" }, "node_modules/@vitejs/plugin-vue": { "version": "5.0.5", "resolved": "https://registry.npmjs.org/@vitejs/plugin-vue/-/plugin-vue-5.0.5.tgz", "integrity": "sha512-LOjm7XeIimLBZyzinBQ6OSm3UBCNVCpLkxGC0oWmm2YPzVZoxMsdvNVimLTBzpAnR9hl/yn1SHGuRfe6/Td9rQ==", - "license": "MIT", "engines": { "node": "^18.0.0 || >=20.0.0" }, @@ -938,13 +978,12 @@ } }, "node_modules/@vue/compiler-core": { - "version": "3.4.29", - "resolved": "https://registry.npmjs.org/@vue/compiler-core/-/compiler-core-3.4.29.tgz", - "integrity": "sha512-TFKiRkKKsRCKvg/jTSSKK7mYLJEQdUiUfykbG49rubC9SfDyvT2JrzTReopWlz2MxqeLyxh9UZhvxEIBgAhtrg==", - "license": "MIT", + "version": "3.4.31", + "resolved": "https://registry.npmjs.org/@vue/compiler-core/-/compiler-core-3.4.31.tgz", + "integrity": "sha512-skOiodXWTV3DxfDhB4rOf3OGalpITLlgCeOwb+Y9GJpfQ8ErigdBUHomBzvG78JoVE8MJoQsb+qhZiHfKeNeEg==", "dependencies": { "@babel/parser": "^7.24.7", - "@vue/shared": "3.4.29", + "@vue/shared": "3.4.31", "entities": "^4.5.0", "estree-walker": "^2.0.2", "source-map-js": "^1.2.0" @@ -954,7 +993,6 @@ "version": "4.5.0", "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==", - "license": "BSD-2-Clause", "engines": { "node": ">=0.12" }, @@ -963,26 +1001,24 @@ } }, "node_modules/@vue/compiler-dom": { - "version": "3.4.29", - "resolved": "https://registry.npmjs.org/@vue/compiler-dom/-/compiler-dom-3.4.29.tgz", - "integrity": "sha512-A6+iZ2fKIEGnfPJejdB7b1FlJzgiD+Y/sxxKwJWg1EbJu6ZPgzaPQQ51ESGNv0CP6jm6Z7/pO6Ia8Ze6IKrX7w==", - "license": "MIT", + "version": "3.4.31", + "resolved": "https://registry.npmjs.org/@vue/compiler-dom/-/compiler-dom-3.4.31.tgz", + "integrity": "sha512-wK424WMXsG1IGMyDGyLqB+TbmEBFM78hIsOJ9QwUVLGrcSk0ak6zYty7Pj8ftm7nEtdU/DGQxAXp0/lM/2cEpQ==", "dependencies": { - "@vue/compiler-core": "3.4.29", - "@vue/shared": "3.4.29" + "@vue/compiler-core": "3.4.31", + "@vue/shared": "3.4.31" } }, "node_modules/@vue/compiler-sfc": { - "version": "3.4.29", - "resolved": "https://registry.npmjs.org/@vue/compiler-sfc/-/compiler-sfc-3.4.29.tgz", - "integrity": "sha512-zygDcEtn8ZimDlrEQyLUovoWgKQic6aEQqRXce2WXBvSeHbEbcAsXyCk9oG33ZkyWH4sl9D3tkYc1idoOkdqZQ==", - "license": "MIT", + "version": "3.4.31", + "resolved": "https://registry.npmjs.org/@vue/compiler-sfc/-/compiler-sfc-3.4.31.tgz", + "integrity": "sha512-einJxqEw8IIJxzmnxmJBuK2usI+lJonl53foq+9etB2HAzlPjAS/wa7r0uUpXw5ByX3/0uswVSrjNb17vJm1kQ==", "dependencies": { "@babel/parser": "^7.24.7", - "@vue/compiler-core": "3.4.29", - "@vue/compiler-dom": "3.4.29", - "@vue/compiler-ssr": "3.4.29", - "@vue/shared": "3.4.29", + "@vue/compiler-core": "3.4.31", + "@vue/compiler-dom": "3.4.31", + "@vue/compiler-ssr": "3.4.31", + "@vue/shared": "3.4.31", "estree-walker": "^2.0.2", "magic-string": "^0.30.10", "postcss": "^8.4.38", @@ -990,106 +1026,93 @@ } }, "node_modules/@vue/compiler-ssr": { - "version": "3.4.29", - "resolved": "https://registry.npmjs.org/@vue/compiler-ssr/-/compiler-ssr-3.4.29.tgz", - "integrity": "sha512-rFbwCmxJ16tDp3N8XCx5xSQzjhidYjXllvEcqX/lopkoznlNPz3jyy0WGJCyhAaVQK677WWFt3YO/WUEkMMUFQ==", - "license": "MIT", + "version": "3.4.31", + "resolved": "https://registry.npmjs.org/@vue/compiler-ssr/-/compiler-ssr-3.4.31.tgz", + "integrity": "sha512-RtefmITAje3fJ8FSg1gwgDhdKhZVntIVbwupdyZDSifZTRMiWxWehAOTCc8/KZDnBOcYQ4/9VWxsTbd3wT0hAA==", "dependencies": { - "@vue/compiler-dom": "3.4.29", - "@vue/shared": "3.4.29" + "@vue/compiler-dom": "3.4.31", + "@vue/shared": "3.4.31" } }, "node_modules/@vue/devtools-api": { - "version": "7.3.0", - "resolved": "https://registry.npmjs.org/@vue/devtools-api/-/devtools-api-7.3.0.tgz", - "integrity": "sha512-EQ6DIm9AuL9q6IzjjnxeHWgzHzZTI+0ZGyLyG6faLN1e0tzLWPut58OtvFbLP/hbEhE5zPlsdUsH1uFr7RVFYw==", - "license": "MIT", + "version": "7.3.5", + "resolved": "https://registry.npmjs.org/@vue/devtools-api/-/devtools-api-7.3.5.tgz", + "integrity": "sha512-BSdBBu5hOIv+gBJC9jzYMh5bC27FQwjWLSb8fVAniqlL9gvsqvK27xTgczMf+hgctlszMYQnRm3bpY/j8vhPqw==", "dependencies": { - "@vue/devtools-kit": "^7.3.0" + "@vue/devtools-kit": "^7.3.5" } }, "node_modules/@vue/devtools-kit": { - "version": "7.3.0", - "resolved": "https://registry.npmjs.org/@vue/devtools-kit/-/devtools-kit-7.3.0.tgz", - "integrity": "sha512-J9C+ue3Ka8cumQY/hMsNTcbb1tczqVBBXFMw4isa5YvPjyIBgEtJBfDSUVIK3nE+YWk7UNliUuCcE1GHEKaGcw==", - "license": "MIT", + "version": "7.3.5", + "resolved": "https://registry.npmjs.org/@vue/devtools-kit/-/devtools-kit-7.3.5.tgz", + "integrity": "sha512-wwfi10gJ1HMtjzcd8aIOnzBHlIRqsYDgcDyrKvkeyc0Gbcoe7UrkXRVHZUOtcxxoplHA0PwpT6wFg0uUCmi8Ww==", "dependencies": { - "@vue/devtools-shared": "^7.3.0", + "@vue/devtools-shared": "^7.3.5", "birpc": "^0.2.17", "hookable": "^5.5.3", "mitt": "^3.0.1", "perfect-debounce": "^1.0.0", "speakingurl": "^14.0.1", "superjson": "^2.2.1" - }, - "peerDependencies": { - "vue": "^3.0.0" } }, "node_modules/@vue/devtools-shared": { - "version": "7.3.0", - "resolved": "https://registry.npmjs.org/@vue/devtools-shared/-/devtools-shared-7.3.0.tgz", - "integrity": "sha512-bYw4BtZclxzVrYBeYYHzNOcLlvVZbe9tutwtrixTtdgynHvuSJa5KI2MqWiumpGYm2feFI5sHlC8Vt61v4z18g==", - "license": "MIT", + "version": "7.3.5", + "resolved": "https://registry.npmjs.org/@vue/devtools-shared/-/devtools-shared-7.3.5.tgz", + "integrity": "sha512-Rqii3VazmWTi67a86rYopi61n5Ved05EybJCwyrfoO9Ok3MaS/4yRFl706ouoISMlyrASJFEzM0/AiDA6w4f9A==", "dependencies": { - "rfdc": "^1.3.1" + "rfdc": "^1.4.1" } }, "node_modules/@vue/reactivity": { - "version": "3.4.29", - "resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.4.29.tgz", - "integrity": "sha512-w8+KV+mb1a8ornnGQitnMdLfE0kXmteaxLdccm2XwdFxXst4q/Z7SEboCV5SqJNpZbKFeaRBBJBhW24aJyGINg==", - "license": "MIT", + "version": "3.4.31", + "resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.4.31.tgz", + "integrity": "sha512-VGkTani8SOoVkZNds1PfJ/T1SlAIOf8E58PGAhIOUDYPC4GAmFA2u/E14TDAFcf3vVDKunc4QqCe/SHr8xC65Q==", "dependencies": { - "@vue/shared": "3.4.29" + "@vue/shared": "3.4.31" } }, "node_modules/@vue/runtime-core": { - "version": "3.4.29", - "resolved": "https://registry.npmjs.org/@vue/runtime-core/-/runtime-core-3.4.29.tgz", - "integrity": "sha512-s8fmX3YVR/Rk5ig0ic0NuzTNjK2M7iLuVSZyMmCzN/+Mjuqqif1JasCtEtmtoJWF32pAtUjyuT2ljNKNLeOmnQ==", - "license": "MIT", + "version": "3.4.31", + "resolved": "https://registry.npmjs.org/@vue/runtime-core/-/runtime-core-3.4.31.tgz", + "integrity": "sha512-LDkztxeUPazxG/p8c5JDDKPfkCDBkkiNLVNf7XZIUnJ+66GVGkP+TIh34+8LtPisZ+HMWl2zqhIw0xN5MwU1cw==", "dependencies": { - "@vue/reactivity": "3.4.29", - "@vue/shared": "3.4.29" + "@vue/reactivity": "3.4.31", + "@vue/shared": "3.4.31" } }, "node_modules/@vue/runtime-dom": { - "version": "3.4.29", - "resolved": "https://registry.npmjs.org/@vue/runtime-dom/-/runtime-dom-3.4.29.tgz", - "integrity": "sha512-gI10atCrtOLf/2MPPMM+dpz3NGulo9ZZR9d1dWo4fYvm+xkfvRrw1ZmJ7mkWtiJVXSsdmPbcK1p5dZzOCKDN0g==", - "license": "MIT", - "dependencies": { - "@vue/reactivity": "3.4.29", - "@vue/runtime-core": "3.4.29", - "@vue/shared": "3.4.29", + "version": "3.4.31", + "resolved": "https://registry.npmjs.org/@vue/runtime-dom/-/runtime-dom-3.4.31.tgz", + "integrity": "sha512-2Auws3mB7+lHhTFCg8E9ZWopA6Q6L455EcU7bzcQ4x6Dn4cCPuqj6S2oBZgN2a8vJRS/LSYYxwFFq2Hlx3Fsaw==", + "dependencies": { + "@vue/reactivity": "3.4.31", + "@vue/runtime-core": "3.4.31", + "@vue/shared": "3.4.31", "csstype": "^3.1.3" } }, "node_modules/@vue/server-renderer": { - "version": "3.4.29", - "resolved": "https://registry.npmjs.org/@vue/server-renderer/-/server-renderer-3.4.29.tgz", - "integrity": "sha512-HMLCmPI2j/k8PVkSBysrA2RxcxC5DgBiCdj7n7H2QtR8bQQPqKAe8qoaxLcInzouBmzwJ+J0x20ygN/B5mYBng==", - "license": "MIT", + "version": "3.4.31", + "resolved": "https://registry.npmjs.org/@vue/server-renderer/-/server-renderer-3.4.31.tgz", + "integrity": "sha512-D5BLbdvrlR9PE3by9GaUp1gQXlCNadIZytMIb8H2h3FMWJd4oUfkUTEH2wAr3qxoRz25uxbTcbqd3WKlm9EHQA==", "dependencies": { - "@vue/compiler-ssr": "3.4.29", - "@vue/shared": "3.4.29" + "@vue/compiler-ssr": "3.4.31", + "@vue/shared": "3.4.31" }, "peerDependencies": { - "vue": "3.4.29" + "vue": "3.4.31" } }, "node_modules/@vue/shared": { - "version": "3.4.29", - "resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.4.29.tgz", - "integrity": "sha512-hQ2gAQcBO/CDpC82DCrinJNgOHI2v+FA7BDW4lMSPeBpQ7sRe2OLHWe5cph1s7D8DUQAwRt18dBDfJJ220APEA==", - "license": "MIT" + "version": "3.4.31", + "resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.4.31.tgz", + "integrity": "sha512-Yp3wtJk//8cO4NItOPpi3QkLExAr/aLBGZMmTtW9WpdwBCJpRM6zj9WgWktXAl8IDIozwNMByT45JP3tO3ACWA==" }, "node_modules/@vueuse/core": { "version": "10.11.0", "resolved": "https://registry.npmjs.org/@vueuse/core/-/core-10.11.0.tgz", "integrity": "sha512-x3sD4Mkm7PJ+pcq3HX8PLPBadXCAlSDR/waK87dz0gQE+qJnaaFhc/dZVfJz+IUYzTMVGum2QlR7ImiJQN4s6g==", - "license": "MIT", "dependencies": { "@types/web-bluetooth": "^0.0.20", "@vueuse/metadata": "10.11.0", @@ -1105,7 +1128,6 @@ "resolved": "https://registry.npmjs.org/vue-demi/-/vue-demi-0.14.8.tgz", "integrity": "sha512-Uuqnk9YE9SsWeReYqK2alDI5YzciATE0r2SkA6iMAtuXvNTMNACJLJEXNXaEy94ECuBe4Sk6RzRU80kjdbIo1Q==", "hasInstallScript": true, - "license": "MIT", "bin": { "vue-demi-fix": "bin/vue-demi-fix.js", "vue-demi-switch": "bin/vue-demi-switch.js" @@ -1130,7 +1152,6 @@ "version": "10.11.0", "resolved": "https://registry.npmjs.org/@vueuse/integrations/-/integrations-10.11.0.tgz", "integrity": "sha512-Pp6MtWEIr+NDOccWd8j59Kpjy5YDXogXI61Kb1JxvSfVBO8NzFQkmrKmSZz47i+ZqHnIzxaT38L358yDHTncZg==", - "license": "MIT", "dependencies": { "@vueuse/core": "10.11.0", "@vueuse/shared": "10.11.0", @@ -1197,7 +1218,6 @@ "resolved": "https://registry.npmjs.org/vue-demi/-/vue-demi-0.14.8.tgz", "integrity": "sha512-Uuqnk9YE9SsWeReYqK2alDI5YzciATE0r2SkA6iMAtuXvNTMNACJLJEXNXaEy94ECuBe4Sk6RzRU80kjdbIo1Q==", "hasInstallScript": true, - "license": "MIT", "bin": { "vue-demi-fix": "bin/vue-demi-fix.js", "vue-demi-switch": "bin/vue-demi-switch.js" @@ -1222,7 +1242,6 @@ "version": "10.11.0", "resolved": "https://registry.npmjs.org/@vueuse/metadata/-/metadata-10.11.0.tgz", "integrity": "sha512-kQX7l6l8dVWNqlqyN3ePW3KmjCQO3ZMgXuBMddIu83CmucrsBfXlH+JoviYyRBws/yLTQO8g3Pbw+bdIoVm4oQ==", - "license": "MIT", "funding": { "url": "https://github.com/sponsors/antfu" } @@ -1231,7 +1250,6 @@ "version": "10.11.0", "resolved": "https://registry.npmjs.org/@vueuse/shared/-/shared-10.11.0.tgz", "integrity": "sha512-fyNoIXEq3PfX1L3NkNhtVQUSRtqYwJtJg+Bp9rIzculIZWHTkKSysujrOk2J+NrRulLTQH9+3gGSfYLWSEWU1A==", - "license": "MIT", "dependencies": { "vue-demi": ">=0.14.8" }, @@ -1244,7 +1262,6 @@ "resolved": "https://registry.npmjs.org/vue-demi/-/vue-demi-0.14.8.tgz", "integrity": "sha512-Uuqnk9YE9SsWeReYqK2alDI5YzciATE0r2SkA6iMAtuXvNTMNACJLJEXNXaEy94ECuBe4Sk6RzRU80kjdbIo1Q==", "hasInstallScript": true, - "license": "MIT", "bin": { "vue-demi-fix": "bin/vue-demi-fix.js", "vue-demi-switch": "bin/vue-demi-switch.js" @@ -1276,38 +1293,72 @@ "node": ">=0.4.0" } }, + "node_modules/acorn-walk": { + "version": "8.3.3", + "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.3.tgz", + "integrity": "sha512-MxXdReSRhGO7VlFe1bRG/oI7/mdLV9B9JJT0N8vZOhF7gFRR5l3M8W9G8JxmKV+JC5mGqJ0QvqfSOLsCPa4nUw==", + "dev": true, + "dependencies": { + "acorn": "^8.11.0" + }, + "engines": { + "node": ">=0.4.0" + } + }, "node_modules/algoliasearch": { - "version": "4.23.3", - "resolved": "https://registry.npmjs.org/algoliasearch/-/algoliasearch-4.23.3.tgz", - "integrity": "sha512-Le/3YgNvjW9zxIQMRhUHuhiUjAlKY/zsdZpfq4dlLqg6mEm0nL6yk+7f2hDOtLpxsgE4jSzDmvHL7nXdBp5feg==", - "license": "MIT", - "dependencies": { - "@algolia/cache-browser-local-storage": "4.23.3", - "@algolia/cache-common": "4.23.3", - "@algolia/cache-in-memory": "4.23.3", - "@algolia/client-account": "4.23.3", - "@algolia/client-analytics": "4.23.3", - "@algolia/client-common": "4.23.3", - "@algolia/client-personalization": "4.23.3", - "@algolia/client-search": "4.23.3", - "@algolia/logger-common": "4.23.3", - "@algolia/logger-console": "4.23.3", - "@algolia/recommend": "4.23.3", - "@algolia/requester-browser-xhr": "4.23.3", - "@algolia/requester-common": "4.23.3", - "@algolia/requester-node-http": "4.23.3", - "@algolia/transporter": "4.23.3" + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/algoliasearch/-/algoliasearch-4.24.0.tgz", + "integrity": "sha512-bf0QV/9jVejssFBmz2HQLxUadxk574t4iwjCKp5E7NBzwKkrDEhKPISIIjAU/p6K5qDx3qoeh4+26zWN1jmw3g==", + "dependencies": { + "@algolia/cache-browser-local-storage": "4.24.0", + "@algolia/cache-common": "4.24.0", + "@algolia/cache-in-memory": "4.24.0", + "@algolia/client-account": "4.24.0", + "@algolia/client-analytics": "4.24.0", + "@algolia/client-common": "4.24.0", + "@algolia/client-personalization": "4.24.0", + "@algolia/client-search": "4.24.0", + "@algolia/logger-common": "4.24.0", + "@algolia/logger-console": "4.24.0", + "@algolia/recommend": "4.24.0", + "@algolia/requester-browser-xhr": "4.24.0", + "@algolia/requester-common": "4.24.0", + "@algolia/requester-node-http": "4.24.0", + "@algolia/transporter": "4.24.0" } }, "node_modules/ansi-colors": { "version": "4.1.3", "resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-4.1.3.tgz", "integrity": "sha512-/6w/C21Pm1A7aZitlI5Ni/2J6FFQN8i1Cvz3kHABAAbw93v/NlvKdVOqz7CCWz/3iv/JplRSEEZ83XION15ovw==", - "license": "MIT", "engines": { "node": ">=6" } }, + "node_modules/ansi-regex": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.0.1.tgz", + "integrity": "sha512-n5M855fKb2SsfMIiFFoVrABHJC8QtHwVx+mHWP3QcEqBHYienj5dHSgjbxtC0WEZXYt4wcD6zrQElDPhFuZgfA==", + "dev": true, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/ansi-styles": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.1.tgz", + "integrity": "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==", + "dev": true, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, "node_modules/anymatch": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", @@ -1320,12 +1371,23 @@ "node": ">= 8" } }, + "node_modules/arg": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz", + "integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==", + "dev": true + }, "node_modules/argparse": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", - "dev": true, - "license": "Python-2.0" + "dev": true + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true }, "node_modules/binary-extensions": { "version": "2.3.0", @@ -1342,7 +1404,6 @@ "version": "0.2.17", "resolved": "https://registry.npmjs.org/birpc/-/birpc-0.2.17.tgz", "integrity": "sha512-+hkTxhot+dWsLpp3gia5AkVHIsKlZybNT5gIYiDlNzJrmYPcTM9k5/w2uaj3IPpd7LlEYpmCj4Jj1nC41VhDFg==", - "license": "MIT", "funding": { "url": "https://github.com/sponsors/antfu" } @@ -1350,8 +1411,16 @@ "node_modules/boolbase": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz", - "integrity": "sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==", - "license": "ISC" + "integrity": "sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==" + }, + "node_modules/brace-expansion": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", + "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", + "dev": true, + "dependencies": { + "balanced-match": "^1.0.0" + } }, "node_modules/braces": { "version": "3.0.3", @@ -1368,7 +1437,6 @@ "version": "1.0.0-rc.10", "resolved": "https://registry.npmjs.org/cheerio/-/cheerio-1.0.0-rc.10.tgz", "integrity": "sha512-g0J0q/O6mW8z5zxQ3A8E8J1hUgp4SMOvEoW/x84OwyHKe/Zccz83PVT4y5Crcr530FV6NgmKI1qvGTKVl9XXVw==", - "license": "MIT", "dependencies": { "cheerio-select": "^1.5.0", "dom-serializer": "^1.3.2", @@ -1389,7 +1457,6 @@ "version": "1.6.0", "resolved": "https://registry.npmjs.org/cheerio-select/-/cheerio-select-1.6.0.tgz", "integrity": "sha512-eq0GdBvxVFbqWgmCm7M3XGs1I8oLy/nExUnh6oLqmBditPO9AqQJrkslDpMun/hZ0yyTs8L0m85OHp4ho6Qm9g==", - "license": "BSD-2-Clause", "dependencies": { "css-select": "^4.3.0", "css-what": "^6.0.1", @@ -1428,7 +1495,6 @@ "version": "2.0.4", "resolved": "https://registry.npmjs.org/cli-color/-/cli-color-2.0.4.tgz", "integrity": "sha512-zlnpg0jNcibNrO7GG9IeHH7maWFeCz+Ja1wx/7tZNU5ASSSSZ+/qZciM0/LHCYxSdqv5h2sdbQ/PXYdOuetXvA==", - "license": "ISC", "dependencies": { "d": "^1.0.1", "es5-ext": "^0.10.64", @@ -1440,11 +1506,28 @@ "node": ">=0.10" } }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, "node_modules/commander": { "version": "6.2.1", "resolved": "https://registry.npmjs.org/commander/-/commander-6.2.1.tgz", "integrity": "sha512-U7VdrJFnJgo4xjrHpTzu0yrHPGImdsmD95ZlgYSEajAn2JKzDhDTPG9kBTefmObL2w/ngeZnilk+OV9CG3d7UA==", - "license": "MIT", "engines": { "node": ">= 6" } @@ -1453,7 +1536,6 @@ "version": "3.0.5", "resolved": "https://registry.npmjs.org/copy-anything/-/copy-anything-3.0.5.tgz", "integrity": "sha512-yCEafptTtb4bk7GLEQoM8KVJpxAfdBJYaXyzQEgQQQgYrZiDp8SJmGKlYza6CYjEDNstAdNdKA3UuoULlEbS6w==", - "license": "MIT", "dependencies": { "is-what": "^4.1.8" }, @@ -1464,11 +1546,30 @@ "url": "https://github.com/sponsors/mesqueeb" } }, + "node_modules/create-require": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz", + "integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==", + "dev": true + }, + "node_modules/cross-spawn": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", + "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", + "dev": true, + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, "node_modules/css-select": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/css-select/-/css-select-4.3.0.tgz", "integrity": "sha512-wPpOYtnsVontu2mODhA19JrqWxNsfdatRKd64kmpRbQgh1KtItko5sTnEpPdpSaJszTOhEMlF/RPz28qj4HqhQ==", - "license": "BSD-2-Clause", "dependencies": { "boolbase": "^1.0.0", "css-what": "^6.0.1", @@ -1484,7 +1585,6 @@ "version": "6.1.0", "resolved": "https://registry.npmjs.org/css-what/-/css-what-6.1.0.tgz", "integrity": "sha512-HTUrgRJ7r4dsZKU6GjmpfRK1O76h97Z8MfS1G0FozR+oF2kG6Vfe8JE6zwrkbxigziPHinCJ+gCPjA9EaBDtRw==", - "license": "BSD-2-Clause", "engines": { "node": ">= 6" }, @@ -1495,14 +1595,12 @@ "node_modules/csstype": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz", - "integrity": "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==", - "license": "MIT" + "integrity": "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==" }, "node_modules/d": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/d/-/d-1.0.2.tgz", "integrity": "sha512-MOqHvMWF9/9MX6nza0KgvFH4HpMU0EF5uUDXqX/BtxtU8NfB0QzRtJ8Oe/6SuS4kbhyzVJwjd97EA4PKrzJ8bw==", - "license": "ISC", "dependencies": { "es5-ext": "^0.10.64", "type": "^2.7.2" @@ -1511,11 +1609,19 @@ "node": ">=0.12" } }, + "node_modules/diff": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz", + "integrity": "sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==", + "dev": true, + "engines": { + "node": ">=0.3.1" + } + }, "node_modules/dom-serializer": { "version": "1.4.1", "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-1.4.1.tgz", "integrity": "sha512-VHwB3KfrcOOkelEG2ZOfxqLZdfkil8PtJi4P8N2MMXucZq2yLp75ClViUlOVwyoHEDjYU433Aq+5zWP61+RGag==", - "license": "MIT", "dependencies": { "domelementtype": "^2.0.1", "domhandler": "^4.2.0", @@ -1534,14 +1640,12 @@ "type": "github", "url": "https://github.com/sponsors/fb55" } - ], - "license": "BSD-2-Clause" + ] }, "node_modules/domhandler": { "version": "4.3.1", "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-4.3.1.tgz", "integrity": "sha512-GrwoxYN+uWlzO8uhUXRl0P+kHE4GtVPfYzVLcUxPL7KNdHKj66vvlhiweIHqYYXWlw+T8iLMp42Lm67ghw4WMQ==", - "license": "BSD-2-Clause", "dependencies": { "domelementtype": "^2.2.0" }, @@ -1556,7 +1660,6 @@ "version": "2.8.0", "resolved": "https://registry.npmjs.org/domutils/-/domutils-2.8.0.tgz", "integrity": "sha512-w96Cjofp72M5IIhpjgobBimYEfoPjx1Vx0BSX9P30WBdZW2WIKU0T1Bd0kz2eNZ9ikjKgHbEyKx8BB6H1L3h3A==", - "license": "BSD-2-Clause", "dependencies": { "dom-serializer": "^1.0.1", "domelementtype": "^2.2.0", @@ -1566,11 +1669,22 @@ "url": "https://github.com/fb55/domutils?sponsor=1" } }, + "node_modules/eastasianwidth": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", + "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==", + "dev": true + }, + "node_modules/emoji-regex": { + "version": "9.2.2", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", + "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", + "dev": true + }, "node_modules/entities": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/entities/-/entities-2.2.0.tgz", "integrity": "sha512-p92if5Nz619I0w+akJrLZH0MX0Pb5DX39XOwQTtXSdQQOaYH03S1uIQp4mhOZtAXrxq4ViO67YTiLBo2638o9A==", - "license": "BSD-2-Clause", "funding": { "url": "https://github.com/fb55/entities?sponsor=1" } @@ -1580,7 +1694,6 @@ "resolved": "https://registry.npmjs.org/es5-ext/-/es5-ext-0.10.64.tgz", "integrity": "sha512-p2snDhiLaXe6dahss1LddxqEm+SkuDvV8dnIQG0MWjyHpcMNfXKPE+/Cc0y+PhxJX3A4xGNeFCj5oc0BUh6deg==", "hasInstallScript": true, - "license": "ISC", "dependencies": { "es6-iterator": "^2.0.3", "es6-symbol": "^3.1.3", @@ -1595,7 +1708,6 @@ "version": "2.0.3", "resolved": "https://registry.npmjs.org/es6-iterator/-/es6-iterator-2.0.3.tgz", "integrity": "sha512-zw4SRzoUkd+cl+ZoE15A9o1oQd920Bb0iOJMQkQhl3jNc03YqVjAhG7scf9C5KWRU/R13Orf588uCC6525o02g==", - "license": "MIT", "dependencies": { "d": "1", "es5-ext": "^0.10.35", @@ -1606,7 +1718,6 @@ "version": "3.1.4", "resolved": "https://registry.npmjs.org/es6-symbol/-/es6-symbol-3.1.4.tgz", "integrity": "sha512-U9bFFjX8tFiATgtkJ1zg25+KviIXpgRvRHS8sau3GfhVzThRQrOeksPeT0BWW2MNZs1OEWJ1DPXOQMn0KKRkvg==", - "license": "ISC", "dependencies": { "d": "^1.0.2", "ext": "^1.7.0" @@ -1619,7 +1730,6 @@ "version": "2.0.3", "resolved": "https://registry.npmjs.org/es6-weak-map/-/es6-weak-map-2.0.3.tgz", "integrity": "sha512-p5um32HOTO1kP+w7PRnB+5lQ43Z6muuMuIMffvDN8ZB4GcnjLBV6zGStpbASIMk4DCAvEaamhe2zhyCb/QXXsA==", - "license": "ISC", "dependencies": { "d": "1", "es5-ext": "^0.10.46", @@ -1632,7 +1742,6 @@ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz", "integrity": "sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==", "hasInstallScript": true, - "license": "MIT", "bin": { "esbuild": "bin/esbuild" }, @@ -1669,7 +1778,6 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/escape-goat/-/escape-goat-3.0.0.tgz", "integrity": "sha512-w3PwNZJwRxlp47QGzhuEBldEqVHHhh8/tIPcl6ecf2Bou99cdAt0knihBV0Ecc7CGxYduXVBDheH1K2oADRlvw==", - "license": "MIT", "engines": { "node": ">=10" }, @@ -1681,7 +1789,6 @@ "version": "3.2.25", "resolved": "https://registry.npmjs.org/esm/-/esm-3.2.25.tgz", "integrity": "sha512-U1suiZ2oDVWv4zPO56S0NcR5QriEahGtdN2OR6FiOG4WJvcjBVFB0qI4+eKoWFH483PKGuLuu6V8Z4T5g63UVA==", - "license": "MIT", "engines": { "node": ">=6" } @@ -1690,7 +1797,6 @@ "version": "2.0.1", "resolved": "https://registry.npmjs.org/esniff/-/esniff-2.0.1.tgz", "integrity": "sha512-kTUIGKQ/mDPFoJ0oVfcmyJn4iBDRptjNVIzwIFR7tqWXdVI9xfA2RMwY/gbSpJG3lkdWNEjLap/NqVHZiJsdfg==", - "license": "ISC", "dependencies": { "d": "^1.0.1", "es5-ext": "^0.10.62", @@ -1704,14 +1810,12 @@ "node_modules/estree-walker": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", - "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", - "license": "MIT" + "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==" }, "node_modules/event-emitter": { "version": "0.3.5", "resolved": "https://registry.npmjs.org/event-emitter/-/event-emitter-0.3.5.tgz", "integrity": "sha512-D9rRn9y7kLPnJ+hMq7S/nhvoKwwvVJahBi2BPmx3bvbsEdK3W9ii8cBSGjP+72/LnM4n6fo3+dkCX5FeTQruXA==", - "license": "MIT", "dependencies": { "d": "1", "es5-ext": "~0.10.14" @@ -1721,7 +1825,6 @@ "version": "1.7.0", "resolved": "https://registry.npmjs.org/ext/-/ext-1.7.0.tgz", "integrity": "sha512-6hxeJYaL110a9b5TEJSj0gojyHQAmA2ch5Os+ySCiA1QGdS697XWY1pzsrSjqA9LDEEgdB/KypIlR59RcLuHYw==", - "license": "ISC", "dependencies": { "type": "^2.7.2" } @@ -1741,17 +1844,31 @@ "version": "7.5.4", "resolved": "https://registry.npmjs.org/focus-trap/-/focus-trap-7.5.4.tgz", "integrity": "sha512-N7kHdlgsO/v+iD/dMoJKtsSqs5Dz/dXZVebRgJw23LDk+jMi/974zyiOYDziY2JPp8xivq9BmUGwIJMiuSBi7w==", - "license": "MIT", "dependencies": { "tabbable": "^6.2.0" } }, + "node_modules/foreground-child": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.2.1.tgz", + "integrity": "sha512-PXUUyLqrR2XCWICfv6ukppP96sdFwWbNEnfEMt7jNsISjMsvaLNinAHNDYyvkyU+SZG2BTSbT5NjG+vZslfGTA==", + "dev": true, + "dependencies": { + "cross-spawn": "^7.0.0", + "signal-exit": "^4.0.1" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/fsevents": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", "hasInstallScript": true, - "license": "MIT", "optional": true, "os": [ "darwin" @@ -1760,6 +1877,29 @@ "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, + "node_modules/glob": { + "version": "10.4.2", + "resolved": "https://registry.npmjs.org/glob/-/glob-10.4.2.tgz", + "integrity": "sha512-GwMlUF6PkPo3Gk21UxkCohOv0PLcIXVtKyLlpEI28R/cO/4eNOdmLk3CMW1wROV/WR/EsZOWAfBbBOqYvs88/w==", + "dev": true, + "dependencies": { + "foreground-child": "^3.1.0", + "jackspeak": "^3.1.2", + "minimatch": "^9.0.4", + "minipass": "^7.1.2", + "package-json-from-dist": "^1.0.0", + "path-scurry": "^1.11.1" + }, + "bin": { + "glob": "dist/esm/bin.mjs" + }, + "engines": { + "node": ">=16 || 14 >=14.18" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/glob-parent": { "version": "5.1.2", "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", @@ -1774,8 +1914,7 @@ "node_modules/hookable": { "version": "5.5.3", "resolved": "https://registry.npmjs.org/hookable/-/hookable-5.5.3.tgz", - "integrity": "sha512-Yc+BQe8SvoXH1643Qez1zqLRmbA5rCL+sSmk6TVos0LWVfNIB7PGncdlId77WzLGSIB5KaWgTaNTs2lNVEI6VQ==", - "license": "MIT" + "integrity": "sha512-Yc+BQe8SvoXH1643Qez1zqLRmbA5rCL+sSmk6TVos0LWVfNIB7PGncdlId77WzLGSIB5KaWgTaNTs2lNVEI6VQ==" }, "node_modules/htmlparser2": { "version": "6.1.0", @@ -1788,7 +1927,6 @@ "url": "https://github.com/sponsors/fb55" } ], - "license": "MIT", "dependencies": { "domelementtype": "^2.0.1", "domhandler": "^4.0.0", @@ -1815,6 +1953,15 @@ "node": ">=0.10.0" } }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true, + "engines": { + "node": ">=8" + } + }, "node_modules/is-glob": { "version": "4.0.3", "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", @@ -1837,14 +1984,12 @@ "node_modules/is-promise": { "version": "2.2.2", "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-2.2.2.tgz", - "integrity": "sha512-+lP4/6lKUBfQjZ2pdxThZvLUAafmZb8OAxFb8XXtiQmS35INgr85hdOGoEs124ez1FCnZJt6jau/T+alh58QFQ==", - "license": "MIT" + "integrity": "sha512-+lP4/6lKUBfQjZ2pdxThZvLUAafmZb8OAxFb8XXtiQmS35INgr85hdOGoEs124ez1FCnZJt6jau/T+alh58QFQ==" }, "node_modules/is-what": { "version": "4.1.16", "resolved": "https://registry.npmjs.org/is-what/-/is-what-4.1.16.tgz", "integrity": "sha512-ZhMwEosbFJkA0YhFnNDgTM4ZxDRsS6HqTo7qsZM08fehyRYIYa0yHu5R6mgo1n/8MgaPBXiPimPD77baVFYg+A==", - "license": "MIT", "engines": { "node": ">=12.13" }, @@ -1852,11 +1997,34 @@ "url": "https://github.com/sponsors/mesqueeb" } }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "dev": true + }, + "node_modules/jackspeak": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-3.4.0.tgz", + "integrity": "sha512-JVYhQnN59LVPFCEcVa2C3CrEKYacvjRfqIQl+h8oi91aLYQVWRYbxjPcv1bUiUy/kLmQaANrYfNMCO3kuEDHfw==", + "dev": true, + "dependencies": { + "@isaacs/cliui": "^8.0.2" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + }, + "optionalDependencies": { + "@pkgjs/parseargs": "^0.11.0" + } + }, "node_modules/json5": { "version": "2.2.3", "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", - "license": "MIT", "bin": { "json5": "lib/cli.js" }, @@ -1868,7 +2036,6 @@ "version": "8.1.0", "resolved": "https://registry.npmjs.org/juice/-/juice-8.1.0.tgz", "integrity": "sha512-FLzurJrx5Iv1e7CfBSZH68dC04EEvXvvVvPYB7Vx1WAuhCp1ZPIMtqxc+WTWxVkpTIC2Ach/GAv0rQbtGf6YMA==", - "license": "MIT", "dependencies": { "cheerio": "1.0.0-rc.10", "commander": "^6.1.0", @@ -1883,12 +2050,20 @@ "node": ">=10.0.0" } }, + "node_modules/kleur": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/kleur/-/kleur-3.0.3.tgz", + "integrity": "sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==", + "dev": true, + "engines": { + "node": ">=6" + } + }, "node_modules/linkify-it": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/linkify-it/-/linkify-it-5.0.0.tgz", "integrity": "sha512-5aHCbzQRADcdP+ATqnDuhhJ/MRIqDkZX5pyjFHRRysS8vZ5AbqGEoFIb6pYHPZ+L/OC2Lc+xT8uHVVR5CAK/wQ==", "dev": true, - "license": "MIT", "dependencies": { "uc.micro": "^2.0.0" } @@ -1896,14 +2071,21 @@ "node_modules/lodash": { "version": "4.17.21", "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", - "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", - "license": "MIT" + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==" + }, + "node_modules/lru-cache": { + "version": "10.3.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.3.0.tgz", + "integrity": "sha512-CQl19J/g+Hbjbv4Y3mFNNXFEL/5t/KCg8POCuUqd4rMKjGG+j1ybER83hxV58zL+dFI1PTkt3GNFSHRt+d8qEQ==", + "dev": true, + "engines": { + "node": "14 || >=16.14" + } }, "node_modules/lru-queue": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/lru-queue/-/lru-queue-0.1.0.tgz", "integrity": "sha512-BpdYkt9EvGl8OfWHDQPISVpcl5xZthb+XPsbELj5AQXxIC8IriDZIQYjBJPEm5rS420sjZ0TLEzRcq5KdBhYrQ==", - "license": "MIT", "dependencies": { "es5-ext": "~0.10.2" } @@ -1912,23 +2094,26 @@ "version": "0.30.10", "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.10.tgz", "integrity": "sha512-iIRwTIf0QKV3UAnYK4PU8uiEc4SRh5jX0mwpIwETPpHdhVM4f53RSwS/vXvN1JhGX+Cs7B8qIq3d6AH49O5fAQ==", - "license": "MIT", "dependencies": { "@jridgewell/sourcemap-codec": "^1.4.15" } }, + "node_modules/make-error": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", + "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==", + "dev": true + }, "node_modules/mark.js": { "version": "8.11.1", "resolved": "https://registry.npmjs.org/mark.js/-/mark.js-8.11.1.tgz", - "integrity": "sha512-1I+1qpDt4idfgLQG+BNWmrqku+7/2bi5nLf4YwF8y8zXvmfiTBY3PV3ZibfrjBueCByROpuBjLLFCajqkgYoLQ==", - "license": "MIT" + "integrity": "sha512-1I+1qpDt4idfgLQG+BNWmrqku+7/2bi5nLf4YwF8y8zXvmfiTBY3PV3ZibfrjBueCByROpuBjLLFCajqkgYoLQ==" }, "node_modules/markdown-it": { "version": "14.1.0", "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-14.1.0.tgz", "integrity": "sha512-a54IwgWPaeBCAAsv13YgmALOF1elABB08FxO9i+r4VFk5Vl4pKokRPeX8u5TCgSsPi6ec1otfLjdOpVcgbpshg==", "dev": true, - "license": "MIT", "dependencies": { "argparse": "^2.0.1", "entities": "^4.4.0", @@ -1945,7 +2130,6 @@ "version": "4.3.2", "resolved": "https://registry.npmjs.org/markdown-it-mathjax3/-/markdown-it-mathjax3-4.3.2.tgz", "integrity": "sha512-TX3GW5NjmupgFtMJGRauioMbbkGsOXAAt1DZ/rzzYmTHqzkO1rNAdiMD4NiruurToPApn2kYy76x02QN26qr2w==", - "license": "MIT", "dependencies": { "juice": "^8.0.0", "mathjax-full": "^3.2.0" @@ -1953,15 +2137,13 @@ }, "node_modules/markdown-it-vuepress-code-snippet-enhanced": { "version": "1.0.1", - "resolved": "git+ssh://git@github.com/IMB11/md-it-enhanced-snippets.git#dfb9fa25527b2f772d50ca37ae526484c890b8ae", - "license": "MIT" + "resolved": "git+ssh://git@github.com/IMB11/md-it-enhanced-snippets.git#dfb9fa25527b2f772d50ca37ae526484c890b8ae" }, "node_modules/markdown-it/node_modules/entities": { "version": "4.5.0", "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==", "dev": true, - "license": "BSD-2-Clause", "engines": { "node": ">=0.12" }, @@ -1974,7 +2156,6 @@ "resolved": "https://registry.npmjs.org/markdownlint/-/markdownlint-0.34.0.tgz", "integrity": "sha512-qwGyuyKwjkEMOJ10XN6OTKNOVYvOIi35RNvDLNxTof5s8UmyGHlCdpngRHoRGNvQVGuxO3BJ7uNSgdeX166WXw==", "dev": true, - "license": "MIT", "dependencies": { "markdown-it": "14.1.0", "markdownlint-micromark": "0.1.9" @@ -1991,7 +2172,6 @@ "resolved": "https://registry.npmjs.org/markdownlint-micromark/-/markdownlint-micromark-0.1.9.tgz", "integrity": "sha512-5hVs/DzAFa8XqYosbEAEg6ok6MF2smDj89ztn9pKkCtdKHVdPQuGMH7frFfYL9mLkvfFe4pTyAMffLbjf3/EyA==", "dev": true, - "license": "MIT", "engines": { "node": ">=18" }, @@ -2000,43 +2180,33 @@ } }, "node_modules/markdownlint-rule-helpers": { - "version": "0.7.0", - "resolved": "https://registry.npmjs.org/markdownlint-rule-helpers/-/markdownlint-rule-helpers-0.7.0.tgz", - "integrity": "sha512-xZByWJNBaCMHo7nYPv/5aO8Jt68YcMvyouFXhuXmJzbqCsQy8rfCj0kYcv22kdK5PwAgMdbHg0hyTdURbUZtJw==", - "dev": true, - "license": "MIT" - }, - "node_modules/markdownlint-rule-search-replace": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/markdownlint-rule-search-replace/-/markdownlint-rule-search-replace-1.2.0.tgz", - "integrity": "sha512-l2eeVjb0ijxO+dO1ZrODcht+qnJ0VuiAAdBx1J8oa2kAugXl3NhxAGjfNuTfEJae5OQbdSGT+NjMczyzBXvWMA==", + "version": "0.21.0", + "resolved": "https://registry.npmjs.org/markdownlint-rule-helpers/-/markdownlint-rule-helpers-0.21.0.tgz", + "integrity": "sha512-27WM6H76t79EZjEl3jSabV0ZzXsC5QaSslI/5N1XuXV0mJRA6i3BPMGFrtZUbhlCNgtY6oC9h5JhtpDMv95tKg==", "dev": true, - "license": "MIT", "dependencies": { - "markdownlint-rule-helpers": "0.21.0" + "markdownlint-micromark": "0.1.2" }, "engines": { "node": ">=16" } }, - "node_modules/markdownlint-rule-search-replace/node_modules/markdownlint-micromark": { + "node_modules/markdownlint-rule-helpers/node_modules/markdownlint-micromark": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/markdownlint-micromark/-/markdownlint-micromark-0.1.2.tgz", "integrity": "sha512-jRxlQg8KpOfM2IbCL9RXM8ZiYWz2rv6DlZAnGv8ASJQpUh6byTBnEsbuMZ6T2/uIgntyf7SKg/mEaEBo1164fQ==", "dev": true, - "license": "MIT", "engines": { "node": ">=14.18.0" } }, - "node_modules/markdownlint-rule-search-replace/node_modules/markdownlint-rule-helpers": { - "version": "0.21.0", - "resolved": "https://registry.npmjs.org/markdownlint-rule-helpers/-/markdownlint-rule-helpers-0.21.0.tgz", - "integrity": "sha512-27WM6H76t79EZjEl3jSabV0ZzXsC5QaSslI/5N1XuXV0mJRA6i3BPMGFrtZUbhlCNgtY6oC9h5JhtpDMv95tKg==", + "node_modules/markdownlint-rule-search-replace": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/markdownlint-rule-search-replace/-/markdownlint-rule-search-replace-1.2.0.tgz", + "integrity": "sha512-l2eeVjb0ijxO+dO1ZrODcht+qnJ0VuiAAdBx1J8oa2kAugXl3NhxAGjfNuTfEJae5OQbdSGT+NjMczyzBXvWMA==", "dev": true, - "license": "MIT", "dependencies": { - "markdownlint-micromark": "0.1.2" + "markdownlint-rule-helpers": "0.21.0" }, "engines": { "node": ">=16" @@ -2047,17 +2217,21 @@ "resolved": "https://registry.npmjs.org/markdownlint-rule-titlecase/-/markdownlint-rule-titlecase-0.1.0.tgz", "integrity": "sha512-PuYN2NCJGHYeA6CMInQhyywkiu1oix9Ipvf5n0jLiebmwB5ipO9iTtlNrYRUeAX7WamGy0V1OFVnD+ly45utSw==", "dev": true, - "license": "MIT", "dependencies": { "markdownlint-rule-helpers": "^0.7.0", "title-case": "^3.0.2" } }, + "node_modules/markdownlint-rule-titlecase/node_modules/markdownlint-rule-helpers": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/markdownlint-rule-helpers/-/markdownlint-rule-helpers-0.7.0.tgz", + "integrity": "sha512-xZByWJNBaCMHo7nYPv/5aO8Jt68YcMvyouFXhuXmJzbqCsQy8rfCj0kYcv22kdK5PwAgMdbHg0hyTdURbUZtJw==", + "dev": true + }, "node_modules/mathjax-full": { "version": "3.2.2", "resolved": "https://registry.npmjs.org/mathjax-full/-/mathjax-full-3.2.2.tgz", "integrity": "sha512-+LfG9Fik+OuI8SLwsiR02IVdjcnRCy5MufYLi0C3TdMT56L/pjB0alMVGgoWJF8pN9Rc7FESycZB9BMNWIid5w==", - "license": "Apache-2.0", "dependencies": { "esm": "^3.2.25", "mhchemparser": "^4.1.0", @@ -2069,8 +2243,7 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/mdurl/-/mdurl-2.0.0.tgz", "integrity": "sha512-Lf+9+2r+Tdp5wXDXC4PcIBjTDtq4UKjCPMQhKIuzpJNW0b96kVqSwW0bT7FhRSfmAiFYgP+SCRvdrDozfh0U5w==", - "dev": true, - "license": "MIT" + "dev": true }, "node_modules/media-captions": { "version": "1.0.3", @@ -2089,7 +2262,6 @@ "version": "0.4.17", "resolved": "https://registry.npmjs.org/memoizee/-/memoizee-0.4.17.tgz", "integrity": "sha512-DGqD7Hjpi/1or4F/aYAspXKNm5Yili0QDAFAY4QYvpqpgiY6+1jOfqpmByzjxbWd/T9mChbCArXAbDAsTm5oXA==", - "license": "ISC", "dependencies": { "d": "^1.0.2", "es5-ext": "^0.10.64", @@ -2107,20 +2279,17 @@ "node_modules/mensch": { "version": "0.3.4", "resolved": "https://registry.npmjs.org/mensch/-/mensch-0.3.4.tgz", - "integrity": "sha512-IAeFvcOnV9V0Yk+bFhYR07O3yNina9ANIN5MoXBKYJ/RLYPurd2d0yw14MDhpr9/momp0WofT1bPUh3hkzdi/g==", - "license": "MIT" + "integrity": "sha512-IAeFvcOnV9V0Yk+bFhYR07O3yNina9ANIN5MoXBKYJ/RLYPurd2d0yw14MDhpr9/momp0WofT1bPUh3hkzdi/g==" }, "node_modules/mhchemparser": { "version": "4.2.1", "resolved": "https://registry.npmjs.org/mhchemparser/-/mhchemparser-4.2.1.tgz", - "integrity": "sha512-kYmyrCirqJf3zZ9t/0wGgRZ4/ZJw//VwaRVGA75C4nhE60vtnIzhl9J9ndkX/h6hxSN7pjg/cE0VxbnNM+bnDQ==", - "license": "Apache-2.0" + "integrity": "sha512-kYmyrCirqJf3zZ9t/0wGgRZ4/ZJw//VwaRVGA75C4nhE60vtnIzhl9J9ndkX/h6hxSN7pjg/cE0VxbnNM+bnDQ==" }, "node_modules/mime": { "version": "2.6.0", "resolved": "https://registry.npmjs.org/mime/-/mime-2.6.0.tgz", "integrity": "sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg==", - "license": "MIT", "bin": { "mime": "cli.js" }, @@ -2128,23 +2297,44 @@ "node": ">=4.0.0" } }, + "node_modules/minimatch": { + "version": "9.0.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz", + "integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==", + "dev": true, + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/minipass": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz", + "integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==", + "dev": true, + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, "node_modules/minisearch": { "version": "6.3.0", "resolved": "https://registry.npmjs.org/minisearch/-/minisearch-6.3.0.tgz", - "integrity": "sha512-ihFnidEeU8iXzcVHy74dhkxh/dn8Dc08ERl0xwoMMGqp4+LvRSCgicb+zGqWthVokQKvCSxITlh3P08OzdTYCQ==", - "license": "MIT" + "integrity": "sha512-ihFnidEeU8iXzcVHy74dhkxh/dn8Dc08ERl0xwoMMGqp4+LvRSCgicb+zGqWthVokQKvCSxITlh3P08OzdTYCQ==" }, "node_modules/mitt": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/mitt/-/mitt-3.0.1.tgz", - "integrity": "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==", - "license": "MIT" + "integrity": "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==" }, "node_modules/mj-context-menu": { "version": "0.6.1", "resolved": "https://registry.npmjs.org/mj-context-menu/-/mj-context-menu-0.6.1.tgz", - "integrity": "sha512-7NO5s6n10TIV96d4g2uDpG7ZDpIhMh0QNfGdJw/W47JswFcosz457wqz/b5sAKvl12sxINGFCn80NZHKwxQEXA==", - "license": "Apache-2.0" + "integrity": "sha512-7NO5s6n10TIV96d4g2uDpG7ZDpIhMh0QNfGdJw/W47JswFcosz457wqz/b5sAKvl12sxINGFCn80NZHKwxQEXA==" }, "node_modules/nanoid": { "version": "3.3.7", @@ -2156,7 +2346,6 @@ "url": "https://github.com/sponsors/ai" } ], - "license": "MIT", "bin": { "nanoid": "bin/nanoid.cjs" }, @@ -2167,14 +2356,12 @@ "node_modules/next-tick": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/next-tick/-/next-tick-1.1.0.tgz", - "integrity": "sha512-CXdUiJembsNjuToQvxayPZF9Vqht7hewsvy2sOWafLvi2awflj9mOC6bHIg50orX8IJvWKY9wYQ/zB2kogPslQ==", - "license": "ISC" + "integrity": "sha512-CXdUiJembsNjuToQvxayPZF9Vqht7hewsvy2sOWafLvi2awflj9mOC6bHIg50orX8IJvWKY9wYQ/zB2kogPslQ==" }, "node_modules/node-fetch": { "version": "2.7.0", "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", - "license": "MIT", "dependencies": { "whatwg-url": "^5.0.0" }, @@ -2202,7 +2389,6 @@ "version": "2.1.1", "resolved": "https://registry.npmjs.org/nth-check/-/nth-check-2.1.1.tgz", "integrity": "sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==", - "license": "BSD-2-Clause", "dependencies": { "boolbase": "^1.0.0" }, @@ -2210,32 +2396,59 @@ "url": "https://github.com/fb55/nth-check?sponsor=1" } }, + "node_modules/package-json-from-dist": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.0.tgz", + "integrity": "sha512-dATvCeZN/8wQsGywez1mzHtTlP22H8OEfPrVMLNr4/eGa+ijtLn/6M5f0dY8UKNrC2O9UCU6SSoG3qRKnt7STw==", + "dev": true + }, "node_modules/parse5": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/parse5/-/parse5-6.0.1.tgz", - "integrity": "sha512-Ofn/CTFzRGTTxwpNEs9PP93gXShHcTq255nzRYSKe8AkVpZY7e1fpmTfOyoIvjP5HG7Z2ZM7VS9PPhQGW2pOpw==", - "license": "MIT" + "integrity": "sha512-Ofn/CTFzRGTTxwpNEs9PP93gXShHcTq255nzRYSKe8AkVpZY7e1fpmTfOyoIvjP5HG7Z2ZM7VS9PPhQGW2pOpw==" }, "node_modules/parse5-htmlparser2-tree-adapter": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/parse5-htmlparser2-tree-adapter/-/parse5-htmlparser2-tree-adapter-6.0.1.tgz", "integrity": "sha512-qPuWvbLgvDGilKc5BoicRovlT4MtYT6JfJyBOMDsKoiT+GiuP5qyrPCnR9HcPECIJJmZh5jRndyNThnhhb/vlA==", - "license": "MIT", "dependencies": { "parse5": "^6.0.1" } }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/path-scurry": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-1.11.1.tgz", + "integrity": "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==", + "dev": true, + "dependencies": { + "lru-cache": "^10.2.0", + "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" + }, + "engines": { + "node": ">=16 || 14 >=14.18" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/perfect-debounce": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/perfect-debounce/-/perfect-debounce-1.0.0.tgz", - "integrity": "sha512-xCy9V055GLEqoFaHoC1SoLIaLmWctgCUaBaWxDZ7/Zx4CTyX7cJQLJOok/orfjZAh9kEYpjJa4d0KcJmCbctZA==", - "license": "MIT" + "integrity": "sha512-xCy9V055GLEqoFaHoC1SoLIaLmWctgCUaBaWxDZ7/Zx4CTyX7cJQLJOok/orfjZAh9kEYpjJa4d0KcJmCbctZA==" }, "node_modules/picocolors": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.1.tgz", - "integrity": "sha512-anP1Z8qwhkbmu7MFP5iTt+wQKXgwzf7zTyGlcdzabySa9vd0Xt392U0rVmz9poOaBj0uHJKyyo9/upk0HrEQew==", - "license": "ISC" + "integrity": "sha512-anP1Z8qwhkbmu7MFP5iTt+wQKXgwzf7zTyGlcdzabySa9vd0Xt392U0rVmz9poOaBj0uHJKyyo9/upk0HrEQew==" }, "node_modules/picomatch": { "version": "2.3.1", @@ -2249,9 +2462,9 @@ } }, "node_modules/postcss": { - "version": "8.4.38", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.38.tgz", - "integrity": "sha512-Wglpdk03BSfXkHoQa3b/oulrotAkwrlLDRSOb9D0bN86FdRyE9lppSp33aHNPgBa0JKCoB+drFLZkQoRRYae5A==", + "version": "8.4.39", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.39.tgz", + "integrity": "sha512-0vzE+lAiG7hZl1/9I8yzKLx3aR9Xbof3fBHKunvMfOCYAtMhrsnccJY2iTURb9EZd5+pLuiNV9/c/GZJOHsgIw==", "funding": [ { "type": "opencollective", @@ -2266,10 +2479,9 @@ "url": "https://github.com/sponsors/ai" } ], - "license": "MIT", "dependencies": { "nanoid": "^3.3.7", - "picocolors": "^1.0.0", + "picocolors": "^1.0.1", "source-map-js": "^1.2.0" }, "engines": { @@ -2277,21 +2489,32 @@ } }, "node_modules/preact": { - "version": "10.22.0", - "resolved": "https://registry.npmjs.org/preact/-/preact-10.22.0.tgz", - "integrity": "sha512-RRurnSjJPj4rp5K6XoP45Ui33ncb7e4H7WiOHVpjbkvqvA3U+N8Z6Qbo0AE6leGYBV66n8EhEaFixvIu3SkxFw==", - "license": "MIT", + "version": "10.22.1", + "resolved": "https://registry.npmjs.org/preact/-/preact-10.22.1.tgz", + "integrity": "sha512-jRYbDDgMpIb5LHq3hkI0bbl+l/TQ9UnkdQ0ww+lp+4MMOdqaUYdFc5qeyP+IV8FAd/2Em7drVPeKdQxsiWCf/A==", "funding": { "type": "opencollective", "url": "https://opencollective.com/preact" } }, + "node_modules/prompts": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/prompts/-/prompts-2.4.2.tgz", + "integrity": "sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q==", + "dev": true, + "dependencies": { + "kleur": "^3.0.3", + "sisteransi": "^1.0.5" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/punycode.js": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/punycode.js/-/punycode.js-2.3.1.tgz", "integrity": "sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA==", "dev": true, - "license": "MIT", "engines": { "node": ">=6" } @@ -2310,14 +2533,12 @@ "node_modules/rfdc": { "version": "1.4.1", "resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.4.1.tgz", - "integrity": "sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==", - "license": "MIT" + "integrity": "sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==" }, "node_modules/rollup": { "version": "4.18.0", "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.18.0.tgz", "integrity": "sha512-QmJz14PX3rzbJCN1SG4Xe/bAAX2a6NpCP8ab2vfu2GiUr8AQcr2nCV/oEO3yneFarB67zk8ShlIyWb2LGTb3Sg==", - "license": "MIT", "dependencies": { "@types/estree": "1.0.5" }, @@ -2352,23 +2573,59 @@ "version": "2.14.0", "resolved": "https://registry.npmjs.org/search-insights/-/search-insights-2.14.0.tgz", "integrity": "sha512-OLN6MsPMCghDOqlCtsIsYgtsC0pnwVTyT9Mu6A3ewOj1DxvzZF6COrn2g86E/c05xbktB0XN04m/t1Z+n+fTGw==", - "license": "MIT", "peer": true }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true, + "engines": { + "node": ">=8" + } + }, "node_modules/shiki": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/shiki/-/shiki-1.7.0.tgz", - "integrity": "sha512-H5pMn4JA7ayx8H0qOz1k2qANq6mZVCMl1gKLK6kWIrv1s2Ial4EmD4s4jE8QB5Dw03d/oCQUxc24sotuyR5byA==", - "license": "MIT", + "version": "1.10.1", + "resolved": "https://registry.npmjs.org/shiki/-/shiki-1.10.1.tgz", + "integrity": "sha512-uafV7WCgN4YYrccH6yxpnps6k38sSTlFRrwc4jycWmhWxJIm9dPrk+XkY1hZ2t0I7jmacMNb15Lf2fspa/Y3lg==", "dependencies": { - "@shikijs/core": "1.7.0" + "@shikijs/core": "1.10.1" + } + }, + "node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "dev": true, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/sisteransi": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz", + "integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==", + "dev": true + }, "node_modules/slick": { "version": "1.12.2", "resolved": "https://registry.npmjs.org/slick/-/slick-1.12.2.tgz", "integrity": "sha512-4qdtOGcBjral6YIBCWJ0ljFSKNLz9KkhbWtuGvUyRowl1kxfuE1x/Z/aJcaiilpb3do9bl5K7/1h9XC5wWpY/A==", - "license": "MIT (http://mootools.net/license.txt)", "engines": { "node": "*" } @@ -2377,7 +2634,6 @@ "version": "1.2.0", "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.0.tgz", "integrity": "sha512-itJW8lvSA0TXEphiRoawsCksnlf8SyvmFzIhltqAHluXd88pkCd+cXJVHTDwdCr0IzwptSm035IHQktUu1QUMg==", - "license": "BSD-3-Clause", "engines": { "node": ">=0.10.0" } @@ -2386,7 +2642,6 @@ "version": "14.0.1", "resolved": "https://registry.npmjs.org/speakingurl/-/speakingurl-14.0.1.tgz", "integrity": "sha512-1POYv7uv2gXoyGFpBCmpDVSNV74IfsWlDW216UPjbWufNf+bSU6GdbDsxdcxtfwb4xlI3yxzOTKClUosxARYrQ==", - "license": "BSD-3-Clause", "engines": { "node": ">=0.10.0" } @@ -2395,7 +2650,6 @@ "version": "4.0.7", "resolved": "https://registry.npmjs.org/speech-rule-engine/-/speech-rule-engine-4.0.7.tgz", "integrity": "sha512-sJrL3/wHzNwJRLBdf6CjJWIlxC04iYKkyXvYSVsWVOiC2DSkHmxsqOhEeMsBA9XK+CHuNcsdkbFDnoUfAsmp9g==", - "license": "Apache-2.0", "dependencies": { "commander": "9.2.0", "wicked-good-xpath": "1.3.0", @@ -2409,16 +2663,110 @@ "version": "9.2.0", "resolved": "https://registry.npmjs.org/commander/-/commander-9.2.0.tgz", "integrity": "sha512-e2i4wANQiSXgnrBlIatyHtP1odfUp0BbV5Y5nEGbxtIrStkEOAAzCUirvLBNXHLr7kwLvJl6V+4V3XV9x7Wd9w==", - "license": "MIT", "engines": { "node": "^12.20.0 || >=14" } }, + "node_modules/string-width": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", + "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==", + "dev": true, + "dependencies": { + "eastasianwidth": "^0.2.0", + "emoji-regex": "^9.2.2", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/string-width-cjs": { + "name": "string-width", + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width-cjs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width-cjs/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true + }, + "node_modules/string-width-cjs/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", + "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", + "dev": true, + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/strip-ansi-cjs": { + "name": "strip-ansi", + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi-cjs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, "node_modules/superjson": { "version": "2.2.1", "resolved": "https://registry.npmjs.org/superjson/-/superjson-2.2.1.tgz", "integrity": "sha512-8iGv75BYOa0xRJHK5vRLEjE2H/i4lulTjzpUXic3Eg8akftYjkmQDa8JARQ42rlczXyFR3IeRoeFCc7RxHsYZA==", - "license": "MIT", "dependencies": { "copy-anything": "^3.0.2" }, @@ -2429,14 +2777,12 @@ "node_modules/tabbable": { "version": "6.2.0", "resolved": "https://registry.npmjs.org/tabbable/-/tabbable-6.2.0.tgz", - "integrity": "sha512-Cat63mxsVJlzYvN51JmVXIgNoUokrIaT2zLclCXjRd8boZ0004U4KCs/sToJ75C6sdlByWxpYnb5Boif1VSFew==", - "license": "MIT" + "integrity": "sha512-Cat63mxsVJlzYvN51JmVXIgNoUokrIaT2zLclCXjRd8boZ0004U4KCs/sToJ75C6sdlByWxpYnb5Boif1VSFew==" }, "node_modules/timers-ext": { "version": "0.1.8", "resolved": "https://registry.npmjs.org/timers-ext/-/timers-ext-0.1.8.tgz", "integrity": "sha512-wFH7+SEAcKfJpfLPkrgMPvvwnEtj8W4IurvEyrKsDleXnKLCDw71w8jltvfLa8Rm4qQxxT4jmDBYbJG/z7qoww==", - "license": "ISC", "dependencies": { "es5-ext": "^0.10.64", "next-tick": "^1.1.0" @@ -2450,7 +2796,6 @@ "resolved": "https://registry.npmjs.org/title-case/-/title-case-3.0.3.tgz", "integrity": "sha512-e1zGYRvbffpcHIrnuqT0Dh+gEJtDaxDSoG4JAIpq4oDFyooziLBIiYQv0GBT4FUAnUop5uZ1hiIAj7oAF6sOCA==", "dev": true, - "license": "MIT", "dependencies": { "tslib": "^2.0.3" } @@ -2469,39 +2814,91 @@ "node_modules/tr46": { "version": "0.0.3", "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", - "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", - "license": "MIT" + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==" + }, + "node_modules/ts-node": { + "version": "10.9.2", + "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.2.tgz", + "integrity": "sha512-f0FFpIdcHgn8zcPSbf1dRevwt047YMnaiJM3u2w2RewrB+fob/zePZcrOyQoLMMO7aBIddLcQIEK5dYjkLnGrQ==", + "dev": true, + "dependencies": { + "@cspotcode/source-map-support": "^0.8.0", + "@tsconfig/node10": "^1.0.7", + "@tsconfig/node12": "^1.0.7", + "@tsconfig/node14": "^1.0.0", + "@tsconfig/node16": "^1.0.2", + "acorn": "^8.4.1", + "acorn-walk": "^8.1.1", + "arg": "^4.1.0", + "create-require": "^1.1.0", + "diff": "^4.0.1", + "make-error": "^1.1.1", + "v8-compile-cache-lib": "^3.0.1", + "yn": "3.1.1" + }, + "bin": { + "ts-node": "dist/bin.js", + "ts-node-cwd": "dist/bin-cwd.js", + "ts-node-esm": "dist/bin-esm.js", + "ts-node-script": "dist/bin-script.js", + "ts-node-transpile-only": "dist/bin-transpile.js", + "ts-script": "dist/bin-script-deprecated.js" + }, + "peerDependencies": { + "@swc/core": ">=1.2.50", + "@swc/wasm": ">=1.2.50", + "@types/node": "*", + "typescript": ">=2.7" + }, + "peerDependenciesMeta": { + "@swc/core": { + "optional": true + }, + "@swc/wasm": { + "optional": true + } + } }, "node_modules/tslib": { "version": "2.6.3", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.6.3.tgz", - "integrity": "sha512-xNvxJEOUiWPGhUuUdQgAJPKOOJfGnIyKySOc09XkKsgdUV/3E2zvwZYdejjmRgPCgcym1juLH3226yA7sEFJKQ==", - "license": "0BSD" + "integrity": "sha512-xNvxJEOUiWPGhUuUdQgAJPKOOJfGnIyKySOc09XkKsgdUV/3E2zvwZYdejjmRgPCgcym1juLH3226yA7sEFJKQ==" }, "node_modules/type": { "version": "2.7.3", "resolved": "https://registry.npmjs.org/type/-/type-2.7.3.tgz", - "integrity": "sha512-8j+1QmAbPvLZow5Qpi6NCaN8FB60p/6x8/vfNqOk/hC+HuvFZhL4+WfekuhQLiqFZXOgQdrs3B+XxEmCc6b3FQ==", - "license": "ISC" + "integrity": "sha512-8j+1QmAbPvLZow5Qpi6NCaN8FB60p/6x8/vfNqOk/hC+HuvFZhL4+WfekuhQLiqFZXOgQdrs3B+XxEmCc6b3FQ==" + }, + "node_modules/typescript": { + "version": "5.5.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.5.3.tgz", + "integrity": "sha512-/hreyEujaB0w76zKo6717l3L0o/qEUtRgdvUBvlkhoWeOVMjMuHNHk0BRBzikzuGDqNmPQbg5ifMEqsHLiIUcQ==", + "devOptional": true, + "peer": true, + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } }, "node_modules/uc.micro": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/uc.micro/-/uc.micro-2.1.0.tgz", "integrity": "sha512-ARDJmphmdvUk6Glw7y9DQ2bFkKBHwQHLi2lsaH6PPmz/Ka9sFOBsBluozhDltWmnv9u/cF6Rt87znRTPV+yp/A==", - "dev": true, - "license": "MIT" + "dev": true }, "node_modules/undici-types": { "version": "5.26.5", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz", "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==", - "devOptional": true, - "license": "MIT" + "devOptional": true }, "node_modules/unplugin": { - "version": "1.10.1", - "resolved": "https://registry.npmjs.org/unplugin/-/unplugin-1.10.1.tgz", - "integrity": "sha512-d6Mhq8RJeGA8UfKCu54Um4lFA0eSaRa3XxdAJg8tIdxbu1ubW0hBCZUL7yI2uGyYCRndvbK8FLHzqy2XKfeMsg==", + "version": "1.11.0", + "resolved": "https://registry.npmjs.org/unplugin/-/unplugin-1.11.0.tgz", + "integrity": "sha512-3r7VWZ/webh0SGgJScpWl2/MRCZK5d3ZYFcNaeci/GQ7Teop7zf0Nl2pUuz7G21BwPd9pcUPOC5KmJ2L3WgC5g==", "dependencies": { "acorn": "^8.11.3", "chokidar": "^3.6.0", @@ -2512,19 +2909,24 @@ "node": ">=14.0.0" } }, + "node_modules/v8-compile-cache-lib": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz", + "integrity": "sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==", + "dev": true + }, "node_modules/valid-data-url": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/valid-data-url/-/valid-data-url-3.0.1.tgz", "integrity": "sha512-jOWVmzVceKlVVdwjNSenT4PbGghU0SBIizAev8ofZVgivk/TVHXSbNL8LP6M3spZvkR9/QolkyJavGSX5Cs0UA==", - "license": "MIT", "engines": { "node": ">=10" } }, "node_modules/vidstack": { - "version": "1.11.22", - "resolved": "https://registry.npmjs.org/vidstack/-/vidstack-1.11.22.tgz", - "integrity": "sha512-prJUMxRNSJElzVv6imqAoZMR/x+mYSTC2bCjovXToE3tMGrBCFlYLwuaOht55vm0QS6oU03dDp3tqKGXqhMZOg==", + "version": "1.11.24", + "resolved": "https://registry.npmjs.org/vidstack/-/vidstack-1.11.24.tgz", + "integrity": "sha512-RTd8hj3FD3ScIizm/JNnWKCaMwt9JVTU8Dgq+aOhzptyA6S+rGjXKbpQatp4GL714SwTjHjDVawCtbUrq4S10w==", "dependencies": { "media-captions": "^1.0.1", "unplugin": "^1.10.1" @@ -2534,10 +2936,9 @@ } }, "node_modules/vite": { - "version": "5.3.1", - "resolved": "https://registry.npmjs.org/vite/-/vite-5.3.1.tgz", - "integrity": "sha512-XBmSKRLXLxiaPYamLv3/hnP/KXDai1NDexN0FpkTaZXTfycHvkRHoenpgl/fvuK/kPbB6xAgoyiryAhQNxYmAQ==", - "license": "MIT", + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/vite/-/vite-5.3.2.tgz", + "integrity": "sha512-6lA7OBHBlXUxiJxbO5aAY2fsHHzDr1q7DvXYnyZycRs2Dz+dXBWuhpWHvmljTRTpQC2uvGmUFFkSHF2vGo90MA==", "dependencies": { "esbuild": "^0.21.3", "postcss": "^8.4.38", @@ -2592,7 +2993,6 @@ "version": "1.2.3", "resolved": "https://registry.npmjs.org/vitepress/-/vitepress-1.2.3.tgz", "integrity": "sha512-GvEsrEeNLiDE1+fuwDAYJCYLNZDAna+EtnXlPajhv/MYeTjbNK6Bvyg6NoTdO1sbwuQJ0vuJR99bOlH53bo6lg==", - "license": "MIT", "dependencies": { "@docsearch/css": "^3.6.0", "@docsearch/js": "^3.6.0", @@ -2628,10 +3028,9 @@ } }, "node_modules/vitepress-versioning-plugin": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/vitepress-versioning-plugin/-/vitepress-versioning-plugin-1.0.2.tgz", - "integrity": "sha512-3xjZL1kdplWuhu2ZG+AEtojJ5FTFpZSws0OMfFkStD7X1tTu+46BLxaWBlyySq1xltkF7Zzyn5jLzhfBBHR68g==", - "license": "MIT", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/vitepress-versioning-plugin/-/vitepress-versioning-plugin-1.1.0.tgz", + "integrity": "sha512-tstqH/lpdqDsjU1Lq0tffcVetbQ0ETDB2SLTfIcZnMX6xXbU0/dCxC36ZuPM2++y4iU7ZO2D9Uu/4z0DenE6SA==", "dependencies": { "@types/lodash": "^4.17.5", "cli-color": "^2.0.4", @@ -2642,16 +3041,15 @@ } }, "node_modules/vue": { - "version": "3.4.29", - "resolved": "https://registry.npmjs.org/vue/-/vue-3.4.29.tgz", - "integrity": "sha512-8QUYfRcYzNlYuzKPfge1UWC6nF9ym0lx7mpGVPJYNhddxEf3DD0+kU07NTL0sXuiT2HuJuKr/iEO8WvXvT0RSQ==", - "license": "MIT", + "version": "3.4.31", + "resolved": "https://registry.npmjs.org/vue/-/vue-3.4.31.tgz", + "integrity": "sha512-njqRrOy7W3YLAlVqSKpBebtZpDVg21FPoaq1I7f/+qqBThK9ChAIjkRWgeP6Eat+8C+iia4P3OYqpATP21BCoQ==", "dependencies": { - "@vue/compiler-dom": "3.4.29", - "@vue/compiler-sfc": "3.4.29", - "@vue/runtime-dom": "3.4.29", - "@vue/server-renderer": "3.4.29", - "@vue/shared": "3.4.29" + "@vue/compiler-dom": "3.4.31", + "@vue/compiler-sfc": "3.4.31", + "@vue/runtime-dom": "3.4.31", + "@vue/server-renderer": "3.4.31", + "@vue/shared": "3.4.31" }, "peerDependencies": { "typescript": "*" @@ -2666,7 +3064,6 @@ "version": "6.0.1", "resolved": "https://registry.npmjs.org/web-resource-inliner/-/web-resource-inliner-6.0.1.tgz", "integrity": "sha512-kfqDxt5dTB1JhqsCUQVFDj0rmY+4HLwGQIsLPbyrsN9y9WV/1oFDSx3BQ4GfCv9X+jVeQ7rouTqwK53rA/7t8A==", - "license": "MIT", "dependencies": { "ansi-colors": "^4.1.1", "escape-goat": "^3.0.0", @@ -2683,7 +3080,6 @@ "version": "3.3.0", "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-3.3.0.tgz", "integrity": "sha512-J1C5rIANUbuYK+FuFL98650rihynUOEzRLxW+90bKZRWB6A1X1Tf82GxR1qAWLyfNPRvjqfip3Q5tdYlmAa9lA==", - "license": "BSD-2-Clause", "dependencies": { "domelementtype": "^2.0.1" }, @@ -2698,7 +3094,6 @@ "version": "5.0.1", "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-5.0.1.tgz", "integrity": "sha512-vKZZra6CSe9qsJzh0BjBGXo8dvzNsq/oGvsjfRdOrrryfeD9UOBEEQdeoqCRmKZchF5h2zOBMQ6YuQ0uRUmdbQ==", - "license": "MIT", "dependencies": { "domelementtype": "^2.0.1", "domhandler": "^3.3.0", @@ -2712,8 +3107,7 @@ "node_modules/webidl-conversions": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", - "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", - "license": "BSD-2-Clause" + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==" }, "node_modules/webpack-sources": { "version": "3.2.3", @@ -2732,26 +3126,138 @@ "version": "5.0.0", "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", - "license": "MIT", "dependencies": { "tr46": "~0.0.3", "webidl-conversions": "^3.0.0" } }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, "node_modules/wicked-good-xpath": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/wicked-good-xpath/-/wicked-good-xpath-1.3.0.tgz", - "integrity": "sha512-Gd9+TUn5nXdwj/hFsPVx5cuHHiF5Bwuc30jZ4+ronF1qHK5O7HD0sgmXWSEgwKquT3ClLoKPVbO6qGwVwLzvAw==", - "license": "MIT" + "integrity": "sha512-Gd9+TUn5nXdwj/hFsPVx5cuHHiF5Bwuc30jZ4+ronF1qHK5O7HD0sgmXWSEgwKquT3ClLoKPVbO6qGwVwLzvAw==" + }, + "node_modules/wrap-ansi": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", + "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==", + "dev": true, + "dependencies": { + "ansi-styles": "^6.1.0", + "string-width": "^5.0.1", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs": { + "name": "wrap-ansi", + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dev": true, + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true + }, + "node_modules/wrap-ansi-cjs/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } }, "node_modules/xmldom-sre": { "version": "0.1.31", "resolved": "https://registry.npmjs.org/xmldom-sre/-/xmldom-sre-0.1.31.tgz", "integrity": "sha512-f9s+fUkX04BxQf+7mMWAp5zk61pciie+fFLC9hX9UVvCeJQfNHRHXpeo5MPcR0EUf57PYLdt+ZO4f3Ipk2oZUw==", - "license": "(LGPL-2.0 or MIT)", "engines": { "node": ">=0.1" } + }, + "node_modules/yn": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz", + "integrity": "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==", + "dev": true, + "engines": { + "node": ">=6" + } } } } diff --git a/package.json b/package.json index 7610ab8de..8d084f491 100644 --- a/package.json +++ b/package.json @@ -3,13 +3,19 @@ "scripts": { "dev": "vitepress dev", "build": "vitepress build", - "preview": "vitepress preview" + "preview": "vitepress preview", + "bump": "ts-node ./.vitepress/update.ts" }, "devDependencies": { + "@types/glob": "^8.1.0", "@types/node": "^20.14.5", + "@types/prompts": "^2.4.9", + "glob": "^10.4.2", "markdownlint": "^0.34.0", "markdownlint-rule-search-replace": "^1.2.0", - "markdownlint-rule-titlecase": "^0.1.0" + "markdownlint-rule-titlecase": "^0.1.0", + "prompts": "^2.4.2", + "ts-node": "^10.9.2" }, "optionalDependencies": { "@rollup/rollup-linux-x64-gnu": "4.18.0" diff --git a/players/installing-fabric.md b/players/installing-fabric.md index 9d85eeb89..de6157a38 100644 --- a/players/installing-fabric.md +++ b/players/installing-fabric.md @@ -3,6 +3,8 @@ title: Installing Fabric description: A step by step guide on how to install Fabric. authors: - IMB11 + - Benonardo + - modmuss50 --- # Installing Fabric {#installing-fabric} diff --git a/players/installing-java/linux.md b/players/installing-java/linux.md index 2502ade89..53779465a 100644 --- a/players/installing-java/linux.md +++ b/players/installing-java/linux.md @@ -7,7 +7,7 @@ authors: # Installing Java on Linux {#installing-java-on-linux} -This guide will walk you through installing Java 17 on Linux. +This guide will walk you through installing Java 21 on Linux. ## 1. Check if Java Is Already Installed {#1-check-if-java-is-already-installed} @@ -16,12 +16,12 @@ Open a terminal, type `java -version`, and press Enter. ![Terminal with "java -version" typed in](/assets/players/installing-java/linux-java-version.png) ::: warning -To use the majority of modern Minecraft versions, you'll need at least Java 17 installed. If this command displays any version lower than 17, you'll need to update your existing Java installation. +To use Minecraft 1.21, you'll need at least Java 21 installed. If this command displays any version lower than 21, you'll need to update your existing Java installation. ::: -## 2. Downloading and Installing Java 17 {#2-downloading-and-installing-java-17} +## 2. Downloading and Installing Java 21 {#2-downloading-and-installing-java} -We recommend using OpenJDK 17, which is available for most Linux distributions. +We recommend using OpenJDK 21, which is available for most Linux distributions. ### Arch Linux {#arch-linux} @@ -49,31 +49,31 @@ sudo pacman -S jdk-openjdk ### Debian/Ubuntu {#debian-ubuntu} -You can install Java 17 using `apt` with the following commands: +You can install Java 21 using `apt` with the following commands: ```sh sudo apt update -sudo apt install openjdk-17-jdk +sudo apt install openjdk-21-jdk ``` ### Fedora {#fedora} -You can install Java 17 using `dnf` with the following commands: +You can install Java 21 using `dnf` with the following commands: ```sh -sudo dnf install java-17-openjdk +sudo dnf install java-21-openjdk ``` If you don't need a graphical interface, you can install the headless version instead: ```sh -sudo dnf install java-17-openjdk-headless +sudo dnf install java-21-openjdk-headless ``` If you plan to develop mods, you'll need the JDK instead: ```sh -sudo dnf install java-17-openjdk-devel +sudo dnf install java-21-openjdk-devel ``` ### Other Linux Distributions {#other-linux-distributions} @@ -82,9 +82,9 @@ If your distribution isn't listed above, you can download the latest JRE from [A You should refer to an alternative guide for your distribution if you plan to develop mods. -## 3. Verify That Java 17 Is Installed {#3-verify-that-java-17-is-installed} +## 3. Verify That Java 21 Is Installed {#3-verify-that-java-is-installed} -Once the installation is complete, you can verify that Java 17 is installed by opening a terminal and typing `java -version`. +Once the installation is complete, you can verify that Java 21 is installed by opening a terminal and typing `java -version`. If the command runs successfully, you will see something like shown before, where the Java version is displayed: diff --git a/players/installing-java/windows.md b/players/installing-java/windows.md index 700e76a63..85df1f496 100644 --- a/players/installing-java/windows.md +++ b/players/installing-java/windows.md @@ -7,7 +7,7 @@ authors: # Installing Java on Windows {#installing-java-on-windows} -This guide will walk you through installing Java 17 on Windows. +This guide will walk you through installing Java 21 on Windows. The Minecraft Launcher comes with its own Java installation, so this section is only relevant if you want to use the Fabric `.jar` based installer, or if you want to use the Minecraft Server `.jar`. @@ -26,12 +26,12 @@ If the command runs successfully, you will see something like this. If the comma ![Command prompt with "java -version" typed in](/assets/players/installing-java/windows-java-version.png) ::: warning -To use the majority of modern Minecraft versions, you'll need at least Java 17 installed. If this command displays any version lower than 17, you'll need to update your existing Java installation. +To use Minecraft 1.21, you'll need at least Java 21 installed. If this command displays any version lower than 21, you'll need to update your existing Java installation. ::: -## 2. Download the Java 17 Installer {#2-download-the-java-17-installer} +## 2. Download the Java 21 Installer {#2-download-the-java-installer} -To install Java 17, you'll need to download the installer from [Adoptium](https://adoptium.net/en-GB/temurin/releases/?os=windows&package=jdk&version=17). +To install Java 21, you'll need to download the installer from [Adoptium](https://adoptium.net/en-GB/temurin/releases/?os=windows&package=jdk&version=21). You'll want to download the `Windows Installer (.msi)` version: @@ -43,18 +43,18 @@ The majority of modern computers will have a 64-bit operating system. If you are ## 3. Run the Installer! {#3-run-the-installer} -Follow the steps in the installer to install Java 17. When you reach this page, you should set the following features to "Entire feature will be installed on local hard drive": +Follow the steps in the installer to install Java 21. When you reach this page, you should set the following features to "Entire feature will be installed on local hard drive": - `Set JAVA_HOME environment variable` - This will be added to your PATH. - `JavaSoft (Oracle) registry keys` -![Java 17 installer with "Set JAVA_HOME variable" and "JavaSoft (Oracle) registry keys" highlighted](/assets/players/installing-java/windows-wizard-screenshot.png) +![Java 21 installer with "Set JAVA_HOME variable" and "JavaSoft (Oracle) registry keys" highlighted](/assets/players/installing-java/windows-wizard-screenshot.png) Once you've done that, you can click `Next` and continue with the installation. -## 4. Verify That Java 17 Is Installed {#4-verify-that-java-17-is-installed} +## 4. Verify That Java 21 Is Installed {#4-verify-that-java-is-installed} -Once the installation is complete, you can verify that Java 17 is installed by opening the command prompt again and typing `java -version`. +Once the installation is complete, you can verify that Java 21 is installed by opening the command prompt again and typing `java -version`. If the command runs successfully, you will see something like shown before, where the Java version is displayed: diff --git a/reference/1.20.4/build.gradle b/reference/1.20.4/build.gradle new file mode 100644 index 000000000..a5d601578 --- /dev/null +++ b/reference/1.20.4/build.gradle @@ -0,0 +1,9 @@ +def minecraftVersion = "1.20.4" +def yarnVersion = "1.20.4+build.3" +def fabricApiVersion = "0.92.0+1.20.4" + +dependencies { + minecraft "com.mojang:minecraft:${minecraftVersion}" + mappings "net.fabricmc:yarn:${yarnVersion}:v2" + modImplementation "net.fabricmc.fabric-api:fabric-api:${fabricApiVersion}" +} diff --git a/reference/1.20.4/src/client/java/com/example/docs/FabricDocsReferenceClient.java b/reference/1.20.4/src/client/java/com/example/docs/FabricDocsReferenceClient.java new file mode 100644 index 000000000..91de9418e --- /dev/null +++ b/reference/1.20.4/src/client/java/com/example/docs/FabricDocsReferenceClient.java @@ -0,0 +1,18 @@ +package com.example.docs; + +import net.minecraft.client.particle.EndRodParticle; + +import net.fabricmc.api.ClientModInitializer; +import net.fabricmc.fabric.api.client.particle.v1.ParticleFactoryRegistry; + +public class FabricDocsReferenceClient implements ClientModInitializer { + @Override + public void onInitializeClient() { + // This entrypoint is suitable for setting up client-specific logic, such as rendering. + + // #particle_register_client + // For this example, we will use the end rod particle behaviour. + ParticleFactoryRegistry.getInstance().register(FabricDocsReference.SPARKLE_PARTICLE, EndRodParticle.Factory::new); + // #particle_register_client + } +} diff --git a/reference/1.20.4/src/client/java/com/example/docs/client/command/FabricDocsReferenceClientCommands.java b/reference/1.20.4/src/client/java/com/example/docs/client/command/FabricDocsReferenceClientCommands.java new file mode 100644 index 000000000..2c43875d1 --- /dev/null +++ b/reference/1.20.4/src/client/java/com/example/docs/client/command/FabricDocsReferenceClientCommands.java @@ -0,0 +1,22 @@ +package com.example.docs.client.command; + +import net.minecraft.text.Text; + +import net.fabricmc.api.ClientModInitializer; +import net.fabricmc.fabric.api.client.command.v2.ClientCommandManager; +import net.fabricmc.fabric.api.client.command.v2.ClientCommandRegistrationCallback; + +// Class to contain all mod client command registrations. +public class FabricDocsReferenceClientCommands implements ClientModInitializer { + @Override + public void onInitializeClient() { + // :::1 + ClientCommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) -> { + dispatcher.register(ClientCommandManager.literal("clienttater").executes(context -> { + context.getSource().sendFeedback(Text.literal("Called /clienttater with no arguments.")); + return 1; + })); + }); + // :::1 + } +} diff --git a/reference/1.20.4/src/client/java/com/example/docs/mixin/client/ExampleClientMixin.java b/reference/1.20.4/src/client/java/com/example/docs/mixin/client/ExampleClientMixin.java new file mode 100644 index 000000000..4fd21eee5 --- /dev/null +++ b/reference/1.20.4/src/client/java/com/example/docs/mixin/client/ExampleClientMixin.java @@ -0,0 +1,16 @@ +package com.example.docs.mixin.client; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import net.minecraft.client.MinecraftClient; + +@Mixin(MinecraftClient.class) +public class ExampleClientMixin { + @Inject(at = @At("HEAD"), method = "run") + private void run(CallbackInfo info) { + // This code is injected into the start of MinecraftClient.run()V + } +} diff --git a/reference/1.20.4/src/client/java/com/example/docs/mixin/client/TitleScreenMixin.java b/reference/1.20.4/src/client/java/com/example/docs/mixin/client/TitleScreenMixin.java new file mode 100644 index 000000000..f8cf56721 --- /dev/null +++ b/reference/1.20.4/src/client/java/com/example/docs/mixin/client/TitleScreenMixin.java @@ -0,0 +1,27 @@ +package com.example.docs.mixin.client; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import net.minecraft.client.gui.screen.Screen; +import net.minecraft.client.gui.screen.TitleScreen; +import net.minecraft.client.gui.widget.ButtonWidget; +import net.minecraft.text.Text; + +import com.example.docs.rendering.DrawContextExampleScreen; +import com.example.docs.rendering.screens.CustomScreen; + +@Mixin(TitleScreen.class) +public class TitleScreenMixin extends Screen { + protected TitleScreenMixin(Text title) { + super(title); + } + + @Inject(method = "init", at = @At("TAIL"), cancellable = false) + private void addTestWidgets(CallbackInfo ci) { + this.addDrawableChild(ButtonWidget.builder(Text.of("DrawContext Test"), (btn) -> this.client.setScreen(new DrawContextExampleScreen())).dimensions(5, 5, 60, 20).build()); + this.addDrawableChild(ButtonWidget.builder(Text.of("CustomScreen 1"), (btn) -> this.client.setScreen(new CustomScreen(Text.empty()))).dimensions(5, 5+30, 60, 20).build()); + } +} diff --git a/reference/1.20.4/src/client/java/com/example/docs/rendering/DrawContextExampleScreen.java b/reference/1.20.4/src/client/java/com/example/docs/rendering/DrawContextExampleScreen.java new file mode 100644 index 000000000..833bdd88e --- /dev/null +++ b/reference/1.20.4/src/client/java/com/example/docs/rendering/DrawContextExampleScreen.java @@ -0,0 +1,75 @@ +package com.example.docs.rendering; + +import net.minecraft.client.gui.DrawContext; +import net.minecraft.client.gui.screen.Screen; +import net.minecraft.text.Text; +import net.minecraft.util.Identifier; + +public class DrawContextExampleScreen extends Screen { + public DrawContextExampleScreen() { + super(Text.empty()); + } + + @Override + public void render(DrawContext context, int mouseX, int mouseY, float delta) { + super.render(context, mouseX, mouseY, delta); + + // :::1 + int rectangleX = 10; + int rectangleY = 10; + int rectangleWidth = 100; + int rectangleHeight = 50; + // x1, y1, x2, y2, color + context.fill(rectangleX, rectangleY, rectangleX + rectangleWidth, rectangleY + rectangleHeight, 0xFF0000FF); + // :::1 + + // :::2 + // x, y, width, height, color + context.drawBorder(rectangleX, rectangleY, rectangleWidth, rectangleHeight, 0xFFFF0000); + // :::2 + + // :::3 + // Let's split the rectangle in half using a green line. + // x, y1, y2, color + context.drawVerticalLine(rectangleX + rectangleWidth / 2, rectangleY, rectangleY + rectangleHeight, 0xFF00FF00); + // :::3 + + // :::4 + // Let's create a scissor region that covers a middle bar section of the screen. + int scissorRegionX = 200; + int scissorRegionY = 20; + int scissorRegionWidth = 100; + + // The height of the scissor region is the height of the screen minus the height of the top and bottom bars. + int scissorRegionHeight = this.height - 40; + + // x1, y1, x2, y2 + context.enableScissor(scissorRegionX, scissorRegionY, scissorRegionX + scissorRegionWidth, scissorRegionY + scissorRegionHeight); + + // Let's fill the entire screen with a color gradient, it should only be visible in the scissor region. + // x1, y1, x2, y2, color1, color2 + context.fillGradient(0, 0, this.width, this.height, 0xFFFF0000, 0xFF0000FF); + + // Disable the scissor region. + context.disableScissor(); + // :::4 + + // :::5 + Identifier texture = new Identifier("minecraft", "textures/block/deepslate.png"); + // texture, x, y, u, v, width, height, textureWidth, textureHeight + context.drawTexture(texture, 90, 90, 0, 0, 16, 16, 16, 16); + // :::5 + + // :::6 + Identifier texture2 = new Identifier("fabric-docs-reference", "textures/gui/test-uv-drawing.png"); + int u = 10, v = 13, regionWidth = 14, regionHeight = 14; + // texture, x, y, width, height, u, v, regionWidth, regionHeight, textureWidth, textureHeight + context.drawTexture(texture2, 90, 190, 14, 14, u, v, regionWidth, regionHeight, 256, 256); + // :::6 + + // :::7 + // TextRenderer, text (string, or Text object), x, y, color, shadow + context.drawText(client.textRenderer, "Hello, world!", 10, 200, 0xFFFFFFFF, false); + // :::7 + } +} diff --git a/reference/1.20.4/src/client/java/com/example/docs/rendering/HudRenderingEntrypoint.java b/reference/1.20.4/src/client/java/com/example/docs/rendering/HudRenderingEntrypoint.java new file mode 100644 index 000000000..b645a5e3a --- /dev/null +++ b/reference/1.20.4/src/client/java/com/example/docs/rendering/HudRenderingEntrypoint.java @@ -0,0 +1,31 @@ +package com.example.docs.rendering; + +import net.minecraft.util.math.ColorHelper; +import net.minecraft.util.math.MathHelper; + +import net.fabricmc.api.ClientModInitializer; +import net.fabricmc.fabric.api.client.rendering.v1.HudRenderCallback; + +public class HudRenderingEntrypoint implements ClientModInitializer { + private float totalTickDelta = 0.0F; + @Override + public void onInitializeClient() { + // :::1 + HudRenderCallback.EVENT.register((context, tickDelta) -> { + int color = 0xFFFF0000; // Red + int targetColor = 0xFF00FF00; // Green + + // Total tick delta is stored in a field, so we can use it later. + totalTickDelta += tickDelta; + + // "lerp" simply means "linear interpolation", which is a fancy way of saying "blend". + float lerpedAmount = MathHelper.abs(MathHelper.sin(totalTickDelta / 50F)); + int lerpedColor = ColorHelper.Argb.lerp(lerpedAmount, color, targetColor); + + // Draw a square with the lerped color. + // x1, x2, y1, y2, z, color + context.fill(0, 0, 100, 100, 0, lerpedColor); + }); + // :::1 + } +} diff --git a/reference/1.20.4/src/client/java/com/example/docs/rendering/RenderingConceptsEntrypoint.java b/reference/1.20.4/src/client/java/com/example/docs/rendering/RenderingConceptsEntrypoint.java new file mode 100644 index 000000000..415df486b --- /dev/null +++ b/reference/1.20.4/src/client/java/com/example/docs/rendering/RenderingConceptsEntrypoint.java @@ -0,0 +1,93 @@ +package com.example.docs.rendering; + +import com.mojang.blaze3d.systems.RenderSystem; +import org.joml.Matrix4f; + +import net.minecraft.client.render.BufferBuilder; +import net.minecraft.client.render.GameRenderer; +import net.minecraft.client.render.Tessellator; +import net.minecraft.client.render.VertexFormat; +import net.minecraft.client.render.VertexFormats; +import net.minecraft.client.util.math.MatrixStack; +import net.minecraft.util.math.MathHelper; +import net.minecraft.util.math.RotationAxis; + +import net.fabricmc.api.ClientModInitializer; +import net.fabricmc.fabric.api.client.rendering.v1.HudRenderCallback; + +public class RenderingConceptsEntrypoint implements ClientModInitializer { + public float totalTickDelta = 0F; + + @Override + public void onInitializeClient() { + // "A Practical Example: Rendering a Triangle Strip" + // :::1 + HudRenderCallback.EVENT.register((drawContext, tickDelta) -> { + // :::1 + if (true) { + return; + } + + // :::2 + MatrixStack matrices = drawContext.getMatrices(); + + // Store the total tick delta in a field, so we can use it later. + totalTickDelta += tickDelta; + + // Push a new matrix onto the stack. + matrices.push(); + // :::2 + // :::1 + // Get the transformation matrix from the matrix stack, alongside the tessellator instance and a new buffer builder. + Matrix4f transformationMatrix = drawContext.getMatrices().peek().getPositionMatrix(); + Tessellator tessellator = Tessellator.getInstance(); + BufferBuilder buffer = tessellator.getBuffer(); + + // :::1 + // :::2 + // Scale the matrix by 0.5 to make the triangle smaller and larger over time. + float scaleAmount = MathHelper.sin(totalTickDelta / 10F) / 2F + 1.5F; + + // Apply the scaling amount to the matrix. + // We don't need to scale the Z axis since it's on the HUD and 2D. + matrices.scale(scaleAmount, scaleAmount, 1F); + // :::2 + matrices.scale(1 / scaleAmount, 1 / scaleAmount, 1F); + matrices.translate(60f, 60f, 0f); + // :::3 + // Lerp between 0 and 360 degrees over time. + float rotationAmount = (float) (totalTickDelta / 50F % 360); + matrices.multiply(RotationAxis.POSITIVE_Z.rotation(rotationAmount)); + // Shift entire diamond so that it rotates in its center. + matrices.translate(-20f, -40f, 0f); + // :::3 + + // :::1 + // Initialize the buffer using the specified format and draw mode. + buffer.begin(VertexFormat.DrawMode.TRIANGLE_STRIP, VertexFormats.POSITION_COLOR); + + // Write our vertices, Z doesn't really matter since it's on the HUD. + buffer.vertex(transformationMatrix, 20, 20, 5).color(0xFF414141).next(); + buffer.vertex(transformationMatrix, 5, 40, 5).color(0xFF000000).next(); + buffer.vertex(transformationMatrix, 35, 40, 5).color(0xFF000000).next(); + buffer.vertex(transformationMatrix, 20, 60, 5).color(0xFF414141).next(); + + // We'll get to this bit in the next section. + RenderSystem.setShader(GameRenderer::getPositionColorProgram); + RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F); + + // Draw the buffer onto the screen. + tessellator.draw(); + // :::1 + // :::2 + + // ... write to the buffer. + + // Pop our matrix from the stack. + matrices.pop(); + // :::2 + // :::1 + }); + // :::1 + } +} diff --git a/reference/1.20.4/src/client/java/com/example/docs/rendering/TextTests.java b/reference/1.20.4/src/client/java/com/example/docs/rendering/TextTests.java new file mode 100644 index 000000000..036207d27 --- /dev/null +++ b/reference/1.20.4/src/client/java/com/example/docs/rendering/TextTests.java @@ -0,0 +1,18 @@ +package com.example.docs.rendering; + +import net.minecraft.text.MutableText; +import net.minecraft.text.Text; + +public class TextTests { + public void test() { + // :::1 + MutableText mutable = Text.translatable("my_mod.text.bye"); + String json = Text.Serialization.toJsonString(mutable); + // :::1 + + // :::2 + String jsonString = Text.Serialization.toJsonString(mutable); + MutableText deserialized = Text.Serialization.fromJson(jsonString); + // :::2 + } +} diff --git a/reference/1.20.4/src/client/java/com/example/docs/rendering/screens/CustomScreen.java b/reference/1.20.4/src/client/java/com/example/docs/rendering/screens/CustomScreen.java new file mode 100644 index 000000000..02e0d76cd --- /dev/null +++ b/reference/1.20.4/src/client/java/com/example/docs/rendering/screens/CustomScreen.java @@ -0,0 +1,65 @@ +package com.example.docs.rendering.screens; + +import net.minecraft.client.gui.DrawContext; +import net.minecraft.client.gui.screen.Screen; +import net.minecraft.client.gui.widget.ButtonWidget; +import net.minecraft.client.toast.SystemToast; +import net.minecraft.text.Text; + +// :::1 +public class CustomScreen extends Screen { + // :::1 + // :::2 + public Screen parent; + public CustomScreen(Text title, Screen parent) { + super(title); + this.parent = parent; + } + + @Override + public void close() { + this.client.setScreen(this.parent); + } + + // :::2 + public CustomScreen(Text title) { + super(title); + } + + @Override + protected void init() { + ButtonWidget buttonWidget = ButtonWidget.builder(Text.of("Hello World"), (btn) -> { + // When the button is clicked, we can display a toast to the screen. + this.client.getToastManager().add( + SystemToast.create(this.client, SystemToast.Type.NARRATOR_TOGGLE, Text.of("Hello World!"), Text.of("This is a toast.")) + ); + }).dimensions(40, 40, 120, 20).build(); + // x, y, width, height + // It's recommended to use the fixed height of 20 to prevent rendering issues with the button + // textures. + + // Register the button widget. + this.addDrawableChild(buttonWidget); + + // :::1 + // :::3 + // Add a custom widget to the screen. + // x, y, width, height + CustomWidget customWidget = new CustomWidget(40, 80, 120, 20); + this.addDrawableChild(customWidget); + // :::3 + // :::1 + } + + @Override + public void render(DrawContext context, int mouseX, int mouseY, float delta) { + super.render(context, mouseX, mouseY, delta); + + // Minecraft doesn't have a "label" widget, so we'll have to draw our own text. + // We'll subtract the font height from the Y position to make the text appear above the button. + // Subtracting an extra 10 pixels will give the text some padding. + // textRenderer, text, x, y, color, hasShadow + context.drawText(this.textRenderer, "Special Button", 40, 40 - this.textRenderer.fontHeight - 10, 0xFFFFFFFF, true); + } +} +// :::1 diff --git a/reference/1.20.4/src/client/java/com/example/docs/rendering/screens/CustomWidget.java b/reference/1.20.4/src/client/java/com/example/docs/rendering/screens/CustomWidget.java new file mode 100644 index 000000000..c5c24e275 --- /dev/null +++ b/reference/1.20.4/src/client/java/com/example/docs/rendering/screens/CustomWidget.java @@ -0,0 +1,40 @@ +package com.example.docs.rendering.screens; + +import net.minecraft.client.gui.DrawContext; +import net.minecraft.client.gui.screen.narration.NarrationMessageBuilder; +import net.minecraft.client.gui.widget.ClickableWidget; +import net.minecraft.text.Text; + +// :::1 +public class CustomWidget extends ClickableWidget { + public CustomWidget(int x, int y, int width, int height) { + super(x, y, width, height, Text.empty()); + } + + @Override + protected void renderWidget(DrawContext context, int mouseX, int mouseY, float delta) { + // We'll just draw a simple rectangle for now. + // x1, y1, x2, y2, startColor, endColor + int startColor = 0xFF00FF00; // Green + int endColor = 0xFF0000FF; // Blue + + // :::1 + // :::2 + // This is in the "renderWidget" method, so we can check if the mouse is hovering over the widget. + if (isHovered()) { + startColor = 0xFFFF0000; // Red + endColor = 0xFF00FFFF; // Cyan + } + + // :::2 + // :::1 + context.fillGradient(getX(), getY(), getX() + this.width, getY() + this.height, startColor, endColor); + } + + @Override + protected void appendClickableNarrations(NarrationMessageBuilder builder) { + // For brevity, we'll just skip this for now - if you want to add narration to your widget, you can do so here. + return; + } +} +// :::1 diff --git a/reference/1.20.4/src/client/resources/fabric-docs-reference.client.mixins.json b/reference/1.20.4/src/client/resources/fabric-docs-reference.client.mixins.json new file mode 100644 index 000000000..ea40afa34 --- /dev/null +++ b/reference/1.20.4/src/client/resources/fabric-docs-reference.client.mixins.json @@ -0,0 +1,12 @@ +{ + "required": true, + "package": "com.example.docs.mixin.client", + "compatibilityLevel": "JAVA_17", + "client": [ + "ExampleClientMixin", + "TitleScreenMixin" + ], + "injectors": { + "defaultRequire": 1 + } +} \ No newline at end of file diff --git a/reference/1.20.4/src/main/generated/data/fabric-docs-reference/damage_type/tater.json b/reference/1.20.4/src/main/generated/data/fabric-docs-reference/damage_type/tater.json new file mode 100644 index 000000000..e02cf9daa --- /dev/null +++ b/reference/1.20.4/src/main/generated/data/fabric-docs-reference/damage_type/tater.json @@ -0,0 +1,5 @@ +{ + "exhaustion": 0.1, + "message_id": "tater", + "scaling": "when_caused_by_living_non_player" +} \ No newline at end of file diff --git a/reference/1.20.4/src/main/generated/data/minecraft/tags/damage_type/bypasses_armor.json b/reference/1.20.4/src/main/generated/data/minecraft/tags/damage_type/bypasses_armor.json new file mode 100644 index 000000000..a257e3648 --- /dev/null +++ b/reference/1.20.4/src/main/generated/data/minecraft/tags/damage_type/bypasses_armor.json @@ -0,0 +1,6 @@ +{ + "replace": false, + "values": [ + "fabric-docs-reference:tater" + ] +} \ No newline at end of file diff --git a/reference/1.20.4/src/main/java/com/example/docs/FabricDocsReference.java b/reference/1.20.4/src/main/java/com/example/docs/FabricDocsReference.java new file mode 100644 index 000000000..86ea5a4b1 --- /dev/null +++ b/reference/1.20.4/src/main/java/com/example/docs/FabricDocsReference.java @@ -0,0 +1,44 @@ +package com.example.docs; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.minecraft.particle.DefaultParticleType; +import net.minecraft.registry.Registries; +import net.minecraft.registry.Registry; +import net.minecraft.util.Identifier; + +import net.fabricmc.api.ModInitializer; +import net.fabricmc.fabric.api.particle.v1.FabricParticleTypes; + +//#entrypoint +public class FabricDocsReference implements ModInitializer { + // This logger is used to write text to the console and the log file. + // It is considered best practice to use your mod id as the logger's name. + // That way, it's clear which mod wrote info, warnings, and errors. + public static final String MOD_ID = "fabric-docs-reference"; + public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID); + + //#entrypoint + //#particle_register_main + // This DefaultParticleType gets called when you want to use your particle in code. + public static final DefaultParticleType SPARKLE_PARTICLE = FabricParticleTypes.simple(); + + //#particle_register_main + //#entrypoint + @Override + public void onInitialize() { + // This code runs as soon as Minecraft is in a mod-load-ready state. + // However, some things (like resources) may still be uninitialized. + // Proceed with mild caution. + + LOGGER.info("Hello Fabric world!"); + //#entrypoint + + //#particle_register_main + // Register our custom particle type in the mod initializer. + Registry.register(Registries.PARTICLE_TYPE, new Identifier(MOD_ID, "sparkle_particle"), SPARKLE_PARTICLE); + //#particle_register_main + //#entrypoint + } +} diff --git a/reference/1.20.4/src/main/java/com/example/docs/FabricDocsReferenceDataGenerator.java b/reference/1.20.4/src/main/java/com/example/docs/FabricDocsReferenceDataGenerator.java new file mode 100644 index 000000000..3d224db49 --- /dev/null +++ b/reference/1.20.4/src/main/java/com/example/docs/FabricDocsReferenceDataGenerator.java @@ -0,0 +1,10 @@ +package com.example.docs; + +import net.fabricmc.fabric.api.datagen.v1.DataGeneratorEntrypoint; +import net.fabricmc.fabric.api.datagen.v1.FabricDataGenerator; + +public class FabricDocsReferenceDataGenerator implements DataGeneratorEntrypoint { + @Override + public void onInitializeDataGenerator(FabricDataGenerator fabricDataGenerator) { + } +} diff --git a/reference/1.20.4/src/main/java/com/example/docs/block/FabricDocsReferenceBlocks.java b/reference/1.20.4/src/main/java/com/example/docs/block/FabricDocsReferenceBlocks.java new file mode 100644 index 000000000..9cec4e4ff --- /dev/null +++ b/reference/1.20.4/src/main/java/com/example/docs/block/FabricDocsReferenceBlocks.java @@ -0,0 +1,12 @@ +package com.example.docs.block; + +import net.fabricmc.api.ModInitializer; + +// :::1 +public class FabricDocsReferenceBlocks implements ModInitializer { + @Override + public void onInitialize() { + ModBlocks.initialize(); + } +} +// :::1 diff --git a/reference/1.20.4/src/main/java/com/example/docs/block/ModBlocks.java b/reference/1.20.4/src/main/java/com/example/docs/block/ModBlocks.java new file mode 100644 index 000000000..599018e2c --- /dev/null +++ b/reference/1.20.4/src/main/java/com/example/docs/block/ModBlocks.java @@ -0,0 +1,78 @@ +package com.example.docs.block; + +import net.minecraft.block.AbstractBlock; +import net.minecraft.block.Block; +import net.minecraft.block.PillarBlock; +import net.minecraft.item.BlockItem; +import net.minecraft.item.Item; +import net.minecraft.registry.Registries; +import net.minecraft.registry.Registry; +import net.minecraft.sound.BlockSoundGroup; +import net.minecraft.util.Identifier; + +import net.fabricmc.fabric.api.itemgroup.v1.ItemGroupEvents; + +import com.example.docs.FabricDocsReference; +import com.example.docs.block.custom.PrismarineLampBlock; +import com.example.docs.item.ModItems; + +// :::1 +public class ModBlocks { + // :::1 + + // :::2 + public static final Block CONDENSED_DIRT = register( + new Block(AbstractBlock.Settings.create().sounds(BlockSoundGroup.GRASS)), + "condensed_dirt", + true + ); + // :::2 + // :::3 + public static final Block CONDENSED_OAK_LOG = register( + new PillarBlock( + AbstractBlock.Settings.create() + .sounds(BlockSoundGroup.WOOD) + ), "condensed_oak_log", true + ); + // :::3 + // :::4 + public static final Block PRISMARINE_LAMP = register( + new PrismarineLampBlock( + AbstractBlock.Settings.create() + .sounds(BlockSoundGroup.LANTERN) + .luminance(PrismarineLampBlock::getLuminance) + ), "prismarine_lamp", true + ); + // :::4 + // :::1 + public static Block register(Block block, String name, boolean shouldRegisterItem) { + // Register the block and its item. + Identifier id = new Identifier(FabricDocsReference.MOD_ID, name); + + // Sometimes, you may not want to register an item for the block. + // Eg: if it's a technical block like `minecraft:air` or `minecraft:end_gateway` + if (shouldRegisterItem) { + BlockItem blockItem = new BlockItem(block, new Item.Settings()); + Registry.register(Registries.ITEM, id, blockItem); + } + + return Registry.register(Registries.BLOCK, id, block); + } + + // :::1 + public static void initialize() { + // :::3 + ItemGroupEvents.modifyEntriesEvent(ModItems.CUSTOM_ITEM_GROUP_KEY).register((itemGroup) -> { + itemGroup.add(ModBlocks.CONDENSED_DIRT.asItem()); + }); + // :::3 + + ItemGroupEvents.modifyEntriesEvent(ModItems.CUSTOM_ITEM_GROUP_KEY).register((itemGroup) -> { + itemGroup.add(ModBlocks.CONDENSED_OAK_LOG.asItem()); + itemGroup.add(ModBlocks.PRISMARINE_LAMP.asItem()); + }); + }; + + // :::1 +} +// :::1 diff --git a/reference/1.20.4/src/main/java/com/example/docs/block/custom/PrismarineLampBlock.java b/reference/1.20.4/src/main/java/com/example/docs/block/custom/PrismarineLampBlock.java new file mode 100644 index 000000000..b81112be3 --- /dev/null +++ b/reference/1.20.4/src/main/java/com/example/docs/block/custom/PrismarineLampBlock.java @@ -0,0 +1,70 @@ +package com.example.docs.block.custom; + +import net.minecraft.block.Block; +import net.minecraft.block.BlockState; +import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.sound.SoundCategory; +import net.minecraft.sound.SoundEvents; +import net.minecraft.state.StateManager; +import net.minecraft.state.property.BooleanProperty; +import net.minecraft.util.ActionResult; +import net.minecraft.util.Hand; +import net.minecraft.util.hit.BlockHitResult; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; + +// :::1 +public class PrismarineLampBlock extends Block { + public static final BooleanProperty ACTIVATED = BooleanProperty.of("activated"); + + // :::1 + // :::3 + public PrismarineLampBlock(Settings settings) { + super(settings); + + // Set the default state of the block to be deactivated. + setDefaultState(getDefaultState().with(ACTIVATED, false)); + } + + // :::3 + // :::2 + @Override + protected void appendProperties(StateManager.Builder builder) { + builder.add(ACTIVATED); + } + + // :::2 + // :::4 + @Override + public ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) { + if (!player.getAbilities().allowModifyWorld) { + // Skip if the player isn't allowed to modify the world. + return ActionResult.PASS; + } else { + // Get the current value of the "activated" property + boolean activated = state.get(ACTIVATED); + + // Flip the value of activated and save the new blockstate. + world.setBlockState(pos, state.with(ACTIVATED, !activated)); + + // Play a click sound to emphasise the interaction. + world.playSound(player, pos, SoundEvents.BLOCK_COMPARATOR_CLICK, SoundCategory.BLOCKS, 1.0F, 1.0F); + + return ActionResult.SUCCESS; + } + } + + // :::4 + // :::5 + public static int getLuminance(BlockState currentBlockState) { + // Get the value of the "activated" property. + boolean activated = currentBlockState.get(PrismarineLampBlock.ACTIVATED); + + // Return a light level if activated = true + return activated ? 15 : 0; + } + + // :::5 + // :::1 +} +// :::1 diff --git a/reference/1.20.4/src/main/java/com/example/docs/codec/Bean.java b/reference/1.20.4/src/main/java/com/example/docs/codec/Bean.java new file mode 100644 index 000000000..f02a5f35d --- /dev/null +++ b/reference/1.20.4/src/main/java/com/example/docs/codec/Bean.java @@ -0,0 +1,8 @@ +package com.example.docs.codec; + +// ::: +// The abstract type we want to create a codec for +public interface Bean { + BeanType getType(); +} +// ::: diff --git a/reference/1.20.4/src/main/java/com/example/docs/codec/BeanType.java b/reference/1.20.4/src/main/java/com/example/docs/codec/BeanType.java new file mode 100644 index 000000000..2e75bf8bf --- /dev/null +++ b/reference/1.20.4/src/main/java/com/example/docs/codec/BeanType.java @@ -0,0 +1,19 @@ +package com.example.docs.codec; + +import com.mojang.serialization.Codec; +import com.mojang.serialization.Lifecycle; + +import net.minecraft.registry.Registry; +import net.minecraft.registry.RegistryKey; +import net.minecraft.registry.SimpleRegistry; +import net.minecraft.util.Identifier; + +// ::: +// A record to keep information relating to a specific +// subclass of Bean, in this case only holding a Codec. +public record BeanType(Codec codec) { + // Create a registry to map identifiers to bean types + public static final Registry> REGISTRY = new SimpleRegistry<>( + RegistryKey.ofRegistry(new Identifier("example", "bean_types")), Lifecycle.stable()); +} +// ::: diff --git a/reference/1.20.4/src/main/java/com/example/docs/codec/BeanTypes.java b/reference/1.20.4/src/main/java/com/example/docs/codec/BeanTypes.java new file mode 100644 index 000000000..c1cc08d30 --- /dev/null +++ b/reference/1.20.4/src/main/java/com/example/docs/codec/BeanTypes.java @@ -0,0 +1,18 @@ +package com.example.docs.codec; + +import net.minecraft.registry.Registry; +import net.minecraft.util.Identifier; + +// ::: +// An empty class to hold static references to all BeanTypes +public class BeanTypes { + // Make sure to register the bean types and leave them accessible to + // the getType method in their respective subclasses. + public static final BeanType STRINGY_BEAN = register("stringy_bean", new BeanType<>(StringyBean.CODEC)); + public static final BeanType COUNTING_BEAN = register("counting_bean", new BeanType<>(CountingBean.CODEC)); + + public static BeanType register(String id, BeanType beanType) { + return Registry.register(BeanType.REGISTRY, new Identifier("example", id), beanType); + } +} +// ::: diff --git a/reference/1.20.4/src/main/java/com/example/docs/codec/CountingBean.java b/reference/1.20.4/src/main/java/com/example/docs/codec/CountingBean.java new file mode 100644 index 000000000..e6b33f437 --- /dev/null +++ b/reference/1.20.4/src/main/java/com/example/docs/codec/CountingBean.java @@ -0,0 +1,31 @@ +package com.example.docs.codec; + +import com.mojang.serialization.Codec; +import com.mojang.serialization.codecs.RecordCodecBuilder; + +// ::: +// Another implementation +public class CountingBean implements Bean { + public static final Codec CODEC = RecordCodecBuilder.create(instance -> instance.group( + Codec.INT.fieldOf("counting_number").forGetter(CountingBean::getCountingNumber) + ).apply(instance, CountingBean::new)); + + private int countingNumber; + // ::: + + public CountingBean(int countingNumber) { + this.countingNumber = countingNumber; + } + + public int getCountingNumber() { + return countingNumber; + } + + // ::: + + @Override + public BeanType getType() { + return BeanTypes.COUNTING_BEAN; + } +} +// ::: diff --git a/reference/1.20.4/src/main/java/com/example/docs/codec/StringyBean.java b/reference/1.20.4/src/main/java/com/example/docs/codec/StringyBean.java new file mode 100644 index 000000000..be1f64e71 --- /dev/null +++ b/reference/1.20.4/src/main/java/com/example/docs/codec/StringyBean.java @@ -0,0 +1,33 @@ +package com.example.docs.codec; + +import com.mojang.serialization.Codec; +import com.mojang.serialization.codecs.RecordCodecBuilder; + +// ::: +// An implementing class of Bean, with its own codec. +public class StringyBean implements Bean { + public static final Codec CODEC = RecordCodecBuilder.create(instance -> instance.group( + Codec.STRING.fieldOf("stringy_string").forGetter(StringyBean::getStringyString) + ).apply(instance, StringyBean::new)); + + private String stringyString; + // ::: + + public StringyBean(String stringyString) { + this.stringyString = stringyString; + } + + public String getStringyString() { + return stringyString; + } + + // ::: + + // It is important to be able to retrieve the + // BeanType of a Bean from it's instance. + @Override + public BeanType getType() { + return BeanTypes.STRINGY_BEAN; + } +} +// ::: diff --git a/reference/1.20.4/src/main/java/com/example/docs/command/BlockPosArgumentType.java b/reference/1.20.4/src/main/java/com/example/docs/command/BlockPosArgumentType.java new file mode 100644 index 000000000..bcf1b69a9 --- /dev/null +++ b/reference/1.20.4/src/main/java/com/example/docs/command/BlockPosArgumentType.java @@ -0,0 +1,40 @@ +package com.example.docs.command; + +import com.mojang.brigadier.StringReader; +import com.mojang.brigadier.arguments.ArgumentType; +import com.mojang.brigadier.exceptions.CommandSyntaxException; + +import net.minecraft.util.math.BlockPos; + +// :::1 +public class BlockPosArgumentType implements ArgumentType { + /** + * Parse the BlockPos from the reader in the {x, y, z} format. + */ + @Override + public BlockPos parse(StringReader reader) throws CommandSyntaxException { + try { + // This requires the argument to be surrounded by quotation marks. + // eg: "{1, 2, 3}" + String string = reader.readString(); + + // Remove the { and } from the string using regex. + string = string.replace("{", "").replace("}", ""); + + // Split the string into the x, y, and z values. + String[] split = string.split(","); + + // Parse the x, y, and z values from the split string. + int x = Integer.parseInt(split[0].trim()); + int y = Integer.parseInt(split[1].trim()); + int z = Integer.parseInt(split[2].trim()); + + // Return the BlockPos. + return new BlockPos(x, y, z); + } catch (Exception e) { + // Throw an exception if anything fails inside the try block. + throw CommandSyntaxException.BUILT_IN_EXCEPTIONS.dispatcherParseException().create("Invalid BlockPos format. Expected {x, y, z}"); + } + } +} +// :::1 diff --git a/reference/1.20.4/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java b/reference/1.20.4/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java new file mode 100644 index 000000000..10b2ef0c9 --- /dev/null +++ b/reference/1.20.4/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java @@ -0,0 +1,210 @@ +package com.example.docs.command; + +import com.mojang.brigadier.arguments.IntegerArgumentType; +import com.mojang.brigadier.context.CommandContext; + +import net.minecraft.command.argument.EntityArgumentType; +import net.minecraft.command.argument.serialize.ConstantArgumentSerializer; +import net.minecraft.command.suggestion.SuggestionProviders; +import net.minecraft.entity.EntityType; +import net.minecraft.server.command.CommandManager; +import net.minecraft.server.command.ServerCommandSource; +import net.minecraft.text.Text; +import net.minecraft.util.Identifier; +import net.minecraft.util.math.BlockPos; + +import net.fabricmc.api.ModInitializer; +import net.fabricmc.fabric.api.command.v2.ArgumentTypeRegistry; +import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback; + +// Class to contain all mod command registrations. +public class FabricDocsReferenceCommands implements ModInitializer { + @Override + public void onInitialize() { + // :::_1 + CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> { + dispatcher.register(CommandManager.literal("tater").executes(context -> { + context.getSource().sendFeedback(() -> Text.literal("Called /tater with no arguments."), false); + return 1; + })); + }); + // :::_1 + + // :::11 + ArgumentTypeRegistry.registerArgumentType( + new Identifier("fabric-docs", "block_pos"), + BlockPosArgumentType.class, + ConstantArgumentSerializer.of(BlockPosArgumentType::new) + ); + // :::11 + + // :::2 + CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> { + if (environment.dedicated) { + dispatcher.register(CommandManager.literal("dedicatedtater").executes(context -> { + context.getSource() + .sendFeedback(() -> Text.literal("Called /dedicatedtater with no arguments."), false); + return 1; + })); + } + }); + // :::2 + + // :::3 + CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> { + dispatcher.register(CommandManager.literal("requiredtater") + .requires(source -> source.hasPermissionLevel(1)) + .executes(context -> { + context.getSource() + .sendFeedback(() -> Text.literal("Called /requiredtater with no arguments."), false); + return 1; + })); + }); + // :::3 + + // :::4 + CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> { + dispatcher.register(CommandManager.literal("argtater1") + .then(CommandManager.argument("value", IntegerArgumentType.integer()) + .executes(context -> { + int value = IntegerArgumentType.getInteger(context, "value"); + context.getSource() + .sendFeedback( + () -> Text.literal( + "Called /argtater1 with value = %s".formatted(value)), + false); + return 1; + }))); + }); + // :::4 + + // :::5 + CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> { + dispatcher.register(CommandManager.literal("argtater2") + .then(CommandManager.argument("value1", IntegerArgumentType.integer()) + .executes(context -> { + int value1 = IntegerArgumentType.getInteger(context, "value1"); + context.getSource() + .sendFeedback( + () -> Text.literal( + "Called /argtater2 with value 1 = %s".formatted(value1)), + false); + return 1; + }) + .then(CommandManager.argument("value2", IntegerArgumentType.integer()) + .executes(context -> { + int value1 = IntegerArgumentType.getInteger(context, "value1"); + int value2 = IntegerArgumentType.getInteger(context, "value2"); + context.getSource() + .sendFeedback( + () -> Text.literal( + "Called /argtater2 with value 1 = %s and value 2 = %s" + .formatted(value1, value2)), + false); + return 1; + })))); + }); + // :::5 + + // :::6 + CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> { + dispatcher.register(CommandManager.literal("argtater3") + .then(CommandManager.argument("value1", IntegerArgumentType.integer()) + .executes(context -> + printValues(IntegerArgumentType.getInteger(context, "value1"), 0, context)) + .then(CommandManager.argument("value2", IntegerArgumentType.integer()) + .executes(context -> printValues( + IntegerArgumentType.getInteger(context, "value1"), + IntegerArgumentType.getInteger(context, "value2"), + context))))); + }); + // :::6 + + // :::7 + CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> { + dispatcher.register(CommandManager.literal("subtater1") + .then(CommandManager.literal("subcommand").executes(context -> { + context.getSource() + .sendFeedback( + () -> Text.literal("Called /subtater1 subcommand with no arguments."), false); + return 1; + }))); + }); + // :::7 + + // :::8 + CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> { + dispatcher.register(CommandManager.literal("subtater2") + .executes(context -> { + context.getSource() + .sendFeedback(() -> Text.literal("Called /subtater2 with no arguments."), false); + return 1; + }) + .then(CommandManager.literal("subcommand").executes(context -> { + context.getSource() + .sendFeedback( + () -> Text.literal("Called /subtater2 subcommand with no arguments."), false); + return 1; + }))); + }); + // :::8 + + // :::9 + CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> { + dispatcher.register(CommandManager.literal("entity_name").then( + CommandManager.argument("entity", EntityArgumentType.entity()) + .suggests(SuggestionProviders.SUMMONABLE_ENTITIES) + .executes(context -> { + EntityType entityType = EntityArgumentType.getEntity(context, "entity").getType(); + context.getSource().sendFeedback( + () -> Text.literal("Called /subtater2 with entity: ") + .append( + Text.translatable(entityType.getTranslationKey()) + ), + false); + return 1; + }) + )); + }); + // :::9 + + // :::10 + CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> { + dispatcher.register(CommandManager.literal("parse_pos").then( + CommandManager.argument("pos", new BlockPosArgumentType()) + .executes(context -> { + BlockPos arg = context.getArgument("pos", BlockPos.class); + context.getSource().sendFeedback( + () -> Text.literal("Called /parse_pos with BlockPos: ") + .append(Text.of(arg.toString())), + false); + return 1; + }) + )); + }); + // :::10 + + // :::12 + CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> { + final var taterCommandNode = dispatcher.register(CommandManager.literal("tater4").executes(context -> { + context.getSource().sendFeedback(() -> Text.literal("Called /tater4 with no arguments."), false); + return 1; + })); + dispatcher.register(CommandManager.literal("redirect_potato").redirect(taterCommandNode)); + }); + // :::12 + } + + // :::6 + + private static int printValues(int value1, int value2, CommandContext context) { + context.getSource() + .sendFeedback( + () -> Text.literal( + "Called /argtater3 with value 1 = %s and value 2 = %s".formatted(value1, value2)), + false); + return 1; + } + + // :::6 +} diff --git a/reference/1.20.4/src/main/java/com/example/docs/command/PlayerSuggestionProvider.java b/reference/1.20.4/src/main/java/com/example/docs/command/PlayerSuggestionProvider.java new file mode 100644 index 000000000..202871674 --- /dev/null +++ b/reference/1.20.4/src/main/java/com/example/docs/command/PlayerSuggestionProvider.java @@ -0,0 +1,32 @@ +package com.example.docs.command; + +import java.util.Collection; +import java.util.concurrent.CompletableFuture; + +import com.mojang.brigadier.context.CommandContext; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import com.mojang.brigadier.suggestion.SuggestionProvider; +import com.mojang.brigadier.suggestion.Suggestions; +import com.mojang.brigadier.suggestion.SuggestionsBuilder; + +import net.minecraft.server.command.ServerCommandSource; + +// :::1 +public class PlayerSuggestionProvider implements SuggestionProvider { + @Override + public CompletableFuture getSuggestions(CommandContext context, SuggestionsBuilder builder) throws CommandSyntaxException { + ServerCommandSource source = context.getSource(); + + // Thankfully, the ServerCommandSource has a method to get a list of player names. + Collection playerNames = source.getPlayerNames(); + + // Add all player names to the builder. + for (String playerName : playerNames) { + builder.suggest(playerName); + } + + // Lock the suggestions after we've modified them. + return builder.buildFuture(); + } +} +// :::1 diff --git a/reference/1.20.4/src/main/java/com/example/docs/damage/FabricDocsReferenceDamageTypes.java b/reference/1.20.4/src/main/java/com/example/docs/damage/FabricDocsReferenceDamageTypes.java new file mode 100644 index 000000000..5bb8b9bf9 --- /dev/null +++ b/reference/1.20.4/src/main/java/com/example/docs/damage/FabricDocsReferenceDamageTypes.java @@ -0,0 +1,27 @@ +package com.example.docs.damage; + +import net.minecraft.block.AbstractBlock; +import net.minecraft.block.Block; +import net.minecraft.entity.damage.DamageType; +import net.minecraft.item.BlockItem; +import net.minecraft.item.Item; +import net.minecraft.registry.Registries; +import net.minecraft.registry.Registry; +import net.minecraft.registry.RegistryKey; +import net.minecraft.registry.RegistryKeys; +import net.minecraft.util.Identifier; + +import net.fabricmc.api.ModInitializer; + +public class FabricDocsReferenceDamageTypes implements ModInitializer { + public static final Block TATER_BLOCK = new TaterBlock(AbstractBlock.Settings.create()); + // :::1 + public static final RegistryKey TATER_DAMAGE = RegistryKey.of(RegistryKeys.DAMAGE_TYPE, new Identifier("fabric-docs-reference", "tater")); + // :::1 + + @Override + public void onInitialize() { + Registry.register(Registries.BLOCK, new Identifier("fabric-docs-reference", "tater"), TATER_BLOCK); + Registry.register(Registries.ITEM, new Identifier("fabric-docs-reference", "tater"), new BlockItem(TATER_BLOCK, new Item.Settings())); + } +} diff --git a/reference/1.20.4/src/main/java/com/example/docs/damage/FabricDocsReferenceDamageTypesDataGenerator.java b/reference/1.20.4/src/main/java/com/example/docs/damage/FabricDocsReferenceDamageTypesDataGenerator.java new file mode 100644 index 000000000..32466d71c --- /dev/null +++ b/reference/1.20.4/src/main/java/com/example/docs/damage/FabricDocsReferenceDamageTypesDataGenerator.java @@ -0,0 +1,75 @@ +package com.example.docs.damage; + +import java.util.concurrent.CompletableFuture; + +import com.google.gson.JsonObject; + +import net.minecraft.data.DataOutput; +import net.minecraft.data.DataProvider; +import net.minecraft.data.DataWriter; +import net.minecraft.entity.damage.DamageScaling; +import net.minecraft.entity.damage.DamageType; +import net.minecraft.registry.RegistryBuilder; +import net.minecraft.registry.RegistryKeys; +import net.minecraft.registry.RegistryWrapper; +import net.minecraft.registry.tag.TagKey; +import net.minecraft.util.Identifier; + +import net.fabricmc.fabric.api.datagen.v1.DataGeneratorEntrypoint; +import net.fabricmc.fabric.api.datagen.v1.FabricDataGenerator; +import net.fabricmc.fabric.api.datagen.v1.FabricDataOutput; +import net.fabricmc.fabric.api.datagen.v1.provider.FabricTagProvider; + +public class FabricDocsReferenceDamageTypesDataGenerator implements DataGeneratorEntrypoint { + public static final DamageType TATER_DAMAGE_TYPE = new DamageType("tater", DamageScaling.WHEN_CAUSED_BY_LIVING_NON_PLAYER, 0.1f); + + @Override + public void buildRegistry(RegistryBuilder registryBuilder) { + registryBuilder.addRegistry(RegistryKeys.DAMAGE_TYPE, registerable -> { + registerable.register(FabricDocsReferenceDamageTypes.TATER_DAMAGE, TATER_DAMAGE_TYPE); + }); + } + + @Override + public void onInitializeDataGenerator(FabricDataGenerator fabricDataGenerator) { + FabricDataGenerator.Pack pack = fabricDataGenerator.createPack(); + + pack.addProvider(TaterDamageTypesGenerator::new); + pack.addProvider(TaterDamageTypeTagGenerator::new); + } + + private static class TaterDamageTypeTagGenerator extends FabricTagProvider { + TaterDamageTypeTagGenerator(FabricDataOutput output, CompletableFuture registriesFuture) { + super(output, RegistryKeys.DAMAGE_TYPE, registriesFuture); + } + + @Override + protected void configure(RegistryWrapper.WrapperLookup arg) { + getOrCreateTagBuilder(TagKey.of(RegistryKeys.DAMAGE_TYPE, new Identifier("minecraft:bypasses_armor"))).add(FabricDocsReferenceDamageTypes.TATER_DAMAGE); + } + } + + private static class TaterDamageTypesGenerator implements DataProvider { + private final DataOutput.PathResolver path; + + TaterDamageTypesGenerator(FabricDataOutput fabricDataOutput) { + path = fabricDataOutput.getResolver(DataOutput.OutputType.DATA_PACK, "damage_type/"); + } + + @Override + public CompletableFuture run(DataWriter writer) { + JsonObject damageTypeObject = new JsonObject(); + + damageTypeObject.addProperty("exhaustion", TATER_DAMAGE_TYPE.exhaustion()); + damageTypeObject.addProperty("message_id", TATER_DAMAGE_TYPE.msgId()); + damageTypeObject.addProperty("scaling", TATER_DAMAGE_TYPE.scaling().asString()); + + return DataProvider.writeToPath(writer, damageTypeObject, path.resolveJson(new Identifier("fabric-docs-reference", "tater"))); + } + + @Override + public String getName() { + return "Damage Type"; + } + } +} diff --git a/reference/1.20.4/src/main/java/com/example/docs/damage/TaterBlock.java b/reference/1.20.4/src/main/java/com/example/docs/damage/TaterBlock.java new file mode 100644 index 000000000..87e217764 --- /dev/null +++ b/reference/1.20.4/src/main/java/com/example/docs/damage/TaterBlock.java @@ -0,0 +1,29 @@ +package com.example.docs.damage; + +import net.minecraft.block.Block; +import net.minecraft.block.BlockState; +import net.minecraft.entity.Entity; +import net.minecraft.entity.LivingEntity; +import net.minecraft.entity.damage.DamageSource; +import net.minecraft.registry.RegistryKeys; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; + +// :::1 +public class TaterBlock extends Block { + public TaterBlock(Settings settings) { + super(settings); + } + + @Override + public void onSteppedOn(World world, BlockPos pos, BlockState state, Entity entity) { + if (entity instanceof LivingEntity) { + DamageSource damageSource = new DamageSource( + world.getRegistryManager() + .get(RegistryKeys.DAMAGE_TYPE) + .entryOf(FabricDocsReferenceDamageTypes.TATER_DAMAGE)); + entity.damage(damageSource, 5.0f); + } + } +} +// :::1 diff --git a/reference/1.20.4/src/main/java/com/example/docs/effect/FabricDocsReferenceEffects.java b/reference/1.20.4/src/main/java/com/example/docs/effect/FabricDocsReferenceEffects.java new file mode 100644 index 000000000..e63ed6b16 --- /dev/null +++ b/reference/1.20.4/src/main/java/com/example/docs/effect/FabricDocsReferenceEffects.java @@ -0,0 +1,19 @@ +package com.example.docs.effect; + +import net.minecraft.entity.effect.StatusEffect; +import net.minecraft.registry.Registries; +import net.minecraft.registry.Registry; +import net.minecraft.util.Identifier; + +import net.fabricmc.api.ModInitializer; + +// :::1 +public class FabricDocsReferenceEffects implements ModInitializer { + public static final StatusEffect TATER_EFFECT = new TaterEffect(); + + @Override + public void onInitialize() { + Registry.register(Registries.STATUS_EFFECT, new Identifier("fabric-docs-reference", "tater"), TATER_EFFECT); + } +} +// :::1 diff --git a/reference/1.20.4/src/main/java/com/example/docs/effect/TaterEffect.java b/reference/1.20.4/src/main/java/com/example/docs/effect/TaterEffect.java new file mode 100644 index 000000000..3c434af1c --- /dev/null +++ b/reference/1.20.4/src/main/java/com/example/docs/effect/TaterEffect.java @@ -0,0 +1,31 @@ +package com.example.docs.effect; + +import net.minecraft.entity.LivingEntity; +import net.minecraft.entity.effect.StatusEffect; +import net.minecraft.entity.effect.StatusEffectCategory; +import net.minecraft.entity.player.PlayerEntity; + +// :::1 +public class TaterEffect extends StatusEffect { + protected TaterEffect() { + // category: StatusEffectCategory - describes if the effect is helpful (BENEFICIAL), harmful (HARMFUL) or useless (NEUTRAL) + // color: int - Color is the color assigned to the effect (in RGB) + super(StatusEffectCategory.BENEFICIAL, 0xe9b8b3); + } + + // Called every tick to check if the effect can be applied or not + @Override + public boolean canApplyUpdateEffect(int duration, int amplifier) { + // In our case, we just make it return true so that it applies the effect every tick + return true; + } + + // Called when the effect is applied + @Override + public void applyUpdateEffect(LivingEntity entity, int amplifier) { + if (entity instanceof PlayerEntity) { + ((PlayerEntity) entity).addExperience(1 << amplifier); // Higher amplifier gives you experience faster + } + } +} +// :::1 diff --git a/reference/1.20.4/src/main/java/com/example/docs/event/FabricDocsReferenceEvents.java b/reference/1.20.4/src/main/java/com/example/docs/event/FabricDocsReferenceEvents.java new file mode 100644 index 000000000..64b6f84b9 --- /dev/null +++ b/reference/1.20.4/src/main/java/com/example/docs/event/FabricDocsReferenceEvents.java @@ -0,0 +1,61 @@ +package com.example.docs.event; + +import net.minecraft.block.BlockState; +import net.minecraft.block.Blocks; +import net.minecraft.entity.ItemEntity; +import net.minecraft.item.ItemStack; +import net.minecraft.item.Items; +import net.minecraft.loot.LootPool; +import net.minecraft.loot.entry.ItemEntry; +import net.minecraft.util.ActionResult; +import net.minecraft.util.Identifier; + +import net.fabricmc.api.ModInitializer; +import net.fabricmc.fabric.api.event.player.AttackBlockCallback; +import net.fabricmc.fabric.api.loot.v2.LootTableEvents; + +// Class to contain all mod events. +public class FabricDocsReferenceEvents implements ModInitializer { + private static final Identifier COAL_ORE_LOOT_TABLE_ID = Blocks.COAL_ORE.getLootTableId(); + + @Override + public void onInitialize() { + // :::1 + AttackBlockCallback.EVENT.register((player, world, hand, pos, direction) -> { + BlockState state = world.getBlockState(pos); + + // Manual spectator check is necessary because AttackBlockCallbacks fire before the spectator check + if (!player.isSpectator() && player.getMainHandStack().isEmpty() && state.isToolRequired()) { + player.damage(world.getDamageSources().generic(), 1.0F); + } + + return ActionResult.PASS; + }); + // :::1 + + // :::2 + LootTableEvents.MODIFY.register((resourceManager, lootManager, id, tableBuilder, source) -> { + // Let's only modify built-in loot tables and leave data pack loot tables untouched by checking the source. + // We also check that the loot table ID is equal to the ID we want. + if (source.isBuiltin() && COAL_ORE_LOOT_TABLE_ID.equals(id)) { + // We make the pool and add an item + LootPool.Builder poolBuilder = LootPool.builder().with(ItemEntry.builder(Items.EGG)); + tableBuilder.pool(poolBuilder); + } + }); + // :::2 + + // :::3 + SheepShearCallback.EVENT.register((player, sheep) -> { + sheep.setSheared(true); + + // Create diamond item entity at sheep's position. + ItemStack stack = new ItemStack(Items.DIAMOND); + ItemEntity itemEntity = new ItemEntity(player.getWorld(), sheep.getX(), sheep.getY(), sheep.getZ(), stack); + player.getWorld().spawnEntity(itemEntity); + + return ActionResult.FAIL; + }); + // :::3 + } +} diff --git a/reference/1.20.4/src/main/java/com/example/docs/event/SheepShearCallback.java b/reference/1.20.4/src/main/java/com/example/docs/event/SheepShearCallback.java new file mode 100644 index 000000000..ea598bf31 --- /dev/null +++ b/reference/1.20.4/src/main/java/com/example/docs/event/SheepShearCallback.java @@ -0,0 +1,35 @@ +package com.example.docs.event; + +import net.minecraft.entity.passive.SheepEntity; +import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.util.ActionResult; + +import net.fabricmc.fabric.api.event.Event; +import net.fabricmc.fabric.api.event.EventFactory; +/** + * Callback for shearing a sheep. + * Called before the sheep is sheared, items are dropped, and items are damaged. + * Upon return: + * - SUCCESS cancels further processing and continues with normal shearing behavior. + * - PASS falls back to further processing and defaults to SUCCESS if no other listeners are available + * - FAIL cancels further processing and does not shear the sheep. + */ + +// ::: +public interface SheepShearCallback { + Event EVENT = EventFactory.createArrayBacked(SheepShearCallback.class, + (listeners) -> (player, sheep) -> { + for (SheepShearCallback listener : listeners) { + ActionResult result = listener.interact(player, sheep); + + if (result != ActionResult.PASS) { + return result; + } + } + + return ActionResult.PASS; + }); + + ActionResult interact(PlayerEntity player, SheepEntity sheep); +} +// ::: diff --git a/reference/1.20.4/src/main/java/com/example/docs/item/FabricDocsReferenceItems.java b/reference/1.20.4/src/main/java/com/example/docs/item/FabricDocsReferenceItems.java new file mode 100644 index 000000000..68d98da4a --- /dev/null +++ b/reference/1.20.4/src/main/java/com/example/docs/item/FabricDocsReferenceItems.java @@ -0,0 +1,12 @@ +package com.example.docs.item; + +import net.fabricmc.api.ModInitializer; + +// :::1 +public class FabricDocsReferenceItems implements ModInitializer { + @Override + public void onInitialize() { + ModItems.initialize(); + } +} +// :::1 diff --git a/reference/1.20.4/src/main/java/com/example/docs/item/ModItems.java b/reference/1.20.4/src/main/java/com/example/docs/item/ModItems.java new file mode 100644 index 000000000..851ccbc79 --- /dev/null +++ b/reference/1.20.4/src/main/java/com/example/docs/item/ModItems.java @@ -0,0 +1,137 @@ +package com.example.docs.item; + +import net.minecraft.entity.effect.StatusEffectInstance; +import net.minecraft.entity.effect.StatusEffects; +import net.minecraft.item.ArmorItem; +import net.minecraft.item.FoodComponent; +import net.minecraft.item.Item; +import net.minecraft.item.ItemGroup; +import net.minecraft.item.ItemGroups; +import net.minecraft.item.ItemStack; +import net.minecraft.item.SwordItem; +import net.minecraft.registry.Registries; +import net.minecraft.registry.Registry; +import net.minecraft.registry.RegistryKey; +import net.minecraft.text.Text; +import net.minecraft.util.Identifier; + +import net.fabricmc.fabric.api.item.v1.FabricItemSettings; +import net.fabricmc.fabric.api.itemgroup.v1.FabricItemGroup; +import net.fabricmc.fabric.api.itemgroup.v1.ItemGroupEvents; +import net.fabricmc.fabric.api.registry.CompostingChanceRegistry; +import net.fabricmc.fabric.api.registry.FuelRegistry; + +import com.example.docs.FabricDocsReference; +import com.example.docs.item.armor.GuiditeArmorMaterial; +import com.example.docs.item.custom.LightningStick; +import com.example.docs.item.tool.GuiditeMaterial; + +// :::1 +public class ModItems { + // :::1 + + // :::6 + public static final Item GUIDITE_HELMET = register(new ArmorItem(GuiditeArmorMaterial.INSTANCE, ArmorItem.Type.HELMET, new Item.Settings()), "guidite_helmet"); + public static final Item GUIDITE_BOOTS = register(new ArmorItem(GuiditeArmorMaterial.INSTANCE, ArmorItem.Type.BOOTS, new Item.Settings()), "guidite_boots"); + public static final Item GUIDITE_LEGGINGS = register(new ArmorItem(GuiditeArmorMaterial.INSTANCE, ArmorItem.Type.LEGGINGS, new Item.Settings()), "guidite_leggings"); + public static final Item GUIDITE_CHESTPLATE = register(new ArmorItem(GuiditeArmorMaterial.INSTANCE, ArmorItem.Type.CHESTPLATE, new Item.Settings()), "guidite_chestplate"); + // :::6 + public static final Item LIGHTNING_STICK = register(new LightningStick(new FabricItemSettings()), "lightning_stick"); + // :::7 + public static final Item GUIDITE_SWORD = register(new SwordItem(GuiditeMaterial.INSTANCE, 2, 0.5F, new FabricItemSettings()), "guidite_sword"); + // :::7 + // :::9 + public static final RegistryKey CUSTOM_ITEM_GROUP_KEY = RegistryKey.of(Registries.ITEM_GROUP.getKey(), new Identifier(FabricDocsReference.MOD_ID, "item_group")); + public static final ItemGroup CUSTOM_ITEM_GROUP = FabricItemGroup.builder() + .icon(() -> new ItemStack(ModItems.GUIDITE_SWORD)) + .displayName(Text.translatable("itemGroup.fabric_docs_reference")) + .build(); + // :::9 + // :::5 + public static final FoodComponent SUSPICIOUS_FOOD_COMPONENT = new FoodComponent.Builder() + .alwaysEdible() + .snack() + // The duration is in ticks, 20 ticks = 1 second + .statusEffect(new StatusEffectInstance(StatusEffects.POISON, 6 * 20, 1), 1.0f) + .build(); + // :::5 + + // :::2 + public static final Item SUSPICIOUS_SUBSTANCE = register( + // Ignore the food component for now, we'll cover it later in the food section. + new Item(new FabricItemSettings().food(SUSPICIOUS_FOOD_COMPONENT)), + "suspicious_substance" + ); + // :::2 + + // :::1 + public static Item register(Item item, String id) { + // Create the identifier for the item. + Identifier itemID = new Identifier(FabricDocsReference.MOD_ID, id); + + // Register the item. + Item registeredItem = Registry.register(Registries.ITEM, itemID, item); + + // Return the registered item! + return registeredItem; + } + + // :::1 + + // :::3 + public static void initialize() { + // :::3 + // :::4 + // Get the event for modifying entries in the ingredients group. + // And register an event handler that adds our suspicious item to the ingredients group. + ItemGroupEvents.modifyEntriesEvent(ItemGroups.INGREDIENTS) + .register((itemGroup) -> itemGroup.add(ModItems.SUSPICIOUS_SUBSTANCE)); + // :::4 + + ItemGroupEvents.modifyEntriesEvent(ItemGroups.TOOLS) + .register((itemGroup) -> { + itemGroup.add(ModItems.GUIDITE_HELMET); + itemGroup.add(ModItems.GUIDITE_BOOTS); + itemGroup.add(ModItems.GUIDITE_LEGGINGS); + itemGroup.add(ModItems.GUIDITE_CHESTPLATE); + }); + + // :::8 + ItemGroupEvents.modifyEntriesEvent(ItemGroups.TOOLS) + .register((itemGroup) -> itemGroup.add(ModItems.GUIDITE_SWORD)); + // :::8 + + // :::_12 + // Register the group. + Registry.register(Registries.ITEM_GROUP, CUSTOM_ITEM_GROUP_KEY, CUSTOM_ITEM_GROUP); + + // Register items to the custom item group. + ItemGroupEvents.modifyEntriesEvent(CUSTOM_ITEM_GROUP_KEY).register(itemGroup -> { + itemGroup.add(ModItems.SUSPICIOUS_SUBSTANCE); + itemGroup.add(ModItems.GUIDITE_SWORD); + itemGroup.add(ModItems.GUIDITE_HELMET); + itemGroup.add(ModItems.GUIDITE_BOOTS); + itemGroup.add(ModItems.GUIDITE_LEGGINGS); + itemGroup.add(ModItems.GUIDITE_CHESTPLATE); + itemGroup.add(ModItems.LIGHTNING_STICK); + // ... + }); + // :::_12 + + // :::_10 + // Add the suspicious substance to the composting registry with a 30% chance of increasing the composter's level. + CompostingChanceRegistry.INSTANCE.add(ModItems.SUSPICIOUS_SUBSTANCE, 0.3f); + // :::_10 + + // :::_11 + // Add the suspicious substance to the flammable block registry with a burn time of 30 seconds. + // Remember, Minecraft deals with logical based-time using ticks. + // 20 ticks = 1 second. + FuelRegistry.INSTANCE.add(ModItems.GUIDITE_SWORD, 30 * 20); + // :::_11 + // :::3 + } + + // :::3 +} +// :::1 diff --git a/reference/1.20.4/src/main/java/com/example/docs/item/armor/GuiditeArmorMaterial.java b/reference/1.20.4/src/main/java/com/example/docs/item/armor/GuiditeArmorMaterial.java new file mode 100644 index 000000000..d267b5ae1 --- /dev/null +++ b/reference/1.20.4/src/main/java/com/example/docs/item/armor/GuiditeArmorMaterial.java @@ -0,0 +1,97 @@ +package com.example.docs.item.armor; + +import net.minecraft.item.ArmorItem; +import net.minecraft.item.ArmorMaterial; +import net.minecraft.recipe.Ingredient; +import net.minecraft.sound.SoundEvent; +import net.minecraft.sound.SoundEvents; + +import com.example.docs.item.ModItems; + +// :::1 +public class GuiditeArmorMaterial implements ArmorMaterial { + // ... + //:::1 + // :::_10 + public static final GuiditeArmorMaterial INSTANCE = new GuiditeArmorMaterial(); + + // :::_10 + // :::2 + @Override + public int getDurability(ArmorItem.Type type) { + // Replace this multiplier by a constant value for the durability of the armor. + // For reference, diamond uses 33 for all armor pieces, whilst leather uses 5. + int DURABILITY_MULTIPLIER = 12; + return switch (type) { + case BOOTS -> 13 * DURABILITY_MULTIPLIER; + case LEGGINGS -> 15 * DURABILITY_MULTIPLIER; + case CHESTPLATE -> 16 * DURABILITY_MULTIPLIER; + case HELMET -> 11 * DURABILITY_MULTIPLIER; + default -> 0; + }; + } + + // :::2 + // :::3 + @Override + public int getProtection(ArmorItem.Type type) { + // Protection values for all the slots. + // For reference, diamond uses 3 for boots, 6 for leggings, 8 for chestplate, and 3 for helmet, + // whilst leather uses 1, 2, 3 and 1 respectively. + return switch (type) { + case BOOTS, HELMET -> 3; + case LEGGINGS -> 6; + case CHESTPLATE -> 8; + default -> 0; + }; + } + + // :::3 + // :::4 + @Override + public int getEnchantability() { + return 5; + } + + // :::4 + // :::5 + @Override + public SoundEvent getEquipSound() { + // Example for Iron Armor + return SoundEvents.ITEM_ARMOR_EQUIP_IRON; + } + + // :::5 + // :::6 + @Override + public Ingredient getRepairIngredient() { + return Ingredient.ofItems(ModItems.SUSPICIOUS_SUBSTANCE); + } + + // :::6 + // :::7 + @Override + public String getName() { + return "guidite"; + } + + // :::7 + // :::8 + @Override + public float getToughness() { + return 2.0F; + } + + // :::8 + // :::9 + @Override + public float getKnockbackResistance() { + // We don't want knockback resistance for guidite armor, but if you do, + // change this value to 0.XF, where X is the level of knockback resistance you want. + return 0; + } + + // :::9 + // :::1 +} +// :::1 diff --git a/reference/1.20.4/src/main/java/com/example/docs/item/custom/CustomSoundItem.java b/reference/1.20.4/src/main/java/com/example/docs/item/custom/CustomSoundItem.java new file mode 100644 index 000000000..7d15908e8 --- /dev/null +++ b/reference/1.20.4/src/main/java/com/example/docs/item/custom/CustomSoundItem.java @@ -0,0 +1,47 @@ +package com.example.docs.item.custom; + +import net.minecraft.entity.LivingEntity; +import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.item.ItemUsageContext; +import net.minecraft.sound.SoundCategory; +import net.minecraft.sound.SoundEvents; +import net.minecraft.util.ActionResult; +import net.minecraft.util.Hand; + +public class CustomSoundItem extends Item { + public CustomSoundItem(Settings settings) { + super(settings); + } + + // :::1 + @Override + public ActionResult useOnEntity(ItemStack stack, PlayerEntity user, LivingEntity entity, Hand hand) { + // As stated above, don't use the playSound() method on the client side + // ... it wont work! + if (!entity.getWorld().isClient()) { + // Play the sound as if it was coming from the entity. + entity.playSound(SoundEvents.ENTITY_PILLAGER_AMBIENT, 2f, 0.7f); + } + + return super.useOnEntity(stack, user, entity, hand); + } + + // :::1 + // :::2 + @Override + public ActionResult useOnBlock(ItemUsageContext context) { + if (!context.getWorld().isClient()) { + // Play the sound and specify location, category and who made the sound. + // No entity made the sound, so we specify null. + context.getWorld().playSound(null, context.getBlockPos(), + SoundEvents.BLOCK_COPPER_PLACE, SoundCategory.PLAYERS, + 1f, 1f); + } + + return super.useOnBlock(context); + } + + // :::2 +} diff --git a/reference/1.20.4/src/main/java/com/example/docs/item/custom/LightningStick.java b/reference/1.20.4/src/main/java/com/example/docs/item/custom/LightningStick.java new file mode 100644 index 000000000..14fd6c366 --- /dev/null +++ b/reference/1.20.4/src/main/java/com/example/docs/item/custom/LightningStick.java @@ -0,0 +1,58 @@ +package com.example.docs.item.custom; + +import java.util.List; + +import org.jetbrains.annotations.Nullable; + +import net.minecraft.client.item.TooltipContext; +import net.minecraft.entity.EntityType; +import net.minecraft.entity.LightningEntity; +import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.text.Text; +import net.minecraft.util.Formatting; +import net.minecraft.util.Hand; +import net.minecraft.util.TypedActionResult; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; + +// :::1 +public class LightningStick extends Item { + public LightningStick(Settings settings) { + super(settings); + } + + // :::1 + // :::2 + @Override + public TypedActionResult use(World world, PlayerEntity user, Hand hand) { + // Ensure we don't spawn the lightning only on the client. + // This is to prevent desync. + if (world.isClient) { + return TypedActionResult.pass(user.getStackInHand(hand)); + } + + BlockPos frontOfPlayer = user.getBlockPos().offset(user.getHorizontalFacing(), 10); + + // Spawn the lightning bolt. + LightningEntity lightningBolt = new LightningEntity(EntityType.LIGHTNING_BOLT, world); + lightningBolt.setPosition(frontOfPlayer.toCenterPos()); + world.spawnEntity(lightningBolt); + + // Nothing has changed to the item stack, + // so we just return it how it was. + return TypedActionResult.success(user.getStackInHand(hand)); + } + + // :::2 + // :::3 + @Override + public void appendTooltip(ItemStack stack, @Nullable World world, List tooltip, TooltipContext context) { + tooltip.add(Text.translatable("itemTooltip.fabric-docs-reference.lightning_stick").formatted(Formatting.GOLD)); + } + + // :::3 + // :::1 +} +// :::1 diff --git a/reference/1.20.4/src/main/java/com/example/docs/item/tool/GuiditeMaterial.java b/reference/1.20.4/src/main/java/com/example/docs/item/tool/GuiditeMaterial.java new file mode 100644 index 000000000..9e217f700 --- /dev/null +++ b/reference/1.20.4/src/main/java/com/example/docs/item/tool/GuiditeMaterial.java @@ -0,0 +1,62 @@ +package com.example.docs.item.tool; + +import net.minecraft.item.Items; +import net.minecraft.item.ToolMaterial; +import net.minecraft.recipe.Ingredient; + +import com.example.docs.item.ModItems; + +// :::1 +public class GuiditeMaterial implements ToolMaterial { + // Your IDE should override the interface's methods for you, or at least shout at you to do so. + // :::1 + // :::8 + public static final GuiditeMaterial INSTANCE = new GuiditeMaterial(); + // :::8 + + // :::2 + @Override + public int getDurability() { + return 455; + } + + // :::2 + // :::3 + @Override + public float getMiningSpeedMultiplier() { + return 5.0F; + } + + // :::3 + // :::4 + @Override + public float getAttackDamage() { + return 1.5F; + } + + // :::4 + // :::5 + @Override + public int getMiningLevel() { + return 3; + } + + // :::5 + // :::6 + @Override + public int getEnchantability() { + return 22; + } + + // :::6 + // :::7 + @Override + public Ingredient getRepairIngredient() { + return Ingredient.ofItems(ModItems.SUSPICIOUS_SUBSTANCE, Items.POTATO); + } + + // :::7 + + // :::1 +} +// :::1 diff --git a/reference/1.20.4/src/main/java/com/example/docs/mixin/ExampleMixin.java b/reference/1.20.4/src/main/java/com/example/docs/mixin/ExampleMixin.java new file mode 100644 index 000000000..3a385b0aa --- /dev/null +++ b/reference/1.20.4/src/main/java/com/example/docs/mixin/ExampleMixin.java @@ -0,0 +1,16 @@ +package com.example.docs.mixin; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import net.minecraft.server.MinecraftServer; + +@Mixin(MinecraftServer.class) +public class ExampleMixin { + @Inject(at = @At("HEAD"), method = "loadWorld") + private void init(CallbackInfo info) { + // This code is injected into the start of MinecraftServer.loadWorld()V + } +} diff --git a/reference/1.20.4/src/main/java/com/example/docs/mixin/event/SheepEntityMixin.java b/reference/1.20.4/src/main/java/com/example/docs/mixin/event/SheepEntityMixin.java new file mode 100644 index 000000000..60fa33213 --- /dev/null +++ b/reference/1.20.4/src/main/java/com/example/docs/mixin/event/SheepEntityMixin.java @@ -0,0 +1,27 @@ +package com.example.docs.mixin.event; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +import net.minecraft.entity.passive.SheepEntity; +import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.util.ActionResult; +import net.minecraft.util.Hand; + +import com.example.docs.event.SheepShearCallback; + +// ::: +@Mixin(SheepEntity.class) +public class SheepEntityMixin { + @Inject(at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/passive/SheepEntity;sheared(Lnet/minecraft/sound/SoundCategory;)V"), method = "interactMob", cancellable = true) + private void onShear(final PlayerEntity player, final Hand hand, final CallbackInfoReturnable info) { + ActionResult result = SheepShearCallback.EVENT.invoker().interact(player, (SheepEntity) (Object) this); + + if (result == ActionResult.FAIL) { + info.setReturnValue(result); + } + } +} +// ::: diff --git a/reference/latest/src/main/java/com/example/docs/mixin/potion/BrewingRecipeRegistryInvoker.java b/reference/1.20.4/src/main/java/com/example/docs/mixin/potion/BrewingRecipeRegistryInvoker.java similarity index 100% rename from reference/latest/src/main/java/com/example/docs/mixin/potion/BrewingRecipeRegistryInvoker.java rename to reference/1.20.4/src/main/java/com/example/docs/mixin/potion/BrewingRecipeRegistryInvoker.java diff --git a/reference/1.20.4/src/main/java/com/example/docs/potion/FabricDocsReferencePotions.java b/reference/1.20.4/src/main/java/com/example/docs/potion/FabricDocsReferencePotions.java new file mode 100644 index 000000000..82b3c60f6 --- /dev/null +++ b/reference/1.20.4/src/main/java/com/example/docs/potion/FabricDocsReferencePotions.java @@ -0,0 +1,36 @@ +package com.example.docs.potion; + +import net.minecraft.entity.effect.StatusEffectInstance; +import net.minecraft.item.Items; +import net.minecraft.potion.Potion; +import net.minecraft.potion.Potions; +import net.minecraft.recipe.BrewingRecipeRegistry; +import net.minecraft.registry.Registries; +import net.minecraft.registry.Registry; +import net.minecraft.util.Identifier; + +import net.fabricmc.api.ModInitializer; + +import com.example.docs.effect.FabricDocsReferenceEffects; + +// :::1 +public class FabricDocsReferencePotions implements ModInitializer { + public static final Potion TATER_POTION = + Registry.register( + Registries.POTION, + new Identifier("fabric-docs-reference", "tater"), + new Potion( + new StatusEffectInstance( + FabricDocsReferenceEffects.TATER_EFFECT, + 3600, + 0))); + + @Override + public void onInitialize() { + BrewingRecipeRegistry.registerPotionRecipe(Potions.WATER, Items.POTATO, TATER_POTION); + + // Use the mixin invoker if you are not using Fabric API + // BrewingRecipeRegistryInvoker.invokeRegisterPotionRecipe(Potions.WATER, Items.POTATO, TATER_POTION); + } +} +// :::1 diff --git a/reference/1.20.4/src/main/java/com/example/docs/sound/CustomSounds.java b/reference/1.20.4/src/main/java/com/example/docs/sound/CustomSounds.java new file mode 100644 index 000000000..c988b966f --- /dev/null +++ b/reference/1.20.4/src/main/java/com/example/docs/sound/CustomSounds.java @@ -0,0 +1,32 @@ +package com.example.docs.sound; + +import net.minecraft.registry.Registries; +import net.minecraft.registry.Registry; +import net.minecraft.sound.SoundEvent; +import net.minecraft.util.Identifier; + +// :::1 +public class CustomSounds { + private CustomSounds() { + // private empty constructor to avoid accidental instantiation + } + + // ITEM_METAL_WHISTLE is the name of the custom sound event + // and is called in the mod to use the custom sound + public static final SoundEvent ITEM_METAL_WHISTLE = registerSound("metal_whistle"); + + // actual registration of all the custom SoundEvents + private static SoundEvent registerSound(String id) { + Identifier identifier = new Identifier(FabricDocsReferenceSounds.MOD_ID, id); + return Registry.register(Registries.SOUND_EVENT, identifier, SoundEvent.of(identifier)); + } + + // This static method starts class initialization, which then initializes + // the static class variables (e.g. ITEM_METAL_WHISTLE). + public static void initialize() { + FabricDocsReferenceSounds.LOGGER.info("Registering " + FabricDocsReferenceSounds.MOD_ID + " Sounds"); + // Technically this method can stay empty, but some developers like to notify + // the console, that certain parts of the mod have been successfully initialized + } +} +// :::1 diff --git a/reference/1.20.4/src/main/java/com/example/docs/sound/FabricDocsReferenceSounds.java b/reference/1.20.4/src/main/java/com/example/docs/sound/FabricDocsReferenceSounds.java new file mode 100644 index 000000000..cc45f2bda --- /dev/null +++ b/reference/1.20.4/src/main/java/com/example/docs/sound/FabricDocsReferenceSounds.java @@ -0,0 +1,30 @@ +package com.example.docs.sound; + +import org.slf4j.Logger; + +import net.minecraft.registry.Registries; +import net.minecraft.registry.Registry; +import net.minecraft.sound.SoundEvent; +import net.minecraft.util.Identifier; + +import net.fabricmc.api.ModInitializer; + +import com.example.docs.FabricDocsReference; + +// :::2 +public class FabricDocsReferenceSounds implements ModInitializer { + public static final String MOD_ID = FabricDocsReference.MOD_ID; + public static final Logger LOGGER = FabricDocsReference.LOGGER; + + @Override + public void onInitialize() { + // This is the basic registering. Use a new class for registering sounds + // instead, to keep the ModInitializer implementing class clean! + Registry.register(Registries.SOUND_EVENT, new Identifier(MOD_ID, "metal_whistle"), + SoundEvent.of(new Identifier(MOD_ID, "metal_whistle"))); + + // ... the cleaner approach. // [!code focus] + // CustomSounds.initialize(); // [!code focus] + } +} +// :::2 diff --git a/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/blockstates/condensed_dirt.json b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/blockstates/condensed_dirt.json new file mode 100644 index 000000000..20013a7f9 --- /dev/null +++ b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/blockstates/condensed_dirt.json @@ -0,0 +1,5 @@ +{ + "variants": { + "": { "model": "mod_id:block/condensed_dirt" } + } +} \ No newline at end of file diff --git a/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/blockstates/condensed_oak_log.json b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/blockstates/condensed_oak_log.json new file mode 100644 index 000000000..b7a7946c8 --- /dev/null +++ b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/blockstates/condensed_oak_log.json @@ -0,0 +1,16 @@ +{ + "variants": { + "axis=x": { + "model": "mod_id:block/condensed_oak_log_horizontal", + "x": 90, + "y": 90 + }, + "axis=y": { + "model": "mod_id:block/condensed_oak_log" + }, + "axis=z": { + "model": "mod_id:block/condensed_oak_log_horizontal", + "x": 90 + } + } +} \ No newline at end of file diff --git a/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/blockstates/prismarine_lamp.json b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/blockstates/prismarine_lamp.json new file mode 100644 index 000000000..81013e55c --- /dev/null +++ b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/blockstates/prismarine_lamp.json @@ -0,0 +1,10 @@ +{ + "variants": { + "activated=false": { + "model": "fabric-docs-reference:block/prismarine_lamp" + }, + "activated=true": { + "model": "fabric-docs-reference:block/prismarine_lamp_on" + } + } +} \ No newline at end of file diff --git a/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/blockstates/tater.json b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/blockstates/tater.json new file mode 100644 index 000000000..4d19a2be6 --- /dev/null +++ b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/blockstates/tater.json @@ -0,0 +1,7 @@ +{ + "variants": { + "": { + "model": "fabric-docs-reference:block/tater" + } + } +} \ No newline at end of file diff --git a/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/icon.png b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/icon.png new file mode 100644 index 000000000..047b91f23 Binary files /dev/null and b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/icon.png differ diff --git a/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/lang/en_us.json b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/lang/en_us.json new file mode 100644 index 000000000..ba3c1c978 --- /dev/null +++ b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/lang/en_us.json @@ -0,0 +1,18 @@ +{ + "effect.fabric-docs-reference.tater": "Tater", + "sound.fabric-docs-reference.metal_whistle": "Metal Whistle", + "item.minecraft.potion.effect.tater": "Tater Potion", + "death.attack.tater": "%1$s died from Tater damage!", + "item.fabric-docs-reference.suspicious_substance": "Suspicous Substance", + "item.fabric-docs-reference.guidite_sword": "Guidite Sword", + "item.fabric-docs-reference.guidite_helmet": "Guidite Helmet", + "item.fabric-docs-reference.guidite_chestplate": "Guidite Chestplate", + "item.fabric-docs-reference.guidite_leggings": "Guidite Leggings", + "item.fabric-docs-reference.guidite_boots": "Guidite Boots", + "item.fabric-docs-reference.lightning_stick": "Lightning Stick", + "itemTooltip.fabric-docs-reference.lightning_stick": "This is an extremely powerful weapon that can summon lightning bolts.", + "itemGroup.fabric_docs_reference": "Fabric Docs Reference", + "block.fabric-docs-reference.condensed_dirt": "Condensed Dirt", + "block.fabric-docs-reference.condensed_oak_log": "Condensed Oak Log", + "block.fabric-docs-reference.prismarine_lamp": "Prismarine Lamp" +} \ No newline at end of file diff --git a/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/block/condensed_dirt.json b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/block/condensed_dirt.json new file mode 100644 index 000000000..31c730ee4 --- /dev/null +++ b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/block/condensed_dirt.json @@ -0,0 +1,6 @@ +{ + "parent": "block/cube_all", + "textures": { + "all": "fabric-docs-reference:block/condensed_dirt" + } +} \ No newline at end of file diff --git a/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/block/condensed_oak_log.json b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/block/condensed_oak_log.json new file mode 100644 index 000000000..0a9691711 --- /dev/null +++ b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/block/condensed_oak_log.json @@ -0,0 +1,7 @@ +{ + "parent": "block/cube_column", + "textures": { + "end": "fabric-docs-reference:block/condensed_oak_log_top", + "side": "fabric-docs-reference:block/condensed_oak_log" + } +} \ No newline at end of file diff --git a/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/block/condensed_oak_log_horizontal.json b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/block/condensed_oak_log_horizontal.json new file mode 100644 index 000000000..f76486fef --- /dev/null +++ b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/block/condensed_oak_log_horizontal.json @@ -0,0 +1,7 @@ +{ + "parent": "block/cube_column_horizontal", + "textures": { + "end": "fabric-docs-reference:block/condensed_oak_log_top", + "side": "fabric-docs-reference:block/condensed_oak_log" + } +} \ No newline at end of file diff --git a/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/block/prismarine_lamp.json b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/block/prismarine_lamp.json new file mode 100644 index 000000000..2b6a84ee0 --- /dev/null +++ b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/block/prismarine_lamp.json @@ -0,0 +1,6 @@ +{ + "parent": "block/cube_all", + "textures": { + "all": "fabric-docs-reference:block/prismarine_lamp" + } +} \ No newline at end of file diff --git a/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/block/prismarine_lamp_on.json b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/block/prismarine_lamp_on.json new file mode 100644 index 000000000..e7f80e39e --- /dev/null +++ b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/block/prismarine_lamp_on.json @@ -0,0 +1,6 @@ +{ + "parent": "block/cube_all", + "textures": { + "all": "fabric-docs-reference:block/prismarine_lamp_on" + } +} \ No newline at end of file diff --git a/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/block/tater.json b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/block/tater.json new file mode 100644 index 000000000..ac20e489a --- /dev/null +++ b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/block/tater.json @@ -0,0 +1,6 @@ +{ + "parent": "minecraft:block/cube_all", + "textures": { + "all": "fabric-docs-reference:block/tater" + } +} \ No newline at end of file diff --git a/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/item/condensed_dirt.json b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/item/condensed_dirt.json new file mode 100644 index 000000000..b2032bc2c --- /dev/null +++ b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/item/condensed_dirt.json @@ -0,0 +1,3 @@ +{ + "parent": "fabric-docs-reference:block/condensed_dirt" +} \ No newline at end of file diff --git a/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/item/condensed_oak_log.json b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/item/condensed_oak_log.json new file mode 100644 index 000000000..7597e69e3 --- /dev/null +++ b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/item/condensed_oak_log.json @@ -0,0 +1,3 @@ +{ + "parent": "fabric-docs-reference:block/condensed_oak_log" +} \ No newline at end of file diff --git a/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/item/guidite_boots.json b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/item/guidite_boots.json new file mode 100644 index 000000000..0c9ff00bb --- /dev/null +++ b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/item/guidite_boots.json @@ -0,0 +1,6 @@ +{ + "parent": "item/generated", + "textures": { + "layer0": "fabric-docs-reference:item/guidite_boots" + } +} \ No newline at end of file diff --git a/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/item/guidite_chestplate.json b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/item/guidite_chestplate.json new file mode 100644 index 000000000..2b67f83f3 --- /dev/null +++ b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/item/guidite_chestplate.json @@ -0,0 +1,6 @@ +{ + "parent": "item/generated", + "textures": { + "layer0": "fabric-docs-reference:item/guidite_chestplate" + } +} \ No newline at end of file diff --git a/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/item/guidite_helmet.json b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/item/guidite_helmet.json new file mode 100644 index 000000000..ee6e315fd --- /dev/null +++ b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/item/guidite_helmet.json @@ -0,0 +1,6 @@ +{ + "parent": "item/generated", + "textures": { + "layer0": "fabric-docs-reference:item/guidite_helmet" + } +} \ No newline at end of file diff --git a/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/item/guidite_leggings.json b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/item/guidite_leggings.json new file mode 100644 index 000000000..c022ad8e7 --- /dev/null +++ b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/item/guidite_leggings.json @@ -0,0 +1,6 @@ +{ + "parent": "item/generated", + "textures": { + "layer0": "fabric-docs-reference:item/guidite_leggings" + } +} \ No newline at end of file diff --git a/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/item/guidite_sword.json b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/item/guidite_sword.json new file mode 100644 index 000000000..64046c93a --- /dev/null +++ b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/item/guidite_sword.json @@ -0,0 +1,6 @@ +{ + "parent": "item/handheld", + "textures": { + "layer0": "fabric-docs-reference:item/guidite_sword" + } +} \ No newline at end of file diff --git a/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/item/lightning_stick.json b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/item/lightning_stick.json new file mode 100644 index 000000000..c29f9a83b --- /dev/null +++ b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/item/lightning_stick.json @@ -0,0 +1,6 @@ +{ + "parent": "item/generated", + "textures": { + "layer0": "item/stick" + } +} \ No newline at end of file diff --git a/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/item/prismarine_lamp.json b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/item/prismarine_lamp.json new file mode 100644 index 000000000..c7a9333a1 --- /dev/null +++ b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/item/prismarine_lamp.json @@ -0,0 +1,3 @@ +{ + "parent": "fabric-docs-reference:block/prismarine_lamp" +} \ No newline at end of file diff --git a/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/item/suspicious_substance.json b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/item/suspicious_substance.json new file mode 100644 index 000000000..09e3d2f4d --- /dev/null +++ b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/item/suspicious_substance.json @@ -0,0 +1,6 @@ +{ + "parent": "item/generated", + "textures": { + "layer0": "fabric-docs-reference:item/suspicious_substance" + } +} \ No newline at end of file diff --git a/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/item/tater.json b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/item/tater.json new file mode 100644 index 000000000..5302d81e8 --- /dev/null +++ b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/item/tater.json @@ -0,0 +1,3 @@ +{ + "parent": "fabric-docs-reference:block/tater" +} \ No newline at end of file diff --git a/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/particles/sparkle_particle.json b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/particles/sparkle_particle.json new file mode 100644 index 000000000..591e050bb --- /dev/null +++ b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/particles/sparkle_particle.json @@ -0,0 +1,5 @@ +{ + "textures": [ + "fabric-docs-reference:sparkle_particle_texture" + ] +} \ No newline at end of file diff --git a/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/sounds.json b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/sounds.json new file mode 100644 index 000000000..97e8ded66 --- /dev/null +++ b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/sounds.json @@ -0,0 +1,8 @@ +{ + "metal_whistle": { + "subtitle": "sound.fabric-docs-reference.metal_whistle", + "sounds": [ + "fabric-docs-reference:metal_whistle" + ] + } + } \ No newline at end of file diff --git a/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/sounds/metal_whistle.ogg b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/sounds/metal_whistle.ogg new file mode 100644 index 000000000..1d57897cb Binary files /dev/null and b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/sounds/metal_whistle.ogg differ diff --git a/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/textures/block/condensed_oak_log.png b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/textures/block/condensed_oak_log.png new file mode 100644 index 000000000..038c0380f Binary files /dev/null and b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/textures/block/condensed_oak_log.png differ diff --git a/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/textures/block/condensed_oak_log_top.png b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/textures/block/condensed_oak_log_top.png new file mode 100644 index 000000000..80a4fb02b Binary files /dev/null and b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/textures/block/condensed_oak_log_top.png differ diff --git a/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/textures/block/prismarine_lamp.png b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/textures/block/prismarine_lamp.png new file mode 100644 index 000000000..249cd6cee Binary files /dev/null and b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/textures/block/prismarine_lamp.png differ diff --git a/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/textures/block/prismarine_lamp_on.png b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/textures/block/prismarine_lamp_on.png new file mode 100644 index 000000000..870fe9052 Binary files /dev/null and b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/textures/block/prismarine_lamp_on.png differ diff --git a/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/textures/block/tater.png b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/textures/block/tater.png new file mode 100644 index 000000000..37fc5de37 Binary files /dev/null and b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/textures/block/tater.png differ diff --git a/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/textures/gui/test-uv-drawing.png b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/textures/gui/test-uv-drawing.png new file mode 100644 index 000000000..8d1604a38 Binary files /dev/null and b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/textures/gui/test-uv-drawing.png differ diff --git a/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/textures/item/guidite_boots.png b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/textures/item/guidite_boots.png new file mode 100644 index 000000000..b6092f234 Binary files /dev/null and b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/textures/item/guidite_boots.png differ diff --git a/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/textures/item/guidite_chestplate.png b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/textures/item/guidite_chestplate.png new file mode 100644 index 000000000..996534bfd Binary files /dev/null and b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/textures/item/guidite_chestplate.png differ diff --git a/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/textures/item/guidite_helmet.png b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/textures/item/guidite_helmet.png new file mode 100644 index 000000000..e0c6582db Binary files /dev/null and b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/textures/item/guidite_helmet.png differ diff --git a/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/textures/item/guidite_leggings.png b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/textures/item/guidite_leggings.png new file mode 100644 index 000000000..4d37c8da9 Binary files /dev/null and b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/textures/item/guidite_leggings.png differ diff --git a/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/textures/item/guidite_sword.png b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/textures/item/guidite_sword.png new file mode 100644 index 000000000..fcaeb83d6 Binary files /dev/null and b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/textures/item/guidite_sword.png differ diff --git a/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/textures/item/suspicious_substance.png b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/textures/item/suspicious_substance.png new file mode 100644 index 000000000..9575ebbc9 Binary files /dev/null and b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/textures/item/suspicious_substance.png differ diff --git a/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/textures/mob_effect/tater.png b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/textures/mob_effect/tater.png new file mode 100644 index 000000000..511a7bc68 Binary files /dev/null and b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/textures/mob_effect/tater.png differ diff --git a/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/textures/particle/sparkle_particle_texture.png b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/textures/particle/sparkle_particle_texture.png new file mode 100644 index 000000000..b72786571 Binary files /dev/null and b/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/textures/particle/sparkle_particle_texture.png differ diff --git a/reference/latest/src/main/resources/assets/minecraft/textures/models/armor/guidite_layer_1.png b/reference/1.20.4/src/main/resources/assets/minecraft/textures/models/armor/guidite_layer_1.png similarity index 100% rename from reference/latest/src/main/resources/assets/minecraft/textures/models/armor/guidite_layer_1.png rename to reference/1.20.4/src/main/resources/assets/minecraft/textures/models/armor/guidite_layer_1.png diff --git a/reference/latest/src/main/resources/assets/minecraft/textures/models/armor/guidite_layer_2.png b/reference/1.20.4/src/main/resources/assets/minecraft/textures/models/armor/guidite_layer_2.png similarity index 100% rename from reference/latest/src/main/resources/assets/minecraft/textures/models/armor/guidite_layer_2.png rename to reference/1.20.4/src/main/resources/assets/minecraft/textures/models/armor/guidite_layer_2.png diff --git a/reference/1.20.4/src/main/resources/data/fabric-docs-reference/loot_tables/blocks/condensed_dirt.json b/reference/1.20.4/src/main/resources/data/fabric-docs-reference/loot_tables/blocks/condensed_dirt.json new file mode 100644 index 000000000..aa9f99e1a --- /dev/null +++ b/reference/1.20.4/src/main/resources/data/fabric-docs-reference/loot_tables/blocks/condensed_dirt.json @@ -0,0 +1,19 @@ +{ + "type": "minecraft:block", + "pools": [ + { + "rolls": 1, + "entries": [ + { + "type": "minecraft:item", + "name": "fabric-docs-reference:condensed_dirt" + } + ], + "conditions": [ + { + "condition": "minecraft:survives_explosion" + } + ] + } + ] +} \ No newline at end of file diff --git a/reference/1.20.4/src/main/resources/data/minecraft/tags/mineable/shovel.json b/reference/1.20.4/src/main/resources/data/minecraft/tags/mineable/shovel.json new file mode 100644 index 000000000..1e283cce9 --- /dev/null +++ b/reference/1.20.4/src/main/resources/data/minecraft/tags/mineable/shovel.json @@ -0,0 +1,6 @@ +{ + "replace": false, + "values": [ + "fabric-docs-reference:condensed_dirt" + ] +} \ No newline at end of file diff --git a/reference/1.20.4/src/main/resources/fabric-docs-reference.mixins.json b/reference/1.20.4/src/main/resources/fabric-docs-reference.mixins.json new file mode 100644 index 000000000..18611e85e --- /dev/null +++ b/reference/1.20.4/src/main/resources/fabric-docs-reference.mixins.json @@ -0,0 +1,13 @@ +{ + "required": true, + "package": "com.example.docs.mixin", + "compatibilityLevel": "JAVA_17", + "mixins": [ + "ExampleMixin", + "event.SheepEntityMixin", + "potion.BrewingRecipeRegistryInvoker" + ], + "injectors": { + "defaultRequire": 1 + } +} \ No newline at end of file diff --git a/reference/1.20.4/src/main/resources/fabric.mod.json b/reference/1.20.4/src/main/resources/fabric.mod.json new file mode 100644 index 000000000..f9a265034 --- /dev/null +++ b/reference/1.20.4/src/main/resources/fabric.mod.json @@ -0,0 +1,42 @@ +{ + "schemaVersion": 1, + "id": "fabric-docs-reference", + "version": "1.0.0", + "name": "Fabric docs reference", + "icon": "assets/fabric-docs-reference/icon.png", + "environment": "*", + "entrypoints": { + "main": [ + "com.example.docs.FabricDocsReference", + "com.example.docs.event.FabricDocsReferenceEvents", + "com.example.docs.command.FabricDocsReferenceCommands", + "com.example.docs.effect.FabricDocsReferenceEffects", + "com.example.docs.potion.FabricDocsReferencePotions", + "com.example.docs.sound.FabricDocsReferenceSounds", + "com.example.docs.damage.FabricDocsReferenceDamageTypes", + "com.example.docs.item.FabricDocsReferenceItems", + "com.example.docs.block.FabricDocsReferenceBlocks" + ], + "client": [ + "com.example.docs.FabricDocsReferenceClient", + "com.example.docs.client.command.FabricDocsReferenceClientCommands" + ], + "fabric-datagen": [ + "com.example.docs.FabricDocsReferenceDataGenerator", + "com.example.docs.damage.FabricDocsReferenceDamageTypesDataGenerator" + ] + }, + "mixins": [ + "fabric-docs-reference.mixins.json", + { + "config": "fabric-docs-reference.client.mixins.json", + "environment": "client" + } + ], + "depends": { + "fabricloader": ">=0.15.3", + "minecraft": "~1.20.4", + "java": ">=17", + "fabric-api": "*" + } +} diff --git a/reference/build.gradle b/reference/build.gradle index 0e9490fcc..09806bac0 100644 --- a/reference/build.gradle +++ b/reference/build.gradle @@ -1,5 +1,5 @@ plugins { - id 'fabric-loom' version '1.4-SNAPSHOT' apply false + id 'fabric-loom' version '1.7-SNAPSHOT' apply false id "com.diffplug.spotless" version "6.23.3" apply false id 'checkstyle' } @@ -29,7 +29,7 @@ subprojects { } dependencies { - modImplementation "net.fabricmc:fabric-loader:0.15.3" + modImplementation "net.fabricmc:fabric-loader:0.15.11" } fabricApi { @@ -37,14 +37,14 @@ subprojects { } tasks.withType(JavaCompile).configureEach { - it.options.release = 17 + it.options.release = 21 } java { withSourcesJar() - sourceCompatibility = JavaVersion.VERSION_17 - targetCompatibility = JavaVersion.VERSION_17 + sourceCompatibility = JavaVersion.VERSION_21 + targetCompatibility = JavaVersion.VERSION_21 } spotless { diff --git a/reference/gradle/wrapper/gradle-wrapper.properties b/reference/gradle/wrapper/gradle-wrapper.properties index 1af9e0930..a4413138c 100644 --- a/reference/gradle/wrapper/gradle-wrapper.properties +++ b/reference/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME diff --git a/reference/latest/build.gradle b/reference/latest/build.gradle index 05afcfe97..b636d6a16 100644 --- a/reference/latest/build.gradle +++ b/reference/latest/build.gradle @@ -1,5 +1,9 @@ +def minecraftVersion = "1.21" +def yarnVersion = "1.21+build.7" +def fabricApiVersion = "0.100.4+1.21" + dependencies { - minecraft "com.mojang:minecraft:1.20.4" - mappings "net.fabricmc:yarn:1.20.4+build.3:v2" - modImplementation "net.fabricmc.fabric-api:fabric-api:0.92.0+1.20.4" + minecraft "com.mojang:minecraft:${minecraftVersion}" + mappings "net.fabricmc:yarn:${yarnVersion}:v2" + modImplementation "net.fabricmc.fabric-api:fabric-api:${fabricApiVersion}" } diff --git a/reference/latest/src/client/java/com/example/docs/rendering/DrawContextExampleScreen.java b/reference/latest/src/client/java/com/example/docs/rendering/DrawContextExampleScreen.java index 833bdd88e..2f79aa2f7 100644 --- a/reference/latest/src/client/java/com/example/docs/rendering/DrawContextExampleScreen.java +++ b/reference/latest/src/client/java/com/example/docs/rendering/DrawContextExampleScreen.java @@ -55,13 +55,13 @@ public void render(DrawContext context, int mouseX, int mouseY, float delta) { // :::4 // :::5 - Identifier texture = new Identifier("minecraft", "textures/block/deepslate.png"); + Identifier texture = Identifier.of("minecraft", "textures/block/deepslate.png"); // texture, x, y, u, v, width, height, textureWidth, textureHeight context.drawTexture(texture, 90, 90, 0, 0, 16, 16, 16, 16); // :::5 // :::6 - Identifier texture2 = new Identifier("fabric-docs-reference", "textures/gui/test-uv-drawing.png"); + Identifier texture2 = Identifier.of("fabric-docs-reference", "textures/gui/test-uv-drawing.png"); int u = 10, v = 13, regionWidth = 14, regionHeight = 14; // texture, x, y, width, height, u, v, regionWidth, regionHeight, textureWidth, textureHeight context.drawTexture(texture2, 90, 190, 14, 14, u, v, regionWidth, regionHeight, 256, 256); diff --git a/reference/latest/src/client/java/com/example/docs/rendering/HudRenderingEntrypoint.java b/reference/latest/src/client/java/com/example/docs/rendering/HudRenderingEntrypoint.java index b645a5e3a..d226f49fe 100644 --- a/reference/latest/src/client/java/com/example/docs/rendering/HudRenderingEntrypoint.java +++ b/reference/latest/src/client/java/com/example/docs/rendering/HudRenderingEntrypoint.java @@ -11,12 +11,12 @@ public class HudRenderingEntrypoint implements ClientModInitializer { @Override public void onInitializeClient() { // :::1 - HudRenderCallback.EVENT.register((context, tickDelta) -> { + HudRenderCallback.EVENT.register((context, tickDeltaManager) -> { int color = 0xFFFF0000; // Red int targetColor = 0xFF00FF00; // Green // Total tick delta is stored in a field, so we can use it later. - totalTickDelta += tickDelta; + totalTickDelta += tickDeltaManager.getTickDelta(true); // "lerp" simply means "linear interpolation", which is a fancy way of saying "blend". float lerpedAmount = MathHelper.abs(MathHelper.sin(totalTickDelta / 50F)); diff --git a/reference/latest/src/client/java/com/example/docs/rendering/RenderingConceptsEntrypoint.java b/reference/latest/src/client/java/com/example/docs/rendering/RenderingConceptsEntrypoint.java index 415df486b..311ea2434 100644 --- a/reference/latest/src/client/java/com/example/docs/rendering/RenderingConceptsEntrypoint.java +++ b/reference/latest/src/client/java/com/example/docs/rendering/RenderingConceptsEntrypoint.java @@ -4,6 +4,7 @@ import org.joml.Matrix4f; import net.minecraft.client.render.BufferBuilder; +import net.minecraft.client.render.BufferRenderer; import net.minecraft.client.render.GameRenderer; import net.minecraft.client.render.Tessellator; import net.minecraft.client.render.VertexFormat; @@ -22,7 +23,7 @@ public class RenderingConceptsEntrypoint implements ClientModInitializer { public void onInitializeClient() { // "A Practical Example: Rendering a Triangle Strip" // :::1 - HudRenderCallback.EVENT.register((drawContext, tickDelta) -> { + HudRenderCallback.EVENT.register((drawContext, tickDeltaManager) -> { // :::1 if (true) { return; @@ -32,7 +33,7 @@ public void onInitializeClient() { MatrixStack matrices = drawContext.getMatrices(); // Store the total tick delta in a field, so we can use it later. - totalTickDelta += tickDelta; + totalTickDelta += tickDeltaManager.getTickDelta(true); // Push a new matrix onto the stack. matrices.push(); @@ -41,7 +42,6 @@ public void onInitializeClient() { // Get the transformation matrix from the matrix stack, alongside the tessellator instance and a new buffer builder. Matrix4f transformationMatrix = drawContext.getMatrices().peek().getPositionMatrix(); Tessellator tessellator = Tessellator.getInstance(); - BufferBuilder buffer = tessellator.getBuffer(); // :::1 // :::2 @@ -63,21 +63,21 @@ public void onInitializeClient() { // :::3 // :::1 - // Initialize the buffer using the specified format and draw mode. - buffer.begin(VertexFormat.DrawMode.TRIANGLE_STRIP, VertexFormats.POSITION_COLOR); + // Begin a triangle strip buffer using the POSITION_COLOR vertex format. + BufferBuilder buffer = tessellator.begin(VertexFormat.DrawMode.TRIANGLE_STRIP, VertexFormats.POSITION_COLOR); // Write our vertices, Z doesn't really matter since it's on the HUD. - buffer.vertex(transformationMatrix, 20, 20, 5).color(0xFF414141).next(); - buffer.vertex(transformationMatrix, 5, 40, 5).color(0xFF000000).next(); - buffer.vertex(transformationMatrix, 35, 40, 5).color(0xFF000000).next(); - buffer.vertex(transformationMatrix, 20, 60, 5).color(0xFF414141).next(); + buffer.vertex(transformationMatrix, 20, 20, 5).color(0xFF414141); + buffer.vertex(transformationMatrix, 5, 40, 5).color(0xFF000000); + buffer.vertex(transformationMatrix, 35, 40, 5).color(0xFF000000); + buffer.vertex(transformationMatrix, 20, 60, 5).color(0xFF414141); // We'll get to this bit in the next section. RenderSystem.setShader(GameRenderer::getPositionColorProgram); RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F); // Draw the buffer onto the screen. - tessellator.draw(); + BufferRenderer.drawWithGlobalProgram(buffer.end()); // :::1 // :::2 diff --git a/reference/latest/src/client/java/com/example/docs/rendering/TextTests.java b/reference/latest/src/client/java/com/example/docs/rendering/TextTests.java index 036207d27..84d725e79 100644 --- a/reference/latest/src/client/java/com/example/docs/rendering/TextTests.java +++ b/reference/latest/src/client/java/com/example/docs/rendering/TextTests.java @@ -1,18 +1,27 @@ package com.example.docs.rendering; +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.mojang.serialization.JsonOps; + import net.minecraft.text.MutableText; import net.minecraft.text.Text; +import net.minecraft.text.TextCodecs; public class TextTests { public void test() { // :::1 + Gson gson = new Gson(); MutableText mutable = Text.translatable("my_mod.text.bye"); - String json = Text.Serialization.toJsonString(mutable); + String json = gson.toJson(TextCodecs.CODEC.encodeStart(JsonOps.INSTANCE, mutable).getOrThrow()); // :::1 // :::2 - String jsonString = Text.Serialization.toJsonString(mutable); - MutableText deserialized = Text.Serialization.fromJson(jsonString); + String jsonString = "..."; + Text deserialized = TextCodecs.CODEC + .decode(JsonOps.INSTANCE, gson.fromJson(jsonString, JsonElement.class)) + .getOrThrow() + .getFirst(); // :::2 } } diff --git a/reference/latest/src/client/java/com/example/docs/rendering/screens/CustomScreen.java b/reference/latest/src/client/java/com/example/docs/rendering/screens/CustomScreen.java index 02e0d76cd..1cf609b28 100644 --- a/reference/latest/src/client/java/com/example/docs/rendering/screens/CustomScreen.java +++ b/reference/latest/src/client/java/com/example/docs/rendering/screens/CustomScreen.java @@ -22,6 +22,7 @@ public void close() { } // :::2 + // :::1 public CustomScreen(Text title) { super(title); } diff --git a/reference/latest/src/main/java/com/example/docs/FabricDocsReference.java b/reference/latest/src/main/java/com/example/docs/FabricDocsReference.java index 86ea5a4b1..60d387be5 100644 --- a/reference/latest/src/main/java/com/example/docs/FabricDocsReference.java +++ b/reference/latest/src/main/java/com/example/docs/FabricDocsReference.java @@ -3,7 +3,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import net.minecraft.particle.DefaultParticleType; +import net.minecraft.particle.SimpleParticleType; import net.minecraft.registry.Registries; import net.minecraft.registry.Registry; import net.minecraft.util.Identifier; @@ -22,7 +22,7 @@ public class FabricDocsReference implements ModInitializer { //#entrypoint //#particle_register_main // This DefaultParticleType gets called when you want to use your particle in code. - public static final DefaultParticleType SPARKLE_PARTICLE = FabricParticleTypes.simple(); + public static final SimpleParticleType SPARKLE_PARTICLE = FabricParticleTypes.simple(); //#particle_register_main //#entrypoint @@ -37,7 +37,7 @@ public void onInitialize() { //#particle_register_main // Register our custom particle type in the mod initializer. - Registry.register(Registries.PARTICLE_TYPE, new Identifier(MOD_ID, "sparkle_particle"), SPARKLE_PARTICLE); + Registry.register(Registries.PARTICLE_TYPE, Identifier.of(MOD_ID, "sparkle_particle"), SPARKLE_PARTICLE); //#particle_register_main //#entrypoint } diff --git a/reference/latest/src/main/java/com/example/docs/block/ModBlocks.java b/reference/latest/src/main/java/com/example/docs/block/ModBlocks.java index 599018e2c..c7ec6ea98 100644 --- a/reference/latest/src/main/java/com/example/docs/block/ModBlocks.java +++ b/reference/latest/src/main/java/com/example/docs/block/ModBlocks.java @@ -47,7 +47,7 @@ public class ModBlocks { // :::1 public static Block register(Block block, String name, boolean shouldRegisterItem) { // Register the block and its item. - Identifier id = new Identifier(FabricDocsReference.MOD_ID, name); + Identifier id = Identifier.of(FabricDocsReference.MOD_ID, name); // Sometimes, you may not want to register an item for the block. // Eg: if it's a technical block like `minecraft:air` or `minecraft:end_gateway` diff --git a/reference/latest/src/main/java/com/example/docs/block/custom/PrismarineLampBlock.java b/reference/latest/src/main/java/com/example/docs/block/custom/PrismarineLampBlock.java index b81112be3..7bd4cff2c 100644 --- a/reference/latest/src/main/java/com/example/docs/block/custom/PrismarineLampBlock.java +++ b/reference/latest/src/main/java/com/example/docs/block/custom/PrismarineLampBlock.java @@ -8,7 +8,6 @@ import net.minecraft.state.StateManager; import net.minecraft.state.property.BooleanProperty; import net.minecraft.util.ActionResult; -import net.minecraft.util.Hand; import net.minecraft.util.hit.BlockHitResult; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; @@ -36,7 +35,7 @@ protected void appendProperties(StateManager.Builder builder) // :::2 // :::4 @Override - public ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) { + protected ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, BlockHitResult hit) { if (!player.getAbilities().allowModifyWorld) { // Skip if the player isn't allowed to modify the world. return ActionResult.PASS; diff --git a/reference/latest/src/main/java/com/example/docs/codec/BeanType.java b/reference/latest/src/main/java/com/example/docs/codec/BeanType.java index 2e75bf8bf..52effe3c1 100644 --- a/reference/latest/src/main/java/com/example/docs/codec/BeanType.java +++ b/reference/latest/src/main/java/com/example/docs/codec/BeanType.java @@ -14,6 +14,6 @@ public record BeanType(Codec codec) { // Create a registry to map identifiers to bean types public static final Registry> REGISTRY = new SimpleRegistry<>( - RegistryKey.ofRegistry(new Identifier("example", "bean_types")), Lifecycle.stable()); + RegistryKey.ofRegistry(Identifier.of("example", "bean_types")), Lifecycle.stable()); } // ::: diff --git a/reference/latest/src/main/java/com/example/docs/codec/BeanTypes.java b/reference/latest/src/main/java/com/example/docs/codec/BeanTypes.java index c1cc08d30..b1cbed28a 100644 --- a/reference/latest/src/main/java/com/example/docs/codec/BeanTypes.java +++ b/reference/latest/src/main/java/com/example/docs/codec/BeanTypes.java @@ -12,7 +12,7 @@ public class BeanTypes { public static final BeanType COUNTING_BEAN = register("counting_bean", new BeanType<>(CountingBean.CODEC)); public static BeanType register(String id, BeanType beanType) { - return Registry.register(BeanType.REGISTRY, new Identifier("example", id), beanType); + return Registry.register(BeanType.REGISTRY, Identifier.of("example", id), beanType); } } // ::: diff --git a/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java b/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java index 10b2ef0c9..c79d574d3 100644 --- a/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java +++ b/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java @@ -32,7 +32,7 @@ public void onInitialize() { // :::11 ArgumentTypeRegistry.registerArgumentType( - new Identifier("fabric-docs", "block_pos"), + Identifier.of("fabric-docs", "block_pos"), BlockPosArgumentType.class, ConstantArgumentSerializer.of(BlockPosArgumentType::new) ); diff --git a/reference/latest/src/main/java/com/example/docs/damage/FabricDocsReferenceDamageTypes.java b/reference/latest/src/main/java/com/example/docs/damage/FabricDocsReferenceDamageTypes.java index 5bb8b9bf9..b8c8d714b 100644 --- a/reference/latest/src/main/java/com/example/docs/damage/FabricDocsReferenceDamageTypes.java +++ b/reference/latest/src/main/java/com/example/docs/damage/FabricDocsReferenceDamageTypes.java @@ -16,12 +16,12 @@ public class FabricDocsReferenceDamageTypes implements ModInitializer { public static final Block TATER_BLOCK = new TaterBlock(AbstractBlock.Settings.create()); // :::1 - public static final RegistryKey TATER_DAMAGE = RegistryKey.of(RegistryKeys.DAMAGE_TYPE, new Identifier("fabric-docs-reference", "tater")); + public static final RegistryKey TATER_DAMAGE = RegistryKey.of(RegistryKeys.DAMAGE_TYPE, Identifier.of("fabric-docs-reference", "tater")); // :::1 @Override public void onInitialize() { - Registry.register(Registries.BLOCK, new Identifier("fabric-docs-reference", "tater"), TATER_BLOCK); - Registry.register(Registries.ITEM, new Identifier("fabric-docs-reference", "tater"), new BlockItem(TATER_BLOCK, new Item.Settings())); + Registry.register(Registries.BLOCK, Identifier.of("fabric-docs-reference", "tater"), TATER_BLOCK); + Registry.register(Registries.ITEM, Identifier.of("fabric-docs-reference", "tater"), new BlockItem(TATER_BLOCK, new Item.Settings())); } } diff --git a/reference/latest/src/main/java/com/example/docs/damage/FabricDocsReferenceDamageTypesDataGenerator.java b/reference/latest/src/main/java/com/example/docs/damage/FabricDocsReferenceDamageTypesDataGenerator.java index 32466d71c..862e74ab5 100644 --- a/reference/latest/src/main/java/com/example/docs/damage/FabricDocsReferenceDamageTypesDataGenerator.java +++ b/reference/latest/src/main/java/com/example/docs/damage/FabricDocsReferenceDamageTypesDataGenerator.java @@ -45,7 +45,7 @@ private static class TaterDamageTypeTagGenerator extends FabricTagProvider run(DataWriter writer) { damageTypeObject.addProperty("message_id", TATER_DAMAGE_TYPE.msgId()); damageTypeObject.addProperty("scaling", TATER_DAMAGE_TYPE.scaling().asString()); - return DataProvider.writeToPath(writer, damageTypeObject, path.resolveJson(new Identifier("fabric-docs-reference", "tater"))); + return DataProvider.writeToPath(writer, damageTypeObject, path.resolveJson(Identifier.of("fabric-docs-reference", "tater"))); } @Override diff --git a/reference/latest/src/main/java/com/example/docs/effect/FabricDocsReferenceEffects.java b/reference/latest/src/main/java/com/example/docs/effect/FabricDocsReferenceEffects.java index e63ed6b16..c9b10fc22 100644 --- a/reference/latest/src/main/java/com/example/docs/effect/FabricDocsReferenceEffects.java +++ b/reference/latest/src/main/java/com/example/docs/effect/FabricDocsReferenceEffects.java @@ -9,11 +9,15 @@ // :::1 public class FabricDocsReferenceEffects implements ModInitializer { - public static final StatusEffect TATER_EFFECT = new TaterEffect(); + public static final StatusEffect TATER_EFFECT; + + static { + TATER_EFFECT = Registry.register(Registries.STATUS_EFFECT, Identifier.of("fabric-docs-reference", "tater"), new TaterEffect()); + } @Override public void onInitialize() { - Registry.register(Registries.STATUS_EFFECT, new Identifier("fabric-docs-reference", "tater"), TATER_EFFECT); + // ... } } // :::1 diff --git a/reference/latest/src/main/java/com/example/docs/effect/TaterEffect.java b/reference/latest/src/main/java/com/example/docs/effect/TaterEffect.java index 3c434af1c..eb0a705b5 100644 --- a/reference/latest/src/main/java/com/example/docs/effect/TaterEffect.java +++ b/reference/latest/src/main/java/com/example/docs/effect/TaterEffect.java @@ -20,12 +20,14 @@ public boolean canApplyUpdateEffect(int duration, int amplifier) { return true; } - // Called when the effect is applied + // Called when the effect is applied. @Override - public void applyUpdateEffect(LivingEntity entity, int amplifier) { + public boolean applyUpdateEffect(LivingEntity entity, int amplifier) { if (entity instanceof PlayerEntity) { ((PlayerEntity) entity).addExperience(1 << amplifier); // Higher amplifier gives you experience faster } + + return super.applyUpdateEffect(entity, amplifier); } } // :::1 diff --git a/reference/latest/src/main/java/com/example/docs/event/FabricDocsReferenceEvents.java b/reference/latest/src/main/java/com/example/docs/event/FabricDocsReferenceEvents.java index 64b6f84b9..922834ebd 100644 --- a/reference/latest/src/main/java/com/example/docs/event/FabricDocsReferenceEvents.java +++ b/reference/latest/src/main/java/com/example/docs/event/FabricDocsReferenceEvents.java @@ -6,9 +6,10 @@ import net.minecraft.item.ItemStack; import net.minecraft.item.Items; import net.minecraft.loot.LootPool; +import net.minecraft.loot.LootTable; import net.minecraft.loot.entry.ItemEntry; +import net.minecraft.registry.RegistryKey; import net.minecraft.util.ActionResult; -import net.minecraft.util.Identifier; import net.fabricmc.api.ModInitializer; import net.fabricmc.fabric.api.event.player.AttackBlockCallback; @@ -16,7 +17,7 @@ // Class to contain all mod events. public class FabricDocsReferenceEvents implements ModInitializer { - private static final Identifier COAL_ORE_LOOT_TABLE_ID = Blocks.COAL_ORE.getLootTableId(); + private static final RegistryKey COAL_ORE_LOOT_TABLE_ID = Blocks.COAL_ORE.getLootTableKey(); @Override public void onInitialize() { @@ -34,10 +35,10 @@ public void onInitialize() { // :::1 // :::2 - LootTableEvents.MODIFY.register((resourceManager, lootManager, id, tableBuilder, source) -> { + LootTableEvents.MODIFY.register((key, tableBuilder, source) -> { // Let's only modify built-in loot tables and leave data pack loot tables untouched by checking the source. // We also check that the loot table ID is equal to the ID we want. - if (source.isBuiltin() && COAL_ORE_LOOT_TABLE_ID.equals(id)) { + if (source.isBuiltin() && COAL_ORE_LOOT_TABLE_ID.equals(key)) { // We make the pool and add an item LootPool.Builder poolBuilder = LootPool.builder().with(ItemEntry.builder(Items.EGG)); tableBuilder.pool(poolBuilder); diff --git a/reference/latest/src/main/java/com/example/docs/item/FabricDocsReferenceItems.java b/reference/latest/src/main/java/com/example/docs/item/FabricDocsReferenceItems.java index 68d98da4a..fc7222cb0 100644 --- a/reference/latest/src/main/java/com/example/docs/item/FabricDocsReferenceItems.java +++ b/reference/latest/src/main/java/com/example/docs/item/FabricDocsReferenceItems.java @@ -2,10 +2,17 @@ import net.fabricmc.api.ModInitializer; +import com.example.docs.item.armor.ModArmorMaterials; + // :::1 public class FabricDocsReferenceItems implements ModInitializer { @Override public void onInitialize() { + // :::1 + // :::2 + ModArmorMaterials.initialize(); + // :::2 + // :::1 ModItems.initialize(); } } diff --git a/reference/latest/src/main/java/com/example/docs/item/ModItems.java b/reference/latest/src/main/java/com/example/docs/item/ModItems.java index 851ccbc79..12d4b2a2a 100644 --- a/reference/latest/src/main/java/com/example/docs/item/ModItems.java +++ b/reference/latest/src/main/java/com/example/docs/item/ModItems.java @@ -1,9 +1,9 @@ package com.example.docs.item; +import net.minecraft.component.type.FoodComponent; import net.minecraft.entity.effect.StatusEffectInstance; import net.minecraft.entity.effect.StatusEffects; import net.minecraft.item.ArmorItem; -import net.minecraft.item.FoodComponent; import net.minecraft.item.Item; import net.minecraft.item.ItemGroup; import net.minecraft.item.ItemGroups; @@ -15,14 +15,13 @@ import net.minecraft.text.Text; import net.minecraft.util.Identifier; -import net.fabricmc.fabric.api.item.v1.FabricItemSettings; import net.fabricmc.fabric.api.itemgroup.v1.FabricItemGroup; import net.fabricmc.fabric.api.itemgroup.v1.ItemGroupEvents; import net.fabricmc.fabric.api.registry.CompostingChanceRegistry; import net.fabricmc.fabric.api.registry.FuelRegistry; import com.example.docs.FabricDocsReference; -import com.example.docs.item.armor.GuiditeArmorMaterial; +import com.example.docs.item.armor.ModArmorMaterials; import com.example.docs.item.custom.LightningStick; import com.example.docs.item.tool.GuiditeMaterial; @@ -31,17 +30,17 @@ public class ModItems { // :::1 // :::6 - public static final Item GUIDITE_HELMET = register(new ArmorItem(GuiditeArmorMaterial.INSTANCE, ArmorItem.Type.HELMET, new Item.Settings()), "guidite_helmet"); - public static final Item GUIDITE_BOOTS = register(new ArmorItem(GuiditeArmorMaterial.INSTANCE, ArmorItem.Type.BOOTS, new Item.Settings()), "guidite_boots"); - public static final Item GUIDITE_LEGGINGS = register(new ArmorItem(GuiditeArmorMaterial.INSTANCE, ArmorItem.Type.LEGGINGS, new Item.Settings()), "guidite_leggings"); - public static final Item GUIDITE_CHESTPLATE = register(new ArmorItem(GuiditeArmorMaterial.INSTANCE, ArmorItem.Type.CHESTPLATE, new Item.Settings()), "guidite_chestplate"); + public static final Item GUIDITE_HELMET = register(new ArmorItem(ModArmorMaterials.GUIDIE, ArmorItem.Type.HELMET, new Item.Settings()), "guidite_helmet"); + public static final Item GUIDITE_BOOTS = register(new ArmorItem(ModArmorMaterials.GUIDIE, ArmorItem.Type.BOOTS, new Item.Settings()), "guidite_boots"); + public static final Item GUIDITE_LEGGINGS = register(new ArmorItem(ModArmorMaterials.GUIDIE, ArmorItem.Type.LEGGINGS, new Item.Settings()), "guidite_leggings"); + public static final Item GUIDITE_CHESTPLATE = register(new ArmorItem(ModArmorMaterials.GUIDIE, ArmorItem.Type.CHESTPLATE, new Item.Settings()), "guidite_chestplate"); // :::6 - public static final Item LIGHTNING_STICK = register(new LightningStick(new FabricItemSettings()), "lightning_stick"); + public static final Item LIGHTNING_STICK = register(new LightningStick(new Item.Settings()), "lightning_stick"); // :::7 - public static final Item GUIDITE_SWORD = register(new SwordItem(GuiditeMaterial.INSTANCE, 2, 0.5F, new FabricItemSettings()), "guidite_sword"); + public static final Item GUIDITE_SWORD = register(new SwordItem(GuiditeMaterial.INSTANCE, new Item.Settings()), "guidite_sword"); // :::7 // :::9 - public static final RegistryKey CUSTOM_ITEM_GROUP_KEY = RegistryKey.of(Registries.ITEM_GROUP.getKey(), new Identifier(FabricDocsReference.MOD_ID, "item_group")); + public static final RegistryKey CUSTOM_ITEM_GROUP_KEY = RegistryKey.of(Registries.ITEM_GROUP.getKey(), Identifier.of(FabricDocsReference.MOD_ID, "item_group")); public static final ItemGroup CUSTOM_ITEM_GROUP = FabricItemGroup.builder() .icon(() -> new ItemStack(ModItems.GUIDITE_SWORD)) .displayName(Text.translatable("itemGroup.fabric_docs_reference")) @@ -59,7 +58,7 @@ public class ModItems { // :::2 public static final Item SUSPICIOUS_SUBSTANCE = register( // Ignore the food component for now, we'll cover it later in the food section. - new Item(new FabricItemSettings().food(SUSPICIOUS_FOOD_COMPONENT)), + new Item(new Item.Settings().food(SUSPICIOUS_FOOD_COMPONENT)), "suspicious_substance" ); // :::2 @@ -67,7 +66,7 @@ public class ModItems { // :::1 public static Item register(Item item, String id) { // Create the identifier for the item. - Identifier itemID = new Identifier(FabricDocsReference.MOD_ID, id); + Identifier itemID = Identifier.of(FabricDocsReference.MOD_ID, id); // Register the item. Item registeredItem = Registry.register(Registries.ITEM, itemID, item); diff --git a/reference/latest/src/main/java/com/example/docs/item/armor/GuiditeArmorMaterial.java b/reference/latest/src/main/java/com/example/docs/item/armor/GuiditeArmorMaterial.java index d267b5ae1..eb0ed42df 100644 --- a/reference/latest/src/main/java/com/example/docs/item/armor/GuiditeArmorMaterial.java +++ b/reference/latest/src/main/java/com/example/docs/item/armor/GuiditeArmorMaterial.java @@ -1,97 +1,97 @@ -package com.example.docs.item.armor; - -import net.minecraft.item.ArmorItem; -import net.minecraft.item.ArmorMaterial; -import net.minecraft.recipe.Ingredient; -import net.minecraft.sound.SoundEvent; -import net.minecraft.sound.SoundEvents; - -import com.example.docs.item.ModItems; - -// :::1 -public class GuiditeArmorMaterial implements ArmorMaterial { - // ... - //:::1 - // :::_10 - public static final GuiditeArmorMaterial INSTANCE = new GuiditeArmorMaterial(); - - // :::_10 - // :::2 - @Override - public int getDurability(ArmorItem.Type type) { - // Replace this multiplier by a constant value for the durability of the armor. - // For reference, diamond uses 33 for all armor pieces, whilst leather uses 5. - int DURABILITY_MULTIPLIER = 12; - return switch (type) { - case BOOTS -> 13 * DURABILITY_MULTIPLIER; - case LEGGINGS -> 15 * DURABILITY_MULTIPLIER; - case CHESTPLATE -> 16 * DURABILITY_MULTIPLIER; - case HELMET -> 11 * DURABILITY_MULTIPLIER; - default -> 0; - }; - } - - // :::2 - // :::3 - @Override - public int getProtection(ArmorItem.Type type) { - // Protection values for all the slots. - // For reference, diamond uses 3 for boots, 6 for leggings, 8 for chestplate, and 3 for helmet, - // whilst leather uses 1, 2, 3 and 1 respectively. - return switch (type) { - case BOOTS, HELMET -> 3; - case LEGGINGS -> 6; - case CHESTPLATE -> 8; - default -> 0; - }; - } - - // :::3 - // :::4 - @Override - public int getEnchantability() { - return 5; - } - - // :::4 - // :::5 - @Override - public SoundEvent getEquipSound() { - // Example for Iron Armor - return SoundEvents.ITEM_ARMOR_EQUIP_IRON; - } - - // :::5 - // :::6 - @Override - public Ingredient getRepairIngredient() { - return Ingredient.ofItems(ModItems.SUSPICIOUS_SUBSTANCE); - } - - // :::6 - // :::7 - @Override - public String getName() { - return "guidite"; - } - - // :::7 - // :::8 - @Override - public float getToughness() { - return 2.0F; - } - - // :::8 - // :::9 - @Override - public float getKnockbackResistance() { - // We don't want knockback resistance for guidite armor, but if you do, - // change this value to 0.XF, where X is the level of knockback resistance you want. - return 0; - } - - // :::9 - // :::1 -} -// :::1 +//package com.example.docs.item.armor; +// +//import net.minecraft.item.ArmorItem; +//import net.minecraft.item.ArmorMaterial; +//import net.minecraft.recipe.Ingredient; +//import net.minecraft.sound.SoundEvent; +//import net.minecraft.sound.SoundEvents; +// +//import com.example.docs.item.ModItems; +// +//// :::1 +//public class GuiditeArmorMaterial implements ArmorMaterial { +// // ... +// //:::1 +// // :::_10 +// public static final GuiditeArmorMaterial INSTANCE = new GuiditeArmorMaterial(); +// +// // :::_10 +// // :::2 +// @Override +// public int getDurability(ArmorItem.Type type) { +// // Replace this multiplier by a constant value for the durability of the armor. +// // For reference, diamond uses 33 for all armor pieces, whilst leather uses 5. +// int DURABILITY_MULTIPLIER = 12; +// return switch (type) { +// case BOOTS -> 13 * DURABILITY_MULTIPLIER; +// case LEGGINGS -> 15 * DURABILITY_MULTIPLIER; +// case CHESTPLATE -> 16 * DURABILITY_MULTIPLIER; +// case HELMET -> 11 * DURABILITY_MULTIPLIER; +// default -> 0; +// }; +// } +// +// // :::2 +// // :::3 +// @Override +// public int getProtection(ArmorItem.Type type) { +// // Protection values for all the slots. +// // For reference, diamond uses 3 for boots, 6 for leggings, 8 for chestplate, and 3 for helmet, +// // whilst leather uses 1, 2, 3 and 1 respectively. +// return switch (type) { +// case BOOTS, HELMET -> 3; +// case LEGGINGS -> 6; +// case CHESTPLATE -> 8; +// default -> 0; +// }; +// } +// +// // :::3 +// // :::4 +// @Override +// public int getEnchantability() { +// return 5; +// } +// +// // :::4 +// // :::5 +// @Override +// public SoundEvent getEquipSound() { +// // Example for Iron Armor +// return SoundEvents.ITEM_ARMOR_EQUIP_IRON; +// } +// +// // :::5 +// // :::6 +// @Override +// public Ingredient getRepairIngredient() { +// return Ingredient.ofItems(ModItems.SUSPICIOUS_SUBSTANCE); +// } +// +// // :::6 +// // :::7 +// @Override +// public String getName() { +// return "guidite"; +// } +// +// // :::7 +// // :::8 +// @Override +// public float getToughness() { +// return 2.0F; +// } +// +// // :::8 +// // :::9 +// @Override +// public float getKnockbackResistance() { +// // We don't want knockback resistance for guidite armor, but if you do, +// // change this value to 0.XF, where X is the level of knockback resistance you want. +// return 0; +// } +// +// // :::9 +// // :::1 +//} +//// :::1 diff --git a/reference/latest/src/main/java/com/example/docs/item/armor/ModArmorMaterials.java b/reference/latest/src/main/java/com/example/docs/item/armor/ModArmorMaterials.java new file mode 100644 index 000000000..8a0dd49b9 --- /dev/null +++ b/reference/latest/src/main/java/com/example/docs/item/armor/ModArmorMaterials.java @@ -0,0 +1,63 @@ +package com.example.docs.item.armor; + +import java.util.List; +import java.util.Map; +import java.util.function.Supplier; + +import net.minecraft.item.ArmorItem; +import net.minecraft.item.ArmorMaterial; +import net.minecraft.recipe.Ingredient; +import net.minecraft.registry.Registries; +import net.minecraft.registry.Registry; +import net.minecraft.registry.entry.RegistryEntry; +import net.minecraft.sound.SoundEvent; +import net.minecraft.sound.SoundEvents; +import net.minecraft.util.Identifier; + +import com.example.docs.FabricDocsReference; +import com.example.docs.item.ModItems; + +public class ModArmorMaterials { + // :::2 + public static final RegistryEntry GUIDIE = registerMaterial("guidite", + // Defense (protection) point values for each armor piece. + Map.of( + ArmorItem.Type.HELMET, 3, + ArmorItem.Type.CHESTPLATE, 8, + ArmorItem.Type.LEGGINGS, 6, + ArmorItem.Type.BOOTS, 3 + ), + // Enchantability. For reference, leather has 15, iron has 9, and diamond has 10. + 5, + // The sound played when the armor is equipped. + SoundEvents.ITEM_ARMOR_EQUIP_IRON, + // The ingredient(s) used to repair the armor. + () -> Ingredient.ofItems(ModItems.SUSPICIOUS_SUBSTANCE), + 0.0F, + 0.0F, + // Guidite is NOT dyeable, so we will pass false. + false); + // :::2 + + // :::1 + public static RegistryEntry registerMaterial(String id, Map defensePoints, int enchantability, RegistryEntry equipSound, Supplier repairIngredientSupplier, float toughness, float knockbackResistance, boolean dyeable) { + // Get the supported layers for the armor material + List layers = List.of( + // The ID of the texture layer, the suffix, and whether the layer is dyeable. + // We can just pass the armor material ID as the texture layer ID. + // We have no need for a suffix, so we'll pass an empty string. + // We'll pass the dyeable boolean we received as the dyeable parameter. + new ArmorMaterial.Layer(Identifier.of(FabricDocsReference.MOD_ID, id), "", dyeable) + ); + + ArmorMaterial material = new ArmorMaterial(defensePoints, enchantability, equipSound, repairIngredientSupplier, layers, toughness, knockbackResistance); + // Register the material within the ArmorMaterials registry. + material = Registry.register(Registries.ARMOR_MATERIAL, Identifier.of(FabricDocsReference.MOD_ID, id), material); + + // The majority of the time, you'll want the RegistryEntry of the material - especially for the ArmorItem constructor. + return RegistryEntry.of(material); + } + + // :::1 + public static void initialize() { } +} diff --git a/reference/latest/src/main/java/com/example/docs/item/custom/LightningStick.java b/reference/latest/src/main/java/com/example/docs/item/custom/LightningStick.java index 14fd6c366..c7477af01 100644 --- a/reference/latest/src/main/java/com/example/docs/item/custom/LightningStick.java +++ b/reference/latest/src/main/java/com/example/docs/item/custom/LightningStick.java @@ -2,14 +2,12 @@ import java.util.List; -import org.jetbrains.annotations.Nullable; - -import net.minecraft.client.item.TooltipContext; import net.minecraft.entity.EntityType; import net.minecraft.entity.LightningEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; +import net.minecraft.item.tooltip.TooltipType; import net.minecraft.text.Text; import net.minecraft.util.Formatting; import net.minecraft.util.Hand; @@ -48,7 +46,7 @@ public TypedActionResult use(World world, PlayerEntity user, Hand han // :::2 // :::3 @Override - public void appendTooltip(ItemStack stack, @Nullable World world, List tooltip, TooltipContext context) { + public void appendTooltip(ItemStack stack, TooltipContext context, List tooltip, TooltipType type) { tooltip.add(Text.translatable("itemTooltip.fabric-docs-reference.lightning_stick").formatted(Formatting.GOLD)); } diff --git a/reference/latest/src/main/java/com/example/docs/item/tool/GuiditeMaterial.java b/reference/latest/src/main/java/com/example/docs/item/tool/GuiditeMaterial.java index 9e217f700..bd148a901 100644 --- a/reference/latest/src/main/java/com/example/docs/item/tool/GuiditeMaterial.java +++ b/reference/latest/src/main/java/com/example/docs/item/tool/GuiditeMaterial.java @@ -1,8 +1,11 @@ package com.example.docs.item.tool; +import net.minecraft.block.Block; import net.minecraft.item.Items; import net.minecraft.item.ToolMaterial; import net.minecraft.recipe.Ingredient; +import net.minecraft.registry.tag.BlockTags; +import net.minecraft.registry.tag.TagKey; import com.example.docs.item.ModItems; @@ -37,8 +40,8 @@ public float getAttackDamage() { // :::4 // :::5 @Override - public int getMiningLevel() { - return 3; + public TagKey getInverseTag() { + return BlockTags.INCORRECT_FOR_IRON_TOOL; } // :::5 diff --git a/reference/latest/src/main/java/com/example/docs/potion/FabricDocsReferencePotions.java b/reference/latest/src/main/java/com/example/docs/potion/FabricDocsReferencePotions.java index 82b3c60f6..3c8ea1530 100644 --- a/reference/latest/src/main/java/com/example/docs/potion/FabricDocsReferencePotions.java +++ b/reference/latest/src/main/java/com/example/docs/potion/FabricDocsReferencePotions.java @@ -4,12 +4,13 @@ import net.minecraft.item.Items; import net.minecraft.potion.Potion; import net.minecraft.potion.Potions; -import net.minecraft.recipe.BrewingRecipeRegistry; import net.minecraft.registry.Registries; import net.minecraft.registry.Registry; +import net.minecraft.registry.entry.RegistryEntry; import net.minecraft.util.Identifier; import net.fabricmc.api.ModInitializer; +import net.fabricmc.fabric.api.registry.FabricBrewingRecipeRegistryBuilder; import com.example.docs.effect.FabricDocsReferenceEffects; @@ -18,19 +19,25 @@ public class FabricDocsReferencePotions implements ModInitializer { public static final Potion TATER_POTION = Registry.register( Registries.POTION, - new Identifier("fabric-docs-reference", "tater"), + Identifier.of("fabric-docs-reference", "tater"), new Potion( new StatusEffectInstance( - FabricDocsReferenceEffects.TATER_EFFECT, + RegistryEntry.of(FabricDocsReferenceEffects.TATER_EFFECT), 3600, 0))); @Override public void onInitialize() { - BrewingRecipeRegistry.registerPotionRecipe(Potions.WATER, Items.POTATO, TATER_POTION); - - // Use the mixin invoker if you are not using Fabric API - // BrewingRecipeRegistryInvoker.invokeRegisterPotionRecipe(Potions.WATER, Items.POTATO, TATER_POTION); + FabricBrewingRecipeRegistryBuilder.BUILD.register(builder -> { + builder.registerPotionRecipe( + // Input potion. + Potions.WATER, + // Ingredient + Items.POTATO, + // Output potion. + RegistryEntry.of(TATER_POTION) + ); + }); } } // :::1 diff --git a/reference/latest/src/main/java/com/example/docs/sound/CustomSounds.java b/reference/latest/src/main/java/com/example/docs/sound/CustomSounds.java index c988b966f..146aa2fa0 100644 --- a/reference/latest/src/main/java/com/example/docs/sound/CustomSounds.java +++ b/reference/latest/src/main/java/com/example/docs/sound/CustomSounds.java @@ -17,7 +17,7 @@ private CustomSounds() { // actual registration of all the custom SoundEvents private static SoundEvent registerSound(String id) { - Identifier identifier = new Identifier(FabricDocsReferenceSounds.MOD_ID, id); + Identifier identifier = Identifier.of(FabricDocsReferenceSounds.MOD_ID, id); return Registry.register(Registries.SOUND_EVENT, identifier, SoundEvent.of(identifier)); } diff --git a/reference/latest/src/main/java/com/example/docs/sound/FabricDocsReferenceSounds.java b/reference/latest/src/main/java/com/example/docs/sound/FabricDocsReferenceSounds.java index cc45f2bda..dbb925e9f 100644 --- a/reference/latest/src/main/java/com/example/docs/sound/FabricDocsReferenceSounds.java +++ b/reference/latest/src/main/java/com/example/docs/sound/FabricDocsReferenceSounds.java @@ -20,8 +20,8 @@ public class FabricDocsReferenceSounds implements ModInitializer { public void onInitialize() { // This is the basic registering. Use a new class for registering sounds // instead, to keep the ModInitializer implementing class clean! - Registry.register(Registries.SOUND_EVENT, new Identifier(MOD_ID, "metal_whistle"), - SoundEvent.of(new Identifier(MOD_ID, "metal_whistle"))); + Registry.register(Registries.SOUND_EVENT, Identifier.of(MOD_ID, "metal_whistle"), + SoundEvent.of(Identifier.of(MOD_ID, "metal_whistle"))); // ... the cleaner approach. // [!code focus] // CustomSounds.initialize(); // [!code focus] diff --git a/reference/latest/src/main/resources/assets/fabric-docs-reference/textures/models/armor/guidite_layer_1.png b/reference/latest/src/main/resources/assets/fabric-docs-reference/textures/models/armor/guidite_layer_1.png new file mode 100644 index 000000000..a02174be7 Binary files /dev/null and b/reference/latest/src/main/resources/assets/fabric-docs-reference/textures/models/armor/guidite_layer_1.png differ diff --git a/reference/latest/src/main/resources/assets/fabric-docs-reference/textures/models/armor/guidite_layer_2.png b/reference/latest/src/main/resources/assets/fabric-docs-reference/textures/models/armor/guidite_layer_2.png new file mode 100644 index 000000000..a2c9693c3 Binary files /dev/null and b/reference/latest/src/main/resources/assets/fabric-docs-reference/textures/models/armor/guidite_layer_2.png differ diff --git a/reference/latest/src/main/resources/fabric-docs-reference.mixins.json b/reference/latest/src/main/resources/fabric-docs-reference.mixins.json index 18611e85e..c70c74242 100644 --- a/reference/latest/src/main/resources/fabric-docs-reference.mixins.json +++ b/reference/latest/src/main/resources/fabric-docs-reference.mixins.json @@ -4,8 +4,7 @@ "compatibilityLevel": "JAVA_17", "mixins": [ "ExampleMixin", - "event.SheepEntityMixin", - "potion.BrewingRecipeRegistryInvoker" + "event.SheepEntityMixin" ], "injectors": { "defaultRequire": 1 diff --git a/reference/latest/src/main/resources/fabric.mod.json b/reference/latest/src/main/resources/fabric.mod.json index f9a265034..b8713244c 100644 --- a/reference/latest/src/main/resources/fabric.mod.json +++ b/reference/latest/src/main/resources/fabric.mod.json @@ -33,10 +33,5 @@ "environment": "client" } ], - "depends": { - "fabricloader": ">=0.15.3", - "minecraft": "~1.20.4", - "java": ">=17", - "fabric-api": "*" - } + "depends": {} } diff --git a/reference/settings.gradle b/reference/settings.gradle index 889d7b772..281aa1097 100644 --- a/reference/settings.gradle +++ b/reference/settings.gradle @@ -9,4 +9,5 @@ pluginManagement { } } -include "latest" \ No newline at end of file +include "latest" +include "1.20.4" \ No newline at end of file diff --git a/versions/1.20.4/develop/blocks/blockstates.md b/versions/1.20.4/develop/blocks/blockstates.md new file mode 100644 index 000000000..6945b1a2d --- /dev/null +++ b/versions/1.20.4/develop/blocks/blockstates.md @@ -0,0 +1,127 @@ +--- +title: Block States +description: Learn why blockstates are a great way to add visual functionality to your blocks. +authors: + - IMB11 +--- + +# Block States {#block-states} + +A block state is a piece of data attached to a singular block in the Minecraft world containing information on the block in the form of properties - some examples of properties vanilla stores in block states: + +- Rotation: Mostly used for logs and other natural blocks. +- Activated: Heavily used in redstone devices, and blocks such as the furnace or smoker. +- Age: Used in crops, plants, saplings, kelp etc. + +You can probably see why they are useful - they avoid the need to store NBT data in a block entity - reducing the world size, and preventing TPS issues! + +Blockstate definitions are found in the `assets//blockstates` folder. + +## Example: Pillar Block {#pillar-block} + + + +Minecraft has some custom classes already that allow you quickly create certain types of blocks - this example goes through the creation of a block with the `axis` property by creating a "Condensed Oak Log" block. + +The vanilla `PillarBlock` class allows the block to be placed in the X, Y or Z axis. + +@[code transcludeWith=:::3](@/reference/1.20.4/src/main/java/com/example/docs/block/ModBlocks.java) + +Pillar blocks have two textures, top and side - they use the `block/cube_column` model. + +As always, with all block textures, the texture files can be found in `assets//textures/block` + + + +Since the pillar block has two positions, horizontal and vertical, we'll need to make two separate model files: + +- `condensed_oak_log_horizontal.json` which extends the `block/cube_column_horizontal` model. +- `condensed_oak_log.json` which extends the `block/cube_column` model. + +An example of the `condensed_oak_log_horizontal.json` file: + +@[code](@/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/block/condensed_oak_log_horizontal.json) + +--- + +::: info +Remember, blockstate files can be found in the `assets//blockstates` folder, the name of the blockstate file should match the block ID used when registering your block in the `ModBlocks` class. For instance, if the block ID is `condensed_oak_log`, the file should be named `condensed_oak_log.json`. + +For a more in-depth look at all the modifiers available in the blockstate files, check out the [Minecraft Wiki - Models (Block States)](https://minecraft.wiki/w/Tutorials/Models#Block_states) page. +::: + +Next, we need to create a blockstate file. The blockstate file is where the magic happens—pillar blocks have three axes, so we'll use specific models for the following situations: + +- `axis=x` - When the block is placed along the X axis, we will rotate the model to face the positive X direction. +- `axis=y` - When the block is placed along the Y axis, we will use the normal vertical model. +- `axis=z` - When the block is placed along the Z axis, we will rotate the model to face the positive X direction. + +@[code](@/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/blockstates/condensed_oak_log.json) + +As always, you'll need to create a translation for your block, and an item model which parents either of the two models. + +![Example of Pillar block in-game](/assets/develop/blocks/blockstates_1.png) + +## Custom Block States {#custom-block-states} + +Custom block states are great if your block has unique properties - sometimes you may find that your block can re-use vanilla properties. + +This example will create a unique boolean property called `activated` - when a player right-clicks on the block, the block will go from `activated=false` to `activated=true` - changing its texture accordingly. + +### Creating The Property {#creating-the-property} + +Firstly, you'll need to create the property itself - since this is a boolean, we'll use the `BooleanProperty.of` method. + +@[code transcludeWith=:::1](@/reference/1.20.4/src/main/java/com/example/docs/block/custom/PrismarineLampBlock.java) + +Next, we have to append the property to the blockstate manager in the `appendProperties` method. You'll need to override the method to access the builder: + +@[code transcludeWith=:::2](@/reference/1.20.4/src/main/java/com/example/docs/block/custom/PrismarineLampBlock.java) + +You'll also have to set a default state for the `activated` property in the constructor of your custom block. + +@[code transcludeWith=:::3](@/reference/1.20.4/src/main/java/com/example/docs/block/custom/PrismarineLampBlock.java) + +::: warning +Don't forget to register your block using the custom class instead of `Block`! +::: + +### Using The Property {#using-the-property} + +This example flips the boolean `activated` property when the player interacts with the block. We can override the `onUse` method for this: + +@[code transcludeWith=:::4](@/reference/1.20.4/src/main/java/com/example/docs/block/custom/PrismarineLampBlock.java) + +### Visualizing The Property {#visualizing-the-property} + +Before creating the blockstate file, you will need to provide textures for both the activated and deactivated states of the block, as well as the block model. + + + +Use your knowledge of block models to create two models for the block: one for the activated state and one for the deactivated state. Once you've done that, you can begin creating the blockstate file. + +Since you created a new property, you will need to update the blockstate file for the block to account for that property. + +If you have multiple properties on a block, you'll need to account for all possible combinations. For example, `activated` and `axis` would lead to 6 combinations (two possible values for `activated` and three possible values for `axis`). + +Since this block only has two possible variants, as it only has one property (`activated`), the blockstate JSON will look something like this: + +@[code](@/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/blockstates/prismarine_lamp.json) + +--- + +Since the example block is a lamp, we also need to make it emit light when the `activated` property is true. This can be done through the block settings passed to the constructor when registering the block. + +You can use the `luminance` method to set the light level emitted by the block, we can create a static method in the `PrismarineLampBlock` class to return the light level based on the `activated` property, and pass it as a method reference to the `luminance` method: + +@[code transcludeWith=:::5](@/reference/1.20.4/src/main/java/com/example/docs/block/custom/PrismarineLampBlock.java) + +@[code transcludeWith=:::4](@/reference/1.20.4/src/main/java/com/example/docs/block/ModBlocks.java) + +--- + + + +Once you've completed everything, the final result should look something like the following: + + diff --git a/versions/1.20.4/develop/blocks/first-block.md b/versions/1.20.4/develop/blocks/first-block.md new file mode 100644 index 000000000..0060b9089 --- /dev/null +++ b/versions/1.20.4/develop/blocks/first-block.md @@ -0,0 +1,166 @@ +--- +title: Creating Your First Block +description: Learn how to create your first custom block in Minecraft. +authors: + - IMB11 +--- + +# Creating Your First Block {#creating-your-first-block} + +Blocks are the building blocks of Minecraft (no pun intended) - just like everything else in Minecraft, they're stored in registries. + +## Preparing Your Blocks Class {#preparing-your-blocks-class} + +If you've completed the [Creating Your First Item](../items/first-item) page, this process will feel extremely familiar - you will need to create a method that registers your block, and it's block item. + +You should put this method in a class called `ModBlocks` (or whatever you want to name it). + +Mojang does something extremely similar like this with vanilla blocks; you can refer to the `Blocks` class to see how they do it. + +@[code transcludeWith=:::1](@/reference/1.20.4/src/main/java/com/example/docs/block/ModBlocks.java) + +--- + +Just like with items, you need to ensure that the class is loaded so that all static fields containing your block instances are initialized. + +You can do this by creating a dummy `initialize` method, which can be called in your mod initializer to trigger the static initialization. + +::: info +If you are unaware of what static initialization is, it is the process of initializing static fields in a class. This is done when the class is loaded by the JVM, and is done before any instances of the class are created. +::: + +```java +public class ModBlocks { + // ... + + public static void initialize() {} +} +``` + +@[code transcludeWith=:::1](@/reference/1.20.4/src/main/java/com/example/docs/block/FabricDocsReferenceBlocks.java) + +## Creating And Registering Your Block {#creating-and-registering-your-block} + +Similarly to items, blocks take a `Blocks.Settings` class in their constructor, which specifies properties about the block, such as its sound effects and mining level. + +We will not cover all the options here—you can view the class yourself to see the various options, which should be self-explanatory. + +For example purposes, we will be creating a simple block that has the properties of dirt, but is a different material. + +::: tip +You can also use `AbstractBlock.Settings.copy(AbstractBlock block)` to copy the settings of an existing block, in this case, we could have used `Blocks.DIRT` to copy the settings of dirt, but for example purposes we'll use the builder. +::: + +@[code transcludeWith=:::2](@/reference/1.20.4/src/main/java/com/example/docs/block/ModBlocks.java) + +To automatically create the block item, we can pass `true` to the `shouldRegisterItem` parameter of the `register` method we created in the previous step. + +### Adding Your Block to an Item Group {#adding-your-block-to-an-item-group} + +Since the `BlockItem` is automatically created and registered, to add it to an item group, you must use the `Block.asItem()` method to get the `BlockItem` instance. + +For this example, we'll use a custom item group created in the [Custom Item Groups](../items/custom-item-groups) page. + +@[code transcludeWith=:::3](@/reference/1.20.4/src/main/java/com/example/docs/block/ModBlocks.java) + +--- + +You should now notice that your block is in the creative inventory, and can be placed in the world! + +![Block in world without suitable model or texture](/assets/develop/blocks/first_block_0.png). + +There are a few issues though - the block item is not named, and the block has no texture, block model or item model. + +## Adding Block Translations {#adding-block-translations} + +To add a translation, you must create a translation key in your translation file - `assets//lang/en_us.json`. + +Minecraft will use this translation in the creative inventory and other places where the block name is displayed, such as command feedback. + +```json +{ + "block.mod_id.condensed_dirt": "Condensed Dirt" +} +``` + +You can either restart the game or build your mod and press F3 + T to apply changes - and you should see that the block has a name in the creative inventory and other places such as the statistics screen. + +## Models and Textures {#models-and-textures} + +All block textures can be found in the `assets//textures/block` folder - an example texture for the "Condensed Dirt" block is free to use. + + + +To make the texture show up in-game, you must create a block and item model which can be found in the respective locations for the "Condensed Dirt" block: + +- `assets//models/block/condensed_dirt.json` +- `assets//models/item/condensed_dirt.json` + +The item model is pretty simple, it can just use the block model as a parent - since most block models have support for being rendered in a GUI: + +@[code](@/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/item/condensed_dirt.json) + +The block model however, in our case, must parent the `block/cube_all` model: + +@[code](@/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/block/condensed_dirt.json) + +When you load into the game, you may notice that the texture is still missing. This is because you need to add a blockstate definition. + +## Creating the Block State Definition {#creating-the-block-state-definition} + +The blockstate definition is used to instruct the game on which model to render based on the current state of the block. + +For the example block, which doesn't have a complex blockstate, only one entry is needed in the definition. + +This file should be located in the `assets/mod_id/blockstates` folder, and its name should match the block ID used when registering your block in the `ModBlocks` class. For instance, if the block ID is `condensed_dirt`, the file should be named `condensed_dirt.json`. + +@[code](@/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/blockstates/condensed_dirt.json) + +Blockstates are really complex, which is why they are addressed in an upcoming page: [Block States](./blockstates) + +Restarting the game, or reloading via F3 + T to apply changes - you should be able to see the block texture in the inventory and physically in the world: + +![Block in world with suitable texture and model](/assets/develop/blocks/first_block_4.png) + +## Adding Block Drops {#adding-block-drops} + +When breaking the block in survival, you may see that the block does not drop - you might want this functionality, however to make your block drop as an item on break you must implement its loot table - the loot table file should be placed in the `data//loot_tables/blocks/` folder. + +::: info +For a greater understanding of loot tables, you can refer to the [Minecraft Wiki - Loot Tables](https://minecraft.wiki/w/Loot_table) page. +::: + +@[code](@/reference/1.20.4/src/main/resources/data/fabric-docs-reference/loot_tables/blocks/condensed_dirt.json) + +This loot table provides a single item drop of the block item when the block is broken, and when it is blown up by an explosion. + +## Recommending a Harvesting Tool {#recommending-a-harvesting-tool} + +You may also want your block to be harvestable only by a specific tool - for example, you may want to make your block faster to harvest with a shovel. + +All the tool tags should be placed in the `data/minecraft/tags/mineable/` folder - where the name of the file depends on the type of tool used, one of the following: + +- `hoe.json` +- `axe.json` +- `pickaxe.json` +- `shovel.json` + +The contents of the file are quite simple - it is a list of items that should be added to the tag. + +This example adds the "Condensed Dirt" block to the `shovel` tag. + +@[code](@/reference/1.20.4/src/main/resources/data/minecraft/tags/mineable/shovel.json) + +## Mining Levels {#mining-levels} + +Similarly, the mining level tag can be found in the same folder, and respects the following format: + +- `needs_stone_tool.json` - A minimum level of stone tools +- `needs_iron_tool.json` - A minimum level of iron tools +- `needs_diamond_tool.json` - A minimum level of diamond tools. + +The file has the same format as the harvesting tool file - a list of items to be added to the tag. + +## Extra Notes {#extra-notes} + +If you're adding multiple blocks to your mod, you may want to consider using [Data Generation](https://fabricmc.net/wiki/tutorial:datagen_setup) to automate the process of creating block and item models, blockstate definitions, and loot tables. diff --git a/versions/1.20.4/develop/codecs.md b/versions/1.20.4/develop/codecs.md new file mode 100644 index 000000000..2fd0632d5 --- /dev/null +++ b/versions/1.20.4/develop/codecs.md @@ -0,0 +1,462 @@ +--- +title: Codecs +description: A comprehensive guide for understanding and using Mojang's codec system for serializing and deserializing objects. +authors: + - enjarai + - Syst3ms +--- + +# Codecs {#codecs} + +Codec is a system for easily serializing Java objects, and is included in Mojang's DataFixerUpper (DFU) +library, which is included with Minecraft. In a modding context they can be used as an alternative +to GSON and Jankson when reading and writing custom json files, though they're starting to become +more and more relevant, as Mojang is rewriting a lot of old code to use Codecs. + +Codecs are used in conjunction with another API from DFU, `DynamicOps`. A codec defines the structure of an object, while +dynamic ops are used to define a format to be serialized to and from, such as json or NBT. This means any codec can be +used with any dynamic ops, and vice versa, allowing for great flexibility. + +## Using Codecs {#using-codecs} + +### Serializing and Deserializing {#serializing-and-deserializing} + +The basic usage of a codec is to serialize and deserialize objects to and from a specific format. + +Since a few vanilla classes already have codecs defined, we can use those as an example. Mojang has also provided us +with two dynamic ops classes by default, `JsonOps` and `NbtOps`, which tend to cover most use cases. + +Now, let's say we want to serialize a `BlockPos` to json and back. We can do this using the codec statically stored +at `BlockPos.CODEC` with the `Codec#encodeStart` and `Codec#parse` methods, respectively. + +```java +BlockPos pos = new BlockPos(1, 2, 3); + +// Serialize the BlockPos to a JsonElement +DataResult result = BlockPos.CODEC.encodeStart(JsonOps.INSTANCE, pos); +``` + +When using a codec, values are returned in the form of a `DataResult`. This is a wrapper that can represent either a +success or a failure. We can use this in several ways: If we just want our serialized value, `DataResult#result` will +simply return an `Optional` containing our value, while `DataResult#resultOrPartial` also lets us supply a function to +handle any errors that may have occurred. The latter is particularly useful for custom datapack resources, where we'd +want to log errors without causing issues elsewhere. + +So let's grab our serialized value and turn it back into a `BlockPos`: + +```java +// When actually writing a mod, you'll want to properly handle empty Optionals of course +JsonElement json = result.resultOrPartial(LOGGER::error).orElseThrow(); + +// Here we have our json value, which should correspond to `[1, 2, 3]`, +// as that's the format used by the BlockPos codec. +LOGGER.info("Serialized BlockPos: {}", json); + +// Now we'll deserialize the JsonElement back into a BlockPos +DataResult result = BlockPos.CODEC.parse(JsonOps.INSTANCE, json); + +// Again, we'll just grab our value from the result +BlockPos pos = result.resultOrPartial(LOGGER::error).orElseThrow(); + +// And we can see that we've successfully serialized and deserialized our BlockPos! +LOGGER.info("Deserialized BlockPos: {}", pos); +``` + +### Built-in Codecs {#built-in-codecs} + +As mentioned earlier, Mojang has already defined codecs for several vanilla and standard Java classes, including but not +limited to `BlockPos`, `BlockState`, `ItemStack`, `Identifier`, `Text`, and regex `Pattern`s. Codecs for Mojang's own +classes are usually found as static fields named `CODEC` on the class itself, while most others are kept in the `Codecs` +class. It should also be noted that all vanilla registries contain a `getCodec()` method, for example, you +can use `Registries.BLOCK.getCodec()` to get a `Codec` which serializes to the block id and back. + +The Codec API itself also contains some codecs for primitive types, such as `Codec.INT` and `Codec.STRING`. These are +available as statics on the `Codec` class, and are usually used as the base for more complex codecs, as explained below. + +## Building Codecs {#building-codecs} + +Now that we've seen how to use codecs, let's take a look at how we can build our own. Suppose we have the following +class, and we want to deserialize instances of it from json files: + +```java +public class CoolBeansClass { + + private final int beansAmount; + private final Item beanType; + private final List beanPositions; + + public CoolBeansClass(int beansAmount, Item beanType, List beanPositions) {...} + + public int getBeansAmount() { return this.beansAmount; } + public Item getBeanType() { return this.beanType; } + public List getBeanPositions() { return this.beanPositions; } +} +``` + +The corresponding json file might look something like this: + +```json +{ + "beans_amount": 5, + "bean_type": "beanmod:mythical_beans", + "bean_positions": [ + [1, 2, 3], + [4, 5, 6] + ] +} +``` + +We can make a codec for this class by putting together multiple smaller codecs into a larger one. In this case, we'll +need one for each field: + +- a `Codec` +- a `Codec` +- a `Codec>` + +We can get the first one from the aforementioned primitive codecs in the `Codec` class, specifically `Codec.INT`. While +the second one can be obtained from the `Registries.ITEM` registry, which has a `getCodec()` method that returns a +`Codec`. We don't have a default codec for `List`, but we can make one from `BlockPos.CODEC`. + +### Lists {#lists} + +`Codec#listOf` can be used to create a list version of any codec: + +```java +Codec> listCodec = BlockPos.CODEC.listOf(); +``` + +It should be noted that codecs created in this way will always deserialize to an `ImmutableList`. If you need a mutable +list instead, you can make use of [xmap](#mutually-convertible-types) to convert to one during +deserialization. + +### Merging Codecs for Record-Like Classes {#merging-codecs-for-record-like-classes} + +Now that we have separate codecs for each field, we can combine them into one codec for our class using +a `RecordCodecBuilder`. This assumes that our class has a constructor containing every field we want to serialize, and +that every field has a corresponding getter method. This makes it perfect to use in conjunction with records, but it can +also be used with regular classes. + +Let's take a look at how to create a codec for our `CoolBeansClass`: + +```java +public static final Codec CODEC = RecordCodecBuilder.create(instance -> instance.group( + Codec.INT.fieldOf("beans_amount").forGetter(CoolBeansClass::getBeansAmount), + Registries.ITEM.getCodec().fieldOf("bean_type").forGetter(CoolBeansClass::getBeanType), + BlockPos.CODEC.listOf().fieldOf("bean_positions").forGetter(CoolBeansClass::getBeanPositions) + // Up to 16 fields can be declared here +).apply(instance, CoolBeansClass::new)); +``` + +Each line in the group specifies a codec, a field name, and a getter method. The `Codec#fieldOf` call is used to convert +the codec into a [map codec](#mapcodec), and the `forGetter` call specifies the getter method used to retrieve the value +of the field from an instance of the class. Meanwhile, the `apply` call specifies the constructor used to create new +instances. Note that the order of the fields in the group should be the same as the order of the arguments in the +constructor. + +You can also use `Codec#optionalFieldOf` in this context to make a field optional, as explained in +the [Optional Fields](#optional-fields) section. + +### MapCodec, Not to Be Confused With Codec<Map> {#mapcodec} + +Calling `Codec#fieldOf` will convert a `Codec` into a `MapCodec`, which is a variant, but not direct +implementation of `Codec`. `MapCodec`s, as their name suggests are guaranteed to serialize into a +key to value map, or its equivalent in the `DynamicOps` used. Some functions may require one over a regular codec. + +This particular way of creating a `MapCodec` essentially boxes the value of the source codec +inside a map, with the given field name as the key. For example, a `Codec` +when serialized into json would look like this: + +```json +[1, 2, 3] +``` + +But when converted into a `MapCodec` using `BlockPos.CODEC.fieldOf("pos")`, it would look like this: + +```json +{ + "pos": [1, 2, 3] +} +``` + +While the most common use for map codecs is to be merged with other map codecs to construct a codec for a full class worth of +fields, as explained in the [Merging Codecs for Record-like Classes](#merging-codecs-for-record-like-classes) section +above, they can also be turned back into regular codecs using `MapCodec#codec`, which will retain the same behavior of +boxing their input value. + +#### Optional Fields {#optional-fields} + +`Codec#optionalFieldOf` can be used to create an optional map codec. This will, when the specified field is not present +in the container during deserialization, either be deserialized as an empty `Optional` or a specified default value. + +```java +// Without a default value +MapCodec> optionalCodec = BlockPos.CODEC.optionalFieldOf("pos"); + +// With a default value +MapCodec optionalCodec = BlockPos.CODEC.optionalFieldOf("pos", BlockPos.ORIGIN); +``` + +Do note that optional fields will silently ignore any errors that may occur during deserialization. This means that if +the field is present, but the value is invalid, the field will always be deserialized as the default value. + +**Since 1.20.2**, Minecraft itself (not DFU!) does however provide `Codecs#createStrictOptionalFieldCodec`, +which fails to deserialize at all if the field value is invalid. + +### Constants, Constraints, and Composition {#constants-constraints-composition} + +#### Unit {#unit} + +`Codec.unit` can be used to create a codec that always deserializes to a constant value, regardless of the input. When +serializing, it will do nothing. + +```java +Codec theMeaningOfCodec = Codec.unit(42); +``` + +#### Numeric Ranges {#numeric-ranges} + +`Codec.intRange` and its pals, `Codec.floatRange` and `Codec.doubleRange` can be used to create a codec that only +accepts number values within a specified **inclusive** range. This applies to both serialization and deserialization. + +```java +// Can't be more than 2 +Codec amountOfFriendsYouHave = Codec.intRange(0, 2); +``` + +#### Pair {#pair} + +`Codec.pair` merges two codecs, `Codec` and `Codec`, into a `Codec>`. Keep in mind it only works +properly with codecs that serialize to a specific field, such as [converted `MapCodec`s](#mapcodec) or +[record codecs](#merging-codecs-for-record-like-classes). +The resulting codec will serialize to a map combining the fields of both codecs used. + +For example, running this code: + +```java +// Create two separate boxed codecs +Codec firstCodec = Codec.INT.fieldOf("i_am_number").codec(); +Codec secondCodec = Codec.BOOL.fieldOf("this_statement_is_false").codec(); + +// Merge them into a pair codec +Codec> pairCodec = Codec.pair(firstCodec, secondCodec); + +// Use it to serialize data +DataResult result = pairCodec.encodeStart(JsonOps.INSTANCE, Pair.of(23, true)); +``` + +Will output this json: + +```json +{ + "i_am_number": 23, + "this_statement_is_false": true +} +``` + +#### Either {#either} + +`Codec.either` combines two codecs, `Codec` and `Codec`, into a `Codec>`. The resulting codec will, +during deserialization, attempt to use the first codec, and _only if that fails_, attempt to use the second one. +If the second one also fails, the error of the _second_ codec will be returned. + +#### Maps {#maps} + +For processing maps with arbitrary keys, such as `HashMap`s, `Codec.unboundedMap` can be used. This returns a +`Codec>` for a given `Codec` and `Codec`. The resulting codec will serialize to a json object or +whatever equivalent is available for the current dynamic ops. + +Due to limitations of json and nbt, the key codec used _must_ serialize to a string. This includes codecs for types that +aren't strings themselves, but do serialize to them, such as `Identifier.CODEC`. See the example below: + +```java +// Create a codec for a map of identifiers to integers +Codec> mapCodec = Codec.unboundedMap(Identifier.CODEC, Codec.INT); + +// Use it to serialize data +DataResult result = mapCodec.encodeStart(JsonOps.INSTANCE, Map.of( + new Identifier("example", "number"), 23, + new Identifier("example", "the_cooler_number"), 42 +)); +``` + +This will output this json: + +```json +{ + "example:number": 23, + "example:the_cooler_number": 42 +} +``` + +As you can see, this works because `Identifier.CODEC` serializes directly to a string value. A similar effect can be +achieved for simple objects that don't serialize to strings by using [xmap & friends](#mutually-convertible-types) to +convert them. + +### Mutually Convertible Types {#mutually-convertible-types} + +#### `xmap` {#xmap} + +Say we have two classes that can be converted to each other, but don't have a parent-child relationship. For example, +a vanilla `BlockPos` and `Vec3d`. If we have a codec for one, we can use `Codec#xmap` to create a codec for the other by +specifying a conversion function for each direction. + +`BlockPos` already has a codec, but let's pretend it doesn't. We can create one for it by basing it on the +codec for `Vec3d` like this: + +```java +Codec blockPosCodec = Vec3d.CODEC.xmap( + // Convert Vec3d to BlockPos + vec -> new BlockPos(vec.x, vec.y, vec.z), + // Convert BlockPos to Vec3d + pos -> new Vec3d(pos.getX(), pos.getY(), pos.getZ()) +); + +// When converting an existing class (`X` for example) +// to your own class (`Y`) this way, it may be nice to +// add `toX` and static `fromX` methods to `Y` and use +// method references in your `xmap` call. +``` + +#### flatComapMap, comapFlatMap, and flatXMap {#flatcomapmap-comapflatmap-flatxmap} + +`Codec#flatComapMap`, `Codec#comapFlatMap` and `flatXMap` are similar to xmap, but they allow one or both of the +conversion functions to return a DataResult. This is useful in practice because a specific object instance may not +always be valid for conversion. + +Take for example vanilla `Identifier`s. While all identifiers can be turned into strings, not all strings are valid identifiers, +so using xmap would mean throwing ugly exceptions when the conversion fails. +Because of this, its built-in codec is actually a `comapFlatMap` on `Codec.STRING`, nicely +illustrating how to use it: + +```java +public class Identifier { + public static final Codec CODEC = Codec.STRING.comapFlatMap( + Identifier::validate, Identifier::toString + ); + + // ... + + public static DataResult validate(String id) { + try { + return DataResult.success(new Identifier(id)); + } catch (InvalidIdentifierException e) { + return DataResult.error("Not a valid resource location: " + id + " " + e.getMessage()); + } + } + + // ... +} +``` + +While these methods are really helpful, their names are a bit confusing, so here's a table to help you remember which +one to use: + +| Method | A -> B always valid? | B -> A always valid? | +| ----------------------- | -------------------- | -------------------- | +| `Codec#xmap` | Yes | Yes | +| `Codec#comapFlatMap` | No | Yes | +| `Codec#flatComapMap` | Yes | No | +| `Codec#flatXMap` | No | No | + +### Registry Dispatch {#registry-dispatch} + +`Codec#dispatch` let us define a registry of codecs and dispatch to a specific one based on the value of a +field in the serialized data. This is very useful when deserializing objects that have different fields depending on +their type, but still represent the same thing. + +For example, say we have an abstract `Bean` interface with two implementing classes: `StringyBean` and `CountingBean`. To serialize +these with a registry dispatch, we'll need a few things: + +- Separate codecs for every type of bean. +- A `BeanType` class or record that represents the type of bean, and can return the codec for it. +- A function on `Bean` to retrieve its `BeanType`. +- A map or registry to map `Identifier`s to `BeanType`s. +- A `Codec>` based on this registry. If you use a `net.minecraft.registry.Registry`, one can be easily made + using `Registry#getCodec`. + +With all of this, we can create a registry dispatch codec for beans: + +@[code transcludeWith=:::](@/reference/1.20.4/src/main/java/com/example/docs/codec/Bean.java) +@[code transcludeWith=:::](@/reference/1.20.4/src/main/java/com/example/docs/codec/BeanType.java) +@[code transcludeWith=:::](@/reference/1.20.4/src/main/java/com/example/docs/codec/StringyBean.java) +@[code transcludeWith=:::](@/reference/1.20.4/src/main/java/com/example/docs/codec/CountingBean.java) +@[code transcludeWith=:::](@/reference/1.20.4/src/main/java/com/example/docs/codec/BeanTypes.java) + +```java +// Now we can create a codec for bean types +// based on the previously created registry +Codec> beanTypeCodec = BeanType.REGISTRY.getCodec(); + +// And based on that, here's our registry dispatch codec for beans! +// The first argument is the field name for the bean type. +// When left out, it will default to "type". +Codec beanCodec = beanTypeCodec.dispatch("type", Bean::getType, BeanType::getCodec); +``` + +Our new codec will serialize beans to json like this, grabbing only fields that are relevant to their specific type: + +```json +{ + "type": "example:stringy_bean", + "stringy_string": "This bean is stringy!" +} +``` + +```json +{ + "type": "example:counting_bean", + "counting_number": 42 +} +``` + +### Recursive Codecs {#recursive-codecs} + +Sometimes it is useful to have a codec that uses _itself_ to decode specific fields, for example when dealing with certain recursive data structures. In vanilla code, this is used for `Text` objects, which may store other `Text`s as children. Such a codec can be constructed using `Codecs#createRecursive`. + +For example, let's try to serialize a singly-linked list. This way of representing lists consists of a bunch of nodes that hold both a value and a reference to the next node in the list. The list is then represented by its first node, and traversing the list is done by following the next node until none remain. Here is a simple implementation of nodes that store integers. + +```java +public record ListNode(int value, ListNode next) {} +``` + +We can't construct a codec for this by ordinary means, because what codec would we use for the `next` field? We would need a `Codec`, which is what we are in the middle of constructing! `Codecs#createRecursive` lets us achieve that using a magic-looking lambda: + +```java +Codec codec = Codecs.createRecursive( + "ListNode", // a name for the codec + selfCodec -> { + // Here, `selfCodec` represents the `Codec`, as if it was already constructed + // This lambda should return the codec we wanted to use from the start, + // that refers to itself through `selfCodec` + return RecordCodecBuilder.create(instance -> + instance.group( + Codec.INT.fieldOf("value").forGetter(ListNode::value), + // the `next` field will be handled recursively with the self-codec + Codecs.createStrictOptionalFieldCodec(selfCodec, "next", null).forGetter(ListNode::next) + ).apply(instance, ListNode::new) + ); + } +); +``` + +A serialized `ListNode` may then look like this: + +```json +{ + "value": 2, + "next": { + "value": 3, + "next" : { + "value": 5 + } + } +} +``` + +## References {#references} + +- A much more comprehensive documentation of Codecs and related APIs can be found at the + [Unofficial DFU JavaDoc](https://kvverti.github.io/Documented-DataFixerUpper/snapshot/com/mojang/serialization/Codec). +- The general structure of this guide was heavily inspired by the + [Forge Community Wiki's page on Codecs](https://forge.gemwire.uk/wiki/Codecs), a more Forge-specific take on the same + topic. diff --git a/versions/1.20.4/develop/commands/arguments.md b/versions/1.20.4/develop/commands/arguments.md new file mode 100644 index 000000000..db7c1ea75 --- /dev/null +++ b/versions/1.20.4/develop/commands/arguments.md @@ -0,0 +1,63 @@ +--- +title: Command Arguments +description: Learn how to create commands with complex arguments. +--- + +# Command Arguments {#command-arguments} + +Arguments are used in most of the commands. Sometimes they can be optional, which means if you do not provide that +argument, +the command will also run. One node may have multiple argument types, but be aware that there is a possibility of +ambiguity, which should be avoided. + +@[code lang=java highlight={3} transcludeWith=:::4](@/reference/1.20.4/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +In this case, after the command text `/argtater`, you should type an integer. For example, if you +run `/argtater 3`, you will get the feedback message `Called /argtater with value = 3`. If you +type `/argtater` without arguments, the command cannot be correctly parsed. + +Then we add an optional second argument: + +@[code lang=java highlight={3,13} transcludeWith=:::5](@/reference/1.20.4/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +Now you can type one or two integers. If you give one integer, a feedback text with a single value is printed. If you +provide two integers, a feedback text with two values will be printed. + +You may find it unnecessary to specify similar executions twice. Therefore, we can create a method that will be used in +both executions. + +@[code lang=java highlight={3,5,6,7} transcludeWith=:::6](@/reference/1.20.4/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +## Custom Argument Types {#custom-argument-types} + +If vanilla does not have the argument type you need, you can create your own. To do this, you need to create a class that inherits the `ArgumentType` interface where `T` is the type of the argument. + +You will need to implement the `parse` method, which will parse the input string into the desired type. + +For example, you can create an argument type that parses a `BlockPos` from a string with the following format: `{x, y, z}` + +@[code lang=java transcludeWith=:::1](@/reference/1.20.4/src/main/java/com/example/docs/command/BlockPosArgumentType.java) + +### Registering Custom Argument Types {#registering-custom-argument-types} + +::: warning +You need to register the custom argument type on both the server and the client or else the command will not work! +::: + +You can register your custom argument type in the `onInitialize` method of your mod initializer using the `ArgumentTypeRegistry` class: + +@[code lang=java transcludeWith=:::11](@/reference/1.20.4/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +### Using Custom Argument Types {#using-custom-argument-types} + +We can use our custom argument type in a command - by passing an instance of it into the `.argument` method on the command builder. + +@[code lang=java transcludeWith=:::10 highlight={3}](@/reference/1.20.4/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +Running the command, we can test whether or not the argument type works: + +![Invalid argument](/assets/develop/commands/custom-arguments_fail.png) + +![Valid argument](/assets/develop/commands/custom-arguments_valid.png) + +![Command result](/assets/develop/commands/custom-arguments_result.png) diff --git a/versions/1.20.4/develop/commands/basics.md b/versions/1.20.4/develop/commands/basics.md new file mode 100644 index 000000000..76af2f066 --- /dev/null +++ b/versions/1.20.4/develop/commands/basics.md @@ -0,0 +1,197 @@ +--- +title: Creating Commands +description: Create commands with complex arguments and actions. +authors: + - dicedpixels + - i509VCB + - pyrofab + - natanfudge + - Juuxel + - solidblock + - modmuss50 + - technici4n + - atakku + - haykam + - mschae23 + - treeways + - xpple +--- + +# Creating Commands {#creating-commands} + +Creating commands can allow a mod developer to add functionality that can be used through a command. This tutorial will +teach you how to register commands and the general command structure of Brigadier. + +::: info +Brigadier is a command parser and dispatcher written by Mojang for Minecraft. It is a tree-based command library where +you build a tree of commands and arguments. + +Brigadier is open-source: +::: + +## The `Command` Interface {#the-command-interface} + +`com.mojang.brigadier.Command` is a functional interface, which runs some specific code, and throws a +`CommandSyntaxException` in certain cases. It has a generic type `S`, which defines the type of the _command source_. +The command +source provides some context in which a command was run. In Minecraft, the command source is typically a +`ServerCommandSource` which can represent a server, a command block, a remote connection (RCON), a player or an entity. + +The single method in `Command`, `run(CommandContext)` takes a `CommandContext` as the sole parameter and returns +an integer. The command context holds your command source of `S` and allows you to obtain arguments, look at the parsed +command nodes and see the input used in this command. + +Like other functional interfaces, it is usually used as a lambda or a method reference: + +```java +Command command = context -> { + return 0; +}; +``` + +The integer can be considered the result of the command. Typically values less than or equal to zero mean a command has failed and will +do nothing. Positive values mean the command was successful and did something. Brigadier provides a constant to indicate +success; `Command#SINGLE_SUCCESS`. + +### What Can the `ServerCommandSource` Do? {#what-can-the-servercommandsource-do} + +A `ServerCommandSource` provides some additional implementation-specific context when a command is run. This includes +the +ability to get the entity that executed the command, the world the command was run in or the server the command was run +on. + +You can access the command source from a command context by calling `getSource()` on the `CommandContext` instance. + +```java +Command command = context -> { + ServerCommandSource source = context.getSource(); + return 0; +}; +``` + +## Registering a Basic Command {#registering-a-basic-command} + +Commands are registered within the `CommandRegistrationCallback` provided by the Fabric API. + +::: info +For information on registering callbacks, please see the [Events](../events) guide. +::: + +The event should be registered in your mod's initializer. + +The callback has three parameters: + +- `CommandDispatcher dispatcher` - Used to register, parse and execute commands. `S` is the type + of command source the command dispatcher supports. +- `CommandRegistryAccess registryAccess` - Provides an abstraction to registries that may be passed to certain command + argument methods +- `CommandManager.RegistrationEnvironment environment` - Identifies the type of server the commands are being registered + on. + +In the mod initializer, we just register a simple command: + +@[code lang=java transcludeWith=:::_1](@/reference/1.20.4/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +In the `sendFeedback()` method, the first parameter is the text to be sent, which is a `Supplier` to avoid +instantiating Text objects when not needed. + +The second parameter determines whether to broadcast the feedback to other +operators. Generally, if the command is to query something without actually affecting the world, such as query the +current time or some player's score, it should be `false`. If the command does something, such as changing the +time or modifying someone's score, it should be `true`. + +If the command fails, instead of calling `sendFeedback()`, you may directly throw any exception and the server or client +will handle it appropriately. + +`CommandSyntaxException` is generally thrown to indicate syntax errors in commands or arguments. You can also implement +your own exception. + +To execute this command, you must type `/foo`, which is case-sensitive. + +### Registration Environment {#registration-environment} + +If desired, you can also make sure a command is only registered under some specific circumstances, for example, only in +the dedicated environment: + +@[code lang=java highlight={2} transcludeWith=:::2](@/reference/1.20.4/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +### Command Requirements {#command-requirements} + +Let's say you have a command that you only want operators to be able to execute. This is where the `requires()` method +comes into play. The `requires()` method has one argument of a `Predicate` which will supply a `ServerCommandSource` +to test with and determine if the `CommandSource` can execute the command. + +@[code lang=java highlight={3} transcludeWith=:::3](@/reference/1.20.4/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +This command will only execute if the source of the command is a level 2 operator at a minimum, including command +blocks. Otherwise, the command is not registered. + +This has the side effect of not showing this command in tab completion to anyone who is not a level 2 operator. This is +also why you cannot tab-complete most commands when you do not enable cheats. + +### Sub Commands {#sub-commands} + +To add a sub command, you register the first literal node of the command normally. To have a sub command, you have to append the next literal node to the existing node. + +@[code lang=java highlight={3} transcludeWith=:::7](@/reference/1.20.4/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +Similar to arguments, sub command nodes can also be set optional. In the following case, both `/subtater` +and `/subtater subcommand` will be valid. + +@[code lang=java highlight={2,8} transcludeWith=:::8](@/reference/1.20.4/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +## Client Commands {#client-commands} + +Fabric API has a `ClientCommandManager` in `net.fabricmc.fabric.api.client.command.v2` package that can be used to register client-side commands. The code should exist only in client-side code. + +@[code lang=java transcludeWith=:::1](@/reference/1.20.4/src/client/java/com/example/docs/client/command/FabricDocsReferenceClientCommands.java) + +## Command Redirects {#command-redirects} + +Command redirects - also known as aliases - are a way to redirect the functionality of one command to another. This is useful for when you want to change the name of a command, but still want to support the old name. + +@[code lang=java transcludeWith=:::12](@/reference/1.20.4/src/client/java/com/example/docs/client/command/FabricDocsReferenceClientCommands.java) + +## FAQ {#faq} + +### Why Does My Code Not Compile? {#why-does-my-code-not-compile} + +- Catch or throw a `CommandSyntaxException` - `CommandSyntaxException` is not a `RuntimeException`. If you throw it, + that should be in methods that throw `CommandSyntaxException` in method signatures, or it should be caught. + Brigadier will handle the checked exceptions and forward the proper error message in the game for you. + +- Issues with generics - You may have an issue with generics once in a while. If you are registering server + commands (which are most of the case), make sure you are using `CommandManager.literal` + or `CommandManager.argument` instead of `LiteralArgumentBuilder.literal` or `RequiredArgumentBuilder.argument`. + +- Check `sendFeedback()` method - You may have forgotten to provide a boolean as the second argument. Also remember + that, since Minecraft 1.20, the first parameter is `Supplier` instead of `Text`. + +- A Command should return an integer - When registering commands, the `executes()` method accepts a `Command` object, + which is usually a lambda. The lambda should return an integer, instead of other types. + +### Can I Register Commands at Runtime? {#can-i-register-commands-at-runtime} + +::: warning +You can do this, but it is not recommended. You would get the `CommandManager` from the server and add anything commands +you wish to its `CommandDispatcher`. + +After that, you need to send the command tree to every player again +using `CommandManager.sendCommandTree(ServerPlayerEntity)`. + +This is required because the client locally caches the command tree it receives during login (or when operator packets +are sent) for local completions-rich error messages. +::: + +### Can I Unregister Commands at Runtime? {#can-i-unregister-commands-at-runtime} + +::: warning +You can also do this, however, it is much less stable than registering commands at runtime and could cause unwanted side +effects. + +To keep things simple, you need to use reflection on Brigadier and remove nodes. After this, you need to send the +command tree to every player again using `sendCommandTree(ServerPlayerEntity)`. + +If you don't send the updated command tree, the client may think a command still exists, even though the server will +fail execution. +::: diff --git a/versions/1.20.4/develop/commands/suggestions.md b/versions/1.20.4/develop/commands/suggestions.md new file mode 100644 index 000000000..3872ead4a --- /dev/null +++ b/versions/1.20.4/develop/commands/suggestions.md @@ -0,0 +1,45 @@ +--- +title: Command Suggestions +description: Learn how to suggest command argument values to users. +authors: + - IMB11 +--- + +# Command Suggestions {#command-suggestions} + +Minecraft has a powerful command suggestion system that's used in many places, such as the `/give` command. This system allows you to suggest values for command arguments to the user, which they can then select from - it's a great way to make your commands more user-friendly and ergonomic. + +## Suggestion Providers {#suggestion-providers} + +A `SuggestionProvider` is used to make a list of suggestions that will be sent to the client. A suggestion provider is a functional interface that takes a `CommandContext` and a `SuggestionBuilder` and returns some `Suggestions`. The `SuggestionProvider` returns a `CompletableFuture` as the suggestions may not be available immediately. + +## Using Suggestion Providers {#using-suggestion-providers} + +To use a suggestion provider, you need to call the `suggests` method on the argument builder. This method takes a `SuggestionProvider` and returns the modified argument builder with the suggestion provider attached. + +@[code java transcludeWith=:::9 highlight={4}](@/reference/1.20.4/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +## Built-in Suggestion Providers {#built-in-suggestion-providers} + +There are a few built-in suggestion providers that you can use: + +| Suggestion Provider | Description | +| ----------------------------------------- | -------------------------------------------- | +| `SuggestionProviders.SUMMONABLE_ENTITIES` | Suggests all entities that can be summoned. | +| `SuggestionProviders.AVAILABLE_SOUNDS` | Suggests all sounds that can be played. | +| `LootCommand.SUGGESTION_PROVIDER` | Suggests all loot tables that are available. | +| `SuggestionProviders.ALL_BIOMES` | Suggests all biomes that are available. | + +## Creating a Custom Suggestion Provider {#creating-a-custom-suggestion-provider} + +If a built-in provider doesn't satisfy your needs, you can create your own suggestion provider. To do this, you need to create a class that implements the `SuggestionProvider` interface and override the `getSuggestions` method. + +For this example, we'll make a suggestion provider that suggests all the player usernames on the server. + +@[code java transcludeWith=:::1](@/reference/1.20.4/src/main/java/com/example/docs/command/PlayerSuggestionProvider.java) + +To use this suggestion provider, you would simply pass an instance of it into the `.suggests` method on the argument builder. + +Obviously, suggestion providers can be more complex, since they can also read the command context to provide suggestions based on the command's state - such as the arguments that have already been provided. + +This could be in the form of reading the player's inventory and suggesting items, or entities that are nearby the player. diff --git a/versions/1.20.4/develop/entities/damage-types.md b/versions/1.20.4/develop/entities/damage-types.md new file mode 100644 index 000000000..d7831176e --- /dev/null +++ b/versions/1.20.4/develop/entities/damage-types.md @@ -0,0 +1,107 @@ +--- +title: Damage Types +description: Learn how to add custom damage types. +authors: +- dicedpixels +- hiisuuii +- mattidragon +--- + +# Damage Types {#damage-types} + +Damage types define types of damage that entities can take. Since Minecraft 1.19.4, the creation of new damage types has +become data-driven, meaning they are created using JSON files. + +## Creating a Damage Type {#creating-a-damage-type} + +Let's create a custom damage type called _Tater_. We start by creating a JSON file for your custom damage. This file +will +be placed in your mod's `data` directory, in a subdirectory named `damage_type`. + +```:no-line-numbers +resources/data/fabric-docs-reference/damage_type/tater.json +``` + +It has the following structure: + +@[code lang=json](@/reference/1.20.4/src/main/generated/data/fabric-docs-reference/damage_type/tater.json) + +This custom damage type causes 0.1 increase +in [hunger exhaustion](https://minecraft.wiki/w/Hunger#Exhaustion_level_increase) each time a player takes damage, when +the damage is caused by a living, non-player source (e.g., a block). Additionally, the amount of damage dealt will scale +with the world's difficulty + +::: info + +Refer to the [Minecraft Wiki](https://minecraft.wiki/w/Damage_type#JSON_format) for all the possible keys and values. + +::: + +### Accessing Damage Types Through Code {#accessing-damage-types-through-code} + +When we need to access our custom damage type through code, we will use it's `RegistryKey` to build an instance +of `DamageSource`. + +The `RegistryKey` can be obtained as follows: + +@[code lang=java transcludeWith=:::1](@/reference/1.20.4/src/main/java/com/example/docs/damage/FabricDocsReferenceDamageTypes.java) + +### Using Damage Types {#using-damage-types} + +To demonstrate the use of custom damage types, we will use a custom block called _Tater Block_. Let's make is so that +when a living entity steps on a _Tater Block_, it deals _Tater_ damage. + +You can override `onSteppedOn` to inflict this damage. + +We start by creating a `DamageSource` of our custom damage type. + +@[code lang=java transclude={21-24}](@/reference/1.20.4/src/main/java/com/example/docs/damage/TaterBlock.java) + +Then, we call `entity.damage()` with our `DamageSource` and an amount. + +@[code lang=java transclude={25-25}](@/reference/1.20.4/src/main/java/com/example/docs/damage/TaterBlock.java) + +The complete block implementation: + +@[code lang=java transcludeWith=:::1](@/reference/1.20.4/src/main/java/com/example/docs/damage/TaterBlock.java) + +Now whenever a living entity steps on our custom block, it'll take 5 damage (2.5 hearts) using our custom damage type. + +### Custom Death Message {#custom-death-message} + +You can define a death message for the damage type in the format of `death.attack.` in our +mod's `en_us.json` file. + +@[code lang=json transclude={4-4}](@/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/lang/en_us.json) + +Upon death from our damage type, you'll see the following death message: + +![Effect in player inventory](/assets/develop/tater-damage-death.png) + +### Damage Type Tags {#damage-type-tags} + +Some damage types can bypass armor, bypass status effects, and such. Tags are used to control these kinds of properties +of damage types. + +You can find existing damage type tags in `data/minecraft/tags/damage_type`. + +::: info + +Refer to the [Minecraft Wiki](https://minecraft.wiki/w/Tag#Damage_types) for a comprehensive list of damage type +tags. + +::: + +Let's add our Tater damage type to the `bypasses_armor` damage type tag. + +To add our damage type to one of these tags, we create a JSON file under the `minecraft` namespace. + +```:no-line-numbers +data/minecraft/tags/damage_type/bypasses_armor.json +``` + +With the following content: + +@[code lang=json](@/reference/1.20.4/src/main/generated/data/minecraft/tags/damage_type/bypasses_armor.json) + +Ensure your tag does not replace the existing tag by setting the `replace` key to `false`. diff --git a/versions/1.20.4/develop/entities/effects.md b/versions/1.20.4/develop/entities/effects.md new file mode 100644 index 000000000..e948b3ded --- /dev/null +++ b/versions/1.20.4/develop/entities/effects.md @@ -0,0 +1,67 @@ +--- +title: Status Effects +description: Learn how to add custom status effects. +authors: + - dicedpixels + - YanisBft + - FireBlast + - Friendly-Banana + - SattesKrokodil +authors-nogithub: + - siglong + - tao0lu +--- + +# Status Effects {#status-effects} + +Status effects, also known as effects, are a condition that can affect an entity. They can be positive, negative or neutral in nature. The base game +applies these effects in various ways such as food, potions etc. + +The `/effect` command can be used to apply effects on an entity. + +## Custom Status Effects {#custom-status-effects} + +In this tutorial we'll add a new custom effect called _Tater_ which gives you one experience point every game tick. + +### Extend `StatusEffect` {#extend-statuseffect} + +Let's create a custom effect class by extending `StatusEffect`, which is the base class for all effects. + +@[code lang=java transcludeWith=:::1](@/reference/1.20.4/src/main/java/com/example/docs/effect/TaterEffect.java) + +### Registering Your Custom Effect {#registering-your-custom-effect} + +Similar to block and item registration, we use `Registry.register` to register our custom effect into the +`STATUS_EFFECT` registry. This can be done in our initializer. + +@[code lang=java transcludeWith=:::1](@/reference/1.20.4/src/main/java/com/example/docs/effect/FabricDocsReferenceEffects.java) + +### Texture {#texture} + +The status effect icon is a 18x18 PNG which will appear in the player's inventory screen. Place your custom icon in: + +```:no-line-numbers +resources/assets/fabric-docs-reference/textures/mob_effect/tater.png +``` + + + +### Translations {#translations} + +Like any other translation, you can add an entry with ID format `"effect..": "Value"` to the +language file. + +```json +{ + "effect.fabric-docs-reference.tater": "Tater" +} +``` + +### Testing {#testing} + +Use the command `/effect give @p fabric-docs-reference:tater` to give the player our Tater effect. +Use `/effect clear @p fabric-docs-reference:tater` to remove the effect. + +::: info +To create a potion that uses this effect, please see the [Potions](../items/potions) guide. +::: diff --git a/versions/1.20.4/develop/events.md b/versions/1.20.4/develop/events.md new file mode 100644 index 000000000..61525980a --- /dev/null +++ b/versions/1.20.4/develop/events.md @@ -0,0 +1,122 @@ +--- +title: Events +description: A guide for using events provided by the Fabric API. +authors: + - dicedpixels + - mkpoli + - daomephsta + - solidblock + - draylar + - jamieswhiteshirt + - PhoenixVX + - Juuxel + - YanisBft + - liach + - natanfudge +authors-nogithub: + - stormyfabric +--- + +# Events {#events} + +Fabric API provides a system that allows mods to react to actions or occurrences, also defined as _events_ that occur in the game. + +Events are hooks that satisfy common use cases and/or provide enhanced compatibility and performance between mods that hook into the same areas of the code. The use of events often substitutes the use of mixins. + +Fabric API provides events for important areas in the Minecraft codebase that multiple modders may be interested in hooking into. + +Events are represented by instances of `net.fabricmc.fabric.api.event.Event` which stores and calls _callbacks_. Often there is a single event instance for a callback, which is stored in a static field `EVENT` of the callback interface, but there are other patterns as well. For example, `ClientTickEvents` groups several related events together. + +## Callbacks {#callbacks} + +Callbacks are a piece of code that is passed as an argument to an event. When the event is triggered by the game, the passed piece of code will be executed. + +### Callback Interfaces {#callback-interfaces} + +Each event has a corresponding callback interface, conventionally named `Callback`. Callbacks are registered by calling `register()` method on an event instance, with an instance of the callback interface as the argument. + +All event callback interfaces provided by Fabric API can be found in the `net.fabricmc.fabric.api.event` package. + +## Listening to Events {#listening-to-events} + +This example registers an `AttackBlockCallback` to damage the player when they hit blocks that don't drop an item when hand-mined. + +@[code lang=java transcludeWith=:::1](@/reference/1.20.4/src/main/java/com/example/docs/event/FabricDocsReferenceEvents.java) + +### Adding Items to Existing Loot Tables {#adding-items-to-existing-loot-tables} + +Sometimes you may want to add items to loot tables. For example, adding your drops to a vanilla block or entity. + +The simplest solution, replacing the loot table file, can break other mods. What if they want to change them as well? We'll take a look at how you can add items to loot tables without overriding the table. + +We'll be adding eggs to the coal ore loot table. + +#### Listening to Loot Table Loading {#listening-to-loot-table-loading} + +Fabric API has an event that is fired when loot tables are loaded, `LootTableEvents.MODIFY`. You can register a callback for it in your mod initializer. Let's also check that the current loot table is the coal ore loot table. + +@[code lang=java transclude={38-40}](@/reference/1.20.4/src/main/java/com/example/docs/event/FabricDocsReferenceEvents.java) + +#### Adding Items to the Loot Table {#adding-items-to-the-loot-table} + +In loot tables, items are stored in _loot pool entries_, and entries are stored in _loot pools_. To add an item, we'll need to add a pool with an item entry to the loot table. + +We can make a pool with `LootPool#builder`, and add it to the loot table. + +Our pool doesn't have any items either, so we'll make an item entry using `ItemEntry#builder` and add it to the pool. + +@[code highlight={6-7} transcludeWith=:::2](@/reference/1.20.4/src/main/java/com/example/docs/event/FabricDocsReferenceEvents.java) + +## Custom Events {#custom-events} + +Some areas of the game do not have hooks provided by the Fabric API, so you can either use a mixin or create your own event. + +We'll look at creating an event that is triggered when sheep are sheared. The process of creating an event is: + +- Creating the event callback interface +- Triggering the event from a mixin +- Creating a test implementation + +### Creating the Event Callback Interface {#creating-the-event-callback-interface} + +The callback interface describes what must be implemented by event listeners that will listen to your event. The callback interface also describes how the event will be called from our mixin. It is conventional to place an `Event` object as a field in the callback interface, which will identify our actual event. + +For our `Event` implementation, we will choose to use an array-backed event. The array will contain all event listeners that are listening to the event. + +Our implementation will call the event listeners in order until one of them does not return `ActionResult.PASS`. This means that a listener can say "_cancel this_", "_approve this_" or "_don't care, leave it to the next event listener_" using its return value. + +Using `ActionResult` as a return value is a conventional way to make event handlers cooperate in this fashion. + +You'll need to create an interface that has an `Event` instance and method for response implementation. A basic setup for our sheep shear callback is: + +@[code lang=java transcludeWith=:::](@/reference/1.20.4/src/main/java/com/example/docs/event/SheepShearCallback.java) + +Let's look at this more in-depth. When the invoker is called, we iterate over all listeners: + +@[code lang=java transclude={21-22}](@/reference/1.20.4/src/main/java/com/example/docs/event/SheepShearCallback.java) + +We then call our method (in this case, `interact`) on the listener to get its response: + +@[code lang=java transclude={33-33}](@/reference/1.20.4/src/main/java/com/example/docs/event/SheepShearCallback.java) + +If the listener says we have to cancel (`ActionResult.FAIL`) or fully finish (`ActionResult.SUCCESS`), the callback returns the result and finishes the loop. `ActionResult.PASS` moves on to the next listener, and in most cases should result in success if there are no more listeners registered: + +@[code lang=java transclude={25-30}](@/reference/1.20.4/src/main/java/com/example/docs/event/SheepShearCallback.java) + +We can add Javadoc comments to the top of callback classes to document what each `ActionResult` does. In our case, it might be: + +@[code lang=java transclude={9-16}](@/reference/1.20.4/src/main/java/com/example/docs/event/SheepShearCallback.java) + +### Triggering the Event From a Mixin {#triggering-the-event-from-a-mixin} + +We now have the basic event skeleton, but we need to trigger it. Because we want to have the event called when a player attempts to shear a sheep, we call the event `invoker` in `SheepEntity#interactMob` when `sheared()` is called (i.e. sheep can be sheared, and the player is holding shears): + +@[code lang=java transcludeWith=:::](@/reference/1.20.4/src/main/java/com/example/docs/mixin/event/SheepEntityMixin.java) + +### Creating a Test Implementation {#creating-a-test-implementation} + +Now we need to test our event. You can register a listener in your initialization method (or another area, if you prefer) and add custom logic there. Here's an example that drops a diamond instead of wool at the sheep's feet: + +@[code lang=java transcludeWith=:::3](@/reference/1.20.4/src/main/java/com/example/docs/event/FabricDocsReferenceEvents.java) + +If you enter into your game and shear a sheep, a diamond should drop instead of wool. diff --git a/versions/1.20.4/develop/getting-started/creating-a-project.md b/versions/1.20.4/develop/getting-started/creating-a-project.md new file mode 100644 index 000000000..6949c12b0 --- /dev/null +++ b/versions/1.20.4/develop/getting-started/creating-a-project.md @@ -0,0 +1,68 @@ +--- +title: Creating a Project +description: A step-by-step guide on how to create a new mod project using the Fabric template mod generator. +authors: + - IMB11 +--- + +# Creating a Project {#creating-a-project} + +Fabric provides an easy way to create a new mod project using the Fabric Template Mod Generator - if you want, you can manually create a new project using the example mod repository, you should refer to the [Manual Project Creation](#manual-project-creation) section. + +## Generating a Project {#generating-a-project} + +You can use the [Fabric Template Mod Generator](https://fabricmc.net/develop/template/) to generate a new project for your mod - you should fill in the required fields, such as the package name and mod name, and the Minecraft version that you want to develop for. + +![Preview of the generator](/assets/develop/getting-started/template-generator.png) + +If you want to use Kotlin, or want to add data generators, you can select the appropriate options in the `Advanced Options` section. + +![Advanced options section](/assets/develop/getting-started/template-generator-advanced.png) + +Once you've filled in the required fields, click the `Generate` button, and the generator will create a new project for you to use in the form of a zip file. + +You should extract this zip file to a location of your choice, and then open the extracted folder in IntelliJ IDEA: + +![Open Project Prompt](/assets/develop/getting-started/open-project.png) + +## Importing the Project {#importing-the-project} + +Once you've opened the project in IntelliJ IDEA, the IDE should automatically load the project's Gradle configuration and perform the necessary setup tasks. + +If you receive a notification talking about a Gradle build script, you should click the `Import Gradle Project` button: + +![Gradle Prompt](/assets/develop/getting-started/gradle-prompt.png) + +Once the project has been imported, you should see the project's files in the project explorer, and you should be able to start developing your mod. + +## Manual Project Creation {#manual-project-creation} + +::: warning +You will need [Git](https://git-scm.com/) installed in order to clone the example mod repository. +::: + +If you cannot use the Fabric Template Mod Generator, you can create a new project manually by following these steps. + +Firstly, clone the example mod repository using Git: + +```sh +git clone https://github.com/FabricMC/fabric-example-mod/ my-mod-project +``` + +This will clone the repository into a new folder called `my-mod-project`. + +You should then delete the `.git` folder from the cloned repository, and then open the project in IntelliJ IDEA. If the `.git` folder does not appear, you should enable the display of hidden files in your file manager. + +Once you've opened the project in IntelliJ IDEA, it should automatically load the project's Gradle configuration and perform the necessary setup tasks. + +Again, as previously mentioned, if you receive a notification talking about a Gradle build script, you should click the `Import Gradle Project` button. + +### Modifying the Template {#modifying-the-template} + +Once the project has been imported, you should modify the project's details to match your mod's details: + +- Modify the project's `gradle.properties` file to change the `maven_group` and `archive_base_name` properties to match your mod's details. +- Modify the `fabric.mod.json` file to change the `id`, `name`, and `description` properties to match your mod's details. +- Make sure to update the versions of Minecraft, the mappings, the Loader and the Loom - all of which can be queried through - to match the versions you wish to target. + +You can obviously change the package name and the mod's main class to match your mod's details. diff --git a/versions/1.20.4/develop/getting-started/introduction-to-fabric-and-modding.md b/versions/1.20.4/develop/getting-started/introduction-to-fabric-and-modding.md new file mode 100644 index 000000000..04f4aa4d4 --- /dev/null +++ b/versions/1.20.4/develop/getting-started/introduction-to-fabric-and-modding.md @@ -0,0 +1,65 @@ +--- +title: Introduction to Fabric and Modding +description: "A brief introduction to Fabric and modding in Minecraft: Java Edition." +authors: + - IMB11 + - itsmiir +authors-nogithub: + - basil4088 +--- + +# Introduction to Fabric and Modding {#introduction-to-fabric-and-modding} + +## Prerequisites {#prerequisites} + +Before you start, you should have a basic understanding of developing with Java, and an understanding of Object-Oriented Programming (OOP). + +If you are unfamiliar with these concepts, you may want to look into some tutorials on Java and OOP before you start modding, here are some of the resources that you can use to learn Java and OOP: + +- [W3: Java Tutorials](https://www.w3schools.com/java/) +- [Codecademy: Learn Java](https://www.codecademy.com/learn/learn-java) +- [W3: Java OOP](https://www.w3schools.com/java/java_oop.asp) +- [Medium: Introduction to OOP](https://medium.com/@Adekola_Olawale/beginners-guide-to-object-oriented-programming-a94601ea2fbd) + +### Terminology {#terminology} + +Before we start, let's go over some of the terms that you will encounter when modding with Fabric: + +- **Mod**: A modification to the game, adding new features or changing existing ones. +- **Mod Loader**: A tool that loads mods into the game, such as Fabric Loader. +- **Mixin**: A tool for modifying the game's code at runtime - see [Mixin Introduction](https://fabricmc.net/wiki/tutorial:mixin_introduction) for more information. +- **Gradle**: A build automation tool used to build and compile mods, used by Fabric to build mods. +- **Mappings**: A set of mappings that map obfuscated code to human-readable code. +- **Obfuscation**: The process of making code difficult to understand, used by Mojang to protect Minecraft's code. +- **Remapping**: The process of mapping obfuscated code to human-readable code. + +## What Is Fabric? {#what-is-fabric} + +Fabric is a lightweight modding toolchain for Minecraft: Java Edition. + +It is designed to be a simple and easy-to-use modding platform. Fabric is a community-driven project, and it is open-source, meaning that anyone can contribute to the project. + +You should be aware of the four main components of Fabric: + +- **Fabric Loader**: A flexible platform-independent mod loader designed for Minecraft and other games and applications. +- **Fabric Loom**: A Gradle plugin enabling developers to easily develop and debug mods. +- **Fabric API**: A set of APIs and tools for mod developers to use when creating mods. +- **Yarn**: A set of open Minecraft mappings, free for everyone to use under the Creative Commons Zero license. + +## Why Is Fabric Necessary to Mod Minecraft? {#why-is-fabric-necessary-to-mod-minecraft} + +> Modding is the process of modifying a game in order to change its behavior or add new features - in the case of Minecraft, this can be anything from adding new items, blocks, or entities, to changing the game's mechanics or adding new game modes. + +Minecraft: Java Edition is obfuscated by Mojang, making modification alone difficult. However, with the help of modding tools like Fabric, modding becomes much easier. There are several mapping systems that can assist in this process. + +Loom remaps the obfuscated code to a human-readable format using these mappings, making it easier for modders to understand and modify the game's code. Yarn is a popular and excellent mappings choice for this, but other options exist as well. Each mapping project may have its own strengths or focus. + +Loom allows you to easily develop and compile mods against remapped code, and Fabric Loader allows you to load these mods into the game. + +## What Does Fabric API Provide, and Why Is It Needed? {#what-does-fabric-api-provide-and-why-is-it-needed} + +> Fabric API is a set of APIs and tools for mod developers to use when creating mods. + +Fabric API provides a wide set of APIs that build on top of Minecraft's existing functionality - for example, providing new hooks and events for modders to use, or providing new utilities and tools to make modding easier - such as transitive access wideners and the ability to access internal registries, such as the compostable items registry. + +While Fabric API offers powerful features, some tasks, like basic block registration, can be accomplished without it using the vanilla APIs. diff --git a/versions/1.20.4/develop/getting-started/launching-the-game.md b/versions/1.20.4/develop/getting-started/launching-the-game.md new file mode 100644 index 000000000..404d33b5d --- /dev/null +++ b/versions/1.20.4/develop/getting-started/launching-the-game.md @@ -0,0 +1,63 @@ +--- +title: Launching the Game +description: Learn how to utilize the various launch profiles to start and debug your mods in a live game environment. +authors: + - IMB11 +--- + +# Launching the Game {#launching-the-game} + +Fabric Loom provides a variety of launch profiles to help you start and debug your mods in a live game environment. This guide will cover the various launch profiles and how to use them to debug and playtest your mods. + +## Launch Profiles {#launch-profiles} + +If you're using IntelliJ IDEA, you can find the launch profiles in the top-right corner of the window. Click the dropdown menu to see the available launch profiles. + +There should be a client and server profile, with the option to either run it normally or in debug mode: + +![Launch Profiles](/assets/develop/getting-started/launch-profiles.png) + +## Gradle Tasks {#gradle-tasks} + +If you're using the command line, you can use the following Gradle commands to start the game: + +- `./gradlew runClient` - Start the game in client mode. +- `./gradlew runServer` - Start the game in server mode. + +The only problem with this approach is that you can't easily debug your code. If you want to debug your code, you'll need to use the launch profiles in IntelliJ IDEA or via your IDE's Gradle integration. + +## Hotswapping Classes {#hotswapping-classes} + +When you run the game in debug mode, you can hotswap your classes without restarting the game. This is useful for quickly testing changes to your code. + +You're still quite limited though: + +- You can't add or remove methods +- You can't change method parameters +- You can't add or remove fields + +## Hotswapping Mixins {#hotswapping-mixins} + +If you're using Mixins, you can hotswap your Mixin classes without restarting the game. This is useful for quickly testing changes to your Mixins. + +You will need to install the Mixin Java agent for this to work though. + +### 1. Locate the Mixin Library Jar {#1-locate-the-mixin-library-jar} + +In IntelliJ IDEA, you can find the mixin library jar in the "External Libraries" section of the "Project" section: + +![Mixin Library](/assets/develop/getting-started/mixin-library.png) + +You will need to copy the jar's "Absolute Path" for the next step. + +### 2. Add the `-javaagent` VM Argument {#2-add-the--javaagent-vm-argument} + +In your "Minecraft Client" and or "Minecraft Server" run configuration, add the following to the VM Arguments option: + +```:no-line-numbers +-javaagent:"path to mixin library jar here" +``` + +![VM Arguments Screenshot](/assets/develop/getting-started/vm-arguments.png) + +Now, you should be able to modify the contents of your mixin methods during debugging and have the changes take effect without restarting the game. diff --git a/versions/1.20.4/develop/getting-started/project-structure.md b/versions/1.20.4/develop/getting-started/project-structure.md new file mode 100644 index 000000000..835bc6a5a --- /dev/null +++ b/versions/1.20.4/develop/getting-started/project-structure.md @@ -0,0 +1,59 @@ +--- +title: Project Structure +description: An overview of the structure of a Fabric mod project. +authors: + - IMB11 +--- + +# Project Structure {#project-structure} + +This page will go over the structure of a Fabric mod project, and the purpose of each file and folder in the project. + +## `fabric.mod.json` {#fabric-mod-json} + +The `fabric.mod.json` file is the main file that describes your mod to Fabric Loader. It contains information such as the mod's ID, version, and dependencies. + +The most important fields in the `fabric.mod.json` file are: + +- `id`: The mod's ID, which should be unique. +- `name`: The mod's name. +- `environment`: The environment that your mod runs in, such as `client`, `server`, or `*` for both. +- `entrypoints`: The entrypoints that your mod provides, such as `main` or `client`. +- `depends`: The mods that your mod depends on. +- `mixins`: The mixins that your mod provides. + +You can see an example `fabric.mod.json` file below - this is the `fabric.mod.json` file for the reference project that powers this documentation site. + +::: details Reference Project `fabric.mod.json` +@[code lang=json](@/reference/1.20.4/src/main/resources/fabric.mod.json) +::: + +## Entrypoints {#entrypoints} + +As mentioned before, the `fabric.mod.json` file contains a field called `entrypoints` - this field is used to specify the entrypoints that your mod provides. + +The template mod generator creates both a `main` and `client` entrypoint by default - the `main` entrypoint is used for common code, and the `client` entrypoint is used for client-specific code. These entrypoints are called respectively when the game starts. + +@[code lang=java transcludeWith=#entrypoint](@/reference/1.20.4/src/main/java/com/example/docs/FabricDocsReference.java) + +The above is an example of a simple `main` entrypoint that logs a message to the console when the game starts. + +## `src/main/resources` {#src-main-resources} + +The `src/main/resources` folder is used to store the resources that your mod uses, such as textures, models, and sounds. + +It's also the location of `fabric.mod.json` and any mixin configuration files that your mod uses. + +Assets are stored in a structure that mirrors the structure of resource packs - for example, a texture for a block would be stored in `assets/modid/textures/block/block.png`. + +## `src/client/resources` {#src-client-resources} + +The `src/client/resources` folder is used to store client-specific resources, such as textures, models, and sounds that are only used on the client side. + +## `src/main/java` {#src-main-java} + +The `src/main/java` folder is used to store the Java source code for your mod - it exists on both the client and server environments. + +## `src/client/java` {#src-client-java} + +The `src/client/java` folder is used to store client-specific Java source code, such as rendering code or client-side logic - such as block color providers. diff --git a/versions/1.20.4/develop/getting-started/setting-up-a-development-environment.md b/versions/1.20.4/develop/getting-started/setting-up-a-development-environment.md new file mode 100644 index 000000000..fb57880b2 --- /dev/null +++ b/versions/1.20.4/develop/getting-started/setting-up-a-development-environment.md @@ -0,0 +1,55 @@ +--- +title: Setting up a Development Environment +description: A step-by-step guide on how to set up a development environment to create mods using Fabric. +authors: + - IMB11 + - andrew6rant + - SolidBlock-cn + - modmuss50 + - daomephsta + - liach + - telepathicgrunt + - 2xsaiko + - natanfudge + - mkpoli + - falseresync + - asiekierka +authors-nogithub: + - siglong +--- + +# Setting up a Development Environment {#setting-up-a-development-environment} + +To start developing mods with Fabric, you will need to set up a development environment using IntelliJ IDEA. + +## Installing JDK 17 {#installing-jdk-17} + +To develop mods for Minecraft 1.20.4, you will need JDK 17. + +If you need help installing Java, you can refer to the various Java installation guides in the [player guides section](../../players/index). + +## Installing IntelliJ IDEA {#installing-intellij-idea} + +::: info +You can obviously use other IDEs, such as Eclipse or Visual Studio Code, but the majority of the pages on this documentation site will assume that you are using IntelliJ IDEA - you should refer to the documentation for your IDE if you are using a different one. +::: + +If you do not have IntelliJ IDEA installed, you can download it from the [official website](https://www.jetbrains.com/idea/download/) - follow the installation steps for your operating system. + +The Community edition of IntelliJ IDEA is free and open-source, and it is the recommended version for modding with Fabric. + +You may have to scroll down to find the Community edition download link - it looks like the following: + +![IDEA Community Edition Download Prompt](/assets/develop/getting-started/idea-community.png) + +## Installing IDEA Plugins {#installing-idea-plugins} + +Although these plugins aren't strictly necessary, they can make modding with Fabric much easier - you should consider installing them. + +### Minecraft Development {#minecraft-development} + +The Minecraft Development plugin provides support for modding with Fabric, and it is the most important plugin to install. + +You can install it by opening IntelliJ IDEA, and then navigating to `File > Settings > Plugins > Marketplace Tab` - search for `Minecraft Development` in the search bar, and then click the `Install` button. + +Alternatively, you can download it from the [plugin page](https://plugins.jetbrains.com/plugin/8327-minecraft-development) and then install it by navigating to `File > Settings > Plugins > Install Plugin From Disk`. diff --git a/versions/1.20.4/develop/index.md b/versions/1.20.4/develop/index.md new file mode 100644 index 000000000..4dd500f94 --- /dev/null +++ b/versions/1.20.4/develop/index.md @@ -0,0 +1,12 @@ +--- +title: Developer Guides +description: Our curated developer guides, written by the community, span a wide range of topics from setting up a development environment to more advanced topics, such as rendering and networking. +--- + +# Developer Guides {#developer-guides} + +Our curated developer guides, written by the community, span a wide range of topics from setting up a development environment to more advanced topics, such as rendering and networking. + +Take a look at the sidebar for a list of all the developer guides available. If you're looking for something specific, you can use the search bar at the top of the page to find what you need. + +If you want to contribute to the Fabric Documentation, you can find the source code on [GitHub](https://github.com/FabricMC/fabric-docs), and the relevant [contribution guidelines](../contributing). diff --git a/versions/1.20.4/develop/items/custom-armor.md b/versions/1.20.4/develop/items/custom-armor.md new file mode 100644 index 000000000..c82cc27cd --- /dev/null +++ b/versions/1.20.4/develop/items/custom-armor.md @@ -0,0 +1,166 @@ +--- +title: Custom Armor +description: Learn how to create your own armor sets. +authors: + - IMB11 +--- + +# Custom Armor {#custom-armor} + +Armor provides the player with increased defense against attacks from mobs and other players. + +## Creating an Armor Material {#creating-an-armor-material} + +::: info +If you plan to make multiple armor materials, consider using an `Enum` to store them. Vanilla does this in the `ArmorMaterials` class, which stores all the armor materials that are used in the game. + +This class can also be used to determine your armor material's properties in relation to vanilla armor materials. +::: + +All armor items - like tools - have an armor material. + +The armor material tells the game what protection and durability the armor item should have depending on the slot. + +You'll need to create a class that inherits `ArmorMaterial`, like so: + +@[code transcludeWith=:::1](@/reference/1.20.4/src/main/java/com/example/docs/item/armor/GuiditeArmorMaterial.java) + +The following methods will have to be implemented as well - these methods tell the game vital information on your armor items: + +- ### Durability - `getDurability(ArmorItem.Type type)` + + Returns the durability for a specific armor type - in hit points. + + The hit points specify the amount of hits the armor item can take before breaking. + + **Example** + + @[code transcludeWith=:::2](@/reference/1.20.4/src/main/java/com/example/docs/item/armor/GuiditeArmorMaterial.java) + +- #### Protection - `getProtection(ArmorItem.Type type)` + + Returns the protection value for a specific armor type. + + Usually this is always the same, regardless of your armor material. + + **Example** + + @[code transcludeWith=:::3](@/reference/1.20.4/src/main/java/com/example/docs/item/armor/GuiditeArmorMaterial.java) + +- #### Enchantability - `getEnchantability()` + + How easy is it to get better and higher level enchantments with this item? + + **Example** + + @[code transcludeWith=:::4](@/reference/1.20.4/src/main/java/com/example/docs/item/armor/GuiditeArmorMaterial.java) + +- #### Equip Sound - `getEquipsound()` + + What sound should be played when the armor is equipped? + + **Example** + + @[code transcludeWith=:::5](@/reference/1.20.4/src/main/java/com/example/docs/item/armor/GuiditeArmorMaterial.java) + +- #### Repair Ingredient - `getRepairIngredient()` + + What item or items can be used in an anvil to repair the armor items? + + **Example** + + @[code transcludeWith=:::6](@/reference/1.20.4/src/main/java/com/example/docs/item/armor/GuiditeArmorMaterial.java) + +- #### Name - `getName()` + + The name of the armor material - must be lowercase. + + **Example** + + @[code transcludeWith=:::7](@/reference/1.20.4/src/main/java/com/example/docs/item/armor/GuiditeArmorMaterial.java) + +- #### Toughness - `getToughness()` + + How much protection should be given for high-damage attacks? + + For reference, everything except diamond (`2.0F`) and netherite (`4.0F`) have a toughness of zero. + + **Example** + + @[code transcludeWith=:::8](@/reference/1.20.4/src/main/java/com/example/docs/item/armor/GuiditeArmorMaterial.java) + +- #### Knockback Resistance - `getKnockbackResistance()` + + How much knockback resistance should the armor give the entity? + + **Example** + + @[code transcludeWith=:::9](@/reference/1.20.4/src/main/java/com/example/docs/item/armor/GuiditeArmorMaterial.java) + +## Creating an Instance of the ArmorMaterial {#creating-an-instance-of-the-armormaterial} + +To use the armor material with the armor items, you'll need to create an instance of it - similar to a tool material: + +@[code transcludeWith=:::_10](@/reference/1.20.4/src/main/java/com/example/docs/item/armor/GuiditeArmorMaterial.java) + +You can place this instance in the armor material class itself. + +## Creating the Armor Items {#creating-the-armor-items} + +Now that you've created an instance of the material, you can create the armor items in your `ModItems` class: + +Obviously, an armor set doesn't need every type to be satisfied, you can have a set with just boots, or leggings etc. - the vanilla turtle shell helmet is a good example of an armor set with missing slots. + +@[code transcludeWith=:::6](@/reference/1.20.4/src/main/java/com/example/docs/item/ModItems.java) + +You will also need to **add the items to an item group** if you want them to be accessible from the creative inventory. + +As with all items, you should create translation keys for them as well. + +## Texturing and Modelling {#texturing-and-modelling} + +You will need to create two sets of textures: + +- Textures and models for the items themselves. +- The actual armor texture that is visible when an entity wears the armor. + +### Item Textures and Model {#item-textures-and-model} + +These textures are no different to other items - you must create the textures, and create a generic generated item model - which was covered in the [Creating Your First Item](./first-item#adding-a-texture-and-model) guide. + +For example purposes, you may use the following textures and model JSON as a reference. + + + +::: info +You will need model JSON files for all the items, not just the helmet, it's the same principle as other item models. +::: + +@[code](@/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/item/guidite_helmet.json) + +As you can see, in-game the armor items should have suitable models: + +![Armor item models](/assets/develop/items/armor_1.png) + +## Armor Textures and Model {#armor-textures-and-model} + +When an entity wears your armor, currently the missing texture will appear: + +![Broken armor model on player](/assets/develop/items/armor_2.png). + +This is because all armor textures are hardcoded by vanilla, to create our own, we'll have to place the texture in the vanilla armor texture folder. + +There are two layers for the armor texture, both must be present. + +Since the armor material name in our case is `guidite`, the locations of the textures will be: + +- `assets/minecraft/textures/models/armor/guidite_layer_1.png` +- `assets/minecraft/textures/models/armor/guidite_layer_2.png` + + + +The first layer contains textures for the helmet and chestplate, whilst the second layer contains textures for leggings and boots. + +When these textures are present, you should be able to see your armor on entities that wear it: + +![Working armor model on player](/assets/develop/items/armor_3.png). diff --git a/versions/1.20.4/develop/items/custom-item-groups.md b/versions/1.20.4/develop/items/custom-item-groups.md new file mode 100644 index 000000000..2a36df2f2 --- /dev/null +++ b/versions/1.20.4/develop/items/custom-item-groups.md @@ -0,0 +1,38 @@ +--- +title: Custom Item Groups +description: Learn how to create your own item group and add items to it. +authors: + - IMB11 +--- + +# Custom Item Groups {#custom-item-groups} + +Item groups are the tabs in the creative inventory that store items. You can create your own item group to store your items in a separate tab. This is pretty useful if your mod adds a lot of items and you want to keep them organized in one location for your players to easily access. + +## Creating the Item Group {#creating-the-item-group} + +It's surprisingly easy to create an item group. Simply create a new static final field in your items class to store the item group and a registry key for it, you can then use the item group event similarly to how you added your items to the vanilla item groups: + +@[code transcludeWith=:::9](@/reference/1.20.4/src/main/java/com/example/docs/item/ModItems.java) + +@[code transcludeWith=:::_12](@/reference/1.20.4/src/main/java/com/example/docs/item/ModItems.java) + +
+ +You should see the item group is now in the creative inventory menu. However, it is untranslated - you must add a translation key to your translations file - similarly to how you translated your first item. + +![Item group without translation in creative menu](/assets/develop/items/itemgroups_0.png) + +## Adding a Translation Key {#adding-a-translation-key} + +If you used `Text.translatable` for the `displayName` method of the item group builder, you will need to add the translation to your language file. + +```json +{ + "itemGroup.fabric_docs_reference": "Fabric Docs Reference" +} +``` + +Now, as you can see, the item group should be correctly named: + +![Fully completed item group with translation and items](/assets/develop/items/itemgroups_1.png) diff --git a/versions/1.20.4/develop/items/custom-item-interactions.md b/versions/1.20.4/develop/items/custom-item-interactions.md new file mode 100644 index 000000000..7dedddfd2 --- /dev/null +++ b/versions/1.20.4/develop/items/custom-item-interactions.md @@ -0,0 +1,71 @@ +--- +title: Custom Item Interactions +description: Learn how to create an item that uses built-in vanilla events. +authors: + - IMB11 +--- + +# Custom Item Interactions {#custom-item-interactions} + +Basic items can only go so far - eventually you will need an item that interacts with the world when it is used. + +There are some key classes you must understand before taking a look at the vanilla item events. + +## TypedActionResult {#typedactionresult} + +For items, the most common `TypedActionResult` you'll see is for `ItemStacks` - this class tells the game what to replace the item stack (or not to replace) after the event has occured. + +If nothing has occured in the event, you should use the `TypedActionResult#pass(stack)` method where `stack` is the current item stack. + +You can get the current item stack by getting the stack in the player's hand. Usually events that require a `TypedActionResult` pass the hand to the event method. + +```java +TypedActionResult.pass(user.getStackInHand(hand)) +``` + +If you pass the current stack - nothing will change, regardless of if you declare the event as failed, passed/ignored or successful. + +If you want to delete the current stack, you should pass an empty one. The same can be said about decrementing, you fetch the current stack and decrement it by the amount you want: + +```java +ItemStack heldStack = user.getStackInHand(hand); +heldStack.decrement(1); +TypedActionResult.success(heldStack); +``` + +## ActionResult {#actionresult} + +Similarly, an `ActionResult` tells the game the status of the event, whether it was passed/ignored, failed or successful. + +## Overridable Events {#overridable-events} + +Luckily, the Item class has many methods that can be overriden to add extra functionality to your items. + +::: info +A great example of these events being used can be found in the [Playing SoundEvents](../sounds/using-sounds) page, which uses the `useOnBlock` event to play a sound when the player right clicks a block. +::: + +| Method | Information | +| --------------- | ------------------------------------------------------- | +| `postHit` | Ran when the player hits an entity. | +| `postMine` | Ran when the player mines a block. | +| `inventoryTick` | Ran every tick whilst the item is in an inventory. | +| `onCraft` | Ran when the item is crafted. | +| `useOnBlock` | Ran when the player right clicks a block with the item. | +| `use` | Ran when the player right clicks the item. | + +## The `use()` Event {#use-event} + +Let's say you want to make an item that summons a lightning bolt infront of the player - you would need to create a custom class. + +@[code transcludeWith=:::1](@/reference/1.20.4/src/main/java/com/example/docs/item/custom/LightningStick.java) + +The `use` event is probably the most useful out of them all - you can use this event to spawn our lightning bolt, you should spawn it 10 blocks in front of the players facing direction. + +@[code transcludeWith=:::2](@/reference/1.20.4/src/main/java/com/example/docs/item/custom/LightningStick.java) + +As usual, you should register your item, add a model and texture. + +As you can see, the lightning bolt should spawn 10 blocks infront of you - the player. + + diff --git a/versions/1.20.4/develop/items/custom-tools.md b/versions/1.20.4/develop/items/custom-tools.md new file mode 100644 index 000000000..b4a3582bd --- /dev/null +++ b/versions/1.20.4/develop/items/custom-tools.md @@ -0,0 +1,104 @@ +--- +title: Tools and Weapons +description: Learn how to create your own tools and configure their properties. +authors: + - IMB11 +--- + +# Tools {#tools} + +Tools are essential for survival and progression, allowing players to gather resources, construct buildings, and defend themselves. + +## Creating a Tool Material {#creating-a-tool-material} + +::: info +If you're creating multiple tool materials, consider using an `Enum` to store them. Vanilla does this in the `ToolMaterials` class, which stores all the tool materials that are used in the game. + +This class can also be used to determine your tool material's properties in relation to vanilla tool materials. +::: + +You can create a tool material by creating a new class that inherits it - in this example, I'll be creating "Guidite" tools: + +@[code transcludeWith=:::1](@/reference/1.20.4/src/main/java/com/example/docs/item/tool/GuiditeMaterial.java) + +The tool material tells the game the following information: + +- ### Durability - `getDurability()` {#durability} + + How many times the tool can be used before breaking. + + **Example** + + @[code transcludeWith=:::2](@/reference/1.20.4/src/main/java/com/example/docs/item/tool/GuiditeMaterial.java) + +- ### Mining Speed - `getMiningSpeedMultiplier()` {#mining-speed} + + If the tool is used to break blocks, how fast should it break the blocks? + + For reference purposes, the diamond tool material has a mining speed of `8.0F` whilst the stone tool material has a mining speed of `4.0F`. + + **Example** + + @[code transcludeWith=:::3](@/reference/1.20.4/src/main/java/com/example/docs/item/tool/GuiditeMaterial.java) + +- ### Attack Damage - `getAttackDamage()` {#attack-damage} + + How many points of damage should the tool do when used as a weapon against another entity? + + **Example** + + @[code transcludeWith=:::4](@/reference/1.20.4/src/main/java/com/example/docs/item/tool/GuiditeMaterial.java) + +- ### Mining Level - `getMiningLevel()` {#mining-level} + + What blocks can be broken by this tool? Can it mine diamonds? + + A mining level of 3+ is needed to require obsidian whilst a level of 2 is required to mine diamonds. + + **Example** + + @[code transcludeWith=:::5](@/reference/1.20.4/src/main/java/com/example/docs/item/tool/GuiditeMaterial.java) + +- ### Enchantability - `getEnchantability()` {#enchantability} + + How easy is it to get better and higher level enchantments with this item? For reference, Gold has an enchantability of 22 whilst Netherite has an enchantability of 15. + + **Example** + + @[code transcludeWith=:::6](@/reference/1.20.4/src/main/java/com/example/docs/item/tool/GuiditeMaterial.java) + +- ### Repair Ingredient(s) - `getRepairIngredient()` {#repair-ingredient} + + What item or items are used to repair the tool? + + **Example** + + @[code transcludeWith=:::7](@/reference/1.20.4/src/main/java/com/example/docs/item/tool/GuiditeMaterial.java) + +Once you have created your tool material and tweaked it to your likings, you can create an instance of it to be used in the tool item constructors. + +@[code transcludeWith=:::8](@/reference/1.20.4/src/main/java/com/example/docs/item/tool/GuiditeMaterial.java) + +## Creating Tool Items {#creating-tool-items} + +Using the same way you registered your first item, you should register each tool similarly: + +@[code transcludeWith=:::7](@/reference/1.20.4/src/main/java/com/example/docs/item/ModItems.java) + +Remember to add them to an item group if you want to access them from the creative inventory! + +@[code transcludeWith=:::8](@/reference/1.20.4/src/main/java/com/example/docs/item/ModItems.java) + +You will also have to add a texture, item translation and item model. However, for the item model, you'll want to use the `item/handheld` model as your parent. + +For this example, I will be using the following model and texture for the "Guidite Sword" item: + +@[code](@/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/item/guidite_sword.json) + + + +--- + +That's pretty much it! If you go in-game you should see your tool item(s) in the tools tab of the creative inventory menu. + +![Finished tools in inventory](/assets/develop/items/tools_1.png) diff --git a/versions/1.20.4/develop/items/first-item.md b/versions/1.20.4/develop/items/first-item.md new file mode 100644 index 000000000..95aea5723 --- /dev/null +++ b/versions/1.20.4/develop/items/first-item.md @@ -0,0 +1,151 @@ +--- +title: Creating Your First Item +description: Learn how to register a simple item and how to texture, model and name it. +authors: + - IMB11 + - dicedpixels +--- + +# Creating Your First Item {#creating-your-first-item} + +This page will introduce you into some key concepts relating to items, and how you can register, texture, model and name them. + +If you aren't aware, everything in Minecraft is stored in registries, and items are no exception to that. + +## Preparing Your Items Class {#preparing-your-items-class} + +To simplify the registering of items, you can create a method that accepts an instance of an item and a string identifier. + +This method will create an item with the provided identifier and register it with the game's item registry. + +You can put this method in a class called `ModItems` (or whatever you want to name the class). + +Mojang does this with their items as well! Check out the `Items` class for inspiration. + +@[code transcludeWith=:::1](@/reference/1.20.4/src/main/java/com/example/docs/item/ModItems.java) + +## Registering an Item {#registering-an-item} + +You can now register an item using the method now. + +The item constructor takes in an instance of the `Items.Settings` class as a parameter. This class allows you to configure the item's properties through various builder methods. + +::: tip +If you want to change your item's stack size, you can use the `maxCount` method in the `Items.Settings`/`FabricItemSettings` class. + +This will not work if you've marked the item as damageable, as the stack size is always 1 for damageable items to prevent duplication exploits. +::: + +@[code transcludeWith=:::2](@/reference/1.20.4/src/main/java/com/example/docs/item/ModItems.java) + +However, when you go in-game, you can see that our item doesn't exist! This is because you don't statically initialize the class. + +To do this, you can add a public static initialize method to your class and call it from your `ModInitializer` class. Currently, this method doesn't need anything inside it. + +@[code transcludeWith=:::3](@/reference/1.20.4/src/main/java/com/example/docs/item/ModItems.java) + +@[code transcludeWith=:::1](@/reference/1.20.4/src/main/java/com/example/docs/item/FabricDocsReferenceItems.java) + +Calling a method on a class statically initializes it if it hasn't been previously loaded - this means that all `static` fields are evaluated. This is what this dummy `initialize` method is for. + +## Adding the Item to an Item Group {#adding-the-item-to-an-item-group} + +::: info +If you want to add the item to a custom `ItemGroup`, checkout the [Custom Item Groups](./item-groups) page for more information. +::: + +For example purposes, we will add this item to the ingredients `ItemGroup`, you will need to use Fabric API's item group events - specifically `ItemGroupEvents.modifyEntriesEvent` + +This can be done in the `initialize` method of your items class. + +@[code transcludeWith=:::4](@/reference/1.20.4/src/main/java/com/example/docs/item/ModItems.java) + +Loading into the game, you can see that our item has been registered, and is in the Ingredients item group: + +![Item in the ingredients group](/assets/develop/items/first_item_0.png) + +However, it's missing the following: + +- Item Model +- Texture +- Translation (name) + +## Naming The Item {#naming-the-item} + +The item currently doesn't have a translation, so you will need to add one. The translation key has already been provided by Minecraft: `item.mod_id.suspicious_substance`. + +Create a new JSON file at: `src/main/resources/assets//lang/en_us.json` and put in the translation key, and it's value: + +```json +{ + "item.mod_id.suspicious_substance": "Suspicious Substance" +} +``` + +You can either restart the game or build your mod and press F3 + T to apply changes. + +## Adding a Texture and Model {#adding-a-texture-and-model} + +To give your item a texture and model, simply create a 16x16 texture image for your item and save it in the `assets//textures/item` folder. Name the texture file the same as the item's identifier, but with a `.png` extension. + +For example purposes, you can use this example texture for `suspicious_substance.png` + + + +When restarting/reloading the game - you should see that the item still has no texture, that's because you will need to add a model that uses this texture. + +You're going to create a simple `item/generated` model, which takes in an input texture and nothing else. + +Create the model JSON in the `assets//models/item` folder, with the same name as the item; `suspicious_substance.json` + +@[code](@/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/models/item/suspicious_substance.json) + +### Breaking Down the Model JSON {#breaking-down-the-model-json} + +- `parent`: This is the parent model that this model will inherit from. In this case, it's the `item/generated` model. +- `textures`: This is where you define the textures for the model. The `layer0` key is the texture that the model will use. + +Most items will use the `item/generated` model as their parent, as it's a simple model that just displays the texture. + +There are alternatives, such as `item/handheld` which is used for items that are held in the player's hand, such as tools. + +Your item should now look like this in-game: + +![Item with correct model](/assets/develop/items/first_item_2.png) + +## Making the Item Compostable or a Fuel {#making-the-item-compostable-or-a-fuel} + +Fabric API provides various registries that can be used to add additional properties to your item. + +For example, if you want to make your item compostable, you can use the `CompostableItemRegistry`: + +@[code transcludeWith=:::_10](@/reference/1.20.4/src/main/java/com/example/docs/item/ModItems.java) + +Alternatively, if you want to make your item a fuel, you can use the `FuelRegistry` class: + +@[code transcludeWith=:::_11](@/reference/1.20.4/src/main/java/com/example/docs/item/ModItems.java) + +## Adding a Basic Crafting Recipe {#adding-a-basic-crafting-recipe} + + + +If you want to add a crafting recipe for your item, you will need to place a recipe JSON file in the `data//recipes` folder. + +For more information on the recipe format, checkout these resources: + +- [Recipe JSON Generator](https://crafting.thedestruc7i0n.ca/) +- [Minecraft Wiki - Recipe JSON](https://minecraft.wiki/w/Recipe#JSON_Format) + +## Custom Tooltips {#custom-tooltips} + +If you want your item to have a custom tooltip, you will need to create a class that extends `Item` and override the `appendTooltip` method. + +::: info +This example uses the `LightningStick` class created in the [Custom Item Interactions](./custom-item-interactions) page. +::: + +@[code lang=java transcludeWith=:::3](@/reference/1.20.4/src/main/java/com/example/docs/item/custom/LightningStick.java) + +Each call to `add()` will add one line to the tooltip. + +![Tooltip Showcase](/assets/develop/items/first_item_3.png) diff --git a/versions/1.20.4/develop/items/food.md b/versions/1.20.4/develop/items/food.md new file mode 100644 index 000000000..68239b046 --- /dev/null +++ b/versions/1.20.4/develop/items/food.md @@ -0,0 +1,51 @@ +--- +title: Food Items +description: Learn how to add a FoodComponent to an item to make it edible, and configure it. +authors: + - IMB11 +--- + +# Food Items {#food-items} + +Food is a core aspect of survival Minecraft, so when creating edible items you have to consider the food's usage with other edible items. + +Unless you're making a mod with overpowered items, you should consider: + +- How much hunger your edible item adds or removes. +- What potion effect(s) does it grant? +- Is it early-game or endgame accessible? + +## Adding the Food Component {#adding-the-food-component} + +To add a food component to an item, we can pass it to the `FabricItemSettings` instance: + +```java +new FabricItemSettings().food(new FoodComponent.Builder().build()) +``` + +Right now, this just makes the item edible and nothing more. + +The `FoodComponent.Builder` class has many methods that allow you to modify what happens when a player eats your item: + +| Method | Description | +| -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `hunger` | Sets the amount of hunger points your item will replenish. | +| `saturationModifier` | Sets the amount of saturation points your item will add. | +| `meat` | Declares your item as meat. Carnivorous entities, such as wolves, will be able to eat it. | +| `alwaysEdible` | Allows your item to be eaten regardless of hunger level. | +| `snack` | Declares your item as a snack. | +| `statusEffect` | Adds a status effect when you eat your item. Usually a status effect instance and chance is passed to this method, where chance is a decimal percentage (`1f = 100%`) | + +When you've modified the builder to your liking, you can call the `build()` method to get the `FoodComponent` + +Using the example created in the [Creating Your First Item](./first-item) page, I'll be using the following options for the builder: + +@[code transcludeWith=:::5](@/reference/1.20.4/src/main/java/com/example/docs/item/ModItems.java) + +This makes the item: + +- Always edible, it can be eaten regardless of hunger level. +- A "snack". +- Always give Poison II for 6 seconds when eaten. + + diff --git a/versions/1.20.4/develop/items/potions.md b/versions/1.20.4/develop/items/potions.md new file mode 100644 index 000000000..075731da9 --- /dev/null +++ b/versions/1.20.4/develop/items/potions.md @@ -0,0 +1,76 @@ +--- +title: Potions +description: Learn how to add a custom potion for various status effects. +authors: + - dicedpixels + - PandoricaVi + - Drakonkinst +--- + +# Potions {#potions} + +Potions are consumables that grants an entity an effect. A player can brew potions using a Brewing Stand or obtain them +as items through various other game mechanics. + +## Custom Potions {#custom-potions} + +Adding a potion follows a similar path as adding an item. You will create an instance of your potion and register it by +calling `BrewingRecipeRegistry.registerPotionRecipe`. + +::: info +When Fabric API is present, `BrewingRecipeRegistry.registerPotionRecipe` is made accessible through an Access Widener. +::: + +### Creating the Potion {#creating-the-potion} + +Let's start by declaring a field to store your `Potion` instance. We will be directly using the initializer class to +hold this. + +@[code lang=java transclude={18-27}](@/reference/1.20.4/src/main/java/com/example/docs/potion/FabricDocsReferencePotions.java) + +We pass an instance of `StatusEffectInstance`, which takes 3 parameters: + +- `StatusEffect type` - An effect. We use our custom effect here. Alternatively you can access vanilla effects + through `net.minecraft.entity.effect.StatusEffects`. +- `int duration` - Duration of the effect in game ticks. +- `int amplifier` - An amplifier for the effect. For example, Haste II would have an amplifier of 1. + +::: info +To create your own effect, please see the [Effects](../entities/effects) guide. +::: + +### Registering the Potion {#registering-the-potion} + +In our initializer, we call `BrewingRecipeRegistry.registerPotionRecipe`. + +@[code lang=java transclude={30-30}](@/reference/1.20.4/src/main/java/com/example/docs/potion/FabricDocsReferencePotions.java) + +`registerPotionRecipe` takes 3 parameters: + +- `Potion input` - The starting potion. Usually this can be a Water Bottle or an Awkward Potion. +- `Item item` - The item which is the main ingredient of the potion. +- `Potion output` - The resultant potion. + +If you use Fabric API, the mixin invoker is not necessary and a direct call +to `BrewingRecipeRegistry.registerPotionRecipe` can be done. + +The full example: + +@[code lang=java transcludeWith=:::1](@/reference/1.20.4/src/main/java/com/example/docs/potion/FabricDocsReferencePotions.java) + +Once registered, you can brew a Tater potion using a potato. + +![Effect in player inventory](/assets/develop/tater-potion.png) + +::: info Registering Potions Using an `Ingredient` + +With the help of Fabric API, it's possible to register a potion using an `Ingredient` instead of an `Item` using ` +net.fabricmc.fabric.api.registry.FabricBrewingRecipeRegistry`. +::: + +### Registering the Potion Without Fabric API {#registering-the-potion-without-fabric-api} + +Without Fabric API, `BrewingRecipeRegistry.registerPotionRecipe` will be private. In order to access this method, use +the following mixin invoker or use an Access Widener. + +@[code lang=java transcludeWith=:::1](@/reference/1.20.4/src/main/java/com/example/docs/mixin/potion/BrewingRecipeRegistryInvoker.java) diff --git a/versions/1.20.4/develop/rendering/basic-concepts.md b/versions/1.20.4/develop/rendering/basic-concepts.md new file mode 100644 index 000000000..0fe71f943 --- /dev/null +++ b/versions/1.20.4/develop/rendering/basic-concepts.md @@ -0,0 +1,162 @@ +--- +title: Basic Rendering Concepts +description: Learn about the basic concepts of rendering using Minecraft's rendering engine. +authors: + - IMB11 + - "0x3C50" +--- + +# Basic Rendering Concepts {#basic-rendering-concepts} + +::: warning +Although Minecraft is built using OpenGL, as of version 1.17+ you cannot use legacy OpenGL methods to render your own things. Instead, you must use the new `BufferBuilder` system, which formats rendering data and uploads it to OpenGL to draw. + +To summarize, you have to use Minecraft's rendering system, or build your own that utilizes `GL.glDrawElements()`. +::: + +This page will cover the basics of rendering using the new system, going over key terminology and concepts. + +Although much of rendering in Minecraft is abstracted through the various `DrawContext` methods, and you'll likely not need to touch anything mentioned here, it's still important to understand the basics of how rendering works. + +## The `Tessellator` {#the-tessellator} + +The `Tessellator` is the main class used to render things in Minecraft. It is a singleton, meaning that there is only one instance of it in the game. You can get the instance using `Tessellator.getInstance()`. + +## The `BufferBuilder` {#the-bufferbuilder} + +The `BufferBuilder` is the class used to format and upload rendering data to OpenGL. It is used to create a buffer, which is then uploaded to OpenGL to draw. + +The `Tessellator` is used to create a `BufferBuilder`, which is used to format and upload rendering data to OpenGL. You can create a `BufferBuilder` using `Tessellator.getBuffer()`. + +### Initializing the `BufferBuilder` {#initializing-the-bufferbuilder} + +Before you can write anything to the `BufferBuilder`, you must initialize it. This is done using `BufferBuilder.begin(...)`, which takes in a `VertexFormat` and a draw mode. + +#### Vertex Formats {#vertex-formats} + +The `VertexFormat` defines the elements that we include in our data buffer and outlines how these elements should be transmitted to OpenGL. + +The following `VertexFormat` elements are available: + +| Element | Format | +| --------------------------------------------- | --------------------------------------------------------------------------------------- | +| `BLIT_SCREEN` | `{ position (3 floats: x, y and z), uv (2 floats), color (4 ubytes) }` | +| `POSITION_COLOR_TEXTURE_LIGHT_NORMAL` | `{ position, color, texture uv, texture light (2 shorts), texture normal (3 sbytes) }` | +| `POSITION_COLOR_TEXTURE_OVERLAY_LIGHT_NORMAL` | `{ position, color, texture uv, overlay (2 shorts), texture light, normal (3 sbytes) }` | +| `POSITION_TEXTURE_COLOR_LIGHT` | `{ position, texture uv, color, texture light }` | +| `POSITION` | `{ position }` | +| `POSITION_COLOR` | `{ position, color }` | +| `LINES` | `{ position, color, normal }` | +| `POSITION_COLOR_LIGHT` | `{ position, color, light }` | +| `POSITION_TEXTURE` | `{ position, uv }` | +| `POSITION_COLOR_TEXTURE` | `{ position, color, uv }` | +| `POSITION_TEXTURE_COLOR` | `{ position, uv, color }` | +| `POSITION_COLOR_TEXTURE_LIGHT` | `{ position, color, uv, light }` | +| `POSITION_TEXTURE_LIGHT_COLOR` | `{ position, uv, light, color }` | +| `POSITION_TEXTURE_COLOR_NORMAL` | `{ position, uv, color, normal }` | + +#### Draw Modes {#draw-modes} + +The draw mode defines how the data is drawn. The following draw modes are available: + +| Draw Mode | Description | +| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | +| `DrawMode.LINES` | Each element is made up of 2 vertices and is represented as a single line. | +| `DrawMode.LINE_STRIP` | The first element requires 2 vertices. Additional elements are drawn with just 1 new vertex, creating a continuous line. | +| `DrawMode.DEBUG_LINES` | Similar to `DrawMode.LINES`, but the line is always exactly one pixel wide on the screen. | +| `DrawMode.DEBUG_LINE_STRIP` | Same as `DrawMode.LINE_STRIP`, but lines are always one pixel wide. | +| `DrawMode.TRIANGLES` | Each element is made up of 3 vertices, forming a triangle. | +| `DrawMode.TRIANGLE_STRIP` | Starts with 3 vertices for the first triangle. Each additional vertex forms a new triangle with the last two vertices. | +| `DrawMode.TRIANGLE_FAN` | Starts with 3 vertices for the first triangle. Each additional vertex forms a new triangle with the first vertex and the last vertex. | +| `DrawMode.QUADS` | Each element is made up of 4 vertices, forming a quadrilateral. | + +### Writing to the `BufferBuilder` {#writing-to-the-bufferbuilder} + +Once the `BufferBuilder` is initialized, you can write data to it. + +The `BufferBuilder` allows us to construct our buffer, vertex by vertex. To add a vertex, we use the `buffer.vertex(matrix, float, float, float)` method. The `matrix` parameter is the transformation matrix, which we'll discuss in more detail later. The three float parameters represent the (x, y, z) coordinates of the vertex position. + +This method returns a vertex builder, which we can use to specify additional information for the vertex. It's crucial to follow the order of our defined `VertexFormat` when adding this information. If we don't, OpenGL might not interpret our data correctly. After we've finished building a vertex, we call the `.next()` method. This finalizes the current vertex and prepares the builder for the next one. + +It's also worth understanding the concept of culling. Culling is the process of removing faces of a 3D shape that aren't visible from the viewer's perspective. If the vertices for a face are specified in the wrong order, the face might not render correctly due to culling. + +#### What Is a Transformation Matrix? {#what-is-a-transformation-matrix} + +A transformation matrix is a 4x4 matrix that is used to transform a vector. In Minecraft, the transformation matrix is just transforming the coordinates we give into the vertex call. The transformations can scale our model, move it around and rotate it. + +It's sometimes referred to as a position matrix, or a model matrix. + +It's usually obtained via the `MatrixStack` class, which can be obtained via the `DrawContext` object: + +```java +drawContext.getMatrices().peek().getPositionMatrix(); +``` + +#### Rendering a Triangle Strip {#rendering-a-triangle-strip} + +It's easier to explain how to write to the `BufferBuilder` using a practical example. Let's say we want to render something using the `DrawMode.TRIANGLE_STRIP` draw mode and the `POSITION_COLOR` vertex format. + +We're going to draw vertices at the following points on the HUD (in order): + +```txt +(20, 20) +(5, 40) +(35, 40) +(20, 60) +``` + +This should give us a lovely diamond - since we're using the `TRIANGLE_STRIP` draw mode, the renderer will perform the following steps: + +![Four steps that show the placement of the vertices on the screen to form two triangles](/assets/develop/rendering/concepts-practical-example-draw-process.png) + +Since we're drawing on the HUD in this example, we'll use the `HudRenderCallback` event: + +@[code lang=java transcludeWith=:::1](@/reference/1.20.4/src/client/java/com/example/docs/rendering/RenderingConceptsEntrypoint.java) + +This results in the following being drawn on the HUD: + +![Final Result](/assets/develop/rendering/concepts-practical-example-final-result.png) + +::: tip +Try mess around with the colors and positions of the vertices to see what happens! You can also try using different draw modes and vertex formats. +::: + +## The `MatrixStack` {#the-matrixstack} + +After learning how to write to the `BufferBuilder`, you might be wondering how to transform your model - or even animate it. This is where the `MatrixStack` class comes in. + +The `MatrixStack` class has the following methods: + +- `push()` - Pushes a new matrix onto the stack. +- `pop()` - Pops the top matrix off the stack. +- `peek()` - Returns the top matrix on the stack. +- `translate(x, y, z)` - Translates the top matrix on the stack. +- `scale(x, y, z)` - Scales the top matrix on the stack. + +You can also multiply the top matrix on the stack using quaternions, which we will cover in the next section. + +Taking from our example above, we can make our diamond scale up and down by using the `MatrixStack` and the `tickDelta` - which is the time that has passed since the last frame. + +::: warning +You must first push the matrix stack and then pop it after you're done with it. If you don't, you'll end up with a broken matrix stack, which will cause rendering issues. + +Make sure to push the matrix stack before you get a transformation matrix! +::: + +@[code lang=java transcludeWith=:::2](@/reference/1.20.4/src/client/java/com/example/docs/rendering/RenderingConceptsEntrypoint.java) + +![A video showing the diamond scaling up and down](/assets/develop/rendering/concepts-matrix-stack.webp) + +## Quaternions (Rotating Things) {#quaternions-rotating-things} + +Quaternions are a way of representing rotations in 3D space. They are used to rotate the top matrix on the `MatrixStack` via the `multiply(Quaternion, x, y, z)` method. + +It's highly unlikely you'll need to ever use a Quaternion class directly, since Minecraft provides various pre-built Quaternion instances in it's `RotationAxis` utility class. + +Let's say we want to rotate our diamond around the z-axis. We can do this by using the `MatrixStack` and the `multiply(Quaternion, x, y, z)` method. + +@[code lang=java transcludeWith=:::3](@/reference/1.20.4/src/client/java/com/example/docs/rendering/RenderingConceptsEntrypoint.java) + +The result of this is the following: + +![A video showing the diamond rotating around the z-axis](/assets/develop/rendering/concepts-quaternions.webp) diff --git a/versions/1.20.4/develop/rendering/draw-context.md b/versions/1.20.4/develop/rendering/draw-context.md new file mode 100644 index 000000000..ce1e494fc --- /dev/null +++ b/versions/1.20.4/develop/rendering/draw-context.md @@ -0,0 +1,94 @@ +--- +title: Using the Drawing Context +description: Learn how to use the DrawContext class to render various shapes, text and textures. +authors: + - IMB11 +--- + +# Using the Drawing Context {#using-the-drawing-context} + +This page assumes you've taken a look at the [Basic Rendering Concepts](./basic-concepts) page. + +The `DrawContext` class is the main class used for rendering in the game. It is used for rendering shapes, text and textures, and as previously seen, used to manipulate `MatrixStack`s and use `BufferBuilder`s. + +## Drawing Shapes {#drawing-shapes} + +The `DrawContext` class can be used to easily draw **square-based** shapes. If you want to draw triangles, or any non-square based shape, you will need to use a `BufferBuilder`. + +### Drawing Rectangles {#drawing-rectangles} + +You can use the `DrawContext.fill(...)` method to draw a filled rectangle. + +@[code lang=java transcludeWith=:::1](@/reference/1.20.4/src/client/java/com/example/docs/rendering/DrawContextExampleScreen.java) + +![A rectangle](/assets/develop/rendering/draw-context-rectangle.png) + +### Drawing Outlines/Borders {#drawing-outlines-borders} + +Let's say we want to outline the rectangle we just drew. We can use the `DrawContext.drawBorder(...)` method to draw an outline. + +@[code lang=java transcludeWith=:::2](@/reference/1.20.4/src/client/java/com/example/docs/rendering/DrawContextExampleScreen.java) + +![Rectangle with border](/assets/develop/rendering/draw-context-rectangle-border.png) + +### Drawing Individual Lines {#drawing-individual-lines} + +We can use the `DrawContext.drawHorizontalLine(...)` and `DrawContext.drawVerticalLine(...)` methods to draw lines. + +@[code lang=java transcludeWith=:::3](@/reference/1.20.4/src/client/java/com/example/docs/rendering/DrawContextExampleScreen.java) + +![Lines](/assets/develop/rendering/draw-context-lines.png) + +## The Scissor Manager {#the-scissor-manager} + +The `DrawContext` class has a built-in scissor manager. This allows you to easily clip your rendering to a specific area. This is useful for rendering things like tooltips, or other elements that should not be rendered outside of a specific area. + +### Using the Scissor Manager {#using-the-scissor-manager} + +::: tip +Scissor regions can be nested! But make sure that you disable the scissor manager the same amount of times as you enabled it. +::: + +To enable the scissor manager, simply use the `DrawContext.enableScissor(...)` method. Likewise, to disable the scissor manager, use the `DrawContext.disableScissor()` method. + +@[code lang=java transcludeWith=:::4](@/reference/1.20.4/src/client/java/com/example/docs/rendering/DrawContextExampleScreen.java) + +![Scissor region in action](/assets/develop/rendering/draw-context-scissor.png) + +As you can see, even though we tell the game to render the gradient across the entire screen, it only renders within the scissor region. + +## Drawing Textures {#drawing-textures} + +There is no one "correct" way to draw textures onto a screen, as the `drawTexture(...)` method has many different overloads. This section will go over the most common use cases. + +### Drawing an Entire Texture {#drawing-an-entire-texture} + +Generally, it's recommended that you use the overload that specifies the `textureWidth` and `textureHeight` parameters. This is because the `DrawContext` class will assume these values if you don't provide them, which can sometimes be wrong. + +@[code lang=java transcludeWith=:::5](@/reference/1.20.4/src/client/java/com/example/docs/rendering/DrawContextExampleScreen.java) + +![Drawing whole texture example](/assets/develop/rendering/draw-context-whole-texture.png) + +### Drawing a Portion of a Texture {#drawing-a-portion-of-a-texture} + +This is where `u` and `v` come in. These parameters specify the top-left corner of the texture to draw, and the `regionWidth` and `regionHeight` parameters specify the size of the portion of the texture to draw. + +Let's take this texture as an example. + +![Recipe Book Texture](/assets/develop/rendering/draw-context-recipe-book-background.png) + +If we want to only draw a region that contains the magnifying glass, we can use the following `u`, `v`, `regionWidth` and `regionHeight` values: + +@[code lang=java transcludeWith=:::6](@/reference/1.20.4/src/client/java/com/example/docs/rendering/DrawContextExampleScreen.java) + +![Region Texture](/assets/develop/rendering/draw-context-region-texture.png) + +## Drawing Text {#drawing-text} + +The `DrawContext` class has various self-explanatory text rendering methods - for the sake of brevity, they will not be covered here. + +Let's say we want to draw "Hello World" onto the screen. We can use the `DrawContext.drawText(...)` method to do this. + +@[code lang=java transcludeWith=:::7](@/reference/1.20.4/src/client/java/com/example/docs/rendering/DrawContextExampleScreen.java) + +![Drawing text](/assets/develop/rendering/draw-context-text.png) diff --git a/versions/1.20.4/develop/rendering/gui/custom-screens.md b/versions/1.20.4/develop/rendering/gui/custom-screens.md new file mode 100644 index 000000000..995a33d72 --- /dev/null +++ b/versions/1.20.4/develop/rendering/gui/custom-screens.md @@ -0,0 +1,64 @@ +--- +title: Custom Screens +description: Learn how to create custom screens for your mod. +authors: + - IMB11 +--- + +# Custom Screens {#custom-screens} + +::: info +This page refers to normal screens, not handled ones - these screens are the ones that are opened by the player on the client, not the ones that are handled by the server. +::: + +Screens are essentially the GUIs that the player interacts with, such as the title screen, pause screen etc. + +You can create your own screens to display custom content, a custom settings menu, or more. + +## Creating a Screen {#creating-a-screen} + +To create a screen, you need to extend the `Screen` class and override the `init` method - you may optionally override the `render` method as well - but make sure to call it's super method or it wont render the background, widgets etc. + +You should take note that: + +- Widgets are not being created in the constructor because the screen is not yet initialized at that point - and certain variables, such as `width` and `height`, are not yet available or not yet accurate. +- The `init` method is called when the screen is being initialized, and it is the best place to create widgets. + - You add widgets using the `addDrawableChild` method, which accepts any drawable widget. +- The `render` method is called every frame - you can access the draw context, and the mouse position from this method. + +As an example, we can create a simple screen that has a button and a label above it. + +@[code lang=java transcludeWith=:::1](@/reference/1.20.4/src/client/java/com/example/docs/rendering/screens/CustomScreen.java) + +![Custom Screen 1](/assets/develop/rendering/gui/custom-1-example.png) + +## Opening the Screen {#opening-the-screen} + +You can open the screen using the `MinecraftClient`'s `setScreen` method - you can do this from many places, such as a key binding, a command, or a client packet handler. + +```java +MinecraftClient.getInstance().setScreen( + new CustomScreen(Text.empty()) +); +``` + +## Closing the Screen {#closing-the-screen} + +If you want to close the screen, simply set the screen to `null`: + +```java +MinecraftClient.getInstance().setScreen(null); +``` + +If you want to be fancy, and return to the previous screen, you can pass the current screen into the `CustomScreen` constructor and store it in a field, then use it to return to the previous screen when the `close` method is called. + +@[code lang=java transcludeWith=:::2](@/reference/1.20.4/src/client/java/com/example/docs/rendering/screens/CustomScreen.java) + +Now, when opening the custom screen, you can pass the current screen as the second argument - so when you call `CustomScreen#close` - it will return to the previous screen. + +```java +Screen currentScreen = MinecraftClient.getInstance().currentScreen; +MinecraftClient.getInstance().setScreen( + new CustomScreen(Text.empty(), currentScreen) +); +``` diff --git a/versions/1.20.4/develop/rendering/gui/custom-widgets.md b/versions/1.20.4/develop/rendering/gui/custom-widgets.md new file mode 100644 index 000000000..9fcc40d65 --- /dev/null +++ b/versions/1.20.4/develop/rendering/gui/custom-widgets.md @@ -0,0 +1,39 @@ +--- +title: Custom Widgets +description: Learn how to create custom widgets for your screens. +authors: + - IMB11 +--- + +# Custom Widgets {#custom-widgets} + +Widgets are essentially containerized rendering components that can be added to a screen, and can be interacted with by the player through various events such as mouse clicks, key presses, and more. + +## Creating a Widget {#creating-a-widget} + +There are multiple ways to create a widget class, such as extending `ClickableWidget`. This class provides a lot of useful utilities, such as managing width, height, position, and handling events - it implements the `Drawable`, `Element`, `Narratable`, and `Selectable` interfaces: + +- `Drawable` - for rendering - Required to register the widget to the screen via the `addDrawableChild` method. +- `Element` - for events - Required if you want to handle events such as mouse clicks, key presses, and more. +- `Narratable` - for accessibility - Required to make your widget accessible to screen readers and other accessibility tools. +- `Selectable` - for selection - Required if you want to make your widget selectable using the Tab key - this also aids in accessibility. + +@[code lang=java transcludeWith=:::1](@/reference/1.20.4/src/client/java/com/example/docs/rendering/screens/CustomWidget.java) + +## Adding the Widget to the Screen {#adding-the-widget-to-the-screen} + +Like all widgets, you need to add it to the screen using the `addDrawableChild` method, which is provided by the `Screen` class. Make sure you do this in the `init` method. + +@[code lang=java transcludeWith=:::3](@/reference/1.20.4/src/client/java/com/example/docs/rendering/screens/CustomScreen.java) + +![Custom widget on screen](/assets/develop/rendering/gui/custom-widget-example.png) + +## Widget Events {#widget-events} + +You can handle events such as mouse clicks, key presses, by overriding the `onMouseClicked`, `onMouseReleased`, `onKeyPressed`, and other methods. + +For example, you can make the widget change color when it's hovered over by using the `isHovered()` method provided by the `ClickableWidget` class: + +@[code lang=java transcludeWith=:::2](@/reference/1.20.4/src/client/java/com/example/docs/rendering/screens/CustomWidget.java) + +![Hover Event Example](/assets/develop/rendering/gui/custom-widget-events.webp) diff --git a/versions/1.20.4/develop/rendering/hud.md b/versions/1.20.4/develop/rendering/hud.md new file mode 100644 index 000000000..b5d641c48 --- /dev/null +++ b/versions/1.20.4/develop/rendering/hud.md @@ -0,0 +1,30 @@ +--- +title: Rendering in the Hud +description: Learn how to use the HudRenderCallback event to render to the hud. +authors: + - IMB11 +--- + +# Rendering in the Hud {#rendering-in-the-hud} + +We already briefly touched on rendering things to the hud in the [Basic Rendering Concepts](./basic-concepts) page and [Using The Drawing Context](./draw-context), so on this page we'll stick to the `HudRenderCallback` event and the `deltaTick` parameter. + +## HudRenderCallback {#hudrendercallback} + +The `HudRenderCallback` event - provided by Fabric API - is called every frame, and is used to render things to the HUD. + +To register to this event, you can simply call `HudRenderCallback.EVENT.register` and pass in a lambda that takes a `DrawContext` and a `float` (deltaTick) as parameters. + +The draw context can be used to access the various rendering utilities provided by the game, and access the raw matrix stack. + +You should check out the [Draw Context](./draw-context) page to learn more about the draw context. + +### DeltaTick {#deltatick} + +The `deltaTick` parameter is the time since the last frame, in seconds. This can be used to make animations and other time-based effects. + +For example, let's say you want to lerp a color over time. You can use the `deltaTick` parameter to do this: + +@[code lang=java transcludeWith=:::1](@/reference/1.20.4/src/client/java/com/example/docs/rendering/HudRenderingEntrypoint.java) + +![Lerping a color over time](/assets/develop/rendering/hud-rendering-deltatick.webp) diff --git a/versions/1.20.4/develop/rendering/particles/creating-particles.md b/versions/1.20.4/develop/rendering/particles/creating-particles.md new file mode 100644 index 000000000..7a6ffb8e2 --- /dev/null +++ b/versions/1.20.4/develop/rendering/particles/creating-particles.md @@ -0,0 +1,72 @@ +--- +title: Creating Custom Particles +description: Learn how to create a custom particle using Fabric API. +authors: + - Superkat32 +--- + +# Creating Custom Particles {#creating-custom-particles} + +Particles are a powerful tool. They can add ambience to a beautiful scene, or add tension to an edge of your seat boss battle. Let's add one! + +## Register a Custom Particle {#register-a-custom-particle} + +We'll be adding a new sparkle particle which will mimic the movement of an end rod particle. + +We first need to register a `ParticleType` in your mod initializer class using your mod id. + +@[code lang=java transcludeWith=#particle_register_main](@/reference/1.20.4/src/main/java/com/example/docs/FabricDocsReference.java) + +The "sparkle_particle" in lowercase letters is the JSON path for the particle's texture. You will be creating a new JSON file with that exact name later. + +## Client-Side Registration {#client-side-registration} + +After you have registered the particle in the `ModInitializer` entrypoint, you will also need to register the particle in the `ClientModInitializer` entrypoint. + +@[code lang=java transcludeWith=#particle_register_client](@/reference/1.20.4/src/client/java/com/example/docs/FabricDocsReferenceClient.java) + +In this example, we are registering our particle on the client-side. We are then giving the particle some movement using the end rod particle's factory. This means our particle will move exactly like an end rod particle. + +::: tip +You can see all the particle factories by looking at all the implementations of the `ParticleFactory` interface. This is helpful if you want to use another particle's behaviour for your own particle. + +- IntelliJ's hotkey: Ctrl+Alt+B +- Visual Studio Code's hotkey: Ctrl+F12 +::: + +## Creating a JSON File and Adding Textures {#creating-a-json-file-and-adding-textures} + +You will need to create 2 folders in your `resources/assets//` folder. + +| Folder Path | Explanation | +|----------------------|--------------------------------------------------------------------------------------| +| `/textures/particle` | The `particle` folder will contain all the textures for all of your particles. | +| `/particles` | The `particles` folder will contain all of the json files for all of your particles. | + +For this example, we will have only one texture in `textures/particle` called "sparkle_particle_texture.png". + +Next, create a new JSON file in `particles` with the same name as the JSON path that you used when registering your ParticleType. For this example, we will need to create `sparkle_particle.json`. This file is important because it lets Minecraft know which textures our particle should use. + +@[code lang=json](@/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/particles/sparkle_particle.json) + +::: tip +You can add more textures to the `textures` array to create a particle animation. The particle will cycle through the textures in the array, starting with the first texture. +::: + +## Testing the New Particle {#testing-the-new-particle} + +Once you have completed the JSON file and saved your work, you are good to load up Minecraft and test everything out! + +You can see if everything has worked by typing the following command: + +```mcfunction +/particle :sparkle_particle ~ ~1 ~ +``` + +![Showcase of the particle](/assets/develop/rendering/particles/sparkle-particle-showcase.png) + +::: info +The particle will spawn inside the player with this command. You will likely need to walk backwards to actually see it. +::: + +Alternatively, you can also use a command block to summon the particle with the exact same command. diff --git a/versions/1.20.4/develop/sounds/custom.md b/versions/1.20.4/develop/sounds/custom.md new file mode 100644 index 000000000..73f8aa46f --- /dev/null +++ b/versions/1.20.4/develop/sounds/custom.md @@ -0,0 +1,63 @@ +--- +title: Creating Custom Sounds +description: Learn how to add and use a new sound with the registry. +authors: + - JR1811 +--- + +# Creating Custom Sounds {#creating-custom-sounds} + +## Preparing the Audio File {#preparing-the-audio-file} + +Your audio files need to be formatted in a specific way. OGG Vorbis is an open container format for multimedia data, such as audio, and is used in case of Minecraft's sound files. To avoid problems with how Minecraft handles distancing, your audio needs to have only a single channel (Mono). + +Many modern DAWs (Digital Audio Workstation) software can import and export using this file format. In the following example the free and open-source software "[Audacity](https://www.audacityteam.org/)" will be used to bring the audio file into the right format, however any other DAW should suffice as well. + +![Unprepared audio file in Audacity](/assets/develop/sounds/custom_sounds_0.png) + +In this example, a sound of a [whistle](https://freesound.org/people/strongbot/sounds/568995/) is imported into Audacity. It currently is saved as a `.wav` file and has two audio channels (Stereo). Edit the sound to your liking and make sure to delete one of the channels using the drop-down element at the top of the "track head". + +![Splitting Stereo track](/assets/develop/sounds/custom_sounds_1.png) + +![Deleting one of the channels](/assets/develop/sounds/custom_sounds_2.png) + +When exporting or rendering the audio file, make sure to choose the OGG file format. Some DAWs, like REAPER, might support multiple OGG audio layer formats. In this case OGG Vorbis should work just fine. + +![Exporting as OGG file](/assets/develop/sounds/custom_sounds_3.png) + +Also keep in mind that audio files can increase the file size of your mod drastically. If needed, compress the audio when editing and exporting the file to keep the file size of your finished product to a minimum. + +## Loading the Audio File {#loading-the-audio-file} + +Add the new `resources/assets//sounds` directory for the sounds in your mod, and put the exported audio file `metal_whistle.ogg` in there. + +Continue with creating the `resources/assets//sounds.json` file if it doesn't exist yet and add your sound to the sound entries. + +@[code lang=json](@/reference/1.20.4/src/main/resources/assets/fabric-docs-reference/sounds.json) + +The subtitle entry provides more context for the player. The subtitle name is used in the language files in the `resources/assets//lang` directory and will be displayed if the in-game subtitle setting is turned on and this custom sound is being played. + +## Registering the Custom Sound {#registering-the-custom-sound} + +To add the custom sound to the mod, register a SoundEvent in the class which implements the `ModInitializer` entrypoint. + +```java +Registry.register(Registries.SOUND_EVENT, new Identifier(MOD_ID, "metal_whistle"), + SoundEvent.of(new Identifier(MOD_ID, "metal_whistle"))); +``` + +## Cleaning up the Mess {#cleaning-up-the-mess} + +Depending on how many Registry entries there are, this can get messy quickly. To avoid that, we can make use of a new helper class. + +Add two new methods to the newly created helper class. One, which registers all the sounds and one which is used to initialize this class in the first place. After that you can comfortably add new custom `SoundEvent` static class variables as needed. + +@[code lang=java transcludeWith=:::1](@/reference/1.20.4/src/main/java/com/example/docs/sound/CustomSounds.java) + +This way, the `ModInitializer` implementing entrypoint class needs to only implement one line to register all custom SoundEvents. + +@[code lang=java transcludeWith=:::2](@/reference/1.20.4/src/main/java/com/example/docs/sound/FabricDocsReferenceSounds.java) + +## Using the Custom SoundEvent {#using-the-custom-soundevent} + +Use the helper class to access the custom SoundEvent. Checkout the [Playing SoundEvents](./using-sounds) page to learn how to play sounds. diff --git a/versions/1.20.4/develop/sounds/using-sounds.md b/versions/1.20.4/develop/sounds/using-sounds.md new file mode 100644 index 000000000..94631bcd9 --- /dev/null +++ b/versions/1.20.4/develop/sounds/using-sounds.md @@ -0,0 +1,32 @@ +--- +title: Playing Sounds +description: Learn how to play sound events. +--- + +# Playing Sounds {#playing-sounds} + +Minecraft has a big selection of sounds which you can choose from. Check out the `SoundEvents` class to view all the vanilla sound event instances that Mojang has provided. + +## Using Sounds in Your Mod {#using-sounds} + +Make sure to execute the `playSound()` method on the logical server side when using sounds! + +In this example, the `useOnEntity()` and `useOnBlock()` methods for a custom interactive item are used to play a "placing copper block" and a pillager sound. + +@[code lang=java transcludeWith=:::1](@/reference/1.20.4/src/main/java/com/example/docs/item/custom/CustomSoundItem.java) + +The `playSound()` method is used with the `LivingEntity` object. Only the SoundEvent, the volume and the pitch need to be specified. You can also use the `playSound()` method from the world instance to have a higher level of control. + +@[code lang=java transcludeWith=:::2](@/reference/1.20.4/src/main/java/com/example/docs/item/custom/CustomSoundItem.java) + +### SoundEvent and SoundCategory {#soundevent-and-soundcategory} + +The SoundEvent defines which sound will be played. You can also [register your own SoundEvents](./custom) to include your own sound. + +Minecraft has several audio sliders in the in-game settings. The `SoundCategory` enum is used to determine which slider will adjust your sound's volume. + +### Volume and Pitch {#volume-and-pitch} + +The volume parameter can be a bit misleading. In the range of `0.0f - 1.0f` the actual volume of the sound can be changed. If the number gets bigger than that, the volume of `1.0f` will be used and only the distance, in which your sound can be heard, gets adjusted. The block distance can be roughly calculated by `volume * 16`. + +The pitch parameter increases or decreases the pitch value and also changes the duration of the sound. In the range of `(0.5f - 1.0f)` the pitch and the speed gets decreased, while bigger numbers will increase the pitch and the speed. Numbers below `0.5f` will stay at the pitch value of `0.5f`. diff --git a/versions/1.20.4/develop/text-and-translations.md b/versions/1.20.4/develop/text-and-translations.md new file mode 100644 index 000000000..c3131169f --- /dev/null +++ b/versions/1.20.4/develop/text-and-translations.md @@ -0,0 +1,113 @@ +--- +title: Text and Translations +description: Comprehensive documentation for Minecraft's handling of formatted text and translations. +authors: + - IMB11 +--- + +# Text and Translations {#text-and-translations} + +Whenever Minecraft displays text ingame, it's probably defined using a `Text` object. +This custom type is used instead of a `String` to allow for more advanced formatting, +including colors, boldness, obfuscation, and click events. They also allow easy access +to the translation system, making it simple to translate any interface elements into +different languages. + +If you've worked with datapacks or functions before, you may see parallels with the +json text format used for displayNames, books, and signs among other things. As you +can probably guess, this is just a json representation of a `Text` object, and can be +converted to and from using `Text.Serializer`. + +When making a mod, it is generally preferred to construct your `Text` objects directly +in code, making use of translations whenever possible. + +## Text Literals {#text-literals} + +The simplest way to create a `Text` object is to make a literal. This is just a string +that will be displayed as-is, by default without any formatting. + +These are created using the `Text.of` or `Text.literal` methods, which both act slightly +differently. `Text.of` accepts nulls as input, and will return a `Text` instance. In +contrast, `Text.literal` should not be given a null input, but returns a `MutableText`, +this being a subclass of `Text` that can be easily styled and concatenated. More about +this later. + +```java +Text literal = Text.of("Hello, world!"); +MutableText mutable = Text.literal("Hello, world!"); +// Keep in mind that a MutableText can be used as a Text, making this valid: +Text mutableAsText = mutable; +``` + +## Translatable Text {#translatable-text} + +When you want to provide multiple translations for the same string of text, you can use the `Text.translatable` method to reference a translation key in any language file. If the key doesn't exist, the translation key is converted to a literal. + +```java +Text translatable = Text.translatable("my_mod.text.hello"); + +// Similarly to literals, translatable text can be easily made mutable. +MutableText mutable = Text.translatable("my_mod.text.bye"); +``` + +The language file, `en_us.json`, looks like the following: + +```json +{ + "my_mod.text.hello": "Hello!", + "my_mod.text.bye": "Goodbye :(" +} +``` + +## Serializing Text {#serializing-text} + + + +As mentioned before, you can serialize text to JSON using the following serializer class: + +@[code transcludeWith=:::1](@/reference/1.20.4/src/client/java/com/example/docs/rendering/TextTests.java) + +This produces JSON that can be used datapacks, commands and other places that accept the JSON format of text instead of literal or translatable text. + +## Deserializing Text {#deserializing-text} + +Furthermore, to deserialize a JSON text object into an actual `Text` class, you can use the `fromJson` method: + +@[code transcludeWith=:::2](@/reference/1.20.4/src/client/java/com/example/docs/rendering/TextTests.java) + +## Formatting Text {#formatting-text} + +You may be familiar with Minecraft's formatting standards: + +You can apply these formattings using the `Formatting` enum on the `MutableText` class: + +```java +MutableText result = Text.literal("Hello World!") + .formatted(Formatting.AQUA, Formatting.BOLD, Formatting.UNDERLINE); +``` + + + + + + + + + + + + + + + + + + + + + + + + + +
ColorNameChat CodeMOTD CodeHex Code
Black (black)§0\u00A70#000000
Dark Blue (dark_blue)§1\u00A71#0000AA
Dark Green (dark_green)§2\u00A72#00AA00
Dark Aqua (dark_aqua)§3\u00A73#00AAAA
Dark Red (dark_red)§4\u00A74#AA0000
Dark Purple (dark_purple)§5\u00A75#AA00AA
Gold (gold)§6\u00A76#FFAA00
Gray (gray)§7\u00A77#AAAAAA
Dark Gray (dark_gray)§8\u00A78#555555
Blue (blue)§9\u00A79#5555FF
Green (green)§a\u00A7a#55FF55
Aqua (aqua)§b\u00A7b#55FFFF
Red (red)§c\u00A7c#FF5555
Light Purple (light_purple)§d\u00A7d#FF55FF
Yellow (yellow)§e\u00A7e#FFFF55
White (white)§f\u00A7f#FFFFFF
Reset§r
Bold§l
Strikethrough§m
Underline§n
Italic§o
Obfuscated§k
diff --git a/versions/1.20.4/index.md b/versions/1.20.4/index.md new file mode 100644 index 000000000..d4b078d47 --- /dev/null +++ b/versions/1.20.4/index.md @@ -0,0 +1,33 @@ +--- +title: Fabric Documentation +description: The official curated documentation for Fabric, a modding toolchain for Minecraft. +layout: home + +hero: + name: Fabric Documentation + tagline: The official curated documentation for Fabric, a modding toolchain for Minecraft. + +features: + - title: Developer Guides + icon: 🛠️ + details: Our curated developer guides, written by the community, span a wide range of topics from setting up a development environment to more advanced topics, such as rendering and networking. + link: ./develop/index + linkText: Get Started + - title: Player Guides + icon: 📚 + details: Are you a player looking to use mods powered by Fabric? Our player guides have you covered. These guides will help you in downloading, installing, and troubleshooting Fabric mods. + link: ./players/index + linkText: Read More +--- + +
+ +::: warning +You are currently viewing the documentation for Minecraft 1.20.4. If you are looking for the documentation for a different version, please select the version you are using from the dropdown on the navigation bar. +::: + +## Want to Contribute? {#contribute} + +If you want to contribute to the Fabric Documentation, you can find the source code on [GitHub](https://github.com/FabricMC/fabric-docs), and the relevant [contribution guidelines](./contributing). + +
diff --git a/versions/1.20.4/players/faq.md b/versions/1.20.4/players/faq.md new file mode 100644 index 000000000..886be051e --- /dev/null +++ b/versions/1.20.4/players/faq.md @@ -0,0 +1,29 @@ +--- +title: Frequently Asked Questions for Players +description: Frequently asked questions for players and server administrators relating to Fabric. +--- + +# Frequently Asked Questions {#faq} + +There are a lot of questions that are asked frequently, so we've compiled a list of them here. + +## What Minecraft Versions Does Fabric Support? {#what-minecraft-versions-does-fabric-support} + +Officially, Fabric supports all versions of Minecraft starting from snapshots `18w43b` and above, and releases `1.14` and above. + +## Where Can I Download Published Fabric Mods? {#where-can-i-download-published-fabric-mods} + +::: info +You should always check if mods are from a trustworthy source. Check out the [Finding Trustworthy Mods](./finding-mods) guide for more information. +::: + +The majority of authors publish their mods to [Modrinth](https://modrinth.com/mods?g=categories:%27fabric%27) and [CurseForge](https://www.curseforge.com/minecraft/search?class=mc-mods&gameVersionTypeId=4), however some may choose to upload them on their personal websites, or on other platforms, such as a GitHub repository. + +## Where Can I Find Premade Fabric Modpacks? {#where-can-i-find-premade-fabric-modpacks} + +You can find premade Fabric modpacks on a variety of platforms, such as: + +- [Modrinth](https://modrinth.com/modpacks?g=categories:%27fabric%27) +- [CurseForge](https://www.curseforge.com/minecraft/search?class=modpacks&gameVersionTypeId=4) +- [Feed The Beast](https://www.feed-the-beast.com/ftb-app) +- [Technic](https://www.technicpack.net/modpacks) diff --git a/versions/1.20.4/players/finding-mods.md b/versions/1.20.4/players/finding-mods.md new file mode 100644 index 000000000..c556348de --- /dev/null +++ b/versions/1.20.4/players/finding-mods.md @@ -0,0 +1,34 @@ +--- +title: Finding Trustworthy Mods +description: A guide on how to find Fabric mods using trustworthy sources. +authors: + - IMB11 +--- + +# Finding Trustworthy Mods {#finding-mods} + +Firstly, trust is subjective, and you should always use your own judgement when downloading mods. However, there are some things you can do to help you find trustworthy mods. + +## 1. Use a Source That Is Known to Be Trustworthy {#trustworthy-source} + +The majority of authors publish their mods to [Modrinth](https://modrinth.com/mods?g=categories:%27fabric%27) and [CurseForge](https://www.curseforge.com/minecraft/search?class=mc-mods&gameVersionTypeId=4). + +These websites check that the mods are what they say they are, and that they do not contain malicious code. You can also report malicious mods on those websites, and they will take action relatively quickly. + +## 2. Check With Others! {#with-others} + +If you are downloading a mod from a source that is not known to be trustworthy, you should check with others to see if they have downloaded the mod before from the location you're downloading from, and if they have had any issues with it. + +If in doubt, you are welcome to ask in the [Fabric Discord](https://discord.gg/v6v4pMv) in the `#player-support` channel. + +## 3. Avoid Common Malware Sites! {#avoid-malware} + +::: info +Malware sites may not be obvious to everyone. If you are unsure, you should ask for opinions from others or avoid the site altogether and rely only on trusted sources, such as Modrinth and CurseForge. +::: + +There are a lot of websites that claim to have mods for Minecraft, but are actually just malware sites. You should avoid these sites at all costs. + +You can use antivirus software and websites like [Windows Defender](https://www.microsoft.com/en-us/windows/comprehensive-security) or [VirusTotal](https://www.virustotal.com/) to check the downloaded mods. However, do not rely entirely on those methods, because they can be sometimes incorrect. + +Again, if in doubt, you are welcome to ask for opinions in the [Fabric Discord](https://discord.gg/v6v4pMv) in the `#player-support` channel. diff --git a/versions/1.20.4/players/index.md b/versions/1.20.4/players/index.md new file mode 100644 index 000000000..61c3a80e3 --- /dev/null +++ b/versions/1.20.4/players/index.md @@ -0,0 +1,12 @@ +--- +title: Player Guides +description: A collection of guides for players and server administrators on installing and using Fabric. +--- + +# Player Guides {#player-guides} + +This section of the Fabric Documentation is dedicated to players and server administrators who want to learn how to install, use, and troubleshoot Fabric. + +You should refer to the sidebar for a list of all the guides available. + +If you encounter any issues, please report them [on GitHub](https://github.com/FabricMC/fabric-docs) or ask for help on the [Fabric Discord](https://discord.gg/v6v4pMv) in the `#player-support` or `#server-admin-support` channels. diff --git a/versions/1.20.4/players/installing-fabric.md b/versions/1.20.4/players/installing-fabric.md new file mode 100644 index 000000000..9d85eeb89 --- /dev/null +++ b/versions/1.20.4/players/installing-fabric.md @@ -0,0 +1,53 @@ +--- +title: Installing Fabric +description: A step by step guide on how to install Fabric. +authors: + - IMB11 +--- + +# Installing Fabric {#installing-fabric} + +This guide will walk you through installing Fabric for the official Minecraft Launcher. + +For third party launchers, you should consult their documentation. + +## 1. Download the Fabric Installer {#1-download-the-fabric-installer} + +You can download the Fabric Installer from the [Fabric Website](https://fabricmc.net/use/). + +If you use Windows, download the `.exe` version (`Download For Windows`), because it doesn't require Java to be installed on your system. It instead uses Java that came with the official launcher. + +For macOS and Linux, you should download the `.jar` version. Sometimes, you need to install Java before this step. + +## 2. Run the Fabric Installer {#2-run-the-fabric-installer} + +::: warning +Close Minecraft and the Minecraft Launcher first before installing. +::: + +::: details Information for macOS users + +On macOS, you may need to right click the `.jar` file in your downloads directory and click `Open` to run it. + +![MacOS context menu on Fabric Installer](/assets/players/installing-fabric/macos-downloads.png) + +When asked "Are you sure you want to open it?", click `Open` again. +::: + +Once you've opened the installer, you should see a screen like this: + +![Fabric Installer with "Install" highlighted](/assets/players/installing-fabric/installer-screen.png) + +To install Fabric, simply choose your game version from the dropdown, and click `Install`. + +**Make sure that 'Create Profile' is checked.** + +## 3. You're Done! {#3-you-re-done} + +Once the installer has finished, you can open the Minecraft Launcher and select the Fabric profile from the dropdown in the bottom left corner and press Play! + +![Minecraft Launcher with Fabric profile selected](/assets/players/installing-fabric/launcher-screen.png) + +Now that you've installed Fabric, you can add mods to your game! Check out the [Finding Trustworthy Mods](./finding-mods) guide for more information. + +If you encounter any issues while following this guide, you can ask for help in the [Fabric Discord](https://discord.gg/v6v4pMv) in the `#player-support` channel. diff --git a/versions/1.20.4/players/installing-java/linux.md b/versions/1.20.4/players/installing-java/linux.md new file mode 100644 index 000000000..2502ade89 --- /dev/null +++ b/versions/1.20.4/players/installing-java/linux.md @@ -0,0 +1,91 @@ +--- +title: Installing Java on Linux +description: A step by step guide on how to install Java on Linux. +authors: + - IMB11 +--- + +# Installing Java on Linux {#installing-java-on-linux} + +This guide will walk you through installing Java 17 on Linux. + +## 1. Check if Java Is Already Installed {#1-check-if-java-is-already-installed} + +Open a terminal, type `java -version`, and press Enter. + +![Terminal with "java -version" typed in](/assets/players/installing-java/linux-java-version.png) + +::: warning +To use the majority of modern Minecraft versions, you'll need at least Java 17 installed. If this command displays any version lower than 17, you'll need to update your existing Java installation. +::: + +## 2. Downloading and Installing Java 17 {#2-downloading-and-installing-java-17} + +We recommend using OpenJDK 17, which is available for most Linux distributions. + +### Arch Linux {#arch-linux} + +::: info +For more information on installing Java on Arch Linux, see the [Arch Linux Wiki](https://wiki.archlinux.org/title/Java). +::: + +You can install the latest JRE from the official repositories: + +```sh +sudo pacman -S jre-openjdk +``` + +If you're running a server without the need for a graphical interface, you can install the headless version instead: + +```sh +sudo pacman -S jre-openjdk-headless +``` + +If you plan to develop mods, you'll need the JDK instead: + +```sh +sudo pacman -S jdk-openjdk +``` + +### Debian/Ubuntu {#debian-ubuntu} + +You can install Java 17 using `apt` with the following commands: + +```sh +sudo apt update +sudo apt install openjdk-17-jdk +``` + +### Fedora {#fedora} + +You can install Java 17 using `dnf` with the following commands: + +```sh +sudo dnf install java-17-openjdk +``` + +If you don't need a graphical interface, you can install the headless version instead: + +```sh +sudo dnf install java-17-openjdk-headless +``` + +If you plan to develop mods, you'll need the JDK instead: + +```sh +sudo dnf install java-17-openjdk-devel +``` + +### Other Linux Distributions {#other-linux-distributions} + +If your distribution isn't listed above, you can download the latest JRE from [Adoptium](https://adoptium.net/temurin/) + +You should refer to an alternative guide for your distribution if you plan to develop mods. + +## 3. Verify That Java 17 Is Installed {#3-verify-that-java-17-is-installed} + +Once the installation is complete, you can verify that Java 17 is installed by opening a terminal and typing `java -version`. + +If the command runs successfully, you will see something like shown before, where the Java version is displayed: + +![Terminal with "java -version" typed in](/assets/players/installing-java/linux-java-version.png) diff --git a/versions/1.20.4/players/installing-java/windows.md b/versions/1.20.4/players/installing-java/windows.md new file mode 100644 index 000000000..700e76a63 --- /dev/null +++ b/versions/1.20.4/players/installing-java/windows.md @@ -0,0 +1,65 @@ +--- +title: Installing Java on Windows +description: A step by step guide on how to install Java on Windows. +authors: + - IMB11 +--- + +# Installing Java on Windows {#installing-java-on-windows} + +This guide will walk you through installing Java 17 on Windows. + +The Minecraft Launcher comes with its own Java installation, so this section is only relevant if you want to use the Fabric `.jar` based installer, or if you want to use the Minecraft Server `.jar`. + +## 1. Check if Java Is Already Installed {#1-check-if-java-is-already-installed} + +To check if Java is already installed, you must first open the command prompt. + +You can do this by pressing Win R and typing `cmd.exe` into the box that appears. + +![Windows Run Dialog with "cmd.exe" in the run bar](/assets/players/installing-java/windows-run-dialog.png) + +Once you have opened the command prompt, type `java -version` and press Enter. + +If the command runs successfully, you will see something like this. If the command failed, proceed to the next step. + +![Command prompt with "java -version" typed in](/assets/players/installing-java/windows-java-version.png) + +::: warning +To use the majority of modern Minecraft versions, you'll need at least Java 17 installed. If this command displays any version lower than 17, you'll need to update your existing Java installation. +::: + +## 2. Download the Java 17 Installer {#2-download-the-java-17-installer} + +To install Java 17, you'll need to download the installer from [Adoptium](https://adoptium.net/en-GB/temurin/releases/?os=windows&package=jdk&version=17). + +You'll want to download the `Windows Installer (.msi)` version: + +![Adoptium download page with Windows Installer (.msi) highlighted](/assets/players/installing-java/windows-download-java.png) + +You should choose `x86` if you have a 32-bit operating system, or `x64` if you have a 64-bit operating system. + +The majority of modern computers will have a 64-bit operating system. If you are unsure, try using the 64-bit download. + +## 3. Run the Installer! {#3-run-the-installer} + +Follow the steps in the installer to install Java 17. When you reach this page, you should set the following features to "Entire feature will be installed on local hard drive": + +- `Set JAVA_HOME environment variable` - This will be added to your PATH. +- `JavaSoft (Oracle) registry keys` + +![Java 17 installer with "Set JAVA_HOME variable" and "JavaSoft (Oracle) registry keys" highlighted](/assets/players/installing-java/windows-wizard-screenshot.png) + +Once you've done that, you can click `Next` and continue with the installation. + +## 4. Verify That Java 17 Is Installed {#4-verify-that-java-17-is-installed} + +Once the installation is complete, you can verify that Java 17 is installed by opening the command prompt again and typing `java -version`. + +If the command runs successfully, you will see something like shown before, where the Java version is displayed: + +![Command prompt with "java -version" typed in](/assets/players/installing-java/windows-java-version.png) + +--- + +If you encounter any issues, feel free to ask for help in the [Fabric Discord](https://discord.gg/v6v4pMv) in the `#player-support` channel. diff --git a/versions/1.20.4/players/installing-mods.md b/versions/1.20.4/players/installing-mods.md new file mode 100644 index 000000000..7f59be111 --- /dev/null +++ b/versions/1.20.4/players/installing-mods.md @@ -0,0 +1,67 @@ +--- +title: Installing Mods +description: A step by step guide on how to install mods for Fabric. +authors: + - IMB11 +--- + +# Installing Mods {#installing-mods} + +This guide will walk you through installing mods for Fabric using the Minecraft Launcher. + +For third party launchers, you should consult their documentation. + +## 1. Download the Mod {#1-download-the-mod} + +::: warning +You should only download mods from sources you trust. For more information on finding mods, see the [Finding Trustworthy Mods](./finding-mods) guide. +::: + +The majority of mods require Fabric API as well, which can be downloaded from [Modrinth](https://modrinth.com/mod/fabric-api) or [CurseForge](https://curseforge.com/minecraft/mc-mods/fabric-api). + +When downloading mods, ensure that: + +- They work on the version of Minecraft you want to play on. A mod that works on version 1.20, for example, might not work on version 1.20.2. +- They are for Fabric and not another mod loader. +- Furthermore, they are for the correct edition of Minecraft (Java Edition). + +## 2. Move the Mod to the `mods` Folder {#2-move-the-mod-to-the-mods-folder} + +The mods folder can be found in the following locations for each operating system. + +You can usually paste these paths into the address bar of your file explorer to quickly navigate to the folder. + +::: code-group + +```:no-line-numbers [Windows] +%appdata%\.minecraft\mods +``` + +```:no-line-numbers [macOS] +~/Library/Application Support/minecraft/mods +``` + +```:no-line-numbers [Linux] +~/.minecraft/mods +``` + +::: + +Once you've found the `mods` folder, you can move the mod `.jar` files into it. + +![Installed mods in the mods folder](/assets/players/installing-mods.png) + +## 3. You're Done! {#3-you-re-done} + +Once you've moved the mods into the `mods` folder, you can open the Minecraft Launcher and select the Fabric profile from the dropdown in the bottom left corner and press play! + +![Minecraft Launcher with Fabric profile selected](/assets/players/installing-fabric/launcher-screen.png) + +## Troubleshooting {#troubleshooting} + +If you encounter any issues whilst following this guide, you can ask for help in the [Fabric Discord](https://discord.gg/v6v4pMv) in the `#player-support` channel. + +You can also attempt to troubleshoot the issue yourself by reading the troubleshooting pages: + +- [Crash Reports](./troubleshooting/crash-reports) +- [Uploading Logs](./troubleshooting/uploading-logs) diff --git a/versions/1.20.4/players/troubleshooting/crash-reports.md b/versions/1.20.4/players/troubleshooting/crash-reports.md new file mode 100644 index 000000000..c5c4a7986 --- /dev/null +++ b/versions/1.20.4/players/troubleshooting/crash-reports.md @@ -0,0 +1,104 @@ +--- +title: Crash Reports +description: Learn what to do with crash reports, and how to read them. +authors: + - IMB11 +--- + +# Crash Reports {#crash-reports} + +::: tip +If you're having any difficulty with finding the cause of the crash, you can ask for help in the [Fabric Discord](https://discord.gg/v6v4pMv) in the `#player-support` or `#server-admin-support` channel. +::: + +Crash reports are a very important part of troubleshooting issues with your game or server. They contain a lot of information about the crash, and can help you find the cause of the crash. + +## Finding Crash Reports {#finding-crash-reports} + +Crash reports are stored in the `crash-reports` folder in your game directory. If you are using a server, they are stored in the `crash-reports` folder in the server directory. + +For third party launchers, you should refer to their documentation on where to find crash reports. + +Crash reports can be found in the following locations: + +::: code-group + +```:no-line-numbers [Windows] +%appdata%\.minecraft\crash-reports +``` + +```:no-line-numbers [macOS] +~/Library/Application Support/minecraft/crash-reports +``` + +```:no-line-numbers [Linux] +~/.minecraft/crash-reports +``` + +::: + +## Reading Crash Reports {#reading-crash-reports} + +Crash reports are very long, and can be very confusing to read. However, they contain a lot of information about the crash, and can help you find the cause of the crash. + +For this guide, we will be using [this crash report](/public/assets/players/crash-report-example.txt). + +::: details Show Crash Report + +<<< @/public/assets/players/crash-report-example.txt{log} + +::: + +### Crash Report Sections {#crash-report-sections} + +Crash reports consist of several sections, each separated using a header: + +- `---- Minecraft Crash Report ----`, the summary of the report. This section will contain the main error that caused the crash, the time it occurred, and the relevant stack trace. This is the most important section of the crash report as the stack trace can usually contain references to the mod that caused the crash. +- `-- Last Reload --`, this section isn't really useful unless the crash occurred during a resource reload (F3 T). This section will contain the time of the last reload, and the relevant stack trace of any errors that occurred during the reload process. These errors are usually caused by resource packs, and can be ignored unless they are causing issues with the game. +- `-- System Details --`, this section contains information about your system, such as the operating system, Java version, and the amount of memory allocated to the game. This section is useful for determining if you are using the correct version of Java, and if you have allocated enough memory to the game. + - In this section, Fabric will have included a custom line that says `Fabric Mods:`, followed by a list of all the mods you have installed. This section is useful for determining if any conflicts could have occurred between mods. + +### Breaking Down the Crash Report {#breaking-down-the-crash-report} + +Now that we know what each section of the crash report is, we can start to break down the crash report and find the cause of the crash. + +Using the example linked above, we can analyze the crash report and find the cause of the crash, including the mods that caused the crash. + +The stack trace in the `---- Minecraft Crash Report ----` section is the most important in this case, as it contains the main error that caused the crash. In this case, the error is `java.lang.NullPointerException: Cannot invoke "net.minecraft.class_2248.method_9539()" because "net.minecraft.class_2248.field_10540" is null`. + +With the amount of mods mentioned in the stack trace, it can be difficult to point fingers, but the first thing to do is to look for the mod that caused the crash. + + +<<< @/public/assets/players/crash-report-example.txt{8-9,14-15 log} + +In this case, the mod that caused the crash is `snownee`, as it is the first mod mentioned in the stack trace. + +However, with the amount of mods mentioned, it could mean there are some compatibility issues between the mods, and the mod that caused the crash may not be the mod that is at fault. In this case, it is best to report the crash to the mod author, and let them investigate the crash. + +## Mixin Crashes {#mixin-crashes} + +::: info +Mixins are a way for mods to modify the game without having to modify the game's source code. They are used by many mods, and are a very powerful tool for mod developers. +::: + +When a mixin crashes, it will usually mention the mixin in the stack trace, and the class that the mixin is modifying. + +Method mixins will contain `modid$handlerName` in the stack trace, where `modid` is the mod's ID, and `handlerName` is the name of the mixin handler. + +```:no-line-numbers +... net.minecraft.class_2248.method_3821$$$modid$handlerName() ... // [!code focus] +``` + +You can use this information to find the mod that caused the crash, and report the crash to the mod author. + +## What to Do with Crash Reports {#what-to-do-with-crash-reports} + +The best thing to do with crash reports is to upload them to a paste site, and then share the link with the mod author, either on their issue trackers or through some form of communication (Discord etc.). + +This will allow the mod author to investigate the crash, potentially reproduce it, and solve the problem that caused it. + +Common paste sites that are used frequently for crash reports are: + +- [GitHub Gist](https://gist.github.com/) +- [mclo.gs](https://mclo.gs/) +- [Pastebin](https://pastebin.com/) diff --git a/versions/1.20.4/players/troubleshooting/uploading-logs.md b/versions/1.20.4/players/troubleshooting/uploading-logs.md new file mode 100644 index 000000000..a9a4b0d96 --- /dev/null +++ b/versions/1.20.4/players/troubleshooting/uploading-logs.md @@ -0,0 +1,54 @@ +--- +title: Uploading Logs +description: How to upload logs for troubleshooting. +authors: + - IMB11 +--- + +# Uploading Logs {#uploading-logs} + +When troubleshooting issues, it is often necessary to provide logs to help identify the cause of the issue. + +## Why Should I Upload Logs? {#why-should-i-upload-logs} + +Uploading logs allows others to help you troubleshoot your issues much quicker than simply pasting the logs into a chat or forum post. It also allows you to share your logs with others without having to copy and paste them. + +Some paste sites also provide syntax highlighting for logs, which makes them easier to read, and may censor sensitive information, such as your username, or system information. + +## Crash Reports {#crash-reports} + +Crash reports are automatically generated when the game crashes. They only contain crash information and not the actual logs of the game. They are located in the `crash-reports` folder in the game directory. + +For more information on crash reports, see [Crash Reports](./crash-reports). + +## Locating Logs {#locating-logs} + +This guide covers the official Minecraft Launcher (commonly referred to as the "vanilla launcher") - for third party launchers, you should consult their documentation. + +Logs are located in the `logs` folder in the game directory, the game directory can be found in the following locations depending on your operating system: + +::: code-group + +```:no-line-numbers [Windows] +%appdata%\.minecraft +``` + +```:no-line-numbers [macOS] +~/Library/Application Support/minecraft +``` + +```:no-line-numbers [Linux] +~/.minecraft +``` + +::: + +The latest log is called `latest.log`, and previous logs use the naming pattern `yyyy-mm-dd_number.log.gz`. + +## Uploading Logs Online {#uploading-logs-online} + +Logs can be uploaded to a variety of services, such as: + +- [Pastebin](https://pastebin.com/) +- [GitHub Gist](https://gist.github.com/) +- [mclo.gs](https://mclo.gs/) diff --git a/versions/1.20.4/players/updating-fabric.md b/versions/1.20.4/players/updating-fabric.md new file mode 100644 index 000000000..b8a7baad3 --- /dev/null +++ b/versions/1.20.4/players/updating-fabric.md @@ -0,0 +1,42 @@ +--- +title: Updating Fabric +description: A step by step guide on how to update Fabric. +authors: + - IMB11 + - modmuss50 +--- + +# Updating Fabric {#updating-fabric} + +This guide will walk you through updating Fabric for the Minecraft Launcher. + +For third party launchers, you should consult their documentation. + +Updating Fabric is a very similar process to installing Fabric, so parts of this guide will be the same as the [Installing Fabric](./installing-fabric) guide. + +## Why Should I Update Fabric Loader? {#why-should-i-update-fabric-loader} + +Newer mods may require a newer version of Fabric Loader to work, so it's important to keep it up to date to ensure you can use the latest mods. + + + + +To update Fabric, simply ensure the game version and Loader version is correct then click `Install`. + +::: important +Make sure to uncheck 'Create Profile' when running the installer, otherwise it will create a new profile, which in this case we don't need. +::: + +## 3. Open the Profile in the Minecraft Launcher {#3-open-the-profile-in-the-minecraft-launcher} + +Once the installer has finished, you can open the Minecraft Launcher and go to the `Installations` tab. You should go to your Fabric profile and open the edit screen. + +Replace the version with the new version of Fabric Loader you just installed, and press `Save`. + +![Updating Fabric Loader version in the Minecraft Launcher](/assets/players/updating-fabric.png) + +## 4. You're Done! {#4-you-re-done} + +Once you've completed the steps you can go back to the `Play` tab, select the Fabric profile from the dropdown in the bottom left corner and press play! + +If you encounter any issues whilst following this guide, you can ask for help in the [Fabric Discord](https://discord.gg/v6v4pMv) in the `#player-support` channel. diff --git a/versions/1.20.4/translated/.gitkeep b/versions/1.20.4/translated/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/versions/1.20.4/translated/cs_cz/index.md b/versions/1.20.4/translated/cs_cz/index.md new file mode 100644 index 000000000..8e6190e54 --- /dev/null +++ b/versions/1.20.4/translated/cs_cz/index.md @@ -0,0 +1,27 @@ +--- +title: Fabric Dokumentace +description: Oficiální dokumentace pro Fabric, modovací toolchain pro Minecraft. +layout: home +hero: + name: Fabric Dokumentace + tagline: Oficiální dokumentace pro Fabric, modovací toolchain pro Minecraft. +features: + - title: Developer Guides + icon: 🛠️ + details: Our curated developer guides, written by the community, span a wide range of topics from setting up a development environment to more advanced topics, such as rendering and networking. + link: ./develop/index + linkText: Začít + - title: Hráčské Návody + icon: 📚 + details: Jste hráč snícím o používání Fabric modů? Naše hráčské návody vám mohou pomoct. Tyto návody pomůžou se stahování, instalací a spravení Fabric modů. + link: ./players/index + linkText: Zjistit více +--- + +
+ +## Chcete nám pomoct? + +If you want to contribute to the Fabric Documentation, you can find the source code on [GitHub](https://github.com/FabricMC/fabric-docs), and the relevant [contribution guidelines](./contributing). + +
diff --git a/versions/1.20.4/translated/cs_cz/players/faq.md b/versions/1.20.4/translated/cs_cz/players/faq.md new file mode 100644 index 000000000..ddb72b601 --- /dev/null +++ b/versions/1.20.4/translated/cs_cz/players/faq.md @@ -0,0 +1,31 @@ +--- +title: Často kladené otázky hráčů +description: Často kladené otázky hráčů a administrátorů ohledně Fabricu. +--- + +# Často kladené dotazy + +Je hodně otázek, které jsou často kladeny, proto jsme je shromáždili sem do listu. + +## Všeobecné otázky + +### Jaké verze Minecraftu Fabric podporuje? + +Fabric oficiálně podporuje všechny verze hry od snapshotu `18w34b`, a vydání `1.14`. + +### Kam mohu nahrát módy vytvořené přes Fabric? + +:::info +Vždy byste měli zkontrolovat, zda jsou módy z důvěryhodného zdroje. Podívejte se na [Hledání důvěryhodných módů](./finding-mods) pro více informací. +::: + +Většina autorů módů publikuje své módy na [Modrinth](https://modrinth.com/mods?g=categories:%27fabric%27) a [CurseForge](https://www.curseforge.com/minecraft/search?page=1&pageSize=20&sortType=1&class=mc-mods&gameFlavorsIds=4), avšak někteří mohou preferovat nahrávání na své stránky nebo na GitHub. + +### Kde mohu nalézt předvytvořené Fabric modpacky? + +Můžete je nalézt na vícero platformách, např: + +- [Modrinth](https://modrinth.com/modpacks?g=categories:%27fabric%27) +- [CurseForge](https://www.curseforge.com/minecraft/search?page=1&pageSize=20&sortType=1&class=modpacks&gameFlavorsIds=4) +- [Feed The Beast](https://www.feed-the-beast.com/ftb-app) +- [Technic](https://www.technicpack.net/modpacks) diff --git a/versions/1.20.4/translated/de_de/contributing.md b/versions/1.20.4/translated/de_de/contributing.md new file mode 100644 index 000000000..6091b2306 --- /dev/null +++ b/versions/1.20.4/translated/de_de/contributing.md @@ -0,0 +1,181 @@ +# Richtlinien zur Beitragserstellung für die Fabric-Dokumentation + +Diese Website nutzt [VitePress](https://vitepress.dev/) um statisches HTML von den verschiedenen Markdown-Dateien zu generrieren. Du solltest dich mit den Markdown-Erweiterungen vertraut machen, die VitePress [hier](https://vitepress.dev/guide/markdown#features) unterstützt. + +## Inhaltsverzeichnis + +- [Richtlinien zur Beitragserstellung für die Fabric-Dokumentation](#fabric-documentation-contribution-guidelines) + - [Wie man beiträgt](#how-to-contribute) + - [Zum Framework beitragen](#contributing-framework) + - [Inhalte beitragen](#contributing-content) + - [Stilrichtlinien](#style-guidelines) + - [Anleitung zur Erweiterung](#guidance-for-expansion) + - [Überprüfung des Inhalts](#content-verification) + - [Aufräumen](#cleanup) + - [Übersetzen der Dokumentation](#translating-documentation) + +## Wie man beiträgt + +Es wird empfohlen, dass du für jeden Pull-Request ein neues Branch in deinem Fork des Repositorys erstellst. Das macht es einfacher, mehrere Pull-Requests gleichzeitig zu verwalten. + +**Wenn du deine Änderungen lokal ansehen möchtest, musst du [Node.js 18+](https://nodejs.org/en/) installieren.** + +Bevor du einen dieser Befehle ausführst, solltest du `npm install` ausführen, um alle Abhängigkeiten zu installieren. + +**Ausführung des Entwicklungsservers:** + +Damit kannst du deine Änderungen lokal auf `localhost:3000` ansehen und die Seite wird automatisch neu geladen, wenn du Änderungen vornimmst. + +```sh +npm run dev +``` + +**Erstellung der Website:** + +Dies wird alle Markdown-Dateien in statische HTML-Dateien kompilieren und diese in `.vitepress/dist` ablegen + +```sh +npm run build +``` + +**Vorschau auf die erstellte Website:** + +Dies wird einen lokalen Server auf Port 3000 starten, der den Inhalt in `.vitepress/dist` bereitstellt. + +```sh +npm run preview +``` + +## Zum Framework beitragen + +Alle Pull-Requests, die das Framework der Website verändern, sollten mit dem Label `framework` gekennzeichnet werden. + +Du solltest wirklich nur Pull-Requests für das Framework eröffnen, nachdem du dich mit dem Dokumentationsteam im [Fabric Discord](https://discord.gg/v6v4pMv) oder über ein Issue beraten hast. + +**Hinweis: Das Ändern von Seitenleistendateien und der Konfiguration der Navigationsleiste zählt nicht als Pull-Request für das Framework.** + +## Inhalte beitragen + +Inhaltliche Beiträge sind die wichtigste Möglichkeit, zur Fabric-Dokumentation beizutragen. + +Alle Inhalte sollten unseren Stilrichtlinien entsprechen. + +### Stilrichtlinien + +Alle Seiten auf der Website der Fabric-Dokumentation sollten den Stilrichtlinien entsprechen. Wenn du unsicher bist, kannst du im [Fabric Discord](https://discord.gg/v6v4pMv) oder über GitHub Diskussionen nachfragen. + +Die Stilrichtlinien lauten wie folgt: + +1. Alle Seiten müssen einen Titel und eine Beschreibung im Frontmatter haben. + + ```md + --- + title: Dies ist der Titel der Seite + description: Dies ist die Beschreibung der Seite + authors: + - GitHubUsernameHier + --- + + # ... + ``` + +2. Wenn du Seiten erstellst oder änderst, die Code enthalten, platziere den Code an einer geeigneten Stelle innerhalb des Referenz-Mod (im Ordner `/reference` des Repository). Verwende dann die [Code-Snippet-Funktion, die von VitePress angeboten wird](https://vitepress.dev/guide/markdown#import-code-snippets), um den Code einzubetten, oder wenn du eine größere Kontrollspanne benötigst, kannst du die [transclude-Funktion von `markdown-it-vuepress-code-snippet-enhanced`](https://github.com/fabioaanthony/markdown-it-vuepress-code-snippet-enhanced) verwenden. + + **Beispiel:** + + ```md + <<< @/reference/latest/src/main/java/com/example/docs/FabricDocsReference.java{15-21 java} + ``` + + Dies wird die Zeilen 15-21 der Datei `FabricDocsReference.java` des Referenz-Mod einbetten. + + Der resultierende Codeschnipsel sieht wie folgt aus: + + ```java + @Override + public void onInitialize() { + // This code runs as soon as Minecraft is in a mod-load-ready state. + // However, some things (like resources) may still be uninitialized. + // Proceed with mild caution. + + LOGGER.info("Hello Fabric world!"); + } + ``` + + **Transclude-Beispiel:** + + ```md + @[code transcludeWith=#test_transclude](@/reference/.../blah.java) + ``` + + Dies wird die Abschnitte von `blah.java` eingebetten, die mit dem Tag `#test_transclude` markiert sind. + + Zum Beispiel: + + ```java + public final String test = "Bye World!" + + // #test_transclude + public void test() { + System.out.println("Hello World!"); + } + // #test_transclude + ``` + + Nur der Code zwischen den `#test_transclude`-Tags wird eingebettet. + + ```java + public void test() { + System.out.println("Hello World!"); + } + ``` + +3. Die ganze originale Dokumentation ist in englischer Sprache verfasst und folgt den amerikanischen Grammatikregeln. Du kannst zwar [LanguageTool](https://languagetool.org/) verwenden, um deine Grammatik während der Eingabe zu überprüfen, aber mache dir nicht zu viele Gedanken darüber. Unser Dokumentationsteam überprüft und korrigiert die Grammatik während der Bereinigungsphase. Wenn man sich jedoch von Anfang an bemüht, es richtig zu machen, können wir Zeit sparen. + +4. Wenn du einen neuen Abschnitt erstellst, solltest du eine neue Seitenleiste im Ordner `.vitepress/sidebars` anlegen und sie zur Datei `config.mts` hinzufügen. Wenn du dabei Hilfe benötigst, frage bitte auf dem [Fabric Discord](https://discord.gg/v6v4pMv) im Kanal `#docs` nach. + +5. Wenn du eine neue Seite erstellst, solltest du sie der entsprechenden Seitenleiste im Ordner `.vitepress/sidebars` hinzufügen. Auch hier gilt: Wenn du Hilfe benötigst, frage auf dem Fabric Discord im Kanal `#docs` nach. + +6. Alle Bilder sollten an einem geeigneten Ort im Ordner `/assets` abgelegt werden. + +7. ⚠️ **Wenn du andere Seiten verlinkst, verwende relative Links.** ⚠️ + + Der Grund dafür ist das vorhandene Versionssystem, das die Links verarbeitet, um die Version vorher hinzuzufügen. Wenn du absolute Links verwendest, wird die Versionsnummer nicht zum Link hinzugefügt. + + Um z. B. eine Seite im Ordner `/players` mit der Seite `installing-fabric` aus `/players/installing-fabric.md` zu verknüpfen, musst du Folgendes tun: + + ```md + [Dies ist ein Link zu einer anderen Seite](./installing-fabric) + ``` + + Du solltest **NICHT** Folgendes tun: + + ```md + [Dies ist ein Link zu einer anderen Seite](/players/installing-fabric) + ``` + +Alle inhaltlichen Beiträge durchlaufen drei Stufen: + +1. Anleitung für Erweiterung (falls möglich) +2. Überprüfung des Inhalts +3. Bereinigung (Grammatik etc.) + +### Anleitung zur Erweiterung + +Wenn das Dokumentationsteam der Meinung ist, dass du deinen Pull Request erweitern könntest, wird ein Mitglied des Teams den Vermerk `can-expand` zu deinem Pull Request hinzufügen, zusammen mit einem Kommentar, der erklärt, was du ihrer Meinung nach erweitern könntest. Wenn du mit dem Vorschlag einverstanden bist, kannst du deinen Pull-Request erweitern. + +**Fühl dich nicht unter Druck gesetzt, deine Anfrage zu erweitern** Wenn du deine Anfrage nicht erweitern möchtest, kannst du einfach darum bitten, dass die Kennzeichnung `can-expand` entfernt wird. + +Wenn du deinen Pull-Request nicht erweitern willst, aber gerne möchtest, dass jemand anderes ihn zu einem späteren Zeitpunkt erweitert, ist es am besten, ein Issue auf der [Issues-Seite](https://github.com/FabricMC/fabric-docs/issues) zu erstellen und zu erklären, was deiner Meinung nach erweitert werden könnte. + +### Überprüfung des Inhalts + +Dies ist die wichtigste Phase, da sie sicherstellt, dass der Inhalt korrekt ist und den Fabric Stilrichtlinien der Dokumentation entspricht. + +### Aufräumen + +In dieser Phase behebt das Dokumentationsteam Grammatikfehler und nimmt andere Änderungen vor, die es für notwendig hält, bevor es den Pull-Request mergt! + +## Übersetzen der Dokumentation + +Falls du die Dokumentation in deine Sprache übersetzen möchtest, kannst du dies auf der [Fabric Crowdin-Seite](https://crowdin.com/project/fabricmc) tun. diff --git a/versions/1.20.4/translated/de_de/develop/codecs.md b/versions/1.20.4/translated/de_de/develop/codecs.md new file mode 100644 index 000000000..95e2dc23d --- /dev/null +++ b/versions/1.20.4/translated/de_de/develop/codecs.md @@ -0,0 +1,399 @@ +--- +title: Codecs +description: Ein umfassender Leitfaden zum Verständnis und zur Verwendung von Mojangs Codec-System zum Serialisieren und Deserialisieren von Objekten. +authors: + - enjarai + - Syst3ms +--- + +# Codecs + +Ein Codec ist ein System zur einfachen Serialisierung von Java-Objekten und ist in Mojangs DataFixerUpper (DFU) +Bibliothek enthalten, die in Minecraft enthalten ist. In einem Modding-Kontext können sie als Alternative zu GSON und Jankson verwendet werden, wenn man benutzerdefinierte JSON-Dateien liest und schreibt, wobei sie mehr und mehr an Bedeutung gewinnen, da Mojang eine Menge alten Code umschreibt, um Codecs zu verwenden. + +Codecs werden in Verbindung mit einer anderen API von DFU, `DynamicOps`, verwendet. Ein Codec definiert die Struktur eines Objekts, während dynamische Ops verwendet werden, um ein Format zu definieren, in das und aus dem serialisiert werden soll, zum Beispiel JSON oder NBT. Das bedeutet, dass jeder Codec mit allen dynamischen Ops verwendet werden kann und umgekehrt, was eine große Flexibilität ermöglicht. + +## Verwenden von Codecs + +### Serialisierung und Deserialisierung + +Die grundlegende Verwendung eines Codecs ist die Serialisierung und Deserialisierung von Objekten in und aus einem bestimmten Format. + +Da einige Vanilla-Klassen bereits Codecs definiert haben, können wir diese als Beispiel verwenden. Mojang hat uns außerdem standardmäßig zwei dynamische Ops-Klassen zur Verfügung gestellt, `JsonOps` und `NbtOps`, die die meisten Anwendungsfälle abdecken. + +Nehmen wir nun an, wir wollen eine `BlockPos` nach JSON und zurück serialisieren. Wir können dies machen, indem wir den Codec, der statisch in `BlockPos.CODEC` gespeichert ist, mit den Methoden `Codec#encodeStart` bzw. + +```java +BlockPos pos = new BlockPos(1, 2, 3); + +// Serialisieren der BlockPos zu einem JsonElement +DataResult result = BlockPos.CODEC.encodeStart(JsonOps.INSTANCE, pos); +``` + +Bei Verwendung eines Codecs werden die Werte in Form eines `DataResult` zurückgegeben. Dies ist ein Wrapper, der entweder einen Erfolg oder einen Misserfolg darstellen kann. Wir können dies auf verschiedene Weise nutzen: Wenn wir nur unseren serialisierten Wert haben wollen, gibt `DataResult#result` einfach ein `Optional` zurück, das unseren Wert enthält, während `DataResult#resultOrPartial` uns auch die Möglichkeit gibt, eine Funktion zu liefern, die eventuell aufgetretene Fehler behandelt. Letzteres ist besonders nützlich für benutzerdefinierte Datapack-Ressourcen, bei denen wir Fehler protokollieren wollen, ohne dass sie an anderer Stelle Probleme verursachen. + +Nehmen wir also unseren serialisierten Wert und verwandeln ihn zurück in eine `BlockPos`: + +```java +// Wenn du einen Mod schreibst, musst du natürlich mit leeren Optionals richtig umgehen +JsonElement json = result.resultOrPartial(LOGGER::error).orElseThrow(); + +// Hier haben wir unseren JSON-Wert, der `[1, 2, 3]` entsprechen sollte, +// da dies das vom BlockPos-Codec verwendete Format ist. +LOGGER.info("Serialized BlockPos: {}", json); + +// Jetzt werden wir wir das JsonElement zurück in eine BlockPos deserialisieren +DataResult result = BlockPos.CODEC.parse(JsonOps.INSTANCE, json); + +// Auch hier holen wir uns den Wert einfach aus dem Ergebnis +BlockPos pos = result.resultOrPartial(LOGGER::error).orElseThrow(); + +// Und wir können sehen, dass wir unsere BlockPos erfolgreich serialisiert und deserialisiert haben! +LOGGER.info("Deserialized BlockPos: {}", pos); +``` + +### Eingebaute Codecs + +Wie bereits erwähnt, hat Mojang bereits Codecs für mehrere Vanilla- und Standard-Java-Klassen definiert, einschließlich, aber nicht beschränkt auf `BlockPos`, `BlockState`, `ItemStack`, `Identifier`, `Text` und Regex `Pattern`. Codecs für Mojangs eigene Klassen sind normalerweise als statische Attribute mit dem Namen `CODEC` in der Klasse selbst zu finden, während die meisten anderen in der Klasse `Codecs` untergebracht sind. Es sollte auch beachtet werden, dass alle Vanilla-Registries eine `getCodec()`-Methode enthalten, zum Beispiel kann man `Registries.BLOCK.getCodec()` verwenden, um einen `Codec` zu erhalten, der in die Block-ID und zurück serialisiert wird. + +Die Codec API selbst enthält auch einige Codecs für primitive Typen wie `Codec.INT` und `Codec.STRING`. Diese sind als statische Attribute der Klasse "Codec" verfügbar und werden in der Regel als Basis für komplexere Codecs verwendet, wie im Folgenden erläutert. + +## Erstellen von Codecs + +Nachdem wir nun gesehen haben, wie man Codecs verwendet, wollen wir uns ansehen, wie wir unsere eigenen erstellen können. Angenommen, wir haben die folgende Klasse und wollen Instanzen davon aus JSON-Dateien deserialisieren: + +```java +public class CoolBeansClass { + + private final int beansAmount; + private final Item beanType; + private final List beanPositions; + + public CoolBeansClass(int beansAmount, Item beanType, List beanPositions) {...} + + public int getBeansAmount() { return this.beansAmount; } + public Item getBeanType() { return this.beanType; } + public List getBeanPositions() { return this.beanPositions; } +} +``` + +Die entsprechende JSON-Datei könnte etwa so aussehen: + +```json +{ + "beans_amount": 5, + "bean_type": "beanmod:mythical_beans", + "bean_positions": [ + [1, 2, 3], + [4, 5, 6] + ] +} +``` + +Wir können einen Codec für diese Klasse erstellen, indem wir mehrere kleinere Codecs zu einem größeren zusammenfügen. In diesem Fall brauchen wir einen für jedes Feld: + +- ein `Codec` +- ein `Codec` +- ein `Codec>` + +Den ersten können wir aus den oben erwähnten primitiven Codecs in der Klasse `Codec` beziehen, insbesondere aus `Codec.INT`. Der zweite kann aus dem Register `Registries.ITEM` bezogen werden, das eine Methode `getCodec()` hat, die einen `Codec` zurückgibt. Wir haben keinen Standard-Codec für `List`, aber wir können einen aus `BlockPos.CODEC` erstellen. + +### Listen + +`Codec#listOf` kann verwendet werden, um eine Listenversion eines beliebigen Codecs zu erstellen: + +```java +Codec> listCodec = BlockPos.CODEC.listOf(); +``` + +Es sollte beachtet werden, dass Codecs, die auf diese Weise erstellt werden, immer in eine `ImmutableList` deserialisiert werden. Wenn du stattdessen eine veränderbare Liste benötigst, kannst du [xmap](#wechselseitig-konvertierbare-typen) verwenden, um sie während der Deserialisierung in eine solche zu konvertieren. + +### Zusammenführung von Codecs für Record-ähnliche Klassen + +Da wir nun für jedes Feld einen eigenen Codec haben, können wir sie mit einem `RecordCodecBuilder` zu einem Codec für unsere Klasse kombinieren. Dies setzt voraus, dass unsere Klasse einen Konstruktor hat, der jedes Feld enthält, das wir serialisieren wollen, und dass jedes Feld eine entsprechende Getter-Methode hat. Dies macht es perfekt für die Verwendung in Verbindung mit Records, aber es kann auch mit normalen Klassen verwendet werden. + +Schauen wir uns an, wie wir einen Codec für unsere `CoolBeansClass` erstellen können: + +```java +public static final Codec CODEC = RecordCodecBuilder.create(instance -> instance.group( + Codec.INT.fieldOf("beans_amount").forGetter(CoolBeansClass::getBeansAmount), + Registries.ITEM.getCodec().fieldOf("bean_type").forGetter(CoolBeansClass::getBeanType), + BlockPos.CODEC.listOf().fieldOf("bean_positions").forGetter(CoolBeansClass::getBeanPositions) + // Hier können bis zu 16 Attribute deklariert werden +).apply(instance, CoolBeansClass::new)); +``` + +Jede Zeile in der Gruppe gibt einen Codec, einen Attributname und eine Getter-Methode an. Der Aufruf `Codec#fieldOf` wird verwendet, um den Codec in einen [MapCodec](#mapcodec) zu konvertieren, und der Aufruf `forGetter` spezifiziert die Getter-Methode, die verwendet wird, um den Wert des Attributs von einer Instanz der Klasse abzurufen. In der Zwischenzeit gibt der Aufruf `apply` den Konstruktor an, der zur Erzeugung neuer Instanzen verwendet wird. Beachte, dass die Reihenfolge der Attribute in der Gruppe dieselbe sein sollte wie die Reihenfolge der Argumente im Konstruktor. + +Du kannst auch `Codec#optionalFieldOf` in diesem Zusammenhang verwenden, um ein Feld optional zu machen, wie in dem Abschnitt [Optionale Attribute](#optionale-attribute) erklärt. + +### MapCodec, nicht zu verwechseln mit Codec<Map> {#mapcodec} + +Der Aufruf von `Codec#fieldOf` wird einen `Codec` in einen `MapCodec` umwandeln, der eine Variante, aber keine direkte Implementierung von `Codec` ist. `MapCodec`s werden, wie ihr Name schon sagt, garantiert in eine Schlüssel-zu-Wert-Map oder deren Äquivalent in den verwendeten `DynamicOps` serialisiert. Einige Funktionen können einen solchen Codec über einen normalen Codec erfordern. + +Diese besondere Art der Erstellung eines `MapCodec` verpackt im Wesentlichen den Wert des Quellcodecs in eine Map ein, wobei der angegebene Attributname als Schlüssel dient. Zum Beispiel würde ein `Codec`, wenn er in JSON serialisiert wird, wie folgt aussehen: + +```json +[1, 2, 3] +``` + +Bei der Umwandlung in einen `MapCodec` unter Verwendung von `BlockPos.CODEC.fieldOf("pos")` würde es jedoch wie folgt aussehen: + +```json +{ + "pos": [1, 2, 3] +} +``` + +Während die gebräuchlichste Verwendung für Map-Codecs darin besteht, mit anderen Map-Codecs zusammengeführt zu werden, um einen Codec für eine ganze Klasse von Felder zu konstruieren, wie im Abschnitt [Zusammenführung von Codecs für Record-ähnliche Klassen](#Zusammenführung-von-Codecs-für-Record-ähnliche-Klassen) oben erklärt wurde, können sie auch mit `MapCodec#codec` in reguläre Codecs zurückverwandelt werden, die das gleiche Verhalten beibehalten, nämlich ihren Eingabewert verpacken. + +#### Optionale Attribute + +`Codec#optionalFieldOf` kann verwendet werden, um einen optionalen Mapcodec zu erstellen. Wenn das angegebene Feld bei der Deserialisierung nicht im Container vorhanden ist, wird es entweder als leeres `Optional` oder als angegebener Standardwert deserialisiert. + +```java +// Ohne einem Standardwert +MapCodec> optionalCodec = BlockPos.CODEC.optionalFieldOf("pos"); + +// Mit einem Standardwert +MapCodec optionalCodec = BlockPos.CODEC.optionalFieldOf("pos", BlockPos.ORIGIN); +``` + +Beachte, dass optionale Felder alle Fehler, die bei der Deserialisierung auftreten können, ignorieren. Das heißt, wenn das Feld vorhanden ist, aber der Wert ungültig ist, wird das Feld immer als Standardwert deserialisiert. + +**Seit 1.20.2**, Minecraft selbst (nicht DFU!) bietet jedoch `Codecs#createStrictOptionalFieldCodec`, das die Deserialisierung fehlschlägt, wenn der Feldwert ungültig ist. + +### Konstanten, Beschränkungen und Komposition + +#### Einheit + +`Codec.unit` kann verwendet werden, um einen Codec zu erstellen, der immer zu einem konstanten Wert deserialisiert, unabhängig von der Eingabe. Bei der Serialisierung wird nichts getan. + +```java +Codec theMeaningOfCodec = Codec.unit(42); +``` + +#### Zahlenbereiche + +`Codec.intRange` und seine Kollegen `Codec.floatRange` und `Codec.doubleRange` können verwendet werden, um einen Codec zu erstellen, der nur Zahlenwerte innerhalb eines bestimmten **inklusiven** Bereichs akzeptiert. Dies gilt sowohl für die Serialisierung als auch für die Deserialisierung. + +```java +// Kann nicht mehr als 2 sein +Codec amountOfFriendsYouHave = Codec.intRange(0, 2); +``` + +#### Paar + +`Codec.pair` fasst zwei Codecs, `Codec
` und `Codec`, zu einem `Codec` zusammen. Denk daran, dass dies nur richtig mit Codecs funktioniert, die in ein bestimmtes Attribut serialisiert werden, wie zum Beispiel [konvertierte `MapCodec`s](#mapcodec) oder [Record Codecs](#Zusammenführung-von-Codecs-für-Record-ähnliche-Klassen). +Der resultierende Codec wird zu einer Map serialisiert, die die Attribute der beiden verwendeten Codecs kombiniert. + +Beispielsweise wird beim Ausführen dieses Codes: + +```java +// Erstellen von zwei separaten verpackten Codecs +Codec firstCodec = Codec.INT.fieldOf("i_am_number").codec(); +Codec secondCodec = Codec.BOOL.fieldOf("this_statement_is_false").codec(); + +// Sie zu einem Paar-Codec zusammenführen +Codec> pairCodec = Codec.pair(firstCodec, secondCodec); + +// Zum Serialisieren von Daten verwenden +DataResult result = pairCodec.encodeStart(JsonOps.INSTANCE, Pair.of(23, true)); +``` + +Folgendes JSON generiert: + +```json +{ + "i_am_number": 23, + "this_statement_is_false": true +} +``` + +#### Entweder-Oder-Kombination + +`Codec.either` kombiniert zwei Codecs, `Codec` und `Codec`, zu einem `Codec>`. Der resultierende Codec wird bei der Deserialisierung versuchen, den ersten Codec zu verwenden, und _nur wenn das fehlschlägt_, versuchen, den zweiten Codec zu verwenden. +Wenn der zweite Codec ebenfalls fehlschlägt, wird der Fehler des _zweiten_ Codecs zurückgegeben. + +#### Maps + +Für die Verarbeitung von Maps mit beliebigen Schlüsseln, wie zum Beispiel `HashMap`s, kann `Codec.unboundedMap` verwendet werden. Dies gibt einen `Codec>` für einen gegebenen `Codec` und `Codec` zurück. Der resultierende Codec wird zu einem JSON-Objekt serialisiert oder oder ein gleichwertiges Objekt, das für die aktuellen dynamische Ops verfügbar ist. + +Aufgrund der Einschränkungen von JSON und NBT _muss_ der verwendete Schlüsselcodec zu einer Zeichenkette serialisiert werden. Dazu gehören auch Codecs für Typen, die selbst keine Strings sind, aber zu ihnen serialisiert werden, wie zum Beispiel `Identifier.CODEC`. Siehe folgendes Beispiel: + +```java +// Erstellen eines Codecs für eine Abbildung von Bezeichnern auf Ganzzahlen +Codec> mapCodec = Codec.unboundedMap(Identifier.CODEC, Codec.INT); + +// Zum Serialisieren von Daten verwenden +DataResult result = mapCodec.encodeStart(JsonOps.INSTANCE, Map.of( + new Identifier("example", "number"), 23, + new Identifier("example", "the_cooler_number"), 42 +)); +``` + +Dadurch wird dieses JSON ausgegeben: + +```json +{ + "example:number": 23, + "example:the_cooler_number": 42 +} +``` + +Wie du sehen kannst, funktioniert dies, weil `Identifier.CODEC` direkt zu einem String-Wert serialisiert wird. Einen ähnlichen Effekt kann man für einfache Objekte, die nicht in Strings serialisiert werden, erreichen, indem [Wechselseitig konvertierbare Typen](#wechselseitig-konvertierbare-typen) verwendet werden, um um sie zu konvertieren. + +### Wechselseitig konvertierbare Typen + +#### `xmap` + +Angenommen, wir haben zwei Klassen, die ineinander umgewandelt werden können, aber keine Eltern-Kind-Beziehung haben. Zum Beispiel, eine einfache `BlockPos` und `Vec3d`. Wenn wir einen Codec für eine Richtung haben, können wir mit `Codec#xmap` einen Codec für die andere Richtung erstellen, indem wir eine Konvertierungsfunktion für jede Richtung angeben. + +B`BlockPos` hat bereits einen Codec, aber tun wir mal so, als ob er keinen hätte. Wir können einen solchen Codec erstellen, indem wir ihn auf den Codec für `Vec3d` stützen, etwa so: + +```java +Codec blockPosCodec = Vec3d.CODEC.xmap( + // Konvertiert Vec3d zu BlockPos + vec -> new BlockPos(vec.x, vec.y, vec.z), + // Konvertiert BlockPos zu Vec3d + pos -> new Vec3d(pos.getX(), pos.getY(), pos.getZ()) +); + +// Bei der Konvertierung einer bestehenden Klasse (zum Beispiel `X`) +// in deine eigene Klasse (`Y`), kann es sinnvoll sein +// die Methode `toX` und die statische Methode `fromX` zu `Y` und +// Methodenreferenzen in deinem `xmap`-Aufruf hinzufügen. +``` + +#### flatComapMap, comapFlatMap und flatXMap + +`Codec#flatComapMap`, `Codec#comapFlatMap` und `flatXMap` sind ähnlich wie xmap, erlauben aber, dass eine oder beide der Konvertierungsfunktionen ein DataResult zurückgeben. Dies ist in der Praxis nützlich, da eine bestimmte Objektinstanz möglicherweise nicht nicht immer für die Konvertierung gültig ist. + +Nimm zum Beispiel Vanille `Identifier` her. Während alle Bezeichner in Zeichenketten umgewandelt werden können, sind nicht alle Zeichenketten gültige Bezeichner, Daher würde die Verwendung von xmap hässliche Exceptions werfen, wenn die Umwandlung fehlschlägt. +Aus diesem Grund ist der eingebaute Codec eigentlich eine `comapFlatMap` auf `Codec.STRING`, was sehr schön veranschaulicht, wie man ihn verwendet: + +```java +public class Identifier { + public static final Codec CODEC = Codec.STRING.comapFlatMap( + Identifier::validate, Identifier::toString + ); + + // ... + + public static DataResult validate(String id) { + try { + return DataResult.success(new Identifier(id)); + } catch (InvalidIdentifierException e) { + return DataResult.error("Not a valid resource location: " + id + " " + e.getMessage()); + } + } + + // ... +} +``` + +Diese Methoden sind zwar sehr hilfreich, aber ihre Namen sind etwas verwirrend, deshalb hier eine Tabelle, damit du merken kannst, welche zu verwenden ist: + +| Methode | A -> B immer gültig? | B -> A immer gültig? | +| ----------------------- | -------------------- | -------------------- | +| `Codec#xmap` | Ja | Ja | +| `Codec#comapFlatMap` | Nein | Ja | +| `Codec#flatComapMap` | Ja | Nein | +| `Codec#flatXMap` | Nein | Nein | + +### Registry Dispatch + +`Codec#dispatch` ermöglicht die Definition eines Registry von Codecs und die Abfertigung eines bestimmten Codecs auf der Grundlage des Wertes eines +Attributs in den serialisierten Daten. Dies ist sehr nützlich bei der Deserialisierung von Objekten, die je nach Typ unterschiedliche Attribute haben, aber dennoch dasselbe Objekt darstellen. + +Nehmen wir an, wir haben ein abstraktes `Bean`-Interface mit zwei implementierenden Klassen: `StringyBean` und `CountingBean`. Um diese mit einem Registry Dispatch zu serialisieren, benötigen wir einige Dinge: + +- Separate Codecs für jede Art von Bohnen. +- Eine `BeanType`-Klasse oder ein Datensatz, der den Typ der Bohne repräsentiert und den Codec für sie zurückgeben kann. +- Eine Funktion für `Bean` zum Abrufen ihres `BeanType`. +- Eine Map oder Registry, um `Identifier` auf `BeanType` abzubilden. +- Ein `Codec>`, der auf dieser Registry basiert. Wenn du eine `net.minecraft.registry.Registry` verwendest, kann eine solche einfach mit `Registry#getCodec` erstellt werden. + +Mit all dem können wir einen Registry Dispatch Codec für Bohnen erstellen: + +@[code transcludeWith=:::](@/reference/latest/src/main/java/com/example/docs/codec/Bean.java) +@[code transcludeWith=:::](@/reference/latest/src/main/java/com/example/docs/codec/BeanType.java) +@[code transcludeWith=:::](@/reference/latest/src/main/java/com/example/docs/codec/StringyBean.java) +@[code transcludeWith=:::](@/reference/latest/src/main/java/com/example/docs/codec/CountingBean.java) +@[code transcludeWith=:::](@/reference/latest/src/main/java/com/example/docs/codec/BeanTypes.java) + +```java +// Jetzt können wir einen Codec für Bohnentypen erstellen +// auf der Grundlage des zuvor erstellten Registry +Codec> beanTypeCodec = BeanType.REGISTRY.getCodec(); + +// Und darauf aufbauend, hier ist unser Registry Dispatch Codec für Bohnen! +// Das erste Argument ist der Argumentname für den Bohnen-Typ. +// Wenn du das Attribut weglässt, wird es standardmäßig auf "type" gesetzt. +Codec beanCodec = beanTypeCodec.dispatch("type", Bean::getType, BeanType::getCodec); +``` + +Unser neuer Codec serialisiert Bohnen zu JSON und erfasst dabei nur die Felder, die für ihren spezifischen Typ relevant sind: + +```json +{ + "type": "example:stringy_bean", + "stringy_string": "This bean is stringy!" +} +``` + +```json +{ + "type": "example:counting_bean", + "counting_number": 42 +} +``` + +### Rekursive Codecs + +Manchmal ist es nützlich, einen Codec zu haben, der _sich selbst_ verwendet, um bestimmte Felder zu dekodieren, zum Beispiel wenn es um bestimmte rekursive Datenstrukturen geht. Im Vanilla-Code wird dies für `Text`-Objekte verwendet, die andere `Text`e als Kinder speichern können. Ein solcher Codec kann mit `Codecs#createRecursive` erstellt werden. + +Versuchen wir zum Beispiel, eine einfach verknüpfte Liste zu serialisieren. Diese Art der Darstellung von Listen besteht aus einem Bündel von Knoten, die sowohl einen Wert als auch einen Verweis auf den nächsten Knoten in der Liste enthalten. Die Liste wird dann durch ihren ersten Knoten repräsentiert, und das Durchlaufen der Liste erfolgt durch Verfolgen des nächsten Knotens, bis keiner mehr übrig ist. Hier ist eine einfache Implementierung von Knoten, die ganze Zahlen speichern. + +```java +public record ListNode(int value, ListNode next) {} +``` + +Wir können dafür keinen Codec mit normalen Mitteln konstruieren, denn welchen Codec würden wir für das Attribut `next` verwenden? Wir bräuchten einen `Codec`, und den sind wir gerade dabei zu konstruieren! Mit `Codecs#createRecursive` können wir das mit einem magisch aussehenden Lambda erreichen: + +```java +Codec codec = Codecs.createRecursive( + "ListNode", // Ein Name für den Codec + selfCodec -> { + // Hier repräsentiert `selfCodec` den `Codec`, als ob er bereits konstruiert wäre + // Dieses Lambda sollte den Codec zurückgeben, den wir von Anfang an verwenden wollten, + // der sich durch `selfCodec` auf sich selbst bezieht + return RecordCodecBuilder.create(instance -> + instance.group( + Codec.INT.fieldOf("value").forGetter(ListNode::value), + // das Attribut `next` wird rekursiv mit dem eigenen Codec behandelt + Codecs.createStrictOptionalFieldCodec(selfCodec, "next", null).forGetter(ListNode::next) + ).apply(instance, ListNode::new) + ); + } +); +``` + +Ein serialisierter `ListNode` kann dann wie folgt aussehen: + +```json +{ + "value": 2, + "next": { + "value": 3, + "next" : { + "value": 5 + } + } +} +``` + +## Referenzen + +- Eine viel umfassendere Dokumentation von Codecs und verwandten APIs findest du in der [Inoffiziellen DFU JavaDoc](https://kvverti.github.io/Documented-DataFixerUpper/snapshot/com/mojang/serialization/Codec). +- Die allgemeine Struktur dieses Leitfadens wurde stark von dem [Forge Community Wiki's Seiten zu Codecs](https://forge.gemwire.uk/wiki/Codecs) inspiriert, einer eher Forge-spezifischen Darstellung desselben Themas. diff --git a/versions/1.20.4/translated/de_de/develop/commands/arguments.md b/versions/1.20.4/translated/de_de/develop/commands/arguments.md new file mode 100644 index 000000000..3c68e2b60 --- /dev/null +++ b/versions/1.20.4/translated/de_de/develop/commands/arguments.md @@ -0,0 +1,57 @@ +--- +title: Befehlsargumente +description: Lerne, wie man Befehle mit komplexen Parametern erstellt. +--- + +# Befehlsargumente + +Parameter werden in den meisten Befehlen verwendet. Manchmal sind sie optional, das heißt, wenn du diesen Parameter nicht angibst, wird der Befehl dennoch ausgeführt. Ein Knoten kann mehrere Parametertypen haben, aber es ist zu beachten, dass die Möglichkeit einer +Mehrdeutigkeit besteht, die vermieden werden sollte. + +@[code lang=java highlight={3} transcludeWith=:::4](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +In diesem Fall musst du nach dem Befehlstext `/argtater` eine ganze Zahl eingeben. Zum Beispiel, wenn du `/argtater 3` ausführst, erhaltest du die Rückmeldung `Called /argtater with value = 3`. Wenn du `/argtater` ohne Argumente eingibst, kann der Befehl nicht korrekt geparst werden. + +Dann fügen wir ein optionales zweites Argument hinzu: + +@[code lang=java highlight={3,13} transcludeWith=:::5](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +Jetzt kannst du eine oder zwei ganze Zahlen eingeben. Wenn du eine ganze Zahl eingibst, wird ein Feedback-Text mit einem einzigen Wert ausgegeben. Wenn du zwei Ganzzahlen angibst, wird ein Feedback-Text mit zwei Werten ausgegeben. + +Du kannst es unnötig finden, ähnliche Ausführungen zweimal anzugeben. Daher können wir eine Methode erstellen, die in beiden Ausführungen verwendet wird. + +@[code lang=java highlight={3,5,6,7} transcludeWith=:::6](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +## Benutzerdefinierte Argumenttypen + +Wenn Vanilla nicht den von dir benötigten Argumenttyp verfügt, kannst du deinen eigenen erstellen. Dazu musst du eine Klasse erstellen, die das Interface `ArgumentType` erbt, wobei `T` der Typ des Arguments ist. + +Du musst die Methode "parse" implementieren, die die Eingabezeichenfolge zu dem gewünschten Typ parst. + +Du kannst zum Beispiel einen Argumenttyp erstellen, der eine `BlockPos` aus einer Zeichenkette mit dem folgenden Format parst: `{x, y, z}` + +@[code lang=java highlight={3,5,6,7} transcludeWith=:::6](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +### Benutzerdefinierte Argumenttypen registrieren + +:::warning +Du musst den benutzerdefinierten Argumenttyp sowohl im Server als auch im Client registrieren, sonst wird der Befehl nicht funktionieren! +::: + +Du kannst deinen benutzerdefinierten Argumenttyp in der Methode `onInitialize` deines Mod-Initialisierers mit der Klasse `ArgumentTypeRegistry` registrieren: + +@[code lang=java transcludeWith=:::11](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +### Benutzerdefinierte Argumenttypen verwenden + +Wir können unseren benutzerdefinierten Argumenttyp in einem Befehl verwenden, indem wir eine Instanz davon an die Methode `.argument` im Builder des Befehls übergeben. + +@[code lang=java transcludeWith=:::10 highlight={3}](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +Durch das Ausführen des Befehls, können wir testen, ob der Argumenttyp funktioniert oder nicht: + +![Ungültiges Argument](/assets/develop/commands/custom-arguments_fail.png) + +![Gültiges Argument](/assets/develop/commands/custom-arguments_valid.png) + +![Ergebnis des Befehls](/assets/develop/commands/custom-arguments_result.png) diff --git a/versions/1.20.4/translated/de_de/develop/commands/basics.md b/versions/1.20.4/translated/de_de/develop/commands/basics.md new file mode 100644 index 000000000..73acd3316 --- /dev/null +++ b/versions/1.20.4/translated/de_de/develop/commands/basics.md @@ -0,0 +1,163 @@ +--- +title: Befehle erstellen +description: Befehle mit komplexen Parametern und Aktionen erstellen. +authors: + - dicedpixels + - i509VCB + - pyrofab + - natanfudge + - Juuxel + - solidblock + - modmuss50 + - technici4n + - atakku + - haykam + - mschae23 + - treeways + - xpple +--- + +# Befehle erstellen + +Durch das Erstellen von Befehlen kann ein Mod-Entwickler Funktionen hinzufügen, die durch einen Befehl verwendet werden können. Dieses Tutorial wird dir erklären, wie man Befehle registriert und die allgemeine Befehlsstruktur von Brigadier. + +:::info +Brigadier ist ein Befehlsparser und Dispatcher, der von Mojang für Minecraft entwickelt wurde. Es ist eine baumbasierte Befehlsbibliothek, in der du einen Baum von Befehlen und Argumenten aufbaust. Brigadier ist Open Source: +::: + +## Das Interface `Command` + +`com.mojang.brigadier.Command` ist ein funktionales Interface, das einen bestimmten Code ausführt und in bestimmten Fällen eine `CommandSyntaxException` auslöst. Er hat einen generischen Typ `S`, der den Typ der _Befehlsquelle_ definiert. +Die Befehlsquelle liefert einen Kontext, in dem ein Befehl ausgeführt wurde. In Minecraft ist die Befehlsquelle normalerweise ein `ServerCommandSource`, die einen Server, einen Befehlsblock, eine Remote-Verbindung (RCON), einen Spieler oder eine Entität darstellen kann. + +Die einzige Methode in `Command`, `run(CommandContext)`, nimmt einen `CommandContext` als einzigen Parameter und gibt eine ganze Zahl zurück. Der Befehlskontext enthält die Befehlsquelle von `S` und ermöglicht es dir, Argumente zu erhalten, die geparsten Befehlsknoten zu betrachten und die in diesem Befehl verwendete Eingabe zu sehen. + +Wie andere funktionale Interfaces wird es in der Regel als Lambda oder als Methodenreferenz verwendet: + +```java +Command command = context -> { + return 0; +}; +``` + +Die Ganzzahl kann als Ergebnis des Befehls betrachtet werden. Normalerweise bedeuten Werte kleiner oder gleich Null, dass ein Befehl fehlgeschlagen ist und nichts machen wird. Positive Werte bedeuten, dass der Befehl erfolgreich war und etwas gemacht hat. Brigadier bietet eine Konstante zur Anzeige von Erfolg; `Befehl#SINGLE_SUCCESS`. + +### Was kann die `ServerCommandSource` machen? + +Eine "ServerCommandSource" liefert einen zusätzlichen implementierungsspezifischen Kontext, wenn ein Befehl ausgeführt wird. Dazu gehört die Möglichkeit, die Entität, die den Befehl ausgeführt hat, die Welt, in der der Befehl ausgeführt wurde, oder den Server, auf dem der Befehl ausgeführt wurde, zu ermitteln. + +Du kannst auf die Befehlsquelle von einem Befehlskontext aus zugreifen, indem du `getSource()` für die Instanz `CommandContext` aufrufst. + +```java +Command command = context -> { + ServerCommandSource source = context.getSource(); + return 0; +}; +``` + +## Registrieren eines einfachen Befehls + +Befehle werden innerhalb des `CommandRegistrationCallback` registriert, der von der Fabric API bereitgestellt wird. + +:::info +Informationen zur Registrierung von Callbacks findest du in der Anleitung [Events](../events). +::: + +Das Event sollte im Initialisierer deines Mods registriert werden. + +Der Callback hat drei Parameter: + +- `CommandDispatcher dispatcher` - Dient zum Registrieren, Parsen und Ausführen von Befehlen. `S` ist der Typ + der Befehlsquelle, die der Command Dispatcher unterstützt. +- `CommandRegistryAccess registryAccess` - Bietet eine Abstraktion zu Registrys, die an bestimmte Befehlsargumente übergeben werden können + Argument-Methoden +- `CommandManager.RegistrationEnvironment environment` - Identifiziert den Typ des Servers, auf dem die Befehle registriert werden. + +Im Mod-Initialisierer registrieren wir nur einen einfachen Befehl: + +@[code lang=java transcludeWith=:::_1](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +In der Methode `sendFeedback()` ist der erste Parameter der zu sendende Text, der ein `Supplier` ist, um zu vermeiden, dass Text-Objekte instanziert werden, wenn sie nicht benötigt werden. + +Der zweite Parameter bestimmt, ob die Rückmeldung an andere Operatoren gesendet werden soll. Im Allgemeinen sollte der Befehl `false` sein, wenn er etwas abfragen soll, ohne die Welt tatsächlich zu beeinflussen, wie zum Beispiel die aktuelle Zeit oder den Punktestand eines Spielers. die Zeit zu ändern oder den Spielstand einer Person zu ändern, sollte er `true` sein. + +Wenn der Befehl fehlschlägt, kannst du, anstatt `sendFeedback()` aufzurufen, direkt eine beliebige Ausnahme auslösen, die vom Server oder Client entsprechend behandelt wird. + +Die `CommandSyntaxException` wird im Allgemeinen ausgelöst, um Syntaxfehler in Befehlen oder Argumenten aufzuzeigen. Du kannst auch deine eigene Exception implementieren. + +Um diesen Befehl auszuführen, musst du `/foo` eingeben, wobei die Groß- und Kleinschreibung zu beachten ist. + +### Umgebung der Registrierung + +Falls gewünscht, kannst du auch dafür sorgen, dass ein Befehl nur unter bestimmten Umständen registriert wird, zum Beispiel nur in der dedizierten Umgebung: + +@[code lang=java highlight={2} transcludeWith=:::2](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +### Befehlsanforderungen + +Angenommen, du hast einen Befehl, den nur Operatoren ausführen können sollen. An dieser Stelle kommt die Methode `requires()` ins Spiel. Die Methode `requires()` hat ein Argument eines `Predicate`, das eine `ServerCommandSource` liefert, mit der getestet werden kann, ob die `CommandSource` den Befehl ausführen kann. + +@[code lang=java highlight={3} transcludeWith=:::3](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +Dieser Befehl wird nur ausgeführt, wenn die Quelle des Befehls mindestens ein Operator der Ebene 2 ist, einschließlich Befehlsblöcke. Andernfalls ist der Befehl nicht registriert. + +Dies hat den Nebeneffekt, dass dieser Befehl in der Tab-Vervollständigung für alle, die nicht Level 2 Operator sind, nicht angezeigt wird. Das ist auch der Grund, warum du die meisten Befehle nicht mit der Tabulatortaste vervollständigen kannst, wenn du keine Cheats aktivierst. + +### Unterbefehle + +Um einen Unterbefehl hinzuzufügen, registriere den ersten buchstäblichen Knoten des Befehls ganz normal. Um einen Unterbefehl zu haben, musst du den nächsten buchstäblichen Knoten an den bestehenden Knoten anhängen. + +@[code lang=java highlight={3} transcludeWith=:::7](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +Ähnlich wie die Argumente können auch die Unterbefehlsknoten auf optional gesetzt werden. Im folgenden Fall sind sowohl `/subtater` als auch `/subtater subcommand` gültig. + +@[code lang=java highlight={2,8} transcludeWith=:::8](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +## Client-Befehle + +Die Fabric API verfügt über einen `ClientCommandManager` im Paket `net.fabricmc.fabric.api.client.command.v2`, der zur Registrierung clientseitiger Befehle verwendet werden kann. Der Code sollte nur im clientseitigen Code vorhanden sein. + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/client/java/com/example/docs/client/command/FabricDocsReferenceClientCommands.java) + +## Befehlsumleitungen + +Befehlsumleitungen - auch bekannt als Aliase - sind eine Möglichkeit, die Funktionalität eines Befehls auf einen anderen umzuleiten. Dies ist nützlich, wenn du den Namen eines Befehls ändern möchtest, aber den alten Namen beibehalten willst. + +@[code lang=java transcludeWith=:::12](@/reference/latest/src/client/java/com/example/docs/client/command/FabricDocsReferenceClientCommands.java) + +## FAQ + +
+ +### Warum kompiliert mein Code nicht? + +- Abfangen oder Auslösen einer `CommandSyntaxException` - `CommandSyntaxException` ist keine `RuntimeException`. Wenn du sie auslöst, sollte sie in Methoden ausgelöst werden, die `CommandSyntaxException` in den Methodensignaturen auslösen, oder sie sollte abgefangen werden. + Brigadier wird die checked Exceptions behandeln und die entsprechende Fehlermeldung im Spiel für dich weiterleiten. + +- Probleme mit generischen Typen - Es kann sein, dass du hin und wieder ein Problem mit generischen Typen hast. Wenn du Serverbefehle registrierst (was in den meisten Fällen der Fall ist), stelle sicher, dass du `CommandManager.literal` oder `CommandManager.argument` anstelle von `LiteralArgumentBuilder.literal` oder `RequiredArgumentBuilder.argument` benutzt. + +- Überprüfe die Methode `sendFeedback()` - Du hast vielleicht vergessen, einen booleschen Wert als zweites Argument anzugeben. Denke auch daran dass seit Minecraft 1.20 der erste Parameter `Supplier` anstelle von `Text` ist. + +- Ein Befehl sollte eine ganze Zahl zurückgeben - Bei der Registrierung von Befehlen akzeptiert die Methode `executes()` ein `Command` Objekt, das normalerweise ein Lambda ist. Das Lambda sollte eine ganze Zahl zurückgeben, anstelle anderen Typen. + +### Kann ich Befehle zur Laufzeit registrieren? + +::: warning +You can do this, but it is not recommended. You would get the `CommandManager` from the server and add anything commands +you wish to its `CommandDispatcher`. + +Danach musst du den Befehlsbaum mit `CommandManager.sendCommandTree(ServerPlayerEntity)` erneut an jeden Spieler senden. + +Dies ist erforderlich, da der Client den Befehlsbaum, den er bei der Anmeldung (oder beim Senden von Operator-Paketen) erhält, lokal zwischenspeichert, um Fehlermeldungen zu vervollständigen. +::: + +### Kann ich die Registrierung von Befehlen während der Laufzeit aufheben? + +::: warning +You can also do this, however, it is much less stable than registering commands at runtime and could cause unwanted side +effects. + +Um die Dinge einfach zu halten, musst du Reflection auf Brigadier anwenden und Knoten entfernen. Danach musst du den Befehlsbaum erneut an jeden Spieler mit `sendCommandTree(ServerPlayerEntity)` senden. + +Wenn du den aktualisierten Befehlsbaum nicht sendest, kann es sein, dass der Client denkt, dass der Befehl noch existiert, obwohl die Ausführung am Server fehlschlägt. +::: diff --git a/versions/1.20.4/translated/de_de/develop/commands/suggestions.md b/versions/1.20.4/translated/de_de/develop/commands/suggestions.md new file mode 100644 index 000000000..33e44637d --- /dev/null +++ b/versions/1.20.4/translated/de_de/develop/commands/suggestions.md @@ -0,0 +1,45 @@ +--- +title: Befehlsvorschläge +description: Lerne, wie man Spielern Werte für Befehlsargumente vorschlagen kann. +authors: + - IMB11 +--- + +# Befehlsvorschläge + +Minecraft hat ein mächtiges System für Befehlsvorschläge, das an vielen Stellen verwendet wird, wie zum Beispiel beim Befehl `/give`. Mit diesem System kannst du dem Spieler Werte für Befehlsargumente vorschlagen, aus denen er dann auswählen kann - eine großartige Möglichkeit, um deine Befehle benutzerfreundlicher und ergonomischer zu gestalten. + +## Vorschlaganbieter + +Ein `SuggestionProvider` wird verwendet, um eine Liste von Vorschlägen zu erstellen, die an den Spieler gesendet werden. Ein Vorschlaganbieter ist eine funktionales Interface, das einen `CommandContext` und einen `SuggestionBuilder` entgegennimmt und einige `Suggestions` zurückgibt. Der `SuggestionProvider` gibt ein `CompletableFuture` zurück, da die Vorschläge möglicherweise nicht sofort verfügbar sind. + +## Verwenden von Vorschlaganbietern + +Um einen Vorschlaganbieter zu verwenden, musst du die Methode `suggests` auf dem Argument Builder aufrufen. Diese Methode nimmt einen `SuggestionProvider` und gibt den geänderten Argument Builder mit dem angehängten Suggestion Provider zurück. + +@[code java transcludeWith=:::9 highlight={4}](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +## Eingebaute Vorschlaganbieter + +Es gibt einige eingebaute Vorschlaganbieter, du verwenden kannst: + +| Vorschlaganbieter | Beschreibung | +| ----------------------------------------- | ------------------------------------------------------------------------- | +| `SuggestionProviders.SUMMONABLE_ENTITIES` | Schläft alle Entitäten vor, die beschworen werden können. | +| `SuggestionProviders.AVAILABLE_SOUNDS` | Schlägt alle Klänge vor, die abgespielt werden können. | +| `LootCommand.SUGGESTION_PROVIDER` | Zeigt alle verfügbaren Loottabellen an. | +| `SuggestionProviders.ALL_BIOMES` | Schlägt alle Biome vor, die verfügbar sind. | + +## Erstellen eines benutzerdefinierten Vorschlagsanbieters + +Wenn ein eingebauter Anbieter deine Anforderungen nicht erfüllt, kannst du einen eigenen Vorschlaganbieter erstellen. Zu diesem Zweck musst du eine Klasse erstellen, die das Interface `SuggestionProvider` implementiert und die Methode `getSuggestions` überschreibt. + +In diesem Beispiel erstellen wir einen Vorschlaganbieter, der alle Benutzernamen der Spieler auf dem Server vorschlägt. + +@[code java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/command/PlayerSuggestionProvider.java) + +Um diesen Vorschlaganbieter zu verwenden, übergebe einfach eine Instanz davon an die Methode `.suggests` im Argument Builder. + +Natürlich können die Anbieter von Vorschlägen komplexer sein, da sie auch den Befehlskontext lesen können, um Vorschläge zu machen, die auf dem Zustand des Befehls basieren - zum Beispiel auf den Argumenten, die bereits angegeben wurden. + +Dies könnte in Form von Lesen des Inventars des Spielers und Vorschlagen von Gegenständen oder Entitäten, die sich in der Nähe des Spielers befinden, geschehen. diff --git a/versions/1.20.4/translated/de_de/develop/entities/damage-types.md b/versions/1.20.4/translated/de_de/develop/entities/damage-types.md new file mode 100644 index 000000000..e99a8b02c --- /dev/null +++ b/versions/1.20.4/translated/de_de/develop/entities/damage-types.md @@ -0,0 +1,96 @@ +--- +title: Schadensarten +description: Lerne, wie man benutzerdefinierte Schadensarten hinzufügt. +authors: + - dicedpixels + - hiisuuii + - mattidragon +--- + +# Schadensarten + +Schadensarten definieren die Arten von Schaden, die Entitäten erleiden können. Seit Minecraft 1.19.4 ist die Erstellung neuer Schadensarten datengesteuert, das heißt sie werden mithilfe von JSON-Dateien erstellt. + +## Eine Schadensart erstellen + +Lass uns eine benutzerdefinierte Schadensart mit dem Namen _Tater_ erstellen. Wir beginnen mit der Erstellung einer JSON-Datei für deinen benutzerdefinierten Schaden. Diese Datei wird im `data`-Verzeichnis deines Mods in einem Unterverzeichnis mit dem Namen `damage_type` abgelegt. + +```:no-line-numbers +resources/data/fabric-docs-reference/damage_type/tater.json +``` + +Sie hat folgende Struktur: + +@[code lang=json](@/reference/latest/src/main/generated/data/fabric-docs-reference/damage_type/tater.json) + +Diese benutzerdefinierte Schadensart verursacht jedes Mal, wenn ein Spieler Schaden erleidet, einen Anstieg von 0,1 an [Erschöpfung](https://de.minecraft.wiki/w/Hunger#Ersch%C3%B6pfung), wenn der Schaden von einer lebenden Nicht-Spieler-Quelle (z.B. Weiterhin skaliert sich die Höhe des verursachten Schadens mit dem Schwierigkeitsgrad der Welt. + +::: info + +Im [Minecraft Wiki](https://de.minecraft.wiki/w/Schadensarten#Dateiformat) findest du alle möglichen Schlüssel und Werte. + +::: + +### Auf eine Schadensart durch Code zugreifen + +Wenn wir über den Code auf unsere benutzerdefinierte Schadensart zugreifen müssen, verwenden wir seinen `RegistryKey`, um eine Instanz von `DamageSource` zu erstellen. + +Der `RegistryKey` kann wie folgt ermittelt werden: + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/damage/FabricDocsReferenceDamageTypes.java) + +### Schadensarten verwenden + +Um die Verwendung von benutzerdefinierten Schadensarten zu demonstrieren, werden wir einen benutzerdefinierten Block mit dem Namen _Tater-Block_ verwenden. Wenn eine lebende Entität auf einen _Tater-Block_ tritt, verursacht er _Tater_ Schaden. + +Du kannst `onSteppedOn` überschreiben, um diesen Schaden zu zuzufügen. + +Wir beginnen mit der Erstellung einer `DamageSource` unserer benutzerdefinierten Schadensart. + +@[code lang=java transclude={21-24}](@/reference/latest/src/main/java/com/example/docs/damage/TaterBlock.java) + +Dann rufen wir `entity.damage()` mit unserer `DamageSource` und einem Betrag auf. + +@[code lang=java transclude={25-25}](@/reference/latest/src/main/java/com/example/docs/damage/TaterBlock.java) + +Die vollständige Implementierung des Blocks: + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/damage/TaterBlock.java) + +Wenn nun eine lebende Entität auf unseren benutzerdefinierten Block tritt, erleidet sie mit unserer benutzerdefinierten Schadensart 5 Schaden (2,5 Herzen). + +### Benutzerdefinierte Todesnachricht + +Du kannst eine Todesnachricht für die Schadensart im Format `death.attack.` in der Datei `en_us.json` unseres Mods definieren. + +@[code lang=json transclude={4-4}](@/reference/latest/src/main/resources/assets/fabric-docs-reference/lang/en_us.json) + +Beim Tod durch unsere Schadensart wirst du die folgende Todesnachricht sehen: + +![Effekt im Inventar eines Spielers](/assets/develop/tater-damage-death.png) + +### Schadensart-Tags + +Einige Schadensarten können Rüstung, Statuseffekte usw. Tags werden verwendet, um diese Art von Eigenschaften von Schadensarten zu kontrollieren. + +Vorhandene Schadensarten-Tags kannst du in `data/minecraft/tags/damage_type` finden. + +::: info + +Im [Minecraft Wiki](https://minecraft.wiki/w/Tag#Damage_types) kannst du eine umfassende Liste der Schadensarten-Tags finden. + +::: + +Fügen wir unsere Tater-Schadensart dem Schadensart-Tag `bypasses_armor` hinzu. + +Um unsere Schadensart zu einem dieser Tags hinzuzufügen, erstellen wir eine JSON-Datei im Namespace `minecraft`. + +```:no-line-numbers +data/minecraft/tags/damage_type/bypasses_armor.json +``` + +Mit folgendem Inhalt: + +@[code lang=json](@/reference/latest/src/main/generated/data/minecraft/tags/damage_type/bypasses_armor.json) + +Stelle sicher, dass dein Tag das bestehende Tag nicht ersetzt, indem du den Schlüssel `replace` auf `false` setzt. diff --git a/versions/1.20.4/translated/de_de/develop/entities/effects.md b/versions/1.20.4/translated/de_de/develop/entities/effects.md new file mode 100644 index 000000000..0e71aefdc --- /dev/null +++ b/versions/1.20.4/translated/de_de/develop/entities/effects.md @@ -0,0 +1,70 @@ +--- +title: Statuseffekte +description: Lerne, wie man benutzerdefinierte Statuseffekte erstellt. +authors: + - dicedpixels + - YanisBft + - FireBlast + - Friendly-Banana + - SattesKrokodil +authors-nogithub: + - siglong + - tao0lu +--- + +# Statuseffekte + +Statuseffekte, auch Effekte genannt, sind ein Zustand, der eine Entität beeinflussen kann. Sie können positiver, negativer oder neutraler Natur sein. Das Basisspiel wendet diese Effekte auf verschiedene Weise an, zum Beispiel durch Nahrung, Tränke usw. + +Der Befehl `/effect` kann verwendet werden, um Effekte auf eine Entität anzuwenden. + +## Benutzerdefinierte Statuseffekte + +In diesem Tutorial fügen wir einen neuen benutzerdefinierten Effekt namens _Tater_ hinzu, der dir einen Erfahrungspunkt pro Spieltick gibt. + +### `StatusEffect` erweitern + +Lasst uns eine benutzerdefinierte Effektklasse erstellen, indem wir `StatusEffect` erweitern, die die Basisklasse für alle Effekte ist. + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/effect/TaterEffect.java) + +### Deinen benutzerdefinierten Effekt registrieren + +Ähnlich wie bei der Registrierung von Blöcken und Items verwenden wir `Registry.register`, um unseren benutzerdefinierten Effekt in der `STATUS_EFFECT`-Registry zu registrieren. Dies kann in unserem Initialisierer geschehen. + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/effect/FabricDocsReferenceEffects.java) + +### Übersetzungen und Texturen + +Du kannst deinem Statuseffekt einen Namen geben und ein Textursymbol erstellen, das in der Inventaroberfläche des Spielers angezeigt wird. + +#### Texturen + +Das Statuseffekt-Symbol ist ein 18x18 PNG. Platziere dein eigenes Icon in: + +```:no-line-numbers +resources/assets/fabric-docs-reference/textures/mob_effect/tater.png +``` + +![Effekt im Inventar eines Spielers](/assets/develop/tater-effect.png) + +#### **Übersetzungen** + +Wie jede andere Übersetzung kannst du einen Eintrag mit dem ID-Format `"effect..": "Wert"` zur Sprachdatei hinzufügen. + +::: code-group + +```json[assets/fabric-docs-reference/lang/en_us.json] +{ + "effect.fabric-docs-reference.tater": "Tater" +} +``` + +### Testen + +Benutze den Befehl `/effect give @p fabric-docs-reference:tater`, um dem Spieler unseren Tater-Effekt zu geben. +Verwende `/effect clear` +um den Effekt zu entfernen. + +Um einen Trank zu erstellen, der diesen Effekt nutzt, lies bitte die Anleitung [Tränke](../items/potions). +::: diff --git a/versions/1.20.4/translated/de_de/develop/events.md b/versions/1.20.4/translated/de_de/develop/events.md new file mode 100644 index 000000000..6f2a9f640 --- /dev/null +++ b/versions/1.20.4/translated/de_de/develop/events.md @@ -0,0 +1,124 @@ +--- +title: Events +description: Ein Leitfaden für die Nutzung von Events, welche von der Fabric API bereitgestellt werden. +authors: + - dicedpixels + - mkpoli + - daomephsta + - solidblock + - daomephsta + - jamieswhiteshirt + - PhoenixVX + - Juuxel + - YanisBft + - liach + - natanfudge +authors-nogithub: + - stormyfabric +--- + +# Events + +Die Fabric API bietet ein System, das es Mods erlaubt, auf Aktionen oder Ereignisse zu reagieren, die auch als _Events_ im Spiel definiert sind. + +Events sind Hooks, die gemeinsame Anwendungsfälle erfüllen und/oder die Kompatibilität und Leistung zwischen Mods verbessern, die sich in dieselben Bereiche des Codes einklinken. Die Verwendung von Ereignissen ersetzt oft die Verwendung von Mixins. + +Die Fabric API stellt Ereignisse für wichtige Bereiche der Minecraft-Codebasis bereit, an denen mehrere Modder interessiert sein könnten. + +Ereignisse werden durch Instanzen von `net.fabricmc.fabric.api.event.Event` dargestellt, die _Callbacks_ speichern und aufrufen. Oft gibt es eine einzige Event-Instanz für einen Callback, die in einem statischen Attribut `EVENT` des Callback-Interfaces gespeichert wird, aber es gibt auch andere Muster. Zum Beispiel fasst `ClientTickEvents` mehrere zusammenhängende Ereignisse zusammen. + +## Callbacks + +Callbacks sind ein Teil des Codes, der als Argument an ein Event übergeben wird. Wenn das Event vom Spiel ausgelöst wird, wird der übergebene Teil des Codes ausgeführt. + +### Callback Interfaces + +Jedes Ereignis hat ein entsprechendes Callback-Interface, das üblicherweise `Callback` genannt wird. Callbacks werden durch den Aufruf der Methode `register()` für eine Event-Instanz registriert, wobei eine Instanz des Callbacks als Argument angegeben wird. + +Alle Event-Callback-Interfaces, die von der Fabric API bereitgestellt werden, sind im Paket `net.fabricmc.fabric.api.event` zu finden. + +## Auf Events hören + +### Ein einfaches Beispiel + +Dieses Beispiel registriert einen `AttackBlockCallback`, um dem Spieler Schaden zuzufügen, wenn er Blöcke trifft, die keinen Gegenstand fallen lassen, wenn sie von Hand abgebaut werden. + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/event/FabricDocsReferenceEvents.java) + +### Items zu existierenden Beutetabellen hinzufügen + +Manchmal willst du vielleicht Gegenstände zu Beutetabellen hinzufügen. Zum Beispiel, indem du deine Drops zu einem Vanille-Block oder einer Entität hinzufügst. + +Die einfachste Lösung, das Ersetzen der Beutetabellen-Datei, kann andere Mods zerstören. Was ist, wenn sie diese auch ändern wollen? Wir sehen uns an, wie du Gegenstände zu Beutetabellen hinzufügen kannst, ohne die Tabelle zu überschreiben. + +Wir werden die Beutetabelle für Kohleerz um Eier erweitern. + +#### Auf das Laden der Beutetabelle hören + +Die Fabric API hat ein Event, das ausgelöst wird, wenn Beutetabellen geladen werden, `LootTableEvents.MODIFY`. Du kannst einen Callback dafür in deinem Mod-Initialisierer registrieren. Überprüfen wir auch, ob die aktuelle Beutetabelle die Beutetabelle für Kohleerz ist. + +@[code lang=java transclude={38-40}](@/reference/latest/src/main/java/com/example/docs/event/FabricDocsReferenceEvents.java) + +#### Hinzufügen von Items zur Beutetabelle + +In Beutetabellen werden Gegenstände in _Beutepool-Einträgen_ gespeichert, und Einträge werden in _Beutepools_ gespeichert. Um einen Gegenstand hinzuzufügen, müssen wir der Beutetabelle einen Pool mit einem Eintrag für ein Item hinzufügen. + +Wir können einen Pool mit `LootPool#builder` erstellen, und ihn zur Beutetabelle hinzufügen. + +Unser Pool hat auch keine Items, also erstellen wir einen Item-Eintrag mit `ItemEntry#builder` und fügen ihn dem Pool hinzu. + +@[code highlight={6-7} transcludeWith=:::2](@/reference/latest/src/main/java/com/example/docs/event/FabricDocsReferenceEvents.java) + +## Benutzerdefinierte Events + +In einigen Bereichen des Spiels gibt es keine von der Fabric API bereitgestellten Hooks, so dass du entweder ein Mixin verwenden oder dein eigenes Event erstellen kannst. + +Wir werden uns ein Event ansehen, das ausgelöst wird, wenn Schafe geschoren werden. Der Prozess der Erstellung eines Events ist wie folgt: + +- Erstellen des Interface für einen Event Callback +- Auslösen des Events von einem Mixin +- Erstellen einer Testimplementierung + +### Erstellen des Interface für einen Event Callback + +Das Callback-Interface beschreibt, was von den Event-Listenern implementiert werden muss, die auf dein Event hören werden. Das Callback-Interface beschreibt auch, wie das Event von unserem Mixin ausgelöst werden soll. Es ist üblich, ein `Event`-Objekt als Attribut in dem Callback-Interface zu platzieren, das unser tatsächliches Event identifiziert. + +Für unsere `Event`-Implementierung werden wir uns für ein Array-gestütztes Event entscheiden. Das Array enthält alle Event-Listener, die auf das Event hören. + +Unsere Implementierung ruft die Event-Listener der Reihe nach auf, bis einer von ihnen kein `ActionResult.PASS` zurückgibt. Das bedeutet, dass ein Listener mit Hilfe seines Rückgabewerts sagen kann: "_Abbrechen_", "_Zustimmen_" oder "_Egal, überlasse es dem nächsten Event-Listener_". + +Die Verwendung von `ActionResult` als Rückgabewert ist ein konventioneller Weg, um Event-Handler auf diese Weise zusammenarbeiten zu lassen. + +Du musst ein Interface erstellen, das eine `Event`-Instanz und eine Methode zur Implementierung der Antwort hat. Ein Grundaufbau für unseren Schafschur-Callback ist: + +@[code lang=java transcludeWith=:::](@/reference/latest/src/main/java/com/example/docs/event/SheepShearCallback.java) + +Schauen wir uns das genauer an. Wenn der Invoker aufgerufen wird, wird über alle Listener iteriert: + +@[code lang=java transclude={21-22}](@/reference/latest/src/main/java/com/example/docs/event/SheepShearCallback.java) + +Dann rufen wir unsere Methode (in diesem Fall `interact`) auf dem Listener auf, um seine Antwort zu erhalten: + +@[code lang=java transclude={33-33}](@/reference/latest/src/main/java/com/example/docs/event/SheepShearCallback.java) + +Wenn der Listener sagt, dass wir abbrechen (`ActionResult.FAIL`) oder vollständig beenden (`ActionResult.SUCCESS`) müssen, gibt der Callback das Ergebnis zurück und beendet die Schleife. `ActionResult.PASS` geht zum nächsten Listener über und sollte in den meisten Fällen zum Erfolg führen, wenn keine weiteren Listener registriert sind: + +@[code lang=java transclude={25-30}](@/reference/latest/src/main/java/com/example/docs/event/SheepShearCallback.java) + +Wir können Javadoc-Kommentare an die oberste Stelle der Callback-Klassen setzen, um zu dokumentieren, was jedes `ActionResult` macht. In unserem Fall könnte das wie folgt sein: + +@[code lang=java transclude={9-16}](@/reference/latest/src/main/java/com/example/docs/event/SheepShearCallback.java) + +### Auslösen des Events von einem Mixin + +Jetzt haben wir das Grundgerüst für ein Event, aber wir müssen es auslösen. Da wir das Ereignis auslösen wollen, wenn ein Spieler versucht, ein Schaf zu scheren, rufen wir das Ereignis `invoker` in `SheepEntity#interactMob` auf, wenn `sheared()` aufgerufen wird (d.h. + +@[code lang=java transcludeWith=:::](@/reference/latest/src/main/java/com/example/docs/mixin/event/SheepEntityMixin.java) + +### Erstellen einer Testimplementierung + +Jetzt müssen wir unser Event testen. Du kannst einen Listener in deiner Initialisierungsmethode (oder in einem anderen Bereich, wenn du das bevorzugst) registrieren und dort benutzerdefinierte Logik hinzufügen. Hier ist ein Beispiel, bei dem dem ein Diamant anstelle von Wolle auf die Füße des Schafs fällt: + +@[code lang=java transcludeWith=:::3](@/reference/latest/src/main/java/com/example/docs/event/FabricDocsReferenceEvents.java) + +Wenn du im Spiel ein Schaf scherst, sollte anstelle von Wolle ein Diamant fallen. diff --git a/versions/1.20.4/translated/de_de/develop/getting-started/creating-a-project.md b/versions/1.20.4/translated/de_de/develop/getting-started/creating-a-project.md new file mode 100644 index 000000000..264335b23 --- /dev/null +++ b/versions/1.20.4/translated/de_de/develop/getting-started/creating-a-project.md @@ -0,0 +1,68 @@ +--- +title: Ein Projekt erstellen +description: Eine Schritt-für-Schritt-Anleitung, wie man ein neues Mod-Projekt mit dem Fabric Vorlagen Mod Generator erstellt. +authors: + - IMB11 +--- + +# Ein Projekt erstellen + +Fabric bietet eine einfache Möglichkeit, ein neues Mod-Projekt mit dem Fabric Template Mod Generator zu erstellen - wenn du möchtest, kannst du ein neues Projekt auch manuell erstellen, indem du das Beispiel-Mod-Repository verwendest, dann solltest du den Abschnitt [Manuelle Projekterstellung](#manuelle-projekterstellung) lesen. + +## Erstellung eines Projekts + +Du kannst den [Fabric Vorlagen Mod Generator](https://fabricmc.net/develop/template/) verwenden, um ein neues Projekt für deinen Mod zu erstellen - du solltest die erforderlichen Felder ausfüllen, wie zum Beispiel den Paketnamen und den Mod-Namen, sowie die Minecraft-Version, für die du entwickeln möchtest. + +![Vorschau des Generators](/assets/develop/getting-started/template-generator.png) + +Wenn du Kotlin verwenden oder Datengeneratoren hinzufügen möchtest, kannst du die entsprechenden Optionen im Abschnitt `Advanced Options` auswählen. + +![Der Abschnitt "Advanced options"](/assets/develop/getting-started/template-generator-advanced.png) + +Der Generator erstellt dann ein neues Projekt in Form einer ZIP-Datei für dich. + +Du solltest diese ZIP-Datei an einem Ort deiner Wahl entpacken und dann den entpackten Ordner in IntelliJ IDEA öffnen: + +![Aufforderung zum Öffnen des Projekts](/assets/develop/getting-started/open-project.png) + +## Import des Projekts + +Sobald du das Projekt in IntelliJ IDEA geöffnet hast, sollte IDEA automatisch die Gradle-Konfiguration des Projekts laden und die notwendigen Einrichtungsaufgaben durchführen. + +Wenn du eine Benachrichtigung über ein Gradle-Build-Skript erhältst, solltest du auf die Schaltfläche `Import Gradle Project` klicken: + +![Gradle Aufforderung](/assets/develop/getting-started/gradle-prompt.png) + +Sobald das Projekt importiert wurde, solltest du die Dateien des Projekts im Projekt-Explorer sehen und mit der Entwicklung deines Mods beginnen können. + +## Manuelle Projekterstellung + +:::warning +Du musst [Git](https://git-scm.com/) installiert haben, um das Beispiel-Mod-Repository klonen zu können. +::: + +Wenn du den Fabric Vorlagen Mod Generator nicht verwenden kannst, kannst du ein neues Projekt manuell erstellen, indem du folgende Schritte befolgst. + +Klone zunächst das Beispiel-Mod-Repository mit Git: + +```sh +git clone https://github.com/FabricMC/fabric-example-mod/ my-mod-project +``` + +Dadurch wird das Repository in einen neuen Ordner mit dem Namen `my-mod-project` geklont. + +Anschließend solltest du den Ordner `.git` aus dem geklonten Repository löschen und das Projekt in IntelliJ IDEA öffnen. Wenn der Ordner `.git` nicht angezeigt wird, solltest du die Option zur Anzeige versteckter Dateien in deinem Dateimanager aktivieren. + +Sobald du das Projekt in IntelliJ IDEA geöffnet hast, sollte es automatisch die Gradle-Konfiguration des Projekts laden und die notwendigen Einrichtungsaufgaben durchführen. + +Wie bereits erwähnt, solltest du, wenn du eine Benachrichtigung über ein Gradle-Build-Skript erhältst, auf die Schaltfläche `Import Gradle Project` klicken. + +### Die Vorlage bearbeiten + +Sobald das Projekt importiert wurde, solltest du die Details des Projekts so ändern, dass sie mit den Details deines Mods übereinstimmen: + +- Ändere die Datei `gradle.properties` des Projekts, um die Eigenschaften `maven_group` und `archive_base_name` an die Details deines Mods anzupassen. +- Ändere die Datei `fabric.mod.json`, um die Eigenschaften `id`, `name` und `description` an die Details deines Mods anzupassen. +- Stelle sicher, dass die Versionen von Minecraft, die Mappings, der Loader und Loom - die alle über abgefragt werden können - mit den Versionen übereinstimmen, die du ansprechen möchtest. + +Du kannst natürlich den Paketnamen und die Hauptklasse des Mods ändern, um die Details deines Mods anzupassen. diff --git a/versions/1.20.4/translated/de_de/develop/getting-started/introduction-to-fabric-and-modding.md b/versions/1.20.4/translated/de_de/develop/getting-started/introduction-to-fabric-and-modding.md new file mode 100644 index 000000000..c0fbcf7a5 --- /dev/null +++ b/versions/1.20.4/translated/de_de/develop/getting-started/introduction-to-fabric-and-modding.md @@ -0,0 +1,65 @@ +--- +title: Einführung in Fabric und Modding +description: "Eine kurze Einführung in Fabric und Modding in Minecraft: Java Edition." +authors: + - IMB11 + - itsmiir +authors-nogithub: + - basil4088 +--- + +# Einführung in Fabric und Modding + +## Voraussetzungen + +Bevor du anfängst, solltest du ein Grundverständnis für die Entwicklung mit Java und ein Verständnis für objektorientierte Programmierung (OOP) haben. + +Wenn du mit diesen Konzepten nicht vertraut bist, solltest du dir einige Tutorials zu Java und OOP ansehen, bevor du mit dem Modding beginnst. + +- [W3: Java Tutorials](https://www.w3schools.com/java/) +- [Codecademy: Java lernen](https://www.codecademy.com/learn/learn-java) +- [W3: Java OOP](https://www.w3schools.com/java/java_oop.asp) +- [Medium: Einführung in die OOP](https://medium.com/@Adekola_Olawale/beginners-guide-to-object-oriented-programming-a94601ea2fbd) + +### Begriffserklärung + +Bevor wir beginnen, wollen wir einige Begriffe erläutern, die bei der Arbeit mit Fabric vorkommen werden: + +- **Mod**: Eine Modifikation des Spiels, die neue Funktionen hinzufügt oder bestehende ändert. +- **Mod-Loader**: Ein Tool, das Mods in das Spiel lädt, wie zum Beispiel der Fabric Loader. +- **Mixin**: Ein Werkzeug zum Ändern des Spielcodes zur Laufzeit - siehe [Mixin-Einführung](https://fabricmc.net/wiki/tutorial:mixin_introduction) für weitere Informationen. +- **Gradle**: Ein Build-Automatisierungstool zum Erstellen und Kompilieren von Mods, das von Fabric zum Erstellen von Mods verwendet wird. +- **Mappings**: Eine Reihe von Mappings, die obfuskierten Code auf menschenlesbaren Code abbilden. +- **Obfuskation**: Der Prozess, der Code schwer verständlich macht und von Mojang verwendet wird, um den Code von Minecraft zu schützen. +- **Remapping**: Der Prozess der Umwandlung von obfuskierten Code in für Menschen lesbaren Code. + +## Was ist Fabric? + +Fabric ist eine leichtgewichtige Modding-Werkzeugbox für Minecraft: Java Edition. + +Sie ist als einfache und leicht zu bedienende Modding-Plattform konzipiert. Fabric ist ein von der Gemeinschaft getragenes Projekt und ist Open Source, was bedeutet, dass jeder zu dem Projekt beitragen kann. + +Du solltest die vier Hauptkomponenten von Fabric kennen: + +- **Fabric Loader**: Ein flexibler, plattformunabhängiger Mod-Loader für Minecraft und andere Spiele und Anwendungen. +- **Fabric Loom**: Ein Gradle-Plugin, das es Entwicklern ermöglicht, Mods einfach zu entwickeln und zu debuggen. +- **Fabric API**: Eine Reihe von APIs und Werkezuge für Mod-Entwickler, die du bei der Erstellung von Mods verwenden kannst. +- **Yarn**: Eine Reihe offener Minecraft-Mappings, die unter der Creative Commons Zero-Lizenz für jeden frei nutzbar sind. + +## Warum wird Fabric für das Modden von Minecraft benötigt? + +> Beim Modding wird ein Spiel modifiziert, um sein Verhalten zu ändern oder neue Funktionen hinzuzufügen - im Fall von Minecraft kann dies alles sein, vom Hinzufügen neuer Items, Blöcke oder Entitäten bis hin zur Änderung der Spielmechanik oder dem Hinzufügen neuer Spielmodi. + +Minecraft: Die Java Edition wird von Mojang obfuskiert, was Modifikationen allein schwierig macht. Mit Hilfe von Modding-Werkzeugen wie Fabric wird das Modding jedoch viel einfacher. Es gibt verschiedene Mapping-Systeme, die bei diesem Prozess helfen können. + +Loom wandelt den obfuskierten Code mit Hilfe dieser Mappings in ein für Menschen lesbares Format um, was es Moddern erleichtert, den Code des Spiels zu verstehen und zu verändern. Yarn ist eine beliebte und ausgezeichnete Wahl für diese Mappings, aber es gibt auch andere Optionen. Jedes Mapping-Projekt kann seine eigenen Stärken oder Schwerpunkte haben. + +Mit Loom kannst du auf einfache Weise Mods entwickeln und Mods gegen remapped Code kompilieren, und mit Fabric Loader kannst du diese Mods in das Spiel laden. + +## Was bietet die Fabric API und warum ist sie nötig? + +> Fabric API ist eine Sammlung von APIs und Werkzeugen, die Mod-Entwickler bei der Erstellung von Mods verwenden können. + +Die Fabric API bietet eine Vielzahl von APIs, die auf der bestehenden Funktionalität von Minecraft aufbauen - zum Beispiel neue Hooks und Events, die Modder nutzen können, oder neue Utilities und Werkzeuge, die das Modding vereinfachen - wie zum Beispiel Access Wideners und die Möglichkeit, auf interne Registrys zuzugreifen, wie zui, Beispiel die Registry für kompostierbare Items. + +Während die Fabric API leistungsstarke Funktionen bietet, können einige Aufgaben, wie zum Beispiel die grundlegende Blockregistrierung, auch ohne sie mit den Vanilla APIs durchgeführt werden. diff --git a/versions/1.20.4/translated/de_de/develop/getting-started/launching-the-game.md b/versions/1.20.4/translated/de_de/develop/getting-started/launching-the-game.md new file mode 100644 index 000000000..b1ee52497 --- /dev/null +++ b/versions/1.20.4/translated/de_de/develop/getting-started/launching-the-game.md @@ -0,0 +1,63 @@ +--- +title: Starten des Spiels +description: Lerne, wie du die verschiedenen Startprofile verwendest, um deine Mods in einer Live-Spielumgebung zu starten und zu debuggen. +authors: + - IMB11 +--- + +# Starten des Spiels + +Fabric Loom bietet eine Vielzahl von Startprofilen, die dir helfen, deine Mods in einer Live-Spielumgebung zu starten und zu debuggen. Dieser Leitfaden behandelt die verschiedenen Startprofile und wie man sie zum Debuggen und Testen der Mods verwendet. + +## Startprofile + +Wenn du IntelliJ IDEA verwendest, findest du die Startprofile in der oberen rechten Ecke des Fensters. Klicke auf das Dropdown-Menü, um die verfügbaren Startprofile anzuzeigen. + +Es sollte ein Client- und ein Serverprofil geben, mit der Möglichkeit, es entweder normal oder im Debug-Modus auszuführen: + +![Startprofile](/assets/develop/getting-started/launch-profiles.png) + +## Gradle Aufgaben + +Wenn du die Kommandozeile verwendest, kannst du die folgenden Gradle-Befehle verwenden, um das Spiel zu starten: + +- `./gradlew runClient` - Startet das Spiel im Client-Modus. +- `./gradlew runServer` - Startet das Spiel im Server-Modus. + +Das einzige Problem bei diesem Ansatz ist, dass Sie Ihren Code nicht einfach debuggen können. Wenn du deinen Code debuggen willst, musst du die Startprofile in IntelliJ IDEA oder über die Gradle-Integration deiner IDE verwenden. + +## Hotswapping von Klassen + +Wenn du das Spiel im Debug-Modus ausführst, kannst du deine Klassen per Hotswap austauschen, ohne das Spiel neu zu starten. Dies ist nützlich, um Änderungen an deinem Code schnell zu testen. + +Du bist aber immer noch ziemlich eingeschränkt: + +- Du kannst keine Methoden hinzufügen oder entfernen +- Du kannst die Methodenparameter nicht ändern +- Du kannst keine Attribute hinzufügen oder entfernen + +## Hotswapping von Mixins + +Wenn du Mixins verwendest, kannst du deine Mixin-Klassen per Hotswap austauschen, ohne das Spiel neu zu starten. Dies ist nützlich, um Änderungen an deinen Mixins schnell zu testen. + +Hierzu musst du allerdings den Mixin-Java-Agent installieren, damit das funktioniert. + +### 1. Finde die JAR der Mixin Bibliothek + +In IntelliJ IDEA findest du die Mixin-Bibliothek JAR im Abschnitt "External Libraries" des Abschnitts "Project": + +![Mixin Bibliothek](/assets/develop/getting-started/mixin-library.png) + +Für den nächsten Schritt musst du den "Absolute Path" (Absoluten Pfad) der JAR-Datei kopieren. + +### 2. Füge das VM-Argument `-javaagent` hinzu + +Füge in deiner "Minecraft Client"- und/oder "Minecraft Server"-Ausführungskonfiguration Folgendes zur Option VM-Argumente hinzu: + +```:no-line-numbers +-javaagent:"Pfad zur Mixin-Bibliothek JAR hier" +``` + +![Bildschirmfoto der VM-Argumente](/assets/develop/getting-started/vm-arguments.png) + +Jetzt solltest du in der Lage sein, den Inhalt deiner Mixin-Methoden während des Debuggens zu ändern und die Änderungen wirksam werden zu lassen, ohne das Spiel neu zu starten. diff --git a/versions/1.20.4/translated/de_de/develop/getting-started/project-structure.md b/versions/1.20.4/translated/de_de/develop/getting-started/project-structure.md new file mode 100644 index 000000000..29f2061d5 --- /dev/null +++ b/versions/1.20.4/translated/de_de/develop/getting-started/project-structure.md @@ -0,0 +1,59 @@ +--- +title: Projektstruktur +description: Ein Überblick über die Struktur eines Fabric-Mod-Projekts. +authors: + - IMB11 +--- + +# Projektstruktur + +Auf dieser Seite wird die Struktur eines Fabric-Mod-Projekts und der Zweck der einzelnen Dateien und Ordner im Projekt erläutert. + +## `fabric.mod.json` + +Die Datei `fabric.mod.json` ist die Hauptdatei, die deinen Mod für den Fabric Loader beschreibt. Sie enthält Informationen wie die ID des Mods, die Version und die Abhängigkeiten. + +Die wichtigsten Felder in der Datei `fabric.mod.json` sind: + +- `id`: Die Mod-ID, Welche einzigartig sein sollte. +- `name`: Der Name des Mods. +- `environment`: Die Umgebung in der dein Mod läuft, wie beispielsweise `client`, `server`, oder `*` für beide. +- `entrypoints`: Die Einstiegspunkte, die dein Mod bereitstellt, wie beispielsweise `main` oder `client`. +- `depends`: Die Mods, von denen dein Mod abhängt. +- `mixins`: Die Mixins, die dein Mod bereitstellt. + +Nachfolgend siehst du eine Beispieldatei `fabric.mod.json` - dies ist die Datei `fabric.mod.json` für das Referenzprojekt, das diese Dokumentationsseite betreibt. + +:::details Referenzprojekt `fabric.mod.json` +@[code lang=json](@/reference/latest/src/main/resources/fabric.mod.json) +::: + +## Einstiegspunkte + +Wie bereits erwähnt, enthält die Datei `fabric.mod.json` ein Feld namens `entrypoints` - dieses Feld wird verwendet, um die Einstiegspunkte anzugeben, die dein Mod bereitstellt. + +Der Vorlagen-Mod-Generator erstellt standardmäßig sowohl einen `main`- als auch einen `client`-Einstiegspunkt - der `main`-Einstiegspunkt wird für allgemeinen Code verwendet, der `client`-Einstiegspunkt für Client-spezifischen Code. Diese Einstiegspunkte werden jeweils aufgerufen, wenn das Spiel beginnt. + +@[code lang=java transcludeWith=#entrypoint](@/reference/latest/src/main/java/com/example/docs/FabricDocsReference.java) + +Das obige ist ein Beispiel für einen einfachen `main`-Einstiegspunkt, der eine Nachricht an die Konsole ausgibt, wenn das Spiel startet. + +## `src/main/resources` + +Der Ordner `src/main/resources` wird verwendet, um die Ressourcen zu speichern, die dein Mod verwendet, wie Texturen, Modelle und Sounds. + +Es ist auch der Ort, an dem sich die Datei `fabric.mod.json` und alle Mixin-Konfigurationsdateien befinden, die dein Mod verwendet. + +Assets werden in einer Struktur gespeichert, die die Struktur von Ressourcenpaketen widerspiegelt - eine Textur für einen Block würde zum Beispiel in `assets/modid/textures/block/block.png` gespeichert werden. + +## `src/client/resources` + +Der Ordner `src/client/resources` wird verwendet, um Client-spezifische Ressourcen zu speichern, wie Texturen, Modelle und Sounds, die nur auf der Client-Seite verwendet werden. + +## `src/main/java` + +Der Ordner `src/main/java` wird verwendet, um den Java-Quellcode für deinen Mod zu speichern - er existiert sowohl auf der Client- als auch auf der Serverumgebung. + +## `src/client/java` + +Der Ordner `src/client/java` wird verwendet, um clientspezifischen Java-Quellcode zu speichern, wie zum Beispiel Rendering-Code oder clientseitige Logik - wie zum Beispiel Blockfarbenprovider. diff --git a/versions/1.20.4/translated/de_de/develop/getting-started/setting-up-a-development-environment.md b/versions/1.20.4/translated/de_de/develop/getting-started/setting-up-a-development-environment.md new file mode 100644 index 000000000..13619bc41 --- /dev/null +++ b/versions/1.20.4/translated/de_de/develop/getting-started/setting-up-a-development-environment.md @@ -0,0 +1,55 @@ +--- +title: Entwicklungsumgebung einrichten +description: Ein Schritt-für-Schritt-Leitfaden, wie man eine Entwicklungsumgebung für die Erstellung von Mods mit Fabric einrichtet. +authors: + - IMB11 + - andrew6rant + - SolidBlock-cn + - modmuss50 + - daomephsta + - liach + - telepathicgrunt + - 2xsaiko + - natanfudge + - mkpoli + - falseresync + - asiekierka +authors-nogithub: + - siglong +--- + +# Entwicklungsumgebung einrichten + +Um mit der Entwicklung von Mods mit Fabric zu beginnen, musst du eine Entwicklungsumgebung mit IntelliJ IDEA einrichten. + +## JDK 17 installieren + +Um Mods für Minecraft 1.20.4 zu entwickeln, benötigst du eine JDK 17. + +Wenn du Hilfe bei der Installation von Java benötigst, kannst du die verschiedenen Java-Installationsanleitungen im Abschnitt [Leitfäden für Spieler](../../players/index) nachlesen. + +## IntelliJ IDEA installieren + +:::info +Natürlich kannst du auch andere IDEs verwenden, wie zum Beispiel Eclipse oder Visual Studio Code, aber die meisten Seiten dieser Dokumentation gehen davon aus, dass du IntelliJ IDEA verwendest - wenn du eine andere IDE verwendest, solltest du die Dokumentation für deine IDE lesen. +::: + +Wenn du IntelliJ IDEA nicht installiert hast, kannst du es von der [offiziellen Website](https://www.jetbrains.com/idea/download/) herunterladen - befolge die Installationsschritte für dein Betriebssystem. + +Die Community-Edition von IntelliJ IDEA ist kostenlos und Open Source, und sie ist die empfohlene Version für das Modding mit Fabric. + +Möglicherweise musst du nach unten scrollen, um den Download-Link für die Community-Edition zu finden - er sieht wie folgt aus: + +![Aufforderung für den Download derIDEA Community Edition](/assets/develop/getting-started/idea-community.png) + +## IDEA Plugins installieren + +Obwohl diese Plugins nicht unbedingt notwendig sind, können sie das Modding mit Fabric erheblich erleichtern - deshalb solltest du in Erwägung ziehen, sie zu installieren. + +### Minecraft Development + +Das Minecraft Development Plugin bietet Unterstützung für das Modding mit Fabric und ist das wichtigste Plugin, das man installieren sollte. + +Du kannst es installieren, indem du IntelliJ IDEA öffnest und dann zu `File > Settings > Plugins > Marketplace Tab` navigierst - suche nach `Minecraft Development` in der Suchleiste und klicke dann auf die `Install` Schaltfläche. + +Alternativ kannst du es von der [Plugin-Seite](https://plugins.jetbrains.com/plugin/8327-minecraft-development) herunterladen und dann installieren, indem du zu `File > Settings > Plugins > Install Plugin From Disk` navigierst. diff --git a/versions/1.20.4/translated/de_de/develop/index.md b/versions/1.20.4/translated/de_de/develop/index.md new file mode 100644 index 000000000..9f2a79f7e --- /dev/null +++ b/versions/1.20.4/translated/de_de/develop/index.md @@ -0,0 +1,12 @@ +--- +title: Leitfäden für Entwickler +description: Unsere kuratierten, von der Community verfassten Leitfäden für Entwickler decken ein breites Spektrum an Themen ab, von der Einrichtung einer Entwicklungsumgebung bis hin zu fortgeschrittenen Themen wie Rendering und Networking. +--- + +# Leitfäden für Entwickler + +Unsere kuratierten, von der Community verfassten Leitfäden für Entwickler decken ein breites Spektrum an Themen ab, von der Einrichtung einer Entwicklungsumgebung bis hin zu fortgeschrittenen Themen wie Rendering und Networking. + +In der Seitenleiste findest du eine Liste mit allen verfügbaren Entwicklerleitfäden. Wenn du etwas Spezifisches suchst, kannst du die Suchleiste oben auf der Seite verwenden, um zu finden, was du benötigst. + +Wenn du zur Fabric-Dokumentation beitragen möchtest, findest du den Quellcode auf [GitHub](https://github.com/FabricMC/fabric-docs), und die entsprechenden [Beitragsrichtlinien](../contributing). diff --git a/translated/de_de/develop/items/potions.md b/versions/1.20.4/translated/de_de/develop/items/potions.md similarity index 100% rename from translated/de_de/develop/items/potions.md rename to versions/1.20.4/translated/de_de/develop/items/potions.md diff --git a/translated/de_de/develop/rendering/basic-concepts.md b/versions/1.20.4/translated/de_de/develop/rendering/basic-concepts.md similarity index 100% rename from translated/de_de/develop/rendering/basic-concepts.md rename to versions/1.20.4/translated/de_de/develop/rendering/basic-concepts.md diff --git a/versions/1.20.4/translated/de_de/develop/rendering/draw-context.md b/versions/1.20.4/translated/de_de/develop/rendering/draw-context.md new file mode 100644 index 000000000..0cff213c2 --- /dev/null +++ b/versions/1.20.4/translated/de_de/develop/rendering/draw-context.md @@ -0,0 +1,94 @@ +--- +title: Den Zeichenkontext verwenden +description: Lerne, wie man die Klasse DrawContext verwendet, um verschiedene Formen, Texte und Texturen zu rendern. +authors: + - IMB11 +--- + +# Den Zeichenkontext verwenden + +Diese Seite setzt voraus, dass du einen Blick auf die Seite [Grundlegende Rendering-Konzepte](./basic-concepts) geworfen hast. + +Die Klasse `DrawContext` ist die Hauptklasse, die für das Rendering im Spiel verwendet wird. Sie wird für das Rendern von Formen, Text und Texturen verwendet und, wie zuvor gesehen, für die Bearbeitung von `MatrixStack`s und die Verwendung von `BufferBuilder`n. + +## Formen zeichnen + +Die Klasse `DrawContext` kann verwendet werden, um auf einfache Weise **quadratische** Formen zu zeichnen. Wenn du Dreiecke oder andere nicht-quadratische Formen zeichnen willst, musst du einen `BufferBuilder` verwenden. + +### Zeichnen von Dreiecken + +Du kannst die Methode `DrawContext.fill(...)` verwenden, um ein gefülltes Rechteck zu zeichnen. + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/client/java/com/example/docs/rendering/DrawContextExampleScreen.java) + +![Ein Rechteck](/assets/develop/rendering/draw-context-rectangle.png) + +### Zeichnen von Umrissen/Rahmen + +Nehmen wir an, wir wollen das Rechteck, das wir gerade gezeichnet haben, umreißen. Wir können die Methode `DrawContext.drawBorder(...)` verwenden, um einen Umriss zu zeichnen. + +@[code lang=java transcludeWith=:::2](@/reference/latest/src/client/java/com/example/docs/rendering/DrawContextExampleScreen.java) + +![Ein Rechteck mit einer Umrandung](/assets/develop/rendering/draw-context-rectangle-border.png) + +### Zeichnen von individuellen Linien + +Wir können die Methoden `DrawContext.drawHorizontalLine(...)` und `DrawContext.drawVerticalLine(...)` verwenden, um Linien zu zeichnen. + +@[code lang=java transcludeWith=:::3](@/reference/latest/src/client/java/com/example/docs/rendering/DrawContextExampleScreen.java) + +![Linien](/assets/develop/rendering/draw-context-lines.png) + +## Der Scheren-Manager + +Die Klasse `DrawContext` hat einen eingebauten Scheren-Manager. So kannst du dein Rendering ganz einfach auf einen bestimmten Bereich beschränken. Dies ist nützlich für das Rendern von Dingen wie Tooltips oder anderen Elementen, die nicht außerhalb eines bestimmten Bereichs gerendert werden sollen. + +### Den Scheren-Manager nutzen + +:::tip +Scheren-Regionen können verschachtelt werden! Stelle sicher, dass du den Scheren-Manager genauso oft deaktivierst, wie du ihn aktiviert hast. +::: + +Um den Scheren-Manager zu aktivieren, verwende einfach die Methode `DrawContext.enableScissor(...)`. Um den Scheren-Manager zu deaktivieren, verwende die Methode `DrawContext.disableScissor()`. + +@[code lang=java transcludeWith=:::4](@/reference/latest/src/client/java/com/example/docs/rendering/DrawContextExampleScreen.java) + +[Scheren-Region in Aktion](/assets/develop/rendering/draw-context-scissor.png) + +Wie du siehst, wird der Farbverlauf nur innerhalb der Scheren-Region gerendert, obwohl wir der Oberfläche sagen, dass sie den Farbverlauf über die gesamte Oberfläche rendern soll. + +## Zeichnen von Texturen + +Es gibt nicht den einen "richtigen" Weg, um Texturen auf einen Bildschirm zu zeichnen, da die Methode `drawTexture(...)` viele verschiedene Überladungen hat. In diesem Abschnitt werden die häufigsten Anwendungsfälle behandelt. + +### Zeichnen einer ganzen Textur + +Im Allgemeinen wird empfohlen, dass man die Überladung verwendet, die die Parameter `textureWidth` und `textureHeight` angibt. Der Grund dafür ist, dass die Klasse `DrawContext` diese Werte entgegennimmt, wenn du sie nicht angibst, was manchmal falsch sein kann. + +@[code lang=java transcludeWith=:::5](@/reference/latest/src/client/java/com/example/docs/rendering/DrawContextExampleScreen.java) + +![Beispiel für das Zeichnen einer ganzen Textur](/assets/develop/rendering/draw-context-whole-texture.png) + +### Zeichnen eines Teils einer Textur + +Hier kommen `u` und `v` ins Spiel. Diese Parameter geben die obere linke Ecke der zu zeichnenden Textur an, und die Parameter `regionWidth` und `regionHeight` geben die Größe des zu zeichnenden Teils der Textur an. + +Nehmen wir diese Textur als Beispiel. + +![Textur des Rezeptbuchs](/assets/develop/rendering/draw-context-recipe-book-background.png) + +Wenn wir nur einen Bereich zeichnen wollen, der die Lupe enthält, können wir die folgenden Werte `u`, `v`, `regionWidth` und `regionHeight` verwenden: + +@[code lang=java transcludeWith=:::6](@/reference/latest/src/client/java/com/example/docs/rendering/DrawContextExampleScreen.java) + +![Textur der Region](/assets/develop/rendering/draw-context-region-texture.png) + +## Zeichnen von Text + +Die Klasse `DrawContext` verfügt über verschiedene selbsterklärende Methoden zum Rendern von Texten, die hier aus Gründen der Kürze nicht behandelt werden. + +Nehmen wir an, wir wollen "Hello World" auf die Oberfläche zeichnen. Wir können dazu die Methode `DrawContext.drawText(...)` verwenden. + +@[code lang=java transcludeWith=:::7](@/reference/latest/src/client/java/com/example/docs/rendering/DrawContextExampleScreen.java) + +![Einen Text zeichnen](/assets/develop/rendering/draw-context-text.png) diff --git a/versions/1.20.4/translated/de_de/develop/rendering/gui/custom-screens.md b/versions/1.20.4/translated/de_de/develop/rendering/gui/custom-screens.md new file mode 100644 index 000000000..ef0a01208 --- /dev/null +++ b/versions/1.20.4/translated/de_de/develop/rendering/gui/custom-screens.md @@ -0,0 +1,64 @@ +--- +title: Benutzerdefinierte Oberflächen +description: Lerne, wie man benutzerdefinierte Oberflächen für deinen Mod erstellt. +authors: + - IMB11 +--- + +# Benutzerdefinierte Oberflächen + +:::info +Diese Seite bezieht sich auf normale Oberflächen, nicht auf solche, die vom Spieler auf dem Client geöffnet werden, und nicht auf solche, die vom Server bearbeitet werden. +::: + +Oberflächen sind im Wesentlichen die grafischen Oberflächen, mit denen der Spieler interagiert, zum Beispiel der Titelbildschirm, der Pausenbildschirm usw. + +Du kannst deine eigenen Oberflächen erstellen, um benutzerdefinierte Inhalte, ein benutzerdefiniertes Einstellungsmenü und vieles mehr anzuzeigen. + +## Eine Oberfläche erstellen + +Um eine Oberfläche zu erstellen, musst du die `Screen`-Klasse erweitern und die `init`-Methode überschreiben. + +Folgendes solltest du beachten: + +- Widgets werden nicht im Konstruktor erstellt, weil die Oberfläche zu diesem Zeitpunkt noch nicht initialisiert ist - und bestimmte Variablen, wie `width` (Breite) und `height` (Höhe), sind noch nicht verfügbar oder noch nicht genau. +- Die `init`-Methode wird aufgerufen, wenn die Oberfläche initialisiert wird, und sie ist der beste Ort, um Widgets zu erstellen. + - Du kannst Widgets mit der Methode `addDrawableChild` hinzufügen, die jedes zeichenbare Widget akzeptiert. +- Die Methode `render` wird bei jedem Frame aufgerufen - du kannst von dieser Methode aus auf den Zeichenkontext und die Mausposition zugreifen. + +Als Beispiel können wir eine einfache Oberfläche erstellen, der eine Schaltfläche und eine Beschriftung darüber enthält. + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/client/java/com/example/docs/rendering/screens/CustomScreen.java) + +![Benutzerdefinierte Oberfläche 1](/assets/develop/rendering/gui/custom-1-example.png) + +## Die Oberfläche öffnen + +Du kannst die Oberfläche mit der `setScreen`-Methode des `MinecraftClient` öffnen - du kannst dies von vielen Stellen aus tun, wie zum Beispiel einer Tastenbindung, einem Befehl oder einem Client-Paket-Handler. + +```java +MinecraftClient.getInstance().setScreen( + new CustomScreen(Text.empty()) +); +``` + +## Die Oberfläche schließen + +Wenn du eine Oberfläche schließen möchtest, setze die Oberfläche einfach auf `null`: + +```java +MinecraftClient.getInstance().setScreen(null); +``` + +Wenn du ausgefallen sein und zum vorherigen Bildschirm zurückkehren willst, kannst du die aktuelle Oberfläche an den `CustomScreen`-Konstruktor übergeben und ihn in einem Attribut speichern und ihn dann verwenden, um zum vorherigen Bildschirm zurückzukehren, wenn die Methode `close` aufgerufen wird. + +@[code lang=java transcludeWith=:::2](@/reference/latest/src/client/java/com/example/docs/rendering/screens/CustomScreen.java) + +Jetzt kannst du beim Öffnen der benutzerdefinierten Oberfläche den aktuellen Bildschirm als zweites Argument übergeben - wenn du also `CustomScreen#close` aufrufst, wird er zur vorherigen Oberfläche zurückkehren. + +```java +Screen currentScreen = MinecraftClient.getInstance().currentScreen; +MinecraftClient.getInstance().setScreen( + new CustomScreen(Text.empty(), currentScreen) +); +``` diff --git a/versions/1.20.4/translated/de_de/develop/rendering/gui/custom-widgets.md b/versions/1.20.4/translated/de_de/develop/rendering/gui/custom-widgets.md new file mode 100644 index 000000000..b529626ea --- /dev/null +++ b/versions/1.20.4/translated/de_de/develop/rendering/gui/custom-widgets.md @@ -0,0 +1,39 @@ +--- +title: Benutzerdefinierte Widgets +description: Lerne, wie man benutzerdefinierte Widgets für deine Oberfläche erstellt. +authors: + - IMB11 +--- + +# Benutzerdefinierte Widgets + +Widgets sind im Wesentlichen in Containern untergebrachte Rendering-Komponenten, die zu einer Oberfläche hinzugefügt werden können und mit denen der Spieler durch verschiedene Ereignisse wie Mausklicks, Tastendruck usw. + +## Ein Widget erstellen + +Es gibt mehrere Möglichkeiten, eine Widget-Klasse zu erstellen, beispielsweise durch die Erweiterung von `ClickableWidget`. Diese Klasse bietet viele nützliche Funktionen, wie beispielsweise die Verwaltung von Breite, Höhe und Position sowie die Behandlung von Events. + +- `Drawable` - zum Rendern - Erforderlich, um das Widget über die Methode `addDrawableChild` in der Oberfläche zu registrieren. +- `Element` - für Events - Erforderlich, wenn du Events wie Mausklicks, Tastendrücke usw. +- `Narratable` - für die Barrierefreiheit - Erforderlich, um dein Widget für Bildschirmleser und andere Barrierefreiheitstools zugänglich zu machen. +- `Selectable` - für die Auswahl - Erforderlich, wenn du dein Widget mit der Tab-Taste auswählbar machen willst - dies hilft auch bei der Barrierefreiheit. + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/client/java/com/example/docs/rendering/screens/CustomWidget.java) + +## Das Widget zur Oberfläche hinzufügen + +Wie alle Widgets musst du es mit der Methode `addDrawableChild`, die von der Klasse `Screen` bereitgestellt wird, zur Oberfläche hinzufügen. Stelle sicher, dass du dies in der Methode `init` machst. + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/client/java/com/example/docs/rendering/screens/CustomWidget.java) + +![Ein benutzerdefiniertes Widget in einer Oberfläche](/assets/develop/rendering/gui/custom-widget-example.png) + +## Widget Events + +Du kannst Events wie Mausklicks und Tastendrücke behandeln, indem du die Methoden `onMouseClicked`, `onMouseReleased`, `onKeyPressed` und andere Methoden überschreibst. + +Du kannst zum Beispiel dafür sorgen, dass das Widget die Farbe wechselt, wenn man mit dem Mauszeiger darüber fährt, indem du die Methode `isHovered()` verwendest, die von der Klasse `ClickableWidget` bereitgestellt wird: + +@[code lang=java transcludeWith=:::2](@/reference/latest/src/client/java/com/example/docs/rendering/screens/CustomWidget.java) + +![Hover-Event Beispiel](/assets/develop/rendering/gui/custom-widget-events.webp) diff --git a/translated/de_de/develop/rendering/hud.md b/versions/1.20.4/translated/de_de/develop/rendering/hud.md similarity index 100% rename from translated/de_de/develop/rendering/hud.md rename to versions/1.20.4/translated/de_de/develop/rendering/hud.md diff --git a/versions/1.20.4/translated/de_de/develop/rendering/particles/creating-particles.md b/versions/1.20.4/translated/de_de/develop/rendering/particles/creating-particles.md new file mode 100644 index 000000000..bbb00436f --- /dev/null +++ b/versions/1.20.4/translated/de_de/develop/rendering/particles/creating-particles.md @@ -0,0 +1,72 @@ +--- +title: Benutzerdefinierte Partikel erstellen +description: Lerne, wie man benutzerdefinierte Partikel mit der Fabric API erstellt. +authors: + - Superkat32 +--- + +# Benutzerdefinierte Partikel erstellen + +Partikel sind ein mächtiges Werkzeug. Sie können einer schönen Szene Atmosphäre oder einem spannenden Kampf gegen einen Endgegner mehr Spannung verleihen. Lasst uns einen hinzufügen! + +## Einen benutzerdefinierten Partikel registrieren + +Wir werden einen neuen Glitzerpartikel hinzufügen, der die Bewegung eines Partikels des Endstabs nachahmt. + +Zuerst müssen wir mit deiner Mod-Id einen `ParticleType` in deiner Mod-Initialisierungsklasse registrieren. + +@[code lang=java transcludeWith=#particle_register_main](@/reference/latest/src/main/java/com/example/docs/FabricDocsReference.java) + +Der "sparkle_particle" in Kleinbuchstaben ist der JSON-Pfad für die Textur des Partikels. Du wirst später eine neue JSON-Datei mit genau diesem Namen erstellen. + +## Client-seitige Registrierung + +Nachdem du den Partikel im `ModInitializer` Einstiegspunkt registriert hast, musst du den Partikel auch im `ClientModInitializer` Einstiegspunkt registrieren. + +@[code lang=java transcludeWith=#particle_register_client](@/reference/latest/src/client/java/com/example/docs/FabricDocsReferenceClient.java) + +In diesem Beispiel registrieren wir unseren Partikel Client-seitig. Dann geben wir dem Partikel ein wenig Bewegung, indem wir die Factory des Endstabpartikels benutzen. Das bedeutet, dass sich unser Partikel genau wie ein Partikel eines Endstabs bewegt. + +::: tip +You can see all the particle factories by looking at all the implementations of the `ParticleFactory` interface. This is helpful if you want to use another particle's behaviour for your own particle. + +- IntelliJ's Tastaturkürzel: Strg+Alt+B +- Visual Studio Codes Hotkey: Strg+F12 +::: + +## Eine JSON Datei erstellen und Texturen hinzufügen + +Du musst 2 Ordner in deinem `resources/assets//` Ordner erstellen. + +| Ordnerpfad | Erklärung | +| -------------------- | ---------------------------------------------------------------------------------------------------- | +| `/textures/particle` | Der Ordner `particle` wird jegliche Texturen für alle deine Partikel enthalten. | +| `/particles` | Der Ordner `particles` wird jegliche JSON-Dateien für alle deine Partikel enthalten. | + +Für dieses Beispiel werden wir nur eine Textur in `textures/particle` haben, die "sparkle_particle_texture.png" heißt. + +Als nächstes erstelle eine neue JSON-Datei in `particles` mit demselben Namen wie der JSON-Pfad, den du bei der Registrierung deines ParticleType verwendet hast. Für dieses Beispiel müssen wir `sparkle_particle.json` erstellen. Diese Datei ist wichtig, weil sie Minecraft wissen lässt, welche Texturen unsere Partikel verwenden sollen. + +@[code lang=json](@/reference/latest/src/main/resources/assets/fabric-docs-reference/particles/sparkle_particle.json) + +:::tip +Du kannst weitere Texturen in das Array `textures` einfügen, um eine Partikelanimation zu erstellen. Der Partikel durchläuft die Texturen im Array, beginnend mit der ersten Textur. +::: + +## Den neuen Partikel testen + +Sobald du die JSON-Datei fertiggestellt und deine Arbeit gespeichert hast, kannst du Minecraft starten und alles testen! + +Du kannst überprüfen, ob alles funktioniert hat, indem du den folgenden Befehl eingibst: + +```mcfunction +/particle :sparkle_particle ~ ~1 ~ +``` + +![Vorführung des Partikels](/assets/develop/rendering/particles/sparkle-particle-showcase.png) + +:::info +Mit diesem Befehl wird der Partikel im Spieler erzeugt. Du wirst möglicherweise rückwärts gehen müssen, um ihn zu sehen. +::: + +Alternativ kannst du auch einen Befehlsblock verwenden, um den Partikel mit genau demselben Befehl zu erzeugen. diff --git a/versions/1.20.4/translated/de_de/develop/sounds/custom.md b/versions/1.20.4/translated/de_de/develop/sounds/custom.md new file mode 100644 index 000000000..92e431b05 --- /dev/null +++ b/versions/1.20.4/translated/de_de/develop/sounds/custom.md @@ -0,0 +1,63 @@ +--- +title: Benutzerdefinierte Sounds erstellen +description: Lerne, wie man neue Sounds mit einer Registry hinzufügt und nutzt. +authors: + - JR1811 +--- + +# Benutzerdefinierte Sounds erstellen + +## Vorbereitung der Audio-Datei + +Deine Audio-Dateien müssen auf eine bestimmte Weise formatiert werden. OGG Vorbis ist ein offenes Containerformat für Multimediadaten, wie zum Beispiel Audio, und wird für die Sounddateien von Minecraft verwendet. Um Probleme mit der Distanzierung in Minecraft zu vermeiden, darf deine Audio nur einen einzigen Kanal besitzen (Mono). + +Viele moderne DAWs (Digital Audio Workstation) können dieses Dateiformat importieren und exportieren. Im folgenden Beispiel wird die freie und Open Source Software "[Audacity](https://www.audacityteam.org/)" verwendet, um die Audio-Datei in das richtige Format zu bringen, aber auch jede andere DAW sollte ausreichen. + +![Unvorbereitete Audiodatei in Audacity](/assets/develop/sounds/custom_sounds_0.png) + +In diesem Beispiel wird ein [Pfeifton](https://freesound.org/people/strongbot/sounds/568995/) in Audacity importiert. Sie ist derzeit als `.wav`-Datei gespeichert und hat zwei Audiokanäle (Stereo). Bearbeite den Sound nach deinem Geschmack und stelle sicher, dass du einen der Kanäle mit dem Dropdown-Element oben im "Spurkopf" löschst. + +![Aufteilung der Stereospur](/assets/develop/sounds/custom_sounds_1.png) + +![Löschen von einem der Kanäle](/assets/develop/sounds/custom_sounds_2.png) + +Achte beim Exportieren oder Rendern der Audio-Datei darauf, dass du das Dateiformat OGG wählst. REAPER, unterstützen mehrere OGG-Audio-Layer-Formate. In diesem Fall sollte OGG Vorbis sehr gut funktionieren. + +![Export als OGG-Datei](/assets/develop/sounds/custom_sounds_3.png) + +Denke auch daran, dass Audio-Dateien die Dateigröße deines Mods drastisch erhöhen können. Falls erforderlich, komprimiere die Audiodaten beim Bearbeiten und Exportieren der Datei, um die Dateigröße des fertigen Produkts so gering wie möglich zu halten. + +## Laden der Audio-Datei + +Füge das neue Verzeichnis `resources/assets//sounds` für die Sounds in deinem Mod hinzu, und lege die exportierte Audio-Datei `metal_whistle.ogg` dort hinein. + +Fahre mit der Erstellung der Datei `resources/assets//sounds.json` fort, falls sie noch nicht existiert und füge deinen Sound zu den Sound-Einträgen hinzu. + +@[code lang=json](@/reference/latest/src/main/resources/assets/fabric-docs-reference/sounds.json) + +Der Untertiteleintrag bietet dem Spieler mehr Kontext. Der Name des Untertitels wird in den Sprachdateien im Verzeichnis `resources/assets//lang` verwendet und wird angezeigt, wenn die Untertitel-Einstellung im Spiel aktiviert ist und dieser benutzerdefinierte Sound abgespielt wird. + +## Registrieren des benutzerdefinierten Sounds + +Um den benutzerdefinierten Sound zum Mod hinzuzufügen, registriere ein SoundEvent in der Klasse, die den `ModInitializer`-Einstiegspunkt implementiert. + +```java +Registry.register(Registries.SOUND_EVENT, new Identifier(MOD_ID, "metal_whistle"), + SoundEvent.of(new Identifier(MOD_ID, "metal_whistle"))); +``` + +## Das Chaos aufräumen + +Je nachdem, wie viele Einträge in der Registry vorhanden sind, kann dies schnell unübersichtlich werden. Um dies zu vermeiden, können wir eine neue Hilfsklasse verwenden. + +Füge zwei neue Methoden zu der neu erstellten Hilfsklasse hinzu. Eine, die alle Sounds registriert, und eine, die dazu dient, diese Klasse überhaupt erst zu initialisieren. Danach kannst du bequem neue benutzerdefinierte statische Klassenvariablen der Klasse `SoundEvent` nach Bedarf hinzufügen. + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/sound/CustomSounds.java) + +Auf diese Weise muss die `ModInitializer` implementierende Einstiegsklasse nur eine Zeile implementieren, um alle benutzerdefinierten SoundEvents zu registrieren. + +@[code lang=java transcludeWith=:::2](@/reference/latest/src/main/java/com/example/docs/sound/FabricDocsReferenceSounds.java) + +## Das benutzerdefinierte SoundEvent nutzen + +Verwende die Hilfsklasse, um auf das benutzerdefinierte SoundEvent zuzugreifen. Auf der Seite [SoundEvents abspielen](./using-sounds) erfährst du, wie man Sounds abspielt. diff --git a/versions/1.20.4/translated/de_de/develop/sounds/using-sounds.md b/versions/1.20.4/translated/de_de/develop/sounds/using-sounds.md new file mode 100644 index 000000000..8098978a2 --- /dev/null +++ b/versions/1.20.4/translated/de_de/develop/sounds/using-sounds.md @@ -0,0 +1,32 @@ +--- +title: SoundEvents abspielen +description: Lerne, wie man Sound Events abspielt. +--- + +# SoundEvents abspielen + +Minecraft hat eine große Auswahl an Sounds, aus denen du wählen kannst. Schau dir die Klasse `SoundEvents` an, um alle von Mojang bereitgestellten Vanilla-Sound-Event-Instanzen zu sehen. + +## Sounds in deinem Mod verwenden + +Stelle sicher, dass du die Methode `playSound()` auf der logischen Serverseite ausführst, wenn du Sounds verwendest! + +In diesem Beispiel wird die Methode `useOnEntity()` und `useOnBlock()` für ein benutzerdefiniertes interaktives Element verwendet, um einen "platzierenden Kupferblock" und einen Plünderer-Sound abzuspielen. + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/item/CustomSoundItem.java) + +Die Methode `playSound()` wird mit dem Objekt `LivingEntity` verwendet. Nur das SoundEvent, die Lautstärke und die Tonhöhe müssen angegeben werden. Du kannst auch die Methode `playSound()` aus der Weltinstanz verwenden, um ein höheres Maß an Kontrolle zu haben. + +@[code lang=java transcludeWith=:::2](@/reference/latest/src/main/java/com/example/docs/item/CustomSoundItem.java) + +### SoundEvent und SoundCategory + +Das SoundEvent legt fest, welcher Sound abgespielt wird. Du kannst auch [deine eigenen SoundEvents registrieren](./custom), um deinen eigenen Sound einzubinden. + +Minecraft hat mehrere Audio-Schieberegler in den Spieleinstellungen. Das Enum `SoundCategory` wird verwendet, um zu bestimmen, mit welchem Schieberegler die Lautstärke des Sounds eingestellt wird. + +### Lautstärke und Tonhöhe + +Der Lautstärke-Parameter kann ein wenig irreführend sein. Im Bereich von `0.0f - 1.0f` kann die aktuelle Lautstärke des Tons verändert werden. Wenn die Zahl größer ist, wird die Lautstärke von `1.0f` verwendet und nur die Entfernung, in der der Ton zu hören ist, wird angepasst. Die Blockdistanz kann grob durch `Volumen * 16` berechnet werden. + +Der Pitch-Parameter erhöht oder verringert den Wert der Tonhöhe und ändert auch die Dauer des Sounds. Im Bereich von `(0.5f - 1.0f)` wird die Tonhöhe und die Geschwindigkeit verringert, während größere Zahlen die Tonhöhe und die Geschwindigkeit erhöhen. Zahlen unter `0.5f` bleiben auf dem Wert der Tonhöhe von `0.5f`. diff --git a/versions/1.20.4/translated/de_de/index.md b/versions/1.20.4/translated/de_de/index.md new file mode 100644 index 000000000..8f0f0ca66 --- /dev/null +++ b/versions/1.20.4/translated/de_de/index.md @@ -0,0 +1,27 @@ +--- +title: Fabric Dokumentation +description: Die offizielle kuratierte Dokumentation für Fabric, einer Modding-Toolchain für Minecraft. +layout: home +hero: + name: Fabric Dokumentation + tagline: Die offizielle kuratierte Dokumentation für Fabric, einer Modding-Toolchain für Minecraft. +features: + - title: Leitfäden für Entwickler + icon: 🛠️ + details: Unsere kuratierten, von der Community verfassten Leitfäden für Entwickler decken ein breites Spektrum an Themen ab, von der Einrichtung einer Entwicklungsumgebung bis hin zu fortgeschrittenen Themen wie Rendering und Networking. + link: ./develop/index + linkText: Loslegen + - title: Leitfäden für Spieler + icon: 📚 + details: Bist du ein Spieler, der Mods verwenden möchte, die von Fabric unterstützt werden? Unsere Spieler-Leitfäden decken alles ab. Diese Anleitungen werden dir beim Herunterladen, Installieren und Beheben von Problemen mit Fabric-Mods helfen. + link: ./players/index + linkText: Weiterlesen +--- + +
+ +## Möchtest du einen Beitrag leisten? + +Wenn du zur Fabric-Dokumentation beitragen möchtest, findest du den Quellcode auf [GitHub](https://github.com/FabricMC/fabric-docs), und die entsprechenden [Beitragsrichtlinien](./contributing) + +
diff --git a/versions/1.20.4/translated/de_de/navbar_translations.json b/versions/1.20.4/translated/de_de/navbar_translations.json new file mode 100644 index 000000000..789db58b8 --- /dev/null +++ b/versions/1.20.4/translated/de_de/navbar_translations.json @@ -0,0 +1,8 @@ +{ + "title": "Fabric Dokumentation", + "home": "Startseite", + "download": "Herunterladen", + "contribute": "Mitwirken", + "contribute.api": "Fabric API", + "version_switcher": "Version wechseln" +} \ No newline at end of file diff --git a/versions/1.20.4/translated/de_de/players/faq.md b/versions/1.20.4/translated/de_de/players/faq.md new file mode 100644 index 000000000..c0d59a10d --- /dev/null +++ b/versions/1.20.4/translated/de_de/players/faq.md @@ -0,0 +1,31 @@ +--- +title: Häufig gestellte Fragen für Spieler +description: Häufig gestellte Fragen für Spieler und Serveradministratoren in Bezug auf Fabric. +--- + +# Häufig gestellte Fragen + +Es gibt viele Fragen, die häufig gestellt werden, deshalb haben wir hier eine Liste dieser Fragen zusammengestellt. + +## Allgemeine Fragen + +### Welche Minecraft Versionen werden von Fabric unterstützt? + +Offiziell unterstützt Fabric alle Minecraft-Versionen, beginnend mit Snapshot `18w43b` und höher, sowie Vollversionen beginnend mit Version `1.14` und höher. + +### Wo kann ich veröffentlichte Fabric-Mods herunterladen? + +:::info +Du solltest immer prüfen, ob Mods aus einer vertrauenswürdigen Quelle stammen. Weitere Informationen zum Finden von Mods findest du in dem Leitfaden [Vertrauenswürdige Mods finden](./finding-mods). +::: + +Die meisten Autoren veröffentlichen ihre Mods auf [Modrinth](https://modrinth.com/mods?g=categories:%27fabric%27) und [CurseForge](https://www.curseforge.com/minecraft/search?class=mc-mods&gameVersionTypeId=4), manche laden sie jedoch auch auf ihre persönliche Website oder auf andere Plattformen wie GitHub hoch. + +### Wo kann ich vorgemachte Fabric-Modpacks herunterladen? + +Du kannst vorgefertigte Fabric-Modpacks auf einer Vielzahl von Plattformen finden, beispielsweise: + +- [Modrinth](https://modrinth.com/modpacks?g=categories:%27fabric%27) +- [CurseForge](https://www.curseforge.com/minecraft/search?class=modpacks&gameVersionTypeId=4) +- [Feed The Beast](https://www.feed-the-beast.com/ftb-app) +- [Technic](https://www.technicpack.net/modpacks) diff --git a/versions/1.20.4/translated/de_de/players/finding-mods.md b/versions/1.20.4/translated/de_de/players/finding-mods.md new file mode 100644 index 000000000..bee3a6f2b --- /dev/null +++ b/versions/1.20.4/translated/de_de/players/finding-mods.md @@ -0,0 +1,34 @@ +--- +title: Vertrauenswürdige Mods finden +description: Eine Anleitung, wie man Fabric-Mods in vertrauenswürdigen Quellen findet. +authors: + - IMB11 +--- + +# Vertrauenswürdige Mods finden + +Zu Beginn, Vertrauen ist subjektiv, du solltest beim Herunterladen von Mods immer nach eigenem Ermessen handeln. Hier sind ein paar Dinge, die dir helfen können, vertrauenswürdige Mods zu finden. + +## 1. Nutze eine Quelle, die bekanntermaßen vertrauenswürdig ist + +Die meisten Autoren veröffentlichen ihre Mods auf [Modrinth](https://modrinth.com/mods?g=categories:%27fabric%27) und [CurseForge](https://www.curseforge.com/minecraft/search?class=mc-mods&gameVersionTypeId=4). + +Diese Webseiten prüfen, dass die Mods tun, was sie versprechen und, dass sie keinen bösartigen Code enthalten. Du kannst auf diesen Webseiten auch bösartige Mods melden, und sie werden ziemlich schnell Maßnahmen ergreifen. + +## 2. Frage bei Anderen nach! + +Wenn du eine Mod von einer nicht bekanntermaßen vertrauenswürdigen Quelle herunterlädst, solltest du bei Anderen nachfragen, um zu prüfen, ob sie die Mod vorher von der gleichen Seite heruntergeladen haben und ob sie Probleme damit hatten. + +Frag im Zweifel gerne im [Fabric Discord](https://discord.gg/v6v4pMv) im Kanal `#player-support` nach. + +## 3. Vermeide bekannte Schadware-Seiten! + +:::info +Schadware-Seiten sind nicht für jeden offensichtlich. Falls du dir unsicher bist, solltest du dich nach Meinungen Anderer erkunden, oder die Seite meiden und dich nur auf vertrauenswürdige Quellen verlassen, wie Modrinth und CurseForge. +::: + +Es gibt viele Webseiten, die behaupten, sie hätten Mods für Minecraft, obwohl sie in Wirklichkeit nur Schadware-Seiten sind. Diese Seiten solltest du in jedem Fall vermeiden. + +Du kannst Antiviren-Software und Websites wie [Windows Defender](https://www.microsoft.com/en-us/windows/comprehensive-security) oder [VirusTotal](https://www.virustotal.com/) verwenden, um die heruntergeladenen Mods zu überprüfen. Verlass dich aber nicht vollständig auf diese Methoden, da sie manchmal falsche Ergebnisse liefern. + +Nochmal, frag im Zweifel gerne im [Fabric Discord](https://discord.gg/v6v4pMv) im Kanal `#player-support` nach der Meinung Anderer. diff --git a/versions/1.20.4/translated/de_de/players/index.md b/versions/1.20.4/translated/de_de/players/index.md new file mode 100644 index 000000000..87d7e8f6a --- /dev/null +++ b/versions/1.20.4/translated/de_de/players/index.md @@ -0,0 +1,12 @@ +--- +title: Leitfäden für Spieler +description: Eine Sammlung von Anleitungen für Spieler und Serveradministratoren über die Installation und Nutzung von Fabric. +--- + +# Leitfäden für Spieler + +Dieser Abschnitt der Fabric-Dokumentation ist an Spieler und Serveradministratoren gerichtet, die lernen wollen, wie Fabric installiert und genutzt wird und wie Probleme mit Fabric behoben werden können. + +Die Seitenleiste enthält eine Liste mit allen verfügbaren Anleitungen. + +Falls dir Fehler mit der Dokumentation auffallen, bitte melde sie [auf GitHub](https://github.com/FabricMC/fabric-docs) oder falls Fehler auftreten sollten, frage im [Fabric-Discord](https://discord.gg/v6v4pMv) im Kanal `#player-support` oder `#server-admin-support` nach Hilfe. diff --git a/versions/1.20.4/translated/de_de/players/installing-fabric.md b/versions/1.20.4/translated/de_de/players/installing-fabric.md new file mode 100644 index 000000000..fef41ab65 --- /dev/null +++ b/versions/1.20.4/translated/de_de/players/installing-fabric.md @@ -0,0 +1,55 @@ +--- +title: Installation von Fabric +description: Eine Schritt-für-Schritt-Anleitung zur Installation von Fabric. +authors: + - IMB11 +--- + +# Installation von Fabric + +Diese Anleitung wird die Installation von Fabric detailliert für den offiziellen Minecraft-Launcher erklären. + +Für die Launcher von Drittanbietern solltest du deren Dokumentation verwenden. + +## 1. Herunterladen des Fabric-Installers + +Der Fabric-Installer kann von der [Fabric-Webseite](https://fabricmc.net/use/) heruntergeladen werden. + +Wenn du Windows verwendest, lade die `.exe`-Version (`Download For Windows`) herunter, da sie keine Java-Installation auf dem System benötigt. Stattdessen wird die Java-Installation des offiziellen Launchers verwendet. + +Für macOS und Linux solltest du die `.jar`-Version verwenden. Manchmal musst du Java vor diesem Schritt installieren. + +## 2. Ausführen des Fabric-Installers + +:::warning +Schließe zuerst Minecraft und den Minecraft-Launcher vor Beginn der Installation. +::: + +:::details Informationen für macOS-Nutzer + +Auf macOS musst du möglicherweise zuerst einen Rechtsklick auf die `.jar`-Datei im Downloads-Verzeichnis machen, und `Öffnen` zum Ausführen klicken. + +![MacOS Kontextmenü im Fabric-Installer](/assets/players/installing-fabric/macos-downloads.png) + +Bei der Frage "Möchten Sie es wirklich öffnen?", klicke erneut auf `Öffnen`. +::: + +Wenn du den Installer geöffnet hast, sollte diese Oberfläche erscheinen: + +![Fabric-Installer mit "Installieren" hervorgehoben](/assets/players/installing-fabric/installer-screen.png) + +Um Fabric zu installieren, wähle einfach die Spielversion aus der Liste und klicke installieren. + +**Stelle sicher, dass die Option 'Profil erstellen' aktiviert ist.** + +## 3. Du hast es geschafft! + +Sobald das Installationsprogramm fertig ist, kannst du den Minecraft-Launcher öffnen und das Fabric-Profil aus der Liste in der unteren linken Ecke auswählen und spielen! + +![Minecraft-Launcher mit ausgewähltem Fabric-Profil](/assets/players/installing-fabric/launcher-screen.png) + +## Nächste Schritte + +Jetzt, nachdem du Fabric installiert hast, kannst du dem Spiel Mods hinzufügen! Weitere Informationen zum Finden von Mods findest du in dem Leitfaden [Vertrauenswürdige Mods finden](./finding-mods). + +Fall dir beim Folgen dieser Anleitungen irgendwelche Fehler auftreten, kannst du nach Hilfe im [Fabric-Discord](https://discord.gg/v6v4pMv) im Kanal `#player-support` fragen. diff --git a/versions/1.20.4/translated/de_de/players/installing-java/linux.md b/versions/1.20.4/translated/de_de/players/installing-java/linux.md new file mode 100644 index 000000000..8a36a09c5 --- /dev/null +++ b/versions/1.20.4/translated/de_de/players/installing-java/linux.md @@ -0,0 +1,91 @@ +--- +title: Java auf Linux installieren +description: Eine Schritt-für-Schritt-Anleitung zur Installation von Java auf Linux. +authors: + - IMB11 +--- + +# Java auf Linux installieren + +Diese Anleitung führt Sie durch die Installation von Java 17 auf Linux. + +## 1. Überprüfen, ob Java bereits installiert ist + +Öffne ein Terminal und gib `java -version` ein, drücke anschließend Enter. + +![Kommandozeile mit "java -version"](/assets/players/installing-java/linux-java-version.png) + +:::warning +Um den Großteil der modernen Minecraft-Versionen nutzen zu können, musst du Java 17 installiert haben. Wenn der Befehl eine Version niedriger als 17 anzeigt, musst du deine bestehende Java-Installation aktualisieren. +::: + +## 2. Java 17 herunterladen und installieren + +Wir empfehlen OpenJDK 17, welches auf den meisten Linux-Distributionen verfügbar ist. + +### Arch Linux + +:::info +Für mehr Informationen über die Installation von Java auf Arch Linux, schaue in das [Arch Linux Wiki](https://wiki.archlinux.org/title/Java). +::: + +Du kannst die aktuellste JRE aus den offiziellen Repositories installieren: + +```sh +sudo pacman -S jre-openjdk +``` + +Wenn du einen Server betreibst, für den du keine grafische Oberfläche benötigst, kannst du stattdessen die Headless-Version installieren: + +```sh +sudo pacman -S jre-openjdk-headless +``` + +Wenn du planst Mods zu entwickeln, brauchst du stattdessen die JDK: + +```sh +sudo pacman -S jdk-openjdk +``` + +### Debian/Ubuntu + +Du kannst Java 17 über `apt` mit dem folgenden Befehl installieren: + +```sh +sudo apt update +sudo apt install openjdk-17-jdk +``` + +### Fedora + +Du kannst Java 17 über `dnf` mit dem folgenden Befehl installieren: + +```sh +sudo dnf install java-17-openjdk +``` + +Wenn du keine grafische Oberfläche benötigst, kannst du stattdessen die Headless-Version installieren: + +```sh +sudo dnf install java-17-openjdk-headless +``` + +Wenn du planst Mods zu entwickeln, brauchst du stattdessen die JDK: + +```sh +sudo dnf install java-17-openjdk-devel +``` + +### Andere Linux Distributionen + +Wenn deine Distribution oben nicht gelistet ist, kannst du die aktuellste JRE von [Adoptium](https://adoptium.net/temurin/) herunterladen + +Du solltest einen alternativen Leitfaden für deine Distribution verwenden, wenn du Mods entwickeln willst. + +## 3. Verifizieren, dass Java 17 installiert ist + +Sobald die Installation abgeschlossen ist, kannst du überprüfen, ob Java 17 installiert ist, indem du die Kommandozeile erneut öffnest und "java -version" eingibst. + +Wenn der Befehl erfolgreich ausgeführt wird, wird die Java-Version wie zuvor gezeigt angezeigt: + +![Kommandozeile mit "java -version"](/assets/players/installing-java/linux-java-version.png) diff --git a/versions/1.20.4/translated/de_de/players/installing-java/windows.md b/versions/1.20.4/translated/de_de/players/installing-java/windows.md new file mode 100644 index 000000000..3393cead6 --- /dev/null +++ b/versions/1.20.4/translated/de_de/players/installing-java/windows.md @@ -0,0 +1,65 @@ +--- +title: Java auf Windows installieren +description: Eine Schritt-für-Schritt-Anleitung zur Installation von Java auf Windows. +authors: + - IMB11 +--- + +# Java auf Windows installieren + +Diese Anleitung führt Sie durch die Installation von Java 17 auf Windows. + +Der Minecraft Launcher kommt bereits mit seiner eigenen Java Installation, diese Sektion ist also nur relevant, wenn Sie den Fabric `.jar` basierten Installer verwenden möchten oder wenn Sie die Minecraft Server `.jar` verwenden möchten. + +## 1. Überprüfen, ob Java bereits installiert ist + +Um zu überprüfen, ob Java bereits installiert ist, öffnen Sie die Kommandozeile. + +Drücken Sie Win + R und geben Sie `cmd.exe` in das Feld ein. + +![Windows-Ausführungsdialog mit "cmd.exe" in der Ausführungsleiste](/assets/players/installing-java/windows-run-dialog.png) + +Wenn Sie die Kommandozeile geöffnet haben, geben Sie `java -version` ein und drücken Enter. + +Wenn der Befehl erfolgreich ausgeführt wird, sollten Sie folgendes sehen. Wenn der Befehl fehlgeschlagen ist, fahren Sie mit dem nächsten Schritt fort. + +![Kommandozeile mit "java -version"](/assets/players/installing-java/windows-java-version.png) + +:::warning +Um den Großteil der modernen Minecraft-Versionen nutzen zu können, musst du Java 17 installiert haben. Wenn der Befehl eine Version niedriger als 17 anzeigt, musst du deine bestehende Java-Installation aktualisieren. +::: + +## 2. Herunterladen des Java 17 Installer + +Um Java 17 zu installieren, laden Sie bitte den Installer von [Adoptium](https://adoptium.net/en-GB/temurin/releases/?os=windows&package=jdk&version=17) herunter. + +Sie müssen die Version "Windows Installer (.msi)" herunterladen: + +![Adoptium Download-Seite mit hervorgehobenem Windows Installer (.msi)](/assets/players/installing-java/windows-download-java.png) + +Sie sollten `x86` wählen, wenn Sie ein 32-Bit-Betriebssystem haben, oder `x64`, wenn Sie ein 64-Bit-Betriebssystem haben. + +Die meisten modernen Computer sind mit einem 64-Bit-Betriebssystem ausgestattet. Wenn Sie sich unsicher sind, versuchen Sie es mit dem 64-Bit-Download. + +## 3. Installer starten! + +Folgen Sie den Schritten des Installationsprogramms, um Java 17 zu installieren. Wenn Sie diese Seite erreichen, sollten Sie die folgenden Funktionen auf "Die gesamte Funktion wird auf der lokalen Festplatte installiert" einstellen: + +- `JAVA_HOME Umgebungsvariable setzen` - Diese wird zu Ihrem PATH hinzugefügt. +- JavaSoft (Oracle)-Registrierungsschlüssel + +![Java 17-Installationsprogramm mit "JAVA_HOME-Variable setzen" und "JavaSoft (Oracle) Registrierungsschlüssel" hervorgehoben](/assets/players/installing-java/windows-wizard-screenshot.png) + +Wenn Sie das getan haben, können Sie `Weiter` klicken und mit der Installation fortfahren. + +## 4. Verifizieren, dass Java 17 installiert ist + +Sobald die Installation abgeschlossen ist, können Sie überprüfen, ob Java 17 installiert ist, indem Sie die Kommandozeile erneut öffnen und "java -version" eingeben. + +Wenn der Befehl erfolgreich ausgeführt wird, wird die Java-Version wie zuvor gezeigt angezeigt: + +![Kommandozeile mit "java -version"](/assets/players/installing-java/windows-java-version.png) + +--- + +Sollten Sie auf Probleme stoßen, können Sie im [Fabric Discord](https://discord.gg/v6v4pMv) im Channel `#player-support` um Hilfe bitten. diff --git a/versions/1.20.4/translated/de_de/players/installing-mods.md b/versions/1.20.4/translated/de_de/players/installing-mods.md new file mode 100644 index 000000000..622b91fb6 --- /dev/null +++ b/versions/1.20.4/translated/de_de/players/installing-mods.md @@ -0,0 +1,67 @@ +--- +title: Mods installieren +description: Eine Schritt-für-Schritt-Anleitung zur Installation von Mods für Fabric. +authors: + - IMB11 +--- + +# Mods installieren + +Diese Anleitung wird die Installation von Mods für Fabric detailliert für den Minecraft-Launcher erklären. + +Für die Launcher von Drittanbietern solltest du deren Dokumentation verwenden. + +## 1. Herunterladen der Mod + +:::warning +Du solltest Mods nur aus Quellen herunterladen, denen du vertraust. Weitere Informationen zum Finden von Mods findest du iim Leitfaden [Vertrauenswürdige Mods finden](./finding-mods). +::: + +Die meisten Mods benötigen auch die Fabric API, die von [Modrinth](https://modrinth.com/mod/fabric-api) oder [CurseForge](https://curseforge.com/minecraft/mc-mods/fabric-api) heruntergeladen werden kann. + +Stelle beim Herunterladen von Mods sicher, dass: + +- Sie auf der Version von Minecraft funktionieren, auf der du spielen möchtest. Eine Mod, die beispielsweise auf der Version 1.20 funktioniert, muss nicht auf der Version 1.20.2 funktionieren. +- Sie für Fabric sind und nicht für einen anderen Mod-Loader. +- Sie für die korrekte Edition von Minecraft sind (Java Edition). + +## 2. Verschieben der Mod in das Verzeichnis `mods` + +Das Mods-Verzeichnis kann, abhängig vom Betriebssystem, an den folgenden Stellen gefunden werden. + +Normalerweise können die Pfade direkt in der Adressleiste des Dateiexplorers eingefügt werden, um schnell zum Verzeichnis zu navigieren. + +::: code-group + +```:no-line-numbers [Windows] +%appdata%\.minecraft\mods +``` + +```:no-line-numbers [macOS] +~/Library/Application Support/minecraft/mods +``` + +```:no-line-numbers [Linux] +~/.minecraft/mods +``` + +::: + +Sobald du das `mods`-Verzeichnis gefunden hast, kannst du die `.jar`-Dateien der Mods dorthin verschieben. + +![Installierte Mods im mods-Verzeichnis](/assets/players/installing-mods.png) + +## 3. Du hast es geschafft! + +Sobald du die Mods in das `mods`-Verzeichnis verschoben hast, kannst du den Minecraft-Launcher öffnen und das Fabric-Profil aus der Liste in der unteren linken Ecke auswählen und spielen! + +![Minecraft-Launcher mit ausgewähltem Fabric-Profil](/assets/players/installing-fabric/launcher-screen.png) + +## Problembehandlung + +Fall dir beim Folgen dieser Anleitungen irgendwelche Fehler auftreten, kannst du nach Hilfe im [Fabric-Discord](https://discord.gg/v6v4pMv) im Kanal `#player-support` fragen. + +Du kannst auch versuchen, das Problem mit diesen Fehlerbehebungs-Seiten selbst zu lösen: + +- [Absturzberichte](./troubleshooting/crash-reports) +- [Logs hochladen](./troubleshooting/uploading-logs) diff --git a/versions/1.20.4/translated/de_de/players/troubleshooting/crash-reports.md b/versions/1.20.4/translated/de_de/players/troubleshooting/crash-reports.md new file mode 100644 index 000000000..928d0c971 --- /dev/null +++ b/versions/1.20.4/translated/de_de/players/troubleshooting/crash-reports.md @@ -0,0 +1,104 @@ +--- +title: Absturzberichte +description: Erfahre, wie mit Absturzberichten umzugehen ist, und wie man sie liest. +authors: + - IMB11 +--- + +# Absturzberichte + +:::tip +Falls du Schwierigkeiten hast, den Grund für einen Absturz herauszufinden, frage im [Fabric Discord](https://discord.gg/v6v4pMv) im Kanal `#player-support` oder `#server-admin-support` nach Hilfe. +::: + +Absturzberichte sind ein sehr wichtiger Teil, um Probleme mit deinem Spiel oder Server zu beheben. Sie enthalten viele Informationen über den Absturz und können beim Finden der Ursache für den Absturz hilfreich sein. + +## Absturzberichte finden + +Absturzberichte werden im `crash-reports`-Verzeichnis in deinem Spiel-Verzeichnis gespeichert. Falls du einen Server nutzt, sind sie im `crash-reports`-Verzeichnis im Server-Verzeichnis. + +Für Launcher von Drittanbietern solltest du deren Dokumentation verwenden, um den Ort der Absturzberichte zu finden. + +Absturzberichte befinden sich an den folgenden Orten: + +::: code-group + +```:no-line-numbers [Windows] +%appdata%\.minecraft\crash-reports +``` + +```:no-line-numbers [macOS] +~/Library/Application Support/minecraft/crash-reports +``` + +```:no-line-numbers [Linux] +~/.minecraft/crash-reports +``` + +::: + +## Absturzberichte lesen + +Absturzberichte sind sehr lang und können verwirrend zu lesen sein. Allerdings enthalten sie viele Informationen über den Absturz, die beim Finden der Ursache sehr hilfreich sind. + +In dieser Anleitung werden wir den [folgenden Absturzbericht als Beispiel](https://github.com/FabricMC/fabric-docs/blob/main/public/assets/players/crash-report-example.txt) verwenden. + +### Abschnitte des Absturzberichts + +Absturzberichte bestehen aus mehreren Abschnitten, jeder ist mit einer Überschrift getrennt: + +- `---- Minecraft Crash Report ----`, die Zusammenfassung des Berichts. Dieser Abschnitt enthält den Hauptfehler, der den Absturz verursacht hat, den Zeitpunkt an dem das Problem aufgetreten ist und den relevanten Stacktrace. Dies ist der wichtigste Abschnitt des Absturzberichts, da der Stacktrace normalerweise Referenzen zu der Mod enthält, die den Absturz verursacht hat. +- `-- Last Reload --`, dieser Abschnitt ist nicht wirklich hilfreich, es sei denn, der Absturz ist während dem Neu-Laden von Resourcen (F3+T) aufgetreten. Dieser Abschnitt enthält den Zeitpunkt des letzten Neu-Ladens, den relevanten Stacktrace und alle Fehler, die währenddessen aufgetreten sind. Diese Fehler werden normalerweise durch Ressourcenpakete ausgelöst und können ignoriert werden, wenn sie keine Probleme mit dem Spiel verursachen. +- `-- System Details --`, dieser Abschnitt enthält Informationen über dein System, wie das Betriebssystem, die Java-Version, und die Speichermenge, die dem Spiel zugewiesen wurde. Dieser Abschnitt ist nützlich, um festzustellen, ob du die korrekte Java-Version verwendest und ob du dem Spiel genug Speicher zugewiesen hast. + - In diesem Abschnitt fügt Fabric eine eigene Zeile ein, die mit `Fabric Mods:` beginnt und darauf folgend alle installierten Mods auflistet. Dieser Abschnitt ist nützlich, um festzustellen, ob Konflikte zwischen Mods aufgetreten sein könnten. + +### Den Absturzbericht herunterbrechen + +Da wir jetzt alle Abschnitte des Absturzberichts kennengelernt haben, können wir nun beginnen, den Absturzbericht herunterzubrechen und die Ursache des Absturzes zu finden. + +Mit dem obigen verwiesenen Beispiel können wir den Absturzbericht analysieren und die Ursache für den Absturz herausfinden und welche Mods den Absturz verursachen. + +Der Stacktrace im `---- Minecraft Crash Report ----`-Abschnitt ist in diesem Fall der wichtigste, da er den Hauptfehler, der diesen Absturz verursacht, enthält. In diesem Fall ist der Fehler `java.lang.NullPointerException: Cannot invoke "net.minecraft.class_2248.method_9539()" because "net.minecraft.class_2248.field_10540" is null`. + +Mit der Anzahl an Mods, die sich in diesem Stacktrace befinden, kann es schwierig sein, den Schuldigen zu finden, aber das Erste, was zu tun ist, ist die Mod zu finden, die den Absturz verursacht. + +```:no-line-numbers +at snownee.snow.block.ShapeCaches.get(ShapeCaches.java:51) +at snownee.snow.block.SnowWallBlock.method_9549(SnowWallBlock.java:26) // [!code focus] +... +at me.jellysquid.mods.sodium.client.render.chunk.compile.pipeline.BlockOcclusionCache.shouldDrawSide(BlockOcclusionCache.java:52) +at link.infra.indium.renderer.render.TerrainBlockRenderInfo.shouldDrawFaceInner(TerrainBlockRenderInfo.java:31) +... +``` + +In diesem Fall ist die Mod, die den Absturz verursacht `snownee`, da es die erste Mod im Stacktrace ist, die erwähnt wird. + +Mit der Anzahl an erwähnten Mods kann es aber auf Kompatibilitätsprobleme zwischen den Mods hindeuten, und die Mod, die den Absturz verursacht hat, muss nicht die Schuldige sein. In diesem Fall ist es das Beste, den Absturz dem Autor zu melden und ihn den Absturz weiter untersuchen zu lassen. + +## Abstürze durch Mixins + +:::info +Mixins sind eine Möglichkeit, das Spiel zu verändern, ohne den Quellcode des Spiels zu verändern. Sie werden von vielen Mods genutzt und sind ein mächtiges Werkzeug für Mod-Entwickler. +::: + +Wenn ein Mixin abstürzt, wird normalerweise das Mixin im Stacktrace erwähnt, mit der Klasse, die das Mixin verändert. + +Mixins für Methoden enthalten `modid$handlerName` im Stacktrace, wobei `modid` die ID der Mod ist und `handlerName` der Name des Mixin-Handlers ist. + +```:no-line-numbers +... net.minecraft.class_2248.method_3821$$$modid$handlerName() ... // [!code focus] +``` + +Du kannst diese Information nutzen, um die Mod zu finden, die den Absturz verursacht und den Absturz an den Mod-Autor zu melden. + +## Was macht man mit Absturzberichten + +Das Beste, was man mit Absturzberichten machen kann, ist sie auf eine Paste-Seite hochzuladen und einen Link mit dem Mod-Autor entweder über den Issue-Tracker oder durch eine andere Art der Kommunikation (Discord etc.) zu teilen. + +Das ermöglicht es dem Mod-Autor den Absturz zu untersuchen, potenziell zu reproduzieren und das Problem zu lösen, das den Absturz verursacht hat. + +Bekannte Paste-Seiten, die oft für Absturzberichte genutzt werden, sind: + +- [GitHub Gist](https://gist.github.com/) +- [Pastebin](https://pastebin.com/) +- [MCLogs](https://mclo.gs/) diff --git a/versions/1.20.4/translated/de_de/players/troubleshooting/uploading-logs.md b/versions/1.20.4/translated/de_de/players/troubleshooting/uploading-logs.md new file mode 100644 index 000000000..d91ad9294 --- /dev/null +++ b/versions/1.20.4/translated/de_de/players/troubleshooting/uploading-logs.md @@ -0,0 +1,54 @@ +--- +title: Logs hochladen +description: Wie man Logs zur Fehlerbehebung hochlädt. +authors: + - IMB11 +--- + +# Logs hochladen + +Wenn man versucht, Fehler zu beheben, ist es oft nötig, Logs bereitzustellen, die beim Identifizieren der Ursache des Fehlers helfen. + +## Warum sollte ich Logs hochladen? + +Das Hochladen von Logs ermöglicht es anderen, dir bei der Fehlersuche schneller zu helfen, als wenn die Logs in den Chat oder Forenbeiträge eingefügt werden. Es ermöglicht dir auch, die Logs mit anderen zu teilen, ohne sie zu Kopieren oder Einfügen zu müssen. + +Manche Paste-Seiten stellen Syntaxhervorhebung für Logs bereit, was sie deutlich einfacher zu lesen macht und zensieren sensible Daten, wie Benutzernamen oder Systeminformationen. + +## Absturzberichte + +Absturzberichte werden automatisch generiert, wenn das Spiel abstürzt. Sie enthalten nur Absturzinformationen, aber nicht die eigentlichen Logs des Spiels. Sie befinden sich im `crash-reports`-Verzeichnis im Spiel-Verzeichnis. + +Für weitere Informationen über Absturzberichte, siehe [Absturzberichte](./crash-reports). + +## Logs finden + +Diese Anleitung behandelt den offiziellen Minecraft-Launcher (oft auch "Vanilla-Launcher" genannt) - für Launcher von Drittanbietern solltest du deren Dokumentation verwenden. + +Logs befinden sich im `logs`-Verzeichnis innerhalb des Spiel-Verzeichnisses, das Spiel-Verzeichnis kann sich, abhängig von deinem Betriebssystem, an den folgenden Orten befinden: + +::: code-group + +```:no-line-numbers [Windows] +%appdata%\.minecraft +``` + +```:no-line-numbers [macOS] +~/Library/Application Support/minecraft +``` + +```:no-line-numbers [Linux] +~/.minecraft +``` + +::: + +Das neueste Log hat den Dateinamen `latest.log` und vorherige Logs nutzen das Muster `JJJJ-MM-TT_Nummer.log.gz` zur Benennung. + +## Logs hochladen + +Logs können bei einer Vielzahl von Diensten hochgeladen werden, zum Beispiel: + +- [Pastebin](https://pastebin.com/) +- [GitHub Gist](https://gist.github.com/) +- [mclo.gs](https://mclo.gs/) diff --git a/versions/1.20.4/translated/de_de/players/updating-fabric.md b/versions/1.20.4/translated/de_de/players/updating-fabric.md new file mode 100644 index 000000000..d7a8fbb5d --- /dev/null +++ b/versions/1.20.4/translated/de_de/players/updating-fabric.md @@ -0,0 +1,41 @@ +--- +title: Aktualisieren von Fabric +description: Eine Schritt-für-Schritt-Anleitung zum Aktualisieren von Fabric. +authors: + - IMB11 + - modmuss50 +--- + +# Aktualisieren von Fabric + +Diese Anleitung wird das Aktualisieren von Fabric detailliert für den Minecraft-Launcher erklären. + +Für die Launcher von Drittanbietern solltest du deren Dokumentation verwenden. + +Das Vorgehen beim Aktualisieren von Fabric ist der Installation ähnlich, deshalb werden sich Teile dieser Anleitung mit der Anleitung [Installation von Fabric](./installing-fabric) überschneiden. + +## Warum sollte ich den Fabric-Loader aktualisieren? + +Neuere Mods können eine neuere Version des Fabric-Loaders benötigen, um zu funktionieren, weshalb es wichtig ist, ihn auf dem neuesten Stand zu halten, um immer die neuesten Mods benutzen zu können. + + + + + +Um Fabric zu aktualisieren, stelle sicher, dass die Spielversion und die Loader-Version korrekt sind und klicke auf `Installieren`. + +**Stelle sicherm dass die Option 'Profil erstellen'' deaktiviert ist, wenn du den Installer ausführst, da sonst ein neues Profil erstellt wird, das in diesem Fall nicht benötigt wird.** + +## 3. Öffne das Profil im Minecraft-Launcher + +Sobald die Installation beendet ist, kannst du den Minecraft-Launcher öffnen und zum `Installationen`-Tab navigieren. Wähle dein Fabric-Profil und öffne die Bearbeitungsoberfläche. + +Ersetze die Version mit der neuen Version des Fabric-Loaders, die gerade installiert wurde und klicke auf `Speichern`. + +![Aktualisieren der Fabric-Loader-Version im Minecraft-Launcher](/assets/players/updating-fabric.png) + +## 4. Du hast es geschafft! + +Wenn du mit allen Schritten fertig bist, kannst du zurück zum `Spielen`-Tab navigieren, das Fabric-Profil aus der Liste in der unteren linken Ecke auswählen und spielen! + +Fall dir beim Folgen dieser Anleitungen irgendwelche Fehler auftreten, kannst du nach Hilfe im [Fabric-Discord](https://discord.gg/v6v4pMv) im Kanal `#player-support` fragen. diff --git a/versions/1.20.4/translated/de_de/sidebar_translations.json b/versions/1.20.4/translated/de_de/sidebar_translations.json new file mode 100644 index 000000000..0e08ce760 --- /dev/null +++ b/versions/1.20.4/translated/de_de/sidebar_translations.json @@ -0,0 +1,47 @@ +{ + "players.title": "Leitfäden für Spieler", + "players.faq": "Häufig gestellte Fragen", + "players.installingJava": "Java installieren", + "players.installingJava.windows": "Windows", + "players.installingJava.macOS": "macOS", + "players.installingJava.linux": "Linux", + "players.installingFabric": "Fabric installieren", + "players.findingMods": "Vertrauenswürdige Mods finden", + "players.installingMods": "Mods installieren", + "players.troubleshooting": "Problembehandlung", + "players.troubleshooting.uploadingLogs": "Deine Logs hochladen", + "players.troubleshooting.crashReports": "Absturzberichte", + "players.updatingFabric": "Aktualisieren von Fabric", + "develop.title": "Leitfäden für Entwickler", + "develop.gettingStarted": "Erste Schritte", + "develop.gettingStarted.introduction": "Einführung in Fabric und Modding", + "develop.gettingStarted.devEnvSetup": "Einrichten deiner Entwicklungsumgebung", + "develop.gettingStarted.creatingProject": "Ein Projekt erstellen", + "develop.gettingStarted.projectStructure": "Projektstruktur", + "develop.gettingStarted.launchGame": "Starten des Spiels", + "develop.items": "Gegenstände", + "develop.items.potions": "Tränke", + "develop.entities": "Entitäten", + "develop.entities.effects": "Statuseffekte", + "develop.entities.damage-types": "Schadensarten", + "develop.commands": "Befehle", + "develop.commands.basics": "Befehle erstellen", + "develop.commands.arguments": "Argumente", + "develop.commands.suggestions": "Vorschläge", + "develop.rendering": "Rendering", + "develop.rendering.basicConcepts": "Grundlegende Rendering-Konzepte", + "develop.rendering.drawContext": "Den Zeichenkontext verwenden", + "develop.rendering.hud": "Rendering im Hud", + "develop.rendering.gui": "GUIs und Oberflächen", + "develop.rendering.gui.customScreens": "Benutzerdefinierte Oberflächen", + "develop.rendering.gui.customWidgets": "Benutzerdefinierte Widgets", + "develop.rendering.particles": "Partikel", + "develop.rendering.particles.creatingParticles": "Erstellen von benutzerdefinierten Partikeln", + "develop.misc": "Diverse Seiten", + "develop.misc.codecs": "Codecs", + "develop.misc.events": "Events", + "develop.sounds": "Sounds", + "develop.sounds.using-sounds": "SoundEvents abspielen", + "develop.sounds.custom": "Benutzerdefinierte Sounds erstellen", + "github.edit": "Diese Seite auf GitHub bearbeiten" +} \ No newline at end of file diff --git a/versions/1.20.4/translated/es_es/contributing.md b/versions/1.20.4/translated/es_es/contributing.md new file mode 100644 index 000000000..98c5cc403 --- /dev/null +++ b/versions/1.20.4/translated/es_es/contributing.md @@ -0,0 +1,181 @@ +# Pautas de Contribución para la Documentación de Fabric + +Esta página web utiliza [VitePress](https://vitepress.dev/) para generar HTML estático a partir de varios archivos markdown. Debes familiarizarte con las extensiones de markdown que VitePress soporta [aquí](https://vitepress.dev/guide/markdown#features). + +## Índice de Contenido + +- [Pautas de Contribución para la Documentación de Fabric](#fabric-documentation-contribution-guidelines) + - [Como Contribuir](#how-to-contribute) + - [Estructura de Contribuciones](#contributing-framework) + - [Contribuir Contenido](#contributing-content) + - [Pautas de Estilo](#style-guidelines) + - [Guias para Expansiones](#guidance-for-expansion) + - [Verificación de Contenido](#content-verification) + - [Limpieza](#cleanup) + - [Traducir la Documentación](#translating-documentation) + +## Como Contribuir + +Es recomendado que crees una nueva rama en tu bifurcación del repositorio por cada solicitud de extracción que crees. Esto facilita el manejo de multiples solicitudes de extracción al mismo tiempo. + +**Si quieres tener una vista previa de tus cambios localmente, necesitarás instalar [Node.js 18+](https://nodejs.org/en/)** + +Antes de correr cualquiera de estos comandos, asegúrate de correr `npm install` para instalar todas las dependencias. + +**Ejecutar el servidor de desarrollo:** + +Esto te permitirá ver una vista previa de tus cambios localmente en `localhost:3000`. + +```sh +npm run dev +``` + +**Construyendo la página web:** + +Esto compilará todos los archivos markdown en archivos HTML estáticos, los cuales estarán en `.vitepress/dist` + +```sh +npm run build +``` + +**Viendo la vista previa de la página web:** + +Esto ejecutará un servidor local en el puerto 3000 usando el contenido encontrado en `.vitepress/dist` + +```sh +npm run preview +``` + +## Estructura de Contribuciones + +Cualquier solicitud de extracción que modifique la estructura interna de la página web debe ser etiquetada con la etiqueta `framework`. + +En realidad solo deberías realizar solicitudes de extracción para la estructura después de consultar con el equipo de documentación en el servidor de [Discord de Fabric](https://discord.gg/v6v4pMv) o mediante una propuesta. + +**Nota: Modificar la configuración de los archivos de la barra lateral o la barra de navegación no cuenta como una solicitud de extracción de estructura.** + +## Contribuir Contenido + +La contribución de contenido es la manera principal para contribuir a la Documentación de Fabric. + +Todo el contenido debe seguir nuestras pautas de estilo. + +### Pautas de Estilo + +Todas las páginas de la Documentación de Fabric deben seguir las pautas de estilo. Si no estás seguro sobre cualquier cosa, puedes preguntar en el servidor de [Discord de Fabric](https://discord.gg/v6v4pMv) o mediante las Discusiones de Github. + +La guía de estilo es la siguiente: + +1. Todas las páginas deben tener un título y una descripción como o en el asunto. + + ```md + --- + title: Este es el título de la página + description: Esta es la descripción de la página + authors: + - UsuarioDeGithubAquí + --- + + # ... + ``` + +2. Si quieres crear o modificar páginas que contengan código, debes colocar el código en un lugar apropiado dentro del mod de referencia (localizado en el folder `/reference` del repositorio). Luego, utiliza la [funcionalidad de fragmentos de código ofrecida por VitePress](https://vitepress.dev/guide/markdown#import-code-snippets) para adjuntar el código, o si necesitas mayor control, puedes usar la [funcionalidad de transcluir de `markdown-it-vuepress-code-snippet-enhanced`](https://github.com/fabioaanthony/markdown-it-vuepress-code-snippet-enhanced). + + **Por ejemplo:** + + ```md + <<< @/reference/latest/src/main/java/com/example/docs/FabricDocsReference.java{15-21 java} + ``` + + Esto adjuntará las líneas 15-21 del archivo `FabricDocsReference.java` del mod de referencia. + + El fragmento de código resultante se verá así: + + ```java + @Override + public void onInitialize() { + // This code runs as soon as Minecraft is in a mod-load-ready state. + // However, some things (like resources) may still be uninitialized. + // Proceed with mild caution. + + LOGGER.info("Hello Fabric world!"); + } + ``` + + **Ejemplo de translcuir:** + + ```md + @[code transcludeWith=#test_transclude](@/reference/.../blah.java) + ``` + + Esto adjuntará las secciones de `blah.java` marcadas con la etiqueta `#test_transclude`. + + Por ejemplo: + + ```java + public final String test = "Bye World!" + + // #test_transclude + public void test() { + System.out.println("Hello World!"); + } + // #test_transclude + ``` + + Solo se adjuntará el código entre las etiquetas de `#test_transclude`. + + ```java + public void test() { + System.out.println("Hello World!"); + } + ``` + +3. Toda la documentación original está escrita en Inglés, usando las reglas gramáticas del dialecto Estadounidense. Aunque puedes usar [LanguageTool](https://languagetool.org/) para verificar tu gramática mientras que escribes, no te estreses mucho por ello. Nuestro equipo de documentación verificará y corregirá la gramática durante la etapa de limpieza. Sin embargo, puedes ahorrarnos tiempo tomando esfuerzo en escribir bien. + +4. Si estás creando una nueva sección, debes crear una nueva barra lateral en el folder de `.vitepress/sidebars` y agregarla en el archivo `config.mts`. Si necesitas ayuda con esto, puedes preguntar en el canal de `#docs` en el servidor de [Discord de Fabric](https://discord.gg/v6v4pMv). + +5. Cuando crees una nueva página, debes agregarla a la barra lateral correspondiente en el folder de `.vitepress/sidebars`. De nuevo, si necesitas ayuda, pregunta en el servidor de Discord de Fabric, en el canal de `#docs`. + +6. Cualquier imagen debe ser colocada en un lugar apropiado en el folder de `/assets`. + +7. ⚠️ **Cuando enlaces a otras páginas, usa links relativos.** ⚠️ + + Esto es debido al sistema de versiones presente, el cual procesará los links para agregar la versión antes. Si usas links absolutos, el número de versión no será agregado al link. + + Por ejemplo, para una página en el folder de `/players`, enlazar a la página de `installing-fabric` encontrada en `/players/installing-fabric.md` requerirá de lo siguiente: + + ```md + [Esto es un link a otra página](./installing-fabric) + ``` + + **NO** hagas lo siguiente: + + ```md + [Esto es un link a otra página](/players/installing-fabric) + ``` + +Todas las contribuciones de contenido pasa por tres etapas: + +1. Guías para expansiones (si es posible) +2. Verificación de Contenido +3. Limpieza (Gramática etc.) + +### Guías para Expansiones + +Si el equipo de documentación piensa que puedes expandir tu solicitud de extracción en cuanto al contenido, un miembro del equipo añadirá la etiqueta `expansion` a tu solicitud de extracción junto con un comentario explicando lo que el miembro de equipo piensa que puedes hacer para expandir tu solicitud. Si estás de acuerdo con la sugerencia, puedes expandir tu solicitud de extracción. + +**No te sientas presionado en expandir tu solicitud de extracción.** Si no quieres expandirla, simplemente puedes pedir que se te remueva la etiqueta de `expansion`. + +Si no quieres expandir tu solicitud de extracción, pero quisieras que otra persona lo expanda después, es mejor crear una propuesta en la [Página de Propuestas](https://github.com/FabricMC/fabric-docs/issues) y explicar lo que quisieras que se expanda. + +### Verificación de Contenido + +Esta etapa es la más importante, ya que asegura que el contenido es correcto y sigue las Pautas de Estilo de Documentación de Fabric. + +### Limpieza + +¡En esta etapa, el equipo de documentación arreglará problemas con la gramática y hará cualquier otros cambios lingüísticos necesarios antes de aceptar la solicitud de extracción! + +## Traducir la Documentación + +Si quieres traducir esta documentación a tu idioma, puedes hacer esto en la [página de Crowdin de Fabric](https://crowdin.com/project/fabricmc). diff --git a/versions/1.20.4/translated/es_es/develop/codecs.md b/versions/1.20.4/translated/es_es/develop/codecs.md new file mode 100644 index 000000000..5156ab5ad --- /dev/null +++ b/versions/1.20.4/translated/es_es/develop/codecs.md @@ -0,0 +1,398 @@ +--- +title: Codecs +description: Una guía completa para entender y usar el sistema de codecs de Mojang para la serialización y deserialización de objetos. +authors: + - enjarai + - Syst3ms +--- + +# Codecs + +Los Codecs es un sistema para la fácil serialización de objetos de Java, el cual viene incluido en la librería de DataFixerUpper (DFU) de Mojang, el cual es incluido en Minecraft. En el contexto de desarrollo de mods, pueden ser usados como una alternativa a GSON y Jankson a la hora de leer y escribir archivos json, aunque se están haciendo cada vez más y más relevantes, a medida que Mojang reescribe bastante código viejo para que use Codecs. + +Los codecs son usandos en conjunto con otro API de DFU, llamado `DynamicOps` (Operaciones Dinámicas). Un codec define la estructura de un objeto, mientras que un "dynamic ops" es usado para definir un formato con el cual (de) serializar, como json o NBT. Esto quiere decir que un codec puede user usado con cualquier "dynamic ops" y vice versa, permitiendo mayor flexibilidad. + +## Usando Codecs + +### Serializando y Deserializando + +La manera básica de usar un codec es para serializar y deserializar objetos desde y a un formato en específico. + +Ya que algunas clases vanila ya tienen codecs definidos, podemos usarlos como ejemplo. Mojang también nos ha dado dos clases de "dynamic ops" por defecto, llamadas `JsonOps` y `NbtOps`, las cuales tienden a ser usadas en la mayoría de los casos. + +Digamos que queremos serializar un `BlockPos` a json y de vuelta. Podemos hacer esto mediante el codec guardado estáticamente en `BlockPos.CODEC` con los métodos `Codec#encodeStart` y `Codec#parse`, respectivamente. + +```java +BlockPos pos = new BlockPos(1, 2, 3); + +// Serializamos el BlockPos a un JsonElement +DataResult result = BlockPos.CODEC.encodeStart(JsonOps.INSTANCE, pos); +``` + +Cuando usamos codecs, los valores retornados vienen en la forma de un `DataResult` ("Resultado de Dato"). Esto es una envoltura que puede representar o un éxito o un fracaso. Podemos usarlo de varias maneras: Si solo queremos nuestro valor serializado, entonces `DataResult#result` simplemente nos dará un `Optional` que contiene nuestro valor, mientras que `DataResult#resultOrPartial` también nos deja suplír una función para manejar cualquier error que pudo haber ocurrido. Esto último es particularmente útil para recursos de datapacks ("paquetes de datos"), donde querríamos escribir o "loggear" errores sin causar problemas en otros lugares. + +Ahora podemos obtener nuestro valor serializado y convertirlo de vuelta a un `BlockPos`: + +```java +// Cuando desarrolles un mod, querrás obviamente manejar Opcionales vaciós apropiadamente +JsonElement json = result.resultOrPartial(LOGGER::error).orElseThrow(); + +// Aquí tenemos nuestro valor json, que debería corresponder a `[1, 2, 3]`, +// ya que es el formato usado por el codec de BlockPos. +LOGGER.info("Serialized BlockPos: {}", json); + +// Ahora deserializaremos nuestro el JsonElement de vuelta a un BlockPos +DataResult result = BlockPos.CODEC.parse(JsonOps.INSTANCE, json); + +// Una vez más solo agarraremos nuestro valor del resultado +BlockPos pos = result.resultOrPartial(LOGGER::error).orElseThrow(); + +// ¡Y ahora podemos ver que hemos serializado y deserializado nuestro BlockPos exitósamente! +LOGGER.info("Deserialized BlockPos: {}", pos); +``` + +### Codecs Incluidos + +Como hemos mencionado anterioramente, Mojang ya tiene definido varios codecs para varias clases vanila y clases de Java estándares, como por ejemplo, `BlockPos`, `BlockState`, `ItemStack`, `Identifier`, `Text`, y regex `Pattern`s (patrones regex). Los Codecs para las clases propias de Mojang usualmente se pueden encontrar como miembros estáticos con el nombre de `CODEC` en la clase misma, mientras que la mayoría de los demás se encuentran en la clase `Codecs`. Es importante saber que todos los registros vanila tienen un método `getCodec()`, por ejemplo, puedes usar `Registries.BLOCK.getCodec()` para tener un `Codec` el cual (de)serializa IDs de bloques. + +La API de Codec también tiene codecs para tipos de variable primitivos, como `Codec.INT` y `Codec.STRING`. Estos se pueden encontrar como miembros estáticos en la clase `Codec`, y usualmente son la base de Codecs más complejos, como explicado a continuación. + +## Construyendo Codecs + +Ahora que hemos visto como usar codecs, veamos como podemos hacer nuestros propios codecs. Supongamos que tenemos la siguiente clase, y queremos deserializar instancias de ella desde archivos json: + +```java +public class CoolBeansClass { + + private final int beansAmount; + private final Item beanType; + private final List beanPositions; + + public CoolBeansClass(int beansAmount, Item beanType, List beanPositions) {...} + + public int getBeansAmount() { return this.beansAmount; } + public Item getBeanType() { return this.beanType; } + public List getBeanPositions() { return this.beanPositions; } +} +``` + +El archivo json correspondiente puede verse algo así: + +```json +{ + "beans_amount": 5, + "bean_type": "beanmod:mythical_beans", + "bean_positions": [ + [1, 2, 3], + [4, 5, 6] + ] +} +``` + +Podemos hacer un codec para esta clase integrando varios codecs más pequeños en uno más grande. En este caso, necesitaremos uno para cada miembro: + +- un `Codec` +- un `Codec` +- un `Codec>` + +Podemos obtener el primero usando los codecs primitivos ya mencionados, mediante la clase `Codec`, específicamente `Codec.INT`. Mientras que el segundo se puede obtener mediante el registro `Registries.ITEM`, el cuando tiene un método `getCodec()`, el cual retorna un `Codec`. No tenemos un codec por defecto para `List`, pero podemos crear uno a partir de `BlockPos.CODEC`. + +### Listas + +`Codec#listOf` puede ser usado para crear una versión lista de cualquier codec: + +```java +Codec> listCodec = BlockPos.CODEC.listOf(); +``` + +Debe ser recalcado que los codecs creados de esta manera siempre se deserializarán a un `ImmutableList` (lista inmutable o no modificable). Si en cambio necesitas una lista mutable, puedes usar [xmap](#mutually-convertible-types-and-you) para convertir a una durante la deserialización. + +### Combinar Codecs para Clases como Records + +Ahora que tenemos codecs separados para cada miembro, podemos combinarlos en un solo codec usando un `RecordCodecBuilder`. Esto asume que nuestra clase tiene un constructor que contiene cada miembro que queremos serializar, y que cada miembro tiene su propio método adquiridor (getter method). Esto lo hace perfecto para usar en conjunto con records, pero también pueden ser usados con clases normales. + +Veamos como podemos crear un codec para nuestra clase `CoolBeansClass`: + +```java +public static final Codec CODEC = RecordCodecBuilder.create(instance -> instance.group( + Codec.INT.fieldOf("beans_amount").forGetter(CoolBeansClass::getBeansAmount), + Registries.ITEM.getCodec().fieldOf("bean_type").forGetter(CoolBeansClass::getBeanType), + BlockPos.CODEC.listOf().fieldOf("bean_positions").forGetter(CoolBeansClass::getBeanPositions) + // El máximo de miembros que se pueden declarar aquí es 16 +).apply(instance, CoolBeansClass::new)); +``` + +Cada línea en el grupo especifica un codec, un nombre para el miembro, y el método adquiridor. El llamado a `Codec#fieldOf` es usado para convertir el codec a un [map codec](#mapcodec), y el llamado a `forGetter` especifica el método adquiridor que se usará para obtener el valor del miembro a partir de una instancia de la clase. Mientras tanto, el llamado a `apply` especifica que el constructor usado para crear nuevas instancias. Es importante saber que el orden de los miembros en el grupo debe ser el mismo que el orden de los argumentos del constructor. + +También puedes usar `Codec#optionalFieldOf` en este contexto para hacer un miembro opcional, como explicado en la sección de [Miembros Opcionales](#optional-fields). + +### MapCodec, sin ser confundido con Codec<Map> {#mapcodec} + +Llamar `Codec#fieldOf` convertirá un `Codec` a un `MapCodec`, el cual es una implementación variante, pero no directa de `Codec`. Como su nombre lo indica, los `MapCodec`s garantizan la serialización a una asociación (map) llave a valor, o su equivalente en el `DynamicOps` usado. Algunas funciones pueden requerir una, en vez de un codec regular. + +Esta manea particular de crear un `MapCodec` esencialmente empaqueta los valores del codec fuente dentro de una asociación (map), usando el nombre del miembro proveído como la llave. Por ejemplo, un `Codec`, cuando es serializado a json, puede verse así: + +```json +[1, 2, 3] +``` + +Pero cuando es convertido a un `MapCodec` usando `BlockPos.CODEC.fieldOf("pos")`, se verá así: + +```json +{ + "pos": [1, 2, 3] +} +``` + +Aunque el uso más común para los map codecs es para que se combinen con otros map codecs para construir un codec para una clase completa con varios miemros, como fue explicado en la sección [Combinar Codecs para Clases como Records](#merging-codecs-for-record-like-classes), también pueden ser convertidos de vuelta a codecs regulares usando `MapCodec#codec`, el cual mantendrá el mismo comportamiento para empaquetar sus valores de entrada. + +#### Codecs Opcionales + +`Codec#optionalFieldOf` puede ser usado para crear un map codec opcional. Esto hará que, cuando el miembro especificado no esté presente en el contenedor durante la deserialización, se deserialize a un `Optional` vacío, o a un valor por defecto especificado. + +```java +// Sin valor por defecto +MapCodec> optionalCodec = BlockPos.CODEC.optionalFieldOf("pos"); + +// Con valor por defecto +MapCodec optionalCodec = BlockPos.CODEC.optionalFieldOf("pos", BlockPos.ORIGIN); +``` + +Ten en cuenta que los miembros opcionales ignorarán silenciosamente cualquier error que ocurra durante la deserialización. Esto significa que si el miembro está presente, pero el valor es inválido, el miembro siempre se deserializará al valor por defecto. + +**Desde la 1.20.2**, debido a Minecraft (no DFU!) en cambio si provee `Codecs#createStrictOptionalFieldCodec`, el cual falla en la deserialización si el valor del miembro es inválido. + +### Constantes, Restricciones, y Composición + +#### Unidad + +`Codec.unit` puede usarse para crear un codec el cual siempre deserializará a un valor constante, independiente del valor dado. Cuando se serialice, no hará nada. + +```java +Codec theMeaningOfCodec = Codec.unit(42); +``` + +#### Rangos Numéricos + +`Codec.intRange` y sus amigos, `Codec.floatRange` y `Codec.doubleRange` pueden ser usados para crear un codec que solo acepta valores numéricos dentro de un rango **inclusivo**. Esto se aplica tanto en la serialización y deserialización. + +```java +// No puede ser mayor a 2 +Codec amountOfFriendsYouHave = Codec.intRange(0, 2); +``` + +#### Pares + +`Codec.pair` combina dos codecs, `Codec
` y `Codec`, a un `Codec>`. Ten en cuenta que solo funciona bien con codecs que serializan a un miembro específico, como un [`MapCodec`s convertidos](#mapcodec) o +[codecs de record](#merging-codecs-for-record-like-classes). +El codec resultante será serializado a una asociación (map) que combina los miembros de ambos codecs usados. + +Por ejemplo, al correr este código: + +```java +// Crea dos codecs empaquetados +Codec firstCodec = Codec.INT.fieldOf("i_am_number").codec(); +Codec secondCodec = Codec.BOOL.fieldOf("this_statement_is_false").codec(); + +// Combinalos a un codec par +Codec> pairCodec = Codec.pair(firstCodec, secondCodec); + +// Usalo para serializar datos +DataResult result = pairCodec.encodeStart(JsonOps.INSTANCE, Pair.of(23, true)); +``` + +Producirá este json: + +```json +{ + "i_am_number": 23, + "this_statement_is_false": true +} +``` + +#### Cualquiera (Either) + +`Codec.either` combina dos codecs, `Codec` y `Codec`, a un `Codec>`. El codec resultante intentará, durante la deserialización, usar el primer codec, y _solo si eso falla_, entonces intentará usar el segundo. +Si el segundo también falla, el error del _segundo_ codec será retornado. + +#### Asociaciones (Maps) + +Para procesar asociaciones con llaves arbitrarias, como `HashMap`s, se puede usar `Codec.unboundedMap`. Esto nos dá un `Codec>`, para un `Codec` y un `Codec` dado. El codec resultante será serializado a un objeto json o el equivalente disponible en el dynamic ops actual. + +Debido a las limitaciones de json y nbt, los codecs para las llaves _deben_ ser serializados a una cadena de caracteres (string). Esto incluye codecs para tipos que no son cadenas de caracteres por su cuenta, pero si se serializan a ellas, como `Identifier.CODEC`. Vea el ejemplo a continuación: + +```java +// Crea un codec para un mapa de identificadores a numeros enteros +Codec> mapCodec = Codec.unboundedMap(Identifier.CODEC, Codec.INT); + +// Usalo para serializar datos +DataResult result = mapCodec.encodeStart(JsonOps.INSTANCE, Map.of( + new Identifier("example", "number"), 23, + new Identifier("example", "the_cooler_number"), 42 +)); +``` + +Esto producirá este json: + +```json +{ + "example:number": 23, + "example:the_cooler_number": 42 +} +``` + +Como puedes ver, esto funciona porque `Identifier.CODEC` se serializa directamente a una cadena de caracteres. Un efecto similar puede ser logrado para objetos simples que no se serializan a cadenas de caracteres usando [xmap y sus amigos](#mutually-convertible-types-and-you) para convertirlos. + +### Tipos Mutuamente Convertibles y Tú + +#### xmap + +Digamos que tenemos dos clases que pueden ser convertidas una a la otra, pero no tienen una relación pariente-hijo. Por ejemplo un `BlockPos`y `Vec3d` vanila. Si tenemos un codec para uno, podemos usar `Codec#xmap` para crear un codec para el otro especificando una función convertidora en ambas direcciones. + +`BlockPos` ya tiene un codec, pero pretendamos que no lo tiene. Podemos crear uno para él basándolo en el codec de `Vec3d` así: + +```java +Codec blockPosCodec = Vec3d.CODEC.xmap( + // Convierte Vec3d a Blockpos + vec -> new BlockPos(vec.x, vec.y, vec.z), + // Convierte BlockPos a Vec3d + pos -> new Vec3d(pos.getX(), pos.getY(), pos.getZ()) +); + +// Cuando convertimos una clase ya existente (`X` por ejemplo) +// a tu propia clase (`Y`) de esta manera, puede ser útil tener +// métodos `toX` y un método estático `fromX` en la clase `Y` y usar +// referencias a métodos en tu llamado a `xmap`. +``` + +#### flatComapMap, comapFlatMap, and flatXMap + +`Codec#flatComapMap`, `Codec#comapFlatMap` y `flatXMap` son similares a xmap, pero permiten que una o ambass de las funciones convertidoras retornen un DataResult. En práctica esto es útil porque una instancia de un objeto puede no ser válida para conversión. + +Toma por ejemplo `Identifier`s vanila. Aunque todos los identificadores pueden ser convertidos a cadenas de caracteres, no todas las cadenas de caracteres son identificadores válidos, así que usar xmap significaría tirar excepciones si la conversión falla. +Debido a esto, su codec incluído es en realidad un `comapFlatMap` en `Codec.STRING`, ilustrando como se pueden usar: + +```java +public class Identifier { + public static final Codec CODEC = Codec.STRING.comapFlatMap( + Identifier::validate, Identifier::toString + ); + + // ... + + public static DataResult validate(String id) { + try { + return DataResult.success(new Identifier(id)); + } catch (InvalidIdentifierException e) { + return DataResult.error("Not a valid resource location: " + id + " " + e.getMessage()); + } + } + + // ... +} +``` + +Aunque estos métodos son muy útiles, sus nombres son un poco confusos, así que aquí hay una tabla para que puedas recordar mejor cuál usar: + +| Método | ¿A -> B siempre válido? | ¿B -> A siempre válido? | +| ----------------------- | ----------------------- | ----------------------- | +| `Codec#xmap` | Sí | Sí | +| `Codec#comapFlatMap` | No | Sí | +| `Codec#flatComapMap` | Sí | No | +| `Codec#flatXMap` | No | No | + +### Despachador de Registros + +`Codec#dispatch` nos permite definir un registro de codecs y despachar a uno en específico basado en el valor de un miembro en los datos serializados. Esto es muy útil cuando deserializamos objetos que tienen diferentes miembros dependiendo de su tipo, pero que igual representan la misma cosa. + +Por ejemplo, digamos que tenemos una interfaz abstracta `Bean`, con dos clases implementadoras: `StringyBean` y `CountingBean`. Para serializarlas con un despachador de registros, necesitaremos algunas cosas: + +- Codecs separados para cada tipo de bean. +- Una clase `BeanType` o un record que represente el tipo de bean, y que pueda retornar un codec para él. +- Una función en `Bean` para obtener su `BeanType`. +- Una asociación o registro para asociar `Identifier`s a `BeanType`s. +- Un `Codec>` basado en este registro. Si usas un `net.minecraft.registry.Registry`, puedes hacer una fácilmente con `Registry#getCodec`. + +Con todo esto, puedes crear un despacho de registros para beans: + +@[code transcludeWith=:::](@/reference/latest/src/main/java/com/example/docs/codec/Bean.java) +@[code transcludeWith=:::](@/reference/latest/src/main/java/com/example/docs/codec/BeanType.java) +@[code transcludeWith=:::](@/reference/latest/src/main/java/com/example/docs/codec/StringyBean.java) +@[code transcludeWith=:::](@/reference/latest/src/main/java/com/example/docs/codec/CountingBean.java) +@[code transcludeWith=:::](@/reference/latest/src/main/java/com/example/docs/codec/BeanTypes.java) + +```java +// Ahora podemos crear un codec para los tipos de bean +// basado en el registro previamente creado +Codec> beanTypeCodec = BeanType.REGISTRY.getCodec(); + +// ¡Y basado en esto, aquí esta nuestro codec de despacho de registros para beans! +// El primer argumento es el nombre del miembro para el tipo de bean. +// Cuando no se especifica, se usa el valor por defecto "type". +Codec beanCodec = beanTypeCodec.dispatch("type", Bean::getType, BeanType::getCodec); +``` + +Nuestro nuevo codec serializará beans a json de esta manera, usando solo los campos relevantes a su tipo especificado: + +```json +{ + "type": "example:stringy_bean", + "stringy_string": "This bean is stringy!" +} +``` + +```json +{ + "type": "example:counting_bean", + "counting_number": 42 +} +``` + +### Codecs Recursivos + +A veces es útil tener un codec que se use a _sí mismo_ para decodificar ciertos miembros, por ejemplo cuando estamos lidiando con ciertas estructuras de datos recursivas. En el código vanilla, esto es usado para objetos `Text` (Texto), los cuales tienen otros objetos `Text` como hijos. Tal codec puede ser construido usando `Codecs#createRecursive`. + +Por ejemplo, tratemos de serializar una lista enlazada. Esta manera de representar listas consiste en varios nodos que contienen un valor y una referencia al siguiente nodo en la lista. La lista es entonces representada mediante el primer nodo, y para caminar por la lista se sigue el siguiente nodo hasta que no quede ninguno. Aquí está una implementación simple de los nodos que guardan números enteros. + +```java +public record ListNode(int value, ListNode next) {} +``` + +No podemos construir un codec para esto mediante métodos ordinarios, porque ¿qué codec usaríamos para el miembro de `next`? ¡Tendríamos que usar un `Codec`, que es lo que estamos construyendo actualmente! `Codecs#createRecursive` nos permite lograr eso con una expresión lambda mágica: + +```java +Codec codec = Codecs.createRecursive( + "ListNode", // a name for the codec + selfCodec -> { + // Here, `selfCodec` represents the `Codec`, as if it was already constructed + // This lambda should return the codec we wanted to use from the start, + // that refers to itself through `selfCodec` + return RecordCodecBuilder.create(instance -> + instance.group( + Codec.INT.fieldOf("value").forGetter(ListNode::value), + // the `next` field will be handled recursively with the self-codec + Codecs.createStrictOptionalFieldCodec(selfCodec, "next", null).forGetter(ListNode::next) + ).apply(instance, ListNode::new) + ); + } +); +``` + +Un `ListNode` serializado se podría ver algo así: + +```json +{ + "value": 2, + "next": { + "value": 3, + "next" : { + "value": 5 + } + } +} +``` + +## Fuentes y Referencias + +- Puedes encontrar una documentación más completa sobre codecs y los APIs relacionados en los [Javadocs de DFU no oficiales](https://kvverti.github.io/Documented-DataFixerUpper/snapshot/com/mojang/serialization/Codec). +- La estructura general de esta guía fue inspirada en gran medida por la [página Wiki de Forge sobre codecs](https://forge.gemwire.uk/wiki/Codecs), una versión de esta página más enfocada para Forge. diff --git a/versions/1.20.4/translated/es_es/develop/commands/arguments.md b/versions/1.20.4/translated/es_es/develop/commands/arguments.md new file mode 100644 index 000000000..d0d1b7568 --- /dev/null +++ b/versions/1.20.4/translated/es_es/develop/commands/arguments.md @@ -0,0 +1,56 @@ +--- +title: Argumentos de Comandos +description: Aprende a crear comandos con argumentos complejos. +--- + +# Argumentos de Comandos + +Los argumentos son usados en la mayoría de los comandos. Algunas veces pueden ser opcionales, lo que significa que el usuario no tiene que dar un argumento para que el comando corra. Un nodo puede tener múltiples tipos de argumentos, pero ten cuidado de no crear ambigüedades. + +@[code lang=java highlight={3} transcludeWith=:::4](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +En este caso, después del texto del comando `/argtater`, debes escribir un número entero. Por ejemplo, si corres `/argtater 3`, obtendrás el mensaje de respuesta `Called /argtater with value = 3`. Si escribes `/argtater` sin argumentos, el comando no puede ser leído y analizado correctamente. + +Ahora añadimos un segundo argumento opcional: + +@[code lang=java highlight={3,13} transcludeWith=:::5](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +Ahora puedes escribir uno o dós números enteros. Si le das un número entero, se mostrará un mensaje de respuesta con un solo valor. Si das dos números enteros, se mostrará un mensaje de respuesta con dos valores. + +Puede que sientas que sea innecesario tener que especificar ejecuciones similares dos veces. Para ello, crearemos un método que se usará para ambas ejecuciones. + +@[code lang=java highlight={3,5,6,7} transcludeWith=:::6](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +## Tipos de Argumentos Personalizados + +Si el juego vanilla no tiene el tipo de argumento que necesitas, puedes crear tu propio tipo de argumento. Para esto, puedes crear una clase que implemente la interfaz `ArgumentType`, donde `T` es el tipo del argumento. + +Necesitarás implementar el método `parse`, el cual leerá y analizará la cadena de caracteres entrada por el usuario a el tipo de argumento deseado. + +Por ejemplo, puedes crear un tipo de argumento que lea un `BlockPos` a partir de una cadena de caracteres con el siguiente formato: `{x, y, z}` + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/command/BlockPosArgumentType.java) + +### Registrar Tipos de Argumentos Personalizados + +:::warning +¡Necesitas registrar el tipo de comando personalizado tanto en el servidor como en el cliente, de lo contrario, el comando no funcionará! +::: + +Puedes registrar tu propio tipo de argumento personalizado en el método `onInitialize` del inicializador de tu mod usando la clase `ArgumentTypeRegistry`: + +@[code lang=java transcludeWith=:::11](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +### Usar Argumentos de Comandos Personalizados + +Podemos usar nuestro tipo de argumento personalizado en un comando pasando una instancia de él al método `.argument` en el constructor del comando. + +@[code lang=java transcludeWith=:::10 highlight={3}](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +Al correr el comando, podemos verificar que el tipo de argumento funciona: + +![Argumento inválido](/assets/develop/commands/custom-arguments_fail.png) + +![Argumento válido](/assets/develop/commands/custom-arguments_valid.png) + +![Resultado del comando](/assets/develop/commands/custom-arguments_result.png) diff --git a/versions/1.20.4/translated/es_es/develop/commands/basics.md b/versions/1.20.4/translated/es_es/develop/commands/basics.md new file mode 100644 index 000000000..f5e5feaa8 --- /dev/null +++ b/versions/1.20.4/translated/es_es/develop/commands/basics.md @@ -0,0 +1,161 @@ +--- +title: Crear Comandos +description: Crea comandos con argumentos y acciones complejas. +authors: + - dicedpixels + - i509VCB + - pyrofab + - natanfudge + - Juuxel + - solidblock + - modmuss50 + - technici4n + - atakku + - haykam + - mschae23 + - treeways + - xpple +--- + +# Crear Comandos + +La creación de comandos le permite a desarrolladores de mods añadir funcionalidad que puede ser usada mediante un comando. Este tutorial te enseñará como registrar comandos y la estructura general de comandos de Brigadier. + +:::info +Brigadier es un analizador y despachador de comandos escrito por Mojang para Minecraft. Es una libraría basada en un una estructura de árbol de comandos, donde construyes un árbol de comandos y argumentos. Brigadier es de fuente abierta: +::: + +## La interfaz `Comand` (Comando) + +`com.mojang.brigadier.Command` es una interfaz funcional, la cual corre un código específico, y tira una excepción de `CommandSyntaxException` (Excepción de Syntax de Comando) en algunos casos. Tiene un tipo genérico `S`, el cual define el tipo de la _fuente de comando_. +La fuente de comando nos dá el contexto en el que se corrió un comando. En Minecraft, la fuente de comando es típicamente un `ServerCommandSource` (Fuente de Comando de Servidor) el cual puede representar un servidor, un bloque de comandos, una conexión remota (RCON), un jugador o una entidad. + +El método `run(CommandContext)` en `Command` tiene un `CommandContext` como el único parámetro y retorna un número entero. El contexto del comando contiene la fuente de comando de `S` y te permite obtener los argumentos, ver los nodos de comando analizados y ver el valor entrado en este comando. + +Al igual que otras interfaces funcionales, puedes usar una expresión Lambda o una referencia de método: + +```java +Command command = context -> { + return 0; +}; +``` + +El número entero retornado puede ser considerado el resultado del comando. Los valores iguales o menores a 0 típicamente significan que el comando ha fallado y no hará nada. Valores positivos indican que el comando fue exitoso e hizo algo. Brigadier provee una constante para indicar éxito; `Command#SINGLE_SUCCESS` (Éxito Único). + +### ¿Qué puede hacer el `ServerCommandSource`? + +Un `ServerCommandSource` nos da contexto específico de implementación adicional cuando el comando es corrido. Esto incluye la habilidad de obtener la entidad que ejecutó el comando, el mundo o el servidor en el que el comando fue ejecutado. + +Puedes acceder la fuente del comando desde un contexto de comando llamando `getSource()` en la instancia de `CommandContext`. + +```java +Command command = context -> { + ServerCommandSource source = context.getSource(); + return 0; +}; +``` + +## Registrar un Comando Básico + +Los comandos son registrados mediante la clase `CommandRegistrationCallback` (Callback de Registración de Comandos) proveída por el Fabric API. + +:::info +Para información sobre como registrar callbacks, por favor visita la guía de [Eventos](../events). +::: + +El evento debería ser registrado en tu inicializador de mod. + +El callback tiene tres parámetros: + +- `CommandDispatcher dispatcher` (Despachador de comandos) - Usado para registrar, analizar y ejecutar comandos. `S` es el tipo de la fuente del comando que el despachador usa. +- `CommandRegistryAccess registryAccess` (Acceso de registro de comandos) - Provee una abstracción sobre los registros que pueden ser dados a ciertos métodos de argumentos de comandos +- `CommandManager.RegistrationEnvironment environment` (Ambiente de Registración) - Identifica el tipo de servidor en el que los comandos se están registrando en. + +En el inicializador de mod, solo registramos un comando simple: + +@[code lang=java transcludeWith=:::_1](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +En el método `sendFeedback()`, el primer parámetro es el texto a ser enviado, el cual está en un `Supplier` (Proveedor) para no tener que instanciar nuevos objetos `Text` (Texto) cuando no es necesario. + +El segundo parámetro determina si deberíamos transmitir el feedback a otros operadores. Generalmente, si el comando solo es para verificar o consultar algo sin afectar realmente el mundo, como verificar el tiempo actual o el puntaje de un jugador, este parametro debería ser `false` (falso). Si el comando hace algo, como cambiar el tiempo o modificar el puntaje de alguien, entonces debería ser `true` (verdadero). + +Si el comando falla, en vez de llamar `sendFeedback()`, puedes directamente tirar una excepción y el servidor o cliente lo manejará apropiadamente. + +`CommandSyntaxException` es generalmente tirada para indicar errores en la sintaxis del comando o sus argumentos. También puedes implementar tus propias excepciones. + +Para ejecutar este comando, debes escribir `/foo`; aquí importan las mayúsculas y minúsculas. + +### Ambiente de Registración + +Si se desea, también puedes asegurarte que un comando solo es registrado bajo ciertas circunstancias específicas, por ejemplo, solo en el ambiente dedicado: + +@[code lang=java highlight={2} transcludeWith=:::2](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +### Requerimientos de Comandos + +Digamos que tienes un comando y que quieres que solo los operadores puedan ejecutarlo. Aquí entra el método `requires()`. El método `requieres()` tiene un argumento de un `Predicate` (Condición) el cual proveerá un `ServerCommandSource` el cual será probado con la condición data para determinar si el `CommandSource` puede ejecutar el comando. + +@[code lang=java highlight={3} transcludeWith=:::3](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +Este comando solo se ejecutará si la fuente del comando es un operador nivel 2 como mínimo, incluyendo bloques de comandos. De lo contrario, el comando no es registrado. + +Esto tiene el efecto secundario de que el comando no se muestra con la auto completación con la tecla Tab a personas que no tienen operador nivel 2. Esta también es la razón por la cual no puedes autocompletar comandos cuando no tienes los trucos activados. + +### Sub Comandos + +Para agregar un sub comando, registras el primer nodo de comando normalmente. Para tener un sub comando, tienes que adjuntar el siguiente literal de nodo de comando al nodo existente. + +@[code lang=java highlight={3} transcludeWith=:::7](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +Similarmente a los argumentos, los nodos de sub comandos pueden ser opcionales. En el siguiente caso ambos comandos `/subtater` y `/subtater subcommand` serán válidos. + +@[code lang=java highlight={2,8} transcludeWith=:::8](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +## Comandos de Cliente + +El Fabric API tiene una clase `ClientCommandManager` en el paquete de `net.fabricmc.fabric.api.client.command.v2` que puede ser usado para registrar comandos en el lado del cliente. Este código solo debe existir en el lado del cliente. + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/client/java/com/example/docs/client/command/FabricDocsReferenceClientCommands.java) + +## Redireccionando Comandos + +Redireccionadores de comandos - también llamados aliases - son una manea de redireccionar la funcionalidad de un comando a otro. Esto es útil cuando quieres cambiar el nombre de un comando, pero todavía quieres mantener soporte para el nombre viejo. + +@[code lang=java transcludeWith=:::12](@/reference/latest/src/client/java/com/example/docs/client/command/FabricDocsReferenceClientCommands.java) + +## Preguntas Frequentes + +
+ +### ¿Por qué mi código no compila? + +- Atrapa o tira una excepción `CommandSyntaxException` - `CommandSyntaxException` no es una `RuntimeException` (Excepción en Tiempo de Ejecución). Si la tiras, debe ser en métodos que tiren un `CommandSyntaxException` en el signature (firma) del método, o ser atrapadas. + Brigadier manejará las excepciones checked (comprobadas) y mandará el mensaje de error correspondiente en el juego para ti. + +- Problemas con genéricos - Puede que tengas problemas con genéricos de vez en cuando. Si estás registrando comandos de servidor (el cual es mayormente el caso), asegúrate de usar `CommandManager.literal` o `CommandManager.argument` en vez de `LiteralArgumentBuilder.literal` o `RequiredArgumentBuilder.argument`. + +- Verifica el método de `sendFeedback()` - Puede que te hayas olvidado de dar el valor booleano al segundo argumento. También recurda que, a partir de Minecraft 1.20, el primer parámetro es un `Supplier` en vez de `Text`. + +- Un comando debería retornar un número entero - Cuando registres comandos, el método `executes()` acepta un objeto `Command`, el cual usualmente es una expresión Lambda. El Lambda debería retornar un número entero, en lugar de otros tipos de valores. + +### ¿Puedo registrar comandos durante la ejecución? + +::: warning +You can do this, but it is not recommended. You would get the `CommandManager` from the server and add anything commands +you wish to its `CommandDispatcher`. + +Después de eso, debes enviar el árbol de comandos a cada jugador de nuevo usando `CommandManager.sendCommandTree(ServerPlayerEntity)`. + +Esto es necesario porque el cliente almacena en un caché el árbol de comandos que recibe durante inicio de sesión (o cuando paquetes de operador son enviados) para mensajes de error con completaciones locales. +::: + +### ¿Puedo des-registrar comandos durante la ejecución? + +::: warning +You can also do this, however, it is much less stable than registering commands at runtime and could cause unwanted side +effects. + +Para mantener las cosas simples, vas a tener que usar reflexión en Brigadier para remover nodos. Después de esto, necesitas enviar el árbol de comandos de nuevo a cada jugador usando `sendCommandTree(ServerPlayerEntity)`. + +Si no envias el árbol de comandos actualizado, el cliente pensará que un comando existe, aunque el servidor no podrá ejecutarlo. +::: diff --git a/versions/1.20.4/translated/es_es/develop/commands/suggestions.md b/versions/1.20.4/translated/es_es/develop/commands/suggestions.md new file mode 100644 index 000000000..517a71938 --- /dev/null +++ b/versions/1.20.4/translated/es_es/develop/commands/suggestions.md @@ -0,0 +1,45 @@ +--- +title: Sugerencias de Comandos +description: Aprende a sugerir valores para argumentos de comandos a usuarios. +authors: + - IMB11 +--- + +# Sugerencias de Comandos + +Minecraft tiene un poderoso sistema de sugerencias de comandos que es usado en muchos lugares, como en el comanado de `/give`. Este sistema te permite sugerir valores para argumentos de comandos al usuario, donde este puede escoger de estos valores - es una buena manera de hacer tus comandos más ergonómicos y amigables al usuario. + +## Proveedores de Sugerencias + +Un `SuggestionProvider` (Proveedor de Sugerencias) es usado para crear una lista de sugerencias que serán enviadas al cliente. Un proveedor de sugerencias es una interfaz funcional que tiene un parámetro de `CommandContext` y un `SuggestionBuilder` (Constructor de Sugerencias), y retorna algunos `Suggestions` (Sugerencias). El `SuggestionProvider` retorna un `CompletableFuture` (Completador a Futuro) ya que las sugerencias pueden no estar disponibles inmediatamente. + +## Usar Proveedores de Sugerencias + +Para usar un proveedor de sugerencias, tienes que llamar el método `suggests` en el constructor del argumento. Este método tiene un parámetro `SuggestionProvider` y retorna un nuevo constructor de argumento con el proveedor de sugerencias adjuntado. + +@[code java transcludeWith=:::9 highlight={4}](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +## Proveedores de Sugerencias Incluidos + +Hay algunos proveedores de sugerencias incluidos que puedes usar: + +| Proveedor de Sugerencias | Descripción | +| ----------------------------------------- | -------------------------------------------------------------------------------------------------------- | +| `SuggestionProviders.SUMMONABLE_ENTITIES` | Sugiere todas las entidades que pueden ser convocadas. | +| `SuggestionProviders.AVAILABLE_SOUNDS` | Sugiere todos los efectos de sonido que pueden ser reproducidos. | +| `LootCommand.SUGGESTION_PROVIDER` | Sugiere todas las loot tables (tablas de loot) que están disponibles. | +| `SuggestionProviders.ALL_BIOMES` | Sugiere todos los biomas disponibles. | + +## Crear un Proveedor de Sugerencias Personalizado + +Si un proveedor incluido no suficiente para tus necesidades, puedes crear tu propio proveedor de sugerencias. Para esto, debes crear una clase que implemente la interfaz `SuggestionProvider` y que anule el método `getSuggestions`. + +Para este ejemplo, haremos un proveedor de sugerencias que sugiere todos los nombres de usuario de los jugadores en el servidor. + +@[code java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/command/PlayerSuggestionProvider.java) + +Para usar este proveedor de sugerencias, simplemente pasa una instancia de él en el método `.suggests` en el constructor del argumento. + +Obviamente, los proveedores de sugerencias pueden ser más complejos, ya que también el contexto del comando para proveer sugerencias basadas en el estado del comando - como los argumentos que ya han sido dados. + +Esto puede ser en la forma de leer el inventario del jugador y sugerir items, o entidades que estén cerca del jugador. diff --git a/versions/1.20.4/translated/es_es/develop/entities/damage-types.md b/versions/1.20.4/translated/es_es/develop/entities/damage-types.md new file mode 100644 index 000000000..41dbe1506 --- /dev/null +++ b/versions/1.20.4/translated/es_es/develop/entities/damage-types.md @@ -0,0 +1,96 @@ +--- +title: Tipos de Daño +description: Aprende a agregar tipos de daño personalizados. +authors: + - dicedpixels + - hiisuuii + - mattidragon +--- + +# Tipos de Daño + +Los tipos de daño definen los tipos de daño que pueden tomar las entidades. Desde Minecraft 1.19.4, la creación de nuevos tipos de daño se ha vuelto basada en datos, lo que significa que se crean mediante archivos JSON. + +## Creando un Tipo de Daño + +Procedamos a crear un nuevo tipo de daño llamado _Tater_. Empezaremos creando el archivo JSON para tu tipo de daño. Este archivo será puesto en el folder de `data` de tu mod, en un sub-folder llamado `damage_types`. + +```:no-line-numbers +resources/data/fabric-docs-reference/damage_type/tater.json +``` + +Tiene la siguiente estructura: + +@[code lang=json](@/reference/latest/src/main/generated/data/fabric-docs-reference/damage_type/tater.json) + +Este tipo de daño personalizado causa un aumento de 0.1 en [cansancio de hambre](https://minecraft.wiki/w/Hunger#Exhaustion_level_increase) cada vez que el jugador toma daño, cuando el daño es ocasionado por una fuente viviente que no sea otro jugador (por ejemplo, un bloque). Adicionalmente, la cantidad de daño dado dependerá de la dificultad del mundo + +::: info + +Verifica la [Wiki de Minecraft](https://minecraft.wiki/w/Damage_type#JSON_format) para ver todas las posibles llaves y valores. + +::: + +### Accediendo los Tipos de Daño en El Código + +Cuando necesitamos acceder nuestro tipo de daño en el código, necesitaremos usar su `RegistryKey` (Llave de Registro) para crear una instancia de `DamageSource` (Fuente de Daño). + +El `RegistryKey` puede ser obtenida de la siguiente manera: + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/damage/FabricDocsReferenceDamageTypes.java) + +### Usando los Tipos de Daño + +Para demostrar el uso de tipos de daño personalizados, usaremos un bloque personalizado llamado **Tater Block**. Hagamos que cuando una entidad viviente pise sobre un **Bloque de Tater**, dará un daño de _Tater_. + +Puedes anular el método `onSteppedOn` para dar este daño. + +Empezamos creando un `DamageSource` de nuestro tipo de daño personalizado. + +@[code lang=java transclude={21-24}](@/reference/latest/src/main/java/com/example/docs/damage/TaterBlock.java) + +Después, llamamos `entity.damage()` con nuestro `DamageSource` y una cantidad. + +@[code lang=java transclude={25-25}](@/reference/latest/src/main/java/com/example/docs/damage/TaterBlock.java) + +La implementación del bloque completa: + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/damage/TaterBlock.java) + +Ahora cuando una entidad viviente pise sobre nuestro bloque personalizado, tomará 5 de daño (2.5 corazones) usando nuestro tipo de daño personalizado. + +### Mensaje de Muerte Personalizado + +Puedes definir un mensje de muerte para el tipo de daño en el formato de `death.attack.` en nuestro archivo `en_us.json` de nuestro mod. + +@[code lang=json transclude={4-4}](@/reference/latest/src/main/resources/assets/fabric-docs-reference/lang/en_us.json) + +Cuando suceda una muerta por nuestro tipo de daño, verás el siguiente mensaje: + +![Efecto en el inventario del jugador](/assets/develop/tater-damage-death.png) + +### Etiquetas de Tipo de Daño + +Algunos tipos de daño pueden pasar por la armadura, efectos de estado, y similares. Los Tags (Etiquetas) controlan estos tipos de propiedades de los tipos de daño. + +Puedes encontrar los tags de tipos de daño existentes en `data/minecraft/tags/damage_type`. + +::: info + +Verifica la [Wiki de Minecraft](https://minecraft.wiki/w/Tag#Damage_types) para una lista completa de los tags de tipo de daño. + +::: + +Agreguemos nuestro tipo de daño de Tater al tag de `bypasses_armor`. + +Para agregar nuestro tipo de daño a uno de estos tags, crearemos un archivo JSON bajo el namespace de `minecraft`. + +```:no-line-numbers +data/minecraft/tags/damage_type/bypasses_armor.json +``` + +Con el siguiente contenido: + +@[code lang=json](@/reference/latest/src/main/generated/data/minecraft/tags/damage_type/bypasses_armor.json) + +Asegúrate que tu tag no reemplace el tag existente dándole un valor de `false` a la llave de `replace`. diff --git a/versions/1.20.4/translated/es_es/develop/entities/effects.md b/versions/1.20.4/translated/es_es/develop/entities/effects.md new file mode 100644 index 000000000..aabc8ea4b --- /dev/null +++ b/versions/1.20.4/translated/es_es/develop/entities/effects.md @@ -0,0 +1,69 @@ +--- +title: Efectos de Estado +description: Aprende a añadir efectos de estado personalizados. +authors: + - dicedpixels + - YanisBft + - FireBlast + - Friendly-Banana + - SattesKrokodil +authors-nogithub: + - siglong + - tao0lu +--- + +# Efectos de Estado + +Los efectos de estado, o simplemente estados, son una condición que puede afectar a una entidad. Pueden ser positivos, negativos o neutrales en naturaleza. El juego base aplica estos efectos de varias maneras como comida, pociones, etc. + +El comando `/effect` puede ser usado para aplicar efectos en una entidad. + +## Efectos de Estado Personalizados + +En este tutorial añadiremos un nuevo efecto de estado personalizado llamado _Tater_, el cual te da un punto de experiencia por cada tick del juego. + +### Extiende `StatusEffect` + +Vamos a crear una para nuestro efecto de estado personalizado extendiendo la clase `StatusEffect`, el cual es la clase base para todos los efectos. + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/effect/TaterEffect.java) + +### Registrar tu Efecto Personalizado + +Similar a la registración de bloques e items, usamos `Registry.register` para registrar nuestro efecto personalizado en el registro de `STATUS_EFFECT`. Esto se puede hacer en nuestro inicializador. + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/effect/FabricDocsReferenceEffects.java) + +### Traducciones y Texturas + +Puedes asignar un nombre a tu efecto de estado y proveer una textura de ícono para que aparezca en la pantalla de inventario. + +#### Textura + +El ícono del efecto de estado es una imagen PNG de 18x18 pixeles. Coloca tu ícono personalizado en: + +```:no-line-numbers +resources/assets/fabric-docs-reference/textures/mob_effect/tater.png +``` + +![Efecto en el inventario del jugador](/assets/develop/tater-effect.png) + +#### Traducciones + +Como cualquier otra traducción, puedes agregar una entrada con el formato de ID `"effect..": "Valor"` al archivo de idioma. + +::: code-group + +```json[assets/fabric-docs-reference/lang/en_us.json] +{ + "effect.fabric-docs-reference.tater": "Tater" +} +``` + +### Probando + +Usa el comando `/effect give @p fabric-docs-reference:tater` para darle al jugador nuestro efecto Tater. Usa el comando `/effect clear` para remover el efecto. + +::: info +Para crear una poción que use este efecto, por favor visita la guía sobre [Pociones](../items/potions). +::: diff --git a/versions/1.20.4/translated/es_es/develop/events.md b/versions/1.20.4/translated/es_es/develop/events.md new file mode 100644 index 000000000..25de86e20 --- /dev/null +++ b/versions/1.20.4/translated/es_es/develop/events.md @@ -0,0 +1,124 @@ +--- +title: Eventos +description: Una guía para usar los eventos ofrecidos por el Fabric API. +authors: + - dicedpixels + - mkpoli + - daomephsta + - solidblock + - draylar + - jamieswhiteshirt + - PhoenixVX + - Juuxel + - YanisBft + - liach + - natanfudge +authors-nogithub: + - stormyfabric +--- + +# Eventos + +El Fabric API provee un sistema que le permite a los mods reaccionar a ciertas acciones u ocurrencias, definidas como _eventos_ que ocurren en el juego. + +Los eventos son enganches que satisfacen usos comunes y/o proveen mejor compatibilidad y rendimiento entre diferentes mods que se enganchan a las mismas áreas del código. El uso de eventos substituye el uso de mixins. + +El Fabric API provee eventos para áreas importantes en el código fuente de Minecraft, las cuales son de interés a desarrolladores de mods para engancharse en. + +Los eventos son representados por instancias de `net.fabricmc.fabric.api.event.Event`, el cual guarda y también llama _callbacks_. Usualmente solo hay una instancia del evento para un callback, el cual es almacenado en un miembro estático `EVENT` en la interfaz del callback, pero también hay otros patrones. Por ejemplo, `ClientTickEvents` agrupa varios eventos relacionados juntos. + +## Callbacks + +Un callback es una porción de código pasada como un argumento a un evento. Cuando el evento es activado por el juego, el código pasado será ejecutado. + +### Interfaces de Callbacks + +Cada evento tiene su propia interfaz de callback, convencionalmente llamada `Callback`. Los callbacks son registrados llamando el método `register()` en una instancia del evento, con una instancia de la interfaz del callback como el argumento. + +Todas las interfaces de callbacks para eventos proveídas por el Fabric API pueden ser encontradas en el paquete `net.fabricmc.fabric.api.event`. + +## Detectando Eventos + +### Un Ejemplo Sencillo + +Este ejemplo registra un `AttackBlockCallback` para atacar el jugador cuando este golpea bloques que no sueltan un item cuando son minados con la mano. + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/event/FabricDocsReferenceEvents.java) + +### Añadiendo Items a Loot Tables Existentes + +A veces, uno desea añadir items a loot tables (o tablas que determinan los items soltados por un objeto, como bloque o entidad). Por ejemplo, añadir tus drops a un bloque o entidad vanilla. + +La solución más simple, la cual es reemplazar el archivo del loot table, puede romper otros mods. ¿Qué tal si otros mods también quierer cambiar el loot table? Echaremos un vistazo a como puedes agregar items a los loot tables sin tener que anularla. + +Agregaremos huevos al loot table del bloque de mena de hierro. + +#### Detectando el Cargado de Loot Tables + +El Fabric API tiene un evento que es llamado cuando los loot tables son cargados, llamado `LootTableEvents.MODIFY`. Puedes registrar un callback para el evento en tu inicializador de mod. Verifiquemos también que el loot table actual sea el del bloque de mena de hierro. + +@[code lang=java transclude={38-40}](@/reference/latest/src/main/java/com/example/docs/event/FabricDocsReferenceEvents.java) + +#### Agregando Items al Loot Table + +En los loot tableas, los items son almacenados en _loot pool entries_ (o entradas en el grupo de loots), y las entradas son guardadas en _loot pools_ (o grupos de loot). Para agregar un item, necesitaremos agregar un grupo con una entrada de item al loot table. + +Podemos crear un grupo con `LootPool#builder`, y agregarlo al loot table. + +Nuestro grupo no tiene ningún item, asique haremos una entrada de item usando `ItemEntry#builder`, y la agregaremos al grupo. + +@[code highlight={6-7} transcludeWith=:::2](@/reference/latest/src/main/java/com/example/docs/event/FabricDocsReferenceEvents.java) + +## Eventos Personalizados + +Algunas áreas del juego no tienen enganches proveídos por el Fabric API, así que puedes usar un mixin o puedes crear tu propio evento. + +Veremos como crear un evento que es llamado cuando una oveja es esquilada. El proceso de creación de un evento es: + +- Crear la interfaz de callback del evento +- Activando el evento desde un mixin +- Crear una implementación de prueba + +### Crear la interfaz de callback del evento + +La interfaz de callback describe lo que debe ser implementado por los usuarios del evento que detectarán tu evento. La interfaz del callback también describe como el evento será llamado desde nuestro mixin. Es convencional poner un objecto `Event` como un miembro en la interfaz de callback, el cual identificará nuestro evento. + +Para nuestra implementación de `Event`, escogeremos usar un evento respaldado por un array (array-backed event). El array contendrá todos los escuchadores de evento que están detectando este evento. + +Nuestra implementación llamará los escuchadores de evento en orden hasta que uno de ellos no retorne `ActionResult.PASS`. Esto signfica que un usuario puede decir "_cancela esto_", "_aprueba esto_" o "_no me importa, déjaselo al siguiente escuchador del evento_" usando el valor retornado. + +Usar `ActionResult` como valor de retorno es una manera convencional para hacer que los diferentes usuarios del evento cooperen de esta manera. + +Necesitarás crear una interfaz que tiene una instancia de `Event` y un método para la implementación de la respuesta. Una configuración básica para nuestro callback de esquilado de oveja es: + +@[code lang=java transcludeWith=:::](@/reference/latest/src/main/java/com/example/docs/event/SheepShearCallback.java) + +Veamos este códigdo con más detalle. Cuando el invocador es llamado, iteramos sobre todos los escuchadores: + +@[code lang=java transclude={21-22}](@/reference/latest/src/main/java/com/example/docs/event/SheepShearCallback.java) + +Entonces llamamos nuestro método (en este caso, `interact`), en el escuchador para obtener su respuesta: + +@[code lang=java transclude={33-33}](@/reference/latest/src/main/java/com/example/docs/event/SheepShearCallback.java) + +Si el escuchador dice que tenemos que cancelar (`ActionResult.FAIL`) o terminar completamente (`ActionResult.SUCCESS`), el callback retorna el resultado y termina el loop. `ActionResult.PASS` prosigue al siguiente escuchador, y en la mayoría de los casos debería resultar en éxito si no hay más escuchadores registrados: + +@[code lang=java transclude={25-30}](@/reference/latest/src/main/java/com/example/docs/event/SheepShearCallback.java) + +Podemos agregar Javadocs por encima de las clases de callback para documentar que es lo que hace cada `ActionResult`. En nuestro caso, puede ser: + +@[code lang=java transclude={9-16}](@/reference/latest/src/main/java/com/example/docs/event/SheepShearCallback.java) + +### Activando el Evento Desde un Mixin + +Ya tenemos el esqueleto básico de nuestro evento, pero necesitamos llamarlo o activarlo. Ya que queremos que nuestro evento sea llamado cuando un jugador trata de esquilar una oveja, podemos llamado el invocador `invoker` del evento en `SheepEntity#interactMob`, cuando el método `sheared()` es llamado (osea que la oveja puede ser esquilada, y el jugador está sosteniendo tijeras): + +@[code lang=java transcludeWith=:::](@/reference/latest/src/main/java/com/example/docs/mixin/event/SheepEntityMixin.java) + +### Creando una Implementación de Prueba + +Ahora necesitamos probar nuestro evento. Puedes registrar un escuchador en tu método de inicialización (o en otro lugar, si lo prefieres) y poner tu propio código ahí. En este ejemplo, cuando la oveja es esquilada, suelta un diamante en vez de lana: + +@[code lang=java transcludeWith=:::3](@/reference/latest/src/main/java/com/example/docs/event/FabricDocsReferenceEvents.java) + +Si entras al juego y esquilas una oveja, un diamante debería ser soltado en vez de lana. diff --git a/versions/1.20.4/translated/es_es/develop/getting-started/creating-a-project.md b/versions/1.20.4/translated/es_es/develop/getting-started/creating-a-project.md new file mode 100644 index 000000000..de3b6850b --- /dev/null +++ b/versions/1.20.4/translated/es_es/develop/getting-started/creating-a-project.md @@ -0,0 +1,68 @@ +--- +title: Creando un Proyecto +description: Una guía paso a paso sobre como crear un proyecto de mod usando el generador de plantillas de mods de Fabric. +authors: + - IMB11 +--- + +# Creando un Proyecto + +Fabric provee una manera fácil de crear un nuevo proyecto de mod usando el Generador de Plantillas de Mods de Fabric - si quieres, puedes crear un nuevo proyecto manualmelnte usando el repositorio del mod de ejemplo, deberías visitar la sección de [Creación Manual de Proyectos](#manual-project-creation). + +## Generando un Proyecto + +Puedes usar el [Generador de Plantillas de Mods de Fabric](https://fabricmc.net/develop/template/) para generar un nuevo proyecto para tu mod - deberías llenar los campos requeridos, como el nombre del paquete y el nombre del mod, y la versión de Minecraft para la cual quieres desarrollar. + +![Vista previa del generador](/assets/develop/getting-started/template-generator.png) + +Si quieres usar Kotlin, o quieres agregar generadores de datos, puedes seleccionar las opciones correspondientes en la sección de `Advanced Options` (Opciones Avanzadas). + +![Sección de Opciones Avanzadas](/assets/develop/getting-started/template-generator-advanced.png) + +Una vez llenados los campos requeridos, haz clic en el botón de `Generate` (Generar), y el generador creará un nuevo proyecto para ti en la forma de archivo zip. + +Deberías extraer este archivo zip en un lugar de tu elección, y luego abre el folder extraído en IntelliJ IDEA: + +![Sugerencia de Proyecto Abierto](/assets/develop/getting-started/open-project.png) + +## Importando el Proyecto + +Una vez que has abierto el proyecto en IntelliJ IDEA, el IDEA debería automáticamente cargar las configuraciones de Gradle y realizar las tareas de configuración necesarias. + +Si recibes una notificación que habla sobre un _script_ de Gradle, deberías hacer clic en el botón de `Import Gradle Project` (Importar Proyecto de Gradle): + +![Sugerencia de Gradle](/assets/develop/getting-started/gradle-prompt.png) + +Una vez que el proyecto ha sido importado, deberías ver los archivos del proyecto en el explorador del proyecto, y deberías poder empezar a desarrollar tu mod. + +## Creación Manual de Proyectos + +:::warning +Necesitarás tener instalado [Git](https://git-scm.com/) para clonar el repositorio del mod de ejemplo. +::: + +Si no puedes usar el Generador de Plantillas de Mods de Fabric, puedes crear un nuevo proyecto siguiendo los siguientes pasos. + +Primero, clona el repositorio del mod de ejemplo usando Git: + +```sh +git clone https://github.com/FabricMC/fabric-example-mod/ my-mod-project +``` + +Esto clonará el repositorio a un nuevo folder llamado `my-mod-project`. + +Después, deberías eliminar el folder de `.git` del repositorio clonado, y luego abre el proyecto en IntelliJ IDEA. Si el folder de `.git` no aparece, deberías habilitar la visualización de archivos ocultos en tu administrador de archivos. + +Una vez que has abierto el proyecto en IntelliJ IDEA, el IDEA debería automáticamente cargar las configuraciones de Gradle y realizar las tareas de configuración necesarias. + +Nuevamente, como ya hemos dicho, si recibes una notificación que habla sobre un _script_ de Gradle, deberías hacer clic en el botón de `Import Gradle Project` (Importar Proyecto de Gradle). + +### Modificando La Plantilla + +Una vez que el proyecto ha sido importado, deberías poder modificar los detalles del proyecto para que encajen con los detalles de tu mod: + +- Modifica el archivo de `gradle.properties` de tu proyecto para cambiar las propiedades de `maven_group` (grupo de maven) y `archive_base_name` (nombre base del archivo) para que sean los de tu mod. +- Modifica el archivo de `fabric.mod.json` para cambiar las propiedades de `id`, `name`, y `description` para que sean los de tu mod. +- Asegúrate de actualizar las versiones de Minecraft, los mapeos, el cargador de Fabric y Loom - todos ellos pueden ser consultados en https://fabricmc.net/develop/ - para tener las versiones deseadas. + +Obviamente también puedes cambiar el nombre del paquete y la clase principal para que sean las de tu mod. diff --git a/versions/1.20.4/translated/es_es/develop/getting-started/introduction-to-fabric-and-modding.md b/versions/1.20.4/translated/es_es/develop/getting-started/introduction-to-fabric-and-modding.md new file mode 100644 index 000000000..433c0baed --- /dev/null +++ b/versions/1.20.4/translated/es_es/develop/getting-started/introduction-to-fabric-and-modding.md @@ -0,0 +1,65 @@ +--- +title: Introducción a Fabric y el desarrollo de Mods +description: "Una breve introducción a Fabric y el desarrollo de mods en Minecraft: Edición de Java." +authors: + - IMB11 + - itsmiir +authors-nogithub: + - basil4088 +--- + +# Introducción a Fabric y el desarrollo de Mods + +## Requisitos Previos + +Antes de empezar, deberías tener un entendimiento básico de programación en Java, y conocimiento de Programación Orientada a Objetos (POO). + +Si no estás familiarizados con estos conceptos, deberías investigar algunos tutoriales sobre Java y POO antes de que empiezas a desarrollar mods, aquí hay algunos de los recursos que puedes usar para aprender Java y POO: + +- [W3: Java Tutorials](https://www.w3schools.com/java/) +- [Codecademy: Learn Java](https://www.codecademy.com/learn/learn-java) +- [W3: Java OOP](https://www.w3schools.com/java/java_oop.asp) +- [Medium: Introduction to OOP](https://medium.com/@Adekola_Olawale/beginners-guide-to-object-oriented-programming-a94601ea2fbd) + +### Terminología + +Antes de empezar, veamos algunos de los términos que usaremos cuando desarrollemos mods para Fabric: + +- **Mod**: Una modificación al juego, que añade nuevas funciones o características o que cambia funciones o características existentes. +- **Mod Loader** (Lanzador o Cargador de Mods): Una herramienta que carga los mods en el juego, como el Lanzador de Fabric. +- **Mixin**: Una herramienta para modificar el código del juego durante el tiempo de ejecución - visita [Introducción a los Mixins](https://fabricmc.net/wiki/tutorial:mixin_introduction) para más información. +- **Gradle**: Una herramienta para la automatización de construcción que se usa para compilar y construir los mods, usado por Fabric para construir mods. +- **Mappings** (Mapeos): Un conjunto de mapeos que traducen o "mapean" código ofuscado a código legible. +- **Obfuscation** (Ofuscación): El proceso de hacer que el código sea difícil de entender, usando por Mojang para proteger el código de Minecraft. +- **Remapping** (Remapeado): El proceso de mapear código ofuscado a código legible. + +## ¿Qué es Fabric? + +Fabric is un conjunto de herramientas ligeras para moddear Minecraft: Edición de Java. + +Está diseñado para ser una plataforma de moddeado simple y fácil de entender. Fabric es un proyecto dirigido por la comunidad, y es de fuente abierta, lo que significa que cualquiera puede contribuir al proyecto. + +Deberías saber de los cuatro componentes principales de Fabric: + +- **Fabric Loader** (Lanzador de Fabric): Un lanzador de mods flexible diseñado para Minecraft y otros juegos y aplicaciones, que funciona independiente de la plataforma. +- **Fabric Loom**: Un plugin o extensión de Gradle para desarrollar y depurar mods fácilmente. +- **Fabric API**: Un conjunto de APIs y herramientas para desarrolladores de mods para ser usadas durante la creación de mods. +- **Yarn**: Un conjunto de mapeos de Fabric abiertos. Cualquiera puede usarlos bajo la licencia de Creative Commons Zero. + +## ¿Por qué es necesario Fabric para crear mods para Minecraft? + +> El moddeado es el proceso de modificar el juego con el fin de cambiar su comportamiento y añadir nuevas funciones - en el caso de Minecraft, esto puede ser cualquier cosa, como añadir nuevos items, bloques, o entidades, o cambiar las mecánicas del juego o añadiendo nuevos modos de juego. + +Minecraft: Edición de Java es ofuscado por Mojang, haciendo que la modificación sea dificil por sí sola. Sin embargo, mediante la ayuda de herramientas para la creación de mods como Fabric, la creación de mods se hace mucho más facil. Hay varios sistemas sde mapeo que pueden asistir en el proceso. + +Loom remappea el código ofuscado a código legible usando estos mappings, permitiéndole a los desarrolladores de mods entender y modificar el código del juego. Yarn es una elección popular y excelente para los mpapings, pero también existen otras opciones. Cada proyecto de mappings tiene sus propias ventajas o enfoque. + +Loom te permite fácilmente desarrollar y compilar mods basados en código remapeado, y el Lanzador de Fabric te permite cargar estos mods en el juego. + +## ¿Qué provee el Fabric API, y por qué es necesario? + +> El Fabric API es un conjunto de APIs y herramientas para desarrolladores de mods para ser usadas durante la creación de mods. + +Fabric API provee un conjunto amplio de APIs basadas en la funcionalidad de Minecraft existente - por ejemplo, provee nuevos ganchos y eventos para ser usados por desarrolladores de mods, o provee nuevas utilidades para facilitar el desarrollo de mods - como _access wideners_ (ampliadores de acceso) transitivos y la abilidad de usar registros internos, como el registro de items compostables. + +Mientras que Fabric API ofrece funciones poderosas, algunas tares, como la registración básica de bloques, puede ser lograda sin ella, usando los APIs vanilla. diff --git a/versions/1.20.4/translated/es_es/develop/getting-started/launching-the-game.md b/versions/1.20.4/translated/es_es/develop/getting-started/launching-the-game.md new file mode 100644 index 000000000..b3bc88c95 --- /dev/null +++ b/versions/1.20.4/translated/es_es/develop/getting-started/launching-the-game.md @@ -0,0 +1,63 @@ +--- +title: Corriendo tu Juego +description: Aprende a utilizar los perfiles de lanzamiento varios para cargar y depurar tus mods en un entorno de juego en vivo. +authors: + - IMB11 +--- + +# Corriendo tu Juego + +Fabric Loom provee una variedad de perfiles de lanzamiento para ayudarte a correr y depurar tus mods en un entorno de juego en vivo. Esta guía cubrirá los perfiles de lanzamiento varios y como usarlos para depurar y probar tus mods. + +## Perfiles de Lanzamiento + +Si estás usando IntelliJ IDEA, puedes encontrar los perfiles de lanzamiento en la esquina superior derecha de la ventana. Haz clic en el menú desplegable para ver los perfiles de lanzamiento disponibles. + +Debería haber un perfil para el cliente y el servidor, con la opción de correr cualquiera de los dos normalmente o en modo de depuración: + +![Perfiles de Lanzamiento](/assets/develop/getting-started/launch-profiles.png) + +## Tareas de Gradle + +Si estás usando la línea de comandos, puedes usar los siguientes comandos de Gradle para empezar el juego: + +- `./gradlew runClient` - Lanza el juego en modo de cliente. +- `./gradlew runServer` - Lanza el juego en modo de servidor. + +El único problema con esta opción es que no puedes depurar tu código fácilmente. Si quieres depurar tu código, deberás usar los perfiles de lanzamiento en IntelliJ IDEA o mediante la integración de Gradle de tu IDE. + +## Intercambiar Clases en tiempo de ejecución + +Cuando corres el juego en modo de depuración, puedes intercambiar clases sin tener que reiniciar el juego. Esto es útil para probar cambios en tu código rápidamente. + +Sin embargo, existen varias limitaciones: + +- No puedes agregar o remover métodos +- No puedes cambiar los parámetros de un método +- No puedes agregar o remover miembros + +## Intercambiar Mixins en tiempo de ejecución + +Si estás usando Mixins, puedes intercambiar tus clases de Mixin sin tener que reiniciar el juego. Esto es útil para probar cambios en tu Mixins rápidamente. + +Sin embargo, deberás instalar el _Mixin java agent_ para que esto funcione. + +### 1. Localiza el _Mixin Library Jar_ (Jar de Librería de Mixin) + +En IntelliJ IDEA, puedes encontrar el jar de librería de mixin en la sección de "Librerías Externas" en la sección de "Proyecto": + +![Librería de Mixin](/assets/develop/getting-started/mixin-library.png) + +Deberás copiar el "absolute path" (dirección absoluta) del jar para el siguiente paso. + +### 2. Agrega el argumento de VM de `-javaagent` + +En tus perfiles de lanzamiento de "Minecraft Client" y/o "Minecraft Server", agrega los siguientes argumentos de VM: + +```:no-line-numbers +-javaagent:"dirección absoluta del jar de librería de mixin aquí" +``` + +![Captura de pantalla los Argumentos de VM](/assets/develop/getting-started/vm-arguments.png) + +Ahora deberías poder modificar los contenidos de tus métodos mixin durante la depuración y ver los cambios en el juego sin tener que reiniciarlo. diff --git a/versions/1.20.4/translated/es_es/develop/getting-started/project-structure.md b/versions/1.20.4/translated/es_es/develop/getting-started/project-structure.md new file mode 100644 index 000000000..8923742a1 --- /dev/null +++ b/versions/1.20.4/translated/es_es/develop/getting-started/project-structure.md @@ -0,0 +1,59 @@ +--- +title: Estructura de Proyecto +description: Una descripción general de la estructura de un proyecto de mod de Fabric. +authors: + - IMB11 +--- + +# Estructura de Proyecto + +Esta página cubrirá la estructura de un proyecto de mod de Fabric, y el propósito de cada archivo y folder en el proyecto. + +## `fabric.mod.json` + +El archivo `fabric.mod.json` es el archivo principal que describe tu mod al Lanzador de Fabric. Contiene información como el ID del mod, versión, y dependencias. + +Los campos más importantes en el archivo `fabric.mod.json` son: + +- `id`: El ID del mod, el cual debería ser único. +- `name`: El nombre del mod. +- `enviornment`: El entorno en el que tu mod será corrido en, como `client`, `server` o `*` para ambos. +- `entrypoints`: Los puntos de entrada que tu mod provee, como `main` o `client`. +- `depends:` Los mods en los que tu mod depende en. +- `mixins:` Los mixins que tu mod provee. + +Puedes ver un ejemplo del archivo `fabric.mod.json` abajo - este es el archivo `fabric.mod.json` del proyecto de referencia que este sitio de documentación utiliza. + +:::details Proyecto de Referencia `fabric.mod.json` +@[code lang=json](@/reference/latest/src/main/resources/fabric.mod.json) +::: + +## Puntos de Entrada + +Como ya fue mencionado, el archivo `fabric.mod.json` contiene un campo llamado `entrypoints` - este campo es usado para especificar los puntos de entrada que tu mod usa. + +El generador de plantillas de mods crea los puntos de entrada `main` y `client` por defecto - el punto de entrada de `main` es usado para código común, mientras que el punto de entrada de `client` es usado para código exclusivo o específico para el cliente. Estos puntos de entrada son llamados respectivamente cuando el juego comienza. + +@[code lang=java transcludeWith=#entrypoint](@/reference/latest/src/main/java/com/example/docs/FabricDocsReference.java) + +Lo anterior es un ejemplo de un punto de entrada de `main` simple, el cual manda un mensaje a la consola cuando el juego empieza. + +## `src/main/resources` + +El folder `src/main/resources` es usado para guardar los recursos que tu mod usa, como las texturas, modelos, y sonidos. + +Aquí también se puede encontrar el archivo `fabric.mod.json` y cualquier archivo de configuración de mixin que tu mod use. + +Los _assets_ o recursos son guardados en una estructura que es similar a la estructura de los paquetes de recursos - por ejemplo, una textura para un bloque sería guardada en `assets/modid/textures/block/block.png`. + +## `src/client/resources` + +El folder de `src/client/resources` es usado para guardar recursos específicos al cliente, como las texturas, modelos, y sonidos que solo son usados en el lado del cliente. + +## `src/main/java` + +El folder de `src/main/java` es usado para guardar el código fuente de Java para tu mod - existe tanto los entornos del cliente y el servidor. + +## `src/client/java` + +El folder de `src/client/java` es usado para guardar el código fuente de Java exclusivo del cliente, como código para renderización o lógica para el lado del cliente - como proveedores de colores de bloque. diff --git a/versions/1.20.4/translated/es_es/develop/getting-started/setting-up-a-development-environment.md b/versions/1.20.4/translated/es_es/develop/getting-started/setting-up-a-development-environment.md new file mode 100644 index 000000000..5061e6a03 --- /dev/null +++ b/versions/1.20.4/translated/es_es/develop/getting-started/setting-up-a-development-environment.md @@ -0,0 +1,55 @@ +--- +title: Configurando tu entorno de desarrollo +description: Una guía paso a paso para como configurar un entorno de desarollo para crear mods usando Fabric. +authors: + - IMB11 + - andrew6rant + - SolidBlock-cn + - modmuss50 + - daomephsta + - liach + - telepathicgrunt + - 2xsaiko + - natanfudge + - mkpoli + - falseresync + - asiekierka +authors-nogithub: + - siglong +--- + +# Configurando tu entorno de desarrollo + +Para empezar a desarollar mods usando Fabric, necesitarás configurar un entorno de desarrollo usando IntelliJ IDEA. + +## Instalar Java 17 + +Para desarrollar mods para Minecraft 1.20.4, necesitarás JDK 17. + +Si necesitas ayuda instalando Java, puedes ver nuestras guías sobre la instalación de Java en la [sección de guías para jugadores](../../players/index) + +## Instalando IntelliJ IDEA + +:::info +Obviamente puedes usar otros IDEs, como Eclipse o Visual Studio Code, pero la mayoría de las páginas en esta documentación asumirán que estás usando IntelliJ IDEA - deberías visitar la documentación para tu IDE si estás usando alguno diferente. +::: + +Si no tienes IntelliJ IDEA instalado, puedes descargarlo desde la [página web oficial](https://www.jetbrains.com/idea/download/) - sigue los pasos de instalación para tu sistema operativo. + +La edición de Comunidad de IntelliJ IDEA es gratis y de fuente abierta, y es la versión recomendada para desarrollar mods con Fabric. + +Puede que tengas que deslizar la página hacia abajo para encontrar los enlaces para descargar la edición de Comunidad - se ve de la siguiente manera: + +![Sugerencia de descarga de IntelliJ edición de Comunidad](/assets/develop/getting-started/idea-community.png) + +## Instalando _Plugins_ en IDEA + +Aunque estos plugins no son estrictamente necesarios, hacen el desarrollo de mods con Fabric mucho más fácil - deberías considerar instalarlos. + +### Minecraft Development + +El plugin de Minecraft Development provee soporte para desarrollar mods con Fabric, y es el plugin más importante para instalar. + +Puedes instalarlo abriendo IntelliJ IDEA, y luego navegando a `File > Settings > Plugins > Marketplace Tab` - busca `Minecraft Development` en la barra de búsqueda, y luego haz clic en el botón de `Install` (Instalar). + +Alternativamente, puedes descargarlo desde la [página web del plugin](https://plugins.jetbrains.com/plugin/8327-minecraft-development) y luego puedes instalarlo navegando a `File > Settings > Plutins > Install Plugin from Disk`. diff --git a/versions/1.20.4/translated/es_es/develop/index.md b/versions/1.20.4/translated/es_es/develop/index.md new file mode 100644 index 000000000..83bcdf156 --- /dev/null +++ b/versions/1.20.4/translated/es_es/develop/index.md @@ -0,0 +1,12 @@ +--- +title: Guías para Desarrolladores +description: Nuestras guías para desarrolladores, escritas por la comunidad, cubren una amplia gama de temas, desde la configuración de un entorno de desarrollo hasta temas más avanzados como renderizado y redes. +--- + +# Guías para Desarrolladores + +Nuestras guías para desarrolladores seleccionadas, escritas por la comunidad, cubren una amplia gama de temas, desde la configuración de un entorno de desarrollo hasta temas más avanzados como renderizado y redes. + +Echa un vistazo a la barra lateral para ver una lista de todas las guías para desarrolladores disponibles. Si buscas algo específico, puedes utilizar la barra de búsqueda en la parte superior de la página para encontrar lo que necesitas. + +Si desea contribuir a la Documentación de Fabric, puede encontrar el código fuente en [GitHub](https://github.com/FabricMC/fabric-docs) y las [pautas de contribución](../contributing) relevantes diff --git a/translated/es_es/develop/items/potions.md b/versions/1.20.4/translated/es_es/develop/items/potions.md similarity index 100% rename from translated/es_es/develop/items/potions.md rename to versions/1.20.4/translated/es_es/develop/items/potions.md diff --git a/translated/es_es/develop/rendering/basic-concepts.md b/versions/1.20.4/translated/es_es/develop/rendering/basic-concepts.md similarity index 100% rename from translated/es_es/develop/rendering/basic-concepts.md rename to versions/1.20.4/translated/es_es/develop/rendering/basic-concepts.md diff --git a/versions/1.20.4/translated/es_es/develop/rendering/draw-context.md b/versions/1.20.4/translated/es_es/develop/rendering/draw-context.md new file mode 100644 index 000000000..f9b1b7ba5 --- /dev/null +++ b/versions/1.20.4/translated/es_es/develop/rendering/draw-context.md @@ -0,0 +1,94 @@ +--- +title: Usando el Contexto de Dibujado +description: Aprende a como usar la clase `DrawContext` para renderizar varios objectos, texto y texturas. +authors: + - IMB11 +--- + +# Usando el Contexto de Dibujado + +Esta página asume que ya has visto la página de [Conceptos Básicos de Renderizado](./basic-concepts). + +La clase `DrawContext` es la clase principal usada para renderizar cosas en el juego. Es usada para renderizar objetos, texto y texturas y, como ya hemos visto, es usada para manipular diferentes `MatrixStack`s y usar `BufferBuilder`s. + +## Dibujar Formas + +La clase `DrawContext` puede ser usada para fácilmente dibujar formas **basadas en cuadrados**. Si quieres dibujar triángulos, o cualquier forma no basada en cuadrados, necesitarás usar un `BufferBuilder`. + +### Dibujando Rectángulos + +Puedes usar el método `DrawContext.fill(...)` para dibujar un rectángulo rellenado. + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/client/java/com/example/docs/rendering/DrawContextExampleScreen.java) + +![Un rectángulo](/assets/develop/rendering/draw-context-rectangle.png) + +### Dibujar Contornos/Bordes + +Digamos que queremos delinear el rectángulo que acabamos de dibujar. Podemos usar el método `DrawContext.drawBorder(...)` para dibujar un contorno. + +@[code lang=java transcludeWith=:::2](@/reference/latest/src/client/java/com/example/docs/rendering/DrawContextExampleScreen.java) + +![Rectángulo con bordes](/assets/develop/rendering/draw-context-rectangle-border.png) + +### Dibujar Líneas Individuales + +Podemos usar los métodos `DrawContext.drawHorizontalLine(...)` y `DrawContext.drawVerticalLine(...)` para dibujar líneas. + +@[code lang=java transcludeWith=:::3](@/reference/latest/src/client/java/com/example/docs/rendering/DrawContextExampleScreen.java) + +![Líneas](/assets/develop/rendering/draw-context-lines.png) + +## El _Scissor Manager_ (Gestor de Tijeras) + +La clase `DrawContext` tiene un _scissor manager_ ya incluido. Esto te permite cortar tu renderizado a un área específica. Esto es útil para renderizar cosas como un _tooltip_ (información de herramienta), u otros elementos que no deberían ser renderizados fuera un área en específico. + +### Usando el _Scissor Manager_ + +:::tip +¡Las regiones de tijeras pueden ser anidadas! Pero asegúrate de deshabilitar el _scissor manager_ la misma cantidad de veces que lo habilitaste. +::: + +Para habilitar el _scissor manager_, simplemente usa el método `DrawContext.enableScissor(...)`. De igual forma, para deshabilitar el _scissor manager_, usa el método `DrawContext.disableScissor()`. + +@[code lang=java transcludeWith=:::4](@/reference/latest/src/client/java/com/example/docs/rendering/DrawContextExampleScreen.java) + +![Regiones de tijera en acción](/assets/develop/rendering/draw-context-scissor.png) + +Como puedes ver, aunque le dijimos al juego que renderice la gradiente por toda la pantalla, solo hace dentro de la región de tijera. + +## Dibujar Texturas + +No hay una sola manera "correcta" de dibujar texturas en la pantalla, ya que el método `drawTexture(...)` tiene varias sobrecargas. Esta sección cubrirá los usos más comunes. + +### Dibujar una Textura Entera + +Generalmente, es recomendado que uses la sobrecarga que especifique los parámetros de `textureWidth` y el `textureHeight`. Esto es porque la clase `DrawContext` asumirá estos valores si no los provees, los cuales pueden estar incorrectos algunas veces. + +@[code lang=java transcludeWith=:::5](@/reference/latest/src/client/java/com/example/docs/rendering/DrawContextExampleScreen.java) + +![Ejemplo de diubjar la textura entera](/assets/develop/rendering/draw-context-whole-texture.png) + +### Dibujar una Porción de una Textura + +Aquí es donde `u` y `v` entran en pie. Estos parámetros especifican la esquina superior izquierda de la textura a dibujar, y los parámetros `regionWidth` y `regionHeight` especifican el tamaño de la porción de las texturas a dibujar. + +Tomemos esta textura como ejemplo. + +![Textura del Libro de Recetas](/assets/develop/rendering/draw-context-recipe-book-background.png) + +Si solo queremos dibujar una región que contiene el lente magnificador, podemos usar los siguientes valores para `u`, `v`, `regionWidth`, y `regionHeight`: + +@[code lang=java transcludeWith=:::6](@/reference/latest/src/client/java/com/example/docs/rendering/DrawContextExampleScreen.java) + +![Región de Textura](/assets/develop/rendering/draw-context-region-texture.png) + +## Dibujar Texto + +La clase `DrawContext` tiene varios métodos fáciles de entender para renderizar texto - para ser breves, no serán cubiertos aquí. + +Digamos que queremos dibujar "Hello World" en la pantalla. Podemos usar el método `DrawContext.drawText(...)` para esto. + +@[code lang=java transcludeWith=:::7](@/reference/latest/src/client/java/com/example/docs/rendering/DrawContextExampleScreen.java) + +![Dibujar Texto](/assets/develop/rendering/draw-context-text.png) diff --git a/versions/1.20.4/translated/es_es/develop/rendering/gui/custom-screens.md b/versions/1.20.4/translated/es_es/develop/rendering/gui/custom-screens.md new file mode 100644 index 000000000..93895aa00 --- /dev/null +++ b/versions/1.20.4/translated/es_es/develop/rendering/gui/custom-screens.md @@ -0,0 +1,64 @@ +--- +title: Pantallas Personalizadas +description: Aprende a crear pantallas y menús personalizadas para tu mod. +authors: + - IMB11 +--- + +# Pantallas Personalizadas + +:::info +Esta página se refiere a pantallas normales, y no pantallas manejadas - estas pantallas son las que son abiertas por el jugador en el cliente, no las que son manejadas por el servidor. +::: + +Las pantallas son esencialmente la interfaz gráfica con la que jugador interactúa con, como el menú principal, el menú de pausa, etc. + +Puedes crear tus propios menús para mostrar contenido personalizado, un menú de configuraciones personalizado, o más. + +## Creando una Pantalla + +Para crear una pantalla, necesitarás extender la clase `Screen` y anular el método `init` (inicializar) - opcionalmente también anular el método `render` - pero asegúrate de llamar su implementación súper, de lo contrario no se renderizará el fondo, los widgets, etc. + +Toma en cuenta que: + +- Los widgets no son creados en el constructor de la clase porque la pantalla aún no ha sido inicializada a este punto - y ciertas variables, como `width` (ancho) y `height` (altura), aún no están disponibles o no tienen valores correctos. +- El método `init` es llamado cuando la pantalla es inicializada, y es el mejor lugar para crear widgets. + - Agregas widgets usando el método `addDrawableChild`, el cual acepta cualquier widget dibujable. +- El método `render` es llamado en cada frame - puedes acceder el contexto de dibujado, y la posición del mouse desde este método. + +Por ejemplo, podemos crear una pantalla simple que tiene un botón y una etiqueta arriba. + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/client/java/com/example/docs/rendering/screens/CustomScreen.java) + +![Pantalla Personalizada 1](/assets/develop/rendering/gui/custom-1-example.png) + +## Abrir La Panatalla + +Puedes abrir la pantalla usando el método `setScreen` de la clase `MinecraftClient` - puedes hacer esto desde muchos lugares, como un _key binding_, un comando, o un manipulador de paquetes de cliente. + +```java +MinecraftClient.getInstance().setScreen( + new CustomScreen(Text.empty()) +); +``` + +## Cerrar La Pantalla + +Si quieres cerrar la pantalla, simplemente establece la pantalla actual a un valor `null` (nulo): + +```java +MinecraftClient.getInstance().setScreen(null); +``` + +Si quieres ser más elegante, y retornar a la pantalla anterior, puedes pasar la pantalla actual al constructor de la clase de `CustomScreen` y guardarla en un miembro, y después puedes usarlo para volver a la pantalla anterior cuando el método `close` es llamado. + +@[code lang=java transcludeWith=:::2](@/reference/latest/src/client/java/com/example/docs/rendering/screens/CustomScreen.java) + +Ahora, cuando abramos la pantalla personalizada, puedes pasar la pantalla actual como el segundo argumento - para que cuando llames `CustomScreen#close` - volverá a la pantalla anterior. + +```java +Screen currentScreen = MinecraftClient.getInstance().currentScreen; +MinecraftClient.getInstance().setScreen( + new CustomScreen(Text.empty(), currentScreen) +); +``` diff --git a/versions/1.20.4/translated/es_es/develop/rendering/gui/custom-widgets.md b/versions/1.20.4/translated/es_es/develop/rendering/gui/custom-widgets.md new file mode 100644 index 000000000..fe9476afc --- /dev/null +++ b/versions/1.20.4/translated/es_es/develop/rendering/gui/custom-widgets.md @@ -0,0 +1,39 @@ +--- +title: Widgets Personalizados +description: Aprende a crear widgets personalizados para tus pantallas o menús. +authors: + - IMB11 +--- + +# Widgets Personalizados + +Los widgets son esencialmente componentes renderizados que pueden ser agregados a una pantalla, y que pueden ser usados por el jugador mediante varios eventos como un click del mouse, presionar una tecla, y más. + +## Crear un Widget + +Hay varias maneras de crear una clase widget, como extender `ClickableWidget` (Widget Clickeable). Esta clase provee varias utilidades, como por ejemplo para manejar el ancho, la altura, la posición, y para manejar eventos - implementa las interfaces `Drawable` (Dibujable), `Element` (Elemento), `Narratable` (Narrable), y `Selectable` (Seleccionable): + +- `Drawable` - para renderizar - Requerido para registrar el widget a la pantalla mediante el método `addDrawableChild`. +- `Element` - para eventos - Requerido para manejar eventos como clicks del mouse, cuando se presiona una tecla, y más. +- `Narratable` - para accesibilidad - Requerido para que tu widget sea accesible a lectores de pantalla y otras herramientas de accesibilidad. +- `Seleccionable` - para selecciones - Requerido si quieres que tu widget sea seleccionable usando la tecla Tab - esto también ayuda en accesibilidad. + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/client/java/com/example/docs/rendering/screens/CustomWidget.java) + +## Agregar el Widget a La Pantalla + +Como todos los widgets, necesitarás agregarlo a la pantalla mediante el método `addDrawableChild`, el cual es proveído por la clase `Screen`. Asegúrate de hacerlo en el método `init`. + +@[code lang=java transcludeWith=:::3](@/reference/latest/src/client/java/com/example/docs/rendering/screens/CustomScreen.java) + +![Widget personalizado en la pantalla](/assets/develop/rendering/gui/custom-widget-example.png) + +## Eventos de Widget + +Puedes manejar eventos como clicks del mouse, cuando se presiona una tecla, anulando el método `onMouseClicked` (duranteMouseClickeado), `onMouseReleased` (duranteMouseSoltado), `onKeyPressed` (duranteTeclaPresionada), y otros métodos. + +Por ejemplo, puedes hacer que el widget cambie color cuando el mouse está flotando encima del widget usando el método `isHovering()` proveído por la clase `ClickableWidget`: + +@[code lang=java transcludeWith=:::2](@/reference/latest/src/client/java/com/example/docs/rendering/screens/CustomWidget.java) + +![Ejemplo de Evento de Mouse Flotando](/assets/develop/rendering/gui/custom-widget-events.webp) diff --git a/translated/es_es/develop/rendering/hud.md b/versions/1.20.4/translated/es_es/develop/rendering/hud.md similarity index 100% rename from translated/es_es/develop/rendering/hud.md rename to versions/1.20.4/translated/es_es/develop/rendering/hud.md diff --git a/versions/1.20.4/translated/es_es/develop/rendering/particles/creating-particles.md b/versions/1.20.4/translated/es_es/develop/rendering/particles/creating-particles.md new file mode 100644 index 000000000..05fd06c48 --- /dev/null +++ b/versions/1.20.4/translated/es_es/develop/rendering/particles/creating-particles.md @@ -0,0 +1,72 @@ +--- +title: Creando Partículas Personalizadas +description: Aprende a crear partículas personalizadas usando el Fabric API. +authors: + - Superkat32 +--- + +# Creando Partículas Personalizadas + +Las partículas son una poderosa herramienta. Pueden agregar atmósfera a una hermosa escena, o agregar tensión durante una pelea contra un jefe. ¡Agreguemos una! + +## Registrar una partícula personalizada + +Agregaremos una nueva partícula brillante cuyo movimiento se asemejara al de la partícula de una vara del end. + +Primero tenemos que registrar un `ParticleType` (Tipo de Partícula) en nuestra clase inicializadora de mod usando nuestro _mod id_. + +@[code lang=java transcludeWith=#particle_register_main](@/reference/latest/src/main/java/com/example/docs/FabricDocsReference.java) + +El "sparkle_particle" en letras minúsculas es la dirección JSON para la textura de la partícula. Crearás un archivo JSON con ese mismo nombre más adelante. + +## Registración en el Cliente + +Después de registrar la partícula en la entrada de `ModInitializer`, también necesitarás registrar la partícula en la entrada de `ClientModInitializer` (Inicializador del Mod de Cliente). + +@[code lang=java transcludeWith=#particle_register_client](@/reference/latest/src/client/java/com/example/docs/FabricDocsReferenceClient.java) + +En este ejemplo, estamos registrando nuestra partícula en el lado del cliente. Después estamos dándole movimiento usando la fábrica de partículas de la vara del end. Esto significa que nuestra partícula se moverá exactamente como una partícula de vara del end. + +::: tip +You can see all the particle factories by looking at all the implementations of the `ParticleFactory` interface. This is helpful if you want to use another particle's behaviour for your own particle. + +- Tecla de acceso rápido de IntelliJ: Ctrl+Alt+B +- Tecla de acceso rápido de Visual Studio Code: Ctrl+F12 +::: + +## Crear el archivo JSON y añadir texturas + +Tienes que crear 2 folders in tu folder de `resources/assets//`. + +| Dirección del Folder | Explicación | +| -------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | +| `/textures/particle` | El folder de `particle` (partícula) contendrá todas las texturas para todas tus partículas. | +| `/particles` | El folder de `particles` (partículas) contendrá todos los archivos json de todas tus partículas. | + +Para este ejemplo, solo tendremos una textura en `textures/particle` llamada "sparkle_particle_texture.png". + +Después, creamos un nuevo archivo JSON en `particles` con el mismo nombre que la dirección JSON que usaste para registrar tu `ParticleType`. Para este ejemplo, tendremos que crear `sparkle_particle.json`. Este archivo es importante, ya que le hace saber a Minecraft que texturas debería usar para nuestra partícula. + +@[code lang=json](@/reference/latest/src/main/resources/assets/fabric-docs-reference/particles/sparkle_particle.json) + +:::tip +Puedes agregar más texturas al array de `texturas` para crear una animación de partícula. La partícula rotará las texturas en el array, empezando con la primera textura. +::: + +## Probando la nueva partícula + +¡Una vez que termines tu archivo JSON y hayas guardado tu trabajo, ya puedes iniciar Minecraft y probar que todo esté bien! + +Puedes ver si todo ha funcionado correctamente con el siguiente comando: + +```mcfunction +/particle :sparkle_particle ~ ~1 ~ +``` + +![La partícula siendo mostrada](/assets/develop/rendering/particles/sparkle-particle-showcase.png) + +:::info +La partícula aparecerá dentro de la cabeza del jugador con este comando. Probablemente tengas que caminar para atrás para poder verla. +::: + +También puedes usar un bloque de comandos para invocar la partícula con el mismo comando. diff --git a/versions/1.20.4/translated/es_es/develop/sounds/custom.md b/versions/1.20.4/translated/es_es/develop/sounds/custom.md new file mode 100644 index 000000000..7298c6624 --- /dev/null +++ b/versions/1.20.4/translated/es_es/develop/sounds/custom.md @@ -0,0 +1,63 @@ +--- +title: Crear Sonidos Personalizados +description: Aprende a agregar y usar un nuevo sonido con el registro. +authors: + - JR1811 +--- + +# Crear Sonidos Personalizados + +## Preparando el archivo del sonido + +Tus archivos de sonido tienen que estar formateados de una manera específica. OGG Vorbis es un formato de contenedor abierto para datos multimedia, como audio, y es usado para los archivos de sonido de Minecraft. Para evitar problemas con la manera en que Minecraft maneja el distanciamiento, tu audio tiene que tener solo un canal (Mono). + +Muchos software de DAWs (Estaciones de Trabajo de Audio Digitales) modernos pueden importar y exportar usando este formato de archivo. En el siguiente ejemplo el software gratuito y de fuente abierta "[Audacity](https://www.audacityteam.org/)" será usado para traer el archivo de sonido al formato correcto, aunque cualquier otro DAW debería ser suficiente también. + +![archivo de sonido sin preparar en Audacity](/assets/develop/sounds/custom_sounds_0.png) + +En este ejemplo, un sonido de un [silbido](https://freesound.org/people/strongbot/sounds/568995/) es importado a Audacity. Actualmente está guardado como un archivo ".wav" y tiene dos canales de audio (Stereo). Edita el sonido a tu gusto y asegúrate de eliminar uno de los canales usando el menú desplegable encima del "track head" (cabeza de pista). + +![dividiendo la pista Estereo](/assets/develop/sounds/custom_sounds_1.png) + +![eliminando uno de los canales](/assets/develop/sounds/custom_sounds_2.png) + +Al exportar o renderizar el archivo de audio, asegúrate de elegir el formato de archivo OGG. Algunos DAWs, como REAPER, pueden soportar múltiples capas de audio de OGG. En este caso, OGG Vorbis debería funcionar bien. + +![exportar como archivo OGG](/assets/develop/sounds/custom_sounds_3.png) + +También ten en cuenta que los archivos de audio pueden aumentar el tamaño de tu mod drásticamente. Si es necesario, comprime el audio cuando lo edites y exportes el archivo para mantener el tamaño de tu producto final a un mínimo. + +## Cargando El Archivo de Audio + +Agrega un nuevo folder `resources/assets//sounds` para los sonidos en tu mod, y pon el archivo de audio exportado `metal_whistle.ogg` ahí. + +Continúa creando el archivo `resources/assets//sounds.json` si no existe todavía y agrega tu sonido a las entradas de sonido. + +@[code lang=json](@/reference/latest/src/main/resources/assets/fabric-docs-reference/sounds.json) + +La entrada de subtítulo provee más contexto para el jugador. El nombre del subtítulo es usado en los archivos de lenguaje en el folder de `resources/assets//lang` y serán mostrados si la opción de subtítulos en el juego es activada y el sonido personalizado está siendo reproducido. + +## Registrando el Sonido Personalizado + +Para agregar el sonido personalizado al mod, registra un SoundEvent (Evento de Sonido) en la clase que implemente la interfaz `ModInitializer`. + +```java +Registry.register(Registries.SOUND_EVENT, new Identifier(MOD_ID, "metal_whistle"), + SoundEvent.of(new Identifier(MOD_ID, "metal_whistle"))); +``` + +## Limpiando El Desorden + +Dependiendo de cuantas entradas de Registro hayan, las cosas pueden enredarse rápidamente. Para evitar eso, podemos hacer uso de una nueva clase ayudante. + +Agrega dos nuevos métodos a la nueva clase ayudante creada. Uno, que registre todos los sonidos y uno que es usado para inicializar esta clase en primer lugar. Después de eso, puedes agregar nuevos miembros estáticos de `SoundEvent` cómodamente como sea necesario. + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/sound/CustomSounds.java) + +De esta manera, la clase implementadora de `ModInitializer` solo tiene que implementar una línea para registrar todos los SoundEvents personalizados. + +@[code lang=java transcludeWith=:::2](@/reference/latest/src/main/java/com/example/docs/sound/FabricDocsReferenceSounds.java) + +## Usando el SoundEvent Personalizado + +Use la clase ayudante para acceder el SoundEvent personalizado. Echa un vistazo a la página de [Reproducir SoundEvents (Eventos de Sonido)](./using-sounds) para aprender a reproducir sonidos. diff --git a/versions/1.20.4/translated/es_es/develop/sounds/using-sounds.md b/versions/1.20.4/translated/es_es/develop/sounds/using-sounds.md new file mode 100644 index 000000000..13e12558c --- /dev/null +++ b/versions/1.20.4/translated/es_es/develop/sounds/using-sounds.md @@ -0,0 +1,32 @@ +--- +title: Reproducir SoundEvents (Eventos de Sonido) +description: Aprende a reproducir eventos de sonido. +--- + +# Reproducir SoundEvents (Eventos de Sonido) + +Minecraft tiene una gran selección de sonidos para elegir. Mira la clase de `SoundEvents` para ver todas las instancias de eventos de sonido vanilla que Mojang provee. + +## Usando Sonidos en Tu Mod + +¡Asegúrate de ejecutar el método `playSond()` en el lado del servidor lógico cuando uses sonidos! + +En este ejemplo, los métodos de `useOnEntity()` y `useOnBlock()` para un item interactivo personalizado son usados para reproducir sonidos de "colocar un bloque de cobre" y de saqueador. + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/item/CustomSoundItem.java) + +El método `playSound()` es usado con el objeto de `LivingEntity` (Entidad Viviente). Solamente se tienen que especificar el SoundEvent, el volumen y el tono. También puedes usar el método de `playSound()` de la instancia del mundo para tener un mayor grado de control. + +@[code lang=java transcludeWith=:::2](@/reference/latest/src/main/java/com/example/docs/item/CustomSoundItem.java) + +### SoundEvent y SoundCategory (Categoría de Sonido) + +El SoundEvent define que sonido será reproducido. También puedes [registrar tu propio SoundEvent](./custom) para incluir tu propio sonido. + +Minecraft tiene varios deslizadores de audio en las opciones del juego. El enum (enumeración) de `SoundCategory` es usado para determinar que deslizador ajustará el volumen de tu sonido. + +### Volumen y Tono + +El parámetro de volumen puede ser algo engañoso. El volumen del sonido puede ser cambiado en el rango de `0.0f - 1.0f`. Si el número es mayor que eso, el volumen de `1.0f` será usado y solo la distancia la que tu sonido puede ser escuchado, será ajustada. La distancia en bloques puede ser calculada aproximadamente con `volumen * 16`. + +El parámetro de tono aumenta o disminuye el valor de tono y también cambia la duración del sonido. En el rango `(0.5f - 1.0f)` el tono y la velocidad son disminuídas, mientras que valores números incrementarán el tono y la velocidad. Números por debajo de `0.5f` se mantendrán en el valor de tono de `0.5f`. diff --git a/versions/1.20.4/translated/es_es/index.md b/versions/1.20.4/translated/es_es/index.md new file mode 100644 index 000000000..0600892c2 --- /dev/null +++ b/versions/1.20.4/translated/es_es/index.md @@ -0,0 +1,27 @@ +--- +title: Documentación de Fabric +description: La documentación oficial para Fabric, un conjunto de herramientas para desarrollar mods para Minecraft. +layout: home +hero: + name: Documentación de Fabric + tagline: La documentación oficial seleccionada para Fabric, una cadena de herramientas de modificación para Minecraft. +features: + - title: Guías para Desarrolladores + icon: 🛠️ + details: Nuestras guías para desarrolladores, escritas por la comunidad, cubren una amplia gama de temas, desde la configuración de un entorno de desarrollo hasta temas más avanzados como renderizado y redes. + link: ./develop/index + linkText: Empezar + - title: Guías para Jugadores + icon: 📚 + details: ¿Eres un jugador buscando mods hechos en Fabric? Nuestras guías para jugadores te tienen cubierto. Estas guías te ayudarán en la descarga, instalación, y solución de problemas de mods de Fabric. + link: ./players/index + linkText: Leer más +--- + +
+ +## ¿Quieres contribuir? + +Si quieres contribuir a la Documentación de Fabric, puedes encontrar el código fuente en [GitHub](https://github.com/FabricMC/fabric-docs), y las [pautas de contribución](./contributing) relevantes. + +
diff --git a/versions/1.20.4/translated/es_es/players/faq.md b/versions/1.20.4/translated/es_es/players/faq.md new file mode 100644 index 000000000..76eeda18c --- /dev/null +++ b/versions/1.20.4/translated/es_es/players/faq.md @@ -0,0 +1,31 @@ +--- +title: Preguntas Frecuentes para Jugadores +description: Preguntas frecuentes para jugadores y administradores de servidores relacionadas con Fabric. +--- + +# Preguntas Frecuentes + +Hay varias preguntas que se hacen con frecuencia, por lo que hemos compilado una lista de ellas aquí. + +## Preguntas Generales + +### ¿Qué versiones de Minecraft son compatibles con Fabric? + +Oficialmente, Fabric es compatible con todas las versiones de Minecraft empezando desde la snapshot `18w43b` en adelante, y la versión de salida `1.14` en adelante. + +### ¿Donde puedo descargar mods de Fabric publicados? + +:::info +Siempre debes asegurarte que los mods sean de una fuente confiable. Visita la guía de [Encontrar Mods Confiables](./finding-mods) para mayor información. +::: + +La mayoría de desarrolladores publican sus mods en [Modrinth](https://modrinth.com/mods?g=categories:%27fabric%27) y [CurseForge](https://www.curseforge.com/minecraft/search?page=1&pageSize=20&sortType=1&class=mc-mods&gameFlavorsIds=4), aunque algunos prefieren subir sus mods en sus páginas web personales, o en otras plataformas, como sus repositorios de Github. + +### ¿Dónde puedo encontrar modpacks para Fabric? + +Puedes encontrar modpacks para Fabric en varias plataformas, como: + +- [Modrinth](https://modrinth.com/modpacks?g=categories:%27fabric%27) +- [CurseForge](https://www.curseforge.com/minecraft/search?class=modpacks&gameVersionTypeId=4) +- [Feed The Beast](https://www.feed-the-beast.com/ftb-app) +- [Technic](https://www.technicpack.net/modpacks) diff --git a/versions/1.20.4/translated/es_es/players/finding-mods.md b/versions/1.20.4/translated/es_es/players/finding-mods.md new file mode 100644 index 000000000..5cba3fb50 --- /dev/null +++ b/versions/1.20.4/translated/es_es/players/finding-mods.md @@ -0,0 +1,34 @@ +--- +title: Encontrar Mods Confiables +description: Una guía sobre como encontrar mods de Fabric usando fuentes confiables. +authors: + - IMB11 +--- + +# Encontrar Mods Confiables + +En primer lugar, el término "confiable" es subjetivo, así que siempre usa tu propio juicio y sentido común a la hora de descargar mods. Sin embargo, hay algunas cosas que puedes hacer para encontrar mods confiables. + +## 1. Usa una fuente conocida por su confiabilidad y seguridad + +La mayoría de desarrolladores publican sus mods en [Modrinth](https://modrinth.com/mods?g=categories:%27fabric%27) y [CurseForge](https://www.curseforge.com/minecraft/search?page=1&pageSize=20&sortType=1&class=mc-mods&gameFlavorsIds=4). + +Estas páginas web verifican los mods hacen lo que dicen hacer, y que no contengan código malicioso. También puedes reportar mods maliciosos en esas páginas web, y tomarán acción relativamente rápida. + +## 2. ¡Verifica con otros! + +Si descargas un mod desde una fuente que no es conocida por ser segura, puedes verificar con otros para ver si ellos han descargado el mod antes desde la misma fuente que tu, y verificar si han tenido problemas con ella. + +Si no estás seguro, eres bienvenido a consultar en el servidor de [Discord de Fabric](https://discord.gg/v6v4pMv), en el canal de `#player-support`. + +## 3. ¡Evita sitios con malware comunes! + +:::info +Identificar páginas web con malware no es algo obvio para todos. Si no estás seguro, deberías consultar por opiniones de otros o evitar el sitio completamente y solamente usar fuentes seguras, como Modrinth y CurseForge. +::: + +Hay muchas páginas web que dicen tener mods para Minecraft, pero en realidad solo contienen malware. Debes evitar estos sitios a toda costa. + +Puedes usar software de antivirus y páginas web como [Windows Defender](https://www.microsoft.com/en-us/windows/comprehensive-security) o [VirusTotal](https://www.virustotal.com/) para verificar los mods descargados. Sin embargo, no te bases completamente en esos métodos, ya que pueden producir resultados incorrectos. + +Para reiterar, eres bienvenido a consultar en el servidor de [Discord de Fabric](https://discord.gg/v6v4pMv), en el canal de `#player-support`. diff --git a/versions/1.20.4/translated/es_es/players/index.md b/versions/1.20.4/translated/es_es/players/index.md new file mode 100644 index 000000000..07e88cef4 --- /dev/null +++ b/versions/1.20.4/translated/es_es/players/index.md @@ -0,0 +1,12 @@ +--- +title: Guías para Jugadores +description: Una colección de guías para jugadores y administradores sobre la instalación y el uso de Fabric. +--- + +# Guías para Jugadores + +Esta sección de la Documentación de Fabric está dedicada con jugadores y administradores de servidores que quieren aprender sobre como instalar, y usar, y solucionar problemas relacionados con Fabric. + +Puedes consultar la barra lateral para una lista de las guías disponibles. + +Si encuentras problemas, por favor repórtalos [en GitHub](https://github.com/FabricMC/fabric-docs) o pide ayuda en el servidor de [Discord de Fabric](https://discord.gg/v6v4pMv), en el canal de `#player-support` o `#server-admin-support`. diff --git a/versions/1.20.4/translated/es_es/players/installing-fabric.md b/versions/1.20.4/translated/es_es/players/installing-fabric.md new file mode 100644 index 000000000..8ce64f1ff --- /dev/null +++ b/versions/1.20.4/translated/es_es/players/installing-fabric.md @@ -0,0 +1,55 @@ +--- +title: Instalar Fabric +description: Una guía paso a paso sobre como instalar Fabric. +authors: + - IMB11 +--- + +# Instalar Fabric + +Esta guía te enseñará sobre como instalar Fabric usando el launcher oficial de Minecraft. + +Para launchers o lanzadores de terceros, deberías consultar su documentación. + +## 1. Descarga el instalador de Fabric + +Puedes descargar el instalador de Fabric desde la [Página web de Fabric](https://fabricmc.net/use/). + +Si estás en Windows, descarga el archivo `.exe` (`Download For Windows`), ya que este no requiere que Java esté instalado en tu sistema. Este en cambio usa la instalación de Java que viene con el launcher oficial. + +Si estás en macOS o Linux, descarga la versión `.jar`. En algunas ocasiones, necesitarás instalar Java antes de este paso. + +## 2. Corre el instalador de Fabric + +:::warning +Cierra Minecraft y el Launcher de Minecraft antes de la instalación. +::: + +:::details Información para usuarios de MacOS + +En macOS, puede que tengas que hacer clic derecho en el archivo `.jar` en tu folder de descargas y hacer clic en `Abrir` para correrlo. + +![Instalador de Fabric con "Instalar" remarcado](/assets/players/installing-fabric/macos-downloads.png) + +Cuando aparezca la pregunta "¿Estás seguro de que quieres abrirlo?", has clic en `Abrir` de nuevo. +::: + +Una vez abierto el instalador, deberías ver una pantalla como la siguiente: + +![Instalador de Fabric con "Instalar" remarcado](/assets/players/installing-fabric/installer-screen.png) + +Para instalar Fabric, simplemente escoge tu versión del juego desde el menú deslizador, y cliquea en `Instalar`. + +**Asegurate de que la opción 'Crear Perfil' esté escogida.** + +## 3. ¡Hemos terminado! + +¡Una vez que la instalación haya terminado, puedes abrir el Launcher de Minecraft y seleccionar el perfil de Fabric desde el menú deslizador en la esquina inferior izquierda y presionar Jugar! + +![Launcher de Minecraft con el perfil de Fabric seleccionado](/assets/players/installing-fabric/launcher-screen.png) + +## Siguientes Pasos + +¡Ahora que has instalado Fabric, puedes agregar mods a tu juego! Visita la guía de [Encontrar Mods Confiables](./finding-mods) para mayor información. + +Si encuentras problemas tratando de seguir esta guía, puedes solicitar ayuda en el servidor de [Discord de Fabric](https://discord.gg/v6v4pMv), en el canal de `#player-support`. diff --git a/versions/1.20.4/translated/es_es/players/installing-java/linux.md b/versions/1.20.4/translated/es_es/players/installing-java/linux.md new file mode 100644 index 000000000..deed41f03 --- /dev/null +++ b/versions/1.20.4/translated/es_es/players/installing-java/linux.md @@ -0,0 +1,91 @@ +--- +title: Instalar Java en Linux +description: Una guía paso a paso sobre como instalar Java en Linux. +authors: + - IMB11 +--- + +# Instalar Java en Linux + +Esta guía te enseñará como instalar Java 17 en Linux. + +## 1. Verifica si Java ya está instalado + +Abre una terminal, escribe `java -version`, y presiona Enter. + +![Terminal con el comando "java -version" escrito](/assets/players/installing-java/linux-java-version.png) + +:::warning +Para jugar en la mayoría de las versiones modernas de Minecraft, necesitarás Java 17 como mínimo. Si este comando muestra una versión de Java menor a 17, necesitarás actualizar tu instalación de Java existente. +::: + +## 2. Descargar e Instalar Java 17 + +Recomendamos usar OpenJDK 17, el cual está disponible en múltiples distribuciones de Linux. + +### Arch Linux + +:::info +Para más información sobre como instalar Java en Linux, visita la [Wiki de Arch Linux](https://wiki.archlinux.org/title/Java). +::: + +Puedes instalar el JRE (Entorno de Ejecución de Java) desde los respositorios oficiales: + +```sh +sudo pacman -S jre-openjdk +``` + +Si estás corriendo un servidor sin una interfaz gráfica, puedes instalar la versión "headless" (sin cabecera) en su lugar: + +```sh +sudo pacman -S jre-openjdk-headless +``` + +Si planeas desarrollar mods, necesitarás el JDK (Entorno de Desarrollo de Java) en cambio: + +```sh +sudo pacman -S jdk-openjdk +``` + +### Debian/Ubuntu + +Puedes instalar Java 17 usando `apt` con los siguientes comandos: + +```sh +sudo apt update +sudo apt install openjdk-17-jdk +``` + +### Fedora + +Puedes instalar Java 17 usando `dnf` con los siguientes comandos: + +```sh +sudo dnf install java-17-openjdk +``` + +Si no requieres de una interfaz gráfica, puedes instalar la versión "headless" en su lugar: + +```sh +sudo dnf install java-17-openjdk-headless +``` + +Si planeas desarrollar mods, necesitarás el JDK en cambio: + +```sh +sudo dnf install java-17-openjdk-devel +``` + +### Otras Distribuciones de Linux + +Si tu distribución no está mencionada arriba, puedes descargar el último JRE desde [Adoptium](https://adoptium.net/temurin/) + +Puedes consultar otra guía para tu distribución si planeas desarrollar mods. + +## 3. Verifica si Java 17 ya está instalado + +Una vez terminada la instalación, puedes verificar si Java 17 ya está instalado abriendo una terminal y escribiendo el comando `java -version`. + +Si el comando corre exitosamente, deberías ver algo similar a lo mostrado antes, donde se muestra la versión de Java: + +![Terminal con el comando "java -version" escrito](/assets/players/installing-java/linux-java-version.png) diff --git a/versions/1.20.4/translated/es_es/players/installing-java/windows.md b/versions/1.20.4/translated/es_es/players/installing-java/windows.md new file mode 100644 index 000000000..d469780a8 --- /dev/null +++ b/versions/1.20.4/translated/es_es/players/installing-java/windows.md @@ -0,0 +1,65 @@ +--- +title: Instalar Java en Windows +description: Una guía paso a paso sobre como instalar Java en Windows. +authors: + - IMB11 +--- + +# Instalar en Java en Windows + +Esta guía te enseñará como instalar Java 17 en Windows. + +El launcher de Minecraft viene con su propia instalación de Java, por lo que esta sección solo es relevante si quieres usar el instalador de Fabric `.jar`, o si quieres usar el `.jar` del Servidor de Minecraft. + +## 1. Verifica si Java ya está instalado + +Para comprobar si Java ya está instalado, primero debes abrir la línea de comandos. + +Puedes abrirla presionando Win + R y escribiendo `cmd.exe` en la caja de texto que aparece. + +![Diálogo de Ejecución de Windows con "cmd.exe" en la barra de ejecución](/assets/players/installing-java/windows-run-dialog.png) + +Una vez abierta la línea de comandos, escribe `java -version` y presiona Enter. + +Si el comando corre exitosamente, verás algo similar a esto. Si el comando falla, procede al siguiente paso. + +![Línea de comandos con "java -version" escrito](/assets/players/installing-java/windows-java-version.png) + +:::warning +Para usar la mayoría de las versiones modernas de Minecraft, necesitarás Java 17 instalado como mínimo. Si el comando muestra cualquier versión menor a 17, necesitarás actualizar tu instalación de Java existente. +::: + +## 2. Descarga el instalador de Java 17 + +Para instalar Java 17, debes descargar el instalar desde [Adoptium](https://adoptium.net/en-GB/temurin/releases/?os=windows&package=jdk&version=17). + +Querrás descargar la versión `Windows Installer (.msi)`: + +![Página de descargas de Adoptium con el Windows Installer (.msi) remarcado](/assets/players/installing-java/windows-download-java.png) + +Escoge `x86` si tienes un sistema operativo de 32 bits, o `x64` si tienes un sistema operativo de 64 bits. + +La mayoría de las computadoras modernas tienen un sistema operativo de 64 bits. Si no estás seguro, intenta con la descarga de 64 bits. + +## 3. ¡Corre el instalador! + +Sigue los pasos del instalador para instalar Java 17. Cuando llegues a esta página, debes elegir la opción de "La funcionalidad entera será instalada en el disco duro local" para las siguientes funcionalidades: + +- `Set JAVA_HOME environment variable` - Esto será agregado a tu PATH. +- `JavaSoft (Oracle) registry keys` + +![Instalador de Java 17 con "Set JAVA_HOME variable" y "JavaSoft (Oracle) registry keys" remarcados](/assets/players/installing-java/windows-wizard-screenshot.png) + +Una vez terminado, puedes hacer clic en `Next` y continuar con la instalación. + +## 4. Verificar si Java 17 ya está instalado + +Una vez terminada la instalación, puedes verificar si Java 17 está instalado abriendo la línea de comandos de nuevo y escribiendo `java -version`. + +Si el comando corre exitosamente, verás algo similar a lo mostrado antes, donde la versión de Java se muestra: + +![Línea de comandos con "java -version" escrito](/assets/players/installing-java/windows-java-version.png) + +--- + +Si encuentras problemas, puedes pedir ayuda en el canal de `#player-support` en el servidor de [Discord de Fabric](https://discord.gg/v6v4pMv). diff --git a/versions/1.20.4/translated/es_es/players/installing-mods.md b/versions/1.20.4/translated/es_es/players/installing-mods.md new file mode 100644 index 000000000..af0f12d4d --- /dev/null +++ b/versions/1.20.4/translated/es_es/players/installing-mods.md @@ -0,0 +1,67 @@ +--- +title: Instalar Mods +description: Una guía paso a paso sobre como instalar mods para Fabric. +authors: + - IMB11 +--- + +# Instalar Mods + +Esta guía te enseñará sobre como instalar mods para Fabric usando el Launcher de Minecraft. + +Para launchers o lanzadores de terceros, consulta su documentación. + +## 1. Descarga el Mod + +:::warning +Solo deberías descargar mods desde fuentes en las que confíes. Para mayor información sobre como encontrar mods, visita la guía sobre [Encontrar Mods Confiables](./finding-mods). +::: + +La mayoría de los mods requieren Fabric API, el cual puede ser descargado desde [Modrinth](https://modrinth.com/mod/fabric-api) o [CurseForge](https://curseforge.com/minecraft/mc-mods/fabric-api) + +Cuando descargues mods, asegúrate que: + +- Son compatibles con la versión de Minecraft en la que juegues. Por ejemplo, un mod que funcione en la versión 1.20, puede que no funcione en la versión 1.20.2. +- Son hechos para Fabric y no otro lanzador de mods (mod loader). +- Finalmente, que sean compatibles con la edición de Minecraft correcta (Edición de Java). + +## 2. Mueve el archivo del mod al folder de `mods` + +El folder de mods puede ser encontrado en las siguientes localizaciones dependiendo de tu sistema operativo. + +Usualmente puedes copiar y pegar estas direcciones de archivo en la barra de direcciones de tu explorador de archivos para encontrar el folder rápidamente. + +::: code-group + +```:no-line-numbers [Windows] +%appdata%\.minecraft\mods +``` + +```:no-line-numbers [macOS] +~/Library/Application Support/minecraft/mods +``` + +```:no-line-numbers [Linux] +~/.minecraft/mods +``` + +::: + +Una vez que hayas encontrado el folder de `mods`, puedes colocar el archivo `.jar` del mod ahí. + +![Mods instalados en el folder de mods](/assets/players/installing-mods.png) + +## 3. ¡Hemos terminado! + +¡Una vez que hayas movido los mods al folder de `mods`, puedes abrir el Launcher de Minecraft, seleccionar el perfil de Fabric desde el menú deslizador en la esquina inferior izquierda y presionar Jugar! + +![Launcher de Minecraft con el perfil de Fabric seleccionado](/assets/players/installing-fabric/launcher-screen.png) + +## Solucionar Problemas + +Si encuentras problemas tratando de seguir esta guía, puedes solicitar ayuda en el servidor de [Discord de Fabric](https://discord.gg/v6v4pMv), en el canal de `#player-support`. + +También puedes intentar solucionar el problema tu mismo leyendo las guías sobre como solucionar problemas: + +- [Reportes de Crasheo](./troubleshooting/crash-reports) +- [Subir Logs](./troubleshooting/uploading-logs) diff --git a/versions/1.20.4/translated/es_es/players/troubleshooting/crash-reports.md b/versions/1.20.4/translated/es_es/players/troubleshooting/crash-reports.md new file mode 100644 index 000000000..d4bbbe77c --- /dev/null +++ b/versions/1.20.4/translated/es_es/players/troubleshooting/crash-reports.md @@ -0,0 +1,111 @@ +--- +title: Reportes de Crasheos +description: Aprender sobre que hacer con los reportes de crasheo, y como leerlos. +authors: + - IMB11 +--- + +at snownee.snow.block.ShapeCaches.get(ShapeCaches.java:51) +at snownee.snow.block.SnowWallBlock.method_9549(SnowWallBlock.java:26) // [!code focus] +... +at me.jellysquid.mods.sodium.client.render.chunk.compile.pipeline.BlockOcclusionCache.shouldDrawSide(BlockOcclusionCache.java:52) +at link.infra.indium.renderer.render.TerrainBlockRenderInfo.shouldDrawFaceInner(TerrainBlockRenderInfo.java:31) +... +=================================================== + +:::tip +Si estás teniendo dificultades encontrando la causa del crasheo, puedes pedir ayuda en el servidor de [Discord de Fabric](https://discord.gg/v6v4pMv), en el canal de `#player-support` o `server-admin-support`. +::: + +Los reportes de crasheo son importantes para la solución de problemas con tu juego o servidor. Contienen mucha información sobre el crasheo, y pueden ayudarte a encontrar la causa del crasheo. + +## Encontrar los Reportes de Crasheo + +Los reportes de crasheo se encuentran en el folder de `crash-reports` en el folder de tu juego. Si estás usando un servidor, se encuentran en el folder de `crash-reports` en el folder del servidor. + +Para launchers de terceros, puedes referirte a su documentación sobre donde encontrar los reportes de crasheo. + +Los reportes de crasheo pueden ser encontrados en los siguientes lugares: + +::: code-group + +```:no-line-numbers [Windows] +%appdata%\.minecraft\crash-reports +``` + +```:no-line-numbers [macOS] +~/Library/Application Support/minecraft/crash-reports +``` + +```:no-line-numbers [Linux] +~/.minecraft/crash-reports +``` + +::: + +## Leer los Reportes de Crasheo + +Los reportes de crasheo son muy largos, y pueden ser confusos de leer. Sin embargo, contienen mucha información sobre el crasheo, y pueden ayudarte a encontrar la causa del crasheo. + +Para esta guía, estaremos utilizando el [siguiente reporte de crasheo como ejemplo](https://github.com/FabricMC/fabric-docs/blob/main/public/assets/players/crash-report-example.txt). + +:::details Reportes de Crasheos + +<<< @/public/assets/players/crash-report-example.txt{log} + +::: + +### Secciones del Reporte de Crasheo + +Los reportes de crasheo consisten de varias secciones, cada una separada por un encabezado: + +- `---- Minecraft Crash Report ----`, el resumen del reporte. Esta sección contiene el error principal que ocasionó el crasheo, el tiempo en el que ocurrió, y el stack trace relevante. Esta es la sección más importante del reporte de crasheo, ya que el stack trace usualmente contiene referencias al mod que casuó el crasheo. +- `-- Last Reload --`, esta sección no es muy útil almenos que el crasheo ocurrió durante una recarga de recursos (F3+T). Esta sección contiene el tiempo en el que se hizo la última recarga de recursos, y el stack trace relevante de errores que ocurrieron durante el proceso de recarga. Estos errores usualmente son causados por paquetes de recursos, y pueden ser ignorados al menos que estén causando problemas en el juego. +- `-- System Details --`, esta sección contiene información sobre tu sistema, como el sistema operativo, la versión de Java, y la cantidad de memoria RAM alocada para el juego. Esta sección es útil para determinar si estás usando la versión correcta de Java, y si tienes suficiente memoria alocada para el juego. + - En esta sección, Fabric incluye una línea personalizada que dice `Fabric Mods:`, seguida de una lista de los mods que tienes instalados. Esta sección es útil para determinar si pudo haber ocurrido algún conflicto entre los mods que tienes instalados. + +### Entendiendo el Reporte de Crasheo + +Ahora que sabemos de qué se trata cada sección del reporte de crasheo, podemos empezar a analizar y entender el reporte de crasheo y encontrar la causa del crasheo. + +Usando el ejemplo enlazado arriba, podemos analizar el reporte de crasheo y encontrar la causa del crasheo, incluyendo los mods que causaron el crasheo. + +El stack trace en la sección de `---- Minecraft Crash Report ----` es la más importante en este caso, ya que contiene el error principal que causó el crasheo. En este caso, el error es `java.lang.NullPointerException: Cannot invoke "net.minecraft.class_2248.method_9539()" because "net.minecraft.class_2248.field_10540" is null`. + +Con la cantidad de mods mencionados en el stack trace, puede ser difícil encontrar el mod culpable, pero lo primero que se debe hacer es encontrar el mod que causó el crasheo. + + + +<<< @/public/assets/players/crash-report-example.txt{8-9,14-15 log} + +En este caso, el mod que causó el crasheo es `snownee`, ya que es el primer mod mencionado en el stack trace. + +Sin embargo, con la cantidad de mods mencionados, puede significar que hay problemas de compatibiildad entre los mods, y el mod que causó el crasheo puede que no sea el mod culpable. En este caso, es mejor reportar el crasheo al autor del mod, y dejar que investiguen el crasheo. + +## Crasheos de Mixin + +:::info +Los Mixins son una manea de modificar el juego sin tener que modificar el código fuente del juego. Son usados por muchos mods, y son una herramienta muy útil para desarrolladores de mods. +::: + +Cuando un mixin crashea, usualmente mencionará el mixin en el stack trace, y la clase que el mixin está modificando. + +Los métodos en un mixin contendrán `modid$handlerName` en el stack trace, donde `modid` es el ID del mod, y `handlerName` es el nombre del handler en el mixin. + +```:no-line-numbers +... net.minecraft.class_2248.method_3821$$$modid$handlerName() ... // [!code focus] +``` + +Puedes usar esta información para encontrar el mod que ocasionó el crasheo, y reportar el crasheo al autor del mod. + +## Que hacer con los Reportes de Crasheo + +Lo mejor que puedes hacer con los reportes de crasheo es subirlos a un sitio para pegar texto, y luego compartir el link con el autor del mod, ya sea en su rastreador de problemas o mediante un canal de comunicación (Discord etc). + +Esto le permitirá al autor investigar el crasheo, potencialmente reproducir el problema, y arreglarlo. + +Algunos sitios comunes para pegar texto de reportes de crasheo son: + +- [GitHub Gist](https://gist.github.com/) +- [mclo.gs](https://mclo.gs/) +- [Pastebin](https://pastebin.com/) diff --git a/versions/1.20.4/translated/es_es/players/troubleshooting/uploading-logs.md b/versions/1.20.4/translated/es_es/players/troubleshooting/uploading-logs.md new file mode 100644 index 000000000..d8a23e3a8 --- /dev/null +++ b/versions/1.20.4/translated/es_es/players/troubleshooting/uploading-logs.md @@ -0,0 +1,54 @@ +--- +title: Subir Logs +description: Como subir logs para solucionar problemas. +authors: + - IMB11 +--- + +# Subir Logs + +Durante la solución de problemas, muchas veces es necesario proveer los logs para ayudar a identificar la causa del problema. + +## ¿Porqué debería subir los logs? + +Subir los logs le permite a otros ayudarte a solucionar tus problemas más rápido comparado a simplemente pegar los logs en un chat o en una publicación de foro. También te permite compartir tus logs con otros sin tener que copiar y pegarlos. + +Algunos sitios para pegar texto también remarcan la sintaxis del log, lo cual los hace más facil de leer, y pueden censurar información sensible, como tu nombre de usuario, o información de sistema. + +## Reportes de Crasheos + +Los reportes de crasheo son generados automáticamente cuando tu juego crashea. Solo contienen información sobre el crasheo, más no los logs enteros del juego. Están en el folder de `crash-reports` en el folder del juego. + +Para más información sobre los reportes de crasheo, visita [Reportes de Crasheo](./crash-reports). + +## Encontrar los Logs + +Esta guía cubre el launcher oficial de Minecraft (comúnmente referido como el "launcher vanilla") - para launchers de terceros, puedes consultar su documentación. + +El folder del juego puede ser encontrado en los siguientes lugares dependiendo de tu sistema operativo: + +::: code-group + +```:no-line-numbers [Windows] +%appdata%\.minecraft +``` + +```:no-line-numbers [macOS] +~/Library/Application Support/minecraft +``` + +```:no-line-numbers [Linux] +~/.minecraft +``` + +::: + +El log más recient se llama `latest.log`, mientras que logs anteriores utilizan un patrón de nombramiento como este: `aaaa-mm-dd_numero.log.gz`. + +## Subir Logs + +Los logs pueden ser subidos en una variedad de servicios, como: + +- [Pastebin](https://pastebin.com/) +- [GitHub Gist](https://gist.github.com/) +- [mclo.gs](https://mclo.gs/) diff --git a/versions/1.20.4/translated/es_es/players/updating-fabric.md b/versions/1.20.4/translated/es_es/players/updating-fabric.md new file mode 100644 index 000000000..2c2dc4afe --- /dev/null +++ b/versions/1.20.4/translated/es_es/players/updating-fabric.md @@ -0,0 +1,41 @@ +--- +title: Actualizar Fabric +description: Una guía paso a paso sobre como actualizar Fabric. +authors: + - IMB11 + - modmuss50 +--- + +# Actualizar Fabric + +Esta guía te enseñará como actualizar Fabric desde el Launcher de Minecraft. + +Para launchers o lanzadores de terceros, consulta su documentación. + +El proceso de actualizar Fabric es muy similar al proceso de la instalación de Fabric, por lo que parte de esta guía será la misma que la guía sobre como [Instalar Fabric](./installing-fabric). + +## ¿Porque debería actualizar mi lanzador Fabric? + +Mods más recientes pueden requerir una versión del Lanzador de Fabric más reciente, así que es importante que lo mantengas actualizado para que puedas usar los mods mas recientes. + + + + + +Para actualizar Fabric, simplemente asegurate que la versión del juego y la versión del lanzador de Fabric sean las correctas, y haz click en `Instalar`. + +**Asegurate de no seleccionar la opción de 'Crear Perfil' al correr el instalador, de otro modo creará un nuevo perfil, cosa que no necesitamos en este caso.** + +## 3. Abre el Perfil en el Launcher de Minecraft + +Una vez que la instalación haya terminado, puedes abrir el Launcher de Minecraft e ir a la pestaña de `Instalaciones`. Debes ir a tu perfil de Fabric y abrir la pantalla de edición. + +Reemplaza la versión con la nueva versión del lanzador de Fabric que acabas de instalar, y presiona `Guardar`. + +![Actualizando la versión de Fabric en el Launcher de Minecraft](/assets/players/updating-fabric.png) + +## 4. ¡Hemos terminado! + +¡Una vez completado los pasos, puedes regresar a la pestaña de `Jugar`, seleccionar el perfil de Fabric desde el menú deslizador en la esquina inferior izquierda y presionar Jugar! + +Si encuentras problemas tratando de seguir esta guía, puedes solicitar ayuda en el servidor de [Discord de Fabric](https://discord.gg/v6v4pMv), en el canal de `#player-support`. diff --git a/versions/1.20.4/translated/es_es/sidebar_translations.json b/versions/1.20.4/translated/es_es/sidebar_translations.json new file mode 100644 index 000000000..43db1282b --- /dev/null +++ b/versions/1.20.4/translated/es_es/sidebar_translations.json @@ -0,0 +1,46 @@ +{ + "players.title": "Guías para Jugadores", + "players.faq": "Preguntas Frecuentes", + "players.installingJava": "Instalar Java", + "players.installingJava.windows": "Windows", + "players.installingJava.macOS": "macOS", + "players.installingJava.linux": "Linux", + "players.installingFabric": "Instalando Fabric", + "players.findingMods": "Encontrar Mods Seguros", + "players.installingMods": "Instalar Mods", + "players.troubleshooting": "Solucionar Problemas", + "players.troubleshooting.uploadingLogs": "Subiendo tus Logs", + "players.troubleshooting.crashReports": "Reportes de Crasheos", + "players.updatingFabric": "Actualizando Fabric", + "develop.title": "Guías para Desarrolladores", + "develop.gettingStarted": "Primeros Pasos", + "develop.gettingStarted.introduction": "Introducción a Fabric y el desarrollo de Mods", + "develop.gettingStarted.devEnvSetup": "Configurando tu entorno de desarrollo", + "develop.gettingStarted.creatingProject": "Creando un Proyecto", + "develop.gettingStarted.projectStructure": "Estructura de Proyecto", + "develop.gettingStarted.launchGame": "Corriendo tu Juego", + "develop.items": "Items", + "develop.items.potions": "Pociones", + "develop.entities": "Entidades", + "develop.entities.effects": "Efectos de Estado", + "develop.entities.damage-types": "Tipos de Daño", + "develop.commands": "Comandos", + "develop.commands.basics": "Creando Comandos", + "develop.commands.arguments": "Argumentos", + "develop.commands.suggestions": "Sugerencias", + "develop.rendering": "Renderizado", + "develop.rendering.basicConcepts": "Conceptos Básicos sobre Renderización", + "develop.rendering.drawContext": "Usando el Drawing Context (Contexto de Dibujo)", + "develop.rendering.hud": "Renderizando en el Hud", + "develop.rendering.gui": "Interfaces Gráficas y Menús", + "develop.rendering.gui.customScreens": "Menús Personalizados", + "develop.rendering.gui.customWidgets": "Widgets Personalizados", + "develop.rendering.particles": "Partículas", + "develop.rendering.particles.creatingParticles": "Creando Partículas Personalizadas", + "develop.misc": "Páginas Misceláneas", + "develop.misc.codecs": "Codecs", + "develop.misc.events": "Eventos", + "develop.sounds": "Sonidos", + "develop.sounds.using-sounds": "Reproducir SoundEvents (Eventos de Sonido)", + "develop.sounds.custom": "Crear Sonidos Personalizados" +} \ No newline at end of file diff --git a/versions/1.20.4/translated/fr_fr/develop/codecs.md b/versions/1.20.4/translated/fr_fr/develop/codecs.md new file mode 100644 index 000000000..226c7f129 --- /dev/null +++ b/versions/1.20.4/translated/fr_fr/develop/codecs.md @@ -0,0 +1,397 @@ +--- +title: Codecs +description: Un guide complet pour comprendre et utiliser le système de codecs de Mojang pour la sérialisation et désérialisation d'objets. +authors: + - enjarai + - Syst3ms +--- + +# Codecs + +Les codecs sont un système de sérialisation facile d'objets Java, et est inclus dans la librairie DataFixerUpper (DFU) de Mojang, qui vient avec Minecraft. Dans la création de mods, ils peuvent être utilisés comme une alternative à GSON et Jankson pour lire des fichiers JSON personnalisés. + +Les codecs sont utilisés en tandem avec une autre API de DFU, `DynamicOps`. Un codec définit la structure d'un objet, et les `DynamicOps` (litt. 'opérations dynamiques') définissent un format de (dé)sérialisation, comme JSON ou NBT. Cela signifie que n'importe quel codec peut être utilisé avec n'importe quelles `DynamicOps`, et vice versa, pour une flexibilité accrue. + +## Utilisation des codecs + +### Sérialisation et désérialisation + +En premier lieu, un codec est utilisé pour sérialiser et désérialiser des objets vers et à partir d'un format donné. + +Puisque quelques classes vanilla définissent déjà des codecs, on peut prendre ceux-là en exemple. Mojang fournit également deux `DynamicOps` par défaut, `JsonOps` et `NbtOps`, qui recouvrent la plupart des utilisations. + +Supposons qu'on veuille sérialiser une `BlockPos` en JSON et inversement. C'est possible en utilisant le codec stocké statiquement en `BlockPos.CODEC` avec les méthodes `Codec#encodeStart` et `Codec#parse`, respectivement. + +```java +BlockPos pos = new BlockPos(1, 2, 3); + +// Serialisation de la BlockPos en JsonElement +DataResult result = BlockPos.CODEC.encodeStart(JsonOps.INSTANCE, pos); +``` + +Quand on manipule un codec, les valeurs renvoyées prennent la forme d'un `DataResult` (litt. 'résultat de données'). C'est un adaptateur qui représente soit un succès, soit un échec. On peut l'utiliser de plusieurs façons : si on veut juste la valeur sérialisée, `DataResult#result` renverra un `Optional` contenant la valeur, alors que `DataResult#resultOrPartial` permet également de fournir une fonction pour prendre en charge d'éventuelles erreurs qui se sont produites. La seconde est particulièrement utile pour les ressources de packs de données, où il est souhaitable de signaler les erreurs sans créer de problèmes autre part. + +Prenons donc notre valeur sérialisée et transformons-la en `BlockPos` : + +```java +// Si on écrivait un vrai mod, il faudrait évidemment prendre en charge les Optionals vides +JsonElement json = result.resultOrPartial(LOGGER::error).orElseThrow(); + +// Voici notre valeur JSON, qui devrait correspondre à `[1,2,3]`, +// puisque c'est le format que le codec de BlockPos utilise. +LOGGER.info("BlockPos sérialisée : {}", json); + +// Maintenant on désérialise le JsonElement en BlockPos +DataResult result = BlockPos.CODEC.parse(JsonOps.INSTANCE, json); + +// Encore une fois, on extrait directement notre valeur du résultat +BlockPos pos = result.resultOrPartial(LOGGER::error).orElseThrow(); + +// Et on peut voir qu'on a sérialisé et désérialisé notre BlockPos avec succès ! +LOGGER.info("BlockPos désérialisée : {}", pos); +``` + +### Codecs intégrés + +Comme mentionné ci-dessus, Mojang a déjà défini des codecs pour plusieurs classes vanilla et Java standard, y compris, sans s'y limiter, `BlockPos`, `BlockState`, `ItemStack`, `Identifier`, `Text` et les `Pattern`s regex. Les codecs pour les classes de Mojang sont souvent des champs statiques nommés `CODEC` dans la classe-même, les autres se situant plutôt dans la classe `Codecs`. Par exemple, on peut utiliser `Registries.BLOCK.getCodec()` pour obtenir un `Codec` qui sérialise l'identifiant du bloc et inversement. + +L'API des codecs contient déjà des codecs pour des types primitifs, comme `Codec.INT` et `Codec.STRING`. Ceux-ci sont disponibles statiquement dans la classe `Codec`, et servent souvent de briques pour des codecs plus avancés, comme expliqué ci-dessous. + +## Construction de codecs + +Maintenant qu'on sait utiliser les codecs, regardons comment construire le nôtre. Supposons qu'on ait la classe suivante, et qu'on veuille en désérialiser des instances à partir de fichiers JSON : + +```java +public class CoolBeansClass { + + private final int beansAmount; + private final Item beanType; + private final List beanPositions; + + public CoolBeansClass(int beansAmount, Item beanType, List beanPositions) {...} + + public int getBeansAmount() { return this.beansAmount; } + public Item getBeanType() { return this.beanType; } + public List getBeanPositions() { return this.beanPositions; } +} +``` + +Le fichier JSON correspondant pourrait ressembler à : + +```json +{ + "beans_amount": 5, + "bean_type": "beanmod:mythical_beans", + "bean_positions": [ + [1, 2, 3], + [4, 5, 6] + ] +} +``` + +On peut créer un codec pour cette classe par assemblage de codecs plus simples. Dans ce cas-ci, il en faut un pour chaque champ : + +- un `Codec` +- un `Codec` +- un `Codec>` + +Le premier est un des codecs primitifs de la classe `Codec` mentionnés plus haut, plus précisément `Codec.INT`. Le deuxième s'obtient à partir du registre `Registries.ITEM` et sa méthode `getCodec()` qui renvoie un `Codec`. Il n'y a pas de codec par défaut pour `List`, mais on peut en créer un à partir de `BlockPos.CODEC`. + +### Listes + +`Codec#listOf` crée une version liste de n'importe quel codec : + +```java +Codec> listCodec = BlockPos.CODEC.listOf(); +``` + +À noter que les codecs créés ainsi se désérialisent toujours en `ImmutableList`. Si une liste mutable est nécessaire, on pourrait faire appel à [xmap](#mutually-convertible-types-and-you) pour effectuer la conversion. + +### Fusion de codecs pour les classes similaires à des records + +Avec les codecs pour chaque champ à notre disposition, on peut les combiner en un codec pour la classe avec un `RecordCodecBuilder`. On présuppose ici que la classe a un constructeur avec tous les champs qu'on veut sérialiser, et que ces champs ont des getters associés. C'est idéal pour des classes de type record, mais fonctionne également pour des classes normales. + +Voyons voir comment créer un codec pour notre `CoolBeansClass` : + +```java +public static final Codec CODEC = RecordCodecBuilder.create(instance -> instance.group( + Codec.INT.fieldOf("beans_amount").forGetter(CoolBeansClass::getBeansAmount), + Registries.ITEM.getCodec().fieldOf("bean_type").forGetter(CoolBeansClass::getBeanType), + BlockPos.CODEC.listOf().fieldOf("bean_positions").forGetter(CoolBeansClass::getBeanPositions) + // Jusqu'à 16 champs peuvent être déclarés ici +).apply(instance, CoolBeansClass::new)); +``` + +Chaque argument à la méthode `group` spécifie un codec, un nom de champ, et une méthode getter. L'appel à `Codec#fieldOf` convertit le codec en [codec map](#mapcodec) et celui à `forGetter` indique la méthode getter utilisée pour obtenir la valeur du champ à partir d'une instance de la classe. Enfin, `apply` spécifie le constructeur utilisé pour créer de nouvelles instances. Attention, l'ordre des champs dans la méthode `group` doit être le même que celui des arguments dans le constructeur. + +On peut également utiliser `Codec#optionalFieldOf` dans ce contexte pour rendre un champ facultatif, comme expliqué dans la section [Champs facultatifs](#optional-fields). + +### MapCodec, et non pas Codec<Map> {#mapcodec} + +`Codec#fieldOf` transforme un `Codec` en `MapCodec` qui est une variante de `Codec`, sans en être une implémentation directe. Comme leur nom peut le suggérer, les codecs map sérialisent leurs valeurs dans en maps clés-valeurs, ou plutôt leur équivalent dans les `DynamicOps` utilisées. Certaines fonctions peuvent en nécessiter un au lieu d'un codec normal. + +Essentiellement, cette manière de créer un codec map encapsule simplement la valeur du codec initial dans une map, avec le nom de champ donné pour clé. Par exemple, un `Codec` sérialiserait en JSON ainsi : + +```json +[1, 2, 3] +``` + +Mais quand transformé en `MapCodec` via `BlockPos.CODEC.fieldOf("pos")`, donnerait ceci : + +```json +{ + "pos": [1, 2, 3] +} +``` + +Les codecs map servent principalement à être assemblés afin de construire un codec pour une classe avec plusieurs champs, comme expliqué dans la section [Fusion de codecs pour les classes similaires à des records](#merging-codecs-for-record-like-classes) ci-dessus. + +#### Champs facultatifs + +`Codec#optionalFieldOf` permet de créer un codec map facultatif. Si le champ en question n'est pas présent pendant la désérialisation, celui-ci va le déséraliser soit en `Optional` vide, soit une valeur par défaut donnée. + +```java +// Sans valeur par défaut +MapCodec> optionalCodec = BlockPos.CODEC.optionalFieldOf("pos"); + +// Avec valeur par défaut +MapCodec optionalCodec = BlockPos.CODEC.optionalFieldOf("pos", BlockPos.ORIGIN); +``` + +Attention, les champs facultatifs vont ignorer silencieusement toute erreur lors de la désérialisation. Si le champ est présent mais la valeur invalide, il sera toujours désérialisé en la valeur par défaut. + +**Depuis la 1.20.2**, Minecraft (et non pas DFU!) fournit cependant `Codecs#createStrictOptionalFieldCodec`, qui échoue à désérialiser si la valeur du champ est invalide. + +### Constantes, contraintes et composition + +#### Unit + +`Codec.unit` sert à créer un codec qui désérialise toujours en une valeur constante, indépendamment de l'entrée. Lors de la sérialisation, ce codec ne fera rien. + +```java +Codec leSensDuCodec = Codec.unit(42); +``` + +#### Intervalles numériques + +`Codec.intRange` et ses acolytes `Codec.floatRange` et `Codec.doubleRange` servent à créer un codec qui accepte seulement des valeurs numériques dans un intervalle donné, **bornes incluses**. Cela vaut et pour la sérialisation, et pour la désérialisation. + +```java +// Ne peut excéder 2 +Codec amountOfFriendsYouHave = Codec.intRange(0, 2); +``` + +#### Pair + +`Codec.pair` fusionne deux codecs `Codec
` et `Codec` en un `Codec>`. Il faut garder à l'esprit que cela ne marche correctement qu'avec des codecs qui sérialisent un champ précis, comme [des codec maps convertis](#mapcodec) ou [des codecs records](#merging-codecs-for-record-like-classes). +Le codec résultant sérialisera en une map qui combine les champs des deux codecs utilisés. + +Par exemple, l'exécution de ce code : + +```java +// Création de deux codecs encapsulés distincts +Codec firstCodec = Codec.INT.fieldOf("un_nombre").codec(); +Codec secondCodec = Codec.BOOL.fieldOf("cette_phrase_est_fausse").codec(); + +// Fusion en un codec paire +Codec> pairCodec = Codec.pair(firstCodec, secondCodec); + +// Utilisation pour sérialiser des données +DataResult result = pairCodec.encodeStart(JsonOps.INSTANCE, Pair.of(23, true)); +``` + +Donnera ce JSON en sortie : + +```json +{ + "un_nombre": 23, + "cette_phrase_est_fausse": true +} +``` + +#### Either + +`Codec.either` fusionne deux codecs `Codec` et `Codec` en un `Codec>`. Pendant la désérialisation, le codec résultat essaiera d'utiliser le premier codec, et _seulement si cela échoue_, essaiera d'utiliser le second. +Si le second échoue à son tour, l'erreur du _second_ codec sera renvoyée. + +#### Maps + +Pour gérer des `Map`s avec des clés arbitraires commes des `HashMap`s, `Codec.unboundedMap` peut être utilisé. Celle-ci renvoie un `Codec>`, étant donnés un `Codec` et un `Codec`. Le codec résultant sérialisera en un objet JSON ou équivalent relativement aux `DynamicOps` utilisées. + +À cause de limitations du JSON et du NBT, le codec associé à la clé _doit_ sérialiser en texte. Cela comprend des codecs pour des types qui ne sont pas des textes, mais qui sérialisent ainsi, comme `Identifier.CODEC`. Voir l'exemple suivant : + +```java +// Création d'un codec pour une Map d'identifiants à entiers +Codec> mapCodec = Codec.unboundedMap(Identifier.CODEC, Codec.INT); + +// Utilisation pour sérialiser des données +DataResult result = mapCodec.encodeStart(JsonOps.INSTANCE, Map.of( + new Identifier("example", "nombre"), 23, + new Identifier("example", "le_nombre_plus_cool"), 42 +)); +``` + +Cela donnera ce JSON en sortie : + +```json +{ + "example:nombre": 23, + "example:le_nombre_plus_cool": 42 +} +``` + +Remarquons que ça marche parce que `Identifier.CODEC` sérialise directement en un texte. On peut arriver au même résultat pour des objets qui ne se sérialisent pas en texte grâce à [xmap et compagnie](#mutually-convertible-types-and-you) pour faire la conversion. + +### Les joies des types interconvertibles + +#### xmap + +Supposons qu'on ait deux classes qui peuvent être converties entre elles, mais sans relation parent-enfant. Par exemple, une `BlockPos` et un `Vec3d` vanilla. Si on a un codec pour l'un, `Codec#xmap` permet de créer un codec pour l'autre en donnant une fonction de conversion pour chaque direction. + +`BlockPos` possède déjà un codec, mais imaginons que non. On peut en créer un à partir du codec de `Vec3d` comme ceci : + +```java +Codec blockPosCodec = Vec3d.CODEC.xmap( + // Conversion de Vec3d en BlockPos + vec -> new BlockPos(vec.x, vec.y, vec.z), + // Conversion de BlockPos en Vec3d + pos -> new Vec3d(pos.getX(), pos.getY(), pos.getZ()) +); + +// Si vous convertissez une classe pré-existante (`X` par exemple) +// en une classe à vous (`Y`) ainsi, il peut être pratique +// d'ajouter des méthodes `toX` and `fromX` (statique) à `Y` +// et d'utiliser des références de méthodes dans l'appel à `xmap`. +``` + +#### flatComapMap, comapFlatMap, and flatXMap + +`Codec#flatComapMap`, `Codec#comapFlatMap` et `flatXMap` ressemblent à `xmap`, mais permettent à l'une ou aux deux fonctions de conversions de renvoyer un `DataResult`. C'est utile en pratique car il n'est pas forcément toujours possible de convertir une instance donnée d'un objet. + +Prenons par exemple les `Identifier`s vanilla. Utiliser `xmap` dans ce cas nécessiterait des exceptions inélégantes si la conversion échouait. +Par conséquent, son codec intégré est en réalité un `comapFlatMap` sur `Codec.STRING`, ce qui illustre bien son utilisation : + +```java +public class Identifier { + public static final Codec CODEC = Codec.STRING.comapFlatMap( + Identifier::validate, Identifier::toString + ); + + // ... + + public static DataResult validate(String id) { + try { + return DataResult.success(new Identifier(id)); + } catch (InvalidIdentifierException e) { + return DataResult.error("Not a valid resource location: " + id + " " + e.getMessage()); + } + } + + // ... +} +``` + +Ces méthodes sont très utiles, mais leurs noms sont assez cryptiques, voici donc un tableau pour aider à se souvenir laquelle utiliser : + +| Méthode | A -> B toujours valide ? | B -> A toujours valide ? | +| ----------------------- | ------------------------ | ------------------------ | +| `Codec#xmap` | Oui | Oui | +| `Codec#comapFlatMap` | Non | Oui | +| `Codec#flatComapMap` | Oui | Non | +| `Codec#flatXMap` | Non | Non | + +### Répartition par registre + +Si on définit un registre de codecs, `Codec#dispatch` permet d'utiliser l'un des codecs selon la valeur d'un champ dans les données sérialisées. C'est utile lorsque les objets à désérialiser ont une structure différente selon leur type, mais représentent une même chose. + +Par exemple, imaginons une interface abstraite `Bean` avec deux classes qui l'implémentent : `StringyBean` et `CountingBean`. Pour les sérialiser via une répartition par registre, plusieurs choses sont nécessaires : + +- Des codecs distincts pour chaque type de `Bean`. +- Une classe/record `BeanType` qui représente le type de blob, et peut fournir le codec associé. +- Une méthode de `Bean` qui renvoie son `BeanType`. +- Une map ou un registre pour associer des `Identifier`s à des `BeanType`s. +- Un `Codec>` à partir de ce registre. En utilisant un `net.minecraft.registry.Registry`, cela s'obtient facilement avec `Registry#getCodec`. + +Une fois tout ceci fait, on peut créer un codec de répartition par registre pour les beans : + +@[code transcludeWith=:::](@/reference/latest/src/main/java/com/example/docs/codec/Bean.java) +@[code transcludeWith=:::](@/reference/latest/src/main/java/com/example/docs/codec/BeanType.java) +@[code transcludeWith=:::](@/reference/latest/src/main/java/com/example/docs/codec/StringyBean.java) +@[code transcludeWith=:::](@/reference/latest/src/main/java/com/example/docs/codec/CountingBean.java) +@[code transcludeWith=:::](@/reference/latest/src/main/java/com/example/docs/codec/BeanTypes.java) + +```java +// On peut créer un codec pour les types de bean +// grâce au registre précédemment créé +Codec> beanTypeCodec = BeanType.REGISTRY.getCodec(); + +// Et à partir de ça, un codec de répartition par registre pour beans ! +// Le premier argument est le nom du champ correspondant au type. +// Si omis, il sera égal à "type". +Codec beanCodec = beanTypeCodec.dispatch("type", Bean::getType, BeanType::getCodec); +``` + +Notre nouveau codec sérialisera les beans en JSON ainsi, en n'utilisant que les champs en rapport avec leur type spécifique : + +```json +{ + "type": "example:stringy_bean", + "stringy_string": "Ce bean est textuel !" +} +``` + +```json +{ + "type": "example:counting_bean", + "counting_number": 42 +} +``` + +### Codecs récursifs + +Il est parfois utile d'avoir un codec qui s'utilise _soi-même_ pour décoder certains champs, par exemple avec certaines structures de données récursives. Le code vanilla en fait usage pour les objets `Text`, qui peuvent stocker d'autres `Text`s en tant qu'enfants. Un tel codec peut être construit grâce à `Codecs#createRecursive`. + +À titre d'exemple, essayons de sérialiser une liste simplement chaînée. Cette manière de représenter une liste consiste en des nœuds qui contiennent et une valeur, et une référence au prochain nœud de la liste. La liste est alors représentée par son premier nœud, et pour la parcourir, il suffit de continuer à regarder le nœud suivant juste qu'à ce qu'il n'en existe plus. Voici une implémentation simple de nœuds qui stockent des entiers. + +```java +public record ListNode(int value, ListNode next) {} +``` + +Il est impossible de construire un codec comme d'habitude, puisque quel codec utiliserait-on pour le champ `next` ? Il faudrait un `Codec`, ce qui est précisément ce qu'on veut obtenir ! `Codecs#createRecursive` permet de le faire au moyen d'un lambda magique en apparence : + +```java +Codec codec = Codecs.createRecursive( + "ListNode", // un nom pour le codec + selfCodec -> { + // Ici, `selfCodec` représente le `Codec`, comme s'il était déjà construit + // Ce lambda doit renvoyer le codec qu'on aurait voulu utiliser depuis le départ, + // qui se réfère à lui-même via `selfCodec` + return RecordCodecBuilder.create(instance -> + instance.group( + Codec.INT.fieldOf("value").forGetter(ListNode::value), + // le champ `next` sera récursivement traité grâce à l'auto-codec + Codecs.createStrictOptionalFieldCodec(selfCodec, "next", null).forGetter(ListNode::next) + ).apply(instance, ListNode::new) + ); + } +); +``` + +Un `ListNode` sérialisé pourrait alors ressembler à ceci : + +```json +{ + "value": 2, + "next": { + "value": 3, + "next" : { + "value": 5 + } + } +} +``` + +## Références + +- Il y a une documentation bien plus exhaustive des codecs et des APIs attenantes dans la [JavaDoc DFU non-officielle](https://kvverti.github.io/Documented-DataFixerUpper/snapshot/com/mojang/serialization/Codec). +- La structure globale de ce guide s'inspire beaucoup de [la page du Forge Community Wiki sur les codecs](https://forge.gemwire.uk/wiki/Codecs), qui propose une approche du même sujet plus centrée autour de Forge. diff --git a/versions/1.20.4/translated/fr_fr/develop/commands/arguments.md b/versions/1.20.4/translated/fr_fr/develop/commands/arguments.md new file mode 100644 index 000000000..ec14030c5 --- /dev/null +++ b/versions/1.20.4/translated/fr_fr/develop/commands/arguments.md @@ -0,0 +1,56 @@ +--- +title: Paramètres de Commandes +description: Apprenez comment créer des commandes avec des paramètres complexes. +--- + +# Paramètres de Commandes + +La notion de paramètres est utilisée dans la plupart des commandes. Des fois, ces paramètres peuvent être optionnels, ce qui veut dire que si vous ne donnez pas ce paramètre, la commande va quand même s'exécuter. Un nœud peut avoir plusieurs types de paramètres, mais n'oubliez pas qu'il y a une possibilité d'ambiguïté, qui devrait toujours être évitée. + +@[code lang=java highlight={3} transcludeWith=:::4](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +Dans ce cas d'exemple, après la commande textuelle `/argtater`, vous devez donner un nombre. Par exemple, si vous exécutez `/argtater 3`, vous allez avoir en retour le message `Called /argtater with value = 3`. Si vous tapez `/argater` sans arguments, la commande ne pourra pas être correctement analysée. + +Nous ajoutons ensuite un second paramètre optionnel : + +@[code lang=java highlight={3,13} transcludeWith=:::5](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +Maintenant, vous pouvez donner un ou deux arguments de type nombre à la commande. Si vous donnez un seul nombre, vous allez avoir en retour un texte avec une seule valeur d'affichée. Si vous donnez deux nombres, vous allez avoir en retour un texte avec deux valeurs d'affichées. + +Vous pouvez penser qu'il n'est pas nécessaire de spécifier plusieurs fois des exécutions similaires. Donc, nous allons créer une méthode qui va être utilisée pour les deux cas d'exécution. + +@[code lang=java highlight={3,5,6,7} transcludeWith=:::6](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +## Paramètres de Commande Personnalisés + +Si le type de paramètre de commande dont vous avez besoin n'existe pas en vanilla, vous pouvez toujours le créer par vous-même. Pour le faire, vous avez besoin de créer une nouvelle classe qui hérite l'interface `ArgumentType` où `T` est le type du paramètre. + +Vous devrez implémenter la méthode `parse`, qui va donc analyser la saisie de chaine de caractères afin de la transformer en le type désiré. + +Par exemple, vous pouvez créer un type de paramètre qui transforme une chaine de caractères en `BlockPos` avec le format suivant : `{x, y, z}` + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/command/BlockPosArgumentType.java) + +### Enregistrer les Paramètres de Commande Personnalisés + +:::warning +Vous devez enregistrer votre paramètre de commande personnalisée à la fois sur le serveur et sur le client, sinon dans le cas contraire cette commande ne fonctionnera pas ! +::: + +Vous pouvez enregistrer votre paramètre de commande personnalisé dans la méthode `onInitialize` de l'initialiseur de votre mod en utilisant la classe `ArgumentTypeRegistry` : + +@[code lang=java transcludeWith=:::11](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +### Utiliser les Paramètres de Commande Personnalisés + +Nous pouvons utiliser notre paramètre de commande personnalisé dans une commande, en passant une instance de ce dernier dans la méthode `.argument` du constructeur de commande. + +@[code lang=java transcludeWith=:::10 highlight={3}](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +En exécutant la commande, on peut vérifier si le paramètre de commande fonctionne ou pas : + +![Argument invalide](/assets/develop/commands/custom-arguments_fail.png) + +![Argument valide](/assets/develop/commands/custom-arguments_valid.png) + +![Résultat de commande](/assets/develop/commands/custom-arguments_result.png) diff --git a/versions/1.20.4/translated/fr_fr/index.md b/versions/1.20.4/translated/fr_fr/index.md new file mode 100644 index 000000000..842adce33 --- /dev/null +++ b/versions/1.20.4/translated/fr_fr/index.md @@ -0,0 +1,27 @@ +--- +title: Documentation de Fabric +description: La documentation officielle de Fabric, une chaîne d'outils pour modder Minecraft. +layout: home +hero: + name: Documentation de Fabric + tagline: La documentation officielle de Fabric, une chaîne d'outils pour modder Minecraft. +features: + - title: Developer Guides + icon: 🛠️ + details: Our curated developer guides, written by the community, span a wide range of topics from setting up a development environment to more advanced topics, such as rendering and networking. + link: ./develop/index + linkText: Commencer + - title: Guides des joueurs + icon: 📚 + details: Êtes-vous un joueur envisageant d'utiliser des mods fonctionnant grâce à Fabric ? Nos guides des joueurs sont là pour vous aider. Ces guides vous aideront à télécharger, installer des mods Fabric et résoudre les problèmes pouvant survenir. + link: ./players/index + linkText: En Savoir Plus +--- + +
+ +## Vous souhaitez contribuer ? + +If you want to contribute to the Fabric Documentation, you can find the source code on [GitHub](https://github.com/FabricMC/fabric-docs), and the relevant [contribution guidelines](./contributing). + +
diff --git a/versions/1.20.4/translated/fr_fr/players/faq.md b/versions/1.20.4/translated/fr_fr/players/faq.md new file mode 100644 index 000000000..d09adbc3a --- /dev/null +++ b/versions/1.20.4/translated/fr_fr/players/faq.md @@ -0,0 +1,31 @@ +--- +title: Foire Aux Questions pour les joueurs +description: Foire aux questions pour les joueurs et les administrateurs de serveur liés à Fabric. +--- + +# Foire Aux Questions + +Certaines questions sont posées très fréquemment, donc en voici une liste. + +## Questions générales + +### Quelles versions de Minecraft sont supportées par Fabric ? + +Officiellement, Fabric supporte toutes les versions de Minecraft, les snapshots `18w43b` et ultérieures et les releases `1.14` et ultérieures. + +### Où télécharger des mods Fabric ? + +:::info +Vous devriez toujours vérifier que vos mods proviennent d'une source fiable. Consultez le guide [Trouver des mods](./finding-mods) pour plus d'informations. +::: + +La majorité des auteurs publient leurs mods sur [Modrinth](https://modrinth.com/mods?g=categories:%27fabric%27) et [CurseForge](https://www.curseforge.com/minecraft/search?class=mc-mods&gameVersionTypeId=4), cependant certains peuvent choisir de les mettre en ligne sur leurs sites personnels, ou sur d'autres plateformes, telle qu'un dépot/une repo GitHub. + +### Où puis-je trouver des packs de mods préexistant pour Fabric ? + +Vous pouvez trouver des packs de mods conçu pour Fabric sur une variété de plateformes, telles que : + +- [Modrinth](https://modrinth.com/modpacks?g=categories:%27fabric%27) +- [CurseForge](https://www.curseforge.com/minecraft/search?class=modpacks&gameVersionTypeId=4) +- [Feed The Beast](https://www.feed-the-beast.com/ftb-app) +- [Technic](https://www.technicpack.net/modpacks) diff --git a/versions/1.20.4/translated/fr_fr/players/finding-mods.md b/versions/1.20.4/translated/fr_fr/players/finding-mods.md new file mode 100644 index 000000000..3727470bf --- /dev/null +++ b/versions/1.20.4/translated/fr_fr/players/finding-mods.md @@ -0,0 +1,34 @@ +--- +title: Trouver des mods fiables +description: Un guide pour trouver des mods Fabric depuis des sources fiables. +authors: + - IMB11 +--- + +# Trouver des mods fiables + +La fiabilité d'une source est subjective, et vous devriez toujours juger de par vous-même lorsque vous téléchargez des mods. Mais voici quelques astuces pour vous aider à trouver des mods fiables. + +## 1. Utiliser une source connue pour être fiable + +La majorité des mods sont publiés sur [Modrinth](https://modrinth.com/mods?g=categories:%27fabric%27) ou [CurseForge](https://www.curseforge.com/minecraft/search?page=1&pageSize=20&sortType=1&class=mc-mods&gameFlavorsIds=4). + +Ces sites vérifient que les mods sont bel et bien ce qu'ils prétendent être, et qu'ils ne contiennent pas de code malicieux. Vous pouvez également signaler les mods malicieux sur ces sites, et ces derniers prennent les choses en main relativement rapidement. + +## 2. Voyez avec d'autres personnes ! + +Si vous téléchargez un mod d'une source qui n'est pas réputée pour être fiable, vous devriez voir avec d'autres personnes si elles ont déjà téléchargé le mod depuis la même source, et si elles ont eu des problèmes avec. + +Dans le doute, vous pouvez demander de l'aide sur le [serveur Discord Fabric](https://discord.gg/v6v4pMv) (en anglais) dans le channel `#player-support`. + +## 3. Évitez les sites de malware ! + +:::info +Les sites de malware ne sont pas une évidence pour tout le monde. Si vous n'êtes pas sûr, vous devriez demander l'opinion d'autres personnes ou éviter le site entièrement et uniquement utiliser des sites de confiance, comme Modrinth et CurseForge. +::: + +Il y a plein de sites qui prétendent héberger des mods Minecraft, mais qui ne sont en réalité que des sites de malware. Vous devriez les éviter à tout prix. + +Vous pouvez utiliser des logiciels et sites antivirus comme [Windows Defender](https://www.microsoft.com/en-us/windows/windows-defender) ou [VirusTotal](https://www.virustotal.com/) pour vérifier les mods que vous avez téléchargé. Mais cependant, ne vous fiez pas uniquement à ces méthodes, car elles peuvent parfois être incorrectes. + +Pour rappel, si vous avez un doute, vous êtes le/la bienvenu(e) sur le [serveur Discord Fabric](https://discord.gg/v6v4pMv) pour demander de l'aide dans le channel `#player-support`. diff --git a/versions/1.20.4/translated/fr_fr/players/index.md b/versions/1.20.4/translated/fr_fr/players/index.md new file mode 100644 index 000000000..08377fba7 --- /dev/null +++ b/versions/1.20.4/translated/fr_fr/players/index.md @@ -0,0 +1,12 @@ +--- +title: Guides pour les joueur.ses +description: Une collection de guides pour les joueurs et les administrateurs de serveur sur comment installer et utiliser Fabric. +--- + +# Guides pour les joueur.ses + +Cette section de la documentation de Fabric est destinée aux joueurs et administrateurs serveurs qui souhaitent apprendre comment installer, utiliser et résoudre leurs problèmes avec Fabric. + +La barre latérale contient une liste de tous les guides disponibles. + +Si vous rencontrez de quelconques problèmes avec la documentation, demandez de l'aide sur le [Discord de Fabric](https://discord.gg/v6v4pMv) dans les canaux `#player-support` or `#server-admin-support`, ou signalez-les [sur GitHub](https://github.com/FabricMC/fabric-docs). diff --git a/versions/1.20.4/translated/fr_fr/players/installing-java/linux.md b/versions/1.20.4/translated/fr_fr/players/installing-java/linux.md new file mode 100644 index 000000000..f249e02ec --- /dev/null +++ b/versions/1.20.4/translated/fr_fr/players/installing-java/linux.md @@ -0,0 +1,91 @@ +--- +title: Installer Java sous Linux +description: Un guide étape par étape sur comment installer Java sous Linux. +authors: + - IMB11 +--- + +# Installer Java sous Linux + +Ce guide vous accompagnera dans l'installation de Java 17 sous Linux. + +## 1. Vérifier si Java est déjà installé + +Ouvrez un terminal, entrez `java -version`, et pressez Entrer. + +![Terminal avec "java -version" entré dedans](/assets/players/installing-java/linux-java-version.png) + +:::warning +Pour utiliser la majorité des versions modernes de Minecraft, vous aurez besoin d'avoir au moins Java 17 d'installé. Si cette commande affiche une version inférieure à 17, vous aurez besoin de mettre à jour vous installation Java existante. +::: + +## 2. Télécharger et installer Java 17 + +Nous recommandons d'utiliser OpenJDK 17, qui est disponible sur la plupart des distributions Linux. + +### Arch Linux + +:::info +Pour plus d'information sur comment installer Java sous Arch Linux, consultez le [Wiki d'Arch Linux (Anglais)](https://wiki.archlinux.org/title/Java). +::: + +Vous pouvez installer le dernier JRE depuis les dépots officiels : + +```sh +sudo pacman -S jre-openjdk +``` + +Si vous voulez faire un serveur sans nécéssité d'interface graphique, vous pouvez installer la version sans affiche à la place : + +```sh +sudo pacman -S jre-openjdk-headless +``` + +Si vous prévoyez de développer des mods, vous aurez plutôt besoin du JDK : + +```sh +sudo pacman -S jdk-openjdk +``` + +### Debian/Ubuntu + +Vous pouvez installer Java 17 en utilisant `apt` avec les commandes suivantes : + +```sh +sudo apt update +sudo apt install openjdk-17-jdk +``` + +### Fedora + +Vous pouvez installer Java 17 en utilisant `dnf` avec les commandes suivantes : + +```sh +sudo dnf install java-17-openjdk +``` + +Si vous n'avez pas besoin d'interface graphique, vous pouvez installer la version sans affiche à la place : + +```sh +sudo dnf install java-17-openjdk-headless +``` + +Si vous prévoyez de développer des mods, vous aurez plutôt besoin du JDK : + +```sh +sudo dnf install java-17-openjdk-devel +``` + +### Autres distributions Linux + +Si votre distribution n'est pas listée ci-dessus, vous pouvez télécharger le dernier JRE sur [Adoptium](https://adoptium.net/fr/temurin/) + +Il est recommandé de se référer à un guide alternatif pour votre distribution si vous souhaitez développer des mods. + +## 3. Vérifier que Java 17 est bien installé + +Lorsque l'installation est complète, vous pouvez vérifier que Java 17 est installé en ouvrant un terminal et en entrant `java -version`. + +Si la commande se termine avec succès, vous verrez quelque chose de similaire à avant, où la version de java est affichée : + +![Terminal avec "java -version" entré dedans](/assets/players/installing-java/linux-java-version.png) diff --git a/versions/1.20.4/translated/fr_fr/players/installing-mods.md b/versions/1.20.4/translated/fr_fr/players/installing-mods.md new file mode 100644 index 000000000..9fcfa377f --- /dev/null +++ b/versions/1.20.4/translated/fr_fr/players/installing-mods.md @@ -0,0 +1,67 @@ +--- +title: Installer des mods +description: Un guide pour installer des mods pour Fabric pas à pas. +authors: + - IMB11 +--- + +# Installer des mods + +Ce guide explique en détail le processus d'installation de mods pour Fabric avec le launcher Minecraft officiel. + +Pour les lanceurs tiers, vous devriez consulter leur documentation. + +## 1. Télécharger le mod + +:::warning +Ne téléchargez que des mods provenant de sources dignes de confiance. Pour plus d'informations sur comment trouver des mods, voir le guide [Trouver des mods fiables](./finding-mods). +::: + +La majorité des mods requiert également Fabric API, qui peut être téléchargée depuis [Modrinth](https://modrinth.com/mod/fabric-api) ou [CurseForge](https://curseforge.com/minecraft/mc-mods/fabric-api). + +Lorsque vous téléchargez des mods, assurez-vous : + +- Qu'ils fonctionnent sur la version de Minecraft à laquelle vous souhaitez jouer. Par exemple, un mod qui fonctionne sur la version 1.20 peut ne pas fonctionner sur la version 1.20.2. +- Qu'ils sont pour Fabric et pas un autre mod loader. +- Et qu'ils sont pour la bonne version de Minecraft (Java Edition). + +## 2. Déplacer le mod dans le dossier `mods` + +Le dossier mods peut être trouvé aux emplacements suivants pour chaque système d'exploitation. + +Vous pouvez généralement coller ces chemins dans la barre d'adresse de votre explorateur de fichiers pour naviguer rapidement jusqu'au dossier. + +::: code-group + +```:no-line-numbers [Windows] +%appdata%\.minecraft\mods +``` + +```:no-line-numbers [macOS] +~/Library/Application Support/minecraft/mods +``` + +```:no-line-numbers [Linux] +~/.minecraft/mods +``` + +::: + +Une fois le dossier `mods` trouvé, vous pouvez y déplacer les fichiers `.jar` du mod. + +![Mods installés dans le dossier mods](/assets/players/installing-mods.png) + +## 3. Et voilà ! + +Après avoir déplacé les mods dans le dossier `mods`, vous pouvez ouvrir le launcher Minecraft et sélectionner le profil Fabric depuis le menu déroulant en bas à gauche, puis appuyer sur Jouer. + +![Le lanceur Minecraft avec le profil Fabric sélectionné](/assets/players/installing-fabric/launcher-screen.png) + +## Résolution de problèmes + +Si vous rencontrez des problèmes en suivant ce guide, vous pouvez demander de l'aide dans le [Discord Fabric](https://discord.gg/v6v4pMv) dans le salon `#player-support`. + +Vous pouvez également essayer de dépanner le problème vous-même en utilisant les guides de dépannage : + +- [Rapports de plantage](./troubleshooting/crash-reports) +- [Mettre en ligne des logs](./troubleshooting/uploading-logs) diff --git a/versions/1.20.4/translated/fr_fr/players/updating-fabric.md b/versions/1.20.4/translated/fr_fr/players/updating-fabric.md new file mode 100644 index 000000000..3035600ca --- /dev/null +++ b/versions/1.20.4/translated/fr_fr/players/updating-fabric.md @@ -0,0 +1,41 @@ +--- +title: Mettre à jour Fabric +description: Un guide pour mettre à jour Fabric pas à pas. +authors: + - IMB11 + - modmuss50 +--- + +# Mettre à jour Fabric + +Ce guide explique en détail le processus de mise à jour de Fabric pour le launcher Minecraft. + +Pour les lanceurs tiers, vous devriez consulter leur documentation. + +La mise à jour de Fabric ressemble beaucoup à l'installation de Fabric, donc certains passages seront identiques au guide [Installer Fabric](./installing-fabric). + +## Pourquoi mettre à jour Fabric Loader ? + +De nouveaux mods peuvent nécessiter une version plus récente de Fabric Loader pour fonctionner, il est donc important de le garder à jour pour s'assurer de pouvoir utiliser les mods les plus récents. + + + + + +Pour mettre à jour Fabric, s'assurer que les versions du jeu et de Loader correspondent, puis appuyer sur 'Install' (Installer). + +**Assurez-vous d'avoir décoché 'Créer un profil' en exécutant l'installateur, sinon un nouveau profil sera créé, ce qui est indésirable ici.** + +## 3. Ouvrir le profil dans le launcher Minecraft + +Une fois que l'installateur a terminé, il est désormais possible d'ouvrir le launcher Minecraft et d'aller à l'onglet 'Installations'. Il est recommandé d'aller sur votre profil Fabric et d'ouvrir l'écran d'édition. + +Remplacer la version avec la version de Fabric Loader tout juste installée et appuyer sur 'Sauvegarder'. + +![Mise à jour de la version de Fabric Loader dans le launcher Minecraft](/assets/players/updating-fabric.png) + +## 4. Et voilà ! + +Une fois que ces étapes ont été faites, retourner à l'onglet 'Jeu', sélectionner le profil Fabric depuis le menu déroulant dans le coin inférieur gauche et appuyer sur 'Jouer' ! + +Si vous rencontrez des problèmes en suivant ce guide, vous pouvez demander de l'aide dans le [Discord de Fabric](https://discord.gg/v6v4pMv) dans le salon `#player-support`. diff --git a/versions/1.20.4/translated/fr_fr/sidebar_translations.json b/versions/1.20.4/translated/fr_fr/sidebar_translations.json new file mode 100644 index 000000000..4ce8c95d9 --- /dev/null +++ b/versions/1.20.4/translated/fr_fr/sidebar_translations.json @@ -0,0 +1,46 @@ +{ + "players.title": "Guides des joueurs", + "players.faq": "Foire Aux Questions", + "players.installingJava": "Installer Java", + "players.installingJava.windows": "Windows", + "players.installingJava.macOS": "macOS", + "players.installingJava.linux": "Linux", + "players.installingFabric": "Installer Fabric", + "players.findingMods": "Où trouver des mods fiables", + "players.installingMods": "Installer des mods", + "players.troubleshooting": "Résolution de problèmes", + "players.troubleshooting.uploadingLogs": "Mettre en ligne ses logs", + "players.troubleshooting.crashReports": "Rapports de plantage", + "players.updatingFabric": "Mettre à jour Fabric", + "develop.title": "Guides développeur", + "develop.gettingStarted": "Bien débuter", + "develop.gettingStarted.introduction": "Introduction à Fabric et au modding", + "develop.gettingStarted.devEnvSetup": "Mettre en place votre environnement de développement", + "develop.gettingStarted.creatingProject": "Créer un projet", + "develop.gettingStarted.projectStructure": "Structure du projet", + "develop.gettingStarted.launchGame": "Démarrer votre jeu", + "develop.items": "Les objets", + "develop.items.potions": "Les potions", + "develop.entities": "Entités", + "develop.entities.effects": "Les effets de statut", + "develop.entities.damage-types": "Types de dégâts", + "develop.commands": "Les commandes", + "develop.commands.basics": "Créer des commandes", + "develop.commands.arguments": "Les arguments", + "develop.commands.suggestions": "Les suggestions", + "develop.rendering": "Rendu", + "develop.rendering.basicConcepts": "Concepts élémentaires de rendu", + "develop.rendering.drawContext": "Utiliser le context de dessin", + "develop.rendering.hud": "Afficher dans le Hud", + "develop.rendering.gui": "Écrans et IHMs", + "develop.rendering.gui.customScreens": "Écrans personnalisés", + "develop.rendering.gui.customWidgets": "Widgets personnalisés", + "develop.rendering.particles": "Les particules", + "develop.rendering.particles.creatingParticles": "Créer des particules personnalisées", + "develop.misc": "Pages diverses", + "develop.misc.codecs": "Les codecs", + "develop.misc.events": "Les événements", + "develop.sounds": "Sons", + "develop.sounds.using-sounds": "Jouer SoundEvents", + "develop.sounds.custom": "Créer des sons personnalisés" +} \ No newline at end of file diff --git a/versions/1.20.4/translated/it_it/contributing.md b/versions/1.20.4/translated/it_it/contributing.md new file mode 100644 index 000000000..21a3e5bd1 --- /dev/null +++ b/versions/1.20.4/translated/it_it/contributing.md @@ -0,0 +1,242 @@ +--- +title: Linee Guida per la Contribuzione +description: Linee guida per le contribuzioni alla Documentazione di Fabric. +--- + +# Linee Guida per la Contribuzione {#contributing} + +Questo sito usa [VitePress](https://vitepress.dev/) per generare HTML statico da vari file Markdown. Dovresti familiarizzare con le estensioni per Markdown che VitePress supporta [qui](https://vitepress.dev/guide/markdown#features). + +Ci sono tre modi per contribuire a questo sito: + +- [Tradurre la Documentazione](#translating-documentation) +- [Contribuire con Contenuti](#contributing-content) +- [Contribuire al Framework](#contributing-framework) + +Tutte le contribuzioni devono seguire le nostre [linee guida per lo stile](#style-guidelines). + +## Tradurre la Documentazione {#translating-documentation} + +Se vuoi tradurre la documentazione nella tua lingua, puoi farlo nella [pagina Crowdin di Fabric](https://crowdin.com/project/fabricmc). + +## Contribuire con Contenuti {#contributing-content} + +Le contribuzioni con contenuti sono il modo principale per contribuire alla Documentazione di Fabric. + +Tutte le contribuzioni con contenuti passano per tre fasi: + +1. Indicazioni per l'Espansione (se necessaria) +2. Verifica dei Contenuti +3. Pulizia (Grammatica ecc.) + +Tutto il contenuto deve rispettare le nostre [linee guida per lo stile](#style-guidelines). + +### 1. Prepara le Tue Modifiche {#1-prepare-your-changes} + +Il sito è open-source, ed è sviluppato in una repository su GitHub, il che significa che ci affidiamo al flow GitHub: + +1. [Crea una fork della Repository su GitHub](https://github.com/FabricMC/fabric-docs/fork) +2. Crea un nuovo branch sulla tua fork +3. Aggiungi le tue modifiche su quel branch +4. Apri una Pull Request alla repository originale + +Puoi leggere di più riguardo al flow GitHub [qui](https://docs.github.com/en/get-started/using-github/github-flow). + +È possibile fare modifiche dall'interfaccia web su GitHub, oppure puoi sviluppare e ottenere un'anteprima del sito localmente. + +#### localmente Clonare la Tua Fork {#clone-your-fork} + +Se vuoi sviluppare localmente, dovrai installare [Git](https://git-scm.com/). + +Dopo di che, clona la tua fork della repository con: + +```sh +# assicurati di sostituire "nome-utente" con il tuo nome utente +git clone https://github.com/nome-utente/fabric-docs.git +``` + +#### localmente Installare le Dipendenze {#install-dependencies} + +Se vuoi ottenere un'anteprima locale delle tue modifiche, dovrai installare [Node.js 18+](https://nodejs.org/en/). + +Dopo di che, assicurati di installare tutte le dipendenze con: + +```sh +npm install +``` + +#### localmente Eseguire il Server di Sviluppo {#run-the-development-server} + +Questo di permetterà di ottenere un'anteprima locale delle tue modifiche presso `localhost:5173` e ricaricherà automaticamente la pagina quando farai modifiche. + +```sh +npm run dev +``` + +Ora puoi aprire e navigare sul sito dal browser visitando `http://localhost:5173`. + +#### localmente Costruire il Sito {#building-the-website} + +Questo compilerà tutti i file Markdown in HTML statico e li posizionerà in `.vitepress/dist`: + +```sh +npm run build +``` + +#### localmente Ottenere un'Anteprima del Sito Costruito {#previewing-the-built-website} + +Questo avvierà un server locale in porta `4173` che servirà il contenuto trovato in `.vitepress/dist`: + +```sh +npm run preview +``` + +#### localmente Aprire una Pull Request {#opening-a-pull-request} + +Quando sarai felice delle tue modifiche, puoi fare `push` delle tue modifiche: + +```sh +git add . +git commit -m "Description of your changes" +git push +``` + +Dopo di che segui il link nell'output di `git push` per aprire una PR. + +### 2. Indicazioni per l'Espansione Se Necessaria {#2-guidance-for-expansion-if-needed} + +Se il team della documentazione crede che tu possa espandere la tua pull request, un membro del team aggiungerà l'etichetta `can-expand` alla tua pull request assieme a un commento che spiega cosa credono che tu possa espandere. Se sei d'accordo con il consiglio, puoi espandere la tua pull request. + +Non sentirti obbligato a espandere la tua pull request. Se non vuoi espandere la tua pull request, puoi semplicemente chiedere che l'etichetta `can-expand` venga rimossa. + +Se non vuoi espandere la tua pull request, ma ti va bene che qualcun altro lo faccia successivamente, sarebbe meglio creare un'issue sulla [pagina Issues](https://github.com/FabricMC/fabric-docs/issues) e spiegare cosa credi che si possa espandere. + +### 3. Verifica dei Contenuti {#3-content-verification} + +Tutte le pull request che aggiungono contenuti sono sottoposte a verifica dei contenuti, questa è la fase più importante poiché assicura che il contenuto sia accurato e segua le linee guida per lo stile della Documentazione di Fabric. + +### 4. Pulizia {#4-cleanup} + +Questa fase è quella dove il team della documentazione correggerà ogni errore grammaticale e farà altre modifiche che crede siano necessarie prima di unire la pull request! + +## Contribuire al Framework {#contributing-framework} + +Framework si riferisce alla struttura interna del sito, ogni pull request che modifica il framework del sito dovrebbe essere etichettata con l'etichetta `framework`. + +Dovresti davvero fare pull request riguardanti il framework solo dopo esserti consultato con il team della documentazione nel [Discord di Fabric](https://discord.gg/v6v4pMv) o tramite un'issue. + +::: info +Modificare i file nella sidebar e la configurazione della barra di navigazione non conta come pull request riguardante il framework. +::: + +## Linee Guida per lo Stile {#style-guidelines} + +Se fossi incerto riguardo a qualsiasi cosa, puoi chiedere nel [Discord di Fabric](https://discord.gg/v6v4pMv) o tramite GitHub Discussions. + +### Scrivi l'Originale in Inglese Americano {#write-the-original-in-american-english} + +Tutta la documentazione originale è scritta in inglese, seguendo le regole grammaticali americane. + +Anche se potresti usare [LanguageTool](https://languagetool.org/) per controllare la tua grammatica mentre scrivi, non preoccupartene troppo. Il nostro team di documentazione revisionerà e correggerà la grammatica durante la fase di pulizia. Tuttavia, fare uno sforzo perché sia corretta già dall'inizio può farci risparmiare del tempo. + +### Aggiungi i Dati al Frontmatter {#add-data-to-the-frontmatter} + +Ogni pagina deve avere un titolo (`title`) e una descrizione (`description`) nel frontmatter. + +Ricordati anche di aggiungere il tuo nome utente GitHub ad `authors` nel frontmatter del file Markdown! In questo modo possiamo darti l'attribuzione che meriti. + +```md +--- +title: Titolo della Pagina +description: Questa è la descrizione della pagina. +authors: + - nome-utente +--- + +# Titolo della Pagina {#title-of-the-page} + +... +``` + +### Aggiungi Ancore alle Intestazioni {#add-anchors-to-headings} + +Ogni intestazione deve avere un'ancora, che viene utilizzata per collegarsi a quell'intestazione: + +```md +# Questa È un'Intestazione {#questa-e-un-intestazione} +``` + +L'ancora deve usare caratteri minuscoli, numeri e trattini. + +### Posiziona il Codice Nella Mod `/reference` {#place-code-within-the-reference-mod} + +Se crei o modifichi pagine contenenti codice, metti il codice in una posizione appropriata nella mod reference (presente nella cartella `/reference` della repository). Dopo di che, usa la [funzione code snippet fornita da VitePress](https://vitepress.dev/guide/markdown#import-code-snippets) per incorporare il codice. + +Per esempio, per evidenziare le linee 15-21 del file `FabricDocsReference.java` dalla mod reference: + +::: code-group + +```md +<<< @/reference/latest/src/main/java/com/example/docs/FabricDocsReference.java{15-21} +``` + +<<< @/reference/latest/src/main/java/com/example/docs/FabricDocsReference.java{15-21}[java] + +::: + +Se ti serve un controllo più raffinato, puoi usare la [funzione transclude da `markdown-it-vuepress-code-snippet-enhanced`](https://github.com/fabioaanthony/markdown-it-vuepress-code-snippet-enhanced). + +Per esempio, questo incorporerà le sezioni del suddetto file che sono contrassegnate con il tag `#entrypoint`: + +::: code-group + +```md +@[code transcludeWith=#entrypoint](@/reference/latest/src/main/java/com/example/docs/FabricDocsReference.java) +``` + +@[code transcludeWith=#entrypoint](@/reference/latest/src/main/java/com/example/docs/FabricDocsReference.java) + +::: + +### Crea una Barra Laterale per Ogni Nuova Sezione {#create-a-sidebar-for-each-new-section} + +Se stai creando una nuova sezione, dovresti creare una nuova barra laterale nella cartella `.vitepress/sidebars` ed aggiungerla al file `i18n.ts`. + +Se hai bisogno di assistenza con questo, chiedi per favore nel canale `#docs` del [Discord di Fabric](https://discord.gg/v6v4pMv). + +### Aggiungi Nuove Pagine alle Barre Laterali Appropriate {#add-new-pages-to-the-relevant-sidebars} + +Quando crei una nuova pagina, dovresti aggiungerla alla barra laterale appropriata nella cartella `.vitepress/sidebars`. + +Di nuovo, se hai bisogno di assistenza, chiedi nel canale `#docs` del Discord di Fabric. + +### Posiziona i Contenuti Multimediali in `/assets` {#place-media-in-assets} + +Ogni immagine dovrebbe essere messa in una posizione appropriata nella cartella `/public/assets/`. + +### Usa Link Relativi! {#use-relative-links} + +Questo è dovuto al sistema di gestione delle versioni in uso, che processerà i link per aggiungerci la versione anticipatamente. Se usassi link assoluti, il numero di versione non verrebbe aggiunto al link. + +Devi anche non aggiungere l'estensione del file al link. + +Per esempio, per inserire un link alla pagina `/players/index.md` dalla pagina `/develop/index.md`, dovresti fare il seguente: + +::: code-group + +```md:no-line-numbers [✅ Correct] +Questo è un link relativo! +[Pagina](../players/index) +``` + +```md:no-line-numbers [❌ Wrong] +Questo è un link assoluto. +[Pagina](/players/index) +``` + +```md:no-line-numbers [❌ Wrong] +Questo link relativo ha l'estensione del file. +[Pagina](../players/index.md) +``` + +::: diff --git a/versions/1.20.4/translated/it_it/develop/codecs.md b/versions/1.20.4/translated/it_it/develop/codecs.md new file mode 100644 index 000000000..f44de98e4 --- /dev/null +++ b/versions/1.20.4/translated/it_it/develop/codecs.md @@ -0,0 +1,398 @@ +--- +title: Codec +description: Una guida esaustiva per la comprensione e l'uso del sistema di codec di Mojang per serializzare e deserializzare gli oggetti. +authors: + - enjarai + - Syst3ms +--- + +# Codec + +Un codec è un sistema per serializzare facilmente oggetti Java, ed è incluso nella libreria DataFixerUpper (DFU) di Mojang, che è inclusa in Minecraft. Nel contesto del modding essi possono essere usati come un'alternativa a GSON e Jankson quando si leggono e si scrivono file json personalizzati, anche se hanno cominciato a diventare sempre più rilevanti, visto che Mojang sta riscrivendo molto suo codice in modo che usi i Codec. + +I Codec vengono usati assieme a un'altra API da DFU, `DynamicOps`. Un codec definisce la struttura di un oggetto, mentre i dynamic ops vengono usati per definire un formato da cui e a cui essere serializzato, come json o NBT. Questo significa che qualsiasi codec può essere usato con qualsiasi dynamic ops, e viceversa, permettendo una grande flessibilità. + +## Usare i Codec + +### Serializzazione e Deserializzazione + +L'utilizzo basilare di un codec è serializzare e deserializzare oggetti da e a un formato specifico. + +Poiché alcune classi vanilla hanno già dei codec definiti, possiamo usare quelli come un esempio. Mojang ci ha anche fornito due classi di dynamic ops predefinite, `JsonOps` e `NbtOps`, che tendono a coprire la maggior parte degli casi. + +Ora, immaginiamo di voler serializzare un `BlockPos` a json e viceversa. Possiamo fare questo usando il codec memorizzato staticamente presso `BlockPos.CODEC` con i metodi `Codec#encodeStart` e `Codec#parse`, rispettivamente. + +```java +BlockPos pos = new BlockPos(1, 2, 3); + +// Serializza il BlockPos a un JsonElement +DataResult result = BlockPos.CODEC.encodeStart(JsonOps.INSTANCE, pos); +``` + +Quando si usa un codec, i valori sono restituiti come un `DataResult`. Questo è un wrapper che può rappresentare un successo oppure un fallimento. Possiamo usare questo in diversi modi: Se vogliamo soltanto il nostro valore serializzato, `DataResult#result` restituirà semplicemente un `Optional` contenente il nostro valore, mentre `DataResult#resultOrPartial` ci permette anche di fornire una funzione per gestire qualsiasi errore che potrebbe essersi verificato. La seconda è specialmente utile per risorse di datapack personalizzati, dove vorremmo segnare gli errori nel log senza causare problemi altrove. + +Quindi prendiamo il nostro valore serializzato e ritrasformiamolo nuovamente in un `BlockPos`: + +```java +// Quando stai davvero scrivendo una mod, vorrai ovviamente gestire gli Optional vuoti propriamente +JsonElement json = result.resultOrPartial(LOGGER::error).orElseThrow(); + +// Qui abbiamo il nostro valore json, che dovrebbe corrispondere a `[1, 2, 3]`, +// poiché quello è il formato usato dal codec di BlockPos. +LOGGER.info("Serialized BlockPos: {}", json); + +// Ora deserializzeremo nuovamente il JsonElement in un BlockPos +DataResult result = BlockPos.CODEC.parse(JsonOps.INSTANCE, json); + +// Ancora, prenderemo soltanto il nostro valore dal risultato +BlockPos pos = result.resultOrPartial(LOGGER::error).orElseThrow(); + +// E possiamo notare che abbiamo serializzato e deserializzato il nostro BlockPos con successo! +LOGGER.info("Deserialized BlockPos: {}", pos); +``` + +### Codec Predefiniti + +Come menzionato in precedenza, Mojang ha già definito codec per tante classi Java vanilla e standard, incluse, ma non solo, `BlockPos`, `BlockState`, `ItemStack`, `Identifier`, `Text`, e `Pattern` regex. I Codec per le classi di Mojang si trovano solitamente come attributi static chiamati `CODEC` della classe stessa, mentre molte altre sono mantenute nella classe `Codecs`. Bisogna anche sottolineare che tutte le registry vanilla contengono un metodo `getCodec()`, per esempio, puoi usare `Registries.BLOCK.getCodec()` per ottenere un `Codec` che serializza all'id del blocco e viceversa. + +L'API stessa dei Codec contiene anche alcuni codec per tipi primitivi, come `Codec.INT` e `Codec.STRING`. Queste sono disponibili come statici nella classe `Codec`, e sono solitamente usate come base per codec più complessi, come spiegato sotto. + +## Costruire Codec + +Ora che abbiamo visto come usare i codec, vediamo come possiamo costruircene di nostri. Supponiamo di avere la seguente classe, e di voler deserializzare le sue istanze da file json: + +```java +public class CoolBeansClass { + + private final int beansAmount; + private final Item beanType; + private final List beanPositions; + + public CoolBeansClass(int beansAmount, Item beanType, List beanPositions) {...} + + public int getBeansAmount() { return this.beansAmount; } + public Item getBeanType() { return this.beanType; } + public List getBeanPositions() { return this.beanPositions; } +} +``` + +Il corrispondente file json potrebbe avere il seguente aspetto: + +```json +{ + "beans_amount": 5, + "bean_type": "beanmod:mythical_beans", + "bean_positions": [ + [1, 2, 3], + [4, 5, 6] + ] +} +``` + +Possiamo creare un codec per questa classe mettendo insieme tanti codec più piccoli per formarne uno più grande. In questo caso, ne avremo bisogno di uno per ogni attributo: + +- un `Codec` +- un `Codec` +- un `Codec>` + +Possiamo ottenere il primo dal codec primitivo nella classe `Codec` menzionato in precedenza, nello specifico `Codec.INT`. Mentre il secondo può essere ottenuto dalla registry `Registries.ITEM`, che ha un metodo `getCodec()` che restituisce un `Codec`. Non abbiamo un codec predefinito per `List`, ma possiamo crearne uno a partire da `BlockPos.CODEC`. + +### Liste + +`Codec#listOf` può essere usato per creare una versione lista di qualsiasi codec: + +```java +Codec> listCodec = BlockPos.CODEC.listOf(); +``` + +Bisogna sottolineare che i codec creati così verranno sempre deserializzati a un'`ImmutableList`. Se invece ti servisse una lista mutabile, puoi usare [xmap](#tipi-convertibili-mutualmente-e-tu) per convertirla ad una durante la deserializzazione. + +### Unire i Codec per Classi Simili ai Record + +Ora che abbiamo codec separati per ciascun attributo, possiamo combinarli a formare un singolo codec per la nostra classe usando un `RecordCodecBuilder`. Questo suppone che la nostra classe abbia un costruttore che contiene ogni attributo che vogliamo serializzare, e che ogni attributo ha un metodo getter corrispondente. Questo lo rende perfetto per essere usato assieme ai record, ma può anche essere usato con classi regolari. + +Diamo un'occhiata a come creare un codec per la nostra `CoolBeansClass`: + +```java +public static final Codec CODEC = RecordCodecBuilder.create(instance -> instance.group( + Codec.INT.fieldOf("beans_amount").forGetter(CoolBeansClass::getBeansAmount), + Registries.ITEM.getCodec().fieldOf("bean_type").forGetter(CoolBeansClass::getBeanType), + BlockPos.CODEC.listOf().fieldOf("bean_positions").forGetter(CoolBeansClass::getBeanPositions) + // Un massimo di 16 attributi può essere dichiarato qui +).apply(instance, CoolBeansClass::new)); +``` + +Ogni linea nel gruppo specifica un codec, il nome di un attributo, e un metodo getter. La chiamata a `Codec#fieldOf` è usata per convertire il codec a un [MapCodec](#mapcodec), e la chiamata a `forGetter` specifica il metodo getter usato per ottenere il valore dell'attributo da un'istanza della classe. Inoltre, la chiamata ad `apply` specifica il costruttore usato per creare nuove istanze. Nota che l'ordine degli attributi nel gruppo dovrebbe essere lo stesso di quello dei parametri nel costruttore. + +Puoi anche usare `Codec#optionalFieldOf` in questo contesto per rendere un attributo opzionale, come spiegato nella sezione [Attributi Opzionali](#attributi-opzionali). + +### MapCodec, Da Non Confondere Con Codec<Map> {#mapcodec} + +La chiamata a `Codec#fieldOf` convertirà un `Codec` in un `MapCodec`, che è una variante, ma non una diretta implementazione di `Codec`. I `MapCodec`, come suggerisce il loro nome garantiscono la serializzazione a una mappa chiave-valore, o al suo equivalente nella `DynamicOps` usata. Alcune funzioni ne potrebbero richiedere uno invece di un codec normale. + +Questo modo particolare di creare un `MapCodec` racchiude sostanzialmente il valore del codec sorgente dentro una mappa, con il nome dell'attributo dato come chiave. Per esempio, un `Codec` serializzato a json avrebbe il seguente aspetto: + +```json +[1, 2, 3] +``` + +Ma quando viene convertito in un `MapCodec` usando `BlockPos.CODEC.fieldOf("pos")`, esso ha il seguente aspetto: + +```json +{ + "pos": [1, 2, 3] +} +``` + +Anche se i Map Codec vengono più frequentemente usati per essere uniti ad altri Map Codec per costruire un codec per l'intero insieme di attributi di una classe, come spiegato nella sezione [Unire i Codec per Classi simili ai Record](#unire-i-codec-per-classi-simili-ai-record) sopra, essi possono anche essere ritrasformati in codec normali usando `MapCodec#codec`, che darà lo stesso risultato di incapsulare il loro valore di input. + +#### Attributi Opzionali + +`Codec#optionalFieldOf` può essere usato per create una mappa codec opzionale. Esso, quando l'attributo indicato non è presente nel container durante la deserializzazione, verrà o deserializzato come un `Optional` vuoto oppure con un valore predefinito indicato. + +```java +// Senza un valore predefinito +MapCodec> optionalCodec = BlockPos.CODEC.optionalFieldOf("pos"); + +// Con un valore predefinito +MapCodec optionalCodec = BlockPos.CODEC.optionalFieldOf("pos", BlockPos.ORIGIN); +``` + +Nota che gli attributi opzionali ignoreranno silenziosamente qualsiasi errore che possa verificarsi durante la deserializzazione. Questo significa che se l'attributo è presente, ma il valore non è valido, l'attributo verrà sempre deserializzato al valore predefinito. + +**A partire da 1.20.2**, Minecraft stesso (non DFU!) fornisce `Codecs#createStrictOptionalFieldCodec`, che fallisce del tutto nel deserializzare se il valore dell'attributo non è valido. + +### Costanti, Vincoli, e Composizione + +#### Unità + +`Codec.unit` può essere usato per creare un codec che verrà sempre deserializzato a un valore costante, indipendentemente dall'input. Durante la serializzazione, non farà nulla. + +```java +Codec theMeaningOfCodec = Codec.unit(42); +``` + +#### Intervalli Numerici + +`Codec.intRange` e compagnia, `Codec.floatRange` e `Codec.doubleRange` possono essere usati per creare un codec che accetta soltanto valori numerici all'interno di un intervallo **inclusivo** specificato. Questo si applica sia alla serializzazione sia alla deserializzazione. + +```java +// Non può essere superiore a 2 +Codec amountOfFriendsYouHave = Codec.intRange(0, 2); +``` + +#### Coppia + +`Codec.pair` unisce due codec, `Codec
` e `Codec`, in un `Codec>`. Tieni a mente che funziona correttamente soltanto con codec che serializzano a un attributo specifico, come [MapCodec convertiti](#mapcodec) oppure [Codec di Record](#unire-i-codec-per-classi-simili-ai-record). +Il codec risultante serializzerà a una mappa contenente gli attributi di entrambi i codec usati. + +Per esempio, eseguire questo codice: + +```java +// Crea due codec incapsulati separati +Codec firstCodec = Codec.INT.fieldOf("i_am_number").codec(); +Codec secondCodec = Codec.BOOL.fieldOf("this_statement_is_false").codec(); + +// Uniscili in un codec coppia +Codec> pairCodec = Codec.pair(firstCodec, secondCodec); + +// Usalo per serializzare i dati +DataResult result = pairCodec.encodeStart(JsonOps.INSTANCE, Pair.of(23, true)); +``` + +Restituirà il seguente json: + +```json +{ + "i_am_number": 23, + "this_statement_is_false": true +} +``` + +#### Either + +`Codec.either` unisce due codec, `Codec` e `Codec`, in un `Codec>`. Il codec risultante tenterà, durante la deserializzazione, di usare il primo codec, e _solo se quello fallisce_, tenterà di usare il secondo. +Se anche il secondo fallisse, l'errore del _secondo_ codec verrà restituito. + +#### Mappe + +Per gestire mappe con chiavi arbitrarie, come `HashMap`, `Codec.unboundedMap` può essere usato. Questo restituisce un `Codec>` per un dato `Codec` e `Codec`. Il codec risultante serializzerà a un oggetto json oppure a qualsiasi equivalente disponibile per il dynamic ops corrente. + +Date le limitazioni di json e nbt, il codec chiave utilizzato _deve_ serializzare a una stringa. Questo include codec per tipo che non sono in sé stringhe, ma che serializzano a esse, come `Identifier.CODEC`. Vedi l'esempio sotto: + +```java +// Crea un codec per una mappa da identifier a interi +Codec> mapCodec = Codec.unboundedMap(Identifier.CODEC, Codec.INT); + +// Usalo per serializzare i dati +DataResult result = mapCodec.encodeStart(JsonOps.INSTANCE, Map.of( + new Identifier("example", "number"), 23, + new Identifier("example", "the_cooler_number"), 42 +)); +``` + +Questo restituirà il json seguente: + +```json +{ + "example:number": 23, + "example:the_cooler_number": 42 +} +``` + +Come puoi vedere, questo funziona perché `Identifier.CODEC` serializza direttamente a un valore di tipo stringa. Un effetto simile può essere ottenuto per oggetti semplici che non serializzano a stringhe usando [xmap e compagnia](#tipi-convertibili-mutualmente-e-tu) per convertirli. + +### Tipi Convertibili Mutualmente e Tu + +#### `xmap` + +Immagina di avere due classi che possono essere convertite l'una nell'altra e viceversa, ma che non hanno un legame gerarchico genitore-figlio. Per esempio, un `BlockPos` vanilla e un `Vec3d`. Se avessimo un codec per uno, possiamo usare `Codec#xmap` per creare un codec per l'altro specificando una funzione di conversione per ciascuna direzione. + +`BlockPos` ha già un codec, ma facciamo finta che non ce l'abbia. Possiamo creargliene uno basandolo sul codec per `Vec3d` così: + +```java +Codec blockPosCodec = Vec3d.CODEC.xmap( + // Converti Vec3d a BlockPos + vec -> new BlockPos(vec.x, vec.y, vec.z), + // Converti BlockPos a Vec3d + pos -> new Vec3d(pos.getX(), pos.getY(), pos.getZ()) +); + +// Quando converti una classe esistente (per esempio `X`) +// alla tua classe personalizzata (`Y`) in questo modo, +// potrebbe essere comodo aggiungere i metodi `toX` e +// `fromX` statico ad `Y` e usare riferimenti ai metodi +// nella tua chiamata ad `xmap`. +``` + +#### flatComapMap, comapFlatMap, e flatXMap + +`Codec#flatComapMap`, `Codec#comapFlatMap` e `flatXMap` sono simili a xmap, ma permettono a una o a entrambe le funzioni di conversione di restituire un DataResult. Questo è utile nella pratica perché un'istanza specifica di un oggetto potrebbe non essere sempre valida per la conversione. + +Prendi per esempio gli `Identifier` vanilla. Anche se tutti gli identifier possono essere trasformati in stringhe, non tutte le stringhe sono identifier validi, quindi usare xmap vorrebbe dire lanciare delle brutte eccezioni quando la conversione fallisce. +Per questo, il suo codec predefinito è in realtà una `comapFlatMap` su `Codec.STRING`, che illustra bene come usarla: + +```java +public class Identifier { + public static final Codec CODEC = Codec.STRING.comapFlatMap( + Identifier::validate, Identifier::toString + ); + + // ... + + public static DataResult validate(String id) { + try { + return DataResult.success(new Identifier(id)); + } catch (InvalidIdentifierException e) { + return DataResult.error("Posizione di risorsa non valida: " + id + " " + e.getMessage()); + } + } + + // ... +} +``` + +Anche se questi metodi sono molto d'aiuto, i loro nomi possono confondere un po', quindi ecco una tabella per aiutarti a ricordare quale usare: + +| Metodo | A -> B è sempre valido? | B -> A è sempre valido? | +| ----------------------- | ----------------------- | ----------------------- | +| `Codec#xmap` | Sì | Sì | +| `Codec#comapFlatMap` | No | Sì | +| `Codec#flatComapMap` | Sì | No | +| `Codec#flatXMap` | No | No | + +### Dispatch della Registry + +`Codec#dispatch` ci permette di definire una registry di codec e di fare dispatch ad uno di essi in base al valore di un attributo nei dati serializzati. Questo è molto utile durante la deserializzazione di oggetti che hanno attributi diversi a seconda del loro tipo, ma che rappresentano pur sempre la stessa cosa. + +Per esempio, immaginiamo di avere un'interfaccia astratta `Bean` con due classi che la implementano: `StringyBean` e `CountingBean`. Per serializzare queste con un dispatch di registry, ci serviranno alcune cose: + +- Codec separati per ogni tipo di fagiolo. +- Una classe o un record `BeanType` che rappresenta il tipo di fagiolo, e che può restituire il codec per esso. +- Una funzione in `Bean` per ottenere il suo `BeanType`. +- Una mappa o una registry per mappare `Identifier` a `BeanType`. +- Un `Codec>` basato su questa registry. Se usi una `net.minecraft.registry.Registry`, un codec può essere creato facilmente usando `Registry#getCodec`. + +Con tutto questo, possiamo creare un codec di dispatch di registry per i fagioli: + +@[code transcludeWith=:::](@/reference/latest/src/main/java/com/example/docs/codec/Bean.java) +@[code transcludeWith=:::](@/reference/latest/src/main/java/com/example/docs/codec/BeanType.java) +@[code transcludeWith=:::](@/reference/latest/src/main/java/com/example/docs/codec/StringyBean.java) +@[code transcludeWith=:::](@/reference/latest/src/main/java/com/example/docs/codec/CountingBean.java) +@[code transcludeWith=:::](@/reference/latest/src/main/java/com/example/docs/codec/BeanTypes.java) + +```java +// Ora possiamo creare un codec per i tipi di fagioli +// in base alla registry creata in precedenza +Codec> beanTypeCodec = BeanType.REGISTRY.getCodec(); + +// E in base a quello, ecco il nostro codec di dispatch della registry per i fagioli! +// Il primo parametro e il nome dell'attributo per il tipo di fagiolo. +// Se lasciato vuoto, assumerà "type" come valore predefinito. +Codec beanCodec = beanTypeCodec.dispatch("type", Bean::getType, BeanType::getCodec); +``` + +Il nostro nuovo codec serializzerà fagioli a json così, prendendo solo attributi che sono rilevanti al loro tipo specifico: + +```json +{ + "type": "example:stringy_bean", + "stringy_string": "This bean is stringy!" +} +``` + +```json +{ + "type": "example:counting_bean", + "counting_number": 42 +} +``` + +### Codec Ricorsivi + +A volte è utile avere un codec che utilizza _sé stesso_ per decodificare attributi specifici, per esempio quando si gestiscono certe strutture dati ricorsive. Nel codice vanilla, questo è usato per gli oggetti `Text`, che potrebbero contenere altri `Text` come figli. Un codec del genere può essere costruito usando `Codecs#createRecursive`. + +Per esempio, proviamo a serializzare una lista concatenata singolarmente. Questo metodo di rappresentare le liste consiste di una serie di nodi che contengono sia un valore sia un riferimento al nodo successivo nella lista. La lista è poi rappresentata dal suo primo nodo, e per attraversare la lista si segue il prossimo nodo finché non ce ne sono più. Ecco una semplice implementazione di nodi che contengono interi. + +```java +public record ListNode(int value, ListNode next) {} +``` + +Non possiamo costruire un codec per questo come si fa di solito: quale codec useremmo per l'attributo `next`? Avremmo bisogno di un `Codec`, che è ciò che stiamo costruendo proprio ora! `Codecs#createRecursive` ci permette di fare ciò usando una lambda che sembra magia: + +```java +Codec codec = Codecs.createRecursive( + "ListNode", // un nome per il codec + selfCodec -> { + // Qui, `selfCodec` rappresenta il `Codec`, come se fosse già costruito + // Questa lambda dovrebbe restituire il codec che volevamo usare dall'inizio, + // che punta a sé stesso attraverso `selfCodec` + return RecordCodecBuilder.create(instance -> + instance.group( + Codec.INT.fieldOf("value").forGetter(ListNode::value), + // l'attributo `next` sarà gestito ricorsivamente con il self-codec + Codecs.createStrictOptionalFieldCodec(selfCodec, "next", null).forGetter(ListNode::next) + ).apply(instance, ListNode::new) + ); + } +); +``` + +Un `ListNode` serializzato potrebbe avere questo aspetto: + +```json +{ + "value": 2, + "next": { + "value": 3, + "next" : { + "value": 5 + } + } +} +``` + +## Riferimenti + +- Una documentazione molto più dettagliata sui Codec e sulle relative API può essere trovata presso la [JavaDoc non Ufficiale di DFU](https://kvverti.github.io/Documented-DataFixerUpper/snapshot/com/mojang/serialization/Codec). +- La struttura generale di questa guida è fortemente ispirata dalla [pagina sui codec della Wiki della Community di Forge](https://forge.gemwire.uk/wiki/Codecs), una pagina più orientata verso Forge sullo stesso argomento. diff --git a/versions/1.20.4/translated/it_it/develop/commands/arguments.md b/versions/1.20.4/translated/it_it/develop/commands/arguments.md new file mode 100644 index 000000000..e1223ab38 --- /dev/null +++ b/versions/1.20.4/translated/it_it/develop/commands/arguments.md @@ -0,0 +1,56 @@ +--- +title: Parametri dei Comandi +description: Impara come creare comandi con parametri complessi. +--- + +# Parametri dei Comandi + +La maggior parte dei comandi usa i parametri. A volte possono essere opzionali, il che significa che se non viene fornito quel parametri, il comando verrà eseguito comunque. Ogni nodo può avere tipi di parametri multipli, ma ricorda che c'è una possibilità di ambiguità, che dovrebbe essere evitata. + +@[code lang=java highlight={3} transcludeWith=:::4](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +In questo caso, dopo il testo del comando `/argtater`, dovresti inserire un intero. Per esempio, se eseguissi `/argtater 3`, otterresti il messaggio feedback `Called /argtater with value = 3`. Se scrivessi `/argtater` senza parametri, non sarebbe possibile fare il parsing del comando correttamente. + +Dopo di che aggiungiamo un secondo parametro opzionale: + +@[code lang=java highlight={3,13} transcludeWith=:::5](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +Ora puoi scrivere uno oppure due interi. Se fornisci un intero, un testo di feedback con un singolo valore verrà stampato. Se fornisci due interi, un testo di feedback con due interi verrà stampato. + +Potresti pensare che sia inutile specificare esecuzioni simili due volte. Per cui possiamo creare un metodo che verrà usato in entrambe le esecuzioni. + +@[code lang=java highlight={3,5,6,7} transcludeWith=:::6](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +## Tipi di Parametri Personalizzati + +Se vanilla non fornisce il tipo di parametro che ti serve, puoi creartene uno. Per fare questo, hai bisogno di creare una classe che implementa l'interfaccia `ArgumentType` dove `T` è il tipo del parametro. + +Avrai bisogno d'implementare il metodo `parse`, che farà il parsing della stringa in input nel tipo desiderato. + +Per esempio, puoi creare un tipo di parametro che fa il parsing di un `BlockPos` da una stringa con il formato seguente: `{x, y, z}` + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/command/BlockPosArgumentType.java) + +### Registrare i Tipi di Parametri Personalizzati + +:::warning +Avrai bisogno di registrare i tipi di parametri personalizzati sia sul server sia sul client altrimenti il comando non funzionerà! +::: + +Puoi registrare il tuo tipo di parametro personalizzato nel metodo `onInitialize` dell'inizializer della tua mod usando la classe `ArgumentTypeRegistry`: + +@[code lang=java transcludeWith=:::11](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +### Usare i Tipi di Parametri Personalizzati + +Possiamo usare il nostro tipo di parametro personalizzato in un comando - passando un'istanza di esso nel metodo `.argument` del costruttore del comando. + +@[code lang=java transcludeWith=:::10 highlight={3}](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +Eseguendo il comando possiamo testare se il tipo di parametro funziona o meno: + +![Parametro non valido](/assets/develop/commands/custom-arguments_fail.png) + +![Parametro valido](/assets/develop/commands/custom-arguments_valid.png) + +![Risultato del Comando](/assets/develop/commands/custom-arguments_result.png) diff --git a/versions/1.20.4/translated/it_it/develop/commands/basics.md b/versions/1.20.4/translated/it_it/develop/commands/basics.md new file mode 100644 index 000000000..b12b87b05 --- /dev/null +++ b/versions/1.20.4/translated/it_it/develop/commands/basics.md @@ -0,0 +1,163 @@ +--- +title: Creare Comandi +description: Creare comandi con parametri e azioni complesse. +authors: + - dicedpixels + - i509VCB + - pyrofab + - natanfudge + - Juuxel + - solidblock + - modmuss50 + - technici4n + - atakku + - haykam + - mschae23 + - treeways + - xpple +--- + +# Creare Comandi + +Creare comandi può permettere a uno sviluppatore di mod di aggiungere funzionalità che possono essere usate attraverso un comando. Questo tutorial ti insegnerà come registrare comandi e qual è la struttura generale dei comandi di Brigadier. + +:::info +Brigadier è un parser e un dispatcher di comandi scritto da Mojang per Minecraft. È una libreria comandi basata su una gerarchia dove costruisci un albero di comandi e parametri. Brigadier è open-source: +::: + +## L'interface `Command` + +`com.mojang.brigadier.Command` è un'interfaccia funzionale, che esegue del codice specifico, e lancia una `CommandSyntaxException` in determinati casi. Ha un tipo generico `S`, che definisce il tipo della _sorgente del comando_. +La sorgente del comando fornisce del contesto in cui un comando è stato eseguito. In Minecraft, la sorgente del comando è tipicamente una `ServerCommandSource` che potrebbe rappresentare un server, un blocco comandi, una connessione remota (RCON), un giocatore o un'entità. + +L'unico metodo di `Command`, `run(CommandContext)` prende un `CommandContext` come unico parametro e restituisce un intero. Il contesto del comando contiene la tua sorgente del comando di `S` e ti permette di ottenere parametri, osservare i nodi di un comando di cui è stato effettuato il parsing e vedere l'input usato in questo comando. + +Come altre interfacce funzionali, viene solitamente usata come una lambda o come un riferimento a un metodo: + +```java +Command command = context -> { + return 0; +}; +``` + +L'intero può essere considerato il risultato del comando. Di solito valori minori o uguali a zero indicano che un comando è fallito e non farà nulla. Valori positivi indicano che il comando ha avuto successo e ha fatto qualcosa. Brigadier fornisce una costante per indicare +il successo; `Command#SINGLE_SUCCESS`. + +### Cosa Può Fare la `ServerCommandSource`? + +Una `ServerCommandSource` fornisce del contesto aggiuntivo dipendente dall'implementazione quando un comando viene eseguito. Questo include la possibilità di ottenere l'entità che ha eseguito il comando, il mondo in cui esso è stato eseguito o il server su cui è stato eseguito. + +Puoi accedere alla sorgente del comando dal contesto del comando chiamando `getSource()` sull'istanza di `CommandContext`. + +```java +Command command = context -> { + ServerCommandSource source = context.getSource(); + return 0; +}; +``` + +## Registrare un Comando Basilare + +I comandi sono registrati all'interno del `CommandRegistrationCallback` fornito dall'API di Fabric. + +:::info +Per informazioni su come registrare i callback, vedi per favore la guida [Eventi](../events). +::: + +L'evento dovrebbe essere registrato nell'initializer della tua mod. + +Il callback ha tre parametri: + +- `CommandDispatcher dispatcher` - Usato per registrare, analizzare, ed eseguire comandi. `S` è il tipo di fonte di comando che il dispatcher supporta. +- `CommandRegistryAccess registryAccess` - Fornisce un'astrazione alle registry che potrebbero essere passate ad alcuni argomenti di metodi di comandi +- `CommandManager.RegistrationEnvironment environment` - Identifica il tipo di server su cui i comandi vengono registrati. + +Nell'initializer della mod, registriamo un semplice comando: + +@[code lang=java transcludeWith=:::_1](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +Nel metodo `sendFeedback()` il primo parametro è il testo che viene mandato, che è un `Supplier` per evitare d'istanziare oggetti Text quando non è necessario. + +Il secondo parametro determina se trasmettere il feedback agli altri operatori. In generale, se il comando deve ottenere informazioni senza effettivamente modificare il mondo, come il tempo corrente o una statistica di un giocatore, dovrebbe essere `false`. Se il comando fa qualcosa, come cambiare il tempo o modificare il punteggio di qualcuno, dovrebbe essere `true`. + +Se il comando fallisce, anziché chiamare `sendFeedback()`, puoi direttamente lanciare qualsiasi eccezione e il server o il client la gestiranno in modo appropriato. + +`CommandSyntaxException` generalmente viene lanciata per indicare errori di sintassi nel comando o negli argomenti. Puoi anche implementare la tua eccezione personalizzata. + +Per eseguire questo comando, devi scrivere `/foo`, tutto minuscolo. + +### Ambiente di Registrazione + +Se vuoi, puoi anche assicurarti che un comando venga registrato solo sotto circostanze specifiche, per esempio, solo nell'ambiente dedicato: + +@[code lang=java highlight={2} transcludeWith=:::2](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +### Requisiti dei Comandi + +Immagina di avere un comando e vuoi che solo gli operatori lo possano eseguire. Questo è dove il metodo `requires()` entra in gioco. Il metodo `requires()` ha un solo argomento `Predicate` che fornirà una `ServerCommandSource` con cui testare e determinare se la `CommandSource` può eseguire il comando. + +@[code lang=java highlight={3} transcludeWith=:::3](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +Questo comando verrà eseguito solo se la fonte del comando è un operatore di livello 2 almeno, inclusi i blocchi comandi. Altrimenti, il comando non è registrato. + +Questo ha l'effetto collaterale di non mostrare il comando se si completa con tab a nessuno eccetto operatori di livello 2. Inoltre è il motivo per cui non puoi completare molti dei comandi con tab senza abilitare i comandi. + +### Sotto Comandi + +Per aggiungere un sotto comando, devi registrare il primo nodo letterale del comando normalmente. Per avere un sotto comando, devi aggiungere il nodo letterale successivo al nodo esistente. + +@[code lang=java highlight={3} transcludeWith=:::7](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +Similarmente agli argomenti, i nodi dei sotto comandi possono anch'essi essere opzionali. Nel caso seguente, sia `/subtater` che `/subtater subcommand` saranno validi. + +@[code lang=java highlight={2,8} transcludeWith=:::8](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +## Comandi Lato Client + +L'API di Fabric ha un `ClientCommandManager` nel package `net.fabricmc.fabric.api.client.command.v2` che può essere usato per registrare comandi lato client. Il codice dovrebbe esistere solo nel codice lato client. + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/client/java/com/example/docs/client/command/FabricDocsReferenceClientCommands.java) + +## Reindirizzare Comandi + +I comandi reindirizzati - anche noti come alias - sono un modo di reindirizzare la funzionalità di un comando a un altro. Questo è utile quando vuoi cambiare il nome di un comando, ma vuoi comunque supportare il vecchio nome. + +@[code lang=java transcludeWith=:::12](@/reference/latest/src/client/java/com/example/docs/client/command/FabricDocsReferenceClientCommands.java) + +## Domande Frequenti (FAQ) + +
+ +### Perché il Mio Codice Non Viene Compilato? + +- Catturare o lanciare una `CommandSyntaxException` - `CommandSyntaxException` non è una `RuntimeException`. Se la lanci, dovresti farlo in metodi che lanciano una `CommandSyntaxException` nelle firme dei metodi, oppure dovresti catturarla. + Brigadier gestirà le eccezioni controllate e ti inoltrerà il messaggio d'errore effettivo nel gioco. + +- Problemi con i generic - Potresti avere un problema con i generic una volta ogni tanto. Se stai registrando comandi sul server (ovvero nella maggior parte dei casi), assicurati di star usando `CommandManager.literal` + o `CommandManager.argument` anziché `LiteralArgumentBuilder.literal` o `RequiredArgumentBuilder.argument`. + +- Controlla il metodo `sendFeedback()` - Potresti aver dimenticato di fornire un valore booleano come secondo argomento. Ricordati anche che, da Minecraft 1.20, il primo parametro è `Supplier` anziché `Text`. + +- Un Command dovrebbe restituire un intero - Quando registri comandi, il metodo `executes()` accetta un oggetto `Command`, che è solitamente una lambda. La lambda dovrebbe restituire un intero, anziché altri tipi. + +### Posso Registrare Comandi al Runtime? + +::: warning +You can do this, but it is not recommended. You would get the `CommandManager` from the server and add anything commands +you wish to its `CommandDispatcher`. + +Dopo averlo fatto, devi nuovamente inviare l'albero di comandi a ogni giocatore usando `CommandManager.sendCommandTree(ServerPlayerEntity)`. + +Questo è necessario perché il client mantiene una cache locale dell'albero dei comandi che riceve durante il login (o quando i pacchetti per operatori vengono mandati) per suggerimenti locali e messaggi di errore ricchi. +::: + +### Posso De-Registrare Comandi al Runtime? + +::: warning +You can also do this, however, it is much less stable than registering commands at runtime and could cause unwanted side +effects. + +Per tenere le cose semplici, devi usare la reflection su Brigadier e rimuovere nodi. Dopodiché, devi mandare nuovamente l'albero di comandi a ogni giocatore usando `sendCommandTree(ServerPlayerEntity)`. + +Se non mandi l'albero di comandi aggiornato, il client potrebbe credere che il comando esista ancora, anche se fallirà l'esecuzione sul server. +::: diff --git a/versions/1.20.4/translated/it_it/develop/commands/suggestions.md b/versions/1.20.4/translated/it_it/develop/commands/suggestions.md new file mode 100644 index 000000000..ba7c0de3f --- /dev/null +++ b/versions/1.20.4/translated/it_it/develop/commands/suggestions.md @@ -0,0 +1,45 @@ +--- +title: Suggerimenti dei Comandi +description: Impara come suggerire i valori per gli argomenti dei comandi agli utenti. +authors: + - IMB11 +--- + +# Suggerimenti dei Comandi + +Minecraft ha un potente sistema di suggerimento comandi che viene usato in molti posti, come nel comando `/give`. Questo sistema ti permette di suggerire valori per argomenti dei comandi all'utente, da cui possono poi selezionare - è un ottimo modo per rendere i tuoi comandi più user-friendly ed ergonomici. + +## Provider di Suggerimenti + +Un `SuggestionProvider` viene usato per creare una lista di suggerimenti che verrà mandata al client. Un provider di suggerimenti è un'interfaccia funzionale che prende un `CommandContext` e un `SuggestionBuilder` e restituisce alcune `Suggestions`. Il `SuggestionProvider` restituisce un `CompletableFuture` siccome i suggerimenti potrebbero non essere disponibili immediatamente. + +## Usare i Provider di Suggerimenti + +Per usare un provider di suggerimenti, devi chiamare il metodo `suggests` nel costruttore di argomenti. Questo metodo prende un `SuggestionProvider` e restituisce il costruttore di argomenti modificato con l'aggiunta del suggestion provider. + +@[code java transcludeWith=:::9 highlight={4}](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +## Provider di Suggerimenti Predefiniti + +Ci sono alcuni provider di suggerimenti predefiniti che puoi usare: + +| Provider di Suggerimenti | Descrizione | +| ----------------------------------------- | ----------------------------------------------------------------------- | +| `SuggestionProviders.SUMMONABLE_ENTITIES` | Suggerisce tutte le entità che possono essere evocate. | +| `SuggestionProviders.AVAILABLE_SOUNDS` | Suggerisce tutti i suoni che possono essere riprodotti. | +| `LootCommand.SUGGESTION_PROVIDER` | Suggerisce tutte le loot table disponibili. | +| `SuggestionProviders.ALL_BIOMES` | Suggerisce tutti i biomi disponibili. | + +## Creare un Provider di Suggerimenti Personalizzato + +Se un provider predefinito non soddisfa i tuoi requisiti, puoi creare il tuo provider di suggerimenti personalizzato. Per fare questo, devi creare una classe che implementa l'interfaccia `SuggestionProvider` e fare override del metodo `getSuggestions`. + +Per questo esempio, creeremo un provider di suggerimenti che suggerisce tutti i nomi utente dei giocatori sul server. + +@[code java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/command/PlayerSuggestionProvider.java) + +Per usare questo provider di suggerimenti, passeresti semplicemente una sua istanza al metodo `.suggests` nel costruttore di comandi. + +Ovviamente, i provider di suggerimenti possono essere più complessi, siccome possono anche leggere il contesto dei comandi per fornire suggerimenti basati sullo stato del comando - per esempio quali argomenti sono già stati forniti. + +Ciò potrebbe essere ad esempio leggere l'inventario del giocatore e suggerire oggetti, o entità che sono vicine al giocatore. diff --git a/versions/1.20.4/translated/it_it/develop/entities/damage-types.md b/versions/1.20.4/translated/it_it/develop/entities/damage-types.md new file mode 100644 index 000000000..fcde53532 --- /dev/null +++ b/versions/1.20.4/translated/it_it/develop/entities/damage-types.md @@ -0,0 +1,96 @@ +--- +title: Tipi di Danno +description: Impara come aggiungere tipi di danno personalizzati. +authors: + - dicedpixels + - hiisuuii + - mattidragon +--- + +# Tipi di Danno + +I tipi di danno definiscono tipi di danno che le entità possono subire. A partire da Minecraft 1.19.4, la creazione di nuovi tipi di danno è basata sui dati, per cui essi sono creati tramite file JSON. + +## Creare un Tipo di Danno + +Creiamo un tipo di danno personalizzato chiamato _Tater_. Inizieremo creando un file JSON per il tuo danno personalizzato. Il file sarà posizionato nella cartella `data` della tua mod, in una sottocartella chiamata `damage_type`. + +```:no-line-numbers +resources/data/fabric-docs-reference/damage_type/tater.json +``` + +Ha la struttura seguente: + +@[code lang=json](@/reference/latest/src/main/generated/data/fabric-docs-reference/damage_type/tater.json) + +Questo tipo di danno personalizzato causa un aumento di 0.1 nel livello di esaurimento ([exhaustion level](https://minecraft.wiki/w/Hunger#Exhaustion_level_increase)) ogni volta che il giocatore prende danno, quando il danno è causato da una fonte vivente che non sia un giocatore (per esempio un blocco). Inoltre, la quantità di danno subita cambierà a seconda della difficoltà del mondo + +::: info + +Affidati alla [Minecraft Wiki](https://minecraft.wiki/w/Damage_type#JSON_format) per tutte le possibili chiavi e valori. + +::: + +### Accedere ai Tipi di Danno Tramite Codice + +Quando abbiamo bisogno di accedere al nostro tipo di danno personalizzato tramite codice, useremo la sua `RegistryKey` per costruire un'istanza di `DamageSource`. + +La `RegistryKey` può essere ottenuta nel modo seguente: + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/damage/FabricDocsReferenceDamageTypes.java) + +### Usare i Tipi di Danno + +Per mostrare l'utilizzo dei tipi di danno personalizzati, useremo un blocco personalizzato chiamato _Blocco di Tater_. Facciamo in modo che quando un'entità calpesta un _Blocco di Tater_, esso causa danno _Tater_. + +Puoi fare override di `onSteppedOn` per infliggere questo danno. + +Cominciamo creando una `DamageSource` del nostro tipo di danno personalizzato. + +@[code lang=java transclude={21-24}](@/reference/latest/src/main/java/com/example/docs/damage/TaterBlock.java) + +Poi, chiamiamo `entity.damage()` con la nostra `DamageSource` e con una quantità. + +@[code lang=java transclude={25-25}](@/reference/latest/src/main/java/com/example/docs/damage/TaterBlock.java) + +L'intera implementazione del blocco: + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/damage/TaterBlock.java) + +Ora quando un'entità vivente calpesta il nostro blocco personalizzato, subirà 5 di danno (2.5 cuori) usando il nostro tipo di danno personalizzato. + +### Messaggio di Morte Personalizzato + +Puoi definire un messaggio di morte per il tipo di danno nel formato `death.attack.` nel file `en_us.json` della nostra mod. + +@[code lang=json transclude={4-4}](@/reference/latest/src/main/resources/assets/fabric-docs-reference/lang/en_us.json) + +Al momento della morte dal nostro tipo di danno personalizzato, vedrete il messaggio di morte seguente: + +![Effetto nell'inventario del giocatore](/assets/develop/tater-damage-death.png) + +### Tag dei Tipi di Danno + +Alcuni tipi di danno possono bypassare armatura, bypassare effetti di stato, o simili. I tag sono usati per controllare questo genere di proprietà dei tipi di danno. + +Puoi trovare tipi di danno già esistenti in `data/minecraft/tags/damage_type`. + +::: info + +Affidati alla [Minecraft Wiki](https://minecraft.wiki/w/Tag#Damage_types) per una lista completa dei tag dei tipi di danno. + +::: + +Aggiungiamo il nostro tipo di danno Tater al tag `bypasses_armor` dei tipi di danno. + +Per aggiungere il nostro tipo di danno a uno di questi tag, creeremo un file JSON nel namespace `minecraft`. + +```:no-line-numbers +data/minecraft/tags/damage_type/bypasses_armor.json +``` + +Con il contenuto seguente: + +@[code lang=json](@/reference/latest/src/main/generated/data/minecraft/tags/damage_type/bypasses_armor.json) + +Assicurati che il tuo tag non sostituisca il tag esistente impostando la chiave `replace` a `false`. diff --git a/versions/1.20.4/translated/it_it/develop/entities/effects.md b/versions/1.20.4/translated/it_it/develop/entities/effects.md new file mode 100644 index 000000000..c47299d21 --- /dev/null +++ b/versions/1.20.4/translated/it_it/develop/entities/effects.md @@ -0,0 +1,70 @@ +--- +title: Effetti di Stato +description: Impara come aggiungere effetti di stato personalizzati. +authors: + - dicedpixels + - YanisBft + - FireBlast + - Friendly-Banana + - SattesKrokodil +authors-nogithub: + - siglong + - tao0lu +--- + +# Effetti di Stato + +Gli effetti di stato, anche noti come effetti, sono una condizione che interessa un'entità. Possono essere positivi, negativi o neutrali in natura. Il gioco base applica questi effetti in vari modi, come cibi, pozioni ecc. + +Il comando `/effect` può essere usato per applicare effetti su un'entità. + +## Effetti di Stato Personalizzati + +In questo tutorial aggiungeremo un nuovo effetto personalizzato chiamato _Tater_ che ti darà un punto esperienza in ogni tick di gioco. + +### Estendere `StatusEffect` + +Creiamo una classe per il nostro effetto personalizzato estendendo `StatusEffect`, che è la classe base per tutti gli effetti. + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/effect/TaterEffect.java) + +### Registrare il tuo Effetto Personalizzato + +Come nella registrazione di blocchi e oggetti, usiamo `Registry.register` per registrare i nostri effetti personalizzati nel registro `STATUS_EFFECT`. Questo può essere fatto nel nostro initializer. + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/effect/FabricDocsReferenceEffects.java) + +### Traduzioni e Texture + +Puoi assegnare un nome al tuo effetto di stato e fornire un'icona che apparirà nello schermo dell'inventario del giocatore. + +#### **Texture** + +L'icona dell'effetto è un PNG 18x18. Posiziona la tua icona personalizzata in: + +```:no-line-numbers +resources/assets/fabric-docs-reference/textures/mob_effect/tater.png +``` + +![Effetto nell'inventario del giocatore](/assets/develop/tater-effect.png) + +#### **Traduzioni** + +Come ogni altra traduzione, puoi aggiungere una voce con formato ID `"effect..": "Valore"` al file di lingua. + +::: code-group + +```json[assets/fabric-docs-reference/lang/en_us.json] +{ + "effect.fabric-docs-reference.tater": "Tater" +} +``` + +### Fase di Test + +Usa il comando `/effect give @p fabric-docs-reference:tater` per dare al giocatore il nostro effetto Tater. +Usa `/effect clear @p fabric-docs-reference:tater` per rimuovere l'effetto. + +::: info +Per creare una pozione che usa questo effetto, per favore vedi la guida [Pozioni](../items/potions). +::: diff --git a/versions/1.20.4/translated/it_it/develop/events.md b/versions/1.20.4/translated/it_it/develop/events.md new file mode 100644 index 000000000..93a87e74a --- /dev/null +++ b/versions/1.20.4/translated/it_it/develop/events.md @@ -0,0 +1,124 @@ +--- +title: Eventi +description: Una guida all'uso degli eventi forniti dall'API di Fabric. +authors: + - dicedpixels + - mkpoli + - daomephsta + - solidblock + - draylar + - jamieswhiteshirt + - PhoenixVX + - Juuxel + - YanisBft + - liach + - natanfudge +authors-nogithub: + - stormyfabric +--- + +# Eventi + +L'API di Fabric fornisce un sistema che permette alle mod di reagire ad azioni o circostanze, anche dette _eventi_ che accadono nel gioco. + +Gli eventi sono agganci che soddisfano usi comuni e/o permettono compatibilità e prestazioni migliori tra mod diverse che si agganciano alle stesse aree del codice. L'uso degli eventi spesso sostituisce l'uso dei mixin. + +L'API di Fabric fornisce eventi per aree importanti nel codice base di Minecraft ai quali molti modder potrebbero voler agganciarsi. + +Gli eventi sono rappresentati da istanze di `net.fabricmc.fabric.api.event.Event` che memorizza e chiama i _callback_. Spesso c'è una singola istanza di un evento per un callback, che è conservata in un attributo statico `EVENT` dell'interfaccia callback, ma ci sono anche altre organizzazioni. Per esempio, `ClientTickEvents` raggruppa vari eventi legati insieme. + +## Callback + +I callback sono una parte di codice che viene passata come argomento a un evento. Quando l'evento viene innescato dal gioco, il pezzo di codice passato viene eseguito. + +### Interfacce di Callback + +A ogni evento corrisponde un'interfaccia di callback, convenzionalmente chiamata `Callback`. I callback sono registrati chiamando il metodo `register()` su un'istanza di un evento, con un'istanza dell'interfaccia callback come argomento. + +Tutti le interfacce callback degli eventi fornite dall'API di Fabric possono essere trovate nel package `net.fabricmc.fabric.api.event`. + +## Ascoltare gli Eventi + +### Un Semplice Esempio + +Questo esempio registra un `AttackBlockCallback` per danneggiare il giocatore quando egli colpisce dei blocchi che non droppano un oggetto se rotti senza strumenti. + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/event/FabricDocsReferenceEvents.java) + +### Aggiungere Oggetti alle Loot Table Esistenti + +A volte potresti voler aggiungere oggetti alle loot table. Per esempio, fare in modo che un blocco o un'entità vanilla droppi un tuo oggetto. + +La soluzione più semplice, sostituire il file della loot table, può rompere altre mod. E se volessero cambiarli anche loro? Daremo un'occhiata a come puoi aggiungere oggetti alle loot table senza sovrascriverle. + +Aggiungeremo le uova alla loot table del minerale di carbone. + +#### Ascoltare il Caricamento delle Loot Table + +L'API di Fabric ha un evento che si attiva quando le loot table sono caricate, `LootTableEvents.MODIFY`. Puoi registrare un callback per quell'evento nell'initializer della tua mod. Controlliamo anche che la loot table corrente sia quella del minerale di carbone. + +@[code lang=java transclude={38-40}](@/reference/latest/src/main/java/com/example/docs/event/FabricDocsReferenceEvents.java) + +#### Aggiungere Oggetti alla Loot Table + +Nelle loot table, gli oggetti sono memorizzati come _loot pool entries_, e le voci sono memorizzate in _loot pools_. Per aggiungere un oggetto, dovremo aggiungere una pool con una voce oggetto alla loot table. + +Possiamo creare una pool con `LootPool#builder`, e aggiungerla alla loot table. + +La nostra pool non ha nemmeno un oggetto, quindi dovremo creare una voce oggetto usando `ItemEntry#builder` e aggiungerla alla pool. + +@[code highlight={6-7} transcludeWith=:::2](@/reference/latest/src/main/java/com/example/docs/event/FabricDocsReferenceEvents.java) + +## Eventi Personalizzati + +Alcune aree del gioco non hanno agganci forniti dall'API di Fabric, quindi dovrai usare un mixin o creare il tuo evento personalizzato. + +Vedremo come creare un evento che viene innescato quando una pecora viene tosata. Il processo per la creazione di un evento è: + +- Creare l'interfaccia callback dell'evento +- Innescare l'evento da un mixin +- Creare un'implementazione di prova + +### Creare l'Interfaccia Callback dell'Evento + +L'interfaccia callback descrive cosa deve essere implementato dai listener di eventi che ascolteranno il tuo evento. L'interfaccia callback descrive anche come l'evento verrà chiamato dal tuo mixin. È convenzione posizionare un oggetto `Event` come attributo nell'interfaccia callback, che identificherà effettivamente il nostro evento. + +Per la nostra implementazione di `Event`, sceglieremo di usare un evento basato su un vettore. Il vettore conterrà tutti i listener agli eventi che stanno ascoltando l'evento. + +La nostra implementazione chiamerà i listener di eventi in ordine finché uno di essi non restituisce `ActionResult.PASS`. Questo significa che con il valore restituito un listener può dire "_annulla questo_", "_approva questo_" o "_non m'interessa, lascialo al prossimo listener_". + +Usare `ActionResult` come valore restituito è una convenzione per far cooperare i gestori di eventi in questa maniera. + +Dovrai creare un'interfaccia che ha un'istanza `Event` e un metodo per implementare la risposta. Una semplice configurazione per il nostro callback di tosatura di una pecora è: + +@[code lang=java transcludeWith=:::](@/reference/latest/src/main/java/com/example/docs/event/SheepShearCallback.java) + +Diamogli un'occhiata più precisa. Quando l'invocatore viene chiamato, iteriamo su tutti i listener: + +@[code lang=java transclude={21-22}](@/reference/latest/src/main/java/com/example/docs/event/SheepShearCallback.java) + +Poi chiamiamo il nostro metodo (in questo caso, `interact`) sul listener per ottenere la sua risposta: + +@[code lang=java transclude={33-33}](@/reference/latest/src/main/java/com/example/docs/event/SheepShearCallback.java) + +Se il listener dice che dobbiamo annullare (`ActionResult.FAIL`), oppure finire completamente (`ActionResult.SUCCESS`), il callback restituisce il risultato e finisce il loop. `ActionResult.PASS` si sposta sul prossimo listener, e nella maggior parte dei casi dovrebbe risultare in un successo se non ci sono altri listener registrati: + +@[code lang=java transclude={25-30}](@/reference/latest/src/main/java/com/example/docs/event/SheepShearCallback.java) + +Possiamo aggiungere commenti Javadoc in cima alle classi di callback per documentare cosa fa ogni `ActionResult`. Nel nostro caso, potrebbe essere: + +@[code lang=java transclude={9-16}](@/reference/latest/src/main/java/com/example/docs/event/SheepShearCallback.java) + +### Innescare l'Evento da un Mixin + +Ora abbiamo lo scheletro di base dell'evento, ma dobbiamo anche innescarlo. Siccome vogliamo che l'evento venga chiamato quando un giocatore prova a tosare una pecora, chiamiamo l'`invoker` dell'evento in `SheepEntity#interactMob` quando `sheared()` viene chiamata (ovvero quando la pecora può essere tosata, e il giocatore sta tenendo delle cesoie): + +@[code lang=java transcludeWith=:::](@/reference/latest/src/main/java/com/example/docs/mixin/event/SheepEntityMixin.java) + +### Creare un Implementazione di Prova + +Ora dobbiamo testare il nostro evento. Puoi registrare un listener nel tuo metodo d'inizializzazione (o in un'altra area, se preferisci) e aggiungere logica personalizzata lì. Qui c'è un esempio che droppa un diamante anziché lana ai piedi della pecora: + +@[code lang=java transcludeWith=:::3](@/reference/latest/src/main/java/com/example/docs/event/FabricDocsReferenceEvents.java) + +Se entri nel gioco e tosi una pecora, un diamante dovrebbe essere droppato anziché lana. diff --git a/versions/1.20.4/translated/it_it/develop/getting-started/creating-a-project.md b/versions/1.20.4/translated/it_it/develop/getting-started/creating-a-project.md new file mode 100644 index 000000000..59bba9fa6 --- /dev/null +++ b/versions/1.20.4/translated/it_it/develop/getting-started/creating-a-project.md @@ -0,0 +1,68 @@ +--- +title: Creare un Progetto +description: Una guida passo per passo su come creare un nuovo progetto per una mod con il generatore di mod modello di Fabric. +authors: + - IMB11 +--- + +# Creare un Progetto + +Fabric offre un modo facile per creare un nuovo progetto per una mod attraverso il Generatore di Mod Modello di Fabric - se vuoi, puoi creare un nuovo progetto manualmente usando la repository della mod esempio, dovresti riferirti alla sezione [Creazione Manuale del Progetto](#creazione-manuale-del-progetto). + +## Generare un Progetto + +Puoi usare il [Generatore di Mod Modello di Fabric](https://fabricmc.net/develop/template/) per generare un nuovo progetto per la tua mod - dovresti compilare i campi richiesti, come il nome del package e quello della mod, e la versione di Minecraft per la quale vuoi sviluppare. + +![Anteprima del generatore](/assets/develop/getting-started/template-generator.png) + +Se vuoi usare Kotlin, o vuoi aggiungere generatori di dati, puoi selezionare le opzioni apposite nella sezione `Opzioni Avanzate`. + +![Sezione Opzioni Avanzate](/assets/develop/getting-started/template-generator-advanced.png) + +Una volta che hai compilato i campi richiesti, premi il pulsante `Generate`, e il generatore creerà un nuovo progetto per te sotto forma di file zip. + +Dovresti estrarre questo file zip a una posizione che scegli tu, e poi aprire la cartella estratta in IntelliJ IDEA: + +![Prompt Apri Progetto](/assets/develop/getting-started/open-project.png) + +## Importare il Progetto + +Non appena hai aperto il progetto in IntelliJ IDEA, l'ambiente di sviluppo dovrebbe automaticamente caricare la configurazione Gradle del progetto ed effettuare le operazioni di setup necessarie. + +Se ricevi una notifica riguardo a uno script di build Gradle, dovresti cliccare il pulsante `Importa Progetto Gradle`: + +![Prompt di Gradle](/assets/develop/getting-started/gradle-prompt.png) + +Quando il progetto sarà importato, dovresti vedere i file del progetto nell'explorer di progetto, e dovresti poter cominciare a sviluppare la tua mod. + +## Creazione Manuale del Progetto + +:::warning +Ti servirà che [Git](https://git-scm.com/) sia installato per clonare la repository della mod esempio. +::: + +Se non puoi usare il Generatore di Mod Modello di Fabric, dovresti creare un nuovo progetto manualmente seguendo questi passaggi. + +Anzitutto, clona la repository della mod esempio tramite Git: + +```sh +git clone https://github.com/FabricMC/fabric-example-mod/ mio-progetto-mod +``` + +Questo clonerà la repository in una nuova cartella chiamata `mio-progetto-mod`. + +Dovresti poi eliminare la cartella `.git` dalla repository clonata, e poi aprire il progetto in IntelliJ IDEA. Se la cartella `.git` dovesse non apparire, dovresti attivare la visualizzazione dei file nascosti nel tuo gestore file. + +Quando avrai aperto il progetto in IntelliJ IDEA, esso dovrebbe automaticamente caricare la configurazione Gradle del progetto ed effettuare le operazioni di setup necessarie. + +Di nuovo, come già detto in precedenza, se ricevi una notifica riguardo a uno script di build Gradle, dovresti cliccare il pulsante `Importa Progetto Gradle`. + +### Modificare il Template + +Una volta che il progetto sarà importato, dovresti modificare i dettagli del progetto per corrispondere a quelli della tua mod: + +- Modifica il file `gradle.properties` del tuo progetto per cambiare le proprietà `maven_group` e `archive_base_name` e farle corrispondere con i dettagli della tua mod. +- Modifica il file `fabric.mod.json` per cambiare le proprietà `id`, `name`, e `descrizione` per farle corrispondere ai dettagli della tua mod. +- Assicurati di aggiornare le versioni di Minecraft, i mapping, il Loader e il Loom - tutte queste possono essere trovate attraverso - per farle corrispondere alle versioni che vorresti prendere di mira. + +Ovviamente puoi cambiare il nome del package e la classe principale della mod per farli corrispondere ai dettagli della tua mod. diff --git a/versions/1.20.4/translated/it_it/develop/getting-started/introduction-to-fabric-and-modding.md b/versions/1.20.4/translated/it_it/develop/getting-started/introduction-to-fabric-and-modding.md new file mode 100644 index 000000000..51643525f --- /dev/null +++ b/versions/1.20.4/translated/it_it/develop/getting-started/introduction-to-fabric-and-modding.md @@ -0,0 +1,65 @@ +--- +title: Introduzione a Fabric e al Modding +description: "Una breve introduzione a Fabric e al modding in Minecraft: Java Edition." +authors: + - IMB11 + - itsmiir +authors-nogithub: + - basil4088 +--- + +# Introduzione a Fabric e al Modding + +## Prerequisiti + +Prima d'iniziare, dovresti avere una comprensione basilare dello sviluppo con Java, e una comprensione della Programmazione Orientata agli Oggetti (OOP). + +Se questi concetti non ti sono familiari, potresti voler cercare qualche tutorial su Java e sulla OOP prima di cominciare a fare modding, ecco alcune risorse (in inglese) che puoi usare per imparare Java e OOP: + +- [W3: Java Tutorials](https://www.w3schools.com/java/) +- [Codecademy: Learn Java](https://www.codecademy.com/learn/learn-java) +- [W3: Java OOP](https://www.w3schools.com/java/java_oop.asp) +- [Medium: Introduction to OOP](https://medium.com/@Adekola_Olawale/beginners-guide-to-object-oriented-programming-a94601ea2fbd) + +### Terminologia + +Prima di cominciare, chiariamo alcuni termini che incontrerai nel moddare con Fabric: + +- **Mod**: Una modifica al gioco, che aggiunge nuove funzionalità oppure ne modifica di esistenti. +- **Loader di Mod**: Uno strumento che carica le mod nel gioco, per esempio il Loader di Fabric. +- **Mixin**: Uno strumento per modificare il codice del gioco al runtime - vedi [Mixin Introduction](https://fabricmc.net/wiki/tutorial:mixin_introduction) per maggiori informazioni. +- **Gradle**: Uno strumento per l'automatizzazione del build usato per costruire e compilare mod, usato da Fabric per costruire le mod. +- **Mapping**: Un insieme di mapping che mappano codice offuscato a codice leggibile. +- **Offuscamento**: Il processo di rendere il codice difficile da comprendere, usato da Mojang per proteggere il codice di Minecraft. +- **Remapping**: Il processo di rimappare codice offuscato a codice leggibile. + +## Cos'è Fabric? + +Fabric è una toolchain di modding leggera per Minecraft: Java Edition. + +È progettato per essere una piattaforma per modding semplice e facile da usare. Fabric è un progetto guidato dalla comunità, ed è open-source, per cui chiunque può contribuire al progetto. + +Dovresti conoscere le quattro componenti principali di Fabric: + +- **Loader di Fabric**: Un loader di mod flessibile indipendente dalla piattaforma progettato per Minecraft e per altri giochi e applicazioni. +- **Loom di Fabric**: Un plugin Gradle che permette agli sviluppatori di sviluppare ed effettuare debug delle mod facilmente. +- **API di Fabric**: Un insieme di API e di strumenti per sviluppatori di mod da usare quando si creano mod. +- **Yarn**: Un insieme di mapping Minecraft aperti, gratuiti per tutti da usare sotto la licenza Creative Commons Zero. + +## Perché È Necessario Fabric per Moddare Minecraft? + +> Il modding è il processo di modifica del gioco per cambiarne il comportamento o per aggiungere nuove funzionalità - nel caso di Minecraft, questo può essere qualsiasi cosa dall'aggiungere nuovi oggetti, blocchi, o entità, al cambiare le meccaniche del gioco o aggiungere nuove modalità di gioco. + +Minecraft: Java Edition è offuscato da Mojang, il che rende la pura modifica difficile. Tuttavia, aiutandosi con strumenti di modding come Fabric, il modding diventa molto più facile. Ci sono vari sistemi di mapping che possono aiutare in questo processo. + +Loom rimappa il codice offuscato a un formato leggibile usando questi mapping, rendendo la comprensione e la modifica del codice del gioco più semplice per i modder. Yarn è una scelta popolare ed eccellente di mapping per questo, ma esistono anche altre opzioni. Ogni progetto di mapping potrebbe avere il suo punto forte o la sua focalizzazione. + +Loom ti permette di sviluppare e compilare mod facilmente in riferimento a codice rimappato, e il Loader di Fabric ti permette di caricare queste mod nel gioco. + +## Cosa Fornisce l'API di Fabric, e Perché È Necessaria? + +> L'API di Fabric è un insieme di API e di strumenti per sviluppatori di mod da usare quando si creano mod. + +L'API di Fabric fornisce un largo insieme di API che espandono le funzionalità esistenti di Minecraft - per esempio, fornendo nuovi hook ed eventi che i modder possono usare, o fornendo nuove utilità e strumenti per rendere il modding più facile - come access widener transitivi e la possibilità di accedere a registry interne, come la registry di oggetti compostabili. + +Anche se l'API di Fabric offre funzionalità potenti, alcune operazioni, come la registrazione basilare di blocchi, possono essere effettuate senza di essa usando le API vanilla. diff --git a/versions/1.20.4/translated/it_it/develop/getting-started/launching-the-game.md b/versions/1.20.4/translated/it_it/develop/getting-started/launching-the-game.md new file mode 100644 index 000000000..e91a0e0c2 --- /dev/null +++ b/versions/1.20.4/translated/it_it/develop/getting-started/launching-the-game.md @@ -0,0 +1,63 @@ +--- +title: Avviare il Gioco +description: Impara come usare i vari profili d'avvio per avviare ed effettuare debug delle tue mod in un ambiente di gioco dal vivo. +authors: + - IMB11 +--- + +# Avviare il Gioco + +Loom di Fabric fornisce una varietà di profili d'avvio che ti aiutano ad avviare ed effettuare debug delle tue mod in un ambiente di gioco live. Questa guida tratterà dei vari profili d'avvio e di come usarli per effettuare debug e per testare le tue mod nel gioco. + +## Profili d'Avvio + +Se stai usando IntelliJ IDEA, puoi trovare i profili d'avvio nell'angolo in alto a destra della finestra. Clicca sul menu a tendina per vedere i profili d'avvio disponibili. + +Dovrebbe esserci un profilo client e uno server, con l'opzione di eseguire normalmente o in modalità debug: + +![Profili d'Avvio](/assets/develop/getting-started/launch-profiles.png) + +## Operazioni Gradle + +Se stai usando la linea di comando, puoi usare i comandi Gradle seguenti per avviare il gioco: + +- `./gradlew runClient` - Avvia il gioco in modalità client. +- `./gradlew runServer` - Avvia il gioco in modalità server. + +L'unico problema con questo approccio è che non puoi facilmente effettuare il debug del tuo codice. Se vuoi effettuare debug del tuo codice, avrai bisogno di usare i profili d'avvio in IntelliJ IDEA o tramite l'integrazione Gradle del tuo IDE. + +## Hotswapping delle Classi + +Quando esegui il gioco in modalità debug, puoi fare hotswap ("scambio a caldo") delle tue classe senza riavviare il gioco. Questo è utile per testare cambiamenti al tuo codice velocemente. + +Tuttavia ci sono alcune limitazioni: + +- Non puoi aggiungere né rimuovere metodi +- Non puoi cambiare i parametri dei metodi +- Non puoi aggiungere né togliere attributi + +## Hotswapping dei Mixin + +Se stai usando i Mixin, puoi fare hotswap delle tue classi Mixin senza riavviare il gioco. Questo è utile per testare cambiamenti ai tuoi Mixin velocemente. + +Avrai bisogno d'installare l'agent Java Mixin perché questo funzioni. + +### 1. Trova il Jar della Libreria Mixin + +In IntelliJ IDEA, puoi trovare il jar della libreria Mixin nella sezione "Librerie Esterne" della sezione "Progetto": + +![Libreria Mixin](/assets/develop/getting-started/mixin-library.png) + +Dovrai copiare il "Percorso Assoluto" del jar per il prossimo passaggio. + +### 2. Aggiungi l'argomento VM `-javaagent` + +Nella tua configurazione di avvio "Client Minecraft " e/o "Server Minecraft", aggiungi ciò che segue all'opzione Argomenti VM: + +```:no-line-numbers +-javaagent:"percorso al jar della libreria mixin qui" +``` + +![Screenshot di Argomenti VM](/assets/develop/getting-started/vm-arguments.png) + +Ora, dovresti poter modificare i contenuti dei tuoi metodi mixin durante il debugging e vedere gli effetti delle modifiche senza riavviare il gioco. diff --git a/versions/1.20.4/translated/it_it/develop/getting-started/project-structure.md b/versions/1.20.4/translated/it_it/develop/getting-started/project-structure.md new file mode 100644 index 000000000..561c68665 --- /dev/null +++ b/versions/1.20.4/translated/it_it/develop/getting-started/project-structure.md @@ -0,0 +1,59 @@ +--- +title: Struttura del Progetto +description: Una panoramica sulla struttura di un progetto per una mod Fabric. +authors: + - IMB11 +--- + +# Struttura del Progetto + +Questa pagina analizzerà la struttura di un progetto per una mod Fabric, e l'utilità di ogni file e cartella nel progetto. + +## `fabric.mod.json` + +Il file `fabric.mod.json` è il file principale che descrive la tua mod al Loader di Fabric. Contiene informazioni come l'ID della mod, la versione, e le dipendenze. + +Gli attributi più importanti nel file `fabric.mod.json` sono: + +- `id`: L'ID della mod, che dovrebbe essere unico. +- `name`: Il nome della mod. +- `environment`: L'ambiente in cui la tua mod viene eseguita, come `client`, `server`, o `*` per entrambi. +- `entrypoints`: Gli entrypoint che la tua mod fornisce, come `main` o `client`. +- `depends`: Le mod da cui la tua mod dipende. +- `mixins`: I mixin che la tua mod fornisce. + +Puoi trovare un esempio del file `fabric.mod.json` sotto - questo è il file `fabric.mod.json` per il progetto di riferimento su cui è basato questo sito di documentazione. + +:::details `fabric.mod.json` del Progetto di Riferimento +@[code lang=json](@/reference/latest/src/main/resources/fabric.mod.json) +::: + +## Entrypoint + +Come detto in precedenza, il file `fabric.mod.json` contiene un attributo `entrypoints` - questo attributo è usato per specificare gli entrypoint che la tua mod fornisce. + +Il generatore di mod modello crea sia un entrypoint `main` che `client` predefiniti - l'entrypoint `main` è usato per codice comune, mentre l'entrypoint `client` è usato per codice client specifico. Questi entrypoint vengono chiamati rispettivamente quando il gioco viene avviato. + +@[code lang=java transcludeWith=#entrypoint](@/reference/latest/src/main/java/com/example/docs/FabricDocsReference.java) + +Quello sopra è un esempio di un semplice entrypoint `main` che logga un messaggio alla console quando il gioco si avvia. + +## `src/main/resources` + +La cartella `src/main/resources` viene usata per memorizzare le risorse che la tua mod utilizza, come texture, modelli, e suoni. + +È anche la posizione di `fabric.mod.json` e di qualsiasi file di configurazione mixin che la tua mod utilizza. + +Le risorse sono memorizzate in una struttura che rispecchia la struttura dei pacchetti risorse - per esempio, una texture per un blocco verrebbe memorizzata in `assets/modid/textures/block/block.png`. + +## `src/client/resources` + +La cartella `src/client/resources` viene usata per memorizzare risorse client specifiche, come texture, modelli, e suoni che sono solo utilizzati dal lato client. + +## `src/main/java` + +La cartella `src/main/java` viene usata per memorizzare il codice sorgente Java per la tua mod - esiste sia su ambienti client sia server. + +## `src/client/java` + +La cartella `src/client/java` viene usata per memorizzare codice sorgente Java client specifico, come codice per il rendering o logica del lato client - come provider per il colore dei blocchi. diff --git a/versions/1.20.4/translated/it_it/develop/getting-started/setting-up-a-development-environment.md b/versions/1.20.4/translated/it_it/develop/getting-started/setting-up-a-development-environment.md new file mode 100644 index 000000000..15afef45f --- /dev/null +++ b/versions/1.20.4/translated/it_it/develop/getting-started/setting-up-a-development-environment.md @@ -0,0 +1,55 @@ +--- +title: Impostare un Ambiente di Sviluppo +description: Una guida passo per passo su come impostare un ambiente di sviluppo per creare mod usando Fabric. +authors: + - IMB11 + - andrew6rant + - SolidBlock-cn + - modmuss50 + - daomephsta + - liach + - telepathicgrunt + - 2xsaiko + - natanfudge + - mkpoli + - falseresync + - asiekierka +authors-nogithub: + - siglong +--- + +# Impostare un Ambiente di Sviluppo + +Per iniziare a sviluppare mod con Fabric, avrai bisogno d'impostare un ambiente di sviluppo usando IntelliJ IDEA. + +## Installare JDK 17 + +Per sviluppare mod per Minecraft 1.20.4, avrai bisogno del JDK 17. + +Se ti serve aiuto nell'installare Java, puoi fare riferimento alle varie guide per installazione di Java nella [sezione guide per il giocatore](../../players/index). + +## Installare IntelliJ IDEA + +:::info +Ovviamente puoi usare altri IDE, come Eclipse o Visual Studio Code, ma la maggior parte delle pagine su questo sito di documentazione supporrà che stai usando IntelliJ IDEA - dovresti fare riferimento alla documentazione del tuo IDE se ne stai usando un altro. +::: + +Se non hai IntelliJ IDEA installato, puoi scaricarlo dal [sito ufficiale](https://www.jetbrains.com/idea/download/) - segui i passaggi per l'installazione sul tuo sistema operativo. + +L'edizione Community di IntelliJ IDEA è gratuita e open-source, ed è la versione consigliata per il modding con Fabric. + +Potresti dover scorrere giù per trovare il link per scaricare l'edizione Community - ha il seguente aspetto: + +![Prompt per Scaricare l'Edizione Community di IDEA](/assets/develop/getting-started/idea-community.png) + +## Installare Plugin IDEA + +Anche se questi plugin non sono strettamente necessari, essi rendono il modding con Fabric molto più semplice - dovresti installarli. + +### Minecraft Development + +Il plugin Minecraft Development fornisce supporto per il modding con Fabric, ed è il plugin più importante da installare. + +Puoi installarlo aprendo IntelliJ IDEA, e poi navigando a `File > Impostazioni > Plugin > Scheda Marketplace` - cerca `Minecraft Development` nella barra di ricerca, e poi clicca il pulsante `Installa`. + +In alternativa, puoi scaricarlo dalla [pagina del plugin](https://plugins.jetbrains.com/plugin/8327-minecraft-development) e poi installarlo navigando a `File > Impostazioni > Plugin > Installa Plugin Dal Disco`. diff --git a/versions/1.20.4/translated/it_it/develop/index.md b/versions/1.20.4/translated/it_it/develop/index.md new file mode 100644 index 000000000..22211d122 --- /dev/null +++ b/versions/1.20.4/translated/it_it/develop/index.md @@ -0,0 +1,12 @@ +--- +title: Guide per Sviluppatori +description: Le nostre guide, scritte dalla community, coprono una vasta gamma di argomenti, dal setup di un ambiente di sviluppo ad argomenti più avanzati, come il rendering e il networking. +--- + +# Guide per Sviluppatori + +Le nostre guide, scritte dalla community, coprono una vasta gamma di argomenti, dal setup di un ambiente di sviluppo ad argomenti più avanzati, come il rendering e il networking. + +Dai un'occhiata alla barra laterale per una lista di tutte le guide per sviluppatori disponibili. Se stai cercando qualcosa nello specifico, puoi usare la barra di ricerca in cima alla pagina per trovare quello di cui hai bisogno. + +Se vuoi contribuire alla Documentazione di Fabric, puoi trovare il codice sorgente su [GitHub](https://github.com/FabricMC/fabric-docs), e le corrispondenti [linee guida per la contribuzione](../contributing). diff --git a/translated/it_it/develop/items/potions.md b/versions/1.20.4/translated/it_it/develop/items/potions.md similarity index 100% rename from translated/it_it/develop/items/potions.md rename to versions/1.20.4/translated/it_it/develop/items/potions.md diff --git a/translated/it_it/develop/rendering/basic-concepts.md b/versions/1.20.4/translated/it_it/develop/rendering/basic-concepts.md similarity index 100% rename from translated/it_it/develop/rendering/basic-concepts.md rename to versions/1.20.4/translated/it_it/develop/rendering/basic-concepts.md diff --git a/versions/1.20.4/translated/it_it/develop/rendering/draw-context.md b/versions/1.20.4/translated/it_it/develop/rendering/draw-context.md new file mode 100644 index 000000000..42f94246b --- /dev/null +++ b/versions/1.20.4/translated/it_it/develop/rendering/draw-context.md @@ -0,0 +1,94 @@ +--- +title: Usare il Contesto di Disegno +description: Impara a usare la classe DrawContext per renderizzare varie forme, testi e texture. +authors: + - IMB11 +--- + +# Usare il Contesto di Disegno + +Questa pagina suppone che tu abbia guardato la pagina [Concetti Base del Rendering](./basic-concepts). + +La classe `DrawContext` è la principale classe usata per il rendering nel gioco. Viene usata per renderizzare forme, testi e texture, e come visto in precedenza, usata per manipolare le `MatrixStack` e i `BufferBuilder`. + +## Disegnare Forme + +La classe `DrawContext` può essere usata per disegnare facilmente forme **basate su quadrati**. Se vuoi disegnare triangoli, o altre forme non rettangolari, dovrai usare un `BufferBuilder`. + +### Disegnare Rettangoli + +Puoi usare il metodo `DrawContext.fill(...)` per disegnare un rettangolo pieno. + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/client/java/com/example/docs/rendering/DrawContextExampleScreen.java) + +![Un rettangolo](/assets/develop/rendering/draw-context-rectangle.png) + +### Disegnare Contorni/Bordi + +Immaginiamo di voler aggiungere un contorno al rettangolo che abbiamo disegnato. Possiamo usare il metodo `DrawContext.drawBorder(...)` per disegnare un contorno. + +@[code lang=java transcludeWith=:::2](@/reference/latest/src/client/java/com/example/docs/rendering/DrawContextExampleScreen.java) + +![Rettangolo con bordo](/assets/develop/rendering/draw-context-rectangle-border.png) + +### Disegnare Linee Singole + +Possiamo usare i metodi `DrawContext.drawHorizontalLine(...)` e `DrawContext.drawVerticalLine(...)` per disegnare linee. + +@[code lang=java transcludeWith=:::3](@/reference/latest/src/client/java/com/example/docs/rendering/DrawContextExampleScreen.java) + +![Linee](/assets/develop/rendering/draw-context-lines.png) + +## Il Gestore di Tagli + +La classe `DrawContext` ha un gestore di tagli predefinito. Questo ti permette di ritagliare il rendering a un'area specifica. Questo è utile per renderizzare cose come consigli, o altri elementi che non dovrebbero essere renderizzati al di fuori di un'area specifica. + +### Usare il Gestore di Tagli + +:::tip +Le regioni di taglio possono essere annidate! Ma assicurati di disabilitare il gestore di tagli tante volte quante lo abiliti. +::: + +Per abilitare il gestore di tagli, semplicemente usa il metodo `DrawContext.enableScissor(...)`. Similarmente per disabilitarlo usa il metodo `DrawContext.disableScissor()`. + +@[code lang=java transcludeWith=:::4](@/reference/latest/src/client/java/com/example/docs/rendering/DrawContextExampleScreen.java) + +![Regione di taglio in azione](/assets/develop/rendering/draw-context-scissor.png) + +Come puoi vedere, anche se diciamo al gioco di renderizzare il gradiente attraverso tutto lo schermo, lo renderizza solo nella regione del taglio. + +## Disegnare Texture + +Non c'è un solo modo "corretto" per disegnare texture su uno schermo, siccome il metodo `drawTexture(...)` ha tanti overload diversi. Questa sezione coprirà gli usi più comuni. + +### Disegnare una Texture Intera + +Generalmente, è raccomandato usare l'overload che specifica i parametri `textureWidth` e `textureHeight`. Questo perché la classe `DrawContext` assumerà questi valori se non li specifichi, e a volte potrebbe sbagliare. + +@[code lang=java transcludeWith=:::5](@/reference/latest/src/client/java/com/example/docs/rendering/DrawContextExampleScreen.java) + +![Esempio di tutta la texture disegnata](/assets/develop/rendering/draw-context-whole-texture.png) + +### Disegnare una Porzione di una Texture + +Qui è dove `u` e `v` entrano in gioco. Questi parametri specificano l'angolo in alto a sinistra della texture da disegnare, e i parametri `regionWidth` e `regionHeight` specificano la dimensione della porzione della texture da disegnare. + +Prendiamo questa texture come esempio. + +![Texture del Libro di Ricette](/assets/develop/rendering/draw-context-recipe-book-background.png) + +Se vogliamo solo disegnare una regione che contiene la lente, possiamo usare i seguenti valori per `u`, `v`, `regionWidth` e `regionHeight`: + +@[code lang=java transcludeWith=:::6](@/reference/latest/src/client/java/com/example/docs/rendering/DrawContextExampleScreen.java) + +![Regione di Texture](/assets/develop/rendering/draw-context-region-texture.png) + +## Disegnare Testo + +La classe `DrawContext` ha vari metodi autoesplicativi per renderizzare testo - per brevità, non verranno trattati qui. + +Immaginiamo di voler disegnare "Hello World" sullo schermo. Possiamo usare il metodo `DrawContext.drawText(...)` per farlo. + +@[code lang=java transcludeWith=:::7](@/reference/latest/src/client/java/com/example/docs/rendering/DrawContextExampleScreen.java) + +![Disegnare testo](/assets/develop/rendering/draw-context-text.png) diff --git a/versions/1.20.4/translated/it_it/develop/rendering/gui/custom-screens.md b/versions/1.20.4/translated/it_it/develop/rendering/gui/custom-screens.md new file mode 100644 index 000000000..d4b1ed590 --- /dev/null +++ b/versions/1.20.4/translated/it_it/develop/rendering/gui/custom-screens.md @@ -0,0 +1,64 @@ +--- +title: Schermate Personalizzate +description: Impara come creare schermate personalizzate per la tua mod. +authors: + - IMB11 +--- + +# Schermate Personalizzate + +:::info +Questa pagina si riferisce a schermate normali, non quelle gestite - queste schermate sono quelle aperte dal giocatore sul client, non quelle gestite dal server. +::: + +Le schermate sono essenzialmente le GUI con cui il giocatore interagisce, come la schermata del titolo, la schermata di pausa ecc. + +Puoi creare le tue schermate per mostrare contenuti personalizzati, un menu delle impostazioni personalizzato, e altro. + +## Creare una Schermata + +Per creare una schermata, devi estendere la classe `Screen` e fare override del metodo `init` - puoi anche eventualmente fare override del metodo `render` - ma assicurati di chiamare il suo metodo super altrimenti non renderizzerà lo sfondo, i widget ecc. + +Dovresti prendere nota del fatto che: + +- I Widget non vengono creati nel costruttore perché la schermata non è stata ancora inizializzata a quel punto - e alcune variabili, come `width` e `height`, non sono ancora disponibili o non sono ancora accurate. +- Il metodo `init` viene chiamato quando lo schermo viene inizializzato, e questo è il posto migliore per creare i widget. + - Si aggiungono widget usando il metodo `addDrawableChild`, che accetta qualsiasi widget disegnabile. +- Il metodo `render` viene chiamato ogni frame - puoi accedere al contesto di disegno, e alla posizione del mouse da questo metodo. + +Ad esempio, possiamo creare una semplice schermata che ha un pulsante e un'etichetta al di sopra. + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/client/java/com/example/docs/rendering/screens/CustomScreen.java) + +![Schermata Personalizzata 1](/assets/develop/rendering/gui/custom-1-example.png) + +## Aprire la Schermata + +Puoi aprire la schermata usando il metodo `setScreen` di `MinecraftClient` - puoi farlo da vari posti, come un'associazione a un tasto, un comando, o un gestore dei pacchetti del client. + +```java +MinecraftClient.getInstance().setScreen( + new CustomScreen(Text.empty()) +); +``` + +## Chiudere la Schermata + +Se vuoi chiudere lo schermo, semplicemente imposta la schermata a `null`: + +```java +MinecraftClient.getInstance().setScreen(null); +``` + +Se vuoi essere sofisticato, e tornare alla schermata precedente, puoi passare la schermata corrente nel costruttore `CustomScreen` e conservala in una variabile, per poi tornare alla schermata precedente usando il metodo `close`. + +@[code lang=java transcludeWith=:::2](@/reference/latest/src/client/java/com/example/docs/rendering/screens/CustomScreen.java) + +Ora, aprendo la schermata personalizzata, puoi passare la schermata corrente come secondo argomento - quindi quando chiami `CustomScreen#close` - ritornerà alla schermata precedente. + +```java +Screen currentScreen = MinecraftClient.getInstance().currentScreen; +MinecraftClient.getInstance().setScreen( + new CustomScreen(Text.empty(), currentScreen) +); +``` diff --git a/versions/1.20.4/translated/it_it/develop/rendering/gui/custom-widgets.md b/versions/1.20.4/translated/it_it/develop/rendering/gui/custom-widgets.md new file mode 100644 index 000000000..87e576b5b --- /dev/null +++ b/versions/1.20.4/translated/it_it/develop/rendering/gui/custom-widgets.md @@ -0,0 +1,39 @@ +--- +title: Widget Personalizzati +description: Impara come creare widget personalizzati per la tua schermata. +authors: + - IMB11 +--- + +# Widget Personalizzati + +I Widget sono essenzialmente componenti di rendering containerizzate che possono essere aggiunti a una schermata, e i giocatori possono interagirci attraverso vari eventi come clic del mouse, pressione di tasti, e altro. + +## Creare un Widget + +Si possono seguire varie strade per creare una classe widget, come estendere `ClickableWidget`. Questa classe fornisce un sacco di utilità, come la gestione di larghezza, altezza, posizione, e quella degli eventi - implementa le interfacce `Drawable`, `Element`, `Narratable`, e `Selectable`: + +- `Drawable` - per il rendering - Necessario per registrare il widget alla schermata usando il metodo `addDrawableChild`. +- `Element` - per eventi - Necessario se vuoi gestire gli eventi come click del mouse, pressione di tasti, e altro. +- `Narratable` - per l'accessibilità - Necessario per rendere il tuo widget accessibile a lettori di schermi e ad altri strumenti per l'accessibilità. +- `Selectable` - per la selezione - Necessario se vuoi rendere il tuo widget selezionabile usando il tasto Tab - anche questo aiuta per l'accessibilità. + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/client/java/com/example/docs/rendering/screens/CustomWidget.java) + +## Aggiungere il Widget alla Schermata + +Come tutti i widget, devi aggiungerlo alla schermata usando il metodo `addDrawableChild`, che è fornito dalla classe `Screen`. Assicurati di farlo nel metodo `init`. + +@[code lang=java transcludeWith=:::3](@/reference/latest/src/client/java/com/example/docs/rendering/screens/CustomScreen.java) + +![Widget personalizzato sullo schermo](/assets/develop/rendering/gui/custom-widget-example.png) + +## Eventi di Widget + +Puoi gestire eventi come click del mouse, pressione di tasti, facendo override dei metodi `onMouseClicked`, `onMouseReleased`, `onKeyPressed`, e altri. + +Per esempio, puoi far cambiare colore al widget quando il mouse ci passa sopra usando il metodo `isHovered()` fornito dalla classe `ClickableWidget`: + +@[code lang=java transcludeWith=:::2](@/reference/latest/src/client/java/com/example/docs/rendering/screens/CustomWidget.java) + +![Esempio Evento Hovering](/assets/develop/rendering/gui/custom-widget-events.webp) diff --git a/translated/it_it/develop/rendering/hud.md b/versions/1.20.4/translated/it_it/develop/rendering/hud.md similarity index 100% rename from translated/it_it/develop/rendering/hud.md rename to versions/1.20.4/translated/it_it/develop/rendering/hud.md diff --git a/versions/1.20.4/translated/it_it/develop/rendering/particles/creating-particles.md b/versions/1.20.4/translated/it_it/develop/rendering/particles/creating-particles.md new file mode 100644 index 000000000..9afde755f --- /dev/null +++ b/versions/1.20.4/translated/it_it/develop/rendering/particles/creating-particles.md @@ -0,0 +1,72 @@ +--- +title: Creare Particelle Personalizzate +description: Impara come creare particelle personalizzate usando l'API di Fabric. +authors: + - Superkat32 +--- + +# Creare Particelle Personalizzate + +Le particelle sono uno strumento potente. Possono aggiungere atmosfera a una bella scena, o aggiungere tensione durante una battaglia contro il boss. Aggiungiamone una! + +## Registrare una particella personalizzata + +Aggiungeremo una nuova particella "sparkle" che mimerà il movimento di una particella di una barra dell'End. + +Devi prima registrare un `ParticleType` nella classe initializer della tua mod usando l'id della mod. + +@[code lang=java transcludeWith=#particle_register_main](@/reference/latest/src/main/java/com/example/docs/FabricDocsReference.java) + +La stringa "sparkle_particle" in minuscolo è il percorso JSON per la texture della particella. Dovrai successivamente creare un nuovo file JSON con lo stesso nome. + +## Registrazione sul Client + +Dopo aver registrato la particella nell'entrypoint `ModInitializer`, dovrai anche registrare la particella nell'entrypoint `ClientModInitializer`. + +@[code lang=java transcludeWith=#particle_register_client](@/reference/latest/src/client/java/com/example/docs/FabricDocsReferenceClient.java) + +In questo esempio, stiamo registrando la nostra particella dal lato client. Stiamo dando un po' di movimento alla particella usando la fabbrica della particella della barra dell'End. Questo vuol dire che la nostra particella si muoverà proprio come una particella di una barra dell'End. + +::: tip +You can see all the particle factories by looking at all the implementations of the `ParticleFactory` interface. This is helpful if you want to use another particle's behaviour for your own particle. + +- Combinazione per IntelliJ: Ctrl+Alt+B +- Combinazione per Visual Studio Code: Ctrl+F12 +::: + +## Creare un file JSON e aggiungere le texture + +Dovrai creare 2 cartelle all'interno della cartella `resources/assets//`. + +| Percorso della Cartella | Spiegazione | +| ----------------------- | ----------------------------------------------------------------------------------------------- | +| `/textures/particle` | La cartella `particle` conterrà tutte le texture per tutte le tue particelle. | +| `/particles` | La cartella `particles` conterrà tutti i file json per tutte le tue particelle. | + +Per questo esempio, avremo una sola texture in `textures/particle` chiamata "sparkle_particle_texture.png". + +Dopo, crea un nuovo file JSON in `particles` con lo stesso nome del percorso JSON che hai usato quando hai registrato il tuo ParticleType. Per questo esempio, dovremo creare `sparkle_particle.json`. Questo file è importante perché fa conoscere a Minecraft quali texture dovrebbe usare la nostra particella. + +@[code lang=json](@/reference/latest/src/main/resources/assets/fabric-docs-reference/particles/sparkle_particle.json) + +:::tip +Puoi aggiungere altre texture al vettore `textures` per creare un animazione per la particella. La particella scorrerà attraverso le texture nel vettore, iniziando dalla prima. +::: + +## Testare la nuova particella + +Una volta completato il file JSON e salvato il tuo lavoro, puoi aprire Minecraft e testare tutto! + +Puoi controllare se tutto ha funzionato scrivendo il comando seguente: + +```mcfunction +/particle :sparkle_particle ~ ~1 ~ +``` + +![Dimostrazione della particella](/assets/develop/rendering/particles/sparkle-particle-showcase.png) + +:::info +La particella comparirà all'interno del giocatore con questo comando. Probabilmente dovrai camminare all'indietro per vederla effettivamente. +::: + +In alternativa, puoi anche usare un blocco comandi per far apparire la particella usando lo stesso comando. diff --git a/versions/1.20.4/translated/it_it/develop/sounds/custom.md b/versions/1.20.4/translated/it_it/develop/sounds/custom.md new file mode 100644 index 000000000..ea95c6dbd --- /dev/null +++ b/versions/1.20.4/translated/it_it/develop/sounds/custom.md @@ -0,0 +1,63 @@ +--- +title: Creare Suoni Personalizzati +description: Impara a usare e aggiungere un nuovo suono con la registry. +authors: + - JR1811 +--- + +# Creare Suoni Personalizzati + +## Preparare il File Audio + +I tuoi file audio devono essere formattati in un modo specifico. OGG Vorbis è un formato container aperto per dati multimediali, tra cui audio, e viene usato per i file audio di Minecraft. Per evitare problemi nel modo in cui Minecraft gestisce le distanze, il tuo audio deve essere solo su un singolo canale (Mono). + +Molti software DAW (Digital Audio Workstation) odierni riescono a importare ed esportare usando questo formato. Nell'esempio seguente il software open-source gratuito "[Audacity](https://www.audacityteam.org/)" sarà usato per portare i file audio al formato corretto, tuttavia qualunque altro DAW sarà più che sufficiente. + +![File audio non preparato in Audacity](/assets/develop/sounds/custom_sounds_0.png) + +In questo esempio, il suono di un [fischio](https://freesound.org/people/strongbot/sounds/568995/) viene importato in Audacity. Attualmente questo è salvato come file `.wav` e ha due canali audio (Stereo). Modifica il suono come preferisci e assicurati di cancellare uno dei canali usando il menu a tendina in cima alla "testina". + +![Separare traccia Stereo](/assets/develop/sounds/custom_sounds_1.png) + +![Eliminare uno dei canali](/assets/develop/sounds/custom_sounds_2.png) + +Quando devi esportare o renderizzare un file audio, assicurati di scegliere il formato del file OGG. Alcuni DAW, come REAPER, potrebbero supportare formati audio OGG a più strati. In questo caso OGG Vorbis dovrebbe funzionare senza problemi. + +![Esportare come file OGG](/assets/develop/sounds/custom_sounds_3.png) + +Inoltre tieni a mente che un file audio può aumentare drasticamente le dimensioni del file della tua mod. Se necessario, comprimi l'audio quando stai modificando ed esportando il file, per mantenere le sue dimensioni al minimo. + +## Caricare il File Audio + +Aggiungi un nuovo percorso `resources/assets//sounds` per i suoni della tua mod, e trasferisci qui il file audio esportato `metal_whistle.ogg`. + +Se non esiste ancora, crea il file `resources/assets//sounds.json` e aggiungici i tuoi suoni. + +@[code lang=json](@/reference/latest/src/main/resources/assets/fabric-docs-reference/sounds.json) + +La voce subtitle fornisce un contesto più approfondito per il giocatore. Il nome del sottotitolo è usato nei file di lingua nel percorso `resources/assets//lang` e verrà visualizzato se l'impostazione dei sottotitoli nel gioco è attiva e se questo suono personalizzato viene riprodotto. + +## Registrare il Suono Personalizzato + +Per aggiungere il suono personalizzato alla mod, registra un SoundEvent nella classe che implementa l'entrypoint `ModInitializer`. + +```java +Registry.register(Registries.SOUND_EVENT, new Identifier(MOD_ID, "metal_whistle"), + SoundEvent.of(new Identifier(MOD_ID, "metal_whistle"))); +``` + +## Ripulire il Disordine + +A seconda di quante voci ci sono nella Registry, le cose potrebbero presto sfuggire di mano. Per evitare che ciò accada, possiamo fare uso di una nuova classe di supporto. + +Aggiungi due nuovi metodi alla classe di supporto appena creata. Uno che registra tutti i suoni, e uno che viene usato per inizializzare questa classe in primo luogo. Dopo di che, puoi comodamente aggiungere nuovi attributi `SoundEvent` statici personalizzati a seconda delle necessità. + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/sound/CustomSounds.java) + +Facendo così, la classe entrypoint che implementa `ModInitializer` deve solo implementare una riga per registrare tutti i SoundEvent personalizzati. + +@[code lang=java transcludeWith=:::2](@/reference/latest/src/main/java/com/example/docs/sound/FabricDocsReferenceSounds.java) + +## Usare il SoundEvent Personalizzato + +Usa la classe di supporto per accedere al SoundEvent personalizzato. Consulta la pagina [Riprodurre i SoundEvents](./using-sounds) per imparare come riprodurre i suoni. diff --git a/versions/1.20.4/translated/it_it/develop/sounds/using-sounds.md b/versions/1.20.4/translated/it_it/develop/sounds/using-sounds.md new file mode 100644 index 000000000..20a56ceb0 --- /dev/null +++ b/versions/1.20.4/translated/it_it/develop/sounds/using-sounds.md @@ -0,0 +1,32 @@ +--- +title: Riprodurre Suoni +description: Impara come riprodurre eventi sonori. +--- + +# Riprodurre Suoni + +Minecraft ha una grande selezione di suoni da cui puoi scegliere. Controlla la classe `SoundEvents` per vedere tutte le istanze di eventi sonori vanilla che Mojang ha predisposto. + +## Usare Suoni nella Tua Mod + +Assicurati di eseguire il metodo `playSound()` sul lato del server logico quando usi i suoni! + +In questo esempio, i metodi `useOnEntity()` e `useOnBlock()` per un oggetto interattivo personalizzato sono usati per riprodurre un suono "piazzando blocco di rame" e un suono "predone". + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/item/CustomSoundItem.java) + +Il metodo `playSound()` è usato con l'oggetto `LivingEntity`. Solo il SoundEvent, il volume e il tono devono essere specificati. Puoi anche usare il metodo `playSound()` dall'istanza del mondo per avere un livello di controllo più alto. + +@[code lang=java transcludeWith=:::2](@/reference/latest/src/main/java/com/example/docs/item/CustomSoundItem.java) + +### SoundEvent e SoundCategory + +Il SoundEvent definisce quale suono verrà riprodotto. Puoi anche [registrare i tuoi SoundEvents](./custom) per includere il tuo suono. + +Minecraft ha vari slider audio nelle impostazioni del gioco. L'enum `SoundCategory` è usato per determinare quale slider controllerà il volume del tuo suono. + +### Volume e Tono + +Il parametro volume può causare un po' di confusione. Nell'intervallo `0.0f - 1.0f` il volume reale del suono può essere cambiato. Se il numero diventa più grande di ciò, il volume di `1.0f` verrà usato e soltanto la distanza, nella quale il tuo suono può essere udito, viene cambiata. La distanza in blocchi può essere approssimativamente calcolata come `volume * 16`. + +Il parametro pitch alza o abbassa il valore del tono e cambia anche la durata del suono. Nell'intervallo `(0.5f - 1.0f)` il tono e la velocità si abbassano, mentre valori maggiori alzano il tono e la velocità. Numeri al di sotto di `0.5f` rimarranno al valore di tono `0.5f`. diff --git a/versions/1.20.4/translated/it_it/index.md b/versions/1.20.4/translated/it_it/index.md new file mode 100644 index 000000000..da56364ce --- /dev/null +++ b/versions/1.20.4/translated/it_it/index.md @@ -0,0 +1,27 @@ +--- +title: Documentazione di Fabric +description: La documentazione ufficiale e curata di Fabric, una toolchain per il modding di Minecraft. +layout: home +hero: + name: Documentazione di Fabric + tagline: La documentazione ufficiale e curata di Fabric, una toolchain per il modding di Minecraft. +features: + - title: Guide per Sviluppatori + icon: 🛠️ + details: Le nostre guide, scritte dalla community, coprono una vasta gamma di argomenti, dal setup di un ambiente di sviluppo ad argomenti più avanzati, come il rendering e il networking. + link: ./develop/index + linkText: Per Iniziare + - title: Guide per i Giocatori + icon: 📚 + details: Sei un giocatore che vuole usare mod basate su Fabric? Le nostre guide per giocatori ti aiuteranno. Queste guide ti aiuteranno a scaricare, installare e risolvere eventuali problemi delle mod di Fabric. + link: ./players/index + linkText: Leggi di più +--- + +
+ +## Vuoi Contribuire? + +Se vuoi contribuire alla Documentazione di Fabric, puoi trovare il codice sorgente su [GitHub](https://github.com/FabricMC/fabric-docs), e le corrispondenti [linee guida per la contribuzione](./contributing). + +
diff --git a/versions/1.20.4/translated/it_it/players/faq.md b/versions/1.20.4/translated/it_it/players/faq.md new file mode 100644 index 000000000..5802e7bc5 --- /dev/null +++ b/versions/1.20.4/translated/it_it/players/faq.md @@ -0,0 +1,31 @@ +--- +title: Domande Frequenti per Giocatori (FAQ) +description: Domande frequenti riguardanti Fabric per giocatori e admin di server. +--- + +# Domande Frequenti (FAQ) + +Ci sono molte domande che vengono poste di frequente, quindi ne abbiamo compilato una lista qui. + +## Domande Generali + +### Quali Versioni di Minecraft Supporta Fabric? + +Ufficialmente, Fabric supporta tutte le versioni di Minecraft a partire da snapshot `18w43b` e seguenti, e dalla release `1.14` e superiori. + +### Dove Posso Scaricare le Mod Fabric Pubblicate? + +:::info +Dovresti sempre controllare che le mod provengano da una fonte affidabile. Dai un occhiata alla guida [Trovare Mod Affidabili](./finding-mods) per più informazioni. +::: + +La maggior parte degli autori pubblica le loro mod su [Modrinth](https://modrinth.com/mods?g=categories:%27fabric%27) e [CurseForge](https://www.curseforge.com/minecraft/search?class=mc-mods&gameVersionTypeId=4), anche se altri potrebbero aver deciso di caricarle sui loro siti personali o su altre piattaforme come le repository di GitHub. + +### Dove Posso Trovare Modpack Fabric Prefabbricati? + +Puoi trovare modpack Fabric prefabbricati su varie piattaforme, come: + +- [Modrinth](https://modrinth.com/modpacks?g=categories:%27fabric%27) +- [CurseForge](https://www.curseforge.com/minecraft/search?class=modpacks&gameVersionTypeId=4) +- [Feed The Beast](https://www.feed-the-beast.com/ftb-app) +- [Technic](https://www.technicpack.net/modpacks) diff --git a/versions/1.20.4/translated/it_it/players/finding-mods.md b/versions/1.20.4/translated/it_it/players/finding-mods.md new file mode 100644 index 000000000..b03f13fb7 --- /dev/null +++ b/versions/1.20.4/translated/it_it/players/finding-mods.md @@ -0,0 +1,34 @@ +--- +title: Trovare Mod Affidabili +description: Una guida su come trovare mod Fabric attraverso fonti affidabili. +authors: + - IMB11 +--- + +# Trovare Mod Affidabili + +Anzitutto, la fiducia è soggettiva, e dovresti sempre affidarti al tuo giudizio quando scarichi mod. Tuttavia, ci sono alcune cose che puoi fare che ti aiutano a trovare mod affidabili. + +## 1. Usa una Fonte Nota per Essere Affidabile + +La maggior parte degli autori pubblica le loro mod su [Modrinth](https://modrinth.com/mods?g=categories:%27fabric%27) e [CurseForge](https://www.curseforge.com/minecraft/search?page=1&pageSize=20&sortType=1&class=mc-mods&gameFlavorsIds=4). + +Questi siti controllano che le mod siano quello che dicono di essere, e che non contengano codice maligno. Puoi anche segnalare mod sospette su quei siti, ed essi agiranno in modo relativamente veloce. + +## 2. Controlla con gli Altri! + +Se stai scaricando una mod da una fonte che non è nota per essere affidabile, dovresti controllare con gli altri per vedere se loro l'hanno scaricata prima dalla posizione da cui la stai scaricando tu, e se hanno avuto problemi con essa. + +Se hai dubbi, sentiti libero di chiedere nel [Discord di Fabric](https://discord.gg/v6v4pMv) nel canale `#player-support`. + +## 3. Evita Siti Comuni Maligni! + +:::info +I siti maligni potrebbero non essere ovvi per tutti. Se non sei sicuro, dovresti chiedere l'opinione di altri o evitare il sito completamente e affidarti solo a fonti fidate, come Modrinth e CurseForge. +::: + +Ci sono tanti siti che dicono di avere mod per Minecraft, ma che sono in realtà solo siti maligni. Dovresti evitare questi siti a tutti i costi. + +Puoi usare software antivirus e siti come [Windows Defender](https://www.microsoft.com/it-it/windows/comprehensive-security) o [VirusTotal](https://www.virustotal.com/) per controllare le mod scaricate. Tuttavia, non affidarti completamente su quei metodi, perché a volte potrebbero essere errati. + +Ancora, se hai dubbi, sentiti libero di chiedere l'opinione di altri nel [Discord di Fabric](https://discord.gg/v6v4pMv) nel canale `#player-support`. diff --git a/versions/1.20.4/translated/it_it/players/index.md b/versions/1.20.4/translated/it_it/players/index.md new file mode 100644 index 000000000..798c63440 --- /dev/null +++ b/versions/1.20.4/translated/it_it/players/index.md @@ -0,0 +1,12 @@ +--- +title: Guide per Giocatori +description: Una collezione di guide per giocatori e admin di server riguardo all'installazione e all'utilizzo di Fabric. +--- + +# Guide per Giocatori + +Questa sezione della Documentazione di Fabric è dedicata ai giocatori e agli admin di server che vogliono imparare a installare e usare Fabric e risolverne i problemi. + +Dovresti fare riferimento alla barra laterale per una lista di tutte le guide disponibili. + +Se incontri dei problemi, per favore segnalali [su GitHub](https://github.com/FabricMC/fabric-docs) o chiedi aiuto sul [Discord di Fabric](https://discord.gg/v6v4pMv) nei canali `#player-support` o `#server-admin-support`. diff --git a/versions/1.20.4/translated/it_it/players/installing-fabric.md b/versions/1.20.4/translated/it_it/players/installing-fabric.md new file mode 100644 index 000000000..f67aaac73 --- /dev/null +++ b/versions/1.20.4/translated/it_it/players/installing-fabric.md @@ -0,0 +1,55 @@ +--- +title: Installare Fabric +description: Una guida passo per passo su come installare Fabric. +authors: + - IMB11 +--- + +# Installare Fabric + +Questa guida ti guiderà nell'installazione di Fabric per il Launcher di Minecraft ufficiale. + +Per launcher di terze parti, dovresti consultare la loro documentazione. + +## 1. Scarica l'installer di Fabric + +Puoi scaricare l'installer di Fabric dal [Sito di Fabric](https://fabricmc.net/use/). + +Se usi Windows, scarica la versione `.exe` (`Scarica per Windows`), perché non necessita di Java per essere installata sul tuo sistema. Essa usa invece la versione di Java inclusa nel launcher ufficiale. + +Per macOS e Linux, dovresti scaricare la versione `.jar`. A volte, dovrai installare Java prima di questo passaggio. + +## 2. Esegui l'Installer di Fabric + +:::warning +Chiudi Minecraft e il Launcher di Minecraft prima d'iniziare l'installazione. +::: + +:::details Informazioni per utenti macOS + +Su macOS, potresti dover fare click destro sul file `.jar` nella tua cartella download e cliccare `Apri` per avviarlo. + +![Menu contestuale macOS sull'Installer di Fabric](/assets/players/installing-fabric/macos-downloads.png) + +Quando ti viene chiesto "Sei sicuro di volerlo aprire?", clicca di nuovo `Apri`. +::: + +Una volta aperto l'installer, dovresti vedere una schermata come questa: + +![Fabric Installer con "Installa" evidenziato](/assets/players/installing-fabric/installer-screen.png) + +Per installare Fabric, semplicemente scegli la versione di gioco dal menu a tendina, e clicca `Installa`. + +**Assicurati che `Crea Profilo` sia selezionato.** + +## 3. Hai Finito! + +Una volta che l'installer ha finito, puoi aprire il Launcher di Minecraft e selezionare il profilo Fabric dal menu a tendina in basso a sinistra e premere Gioca! + +![Launcher di Minecraft con il profilo Fabric selezionato](/assets/players/installing-fabric/launcher-screen.png) + +## Prossimi Passi + +Ora che hai installato Fabric, puoi aggiungere le mod al tuo gioco! Dai un occhiata alla guida [Trovare Mod Affidabili](./finding-mods) per più informazioni. + +Se incontri dei problemi seguendo questa guida, puoi chiedere aiuto nel [Discord di Fabric](https://discord.gg/v6v4pMv) nel canale `#player-support`. diff --git a/versions/1.20.4/translated/it_it/players/installing-java/linux.md b/versions/1.20.4/translated/it_it/players/installing-java/linux.md new file mode 100644 index 000000000..c18fd5d16 --- /dev/null +++ b/versions/1.20.4/translated/it_it/players/installing-java/linux.md @@ -0,0 +1,91 @@ +--- +title: Installare Java su Linux +description: Una guida passo per passo su come installare Java su Linux. +authors: + - IMB11 +--- + +# Installare Java su Linux + +Questa guida ti spiegherà come installare Java 17 su Linux. + +## 1. Controlla se Java è già installato + +Apri un terminale, scrivi `java -version` e premi Invio. + +![Terminale con scritto "java -version"](/assets/players/installing-java/linux-java-version.png) + +:::warning +Per usare la maggior parte delle versioni moderne di Minecraft, ti servirà almeno Java 17 installato. Se questo comando mostra una versione inferiore a 17, allora dovrai aggiornare la versione di Java già esistente. +::: + +## 2. Scaricare e Installare Java 17 + +Raccomandiamo l'uso di OpenJDK 17, che è disponibile per la maggior parte delle distribuzioni Linux. + +### Arch Linux + +:::info +Per maggiori informazioni su come installare Java su Arch Linux, vedi [la Wiki di Arch Linux](https://wiki.archlinux.org/title/Java). +::: + +Puoi installare la JRE più recente dalle repository ufficiali: + +```sh +sudo pacman -S jre-openjdk +``` + +Se stai eseguendo un server che non ha bisogno di un'interfaccia grafica, puoi installare la versione headless: + +```sh +sudo pacman -S jre-openjdk-headless +``` + +Se pensi di sviluppare delle mod, ti servirà invece il JDK: + +```sh +sudo pacman -S jdk-openjdk +``` + +### Debian/Ubuntu + +Puoi installare Java 17 usando `apt` con i comandi seguenti: + +```sh +sudo apt update +sudo apt install openjdk-17-jdk +``` + +### Fedora + +Puoi installare Java 17 usando `dnf` con i comandi seguenti: + +```sh +sudo dnf install java-17-openjdk +``` + +Se non hai bisogno di un'interfaccia grafica, puoi installare la versione headless: + +```sh +sudo dnf install java-17-openjdk-headless +``` + +Se pensi di sviluppare delle mod, ti servirà invece il JDK: + +```sh +sudo dnf install java-17-openjdk-devel +``` + +### Altre Distribuzioni Linux + +Se la tua distribuzione non è fra quelle elencate sopra, puoi scaricare il JRE più recente da [Adoptium](https://adoptium.net/temurin/) + +Dovresti fare riferimento a una guida alternativa per la tua distribuzione se vuoi sviluppare delle mod. + +## 3. Verifica che Java 17 Sia Installato + +Quando l'installazione è stata completata, puoi verificare che Java 17 sia installato aprendo il terminale e scrivendo `java -version`. + +Se il comando funziona correttamente, vedrai qualcosa simile a quello mostrato prima, dove è mostrata la versione di Java: + +![Terminale con scritto "java -version"](/assets/players/installing-java/linux-java-version.png) diff --git a/versions/1.20.4/translated/it_it/players/installing-java/windows.md b/versions/1.20.4/translated/it_it/players/installing-java/windows.md new file mode 100644 index 000000000..60a77b7c7 --- /dev/null +++ b/versions/1.20.4/translated/it_it/players/installing-java/windows.md @@ -0,0 +1,65 @@ +--- +title: Installare Java su Windows +description: Una guida passo per passo su come installare Java su Windows. +authors: + - IMB11 +--- + +# Installare Java su Windows + +Questa guida ti spiegherà come installare Java 17 su Windows. + +Il Launcher di Minecraft ha la sua versione di Java installata, quindi questa sezione è rilevante solo se vuoi usare l'installer `.jar` di Fabric, oppure se vuoi usare il `.jar` del Server di Minecraft. + +## 1. Controlla se Java è già installato + +Per controllare se Java è già installato devi prima aprire il prompt dei comandi. + +Puoi farlo premendo Win + R e scrivendo `cmd.exe` nel riquadro che appare. + +![Dialogo Esegui su Windows che mostra "cmd.exe" scritto nella barra](/assets/players/installing-java/windows-run-dialog.png) + +Una volta aperto il prompt dei comandi, scrivi `java -version` e premi Invio. + +Se il comando funziona correttamente, vedrai qualcosa come questo. Se il comando ha fallito, procedi con il prossimo passaggio. + +![Il prompt dei comandi con scritto "java -version"](/assets/players/installing-java/windows-java-version.png) + +:::warning +Per usare la maggior parte delle versioni moderne di Minecraft, ti servirà almeno Java 17 installato. Se questo comando mostra una versione inferiore a 17, allora dovrai aggiornare la versione di Java già esistente. +::: + +## 2. Scarica l'Installer per Java 17 + +Per installare Java 17, dovrai scaricare l'installer da [Adoptium](https://adoptium.net/en-GB/temurin/releases/?os=windows&package=jdk&version=17). + +Dovrai scaricare la versione `Windows Installer (.msi)`: + +![La pagina di download di Adoptium con Windows Installer (.msi) evidenziato](/assets/players/installing-java/windows-download-java.png) + +Dovresti scegliere `x86` se il tuo sistema operativo è a 32-bit, oppure `x64` se tuo sistema operativo è a 64-bit. + +La maggior parte dei computer moderni ha un sistema operativo a 64-bit. Se non sei sicuro, prova a usare il download 64-bit. + +## 3. Esegui l'Installer! + +Segui le istruzioni per installare Java 17. Quando arrivi a questa pagina, dovresti selezionare "L'intera funzionalità verrà installata sul disco rigido locale" per le seguenti funzionalità: + +- `Imposta JAVA_HOME come variabile d'ambiente` - Questo verrà aggiunto al tuo PATH. +- `JavaSoft (Oracle) registry keys` + +![Installer Java 17 con "Set JAVA_HOME variable" e "JavaSoft (Oracle) registry keys" evidenziati](/assets/players/installing-java/windows-wizard-screenshot.png) + +Quando hai finito, puoi cliccare su `Avanti` e continuare con l'installazione. + +## 4. Verifica che Java 17 Sia Installato + +Quando l'installazione è stata completata, puoi verificare che Java 17 è installato aprendo il prompt dei comandi e scrivendo `java -version`. + +Se il comando funziona correttamente, vedrai qualcosa simile a quello mostrato prima, dove è mostrata la versione di Java: + +![Il prompt dei comandi con scritto "java -version"](/assets/players/installing-java/windows-java-version.png) + +--- + +Se incontri dei problemi, sentiti libero di chiedere aiuto nel server [Fabric Discord](https://discord.gg/v6v4pMv) nel canale `#player-support`. diff --git a/versions/1.20.4/translated/it_it/players/installing-mods.md b/versions/1.20.4/translated/it_it/players/installing-mods.md new file mode 100644 index 000000000..3eda77a1a --- /dev/null +++ b/versions/1.20.4/translated/it_it/players/installing-mods.md @@ -0,0 +1,67 @@ +--- +title: Installare le Mod +description: Una guida passo per passo su come installare mod per Fabric. +authors: + - IMB11 +--- + +# Installare le Mod + +Questa guida ti aiuterà a installare mod per Fabric usando il Launcher di Minecraft ufficiale. + +Per launcher di terze parti, dovresti consultare la loro documentazione. + +## 1. Scaricare la Mod + +:::warning +Dovresti solo scaricare mod da fonti di cui ti fidi. Per maggiori informazioni su come trovare le mod, vedi la guida [Trovare Mod Affidabili](./finding-mods). +::: + +La maggior parte delle mod richiede anche l'API di Fabric, che può essere scaricata da [Modrinth](https://modrinth.com/mod/fabric-api) o da [CurseForge](https://curseforge.com/minecraft/mc-mods/fabric-api). + +Quando scarichi delle mod, assicurati che: + +- Funzionino nella versione di Minecraft su cui vuoi giocare. Una mod che funziona sulla versione 1.20, per esempio, potrebbe non funzionare sulla versione 1.20.2. +- Siano per Fabric e non per un altro loader di mod. +- Inoltre, che siano per la corretta edizione di Minecraft (Java Edition). + +## 2. Sposta le Mod nella Cartella `mods` + +La cartella mods può essere trovata nelle posizioni seguenti per ciascun sistema operativo. + +Puoi solitamente incollare questi percorsi nella barra degli indirizzi del tuo gestore di file per navigare velocemente alla cartella. + +::: code-group + +```:no-line-numbers [Windows] +%appdata%\.minecraft\mods +``` + +```:no-line-numbers [macOS] +~/Library/Application Support/minecraft/mods +``` + +```:no-line-numbers [Linux] +~/.minecraft/mods +``` + +::: + +Una volta che hai trovato la cartella `mods`, puoi muovere i file `.jar` della mod in essa. + +![Mod installate nella cartella mods](/assets/players/installing-mods.png) + +## 3. Hai Finito! + +Una volta che hai spostato le mod nella cartella `mods`, puoi aprire il Launcher di Minecraft e selezionare il profilo Fabric dal menu a tendina nell'angolo in basso a sinistra e premere gioca! + +![Launcher di Minecraft con il profilo Fabric selezionato](/assets/players/installing-fabric/launcher-screen.png) + +## Risoluzione dei problemi + +Se incontri qualsiasi problema nel seguire questa guida, puoi chiedere aiuto nel [Discord di Fabric](https://discord.gg/v6v4pMv) nel canale `#player-support`. + +Puoi anche tentare di risolvere il problema da solo leggendo le seguenti pagine di risoluzione dei problemi: + +- [Segnalazioni dei Crash](./troubleshooting/crash-reports) +- [Caricare i Log](./troubleshooting/uploading-logs) diff --git a/versions/1.20.4/translated/it_it/players/troubleshooting/crash-reports.md b/versions/1.20.4/translated/it_it/players/troubleshooting/crash-reports.md new file mode 100644 index 000000000..1ab6414ea --- /dev/null +++ b/versions/1.20.4/translated/it_it/players/troubleshooting/crash-reports.md @@ -0,0 +1,104 @@ +--- +title: Segnalazioni dei Crash +description: Impara cosa fare con le segnalazioni di crash, e come leggerle. +authors: + - IMB11 +--- + +# Segnalazioni dei Crash + +:::tip +Se hai difficoltà nel trovare la causa del crash, puoi chiedere aiuto nel [Discord di Fabric](https://discord.gg/v6v4pMv) nei canali `#player-support` o `#server-admin-support`. +::: + +Le segnalazioni di crash, o degli arresti anomali, sono una parte molto importante della risoluzione di problemi con il tuo gioco o server. Contengono molte informazioni riguardanti il crash, e ti possono aiutare a trovare la causa del crash. + +## Trovare le Segnalazioni di Crash + +Le segnalazioni di crash sono salvate nella cartella `crash-reports` nella tua cartella del gioco. Se stai usando un server, essi sono salvati nella cartella `crash-reports` nella cartella del server. + +Per launcher di terze parti, dovresti affidarti alla loro documentazione per sapere dove trovare le segnalazioni di crash. + +Le segnalazioni di crash possono essere trovate nelle seguenti posizioni: + +::: code-group + +```:no-line-numbers [Windows] +%appdata%\.minecraft\crash-reports +``` + +```:no-line-numbers [macOS] +~/Library/Application Support/minecraft/crash-reports +``` + +```:no-line-numbers [Linux] +~/.minecraft/crash-reports +``` + +::: + +## Leggere le Segnalazioni di Crash + +Le segnalazioni di crash sono molto lunghe, e possono causare confusione nella lettura. Tuttavia, contengono tante informazioni riguardanti il crash, e ti possono aiutare a trovare la causa del crash. + +Per questa guida, useremo [questa segnalazione di crash come esempio](https://github.com/FabricMC/fabric-docs/blob/main/public/assets/players/crash-report-example.txt). + +### Sezioni della Segnalazione di Crash + +Le segnalazioni di crash consistono di varie sezioni, ciascuna separata con un'intestazione: + +- `---- Minecraft Crash Report ----`, il riassunto della segnalazione. Questa sezione contiene l'errore principale che ha causato il crash, l'orario al quale è avvenuto, e la stack trace pertinente. Questa è la sezione più importante della segnalazione del crash poiché lo stack trace potrebbe solitamente contenere riferimenti alla mod che ha causato il crash. +- `-- Last Reload --`, questa sezione non è davvero utile tranne se il crash è avvenuto durante un ricaricamento delle risorse (F3+T). Questa sezione conterrà probabilmente l'orario dell'ultimo ricaricamento, e lo stack trace pertinente di qualsiasi errore che si sia verificato durante il processo di ricaricamento. Questi errori sono solitamente causati dai pacchetti risorse, e possono essere ignorati tranne se stanno causando problemi con il gioco. +- `-- System Details --`, questa sezione contiene informazioni riguardo al tuo sistema, come il sistema operativo, la versione di Java, e la quantità di memoria allocata al gioco. Questa sezione è utile per determinare se stai usando la versione corretta di Java, e se hai allocato abbastanza memoria al gioco. + - In questa sezione, Fabric avrà incluso una linea personalizzata che dice `Fabric Mods:`, seguita da una lista di tutte le mod che hai installato. Questa sezione è utile per determinare se possibili conflitti potrebbero essersi verificati tra mod. + +### Comprendere la Segnalazione del Crash + +Ora che sappiamo cos'è ciascuna sezione della segnalazione di crash, possiamo iniziare a suddividere la segnalazione di crash e trovare la causa del crash. + +Usando l'esempio del link sopra, possiamo analizzare la segnalazione di crash e trovare la causa del crash, incluse le mod che l'hanno causato. + +Lo stack trace nella sezione `---- Minecraft Crash Report ----` è il più importante in questo caso, poiché contiene l'errore principale che ha causato il crash. In questo caso, l'errore è `java.lang.NullPointerException: Cannot invoke "net.minecraft.class_2248.method_9539()" because "net.minecraft.class_2248.field_10540" is null`. + +Con la quantità di mod menzionata nello stack trace, può essere difficile puntare il dito, ma la prima cosa da fare è cercare la mod che ha causato il crash. + +```:no-line-numbers +at snownee.snow.block.ShapeCaches.get(ShapeCaches.java:51) +at snownee.snow.block.SnowWallBlock.method_9549(SnowWallBlock.java:26) // [!code focus] +... +at me.jellysquid.mods.sodium.client.render.chunk.compile.pipeline.BlockOcclusionCache.shouldDrawSide(BlockOcclusionCache.java:52) +at link.infra.indium.renderer.render.TerrainBlockRenderInfo.shouldDrawFaceInner(TerrainBlockRenderInfo.java:31) +... +``` + +In questo caso, la mod che ha causato il crash è `snownee`, poiché è la prima mod menzionata nello stack trace. + +Tuttavia, con la quantità di mod menzionata, potrebbe significare che ci sono problemi di compatibilità tra le mod, e che la mod che ha causato il crash potrebbe non essere la mod colpevole. In questo caso, è meglio segnalare il crash all'autore della mod, e lasciarglielo investigare. + +## Crash che coinvolgono Mixin + +:::info +I mixin sono un modo che hanno le mod per modificare il gioco senza dover modificarne il codice sorgente. Sono usati da varie mod, e sono uno strumento molto potente per gli sviluppatori di mod. +::: + +Quando un mixin causa un crash, esso menzionerà solitamente il mixin nello stack trace, e la classe che il mixin sta modificando. + +I metodi mixin conterranno `modid$handlerName` nello stack trace, mentre `modid` è l'ID della mod, e `handlerName` è il nome del gestore del mixin. + +```:no-line-numbers +... net.minecraft.class_2248.method_3821$$$modid$handlerName() ... // [!code focus] +``` + +Puoi usare queste informazioni per trovare la mod che ha causato il crash, e segnalare il crash all'autore della mod. + +## Cosa Fare delle Segnalazioni di Crash + +La migliore cosa da fare con le segnalazioni di crash è caricarle a un paste site, e poi condividere il link con l'autore della mod, o tramite il suo issue tracker o attraverso qualche mezzo di comunicazione (Discord ecc...). + +Questo permetterà all'autore della mod d'investigare il crash, potenzialmente di riprodurlo, e di risolvere il problema che l'ha causato. + +Paste site comuni usati frequentemente per le segnalazioni di crash sono: + +- [GitHub Gist](https://gist.github.com/) +- [Pastebin](https://pastebin.com/) +- [mclo.gs](https://mclo.gs/) diff --git a/versions/1.20.4/translated/it_it/players/troubleshooting/uploading-logs.md b/versions/1.20.4/translated/it_it/players/troubleshooting/uploading-logs.md new file mode 100644 index 000000000..7694b10b4 --- /dev/null +++ b/versions/1.20.4/translated/it_it/players/troubleshooting/uploading-logs.md @@ -0,0 +1,54 @@ +--- +title: Caricare i Log +description: Come caricare i log per la risoluzione dei problemi. +authors: + - IMB11 +--- + +# Caricare i Log + +Quando stai tentando di risolvere problemi, spesso è necessario fornire i log per aiutare a identificare la causa del problema. + +## Perché Dovrei Caricare i Log? + +Caricare i log permette agli altri di aiutarti a risolvere i tuoi problemi molto più velocemente che non semplicemente incollare i log in una chat o in un post su un forum. Ti permette anche di condividere i tuoi log con altri senza doverli copiare e incollare. + +Alcuni siti forniscono anche colorazione della sintassi per i log, che li rende più facili da leggere, e potrebbero censurare informazioni riservate, come il tuo nome utente, o informazioni sul sistema. + +## Segnalazioni dei Crash + +Le segnalazioni dei crash sono generate automaticamente quando il gioco subisce un crash. Contengono soltanto informazioni sul crash e non i log reali del gioco. Esse sono posizionate nella cartella `crash-reports` nella directory del gioco. + +Per maggiori informazioni sulle segnalazioni dei crash, vedi [Segnalazioni dei Crash](./crash-reports). + +## Localizzare i Log + +Questa guida ricopre il Launcher di Minecraft ufficiale (anche comunemente noto come il "launcher vanilla") - per launcher di terze parti, dovresti consultare la loro documentazione. + +I log sono posizionati nella cartella `logs` della directory del gioco, la directory del gioco può essere trovata nelle seguenti posizioni a seconda del tuo sistema operativo: + +::: code-group + +```:no-line-numbers [Windows] +%appdata%\.minecraft +``` + +```:no-line-numbers [macOS] +~/Library/Application Support/minecraft +``` + +```:no-line-numbers [Linux] +~/.minecraft +``` + +::: + +Il log più recente si chiama `latest.log`, e log precedenti usano lo schema di denominazione `aaaa-mm-gg_numero.log.gz`. + +## Caricare i Log + +I log possono essere caricati su vari servizi, come: + +- [Pastebin](https://pastebin.com/) +- [Gist di GitHub](https://gist.github.com/) +- [mclo.gs](https://mclo.gs/) diff --git a/versions/1.20.4/translated/it_it/players/updating-fabric.md b/versions/1.20.4/translated/it_it/players/updating-fabric.md new file mode 100644 index 000000000..40cd02233 --- /dev/null +++ b/versions/1.20.4/translated/it_it/players/updating-fabric.md @@ -0,0 +1,41 @@ +--- +title: Aggiornare Fabric +description: Una guida passo per passo su come aggiornare Fabric. +authors: + - IMB11 + - modmuss50 +--- + +# Aggiornare Fabric + +Questa guida ti aiuterà nell'aggiornare Fabric per quanto riguarda il Launcher di Minecraft. + +Per launcher di terze parti, dovresti consultare la loro documentazione. + +Aggiornare Fabric è un processo molto simile all'installazione di Fabric, per cui alcune parti di questa guida saranno uguali a quelle della guida [Installare Fabric](./installing-fabric). + +## Perché Dovrei Aggiornare il Loader di Fabric? + +Mod più recenti potrebbero richiedere una versione più moderna del Loader di Fabric per funzionare, quindi è importante tenerlo aggiornato per assicurarti di poter usare le mod più recenti. + + + + + +Per aggiornare Fabric, assicurati semplicemente che la versione del gioco e quella del Loader siano corrette poi clicca `Installa`. + +**Assicurati di deselezionare 'Crea Profilo' quando esegui l'installer, altrimenti creerà un nuovo profilo, che in questo caso non ci serve.** + +## 3. Apri il Profilo nel Launcher di Minecraft + +Appena l'installer ha finito, puoi aprire il Launcher di Minecraft e recarti nella scheda `Installazioni`. Dovresti andare al tuo profilo Fabric e aprire la schermata modifica. + +Sostituisci la versione con la nuova versione del Loader di Fabric che hai appena installato, e premi `Salva`. + +![Aggiornare la versione del Loader di Fabric nel Launcher di Minecraft](/assets/players/updating-fabric.png) + +## 4. Hai Finito! + +Appena avrai completato i passaggi potrai tornare alla scheda `Gioca`, selezionare il profilo Fabric dal menu a tendina nell'angolo in basso a sinistra e premere gioca! + +Se incontri qualsiasi problema nel seguire questa guida, puoi chiedere aiuto nel [Discord di Fabric](https://discord.gg/v6v4pMv) nel canale `#player-support`. diff --git a/versions/1.20.4/translated/it_it/sidebar_translations.json b/versions/1.20.4/translated/it_it/sidebar_translations.json new file mode 100644 index 000000000..52659aad6 --- /dev/null +++ b/versions/1.20.4/translated/it_it/sidebar_translations.json @@ -0,0 +1,46 @@ +{ + "players.title": "Guide per Giocatori", + "players.faq": "Domande Frequenti (FAQ)", + "players.installingJava": "Installare Java", + "players.installingJava.windows": "Windows", + "players.installingJava.macOS": "macOS", + "players.installingJava.linux": "Linux", + "players.installingFabric": "Installare Fabric", + "players.findingMods": "Trovare Mod Affidabili", + "players.installingMods": "Installare le Mod", + "players.troubleshooting": "Risoluzione dei Problemi", + "players.troubleshooting.uploadingLogs": "Caricare i Log", + "players.troubleshooting.crashReports": "Segnalazioni dei Crash", + "players.updatingFabric": "Aggiornare Fabric", + "develop.title": "Guide per Sviluppatori", + "develop.gettingStarted": "Per Iniziare", + "develop.gettingStarted.introduction": "Introduzione a Fabric e al Modding", + "develop.gettingStarted.devEnvSetup": "Impostare un Ambiente di Sviluppo", + "develop.gettingStarted.creatingProject": "Creare un Progetto", + "develop.gettingStarted.projectStructure": "Struttura del Progetto", + "develop.gettingStarted.launchGame": "Avviare il Gioco", + "develop.items": "Oggetti", + "develop.items.potions": "Pozioni", + "develop.entities": "Entità", + "develop.entities.effects": "Effetti di Stato", + "develop.entities.damage-types": "Tipi di Danno", + "develop.commands": "Comandi", + "develop.commands.basics": "Creare Comandi", + "develop.commands.arguments": "Parametri dei Comandi", + "develop.commands.suggestions": "Suggerimenti dei Comandi", + "develop.rendering": "Rendering", + "develop.rendering.basicConcepts": "Concetti Base del Rendering", + "develop.rendering.drawContext": "Usare il Contesto di Disegno", + "develop.rendering.hud": "Rendering nel Hud", + "develop.rendering.gui": "Interfacce Grafiche e Schermate", + "develop.rendering.gui.customScreens": "Schermate Personalizzate", + "develop.rendering.gui.customWidgets": "Widget Personalizzati", + "develop.rendering.particles": "Particelle", + "develop.rendering.particles.creatingParticles": "Creare Particelle Personalizzate", + "develop.misc": "Pagine Varie", + "develop.misc.codecs": "Codec", + "develop.misc.events": "Eventi", + "develop.sounds": "Suoni", + "develop.sounds.using-sounds": "Riprodurre Suoni", + "develop.sounds.custom": "Creare Suoni Personalizzati" +} \ No newline at end of file diff --git a/versions/1.20.4/translated/it_it/website_translations.json b/versions/1.20.4/translated/it_it/website_translations.json new file mode 100644 index 000000000..6550c5b39 --- /dev/null +++ b/versions/1.20.4/translated/it_it/website_translations.json @@ -0,0 +1,46 @@ +{ + "authors.heading": "Autori della pagina", + "authors.nogithub": "%s (non su GitHub)", + "banner": "La Documentazione di Fabric è un lavoro in corso. Segnala problemi su %s o su %s.", + "description": "Documentazione esaustiva di Fabric, la toolchain di modding per Minecraft.", + "footer.next": "Pagina successiva", + "footer.prev": "Pagina precedente", + "github_edit": "Modifica questa pagina su GitHub", + "lang_switcher": "Cambia lingua", + "last_updated": "Ultimo aggiornamento", + "mode_dark": "Passa al tema scuro", + "mode_light": "Passa al tema chiaro", + "mode_switcher": "Aspetto", + "nav.contribute": "Contribuisci", + "nav.contribute.api": "API di Fabric", + "nav.download": "Scarica", + "nav.home": "Home", + "outline": "In questa pagina", + "return_to_top": "Torna all'inizio", + "search.back": "Chiudi ricerca", + "search.button": "Cerca", + "search.display_details": "Mostra lista dettagliata", + "search.footer.close": "per chiudere", + "search.footer.close.key": "Esc", + "search.footer.down.key": "Freccia giù", + "search.footer.navigate": "per navigare", + "search.footer.up.key": "Freccia su", + "search.footer.select": "per selezionare", + "search.footer.select.key": "Invio", + "search.no_results": "Nessun risultato per", + "search.reset": "Cancella ricerca", + "sidebar_menu": "Menu", + "social.discord": "Discord", + "social.github": "GitHub", + "title": "Documentazione di Fabric", + "version_switcher": "Cambia Versione", + "404.code": "404", + "404.crowdin_link": "Traduci su Crowdin", + "404.crowdin_link.label": "Apri l'editor di Crowdin", + "404.english_link": "Leggi in Inglese", + "404.english_link.label": "Apri la versione in inglese", + "404.link": "Torna alla Home", + "404.link.label": "Apri la pagina home", + "404.quote": "Questa pagina ha provato a nuotare nella lava", + "404.title": "Pagina non trovata" +} \ No newline at end of file diff --git a/versions/1.20.4/translated/ko_kr/contributing.md b/versions/1.20.4/translated/ko_kr/contributing.md new file mode 100644 index 000000000..f94ef8523 --- /dev/null +++ b/versions/1.20.4/translated/ko_kr/contributing.md @@ -0,0 +1,181 @@ +# Fabric 문서 기여 가이드라인 + +이 웹사이트는 [VitePress](https://vitepress.dev/)를 사용해 다양한 마크다운 파일에서 정적 HTML을 생성합니다. [여기](https://vitepress.dev/guide/markdown#features)에서 VitePress가 지원하는 마크다운 확장 기능에 익숙해져야 합니다. + +## 목차 + +- [Fabric 문서 기여 가이드라인](#fabric-documentation-contribution-guidelines) + - [기여하기](#how-to-contribute) + - [기여 프레임워크](#contributing-framework) + - [기여 콘텐츠](#contributing-content) + - [스타일 가이드라인](#style-guidelines) + - [확장을 위한 가이드](#guidance-for-expansion) + - [콘텐츠 인증](#content-verification) + - [정리](#cleanup) + - [문서 번역](#translating-documentation) + +## 기여하기 + +매번 새로운 끌어오기 요청을 만들 때 마다 포크 저장소에 새로운 분기를 생성하는게 좋습니다. 이렇게 하면 여러 개의 끌어오기 요청을 관리하기 더 수월해집니다. + +**만약 로컬에서 변경 사항을 미리 보려면, [Node.js 18+](https://nodejs.org/en/) 을 설치해야 합니다.** + +아래 명령어를 실행하기 전에, 먼저 `npm install` 을 실행하여 모든 종속성을 설치했는지 확인하세요. + +**개발 서버 시작하기** + +개발 서버는 `localhost:3000`에서 로컬 변경 사항을 미리 볼 수 있게 합니다. 코드가 변경되면 변경 사항을 자동으로 적용합니다. + +```sh +npm run dev +``` + +**웹사이트 빌드하기** + +웹사이트를 빌드하면 모든 마크다운 파일이 정적 HTML로 컴파일되어 `.vitepress/dist` 에 저장됩니다. + +```sh +npm run build +``` + +**빌드된 웹사이트 미리 보기** + +`.vitepress/dist`에 저장된 콘텐츠를 `localhost:3000` 에서 볼 수 있도록 합니다. + +```sh +npm run preview +``` + +## 프레임워크에 기여하기 + +프레임워크는 웹사이트의 내부 구조로써, 웹사이트의 프레임워크를 수정하는 모든 끌어오기 요청은 `framework` 라벨이 적용되어야 합니다. + +프레임워크 끌어오기 요청은 [Fabric Discord](https://discord.gg/v6v4pMv) 또는 GitHub 이슈에서 문서 개발 팀과 모든 협의가 끝난 후에만 생성해야 합니다. + +**(사이드바 또는 네비게이션 바 구성 변경은 프레임워크 끌어오기 요청으로 간주하지 않습니다)** + +## 문서 콘텐츠에 기여하기 + +문서 콘텐츠에 기여하는건 Fabric 문서에 기여하는 가장 기본적인 방법입니다. + +모든 콘텐츠는 아래 스타일 가이드라인을 준수해야 합니다. + +### 스타일 가이드라인 + +Fabric 문서 웹사이트의 모든 페이지는 스타일 가이드를 준수해야 합니다. 가이드에 대해 궁금한것이 있다면, [Fabric Discord](https://discord.gg/v6v4pMv) GitHub 토론을 통해 질문할 수 있습니다. + +스타일 가이드는 다음과 같습니다. + +1. 모든 페이지는 파일 최상단에 제목과 설명이 입력되어야 합니다. + + ```md + --- + title: 여기에 페이지 제목 입력 + description: 여기에 페이지 설명 입력 + authors: + - 여기에-GitHub-아이디-입력 + --- + + # ... + ``` + +2. 페이지에 코드를 추가하는 경우, 코드를 리퍼런스 모드의 소스 코드에 기입해야 합니다. (모드는 `/reference` 폴더에 있습니다) 그리고, [VitePress의 코드 스니펫 기능](https://vitepress.dev/guide/markdown#import-code-snippets)을 이용하여 코드를 임베드합니다. 만약 span을 더 복잡하게 제어해야 하는 경우, [`markdown-it-vuepress-code-snippet-enhanced` 의 트랜스클루전 기능](https://github.com/fabioaanthony/markdown-it-vuepress-code-snippet-enhanced)을 이용할 수 있습니다. + + **예시:** + + ```md + <<< @/reference/latest/src/main/java/com/example/docs/FabricDocsReference.java{15-21 java} + ``` + + 이는 리퍼런스 모드의 `FabricDocsReference.java` 파일의 15-21 줄을 임베드합니다. + + 임베드된 코드는 다음처럼 표시됩니다. + + ```java + @Override + public void onInitialize() { + // This code runs as soon as Minecraft is in a mod-load-ready state. + // However, some things (like resources) may still be uninitialized. + // Proceed with mild caution. + + LOGGER.info("Hello Fabric world!"); + } + ``` + + **트랜스클루전 예시** + + ```md + @[code transcludeWith=#test_transclude](@/reference/.../blah.java) + ``` + + 이렇게 하면 `blah.java` 파일에서 `#test_transclude` 태그가 적용된 섹션이 임베드 됩니다. + + 예를 들어, `blah.java` 파일의 콘텐츠가 다음과 같을 때, + + ```java + public final String test = "Bye World!" + + // #test_transclude + public void test() { + System.out.println("Hello World!"); + } + // #test_transclude + ``` + + `#test_transclude` 태그 사이의 코드만 임베드 되므로 실제 표시되는 부분은 다음과 같습니다. + + ```java + public void test() { + System.out.println("Hello World!"); + } + ``` + +3. 모든 원본 문서는 미국 문법의 영어로 작성되었습니다. [LanguageTool](https://languagetool.org/)로 문서의 문법이 올바른지 확인할 수 있으니, 너무 신경쓰지 않아도 됩니다. 그리고, 정리(Cleanup) 단계에서 문서 팀이 문법을 고치고 오류를 해결하고 있습니다. 다만, 문서 팀이 시간을 아낄 수 있도록 수시로 문법을 확인해 주세요. + +4. 새로운 섹션을 만들 때는, `.vitepress/sidebars` 폴더에 `config.mts` 파일을 생성해 새로운 사이드바를 생성해야 합니다. 만약 도움이 필요하시다면, [Fabric Discord](https://discord.gg/v6v4pMv)의 `#docs` 채널에 질문해 주세요. + +5. 새로운 페이지를 생성할 때도, `.vitepress/sidebars` 폴더에 연결을 추가해야 합니다. 역시나, 도움이 필요하시면 Fabric Discord의 `#docs` 채널에 질문하시면 됩니다. + +6. 모든 이미지는 `/assets` 폴더의 적당한 위치에 저장되어야 합니다. + +7. ⚠️ **다른 페이지를 언급하려는 경우 연결 링크를 사용하십시오** ⚠️ + + 이렇게 해야 버전 관리 체계가 연결된 페이지의 버전을 올바르게 처리할 수 있습니다. 절대 링크를 사용하면, 버전이 링크에 추가되지 않습니다. + + 예를 들어서, `/players` 폴더의 `installing-fabric` 페이지를 언급하려는 경우, 절대 경로는 `/players/installing-fabric.md` 이지만, 다음과 같이 연결해야 합니다. + + ```md + [This is a link to another page](./installing-fabric) + ``` + + 반대로 다음과 같이 입력하면 **문제가 발생**하게 됩니다! + + ```md + [This is a link to another page](/players/installing-fabric) + ``` + +모든 콘텐츠 기여의 끌어오기 요청은 다음 단계를 거치게 됩니다. + +1. 문서 내용 확장 (가능한 경우) +2. 내용 검증 +3. 정리 (문법 등) + +### 문서 내용 확장 + +만약 문서 팀이 끌어오기 요청의 내용을 확장할 수 있을것으로 보이면, 문서 팀이 가능한 확장 내용과 함께 `expansion` 라벨을 끌어오기 요청에 추가하게 됩니다. 제안에 동의하신다면, 문서 내용을 확장하시면 됩니다. + +**팀의 제안에 압박을 느낄 필요는 없습니다.** 끌어오기 요청을 확장하고 싶지 않은 경우, 간단히 `expansion` 라벨을 제거하시면 됩니다. + +개인적인 사정으로 확장이 어렵거나, 이후에 다른 분이 확장하기를 원하신다면, 이후에 [Issues 페이지](https://github.com/FabricMC/fabric-docs/issues)에 바라는 확장 방향을 설명한 이슈를 생성하시는것도 좋은 방법입니다. + +### 내용 검증 + +모든 끌어오기 요청은 내용 검증을 거쳐야 합니다. 이는 내용이 정확하고 Fabric 문서 스타일 가이드를 준수하는지 확인하는 단계이므로 가장 중요합니다. + +### 정리 + +끌어오기 요청을 병합하기 전, 문서 팀이 문서의 문법을 고치고 내용을 정리하는 단계입니다. + +## 문서 번역하기 + +문서를 한국어 또는 다른 언어로 번역하고 싶다면, [Fabric Crowdin](https://crowdin.com/project/fabricmc)에서 번역에 참여할 수 있습니다. diff --git a/versions/1.20.4/translated/ko_kr/develop/commands/arguments.md b/versions/1.20.4/translated/ko_kr/develop/commands/arguments.md new file mode 100644 index 000000000..07cf0be9b --- /dev/null +++ b/versions/1.20.4/translated/ko_kr/develop/commands/arguments.md @@ -0,0 +1,56 @@ +--- +title: 명령어 인수 +description: 복잡한 인수를 가진 명령어를 만드는 방법을 알아보세요. +--- + +# 명령어 인수 + +인수는 대부분의 명령어에서 사용됩니다. 다시 말해, 어떤 인수는 값을 입력하지 않더라도 명령어가 정상 작동한다는 의미입니다. 하나의 노드는 여러 개의 타입을 가질 수 있지만, 타입이 모호해지면 오류의 원인이 될 수 있으므로 그런 경우는 최대한 피해야 합니다. + +@[code lang=java highlight={3} transcludeWith=:::4](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +이런 경우에는, `/argtater` 명령어 다음에 정수를 입력해야 합니다. 예를 들어, 만약 `/argtater 3` 를 실행하면, `Called /argtater with value = 3` 라고 피드백 메세지를 받을 것입니다. 반대로 `/argtater` 를 아무런 인수 없이 실행하면, 명령어가 올바르게 작동하지 않을 것입니다. + +이제 선택적인 두 번째 인수를 추가해보겠습니다. + +@[code lang=java highlight={3,13} transcludeWith=:::5](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +이렇게 하면 한 개 또는 두 개의 정수형을 입력할 수 있게 됩니다. 만약 한 개의 정수만 입력하면, 피드백 메세지에선 한 가지 값만 출력될 것입니다. 반대로 두 개의 정수을 모두 입력하면, 피드백 메세지에선 두 개의 값을 모두 출력할 것입니다. + +비슷한 처리를 두 번이나 정의할 필요는 없습니다. 대신, 비슷한 처리를 하는 두 가지 인수는 이렇게 만들 수 있습니다. + +@[code lang=java highlight={3,5,6,7} transcludeWith=:::6](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +## 사용자 정의 인수 타입 + +만약 바닐라에 사용하려는 인수 타입이 없다면, 직접 인수 타입을 만들 수도 있습니다. 만드는 방법을 알아보자면, 먼저 `ArgumentType` 인터페이스를 상속하는 클래스를 만들어야 합니다. + +이제 입력된 문자열을 원하는 타입으로 변환하기 위해 `parse` 메소드를 구현해야 합니다. + +예를 들어, `{x, y, z}` 형태로 입력된 문자열을 `BlockPos`로 변환해보겠습니다. + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/command/BlockPosArgumentType.java) + +### 사용자 정의 인수 타입의 등록 + +:::warning +명령어를 올바르게 작동하게 하려면 서버와 클라이언트 모두에 사용자 정의 인수 타입을 등록해야 합니다! +::: + +모드 초기화 단계의 `onInitialize` 메소드 에서 `ArgumentTypeRegistry` 클래스를 통해 사용자 정의 인수 타입을 등록할 수 있습니다. + +@[code lang=java transcludeWith=:::11](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +### 사용자 정의 인수 타입의 사용 + +명령어 빌더의 `.argument` 메소드에 인스턴스를 입력하여 명령어에 사용자 정의 인수 타입을 사용할 수 있습니다. + +@[code lang=java transcludeWith=:::10 highlight={3}](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +명령어를 실행하여 인수 형태가 작동하는지 여부를 확인할 수 있습니다. + +![올바르지 않은 인수](/assets/develop/commands/custom-arguments_fail.png) + +![올바른 인수](/assets/develop/commands/custom-arguments_valid.png) + +![명령어 결과](/assets/develop/commands/custom-arguments_result.png) diff --git a/versions/1.20.4/translated/ko_kr/develop/commands/basics.md b/versions/1.20.4/translated/ko_kr/develop/commands/basics.md new file mode 100644 index 000000000..af67c585d --- /dev/null +++ b/versions/1.20.4/translated/ko_kr/develop/commands/basics.md @@ -0,0 +1,160 @@ +--- +title: 명령어 만들기 +description: 복잡한 인수와 동작을 가진 명령어를 만들어 보세요. +authors: + - dicedpixels + - i509VCB + - pyrofab + - natanfudge + - Juuxel + - solidblock + - modmuss50 + - technici4n + - atakku + - haykam + - mschae23 + - treeways +--- + +# 명령어 만들기 + +"명령어 만들기"에서는 모드 개발자가 명령어를 통한 기능을 추가하는 방법에 대해 설명합니다. 이 튜토리얼에서는 Brigadier의 일반적인 명령어 구조는 무엇이며, 어떻게 명령어를 등록하는지 알아볼 것입니다. + +:::info +Brigadier는 Mojang이 만든 Minecraft의 명령어 파서 및 디스패처로, 명령어 및 인수의 트리를 만드는 트리 기반의 명령어 라이브러리 입니다. 인수 처럼, 하위 명령어 노드도 필수적이진 않습니다. Brigadier는 오픈 소스로, 원본 소스 코드는 여기에서 확인할 수 있습니다: +::: + +## `Command` 인터페이스 + +`com.mojang.brigadier.Command`는 특정 코드를 실행하고 `CommandSyntaxException`을 던지는 기능형 인터페이스 이며, _명령어의 소스_ 의 타입을 결정하는 제네릭 타입 `S`를 가집니다. 인수 처럼, 하위 명령어 노드도 필수적이진 않습니다. +명령어 소스는 명령어를 실행한 대상자를 의미합니다. 마인크래프트에서, 명령어 소스는 서버를 의미하는 `ServerCommandSource`, 명령 블록, 원격 연결 (RCON), 그리고 플레이어와 엔티티가 있습니다. + +`Command`의 `run(CommandContext)` 메소드는 `CommandContext`를 인수로 받아 정수를 반환합니다. 명령어 컨텍스트에선 명령어 소스 `S`와, 인수, 분석된 명령어 노드 또는 명령어의 입력을 받아올 수 있습니다. + +다른 기능형 인터페이스처럼, 이 인터페이스에는 대부분 람다식 또는 메소드 참조가 사용됩니다. + +```java +Command command = context -> { + return 0; +}; +``` + +치트를 켜지 않으면 대부분의 명령어를 탭 자동 완성에서 볼 수 없는 이유이기도 합니다. 일반적으로 음수 값은 명령어를 실행하는데 실패했고, 아무것도 실행되지 않았음을 의미합니다. 반환되는 정수는 명령어의 결과를 의미합니다. `0`은 명령어가 성공적으로 처리되었음을 의미하고, 양수 값은 명령어가 성공적으로 작동했으며 어떠한 작업이 실행되었음을 의미합니다. Brigadier는 성공을 나타내는 상수 `Command#SINGLE_SUCCESS` 를 제공하고 있습니다. + +### `ServerCommandSource`의 역할 + +예를 들어, 명령어가 전용 서버 환경에서만 등록되도록 해보겠습니다. `ServerCommandSource`는 명령어를 실행한 엔티티, 명령어가 실행된 세계 또는 서버 등 명령어가 실행될 때 추가적인 컨텍스트를 제공합니다. + +`CommandContext` 인스턴스에서 `getSource()` 메소드를 호출해 명령어 컨텍스트에서 명령어 소스에 접근할 수도 있습니다. + +```java +Command command = context -> { + ServerCommandSource source = context.getSource(); + return 0; +}; +``` + +## 기본 명령어의 등록 + +명령어는 Fabric API에서 제공하는 `CommandRegistrationCallback` 을 통해 등록됩니다. + +:::info +콜백을 등록하는 방법은 [이벤트](../events) 가이드를 참고하십시오. +::: + +이벤트는 모드 초기화 단계에 등록되어야 합니다. + +콜백은 다음 세 가지 매개변수를 가집니다. + +- `CommandDispatcher dispatcher` - 명령어를 등록, 분석하고 실행하는데 사용됩니다. `S`는 명령어 디스패처가 지원하는 명령어 소스의 타입입니다. +- `CommandRegistryAccess registryAccess` - 특정한 명령어 인수 메소드에 입력될 수 있는 레지스트리의 추상화를 제공합니다. +- `CommandManager.RegistrationEnvironment environment` - 명령어가 등록되는 서버의 유형을 식별합니다. + +이제 모드 초기화에서 간단한 명령어를 한번 등록해봅시다. + +@[code lang=java transcludeWith=:::_1](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +`sendFeedback()` 메소드의 첫 번째 인수는 보내질 텍스트이며, 텍스트 오브젝트의 필요 없는 인스턴스화를 막기 위해 `Supplier` 로 제공됩니다. + +두 번째 인수는 다른 관리자에게 피드백을 전송할지 결정합니다. 일반적으로, 세계 시간이나 플레이어의 점수를 출력하는 등 세계에 영향을 주지 않는 명령어라면 `false` 로 설정됩니다. 반대로 시간이나 플레이어의 점수를 변경하는 등 명령어가 세계에 영향을 준다면 `true` 가 되게 됩니다. + +만약 명령어를 처리하는 데 실패한다면, `sendFeedback()`을 호출하는 대신에 바로 예외를 던질 수 있습니다. + +`CommandSyntaxException`은 일반적으로 명령어나 인수의 구문 오류를 나타낼 때 던져집니다. 원한다면 자신만의 예외도 던질 수 있습니다. + +방금 등록한 명령어를 실행하려면, 대소문자를 구분하여 `/foo`를 입력하면 됩니다. + +### 등록 환경 + +원하는 경우 명령어가 특정한 상황에만 등록되도록 할 수도 있습니다. + +@[code lang=java highlight={2} transcludeWith=:::2](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +### 명령어의 요구 사항 + +관리자만 실행 가능한 명령어를 만들고 싶다고 가정해봅시다. `require()` 메소드를 사용하기 딱 좋은 상황이군요. `require()` 메소드는 `ServerCommandSource`를 제공하고 `CommandSource`가 명령어를 실행할 수 있는지 판단하는 `Predicate`을 인수로 가집니다. + +@[code lang=java highlight={3} transcludeWith=:::3](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +이렇게 하면 명령 블록을 포함해 명령어 소스가 적어도 레벨 2 관리자는 되어야 명령어를 실행할 수 있게 됩니다. 요구 사항을 충족하지 못한다면 명령어는 등록조차 되지 않게 됩니다. + +하지만, 명령어가 등록이 되지 않아 레벨 2 관리자가 아닌 플레이어에게는 탭 자동 완성에서 표시되지 않는다는 단점이 있습니다. 치트를 켜지 않으면 대부분의 명령어를 탭 자동 완성에서 볼 수 없는 이유이기도 합니다. + +### 하위 명령어 + +하위 명령어를 추가하려면, 먼저 상위 명령어의 리터럴 노드를 등록해야 합니다. 그런 다음, 상위 명령어의 리터럴 노드 다음에 하위 명령어의 리터럴 노드를 덧붙이면 됩니다. + +@[code lang=java highlight={3} transcludeWith=:::7](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +인수 처럼, 하위 명령어 노드도 필수적이진 않습니다. 아래와 같은 상황에선, `/subtater` 와 `/subtater subcommand` 모두 올바른 명령어가 되게 됩니다. + +@[code lang=java highlight={2,8} transcludeWith=:::8](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +## 클라이언트 명령어 + +Fabric API는 `net.fabricmc.fabric.api.client.command.v2` 패키지에 클라이언트측 명령어를 등록할 때 사용되는 `ClientCommandManager` 클래스를 가지고 있습니다. 이러한 코드는 오로지 클라이언트측 코드에만 있어야 합니다. + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/client/java/com/example/docs/client/command/FabricDocsReferenceClientCommands.java) + +## 명령어 리다이렉션 + +"별칭 (Aliases)"로도 알려진 명령어 리다이렉션은 명령어의 기능을 다른 명령어로 리다이렉트(전송)하는 방법입니다. 명령어의 이름을 변경하고 싶지만, 기존 이름도 지원하고 싶을 때 유용하게 사용될 수 있습니다. + +@[code lang=java transcludeWith=:::12](@/reference/latest/src/client/java/com/example/docs/client/command/FabricDocsReferenceClientCommands.java) + +## 자주 묻는 질문 + +
+ +### 코드가 컴파일되지 않습니다 + +- `CommandSyntaxException` 예외를 던지거나 처리해 보세요 - `CommandSyntaxException`은 `RuntimeException`이 아닙니다. 예외가 메소드 서명에서 던져지는게 아니라면, 무조건 처리되어야 합니다. + Brigadier가 확인된 예외를 처리하고 게임에서 적절한 오류 메세지를 전송할 것입니다. + +- 제네릭 타입이 올바른지 확인해보세요 - 가끔 제네릭 타입에 문제가 있을 수도 있습니다. (대부분의 경우처럼) 명령어를 서버에 등록하려 한다면, `LiteralArgumentBuilder.literal` 대신에 `CommandManager.literal`, 또는 `RequiredArgumentBuilder.argument` 대신에 `CommandManager.argument`를 사용중인지 확인하세요. + +- `sendFeedback()` 메소드를 확인해보세요 - 두 번째 인수에 불리언을 추가하는걸 잊었을지도 모릅니다. 그리고 Minecraft 1.20부터 첫 번째 인수가 `Text`가 아니라 `Supplier` 임을 기억하세요. + +- 명령어는 무조건 정수를 반환해야 합니다 - 명령어를 등록할 때, `execute()` 메소드는 `Command` 객체를 (대부분의 경우 람다식으로) 받게 됩니다. 람다식은 무조건 정수를 반환해야 합니다. + +### 런타임에서 명령어를 등록할 수 있습니까? + +::: warning +You can do this, but it is not recommended. You would get the `CommandManager` from the server and add anything commands +you wish to its `CommandDispatcher`. + +그 다음에는, `CommandManager.sendCommandTree(ServerPlayerEntity)`를 통해 모든 플레이어에게 다시 명령어 트리를 전송해야 합니다. + +클라이언트는 로컬로 완료 오류를 보여주기 위해 로그인 단계 중에 (또는 관리자 패킷이 전송되었을 때) 서버로부터 명령어 트리를 받아 캐시하기 때문에 필수적인 작업입니다. +::: + +### 런타임에서 명령어를 등록 해제할 수 있습니까? + +::: warning +You can also do this, however, it is much less stable than registering commands at runtime and could cause unwanted side +effects. + +간단하게 하려면, Brigadier를 리플렉션해서 노드를 제거해야 합니다. 그 다음에는, `CommandManager.sendCommandTree(ServerPlayerEntity)`를 통해 모든 플레이어에게 다시 명령어 트리를 전송해야 합니다. + +업데이트된 명령어 트리를 전송하지 않으면, 서버가 명령어 처리에 실패해도 클라이언트는 아직 명령어가 존재한다고 표시할 것입니다. +::: diff --git a/versions/1.20.4/translated/ko_kr/develop/commands/suggestions.md b/versions/1.20.4/translated/ko_kr/develop/commands/suggestions.md new file mode 100644 index 000000000..e3a9a16be --- /dev/null +++ b/versions/1.20.4/translated/ko_kr/develop/commands/suggestions.md @@ -0,0 +1,45 @@ +--- +title: 명령어 제안 +description: 어떻게 명령어 인수를 플레이어에게 제안하는지 알아보세요. +authors: + - IMB11 +--- + +# 명령어 제안 + +Minecraft에는 `/give` 명령어처럼 많은 경우에서 사용되는 강력한 명령어 제안 체계가 잡혀 있습니다. 이 체계는 플레이어에게 명령어 인수 값을 제안하고, 유저가 제안된 값을 선택할 수 있게 해줍니다. + +## 제안 공급자 + +`SuggestionProvider`는 클라이언트에 전송될 제안 리스트를 만드는데 사용됩니다. 이는 `CommandContext`와 `SuggestionBuilder`를 인수로 받고 `Suggestions`를 반환하는 기능형 인터페이스 입니다. `SuggestionProvider`는 `CompletableFuture`를 반환해 인수가 항상 바로 사용 가능한것은 아닙니다. + +## 제안 공급자 사용하기 + +제안 공급자를 사용하려면, 인수 빌더의 `suggests` 메소드를 호출해야 합니다. 이 메드는 `SuggestionProvider`를 인수로 받고 제안 공급자가 덧붙여진 새로운 인수 빌더를 반환합니다. + +@[code java transcludeWith=:::9 highlight={4}](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +## 내장된 제안 공급자 + +시스템에 내장되어 있는 몇 가지 제안 공급자도 있습니다. + +| 제안 공급자 | 설명 | +| ----------------------------------------- | -------------------------------------- | +| `SuggestionProviders.SUMMONABLE_ENTITIES` | 생성 가능한 모든 엔티티를 제안합니다. | +| `SuggestionProviders.AVAILABLE_SOUNDS` | 재생 가능한 모든 소리를 제안합니다. | +| `LootCommand.SUGGESTION_PROVIDER` | 가능한 모든 전리품 테이블을 제안합니다. | +| `SuggestionProviders.ALL_BIOMES` | 가능한 모든 생물 군계를 제안합니다. | + +## 직접 제안 공급자 만들기 + +내장된 제안 공급자에 필요로 하는 것이 없다면, 직접 자신만의 제안 공급자를 만들 수도 있습니다. 이렇게 하려면, 먼저 `SuggestionProvider` 인터페이스를 구현(Implement)하는 클래스를 만들고, `getSuggestion` 메소드를 덮어써야(Override) 합니다. + +예를 들어, 서버의 모든 플레이어 이름을 제안하는 제안 공급자를 만들어 보겠습니다. + +@[code java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/command/PlayerSuggestionProvider.java) + +이 제안 공급자를 사용하려면, 그냥 간단하게 인수 빌더의 `.suggests` 메소드에 만든 인스턴스를 전달하기만 하면 됩니다. + +물론, 제안 공급자는 (이미 제공된 인수처럼) 명령어 컨텍스트를 읽어 명령어의 상태에 따라 제안을 변경할 수 있기 때문에, 제안 공급자가 더 복잡해질 수 있습니다. + +플레이어의 인벤토리의 아이템을 제안하거나, 플레이어 근처에 있는 엔티티를 제안할 수도 있습니다. diff --git a/versions/1.20.4/translated/ko_kr/develop/entities/damage-types.md b/versions/1.20.4/translated/ko_kr/develop/entities/damage-types.md new file mode 100644 index 000000000..9b9e13736 --- /dev/null +++ b/versions/1.20.4/translated/ko_kr/develop/entities/damage-types.md @@ -0,0 +1,96 @@ +--- +title: 피해 유형 +description: 사용자 정의 피해 유형을 추가하는 방법을 알아보세요. +authors: + - dicedpixels + - hiisuuii + - mattidragon +--- + +# 피해 유형 + +피해 유형은 엔티티가 입을 수 있는 피해(대미지)의 종류를 의미합니다. Minecraft 1.19.4 부터, 새로운 피해 유형의 추가는 데이터 기반이 되어, JSON 파일을 통해 생성됩니다. + +## 피해 유형 추가하기 + +_Tater_ 라는 이름의 사용자 정의 피해 유형을 추가해 봅시다. 이는 피해 유형의 JSON 파일을 생성하며 시작됩니다. 이 파일은 모드 리소스의 `data` 디렉토리의 `damage_type` 폴더에 저장됩니다. + +```:no-line-numbers +resources/data/fabric-docs-reference/damage_type/tater.json +``` + +파일은 다음과 같은 구조를 가지게 됩니다. + +@[code lang=json](@/reference/latest/src/main/generated/data/fabric-docs-reference/damage_type/tater.json) + +이 사용자 정의 피해 유형을 플레이어가 살아있는 엔티티가 아닌 것에서 피해를 입었을 때 [허기 피로](https://minecraft.wiki/w/Hunger#Exhaustion_level_increase)를 0.1만큼 올리도록 만들어 봅시다. 참고로, 피해 크기는 세계의 난이도에 비례합니다. + +::: info + +JSON 파일 구조에 대한 자세한 내용은 [Minecraft 위키 (영문)](https://minecraft.wiki/w/Damage_type#JSON_format) 를 참고하십시오. + +::: + +### 코드를 통해 피해 유형에 접근하기 + +코드를 통해 추가한 사용자 정의 피해 유형에 접근하고 싶다면, `DamageSource` 인스턴스를 생성하기 위해 `RegistryKey`에 접근해야 합니다. + +`RegistryKey` 는 다음 코드로 불러올 수 있습니다. + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/damage/FabricDocsReferenceDamageTypes.java) + +### 피해 유형 사용하기 + +피해 유형 사용의 예시를 만들어 보기 위해, 먼저 사용자 정의 블록 _Tater Block_을 추가해보겠습니다. _Tater Block_은 살아있는 엔티티가 밟으면 _Tater_ 피해를 입힙니다. + +피해를 주기 위해 먼저 `onSteppedOn` 메소드를 덮어(Override) 쓰겠습니다. + +사용자 정의 피해 유형의 `DamageSource`를 생성하며 시작합니다. + +@[code lang=java transclude={21-24}](@/reference/latest/src/main/java/com/example/docs/damage/TaterBlock.java) + +그리고, `entity.damage()` 메소드에 `DamageSource`와 피해 크기를 입력하여 호출합니다. + +@[code lang=java transclude={25-25}](@/reference/latest/src/main/java/com/example/docs/damage/TaterBlock.java) + +블록의 코드 전문은 다음과 같습니다. + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/damage/TaterBlock.java) + +이제 살아있는 엔티티가 블록 위에 서면, 사용자 정의 피해 유형으로 크기 5 (2.5 하트) 의 피해를 입게 됩니다. + +### 사용자 정의 사망 메세지 + +`en_us.json` 파일의 `death.attack.` 키를 수정해 사용자 정의 피해 유형의 사망 메세지를 수정할 수 있습니다. + +@[code lang=json transclude={4-4}](@/reference/latest/src/main/resources/assets/fabric-docs-reference/lang/en_us.json) + +이제 사용자 정의 피해 유형으로 사망하면, 다음 사망 메세지를 보게 될 것입니다. + +![플레이어 인벤토리에서 보여지는 효과](/assets/develop/tater-damage-death.png) + +### 피해 유형 태그 + +일부 피해 유형은 갑옷, 상태 효과 등을 무시할 수 있습니다. 태그는 이러한 피해 유형의 속성을 제어하는데 사용됩니다. + +피해 유형 태그는 `data/minecraft/tags/damage_type` 에 저장됩니다. + +::: info + +내장된 피해 유형 태그와 설명은 [Minecraft 위키 (영문)](https://minecraft.wiki/w/Tag#Damage_types) 를 참고하십시오. + +::: + +Tater 피해 유형을 `bypasses_armor` 피해 유형 태그에 추가해 봅시다. + +이러한 태그에 사용자 정의 피해 유형을 추가하려면, 먼저 `minecraft` 네임스페이스로 JSON 파일을 생성해야 합니다. + +```:no-line-numbers +data/minecraft/tags/damage_type/bypasses_armor.json +``` + +파일은 다음과 같은 구조를 가집니다. + +@[code lang=json](@/reference/latest/src/main/generated/data/minecraft/tags/damage_type/bypasses_armor.json) + +`replace` 키를 `false` 로 설정하여 기존 태그의 값을 제거하지 않도록 주의하세요. diff --git a/versions/1.20.4/translated/ko_kr/develop/entities/effects.md b/versions/1.20.4/translated/ko_kr/develop/entities/effects.md new file mode 100644 index 000000000..55012f3bf --- /dev/null +++ b/versions/1.20.4/translated/ko_kr/develop/entities/effects.md @@ -0,0 +1,69 @@ +--- +title: 상태 효과 +description: 사용자 정의 상태 효과를 만드는 방법을 알아보세요. +authors: + - dicedpixels + - YanisBft + - FireBlast + - Friendly-Banana + - SattesKrokodil +authors-nogithub: + - siglong + - tao0lu +--- + +# 상태 효과 + +이펙트, 효과로도 알려진 상태 효과는 엔티티에게 영향을 줄 수 있는 조건을 의미합니다. 이는 자연적으로 좋거나, 나쁘거나, 중립적일 수 있습니다. 기본 게임은 이러한 효과를 음식, 물약 등 다양한 방법으로 적용합니다. + +`/effect` 명령어를 통해 엔티티에게 효과를 부여할 수도 있습니다. + +## 사용자 정의 상태 효과 + +이 튜토리얼에서는, 매 틱마다 플레이어에게 경험 포인트를 주는 새로운 사용자 정의 효과 _Tater_ 를 만들어 보겠습니다. + +### `StatusEffect` 확장 + +모든 효과의 기본이 되는 `StatusEffect` 클래스의 사용자 정의 확장 클래스를 만들어 봅시다. + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/effect/TaterEffect.java) + +### 사용자 정의 효과 등록하기 + +블록, 아이템 등록처럼, `Registry.register`를 통해 `STATUS_EFFECT` 레지스트리에 사용자 정의 효과를 등록할 수 있습니다. 이는 모드 초기화 단계에서 완료되어야 합니다. + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/effect/FabricDocsReferenceEffects.java) + +### 현지화와 텍스쳐 + +사용자 정의 상태 효과에 플레이어의 인벤토리 화면에 보여질 텍스쳐 아이콘과 이름을 지정할 수 있습니다. + +#### 텍스쳐 + +상태 효과의 아이콘은 18x18의 PNG 입니다. 사용자 정의 아이콘을 다음 폴더에 넣어 적용할 수 있습니다: + +```:no-line-numbers +resources/assets/fabric-docs-reference/textures/mob_effect/tater.png +``` + +![플레이어 인벤토리에서 보여지는 효과](/assets/develop/tater-effect.png) + +#### 현지화 + +다른 현지화처럼, 간단히 언어 파일에 `"effect..": "값"` 포맷의 엔트리 ID를 추가하기만 하면 됩니다. + +::: code-group + +```json[assets/fabric-docs-reference/lang/en_us.json] +{ + "effect.fabric-docs-reference.tater": "Tater" +} +``` + +### 테스트 + +`/effect give @s fabric-docs-reference:tater` 명령어를 사용해 직접 Tater 효과를 부여해 보세요. `/effect clear`로 효과를 제거할 수 있습니다. + +::: info +사용자 정의 효과를 부여하는 물약을 만드는 방법은 [물약](../items/potions) 가이드를 참조하세요. +::: diff --git a/versions/1.20.4/translated/ko_kr/develop/index.md b/versions/1.20.4/translated/ko_kr/develop/index.md new file mode 100644 index 000000000..78b99bd0c --- /dev/null +++ b/versions/1.20.4/translated/ko_kr/develop/index.md @@ -0,0 +1,12 @@ +--- +title: 개발자 가이드 +description: "커뮤니티에서 작성한 엄선된 개발자 가이드는 개발 환경 설정부터 렌더링 및 네트워킹과 같은 고급 주제까지 광범위한 주제를 다루고 있습니다. " +--- + +# 개발자 가이드 + +커뮤니티에서 작성한 엄선된 개발자 가이드는 개발 환경 설정부터 렌더링 및 네트워킹과 같은 고급 주제까지 광범위한 주제를 다루고 있습니다. + +사이드바에서 전체 개발자 가이드 문서를 둘러보십시오. 무언가 찾고 있다면, 우측 상단의 검색 바를 통해 원하는 페이지를 찾을 수 있습니다. + +Fabric 문서에 기여하고 싶다면, [GitHub](https://github.com/FabricMC/fabric-docs)에서 원본 코드를 볼 수 있으며, 기여시에는 [기여 가이드라인](../contributing)을 준수하시기 바랍니다. diff --git a/translated/ko_kr/develop/items/potions.md b/versions/1.20.4/translated/ko_kr/develop/items/potions.md similarity index 100% rename from translated/ko_kr/develop/items/potions.md rename to versions/1.20.4/translated/ko_kr/develop/items/potions.md diff --git a/translated/ko_kr/develop/rendering/basic-concepts.md b/versions/1.20.4/translated/ko_kr/develop/rendering/basic-concepts.md similarity index 100% rename from translated/ko_kr/develop/rendering/basic-concepts.md rename to versions/1.20.4/translated/ko_kr/develop/rendering/basic-concepts.md diff --git a/versions/1.20.4/translated/ko_kr/develop/rendering/gui/custom-screens.md b/versions/1.20.4/translated/ko_kr/develop/rendering/gui/custom-screens.md new file mode 100644 index 000000000..6c73a43bb --- /dev/null +++ b/versions/1.20.4/translated/ko_kr/develop/rendering/gui/custom-screens.md @@ -0,0 +1,64 @@ +--- +title: 사용자 정의 화면 +description: 모드의 사용자 정의 화면을 만드는 방법을 알아보세요. +authors: + - IMB11 +--- + +# 사용자 정의 화면 + +:::info +본 튜토리얼은 서버에서 처리되는 화면이 아닌 클라이언트에서 표시되는 일반 화면 에 대한 튜토리얼입니다. +::: + +화면은 일반적으로 타이틀 화면, 일시 정지 화면 등과 같이 플레이어가 상호 작용하는 GUI를 의미합니다. + +이러한 화면은 사용자 정의 정보, 사용자 정의 설정 메뉴 등을 표시하기 위해 직접 만들 수 있습니다. + +## 화면 만들기 + +화면을 만드려면, 먼저 `Screen` 클래스를 확장하는(Extend) 클래스를 만들고, `init` 메소드를 덮어 써야(Override) 합니다. + +사용자 정의 화면을 제작할 때 다음 사항에 유의해야 합니다. + +- 생성자 메소드에서 화면이 초기화되지 않기 때문에 위젯또한 생성되지 않습니다. +- `init` 메소드는 화면이 초기화되었을 때 호출되므로, 위젯을 만들기에 가장 좋은 위치입니다. + - 모든 그려질 수 있는 위젯이 입력되는 `addDrawableChild` 메소드를 통해 위젯을 추가합니다. +- `render` 메소드는 매 프레임마다 호출되므로, 메소드를 통해 그려지는 컨텍스트, 마우스 포인터의 위치에 접근할 수 있습니다. + +예를 들어, 라벨이 위에 있는 버튼이 있는 간단한 화면을 만들어 보겠습니다. + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/client/java/com/example/docs/rendering/screens/CustomScreen.java) + +![사용자 정의 화면 1](/assets/develop/rendering/gui/custom-1-example.png) + +## 화면 열기 + +화면은 `MinecraftClient`의 `setScreen` 메소드를 통해 열 수 있습니다. + +```java +MinecraftClient.getInstance().setScreen( + new CustomScreen(Text.empty()) +); +``` + +## 화면 닫기 + +만약 화면을 닫고 싶다면, `setScreen` 메소드를 통해 간단하게 화면을 `null` 로 설정하면 됩니다. + +```java +MinecraftClient.getInstance().setScreen(null); +``` + +만약 디테일하게 이전 화면으로 되돌아가는 기능을 추가하고 싶다면, 현재 화면을 `CustomScreen` 생성자에 입력하여 필드에 저장하고, `close` 메소드가 호출되었을 때 해당 필드를 사용하여 이전 화면으로 되돌아가면 됩니다. + +@[code lang=java transcludeWith=:::2](@/reference/latest/src/client/java/com/example/docs/rendering/screens/CustomScreen.java) + +이제, 사용자 정의 화면이 열릴 때, 현재 화면을 두 번째 매개변수에 입력하면, `CustomScreen#close`가 호출되었을 때 이전 화면으로 되돌아갈 것입니다. + +```java +Screen currentScreen = MinecraftClient.getInstance().currentScreen; +MinecraftClient.getInstance().setScreen( + new CustomScreen(Text.empty(), currentScreen) +); +``` diff --git a/versions/1.20.4/translated/ko_kr/develop/rendering/gui/custom-widgets.md b/versions/1.20.4/translated/ko_kr/develop/rendering/gui/custom-widgets.md new file mode 100644 index 000000000..40ad0f2ef --- /dev/null +++ b/versions/1.20.4/translated/ko_kr/develop/rendering/gui/custom-widgets.md @@ -0,0 +1,39 @@ +--- +title: 사용자 정의 위젯 +description: 화면에 사용될 사용자 정의 위젯을 만드는 방법을 알아보세요. +authors: + - IMB11 +--- + +# 사용자 정의 위젯 + +위젯은 일반적으로 화면에 추가되는 렌더링 컴포넌트의 컨테이너로, 키 입력, 마우스 클릭 등의 여러 이벤트를 통해 플레이어와 상호작용할 수 있습니다. + +## 위젯 만들기 + +`ClickableWidget`을 확장(Extend)하는 등 위젯 클래스를 만드는 방법은 여러 가지가 있습니다. `ClickableWidget` 클래스는 `Drawable`, `Element`, `Narratable`, `Selectable` 인터페이스를 확장해 높이, 너비, 위치, 이벤트 처리 등 여러 유용한 도구를 제공합니다. + +- `Drawable` - 렌더링 - `addDrawableChild` 메소드를 통해 화면에 위젯을 등록하려면 필수적인 인터페이스입니다. +- `Element` - 이벤트 - 마우스 클릭, 키 입력 등과 같은 이벤트를 처리하려면 필수적입니다. +- `Narratable` - 접근성 - 스크린 리더 등 여러 접근성 도구가 사용자 정의 위젯에 접근하려면 필수적입니다. +- `Selectable` - 탭 선택 - 위젯이 키를 통해 선택 가능하게 하려면 필수적입니다. + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/client/java/com/example/docs/rendering/screens/CustomWidget.java) + +## 화면에 위젯 추가하기 + +다른 위젯와 같이, 위젯을 화면에 추가하려면 `Screen` 클래스에서 제공되는 `addDrawableChild` 메소드를 사용해야 합니다. 이러한 작업은 `init` 메소드에서 수행되어야 합니다. + +@[code lang=java transcludeWith=:::3](@/reference/latest/src/client/java/com/example/docs/rendering/screens/CustomScreen.java) + +![화면에 표시되는 사용자 정의 위젯](/assets/develop/rendering/gui/custom-widget-example.png) + +## 위젯 이벤트 + +`onMouseClicked`, `onMouseReleased`, `onKeyPressed` 등의 메소드를 덮어 쓰기(Override) 하여 마우스 클릭, 키 입력 등과 같은 이벤트를 처리할 수 있습니다. + +예를 들어, `ClickableWidget` 클래스에서 제공되는 `isHovered()` 메소드를 통해 마우스가 호버되면 위젯 색이 변경되도록 해보겠습니다. + +@[code lang=java transcludeWith=:::2](@/reference/latest/src/client/java/com/example/docs/rendering/screens/CustomWidget.java) + +![호버 이벤트 예시](/assets/develop/rendering/gui/custom-widget-events.webp) diff --git a/versions/1.20.4/translated/ko_kr/develop/rendering/particles/creating-particles.md b/versions/1.20.4/translated/ko_kr/develop/rendering/particles/creating-particles.md new file mode 100644 index 000000000..251555d06 --- /dev/null +++ b/versions/1.20.4/translated/ko_kr/develop/rendering/particles/creating-particles.md @@ -0,0 +1,72 @@ +--- +title: 사용자 정의 입자 만들기 +description: Fabric API를 통해 사용자 정의 입자를 만드는 방법을 알아보세요. +authors: + - Superkat32 +--- + +# 사용자 정의 입자 만들기 + +입자는 강력한 도구입니다. 아름다운 장면에 분위기를 더할 수도 있고, 보스와의 전투에 긴장감을 더할 수도 있습니다. 그럼 직접 한번 만들어 봅시다! + +## 사용자 정의 입자 등록하기 + +이 튜토리얼에서는 엔드 막대기 입자처럼 움직이는 새로운 스파클 입자를 추가해 볼 예정입니다. + +먼저, 모드 초기화 클래스에 모드 ID로 `ParticleType` 을 등록해 봅시다. + +@[code lang=java transcludeWith=#particle_register_main](@/reference/latest/src/main/java/com/example/docs/FabricDocsReference.java) + +소문자로 "sparkle_particle"은 이후 입자의 텍스쳐를 위한 JSON 파일의 이름이 되게 됩니다. 곧 JSON 파일을 어떻게 생성하는지 알아볼 것입니다. + +## 클라이언트측에서 등록하기 + +`ModInitializer` 엔트리포인트에 입자를 등록했다면, `ClientModInitializer`의 엔트리포인트에도 입자를 등록해야 합니다. + +@[code lang=java transcludeWith=#particle_register_client](@/reference/latest/src/client/java/com/example/docs/FabricDocsReferenceClient.java) + +위 예시는 입자를 클라이언트측에 등록하는 방법입니다. 이제 엔드 막대기 입자 팩토리를 통해 입자에 움직임을 줘보겠습니다. 이렇게 하면 입자가 엔드 막대기 입자와 똑같이 움직이게 됩니다. + +::: tip +You can see all the particle factories by looking at all the implementations of the `ParticleFactory` interface. This is helpful if you want to use another particle's behaviour for your own particle. + +- IntelliJ 단축 키: Ctrl+Alt+B +- VSCode 단축 키: Ctrl+F12 +::: + +## JSON 파일을 만들고 텍스쳐 추가하기 + +먼저, 모드 소스의 `resources/assets//` 폴더에 두 가지 새로운 폴더를 생성해야 합니다. + +| 폴더 경로 | 설명 | +| -------------------- | --------------------------------------------------------------- | +| `/textures/particle` | `/textures/particle` 폴더는 입자의 모든 텍스쳐를 담습니다. | +| `/particles` | `particles` 폴더는 입자의 정보에 대한 모든 JSON 파일을 담고 있습니다. | + +예를 들어, `textures/particle` 폴더에는 "sparkle_particle_texture.png" 라는 이름의 텍스쳐 이미지를 넣겠습니다. + +그리고, `particles` 폴더에는 ParticleType에 등록한 것과 같은 이름의 소문자를 이름으로 가지는 JSON 파일을 생성합니다. 이 예제에서는, `sparkle_particle.json` 으로 생성하겠습니다. 이 파일은 Minecraft가 입자에 어떠한 텍스쳐를 사용해야 하는지 정의하기 때문에 매우 중요합니다. + +@[code lang=json](@/reference/latest/src/main/resources/assets/fabric-docs-reference/particles/sparkle_particle.json) + +:::tip +입자에 애니메이션을 적용하고 싶다면 `textures` 배열 노드에 더 많은 텍스쳐를 추가하면 됩니다. 입자는 배열의 순서대로 반복될 것입니다. +::: + +## 새 입자 테스트하기 + +위의 모든 작업을 완료했다면, 이제 Minecraft에서 입자를 테스트해볼 차례입니다. + +다음의 명령어를 입력하여 입자가 정상적으로 작동하는지 확인할 수 있습니다. + +```mcfunction +/particle :sparkle_particle ~ ~1 ~ +``` + +![입자 쇼케이스](/assets/develop/rendering/particles/sparkle-particle-showcase.png) + +:::info +이 명령어를 사용하면 입자가 플레이어 안에 생성될 것입니다. 입자를 보려면 뒤로 몇 걸음 걸어야할 수도 있습니다. +::: + +대신, 같은 명령어로 명령 블록을 통해 입자를 생성할 수도 있습니다. diff --git a/versions/1.20.4/translated/ko_kr/index.md b/versions/1.20.4/translated/ko_kr/index.md new file mode 100644 index 000000000..b107ef1eb --- /dev/null +++ b/versions/1.20.4/translated/ko_kr/index.md @@ -0,0 +1,27 @@ +--- +title: Fabric 문서 +description: 마인크래프트용 모딩 툴체인 Fabric의 엄선된 공식 문서입니다. +layout: home +hero: + name: Fabric 문서 + tagline: 마인크래프트용 모딩 툴체인 Fabric의 엄선된 공식 문서입니다. +features: + - title: 개발자 가이드 + icon: 🛠️ + details: 커뮤니티에서 작성한 엄선된 개발자 가이드는 개발 환경 설정부터 렌더링 및 네트워킹과 같은 고급 주제까지 광범위한 주제를 다루고 있습니다. + link: ./develop/index + linkText: 시작하기 + - title: 플레이어 가이드 + icon: 📚 + details: Fabric 기반 모드를 사용하려는 플레이어인가요? 플레이어 가이드에서 자세히 알아보세요. 이 가이드는 Fabric 모드 다운로드, 설치 및 문제 해결을 도와줍니다. + link: ./players/index + linkText: 자세히보기 +--- + +
+ +## 이 프로젝트에 기여하고 싶으신가요? + +Fabric 문서에 기여하고 싶다면, [GitHub](https://github.com/FabricMC/fabric-docs)에서 소스 코드를 볼 수 있으며, 기여시에는 [기여 가이드라인](./contributing)을 준수하시기 바랍니다. + +
diff --git a/versions/1.20.4/translated/ko_kr/players/faq.md b/versions/1.20.4/translated/ko_kr/players/faq.md new file mode 100644 index 000000000..22e4f7ca0 --- /dev/null +++ b/versions/1.20.4/translated/ko_kr/players/faq.md @@ -0,0 +1,31 @@ +--- +title: 자주 묻는 질문 +description: Fabric 관련 서버 관리자와 플레이어가 자주 묻는 질문입니다. +--- + +# 자주 묻는 질문 + +자주 언급되는 질문이 여럿 있으므로, 아래에 간단히 정리했습니다. + +## 일반적인 질문 + +### Fabric이 지원하는 Minecraft 버전은 무엇인가요? + +공식적으로, Fabric은 스냅숏 `18w43b` (`1.14` 이상) 의 모든 버전을 지원합니다. + +### 어디서 Fabric 모드를 다운로드 할 수 있나요? + +:::info +항상 모드를 다운로드한 사이트가 안전한지 확인하세요. [안전한 모드 찾기](./finding-mods) 에서 더 많은 정보를 확인할 수 있습니다. +::: + +대부분의 모드 개발자는 [Modrinth](https://modrinth.com/mods?g=categories:%27fabric%27) 또는 [CurseForge](https://www.curseforge.com/minecraft/search?class=mc-mods&gameVersionTypeId=4) 에 모드를 업로드 합니다. + +### 먼저 생성된 Fabric 모드팩은 어디에서 찾을 수 있나요? + +Fabric 모드팩은 다음과 같이 여러 플랫폼에서 찾을 수 있습니다. + +- [Modrinth](https://modrinth.com/modpacks?g=categories:%27fabric%27) +- [CurseForge](https://www.curseforge.com/minecraft/search?class=modpacks&gameVersionTypeId=4) +- [Feed The Beast](https://www.feed-the-beast.com/ftb-app) +- [Technic](https://www.technicpack.net/modpacks) diff --git a/versions/1.20.4/translated/ko_kr/players/troubleshooting/crash-reports.md b/versions/1.20.4/translated/ko_kr/players/troubleshooting/crash-reports.md new file mode 100644 index 000000000..03aeaf4b2 --- /dev/null +++ b/versions/1.20.4/translated/ko_kr/players/troubleshooting/crash-reports.md @@ -0,0 +1,104 @@ +--- +title: 충돌 보고서 +description: 충돌 보고서가 어떤 역할을 가지고, 어떻게 읽는지 알아보세요. +authors: + - IMB11 +--- + +# 충돌 보고서 + +:::tip +충돌의 원인을 찾는 데 어려움이 있으시다면, [Fabric Discord (영어)](https://discord.gg/v6v4pMv) 의 `#player-support` 또는 `#server-admin-support` 채널에 도움을 요청할 수 있습니다. +::: + +충돌 보고서는 게임 또는 서버의 문제를 해결하기 위해 굉장히 중요한 부분 중 하나입니다. 이러한 충돌 보고서는 충돌에 관련된 많은 정보를 포함하고 있으며, 충돌의 원인을 찾는 데 도움이 됩니다. + +## 충돌 보고서 찾기 + +충돌 보고서는 게임 디렉토리의 `crash-reports` 폴더에 저장됩니다. 서버의 경우, 서버 디렉토리의 `crash-reports` 폴더에 저장됩니다. + +서드 파티 런처의 경우, 충돌 보고서를 찾으려면 해당 런처의 문서를 참고해야 할 수 있습니다. + +충돌 보고서는 다음과 같은 위치에서 찾을 수 있습니다. + +::: code-group + +```:no-line-numbers [Windows] +%appdata%\.minecraft\crash-reports +``` + +```:no-line-numbers [macOS] +~/Library/Application Support/minecraft/crash-reports +``` + +```:no-line-numbers [Linux] +~/.minecraft/crash-reports +``` + +::: + +## 충돌 보고서 읽기 + +충돌 보고서는 매우 길고, 읽기 매우 어려울 수 있습니다. 하지만, 충돌에 관련된 많은 정보를 포함하고 있고, 충돌의 원인을 찾는데 유용합니다. + +이 가이드에선, [이 충돌 보고서를 예시로](https://github.com/FabricMC/fabric-docs/blob/main/public/assets/players/crash-report-example.txt) 보고서를 읽어 볼 것입니다. + +### 충돌 보고서의 목차 + +충돌 보고서는 여러 목차로 이루어져 있으며, 각 목차는 다음 제목을 가집니다. + +- `---- Minecraft Crash Report ----`, 보고서 요약본. 이는 충돌을 일으킨 주요 오류, 발생한 시간, 그리고 관련 스택트레이스로 이루어집니다. 대부분의 경우에서 스택트레이스에 충돌을 일으킨 모드의 리퍼런스가 포함되므로 보고서의 가장 중요한 부분이라고 할 수 있습니다. +- `-- Last Reload --`, 충돌이 리소스 다시 로드 (F3+T) 도중 발생하지 않았다면 대부분 불필요합니다. 다시 로드가 진행된 시간, 다시 로드 중 발생한 오류의 관련 스택 트레이스 등을 포함합니다. 이러한 오류는 대부분 리소스 팩에서 발생하며, 게임에 문제를 일으키지 않는 한 신경 쓸 필요는 없습니다. +- `-- System Details --`, 시스템에 대한 정보. 운영체제, Java 버전, 게임에 할당된 메모리의 양 등이 기록됩니다. 게임에 적당한 양의 메모리가 할당되었는지, 올바른 Java 버전을 사용했는지 등을 확인할 때 유용합니다. + - Fabric의 경우, 여기에 설치된 모드가 기록되는 `Fabric Mods:` 가 추가됩니다. 모드 간 충돌을 파악할 때 유용합니다. + +### 충돌 보고서 분해하기 + +이제 충돌 보고서의 목차를 알았으니, 충돌 보고서를 분해해서 충돌의 원인이 무엇인지 파악할 수 있게 되었습니다. + +아래에 링크된 예시를 통해, 충돌 보고서를 분석하고 충돌을 일으킨 원인과 모드를 찾아봅시다. + +이 예시에서는 `---- Minecraft Crash Report ----` 의 스택트레이스에 충돌을 일으킨 주요 오류가 기록되어 있으므로, 가장 중요한 부분이라 할 수 있습니다. 예시에서 발생한 오류는 `java.lang.NullPointerException: Cannot invoke "net.minecraft.class_2248.method_9539()" because "net.minecraft.class_2248.field_10540" is null` 입니다. + +스택트레이스에 언급된 모드의 개수에 따라, 정확히 지목하기 어려울 수 있지만, 가장 먼저 해야 할 일은 충돌을 일으킨 모드를 찾는 것입니다. + +```:no-line-numbers +at snownee.snow.block.ShapeCaches.get(ShapeCaches.java:51) +at snownee.snow.block.SnowWallBlock.method_9549(SnowWallBlock.java:26) // [!code focus] +... +at me.jellysquid.mods.sodium.client.render.chunk.compile.pipeline.BlockOcclusionCache.shouldDrawSide(BlockOcclusionCache.java:52) +at link.infra.indium.renderer.render.TerrainBlockRenderInfo.shouldDrawFaceInner(TerrainBlockRenderInfo.java:31) +... +``` + +이 예시에서는, 스택트레이스에서 처음으로 언급 된 `snownee` 가 충돌을 일으킨 모드입니다. + +하지만, 여러 모드가 비슷한 비율로 언급되었다면, 모드 간 호환성 문제일 수 있으며, 충돌을 일으킨 모드의 코드는 문제가 없을 가능성도 있습니다. 이런 경우에는, 모드 개발자에서 충돌을 신고하고, 개발자가 충돌을 파악하도록 하는 것이 최고의 선택입니다. + +## Mixin 충돌 + +:::info +Mixin은 게임의 소스 코드를 수정하지 않고 게임을 수정하는 방법 중 하나입니다. 이는 여러 모드에서 사용되고, 개발자에게 가장 강력한 도구가 됩니다. +::: + +Mixin이 충돌하면, 스택 트레이스에는 충돌이 발생한 Mixin과, Mixin을 수정하려고 시도한 모드가 기록됩니다. + +메소드 Mixin은 스택트레이스에 `modId$handlerName` 로 기록되는데, `modId`는 모드의 아이디, `handlerName`은 Mixin 처리기의 이름입니다. + +```:no-line-numbers +... net.minecraft.class_2248.method_3821$$$modid$handlerName() ... // [!code focus] +``` + +이 정보를 통해 충돌을 일으킨 모드를 찾고, 모드 개발자에게 충돌을 신고할 수 있게 됩니다. + +## 충돌 보고서로 할 수 있는 것 + +충돌 보고서로 할 수 있는 최고의 행동은 보고서를 기록(Paste) 사이트에 업로드 하고, 이슈 트래커 또는 커뮤니티에 게시하여 모드 개발자에게 공유하는 것입니다. + +이는 모드 개발자가 충돌을 재현하는 등 분석하고, 충돌을 해결할 수 있게 합니다. + +일반적으로 충돌 보고서에 사용되는 기록 사이트는 다음과 같습니다. + +- [GitHub Gist](https://gist.github.com/) +- [Pastebin](https://pastebin.com/) +- [mclo.gs](https://mclo.gs/) diff --git a/versions/1.20.4/translated/ko_kr/players/troubleshooting/uploading-logs.md b/versions/1.20.4/translated/ko_kr/players/troubleshooting/uploading-logs.md new file mode 100644 index 000000000..f82d9f240 --- /dev/null +++ b/versions/1.20.4/translated/ko_kr/players/troubleshooting/uploading-logs.md @@ -0,0 +1,54 @@ +--- +title: 로그 업로드 +description: 문제를 해결하기 위해 로그를 업로드하는 방법을 알아보세요. +authors: + - IMB11 +--- + +# 로그 업로드 + +문제를 해결할 때, 원인을 파악하기 위해 개발자에게 로그를 전송해야 하는 경우가 자주 있습니다. + +## 로그를 업로드해야 하는 이유 + +로그를 단순히 복사-붙여넣기 하는것 보다 업로드하면 문제를 해결하는게 보다 수월해집니다. 또한 다른 곳으로 로그를 간단하게 전송할 수 있게 됩니다. + +때때로 일부 서비스에서는 로그에 구문 강조를 지원하여, 더 쉽게 읽을 수 있게 하고, 사용자 아이디나 시스템 정보 등 민감한 정보를 걸러주기도 합니다. + +## 충돌 보고서 + +충돌 리포트는 게임이 충돌하면 자동으로 생성되며, 게임의 전체 로그 대신 충돌 관련 정보만 포함하고 있습니다. 충돌 리포트는 게임 디렉토리의 `crash-reports` 폴더에 저장됩니다. + +충돌 리포트에 대한 자세한 정보는 [충돌 리포트](./crash-reports) 페이지를 참고하세요. + +## 로그 찾기 + +본 가이드는 공식 Minecraft 런처 (일반적으로 "바닐라 런처" 라고 불림) 를 위한 것이며, 서드파티 런처는 해당 런처의 문서를 확인해야 합니다. + +로그는 게임 디렉토리의 `logs` 폴더에 저장됩니다. 각 운영체제에서 로그 폴더의 위치는 다음과 같습니다. + +::: code-group + +```:no-line-numbers [Windows] +%appdata%\.minecraft +``` + +```:no-line-numbers [macOS] +~/Library/Application Support/minecraft +``` + +```:no-line-numbers [Linux] +~/.minecraft +``` + +::: + +최신 로그는 `latest.log` 에 저장되며, 이전 로그는 `연도-월-일_순서.log.gz` 의 이름 패턴으로 저장됩니다. + +## 로그 업로드 + +로그는 다음처럼 여러 서비스로 업로드 될 수 있습니다. + +- [Pastebin](https://pastebin.com/) +- [GitHub Gist](https://gist.github.com/) +- [mclo.gs](https://mclo.gs/) diff --git a/versions/1.20.4/translated/ko_kr/sidebar_translations.json b/versions/1.20.4/translated/ko_kr/sidebar_translations.json new file mode 100644 index 000000000..a327a7afc --- /dev/null +++ b/versions/1.20.4/translated/ko_kr/sidebar_translations.json @@ -0,0 +1,46 @@ +{ + "players.title": "플레이어 가이드", + "players.faq": "자주 묻는 질문", + "players.installingJava": "Java 설치", + "players.installingJava.windows": "Windows", + "players.installingJava.macOS": "macOS", + "players.installingJava.linux": "Linux", + "players.installingFabric": "Fabric 설치", + "players.findingMods": "신뢰 가능한 모드 찾기", + "players.installingMods": "모드 설치", + "players.troubleshooting": "스스로 해결", + "players.troubleshooting.uploadingLogs": "로그 업로드", + "players.troubleshooting.crashReports": "충돌 보고서", + "players.updatingFabric": "Fabric 업데이트", + "develop.title": "개발자 가이드", + "develop.gettingStarted": "시작하기", + "develop.gettingStarted.introduction": "패브릭과 모딩 소개", + "develop.gettingStarted.devEnvSetup": "개발 환경 설정하기", + "develop.gettingStarted.creatingProject": "프로젝트 생성하기", + "develop.gettingStarted.projectStructure": "프로젝트 구조", + "develop.gettingStarted.launchGame": "게임 실행하기", + "develop.items": "아이템", + "develop.items.potions": "물약", + "develop.entities": "엔티티", + "develop.entities.effects": "상태 효과", + "develop.entities.damage-types": "피해 유형", + "develop.commands": "명령어", + "develop.commands.basics": "명령어 만들기", + "develop.commands.arguments": "인수", + "develop.commands.suggestions": "제안", + "develop.rendering": "렌더링", + "develop.rendering.basicConcepts": "기본 렌더링 개념", + "develop.rendering.drawContext": "그리기 컨텍스트 사용", + "develop.rendering.hud": "HUD 렌더링", + "develop.rendering.gui": "GUI와 화면", + "develop.rendering.gui.customScreens": "사용자 정의 화면", + "develop.rendering.gui.customWidgets": "사용자 정의 위젯", + "develop.rendering.particles": "입자", + "develop.rendering.particles.creatingParticles": "사용자 정의 입자 만들기", + "develop.misc": "기타", + "develop.misc.codecs": "코덱", + "develop.misc.events": "이벤트", + "develop.sounds": "소리", + "develop.sounds.using-sounds": "소리 이벤트 재생", + "develop.sounds.custom": "사용자 정의 소리 생성" +} \ No newline at end of file diff --git a/versions/1.20.4/translated/ms_my/players/index.md b/versions/1.20.4/translated/ms_my/players/index.md new file mode 100644 index 000000000..eeddd1322 --- /dev/null +++ b/versions/1.20.4/translated/ms_my/players/index.md @@ -0,0 +1,12 @@ +--- +title: Panduan Pemain +description: Koleksi panduan untuk pemain dan juga pentadbir pelayan dalam memasang dan menggunakan Fabric. +--- + +# Panduan Pemain + +Bahagian Dokumentasi Fabric ini dikhususkan kepada pemain dan pentadbir pelayan yang ingin mengetahui cara memasang, menggunakan dan menyelesaikan masalah berkenaan Fabric. + +Anda harus merujuk kepada bar sisi untuk senarai semua panduan yang tersedia. + +Jika anda menghadapi sebarang isu, sila laporkannya [di GitHub](https://github.com/FabricMC/fabric-docs) atau minta bantuan di [pelayan Discord Fabric](https://discord.gg/v6v4pMv) dalam saluran `#player-support` atau `#server-admin-support`. diff --git a/versions/1.20.4/translated/ms_my/players/troubleshooting/uploading-logs.md b/versions/1.20.4/translated/ms_my/players/troubleshooting/uploading-logs.md new file mode 100644 index 000000000..f8f38834d --- /dev/null +++ b/versions/1.20.4/translated/ms_my/players/troubleshooting/uploading-logs.md @@ -0,0 +1,54 @@ +--- +title: Memuat Naik Log +description: Cara memuat naik log untuk menyelesaikan masalah. +authors: + - IMB11 +--- + +# Memuat Naik Log + +Apabila menyelesaikan masalah, anda selalunya perlu menyediakan log untuk membantu mengenal pasti punca isu tersebut. + +## Mengapa saya perlu memuat naik log? + +Memuat naik log membolehkan orang lain membantu anda dalam menyelesaikan masalah anda dengan lebih cepat daripada hanya menampal log ke dalam ruang perbualan atau siaran forum. Ia juga membolehkan anda berkongsi log anda dengan orang lain tanpa perlu menyalin dan menampalnya. + +Sesetengah tapak penampalan juga menyediakan penyerlahan sintaks untuk log, yang menjadikannya lebih mudah dibaca dan mungkin menapis maklumat sensitif, seperti nama pengguna anda atau maklumat sistem. + +## Laporan Ranap Permainan + +Laporan ranap permainan dijana secara automatik apabila permainan ranap. Ia hanya mengandungi maklumat ranap dan bukan log sebenar permainan. Ia terletak di dalam folder `crash-reports` dalam direktori permainan. + +Untuk mendapatkan maklumat lanjut tentang laporan ranap permainan, lihat [Laporan Ranap Permainan](./crash-reports). + +## Mencari Lokasi Log + +Panduan ini merangkumi Pelancar Minecraft rasmi (biasanya dirujuk sebagai "pelancar vanila") - untuk pelancar pihak ketiga, anda harus merujuk dokumentasi mereka. + +Log-log terletak di dalam folder `log` dalam direktori permainan, direktori permainan boleh didapati di lokasi berikut bergantung pada sistem pengoperasian anda: + +::: code-group + +```:no-line-numbers [Windows] +%appdata%\.minecraft +``` + +```:no-line-numbers [macOS] +~/Library/Application Support/minecraft +``` + +```:no-line-numbers [Linux] +~/.minecraft +``` + +::: + +Log terkini dipanggil `latest.log`, dan log sebelumnya menggunakan corak penamaan `yyyy-mm-dd_number.log.gz`. + +## Memuat Naik Log + +Log boleh dimuat naik ke pelbagai perkhidmatan, seperti: + +- [Pastebin](https://pastebin.com/) +- [GitHub Gist](https://gist.github.com/) +- [mclo.gs](https://mclo.gs/) diff --git a/versions/1.20.4/translated/nl_nl/sidebar_translations.json b/versions/1.20.4/translated/nl_nl/sidebar_translations.json new file mode 100644 index 000000000..7639c47e1 --- /dev/null +++ b/versions/1.20.4/translated/nl_nl/sidebar_translations.json @@ -0,0 +1,46 @@ +{ + "players.title": "Gebruikershandleidingen", + "players.faq": "Veelgestelde Vragen", + "players.installingJava": "Java installeren", + "players.installingJava.windows": "Windows", + "players.installingJava.macOS": "macOS", + "players.installingJava.linux": "Linux", + "players.installingFabric": "Fabric Installeren", + "players.findingMods": "Betrouwbare Mods Vinden", + "players.installingMods": "Mods Installeren", + "players.troubleshooting": "Problemen oplossen", + "players.troubleshooting.uploadingLogs": "Je Logs Uploaden", + "players.troubleshooting.crashReports": "Crashrapporten", + "players.updatingFabric": "Fabric Updaten", + "develop.title": "Ontwikkelaarshandleidingen", + "develop.gettingStarted": "Om Te Beginnen", + "develop.gettingStarted.introduction": "Introductie Tot Fabric En Modden", + "develop.gettingStarted.devEnvSetup": "Je Ontwikkelingsomgeving Opzetten", + "develop.gettingStarted.creatingProject": "Een Project Aanmaken", + "develop.gettingStarted.projectStructure": "Projectstructuur", + "develop.gettingStarted.launchGame": "Je Game Starten", + "develop.items": "Voorwerpen", + "develop.items.potions": "Drankjes", + "develop.entities": "Entiteiten", + "develop.entities.effects": "Statuseffecten", + "develop.entities.damage-types": "Schadesoorten", + "develop.commands": "Commando's", + "develop.commands.basics": "Commando's Maken", + "develop.commands.arguments": "Argumenten", + "develop.commands.suggestions": "Suggesties", + "develop.rendering": "Weergave", + "develop.rendering.basicConcepts": "Basis Weergaveconcepten", + "develop.rendering.drawContext": "De Tekencontext Gebruiken", + "develop.rendering.hud": "Weergave In De Hud", + "develop.rendering.gui": "GUIs en Schermen", + "develop.rendering.gui.customScreens": "Zelfgemaakte Schermen", + "develop.rendering.gui.customWidgets": "Zelfgemaakte Widgets", + "develop.rendering.particles": "Deeltjes", + "develop.rendering.particles.creatingParticles": "Deeltjes Zelf Maken", + "develop.misc": "Andere Pagina's", + "develop.misc.codecs": "Codecs", + "develop.misc.events": "Gebeurtenissen", + "develop.sounds": "Geluiden", + "develop.sounds.using-sounds": "Geluiden Afspelen", + "develop.sounds.custom": "Geluiden Zelf Maken" +} \ No newline at end of file diff --git a/versions/1.20.4/translated/pl_pl/index.md b/versions/1.20.4/translated/pl_pl/index.md new file mode 100644 index 000000000..269a92487 --- /dev/null +++ b/versions/1.20.4/translated/pl_pl/index.md @@ -0,0 +1,27 @@ +--- +title: Dokumentacja Fabric +description: Oficjalna wyselekcjonowana dokumentacja dla Fabric, łańcucha narzędzi do modowania dla Minecraft. +layout: home +hero: + name: Dokumentacja Fabric + tagline: Oficjalna wyselekcjonowana dokumentacja dla Fabric, łańcucha narzędzi do modowania dla Minecraft. +features: + - title: Developer Guides + icon: 🛠️ + details: Our curated developer guides, written by the community, span a wide range of topics from setting up a development environment to more advanced topics, such as rendering and networking. + link: ./develop/index + linkText: Rozpocznij + - title: Przewodniki dla graczy + icon: 📚 + details: Jesteś graczem, który chce korzystać modów opartych na Fabric? Nasze przewodniki dla graczy mają wszystko, czego potrzebujesz. Te przewodniki pomogą ci w pobieraniu, instalowaniu i rozwiązywaniu problemów z modami Fabric. + link: ./players/index + linkText: Czytaj więcej +--- + +
+ +## Chcesz wnieść swój udział? + +If you want to contribute to the Fabric Documentation, you can find the source code on [GitHub](https://github.com/FabricMC/fabric-docs), and the relevant [contribution guidelines](./contributing). + +
diff --git a/versions/1.20.4/translated/pl_pl/sidebar_translations.json b/versions/1.20.4/translated/pl_pl/sidebar_translations.json new file mode 100644 index 000000000..cf39c40e1 --- /dev/null +++ b/versions/1.20.4/translated/pl_pl/sidebar_translations.json @@ -0,0 +1,40 @@ +{ + "players.title": "Przewodniki dla graczy", + "players.faq": "Często zadawane pytania", + "players.installingJava": "Instalacja Javy", + "players.installingJava.windows": "Windows", + "players.installingJava.macOS": "macOS", + "players.installingJava.linux": "Linux", + "players.installingFabric": "Instalowanie Fabrika", + "players.findingMods": "Znajdowanie modów godnych zaufania", + "players.installingMods": "Instalowanie modów", + "players.troubleshooting": "Rozwiązywanie problemów", + "players.troubleshooting.uploadingLogs": "Przesyłanie logów", + "players.troubleshooting.crashReports": "Raporty błędów", + "players.updatingFabric": "Aktualizowanie Fabrika", + "develop.title": "Przewodniki dla programistów", + "develop.items": "Przedmioty", + "develop.items.potions": "Mikstury", + "develop.entities": "Byty", + "develop.entities.effects": "Efekty", + "develop.entities.damage-types": "Typy Obrażeń", + "develop.commands": "Polecenia", + "develop.commands.basics": "Tworzenie poleceń", + "develop.commands.arguments": "Argumenty", + "develop.commands.suggestions": "Sugestie", + "develop.rendering": "Renderowanie", + "develop.rendering.basicConcepts": "Podstawowe pojęcia renderowania", + "develop.rendering.drawContext": "Używanie kontekstu rysowania", + "develop.rendering.hud": "Renderowanie w HUD", + "develop.rendering.gui": "Graficzne interfejsy użytkownika i ekrany", + "develop.rendering.gui.customScreens": "Niestandardowe ekrany", + "develop.rendering.gui.customWidgets": "Niestandardowe widżety", + "develop.rendering.particles": "Cząsteczki", + "develop.rendering.particles.creatingParticles": "Tworzenie niestandardowych cząsteczek", + "develop.misc": "Różne strony", + "develop.misc.codecs": "Kodeki", + "develop.misc.events": "Zdarzenia", + "develop.sounds": "Dźwięki", + "develop.sounds.using-sounds": "Odtwarzanie WydarzeńDźwięku", + "develop.sounds.custom": "Tworzenie Niestandardowych Dźwięków" +} \ No newline at end of file diff --git a/versions/1.20.4/translated/pt_br/contributing.md b/versions/1.20.4/translated/pt_br/contributing.md new file mode 100644 index 000000000..791e7ca13 --- /dev/null +++ b/versions/1.20.4/translated/pt_br/contributing.md @@ -0,0 +1,181 @@ +# Diretrizes de Contribuição da Documentação do Fabric + +Este site usa [VitePress](https://vitepress.dev/) para gerar HTML estático de vários arquivos do Markdown. Você deve estar familiarizado com as extensões Markdown que o VitePress suporta [aqui](https://vitepress.dev/guide/markdown#features). + +## Sumário + +- [Diretrizes de contribuição da documentação do Fabric](#fabric-documentation-contribution-guidelines) + - [Como Contribuir](#how-to-contribute) + - [Estrutura Da Contribuição](#contributing-framework) + - [Conteúdo Da Contribuição](#contributing-content) + - [Diretrizes A Se Seguir](#style-guidelines) + - [Instruções para Expandir](#guidance-for-expansion) + - [Verificação De Conteúdo](#content-verification) + - [Apuração](#cleanup) + - [Traduzindo a Documentação](#translating-documentation) + +## Como contribuir + +É recomendado que você crie uma nova "branch" no seu "fork do repositório" a cada "pull request" que você faça. Isso faz ser mais fácil de gerenciar múltiplos "pull requests" de uma vez. + +**Se você quiser visualizar suas alterações localmente, basta instalar [Node.js 18+](https://nodejs.org/en/)** + +Antes de executar alguns desses comandos, certifique-se de executar `npm install` para instalar todas as dependências. + +**Executando o ambiente de desenvolvimento.** + +Isso vai permitir que você visualize as alterações localmente em: `localhost:3000` e recarregará automaticamente a página quando você fizer alterações. + +```sh +npm run dev +``` + +**Fazendo o Website.** + +Isto irá compilar todos os arquivos Markdown em arquivos HTML estáticos e colocá-los em: `.vitepress/dist` + +```sh +npm run build +``` + +**Visualizando o Site Feito.** + +Isso iniciará um servidor local na porta 3000 servindo o conteúdo encontrado em `.vitepress/dist` + +```sh +npm run preview +``` + +## Estrutura Da Contribuição + +"Estrutura" refere-se a estrutura interna do website, qualquer "pull request" que modifique essa "estrutura" do site vai ser relatada como: `framework` + +Na verdade, você só deve fazer solicitações e "pull request" de frameworks após consultar a equipe da documentação do [Fabric Discord](https://discord.gg/v6v4pMv) ou após relatar um problema. + +**Observação: modificar os arquivos da barra lateral e da configuração da barra de navegação não conta como uma solicitação de "pull request de framework.** + +## Contribuindo com Conteúdo + +Contribuições com conteúdo são a principal forma de contribuir com a documentação do Fabric. + +Todo o conteúdo deve seguir as nossas diretrizes. + +### Diretrizes A Se Seguir + +Todas as páginas de site de documentação do Fabric devem seguir as diretrizes. Se estiver em duvida de alguma coisa, você pode perguntar no [Fabric Discord](https://discord.gg/v6v4pMv) ou por meio de discussões no GitHub. + +As diretrizes a serem seguidas: + +1. Todas as páginas devem ter a descrição e o título no topo, a mostra. + + ```md + --- + título: Esse é o Título da Pagina + Descrição: Essa é a descrição da página + autores: + - NomeAleatórioDoGitHub + --- + + # ... + ``` + +2. Se você criar ou modificar páginas contendo código, coloque o código em um local apropriado com o mod de referência (localizado na pasta `/reference` do repositório). Em seguida, use o [recurso de "snippet" de código oferecido pelo "VitePress"](https://vitepress.dev/guide/markdown#import-code-snippets) para incorporar o código ou, se precisar de maior controle, você pode usar o [transcluir recurso de `markdown-it-vuepress-code-snippet-enhanced`](https://github.com/fabioaanthony/markdown-it-vuepress-code-snippet-enhanced). + + **Exemplo.** + + ```md + <<< @/reference/latest/src/main/java/com/example/docs/FabricDocsReference.java{15-21 java} + ``` + + Isso incorporará as linhas 15-21 do arquivo `FabricDocsReference.java` no mod de referência. + + O trecho do código ficará assim: + + ```java + @Override + public void onInitialize() { + // Este código é executado quando o Minecraft esta pronto para carregar mods. + // No entanto, algumas coisas (como recursos) ainda podem não ser inicializadas. + // Proceda com atenção. + + LOGGER.info("Olá Mundo Fabric!"); + } + ``` + + **Exemplo de transclusão:** + + ```md + @[code transcludeWith=#test_transclude](@/reference/.../blah.java) + ``` + + Isso incorporará as seções de `blah.java` marcadas com a tag `#test_transclude`. + + Como por exemplo: + + ```java + public final String test = "Tchau Mundo!" + + // #test_transclude + public void test() { + System.out.println("Olá Mundo!"); + } + // #test_transclude + ``` + + Somente o código entre as tags `#test_transclude` será incorporado. + + ```java + public void test() { + System.out.println("Olá Mundo!"); + } + ``` + +3. A documentação original inteira é escrita em Inglês, seguindo as regras da gramática Estadunidense. Embora você possa usar o [LanguageTool](https://languagetool.org/) para verificar sua gramática enquanto digita,mas não se encuque muito com isso. Nossa equipe de documentação revisará e corrigirá a gramática durante a fase de revisão. No entanto, se esforçar para acertar inicialmente pode nos poupar um bom tempo. + +4. Se você estiver criando uma nova seção, você deve criar uma nova barra lateral na pasta `.vitepress/sidebars` e adicioná-la ao arquivo `config.mts`. Se você precisa de assistência com isso, por favor peça no [Discord do Fabric](https://discord.gg/v6v4pMv) no canal `#docs`. + +5. Ao criar uma nova página, você deve adicioná-la à barra lateral relevante na pasta `.vitepress/sidebars`. De novo, se precisar de ajuda, nos chame no Discord do Fabric no canal `#docs`. + +6. Quaisquer imagens devem ser colocadas em um "local adequado" na pasta `/assets`. + +7. ⚠️ **Ao vincular outras páginas, use links relativos.** ⚠️ + + Isso se deve ao sistema de versionamento em vigor, que processará os links para adicionar uma versão de antemão. Se você usar links absolutos, o número da versão não será adicionado ao link. + + Por exemplo, para uma página na pasta `/players`, para vincular à página `installing-fabric` encontrada em `/players/installing-fabric.md`, você teria que fazer o seguinte: + + ```md + [Isto é um link para outra página](./installing-fabric) + ``` + + Você **NÃO** deve fazer o seguinte: + + ```md + [Isto é um link para outra página](/players/installing-fabric) + ``` + +Todas as contribuições de conteúdo passam por três etapas: + +1. Instruções para Expandir (se necessário) +2. Verificação de Conteúdo +3. Revisão (Gramatica, etc.) + +### Instruções para Expandir + +Se a equipe de documentação julgar que você poderia expandir seu "pull request", um membro da equipe adicionará o rótulo `can-expand` ao seu "pull request" com um comentário explicando o que eles pensam que você poderia expandir. Se você concordar com a sugestão, poderá expandir seu "pull request" + +**Não se sinta pressionado em expandir seu "pull request".** Se não quiser expandir seu "pull request", você pode simplesmente solicitar que o rótulo `can-expand` seja removido. + +Se você não deseja expandir seu "Pull Request", mas deseja que outra pessoa a expanda posteriormente, é melhor criar um "Issue" na [página de "issues"](https://github.com/FabricMC/fabric-docs/issues) e explique o que você acha que pode ser expandido. + +### Verificação de Conteúdo + +Todas as "Pull Requests" que adicionam conteúdo passam por verificação de conteúdo, esta é a etapa mais importante, pois garante que o conteúdo seja preciso e siga as diretrizes da documentação do Fabric. + +### Verificação + +Esta etapa é onde a equipe de documentação corrigirá quaisquer problemas gramaticais e fará quaisquer outras alterações que julgar necessárias antes de mesclar o "Pull Request"! + +## Traduzindo a Documentação + +Se você desejar traduzir a documentação para a sua linguagem, você pode fazer isso na [pagina do Crowdin do Fabric](https://crowdin.com/project/fabricmc). diff --git a/versions/1.20.4/translated/pt_br/develop/entities/damage-types.md b/versions/1.20.4/translated/pt_br/develop/entities/damage-types.md new file mode 100644 index 000000000..b427b17d6 --- /dev/null +++ b/versions/1.20.4/translated/pt_br/develop/entities/damage-types.md @@ -0,0 +1,96 @@ +--- +title: Tipos de Dano +description: Aprenda a adicionar tipos de dano personalizados. +authors: + - dicedpixels + - hiisuuii + - mattidragon +--- + +# Tipos de Dano + +Os tipos de dano definem os tipos de dano que as entidades podem sofrer. A partir do Minecraft 1.19.4, a criação de novos tipos de dano passou a ser baseada em dados, o que significa que eles são criados usando arquivos JSON. + +## Criando um Tipo de Dano + +Vamos criar um tipo de dano customizado chamado _Tater_. Começaremos criando um arquivo JSON para seu dano. Este arquivo será colocado na pasta `data` do seu mod, em uma subpasta chamada `damage_type`. + +```:no-line-numbers +resources/data/fabric-docs-reference/damage_type/tater.json +``` + +Ele terá a seguinte estrutura: + +@[code lang=json](@/reference/latest/src/main/generated/data/fabric-docs-reference/damage_type/tater.json) + +Esse tipo de dano causa aumento de 0.1 na [exaustão de fome](https://minecraft.wiki/w/Hunger#Exhaustion_level_increase) toda vez que um jogador sofrer dano, quando o dano for causado por uma fonte viva que não seja um jogador (ex: um bloco). Além disso, a quantidade de dano causado escalonará com a dificuldade do mundo. + +::: info + +Consulte a [Wiki do Minecraft](https://pt.minecraft.wiki/w/Tipo_de_dano) para todas as chaves e valores possíveis. + +::: + +### Acessando Tipos de Dano Através de Código + +Quando precisarmos acessar nosso tipo de dano através de código, usaremos a sua `RegistryKey` (Chave de Registro) para construir uma instância de `DamageSource` (Fonte de Dano). + +A `RegistryKey` pode ser obtida da seguinte maneira: + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/damage/FabricDocsReferenceDamageTypes.java) + +### Usando Tipos de Dano + +Para demonstrar o uso de tipos de dano personalizados, usaremos um bloco personalizado chamado _Tater Block_. Façamos com que quando uma entidade viva pisar em um _Tater Block_, ele causará dano de _Tater_. + +Você pode substituir `onSteppedOn` para infligir este dano. + +Começaremos criando uma `DamageSource` do nosso tipo de dano customizado. + +@[code lang=java transclude={21-24}](@/reference/latest/src/main/java/com/example/docs/damage/TaterBlock.java) + +Então, chamamos `entity.damage()` com o nosso `DamageSource`e uma quantidade. + +@[code lang=java transclude={25-25}](@/reference/latest/src/main/java/com/example/docs/damage/TaterBlock.java) + +A implementação completa do bloco: + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/damage/TaterBlock.java) + +Agora, quando uma entidade viva pisar no nosso bloco, ela sofrerá 5 de dano (2,5 corações) usando nosso tipo de dano personalizado. + +### Mensagem de Morte Personalizada + +Você pode definir uma mensagem de morte para o tipo de dano no formato de `death.attack.` no arquivo `en_us.json` do mod. + +@[code lang=json transclude={4-4}](@/reference/latest/src/main/resources/assets/fabric-docs-reference/lang/en_us.json) + +Ao morrer devido ao nosso tipo de dano, você verá a seguinte mensagem: + +![Efeito no inventário do jogador](/assets/develop/tater-damage-death.png) + +### Tags de Tipo de Dano + +Alguns danos podem ignorar a armadura, efeitos de estado, e similares. Tags (etiquetas) são usadas para controlar tais propriedades dos tipos de dano. + +As tags de tipo de dano existentes se encontram em `data/minecraft/tags/damage_type`. + +::: info + +Consulte a [Wiki do Minecraft](https://pt.minecraft.wiki/w/Tipo_de_dano) para uma lista compreensiva de tags de tipos de dano. + +::: + +Vamos adicionar nosso dano Tater para a tag `bypasses_armor` (ignora armadura). + +Para adicionar nosso dano a uma dessas tags, criamos um arquivo JSON sob o namespace de `minecraft`. + +```:no-line-numbers +data/minecraft/tags/damage_type/bypasses_armor.json +``` + +Com o seguinte conteúdo: + +@[code lang=json](@/reference/latest/src/main/generated/data/minecraft/tags/damage_type/bypasses_armor.json) + +Certifique-se de que sua tag não substitua a tag existente definindo a chave `replace` como `false`. diff --git a/versions/1.20.4/translated/pt_br/develop/entities/effects.md b/versions/1.20.4/translated/pt_br/develop/entities/effects.md new file mode 100644 index 000000000..f835b06ac --- /dev/null +++ b/versions/1.20.4/translated/pt_br/develop/entities/effects.md @@ -0,0 +1,70 @@ +--- +title: Efeitos de Estado +description: Aprenda a adicionar efeitos de estado personalizados. +authors: + - dicedpixels + - YanisBft + - FireBlast + - Friendly-Banana + - SattesKrokodil +authors-nogithub: + - siglong + - tao0lu +--- + +# Efeitos de Estado + +Efeitos de estado, conhecidos como efeitos, são condições que podem afetar uma entidade. Eles podem ser de natureza positiva, negativa ou neutra. O jogo base aplica esses efeitos de vários modos, como comidas, poções, etc. + +O comando `/effect` pode ser usado para aplicar efeitos numa entidade. + +## Efeitos Personalizados + +Neste tutorial adicionaremos um novo efeito personalizado chamado _Tater_, que lhe dará um ponto de experiência a cada tick do jogo. + +### Estenda `StatusEffect` + +Vamos criar uma classe de efeito personalizado estendendo `StatusEffect`, sendo uma classe base para todos os efeitos. + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/effect/TaterEffect.java) + +### Registrando seu Efeito Personalizado + +Similar a registração de blocos e itens, usamos `Registry.register` para registrar nosso efeito ao registro de `STATUS_EFFECT`. Isso pode ser feito no nosso inicializador. + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/effect/FabricDocsReferenceEffects.java) + +### Traduções e Texturas + +Você pode atribuir um nome ao seu efeito e providenciar uma textura de ícone que aparecerá na tela de inventário do jogador. + +#### Textura + +O ícone de textura é um PNG de 18x18. Coloque seu ícone personalizado em: + +```:no-line-numbers +resources/assets/fabric-docs-reference/textures/mob_effect/tater.png +``` + +![Efeito no inventário do jogador](/assets/develop/tater-effect.png) + +#### Traduções + +Assim como outras traduções, você pode adicionar uma entrada com o formato de ID `"effect..": "Value"` ao arquivo de idioma. + +::: code-group + +```json[assets/fabric-docs-reference/lang/en_us.json] +{ + "effect.fabric-docs-reference.tater": "Tater" +} +``` + +### Testando + +Uso o comando `/effect give @p fabric-docs-reference:tater` para dar ao jogador nosso efeito Tater. +Use `/effect clear @p fabric-docs-reference:tater` para remover o efeito. + +::: info +Para criar uma poção que utiliza este efeito, consulte o [guia de Poções](../items/potions). +::: diff --git a/versions/1.20.4/translated/pt_br/develop/index.md b/versions/1.20.4/translated/pt_br/develop/index.md new file mode 100644 index 000000000..d512f1ffb --- /dev/null +++ b/versions/1.20.4/translated/pt_br/develop/index.md @@ -0,0 +1,12 @@ +--- +title: Guias do desenvolvedor +description: Nossos guias de desenvolvedor, escritos pela comunidade, abrangem uma variedade de tópicos desde a configuração de um ambiente de desenvolvimento até tópicos mais avançados, como renderização e networking. +--- + +# Guias do desenvolvedor + +Nossos guias de desenvolvedor, escritos pela comunidade, abrangem uma variedade de tópicos desde a configuração de um ambiente de desenvolvimento até tópicos mais avançados, como renderização e networking. + +Consulte a barra lateral para uma lista de todos os guias de desenvolvedor disponíveis. Se estiver procurando algo específico, você pode usar a barra de pesquisa no topo da página para achar o que precisa. + +Se desejar contribuir à Documentação do Fabric, você pode encontrar o código-fonte no [GitHub](https://github.com/FabricMC/fabric-docs), leia também as [diretrizes de contribuição](../contributing). diff --git a/translated/pt_br/develop/items/potions.md b/versions/1.20.4/translated/pt_br/develop/items/potions.md similarity index 100% rename from translated/pt_br/develop/items/potions.md rename to versions/1.20.4/translated/pt_br/develop/items/potions.md diff --git a/versions/1.20.4/translated/pt_br/index.md b/versions/1.20.4/translated/pt_br/index.md new file mode 100644 index 000000000..402aa1d69 --- /dev/null +++ b/versions/1.20.4/translated/pt_br/index.md @@ -0,0 +1,27 @@ +--- +title: Documentação do Fabric +description: A documentação oficial para o Fabric, um conjunto de ferramentas para mods de Minecraft. +layout: home +hero: + name: Documentação do Fabric + tagline: A documentação oficial para o Fabric, um conjunto de ferramentas para mods de Minecraft. +features: + - title: Guias para desenvolvedores + icon: 🛠️ + details: Nossos guias de desenvolvedor, escritos pela comunidade, abrangem uma variedade de tópicos desde a configuração de um ambiente de desenvolvimento até tópicos mais avançados, como renderização e networking. + link: ./develop/index + linkText: Guia de Introdução + - title: Guias do Jogador + icon: 📚 + details: Você é um jogador que deseja usar mods desenvolvidos para o Fabric? Nossos guias de jogador irão te ajudar. Esses guias te ajudarão a baixar, instalar e solucionar problemas com mods do Fabric. + link: ./players/index + linkText: Leia Mais +--- + +
+ +## Deseja ajudar? + +If you want to contribute to the Fabric Documentation, you can find the source code on [GitHub](https://github.com/FabricMC/fabric-docs), and the relevant [contribution guidelines](./contributing). + +
diff --git a/versions/1.20.4/translated/pt_br/navbar_translations.json b/versions/1.20.4/translated/pt_br/navbar_translations.json new file mode 100644 index 000000000..839f29951 --- /dev/null +++ b/versions/1.20.4/translated/pt_br/navbar_translations.json @@ -0,0 +1,8 @@ +{ + "title": "Documentação do Fabric", + "home": "Início", + "download": "Download", + "contribute": "Contribua", + "contribute.api": "API do Fabric", + "version_switcher": "Mudar Versão" +} \ No newline at end of file diff --git a/versions/1.20.4/translated/pt_br/players/faq.md b/versions/1.20.4/translated/pt_br/players/faq.md new file mode 100644 index 000000000..cc99b2640 --- /dev/null +++ b/versions/1.20.4/translated/pt_br/players/faq.md @@ -0,0 +1,31 @@ +--- +title: Perguntas frequentes dos jogadores +description: Dúvidas mais frequentes dos jogadores e administradores de servidor sobre o Fabric. +--- + +# Perguntas Frequentes (FAQ) + +Há muitas perguntas feitas com frequência, então compilamos uma lista delas aqui. + +## Perguntas Gerais + +### Quais versões do Minecraft o Fabric é compatível? + +Oficialmente, o Fabric é compatível com todas as versões do Minecraft começando da snapshot `18w43b` em diante, e versões da `1.14` em diante. + +### Onde eu posso baixar mods publicados do Fabric? + +:::info +Você deve sempre verificar se os mods são de fontes confiáveis. Visite o guia [Encontrando Mods Confiáveis](./finding-mods) para mais informações. +::: + +A maioria dos autores publicam seus mods no [Modrinth](https://modrinth.com/mods?g=categories:%27fabric%27) e no [CurseForge](https://www.curseforge.com/minecraft/search?class=mc-mods&gameVersionTypeId=4), no entando, alguns preferem publicá-los em seus sites pessoais, ou em outras plataformas, como um repositório GitHub. + +### Onde eu posso achar modpacks para Fabric pré-feitos? + +Você pode achar modpacks para Fabric pré-feitos em várias plataformas, como: + +- [Modrinth](https://modrinth.com/modpacks?g=categories:%27fabric%27) +- [CurseForge](https://www.curseforge.com/minecraft/search?class=modpacks&gameVersionTypeId=4) +- [Feed The Beast](https://www.feed-the-beast.com/ftb-app) +- [Technic](https://www.technicpack.net/modpacks) diff --git a/versions/1.20.4/translated/pt_br/players/finding-mods.md b/versions/1.20.4/translated/pt_br/players/finding-mods.md new file mode 100644 index 000000000..2f9411046 --- /dev/null +++ b/versions/1.20.4/translated/pt_br/players/finding-mods.md @@ -0,0 +1,34 @@ +--- +title: Encontrando Mods Confiáveis +description: Um guia para achar mods para Fabric usando fontes confiáveis. +authors: + - IMB11 +--- + +# Encontrando Mods Confiáveis + +Primeiramente, a confiança é subjetiva, e você sempre deve usar seu próprio julgamento ao baixar mods. No entanto, há algumas coisas que você pode fazer para te ajudar a encontrar mods confiáveis. + +## 1. Usar uma Fonte que Seja Reconhecidamente Confiável + +A maioria dos autores publicam seus mods no [Modrinth](https://modrinth.com/mods?g=categories:%27fabric%27) e no [CurseForge](https://www.curseforge.com/minecraft/search?class=mc-mods&gameVersionTypeId=4). + +Estes sites verificam se os mods são o que dizem ser e se não contêm código malicioso. Você também pode denunciar mods maliciosos nestes sites, e eles tomarão providência quanto antes. + +## 2. Verificar com Outros! + +Se você estiver baixando um mod por uma fonte não confiável, cheque com outros para ver se já baixaram o mod pelo mesmo local antes e se não tiveram algum problema com ele. + +Em caso de dúvidas, sinta-se à vontade para perguntar no [Discord do Fabric](https://discord.gg/v6v4pMv) no canal `#player-support`. + +## 3. Evitar Sites Comuns de Malware! + +:::info +Sites de malware podem não ser óbvios para todos. Se estiver incerto, peça a opinião de outros ou evite este site por completo e use apenas fontes confiáveis, como Modrinth e CurseForge. +::: + +Há muitos sites que dizem ter mods para Minecraft, mas, na verdade, são apenas malware. Você deve evitar estes sites a todo custo. + +Você pode usar programas de antivírus e sites como o [Windows Defender](https://www.microsoft.com/en-us/windows/comprehensive-security) ou o [VirusTotal](https://www.virustotal.com/) para verificar os mods baixados. No entanto, não confie apenas nestes métodos, pois às vezes eles também podem estar incorretos. + +Novamente, em caso de dúvidas, sinta-se à vontade para pedir opiniões no [Discord do Fabric](https://discord.gg/v6v4pMv) no canal `#player-support`. diff --git a/versions/1.20.4/translated/pt_br/players/index.md b/versions/1.20.4/translated/pt_br/players/index.md new file mode 100644 index 000000000..38aace130 --- /dev/null +++ b/versions/1.20.4/translated/pt_br/players/index.md @@ -0,0 +1,12 @@ +--- +title: Guias para jogadores +description: Uma coleção de guias para jogadores e administradores de servidores ao instalar e usar o Fabric. +--- + +# Guias para jogadores + +Esta seção da Documentação do Fabric é dedicada à jogadores e administradores de servidores que querem aprender a como instalar, usar, e diagnosticar problemas com Fabric. + +Você pode consultar a barra lateral para uma lista de todos os guias disponíveis. + +Se você encontrar qualquer problema, por favor reporte-os [no GitHub](https://github.com/FabricMC/fabric-docs) ou peça ajuda no [Discord do Fabric](https://discord.gg/v6v4pMv) nos canais `#player-support` ou `#server-admin-support`. diff --git a/versions/1.20.4/translated/pt_br/players/installing-fabric.md b/versions/1.20.4/translated/pt_br/players/installing-fabric.md new file mode 100644 index 000000000..e70b6c746 --- /dev/null +++ b/versions/1.20.4/translated/pt_br/players/installing-fabric.md @@ -0,0 +1,55 @@ +--- +title: Instalando Fabric +description: Um guia passo a passo de como instalar Fabric. +authors: + - IMB11 +--- + +# Instalando Fabric + +Este guia o orientará na instalação do Fabric para o Launcher oficial do Minecraft. + +Para launchers de terceiros, você deve consultar suas devidas documentações. + +## 1. Baixar o instalador do Fabric + +Você pode baixar o Instalador do Fabric pelo [Site do Fabric](https://fabricmc.net/use/). + +Se você usa Windows, baixe a versão `.exe` (`Download For Windows`), pois ela não necessita da presença do Java no seu sistema. Ela usa o Java que acompanha o launcher oficial. + +Para macOS e Linux, você deve baixar a versão `.jar`. A instalação do Java antes desse passo pode ser necessária. + +## 2. Executar o instalador do Fabric + +:::warning +Feche o Minecraft e Minecraft Launcher antes da instalação. +::: + +:::details Informação para usuários do macOS + +No macOS, talvez seja necessário clicar com o botão direito no arquivo `.jar` em sua pasta de downloads e clicar em `Open` para executá-lo. + +![Menu de contexto do macOS no Instalador do Fabric](/assets/players/installing-fabric/macos-downloads.png) + +Quando perguntado "Tem certeza de que deseja abrir isso?", aperte em `Abrir` novamente. +::: + +Assim que você abrir o instalador, deverá ver uma tela como essa: + +![Instalador do Fabric com "Instalar" destacado](/assets/players/installing-fabric/installer-screen.png) + +Para instalar o Fabric, apenas escolha a versão do seu jogo e clique em `Instalar`. + +**Certifique-se de que `Criar Perfil` está marcado.** + +## 3. Tudo Pronto! + +Assim que o instalador terminar, você pode abrir o Minecraft Launcher, selecionar o perfil Fabric através do botão no canto inferior esquerdo e clicar em Jogar! + +![Minecraft Launcher com o perfil Fabric selecionado](/assets/players/installing-fabric/launcher-screen.png) + +## Próximos passos + +Agora que você instalou o Fabric, você pode adicionar mods ao seu jogo! Dê uma olhada no guia [Encontrando Mods Confiáveis](./finding-mods) para mais informações. + +Se você encontrar algum problema, sinta-se à vontade para pedir ajuda no [Discord do Fabric](https://discord.gg/v6v4pMv) no canal `#player-support`. diff --git a/versions/1.20.4/translated/pt_br/players/installing-java/linux.md b/versions/1.20.4/translated/pt_br/players/installing-java/linux.md new file mode 100644 index 000000000..e9dcb2a85 --- /dev/null +++ b/versions/1.20.4/translated/pt_br/players/installing-java/linux.md @@ -0,0 +1,91 @@ +--- +title: Instalando Java no Linux +description: Um guia passo a passo de como instalar Java no Linux. +authors: + - IMB11 +--- + +# Instalando Java no Linux + +Este guia o orientará na instalação do Java 17 no Linux. + +## 1. Verificar Se o Java Já Está Instalado + +Abra um terminal, digite `java -version`, e pressione Enter. + +![Terminal com "java -version" digitado](/assets/players/installing-java/linux-java-version.png) + +:::warning +Para usar a maioria das versões modernas do Minecraft, você precisará ter pelo menos o Java 17 instalado. Se este comando exibir uma versão inferior a 17, será necessário atualizar sua instalação do Java atual. +::: + +## 2. Baixando e instalando Java 17 + +Recomendamos usar o OpenJDK 17, que está disponível para a maioria das distribuições Linux. + +### Arch Linux + +:::info +Para mais informações na instalação do Java no Arch Linux, veja a [Wiki do Arch Linux](https://wiki.archlinux.org/title/Java_(Portugu%C3%AAs)). +::: + +Você pode instalar a JRE mais recente através de repositórios oficiais: + +```sh +sudo pacman -S jre-openjdk +``` + +Se estiver rodando um servidor sem a necessidade de uma interface gráfica, você pode instalar a versão headless: + +```sh +sudo pacman -S jre-openjdk-headless +``` + +Se você planeja desenvolver mods, precisará do JDK: + +```sh +sudo pacman -S jdk-openjdk +``` + +### Debian/Ubuntu + +Você pode instalar o Java 17 usando `apt` com os seguintes comandos: + +```sh +sudo apt update +sudo apt install openjdk-17-jdk +``` + +### Fedora + +Você pode instalar o Java 17 usando `dnf` com os seguintes comandos: + +```sh +sudo dnf install java-17-openjdk +``` + +Se você não precisa de uma interface gráfica, você pode instalar a versão headless: + +```sh +sudo dnf install java-17-openjdk-headless +``` + +Se você planeja desenvolver mods, precisará do JDK: + +```sh +sudo dnf install java-17-openjdk-devel +``` + +### Outras distribuições Linux + +Se sua distribuição não foi listada acima, você pode baixar a JRE mais recente pelo [Adoptium](https://adoptium.net/temurin/) + +Você deve consultar um guia próprio de sua distribuição se planeja desenvolver mods. + +## 3. Verificar se o Java 17 está instalado + +Assim que a instalação terminar, você pode verificar se o Java 17 está instalado abrindo o terminal novamente e digitando `java -version`. + +Se o comando for executado com êxito, você verá algo como mostrado anteriormente onde a versão do Java é exibida: + +![Terminal com "java -version" digitado](/assets/players/installing-java/linux-java-version.png) diff --git a/versions/1.20.4/translated/pt_br/players/installing-java/windows.md b/versions/1.20.4/translated/pt_br/players/installing-java/windows.md new file mode 100644 index 000000000..3f337622d --- /dev/null +++ b/versions/1.20.4/translated/pt_br/players/installing-java/windows.md @@ -0,0 +1,65 @@ +--- +title: Instalando Java no Windows +description: Um guia passo a passo de como instalar Java no Windows. +authors: + - IMB11 +--- + +# Instalando Java no Windows + +Este guia o orientará na instalação do Java 17 no Windows. + +O Launcher do Minecraft vem com sua própria instalação do Java, portanto esta seção só é relevante se você quiser usar o instalador baseado em `.jar` do Fabric ou se quiser usar o `.jar` do Servidor do Minecraft. + +## 1. Verificar Se o Java Já Está Instalado + +Para verificar se o Java já está instalado, você deve primeiro abrir o prompt de comando. + +Você pode fazer isso apertando Win + R e digitando `cmd.exe` na janela aberta. + +![Caixa de diálogo Executar do Windows com "cmd.exe" na barra de execução](/assets/players/installing-java/windows-run-dialog.png) + +Após abrir o prompt de comando, digite `java -version` e pressione Enter. + +Se o comando for executado com êxito, você verá algo parecido com isto. Se o comando falhar, prossiga para o próximo passo. + +![Prompt de comando com "java -version" digitado](/assets/players/installing-java/windows-java-version.png) + +:::warning +Para usar a maioria das versões modernas do Minecraft, você precisará ter pelo menos o Java 17 instalado. Se este comando exibir uma versão inferior a 17, será necessário atualizar sua instalação do Java atual. +::: + +## 2. Baixar o Instalador do Java 17 + +Para instalar o Java 17, você precisará baixar o instalador pelo [Adoptium](https://adoptium.net/en-GB/temurin/releases/?os=windows&package=jdk&version=17). + +Você deverá baixar a versão `Windows Installer (.msi)`: + +![Página de download do Adoptium com Windows Installer (.msi) destacado](/assets/players/installing-java/windows-download-java.png) + +Você deverá escolher 'x86' se tiver um sistema operacional 32-bit, ou 'x64' se tiver um sistema operacional 64-bit. + +A maioria dos computadores modernos terão um sistema operacional 64-bit. Em caso de dúvida, tente usar o download 64-bit. + +## 3. Executar o Instalador! + +Siga os passos do instalador para instalar o Java 17. Ao chegar nesta página, você deve definir os seguintes recursos como "Todo o recurso será instalado no disco rígido local": + +- `Set JAVA_HOME environment variable` - Isso será adicionado ou seu PATH. +- `JavaSoft (Oracle) registry keys` + +![Instalador do Java 17 com "Set JAVA_HOME variable" e "JavaSoft (Oracle) registry keys" destacados](/assets/players/installing-java/windows-wizard-screenshot.png) + +Assim que fizer isto, clique em 'Next' e continue com a instalação. + +## 4. Verificar se o Java 17 está instalado + +Assim que a instalação terminar, você pode verificar se o Java 17 está instalado abrindo o prompt de comando novamente e digitando `java -version`. + +Se o comando for executado com êxito, você verá algo como mostrado anteriormente onde a versão do Java é exibida: + +![Prompt de comando com "java -version" digitado](/assets/players/installing-java/windows-java-version.png) + +--- + +Se você encontrar algum problema, sinta-se à vontade para pedir ajuda no [Discord do Fabric](https://discord.gg/v6v4pMv) no canal `#player-support`. diff --git a/versions/1.20.4/translated/pt_br/players/installing-mods.md b/versions/1.20.4/translated/pt_br/players/installing-mods.md new file mode 100644 index 000000000..38c8ac5d2 --- /dev/null +++ b/versions/1.20.4/translated/pt_br/players/installing-mods.md @@ -0,0 +1,67 @@ +--- +title: Instalando Mods +description: Um guia passo a passo de como instalar mods para Fabric. +authors: + - IMB11 +--- + +# Instalando Mods + +Este guia o orientará na instalação de mods para Fabric usando o Minecraft Launcher. + +Para launchers de terceiros, você deve consultar suas devidas documentações. + +## 1. Baixar o Mod + +:::warning +Você deve baixar mods apenas de fontes que confia. Para mais informações sobre achar mods, veja o guia [Encontrando Mods Confiáveis](./finding-mods). +::: + +A maioria dos mods necessitam do Fabric API, que pode ser baixado através do [Modrinth](https://modrinth.com/mod/fabric-api) ou [CurseForge](https://curseforge.com/minecraft/mc-mods/fabric-api). + +Ao baixar mods, certifique-se de que: + +- Eles funcionam na versão do Minecraft que você quer jogar. Um mod feito para a versão 1.20, por exemplo, pode não funcionar na versão 1.20.2. +- Eles são para o Fabric, não outro mod loader (carregador de mods). +- Eles são feitos para a edição certa do Minecraft (Edição Java). + +## 2. Mover o Mod para a Pasta `mods` + +A pasta de mods pode ser encontrada nos seguintes locais para cada sistema operacional. + +Você pode colar esses endereços na barra de endereços do seu navegador de arquivos para rapidamente achar a pasta. + +::: code-group + +```:no-line-numbers [Windows] +%appdata%\.minecraft\mods +``` + +```:no-line-numbers [macOS] +~/Library/Application Support/minecraft/mods +``` + +```:no-line-numbers [Linux] +~/.minecraft/mods +``` + +::: + +Encontrada a pasta `mods`, você pode mover os arquivos `.jar` dos mods para dentro dela. + +![Mods instalados na pasta de mods](/assets/players/installing-mods.png) + +## 3. Tudo Pronto! + +Assim que movidos os mods para a pasta `mods`, você pode abrir o Minecraft Launcher, selecionar o perfil Fabric através do botão no canto inferior esquerdo e clicar em jogar! + +![Minecraft Launcher com o perfil Fabric selecionado](/assets/players/installing-fabric/launcher-screen.png) + +## Solução de Problemas + +Se você encontrar algum problema, sinta-se à vontade para pedir ajuda no [Discord do Fabric](https://discord.gg/v6v4pMv) no canal `#player-support`. + +Você também pode tentar diagnosticar o problema por si mesmo através das páginas de solução de problemas: + +- [Relatórios de Crash](./troubleshooting/crash-reports) +- [Upload de Logs](./troubleshooting/uploading-logs) diff --git a/versions/1.20.4/translated/pt_br/players/updating-fabric.md b/versions/1.20.4/translated/pt_br/players/updating-fabric.md new file mode 100644 index 000000000..60d446981 --- /dev/null +++ b/versions/1.20.4/translated/pt_br/players/updating-fabric.md @@ -0,0 +1,41 @@ +--- +title: Atualizando o Fabric +description: Um guia passo a passo de como atualizar o Fabric. +authors: + - IMB11 + - modmuss50 +--- + +# Atualizando o Fabric + +Este guia o orientará na atualização do Fabric para o Minecraft Launcher. + +Para launchers de terceiros, você deve consultar suas devidas documentações. + +Atualizar o Fabric é um processo similar ao de instalação, portanto partes deste guia serão iguais ao guia de [Instalação do Fabric](./installing-fabric). + +## Por que eu deveria atualizar o Fabric Loader? + +Mods novos podem requerir a versão mais nova do Fabric Loader para funcionar, então é importante mantê-lo atualizado para se poder usar os mods mais recentes. + + + + + +Para atualizar o Fabric, simplesmente certifique-se de que a versão do jogo e a versão do Loader estejam corretas, então clique em `Instalar`. + +**Desmarque 'Criar Perfil' ao rodar o instalador, caso contrário será criado um novo perfil, que nesse caso não é necessário.** + +## 3. Abrir o Perfil no Minecraft Launcher + +Terminada a instalação, abra o Minecraft Launcher e vá para a aba de `Instalações`. Vá para seu perfil Fabric e abra a tela de edição. + +Substitua a versão com a nova versão do Fabric Loader que você acabou de instalar, e aperte `Salvar`. + +![Atualizando a versão do Fabric Loader no Minecraft Launcher](/assets/players/updating-fabric.png) + +## 4. Tudo Pronto! + +Terminado os passsos acima, você pode voltar à aba `Jogar`, selecionar o perfil Fabric através do botão no canto inferior esquerdo e clicar em Jogar! + +Se você encontrar algum problema, sinta-se à vontade para pedir ajuda no [Discord do Fabric](https://discord.gg/v6v4pMv) no canal `#player-support`. diff --git a/versions/1.20.4/translated/pt_br/sidebar_translations.json b/versions/1.20.4/translated/pt_br/sidebar_translations.json new file mode 100644 index 000000000..d9a82e4c7 --- /dev/null +++ b/versions/1.20.4/translated/pt_br/sidebar_translations.json @@ -0,0 +1,47 @@ +{ + "players.title": "Guias do Jogador", + "players.faq": "Perguntas Frequentes (FAQ)", + "players.installingJava": "Instalando o Java", + "players.installingJava.windows": "Windows", + "players.installingJava.macOS": "macOS", + "players.installingJava.linux": "Linux", + "players.installingFabric": "Instalando Fabric", + "players.findingMods": "Encontrando Mods Confiáveis", + "players.installingMods": "Instalando mods", + "players.troubleshooting": "Resolução de Problemas", + "players.troubleshooting.uploadingLogs": "Enviando Seus Logs", + "players.troubleshooting.crashReports": "Relatórios de Erros", + "players.updatingFabric": "Atualizando o Fabric", + "develop.title": "Guias do Desenvolvedor", + "develop.gettingStarted": "Primeiros Passos", + "develop.gettingStarted.introduction": "Introdução ao Fabric e Modding", + "develop.gettingStarted.devEnvSetup": "Configurar um Ambiente de Desenvolvimento", + "develop.gettingStarted.creatingProject": "Criando um Projeto", + "develop.gettingStarted.projectStructure": "Estrutura de Projeto", + "develop.gettingStarted.launchGame": "Iniciando o Jogo", + "develop.items": "Itens", + "develop.items.potions": "Poções", + "develop.entities": "Entidades", + "develop.entities.effects": "Efeitos de Estado", + "develop.entities.damage-types": "Tipos de Dano", + "develop.commands": "Comandos", + "develop.commands.basics": "Criando comandos", + "develop.commands.arguments": "Argumentos", + "develop.commands.suggestions": "Sugestões", + "develop.rendering": "Renderização", + "develop.rendering.basicConcepts": "Conceitos básicos de renderização", + "develop.rendering.drawContext": "Usando o \"Drawing Context\"", + "develop.rendering.hud": "Renderizando a Interface", + "develop.rendering.gui": "GUIs e Telas", + "develop.rendering.gui.customScreens": "Telas Personalizadas", + "develop.rendering.gui.customWidgets": "Widgets Personalizados", + "develop.rendering.particles": "Partículas", + "develop.rendering.particles.creatingParticles": "Criando partículas", + "develop.misc": "Paginas Diversas", + "develop.misc.codecs": "Codecs", + "develop.misc.events": "Eventos", + "develop.sounds": "Sons", + "develop.sounds.using-sounds": "Tocando \"SoundEvents\"", + "develop.sounds.custom": "Criando Sons Personalizados", + "github.edit": "Editar esta página no GitHub" +} \ No newline at end of file diff --git a/versions/1.20.4/translated/ru_ru/contributing.md b/versions/1.20.4/translated/ru_ru/contributing.md new file mode 100644 index 000000000..e22cf705c --- /dev/null +++ b/versions/1.20.4/translated/ru_ru/contributing.md @@ -0,0 +1,181 @@ +# Руководство по внесению вклада в документацию Fabric + +Этот сайт использует [VitePress](https://vitepress.dev/) для генерации статического HTML-кода из различных Markdown-файлов. Вы можете ознакомиться с Markdown-расширениями для VitePress [здесь](https://vitepress.dev/guide/markdown#features). + +## Содержание + +- [Руководство по внесению вклада в документацию Fabric](#fabric-documentation-contribution-guidelines) + - [Как внести свой вклад](#how-to-contribute) + - [Вклад в фреймворк](#contributing-framework) + - [Вклад в содержимое](#contributing-content) + - [Стандарты оформления](#style-guidelines) + - [Справка по дополнениям](#guidance-for-expansion) + - [Проверка содержимого](#content-verification) + - [Полировка](#cleanup) + - [Перевод документации](#translating-documentation) + +## Как внести свой вклад + +Создавайте новые ветки в вашем форке на каждый pull request, что делаете. Это упрощает одновременное управление несколькими pull requests. + +**Если вы хотите предварительно локально просматривать свои изменения, вам нужно будет установить [Node.js версии 18 или выше](https://nodejs.org/en/)**. + +Прежде чем выполнять любые из следующих команд, убедитесь, что выполнили команду `npm install` для установки всех зависимостей. + +**Запуск сервера для разработки:** + +Это позволит вам предварительно просматривать ваши изменения локально по адресу `localhost:3000` и автоматически перезагрузит страницу при внесении изменений. + +```sh +npm run dev +``` + +**Компиляция веб-сайта:** + +Это преобразует все файлы Markdown в статические HTML-файлы и разместит их в папке `.vitepress/dist` + +```sh +npm run build +``` + +**Предварительный просмотр собранного веб-сайта:** + +Это запустит локальный сервер на порту 3000, отображающий содержимое, найденное в `.vitepress/dist` + +```sh +npm run preview +``` + +## Вклад в развитие фреймворка + +Под фреймворком понимается внутренняя структура веб-сайта; любые pull requests, изменяющие фреймворк сайта, должны быть помечены меткой `framework`. + +К вашему сведению, вы должны делать pull requests, касающиеся фреймворка, только после консультации с командой документации на [Discord-сервере Fabric](https://discord.gg/v6v4pMv) или через issue. + +**Примечание: Изменение файлов боковой панели и конфигурации панели навигации не считается pull request, касающимся фреймворка.** + +## Вклад в содержимое + +Вклад в содержимое является основным способом внести свой вклад в документацию Fabric. + +Все материалы должны соответствовать нашим стандартам оформления. + +### Стандарты оформления + +Все страницы веб-сайта документации Fabric должны следовать стандартам оформления. Если вы насчёт чего-то не уверены, можете задать свой вопрос в [Discord-сервере Fabric](https://discord.gg/v6v4pMv) или через GitHub Discussions. + +Наши стандарты оформления включают следующее: + +1. Все страницы должны иметь заголовок и описание. + + ```md + --- + title: Это заголовок страницы + description: Это описание страницы + authors: + - ТутЧьё-тоИмяПользователяСGitHub + --- + + # ... + ``` + +2. Если вы создаёте или изменяете страницы, содержащие код, разместите этот код в каком-нибудь месте мода с примерами (он находится в папке `/reference` репозитория). Затем используйте [функцию вставки кода от VitePress](https://vitepress.dev/guide/markdown#import-code-snippets), чтобы встроить код, или, если вам требуется более широкий контроль, вы можете использовать функцию [transclude из `markdown-it-vuepress-code-snippet-enhanced`](https://github.com/fabioaanthony/markdown-it-vuepress-code-snippet-enhanced). + + **Пример:** + + ```md + <<< @/reference/latest/src/main/java/com/example/docs/FabricDocsReference.java{15-21 java} + ``` + + Это выведет все линии с 15 по 21 из файла `FabricDocsReference.java` из мода с примерами. + + Фрагмент кода будет выглядеть следующим образом: + + ```java + @Override + public void onInitialize() { + // This code runs as soon as Minecraft is in a mod-load-ready state. + // However, some things (like resources) may still be uninitialized. + // Proceed with mild caution. + + LOGGER.info("Hello Fabric world!"); + } + ``` + + **Пример с Transclude:** + + ```md + @[code transcludeWith=#test_transclude](@/reference/.../blah.java) + ``` + + Таким образом будут вставлены фрагменты из `blah.java`, помеченные тегом `#test_transclude`. + + Пример: + + ```java + public final String test = "Bye World!" + + // #test_transclude + public void test() { + System.out.println("Hello World!"); + } + // #test_transclude + ``` + + Код между тегами `#test_transclude` будет выведен. + + ```java + public void test() { + System.out.println("Hello World!"); + } + ``` + +3. Вся оригинальная документация написана на английском языке в соответствии с американскими правилами грамматики. Но вы можете использовать [LanguageTool](https://languagetool.org/) для проверки грамматики при вводе текста, не придав этому особого значения. Наша команда документации может проанализировать и исправить грамматику на этапе очистки. Однако, вы сэкономите нам время, если изначально всё будет правильно. + +4. Если вы создаете новую категорию, вам следует создать новую боковую панель в папке `.vitepress/sidebars` и добавить её в файл `config.mts`. Если вам нужна помощь с этим, спросите [в дискорде Fabric](https://discord.gg/v6v4pMv) в канале `#docs`. + +5. При создании новой страницы вы должны добавить ее на соответствующую боковую панель в папке `.vitepress/sidebars`. Опять же, если вам нужна помощь, спросите в дискорде Fabric в канале `#docs`. + +6. Любые изображения должны находиться в соответствующем месте в папке `/assets`. + +7. ⚠️ **Ссылки на другие страницы должны быть относительными.** ⚠️ + + Это требуется для правильной работы системы с разными версиями, которая заранее обрабатывает ссылки для добавления версии. Если вы используете обычные ссылки, номер версии не будет добавлен к ссылке. + + Например, для страницы в папке `/players`, ссылка на страницу `installing-fabric` по пути `/players/installing-fabric.md`, вы должны сделать следующее: + + ```md + [Ссылка на другую страницу](./installing-fabric) + ``` + + Вы **НЕ** должны делать так: + + ```md + [Ссылка на другую страницу](/players/installing-fabric) + ``` + +Все материалы проходят три этапа: + +1. Справка по дополнению (если нужно) +2. Проверка содержимого +3. Корректура (проверка грамматики и т. д.) + +### Справка по дополнениям + +Если команда документации сочтёт, что ваш pull request можно дополнить, один из членов команды добавит метку `can-expand` к нему и оставит комментарий с пояснением, что именно можно добавить. Если вы согласны с предложением, вы можете принять его. Если вы согласны с этим предложением, вы можете дополнить свой реквест. + +**Вы не обязаны расширять свой pull request.** Если вы не хотите вносить дополнительные изменения в ваш pull request, просто попросите убрать метку `can-expand`. + +Если вы не хотите дополнять свой реквест, но будете рады, что кто-то другой дополнит его позже, лучше всего создать пост [на странице проблем](https://github.com/FabricMC/fabric-docs/issues) и объяснить, что, по вашему мнению, можно было бы дополнить. + +### Проверка содержимого + +Все реквесты, добавляющие содержимое, проходят проверку. Это самый важный этап, поскольку он гарантирует, что контент является точным и соответствует стандартам стиля документации Fabric. + +### Полировка + +На этом этапе наша команда исправит любые грамматические ошибки и внесёт некоторые изменения, которые она сочтёт необходимыми, прежде чем объединить реквест с основным проектом! + +## Перевод документации + +Если вы хотите перевести документацию на свой язык, вы можете сделать это на [странице Fabric на Crowdin](https://crowdin.com/project/fabricmc). diff --git a/versions/1.20.4/translated/ru_ru/develop/commands/arguments.md b/versions/1.20.4/translated/ru_ru/develop/commands/arguments.md new file mode 100644 index 000000000..a6ee50d4f --- /dev/null +++ b/versions/1.20.4/translated/ru_ru/develop/commands/arguments.md @@ -0,0 +1,56 @@ +--- +title: Аргументы команд +description: Узнайте, как создавать команды со сложными аргументами. +--- + +# Аргументы команд + +Большинство команд используют аргументы. Иногда они могут быть необязательными, что означает, что команда выполнится, даже если вы не предоставите этот аргумент. Один узел может иметь несколько типов аргументов, но будьте внимательны, чтобы избежать неоднозначности. + +@[code lang=java highlight={3} transcludeWith=:::4](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +В этом примере после текста команды `/argtater` следует указать целое число. Например, если вы выполните команду `/argtater 3`, вы получите сообщение «Вызвано /argtater с значением = 3». Если вы выполните `/argtater` без аргументов, команда не будет правильно распознана. + +Далее мы добавим необязательный второй аргумент: + +@[code lang=java highlight={3,13} transcludeWith=:::5](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +Теперь вы можете указать одно или два целых числа. Если вы укажете одно число, будет выведено сообщение с одним значением. Если вы укажете два числа, будет выведено сообщение с двумя значениями. + +Возможно, вам покажется излишним дважды указывать схожие исполнения. Поэтому мы можем создать метод, который будет использоваться в обоих случаях. + +@[code lang=java highlight={3,5,6,7} transcludeWith=:::6](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +## Собственные типы аргументов + +Если в стандартной библиотеке нет нужного вам типа аргументов, вы можете создать свой. Для этого нужно создать класс, который наследуется от интерфейса `ArgumentType`, где `T` — это тип аргумента. + +Вам нужно будет реализовать метод `parse`, который преобразует входную строку в нужный тип. + +Например, вы можете создать тип аргумента, который преобразует строку в `BlockPos` с форматом: `{x, y, z}` + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/command/BlockPosArgumentType.java) + +### Регистрация своих типов аргументов + +:::warning +Необходимо зарегистрировать свой тип аргументов как на сервере, так и на клиенте, иначе команда не будет работать! +::: + +Вы можете зарегистрировать свой тип аргументов в методе `onInitialize` вашего инициализатора мода, используя класс `ArgumentTypeRegistry`: + +@[code lang=java transcludeWith=:::11](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +### Использование своих типов аргументов + +Мы можем использовать наш собственный тип аргумента в команде, передав его экземпляр в метод `.argument` при создании команды. + +@[code lang=java transcludeWith=:::10 highlight={3}](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +Выполнив команду, мы можем проверить, работает ли наш тип аргумента: + +![Недопустимый аргумент](/assets/develop/commands/custom-arguments_fail.png) + +![Допустимый аргумент](/assets/develop/commands/custom-arguments_valid.png) + +![Результат команды](/assets/develop/commands/custom-arguments_result.png) diff --git a/versions/1.20.4/translated/ru_ru/develop/entities/effects.md b/versions/1.20.4/translated/ru_ru/develop/entities/effects.md new file mode 100644 index 000000000..b7387df72 --- /dev/null +++ b/versions/1.20.4/translated/ru_ru/develop/entities/effects.md @@ -0,0 +1,70 @@ +--- +title: Эффекты состояния +description: Узнайте, как создавать свои собственные эффекты состояния. +authors: + - dicedpixels + - YanisBft + - FireBlast + - Friendly-Banana + - SattesKrokodil +authors-nogithub: + - siglong + - tao0lu +--- + +# Эффекты состояния + +Эффекты состояния, также известные как просто эффекты, представляют собой состояние, которое может воздействовать на сущность. Они могут сказываться положительно, отрицательно или нейтрально на сущности. В обычном случае в игре эти эффекты применяются несколькими способами, такими как поедание еды, распитие зелий и так далее. + +Можно использовать команду `/effect` для применения эффектов к сущности. + +## Свои эффекты состояния + +В этом руководстве мы добавим новый эффект под названием _Tater_, который даёт игроку одно очко опыта каждый игровой такт. + +### Расширение `StatusEffect` + +Давайте создадим класс нашего эффекта, который будет наследовать основной класс всех эффектов — `StatusEffect`. + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/effect/TaterEffect.java) + +### Регистрация нашего эффекта + +Схожим с регистрацией блоков и предметов образом, мы используем `Registry.register`, чтобы зарегистрировать наш эффект в реестре `STATUS_EFFECT`. Это можно сделать в нашем инициализаторе. + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/effect/FabricDocsReferenceEffects.java) + +### Переводы и текстуры + +Вы можете назначить имя вашему эффекту состояния и дать ему иконку, которая будет отображаться в инвентаре игрока. + +#### Текстура + +Иконка эффекта состояния представляет собой PNG-файл размером 18×18 пикселей. Поместите свою иконку в папку: + +```:no-line-numbers +resources/assets/fabric-docs-reference/textures/mob_effect/tater.png +``` + +![Эффект в инвентаре игрока](/assets/develop/tater-effect.png) + +#### Переводы + +Как и с любыми другими переводами, вы можете добавить запись формата `"effect..": "Значение"` в языковой файл. + +::: code-group + +```json[assets/fabric-docs-reference/lang/en_us.json] +{ + "effect.fabric-docs-reference.tater": "Tater" +} +``` + +### Тестирование + +Используйте команду `/effect give @p fabric-docs-reference:tater`, чтобы дать игроку наш эффект Tater. +Используйте команду `/effect clear @p fabric-docs-reference:tater`, чтобы удалить эффект. + +::: info +Чтобы узнать, как создать зелье, накладывающее этот эффект, ознакомьтесь с руководством по [зельям](../items/potions). +::: diff --git a/versions/1.20.4/translated/ru_ru/develop/getting-started/introduction-to-fabric-and-modding.md b/versions/1.20.4/translated/ru_ru/develop/getting-started/introduction-to-fabric-and-modding.md new file mode 100644 index 000000000..758ea236b --- /dev/null +++ b/versions/1.20.4/translated/ru_ru/develop/getting-started/introduction-to-fabric-and-modding.md @@ -0,0 +1,65 @@ +--- +title: Введение в Fabric и создание модов +description: "Краткое знакомство с Fabric и созданием модов для Minecraft: Java Edition." +authors: + - IMB11 + - itsmiir +--- + + + +# Введение в Fabric и создание модов + +## Подготовка + +Перед тем как начать, вам следует иметь базовые знания разработки на Java и понимание концепций объектно-ориентированного программирования (ООП). + +Если эти концепции вам не знакомы, рекомендуем сначала изучить несколько учебных материалов по Java и ООП. Эти ресурсы могут помочь: + +- [W3: Уроки по Java](https://www.w3schools.com/java/) +- [Codecademy: Выучите Java](https://www.codecademy.com/learn/learn-java) +- [W3: Java в ООП](https://www.w3schools.com/java/java_oop.asp) +- [Medium: Введение в ООП](https://medium.com/@Adekola_Olawale/beginners-guide-to-object-oriented-programming-a94601ea2fbd) + +### Термины + +Прежде чем начнём, давайте рассмотрим некоторые термины, с которыми вы столкнётесь при создании мода на Fabric: + +- **Мод**: Изменение игры, добавляющее новые функции или изменяющее существующие. +- **Загрузчик модов**: Инструмент для загрузки модов в игру, такой как загрузчик Fabric. +- **Mixin**: Инструмент для модификации кода игры во время её выполнения — подробнее во [введении в Mixin](https://fabricmc.net/wiki/tutorial:mixin_introduction). +- **Gradle**: Инструмент автоматизации сборки, применяемый для создания и компиляции модов. Fabric использует его для сборки своих модов. +- **Маппинги**: Набор маппингов, преобразующих обфусцированный код в тот, который может прочесть человек. +- **Обфускация**: Процесс усложнения кода для его затруднённого понимания, используемый Mojang для защиты кода Minecraft. +- **Remapping**: Процесс преобразования обфусцированного кода в тот, который будет читаем для людей. + +## Что такое Fabric? + +Fabric — лёгкий инструмент для создания модов для Minecraft: Java Edition. + +Он разработан как простая и удобная платформа для разработки модов. Fabric — это проект, который ведёт сообщество, и у него открытый исходный код, что означает, что любой может внести в него свой вклад. + +Вам следует знать о четырёх основных компонентах Fabric: + +- **Загрузчик Fabric**: гибкий загрузчик модов, не зависящий от платформы, предназначенный для Minecraft и других игр и приложений. +- **Fabric Loom**: плагин для Gradle, позволяющий разработчикам легко разрабатывать и отлаживать моды. +- **Fabric API**: набор API и инструментов для разработчиков модов, которые можно использовать при создании модов. +- **Yarn**: набор открытых маппингов Minecraft, свободных для использования под лицензией Creative Commons Zero. + +## Почему Fabric необходим для модификации Minecraft? + +> Модификация игры — это процесс изменения игры с целью изменения её поведения или добавления новых возможностей. В случае Minecraft это может включать в себя всё, от добавления новых предметов, блоков или существ до изменения механик игры или добавления новых режимов игры. + +Minecraft: Java Edition обфусцирован компанией Mojang, что делает самостоятельное модифицирование сложным. Однако с помощью инструментов для модификации, таких как Fabric, процесс становится намного проще. Существуют различные системы маппинга, которые могут помочь в этом процессе. + +Loom преобразует обфусцированный код в читаемый формат с помощью этих маппингов, что облегчает мододелам понимание и изменение кода игры. Yarn является популярным и отличным выбором для маппинга, но также существуют и другие варианты. Каждый проект маппинга может иметь свои собственные достоинства и фокусироваться на различных аспектах. + +Loom позволяет легко разрабатывать и компилировать моды на основе кода, над которым провели remapping, а загрузчик Fabric позволяет загружать эти моды в игру. + +## Что даёт Fabric API и зачем это нужно? + +> Fabric API — это набор API и инструментов для разработчиков модов, которые можно использовать при создании модов. + +Fabric API предоставляет широкий набор API, которые расширяют существующие функциональные возможности Minecraft. Например, он предлагает новые хуки и события, которые могут использоваться мододелами, или новые утилиты и инструменты, упрощающие процесс модификации игры, такие как транзитивные расширители доступа и возможность доступа к внутренним реестрам, таким как реестр предметов, которые можно использовать в компостнице. + +Хотя Fabric API предлагает довольно мощные функции, некоторые задачи, такие как базовая регистрация блоков, можно выполнять и без него, используя стандартные API Minecraft. diff --git a/versions/1.20.4/translated/ru_ru/develop/index.md b/versions/1.20.4/translated/ru_ru/develop/index.md new file mode 100644 index 000000000..99508dda4 --- /dev/null +++ b/versions/1.20.4/translated/ru_ru/develop/index.md @@ -0,0 +1,12 @@ +--- +title: Руководства для разработчиков +description: "Наш подбор руководств для разработчиков, написанных сообществом, охватывает широкий спектр тем: от настройки среды разработки до более продвинутых тем, таких как отрисовка и сетевое взаимодействие." +--- + +# Руководства для разработчиков + +Наш подбор руководств для разработчиков, написанных сообществом, охватывает широкий спектр тем: от настройки среды разработки до более продвинутых тем, таких как отрисовка и сетевое взаимодействие. + +Обратите внимание на боковую панель, где представлен список всех доступных руководств для разработчиков. Если вы ищете что-то конкретное, вы можете воспользоваться поиском в верхней части страницы, чтобы найти то, что вам нужно. + +Если вы хотите внести свой вклад в документацию Fabric, вы можете найти её исходный код на [GitHub](https://github.com/FabricMC/fabric-docs) и ознакомиться с соответствующим [руководством по внесению вклада](../contributing). diff --git a/versions/1.20.4/translated/ru_ru/index.md b/versions/1.20.4/translated/ru_ru/index.md new file mode 100644 index 000000000..ed447a984 --- /dev/null +++ b/versions/1.20.4/translated/ru_ru/index.md @@ -0,0 +1,27 @@ +--- +title: Документация Fabric +description: Официальная курируемая документация по Fabric, инструментарию для разработки модов для Minecraft. +layout: home +hero: + name: Документация Fabric + tagline: Официальная курируемая документация по Fabric, инструментарию для разработки модов для Minecraft. +features: + - title: Руководства для разработчиков + icon: 🛠️ + details: "Наш подбор руководств для разработчиков, написанных сообществом, охватывает широкий спектр тем: от настройки среды разработки до более продвинутых тем, таких как отрисовка и сетевое взаимодействие." + link: ./develop/index + linkText: Приступить к прочтению + - title: Руководства для игроков + icon: 📚 + details: Вы игрок, желающий играть с модами, работающими на Fabric? Наши руководства для игроков освещают все необходимые темы. Эти руководства расскажут, как скачать, установить и устранять неполадки с модами для Fabric. + link: ./players/index + linkText: Подробнее +--- + +
+ +## Хотите внести свой вклад? + +Если вы хотите внести свой вклад в документацию Fabric, вы можете найти её исходный код на [GitHub](https://github.com/FabricMC/fabric-docs) и ознакомиться с соответствующим [руководством по внесению вклада](./contributing). + +
diff --git a/versions/1.20.4/translated/ru_ru/players/faq.md b/versions/1.20.4/translated/ru_ru/players/faq.md new file mode 100644 index 000000000..b85c83478 --- /dev/null +++ b/versions/1.20.4/translated/ru_ru/players/faq.md @@ -0,0 +1,31 @@ +--- +title: Часто задаваемые вопросы для игроков +description: Ответы на часто задаваемые вопросы касательно Fabric, поступающие от игроков и администраторов серверов. +--- + +# Часто задаваемые вопросы + +Есть множество вопросов, которые часто задают, поэтому мы составили их список здесь. + +## Общие вопросы + +### Какие версии Minecraft поддерживает Fabric? + +Официально Fabric поддерживает все версии Minecraft, начиная со снапшотов `18w43b` и выше, а также с версии `1.14` и выше. + +### Где я могу скачать моды для Fabric? + +:::info +Вы всегда должны проверять, скачиваете ли вы моды из надежного источника. Смотрите гайд [Поиск безопасных модов](./finding-mods) для большей информации. +::: + +Большинство авторов публикуют свои моды на [Modrinth](https://modrinth.com/mods?g=categories:%27fabric%27) и [CurseForge](https://www.curseforge.com/minecraft/search?class=mc-mods&gameVersionTypeId=4), однако некоторые авторы загружают их на свои личные сайты или на другие платформы, такие как репозиторий GitHub. + +### Где я могу найти готовые модпаки для Fabric? + +Вы можете найти готовые модпаки для Fabric на различных платформах, таких как: + +- [Modrinth](https://modrinth.com/modpacks?g=categories:%27fabric%27) +- [CurseForge](https://www.curseforge.com/minecraft/search?class=modpacks&gameVersionTypeId=4) +- [Feed The Beast](https://www.feed-the-beast.com/ftb-app) +- [Technic](https://www.technicpack.net/modpacks) diff --git a/versions/1.20.4/translated/ru_ru/players/finding-mods.md b/versions/1.20.4/translated/ru_ru/players/finding-mods.md new file mode 100644 index 000000000..7fcffae03 --- /dev/null +++ b/versions/1.20.4/translated/ru_ru/players/finding-mods.md @@ -0,0 +1,34 @@ +--- +title: Поиск безопасных модов +description: Гайд о том, как найти моды для Fabric, используя надежные источники. +authors: + - IMB11 +--- + +# Поиск безопасных модов + +Во-первых, доверие субъективно, и вы всегда должны руководствоваться своим собственным мнением при загрузке модов. Тем не менее есть некоторые вещи, которые вы можете сделать, чтобы найти заслуживающие доверия моды. + +## 1. Используйте безопасные источники + +Большинство авторов публикуют свои моды на [Modrinth](https://modrinth.com/mods?g=categories:%27fabric%27) и [CurseForge](https://www.curseforge.com/minecraft/search?class=mc-mods&gameVersionTypeId=4). + +Эти сайты проверяют, являются ли моды тем, за что они себя выдают, и что они не содержат вредоносного кода. Вы также можете сообщить о вредоносных модах на этих сайтах, и они примут меры относительно быстро. + +## 2. Посоветуйтесь с другими! + +Если вы загружаете мод из источника, который не безопасен, вам следует посоветоваться с другими людьми, чтобы узнать, загружали ли они мод ранее из того места, откуда загружаете вы, и не возникали ли у них какие-либо проблемы с ним. + +Если у вас есть вопросы, вы можете задать их [в дискорде Fabric](https://discord.gg/v6v4pMv) в канале `#player-support`. + +## 3. Избегайте вредоносных сайтов! + +:::info +Вредоносные сайты могут быть очевидны не для всех. Если вы не уверены, вам следует спросить мнения других или вообще избегать других сайтов и полагаться только на надежные источники, такие как Modrinth и CurseForge. +::: + +Есть много сайтов, которые утверждают, что у них есть моды для Minecraft, но на самом деле это просто вредоносные сайты. Вам следует избегать этих сайтов любой ценой. + +Вы можете использовать антивирусы и сайты, такие как [Windows Defender](https://www.microsoft.com/en-us/windows/comprehensive-security) или [VirusTotal](https://www.virustotal.com/) для проверки загруженных модов. Однако не стоит полностью полагаться на эти методы, поскольку иногда они могут быть некорректными. + +Опять же, если у вас есть сомнения, вы можете спросить мнения людей [в дискорде Fabric](https://discord.gg/v6v4pMv) в канале `#player-support`. diff --git a/versions/1.20.4/translated/ru_ru/players/index.md b/versions/1.20.4/translated/ru_ru/players/index.md new file mode 100644 index 000000000..cec37cdbc --- /dev/null +++ b/versions/1.20.4/translated/ru_ru/players/index.md @@ -0,0 +1,12 @@ +--- +title: Руководства для игроков +description: Собрание руководств для игроков и администраторов серверов по установке и использованию Fabric. +--- + +# Руководства для игроков + +Этот раздел документации Fabric предназначен для игроков и администраторов серверов, желающих узнать, как устанавливать, использовать и устранять неполадки с Fabric. + +Список всех доступных руководств есть на боковой панели. + +Если вы столкнулись с какой-либо проблемой, сообщите о ней на [странице GitHub](https://github.com/FabricMC/fabric-docs) или попросите помощи в [дискорде Fabric](https://discord.gg/v6v4pMv) в каналах `#player-support` или `#server-admin-support` (На английском языке). diff --git a/versions/1.20.4/translated/ru_ru/players/installing-fabric.md b/versions/1.20.4/translated/ru_ru/players/installing-fabric.md new file mode 100644 index 000000000..a5d44a17e --- /dev/null +++ b/versions/1.20.4/translated/ru_ru/players/installing-fabric.md @@ -0,0 +1,55 @@ +--- +title: Установка Fabric +description: Пошаговая инструкция по установке Fabric. +authors: + - IMB11 +--- + +# Установка Fabric + +В этом гайде мы расскажем вам об установке Fabric на официальный лаунчер Minecraft. + +Для сторонних лаунчеров вам следует ознакомиться с их документацией. + +## 1. Загрузка установщика Fabric + +Вы можете загрузить установщик Fabric с [сайта Fabric](https://fabricmc.net/use/). + +Если вы используете Windows, скачайте версию `.exe` (`Download For Windows`), потому что для неё не требуется Java в вашей системе. Вместо этого он использует версию Java из официального лаунчера. + +Для macOS и Linux вам потребуется установить версию `.jar`. Иногда вам необходимо установить Java перед выполнением этого шага. + +## 2. Запуск установщика Fabric + +:::warning +Перед установкой закройте Minecraft и лаунчер. +::: + +:::details Информация для пользователей macOS + +На macOS вам может потребоваться щелкнуть правой кнопкой мыши на файл `.jar` и нажать `Открыть`, чтобы запустить его. + +![Контекстное меню установщика Fabric на MacOS](/assets/players/installing-fabric/macos-downloads.png) + +Когда вас спросят: "Вы уверены, что хотите это открыть?", нажмите `Открыть` ещё раз. +::: + +Как только вы откроете установщик, вы должны увидеть экран, похожий на этот: + +![Установщик Fabric с подсвеченным "Install"](/assets/players/installing-fabric/installer-screen.png) + +Чтобы установить Fabric, просто выберите свою версию игры из списка и нажмите `Установить`. + +**Убедитесь, что установлен флажок 'Создать профиль'.** + +## 3. Готово! + +Как только установка завершится, вы можете открыть лаунчер Minecraft, выбрать профиль Fabric из списка в левом нижнем углу и нажать Играть! + +![Лаунчер Minecraft с выбранным профилем Fabric](/assets/players/installing-fabric/launcher-screen.png) + +## Следующие шаги + +Теперь, когда вы установили Fabric, вы можете добавлять моды в свою игру! Смотрите гайд [Поиск безопасных модов](./finding-mods) для большей информации. + +Если вы столкнулись с какими-либо проблемами, попросите помощи в [дискорде Fabric](https://discord.gg/v6v4pMv) в канале `#player-support`. diff --git a/versions/1.20.4/translated/ru_ru/players/installing-java/linux.md b/versions/1.20.4/translated/ru_ru/players/installing-java/linux.md new file mode 100644 index 000000000..fbf8177d7 --- /dev/null +++ b/versions/1.20.4/translated/ru_ru/players/installing-java/linux.md @@ -0,0 +1,91 @@ +--- +title: Установка Java на Linux +description: Пошаговая инструкция по установке Java на Linux. +authors: + - IMB11 +--- + +# Установка Java на Linux + +Этот гайд расскажет, как установить Java 17 на Linux. + +## 1. Проверьте, не установлена ли Java + +Откройте терминал, впишите `java -version` и нажмите Enter. + +![Терминал с введённой командой "java -version"](/assets/players/installing-java/linux-java-version.png) + +:::warning +Чтобы использовать большинство современных версий Minecraft, вам потребуется установить как минимум Java 17. Если эта команда отображает любую версию ниже 17, вам придётся обновить Java. +::: + +## 2. Загрузка и установка Java 17 + +Мы рекомендуем использовать OpenJDK 17, который доступен для большинства дистрибутивов Linux. + +### Arch Linux + +:::info +Для дополнительной информации об установке Java в Arch Linux смотрите [википедию Arch Linux](https://wiki.archlinux.org/title/Java_(Русский)). +::: + +Вы можете установить последнюю версию JRE из официальных репозиториев: + +```sh +sudo pacman -S jre-openjdk +``` + +Если вы используете сервер без необходимости в графическом интерфейсе, вы можете вместо этого установить `headless` версию: + +```sh +sudo pacman -S jre-openjdk-headless +``` + +Если вы планируете разрабатывать моды, вместо этого вам понадобится JDK: + +```sh +sudo pacman -S jdk-openjdk +``` + +### Debian/Ubuntu + +Вы можете установить Java 17, используя `apt`, с помощью следующих команд: + +```sh +sudo apt update +sudo apt install openjdk-17-jdk +``` + +### Fedora + +Вы можете установить Java 17, используя `dnf`, с помощью следующих команд: + +```sh +sudo dnf install java-17-openjdk +``` + +Если вам не нужен графический интерфейс, вы можете вместо этого установить `headless` версию: + +```sh +sudo dnf install java-17-openjdk-headless +``` + +Если вы планируете разрабатывать моды, вместо этого вам понадобится JDK: + +```sh +sudo dnf install java-17-openjdk-devel +``` + +### Другие дистрибутивы Linux + +Если вашего дистрибутива нет в списке выше, вы можете загрузить последнюю версию JRE с [Adoptium](https://adoptium.net/temurin/) + +Вам следует обратиться к альтернативному гайду для вашего дистрибутива, если вы планируете разрабатывать моды. + +## 3. Убедитесь, что Java 17 установлена + +После того как установка закончится, вы можете проверить, что Java 17 установлена, открыв терминал и вписав `java -version`. + +Если команда будет выполнена успешно, вы увидите что-то вроде показанного ранее, где отображается версия Java: + +![Терминал с введённой командой "java -version"](/assets/players/installing-java/linux-java-version.png) diff --git a/versions/1.20.4/translated/ru_ru/players/installing-java/windows.md b/versions/1.20.4/translated/ru_ru/players/installing-java/windows.md new file mode 100644 index 000000000..88c2e1f78 --- /dev/null +++ b/versions/1.20.4/translated/ru_ru/players/installing-java/windows.md @@ -0,0 +1,65 @@ +--- +title: Установка Java на Windows +description: Пошаговая инструкция по установке Java на Windows. +authors: + - IMB11 +--- + +# Установка Java на Windows + +Этот гайд расскажет, как установить Java 17 на Windows. + +Этот гайд понадобится вам, если вы хотите использовать установщик на основе `.jar` Fabric'а, или если вы используете `.jar` сервера Minecraft. + +## 1. Проверьте, не установлена ли Java + +Чтобы проверить, что Java уже установлена, вам нужно сначала открыть командную строку. + +Вы можете сделать это, нажав Win + R и написав `cmd.exe` в появившемся окне. + +![Окно "Выполнить" с введённым "cmd.exe"](/assets/players/installing-java/windows-run-dialog.png) + +После того как вы открыли командную строку, впишите `java -version` и нажмите Enter. + +Если команда выполнена успешно, вы увидите что-то вроде этого. Если выдало ошибку, то переходите к следующему шагу. + +![Командная строка с введённой командой "java -version"](/assets/players/installing-java/windows-java-version.png) + +:::warning +Чтобы использовать большинство современных версий Minecraft, вам потребуется установить как минимум Java 17. Если эта команда отображает любую версию ниже 17, вам придётся обновить Java. +::: + +## 2. Скачивание установщика Java 17 + +Чтобы установить Java 17, вам нужно скачать установщик с [Adoptium](https://adoptium.net/en-GB/temurin/releases/?os=windows&package=jdk&version=17). + +Вам нужно скачать версию `Windows Installer (.msi)`: + +![Adoptium c выделенным Windows Installer (.msi)](/assets/players/installing-java/windows-download-java.png) + +Вам нужно выбрать `x86`, если у вас 32-битная система, или `x64`, если у вас 64-битная операционная система. + +Большинство современных компьютеров имеют 64-битную операционную систему. Если вы не уверены, используйте 64-битный установщик. + +## 3. Запустите установщик! + +Следуйте инструкциям в установщике, чтобы установить Java 17. Когда вы доходите до этой страницы, вы должны выбрать "Entire feature will be installed on local hard drive" для следующих функций: + +- `Set JAVA_HOME environment variable` - будет добавлено в PATH. +- `JavaSoft (Oracle) registry keys` + +![Установщик Java 17 c выделенными "Set JAVA_HOME variable" и "JavaSoft (Oracle) registry keys"](/assets/players/installing-java/windows-wizard-screenshot.png) + +После этого нажмите на `Next` и продолжите установку. + +## 4. Убедитесь, что Java 17 установлена + +После того как установка закончится, вы можете проверить, что Java 17 установлена, открыв командную строку и вписав `java -version`. + +Если команда будет выполнена успешно, вы увидите что-то вроде показанного ранее, где отображается версия Java: + +![Командная строка с введённой командой "java -version"](/assets/players/installing-java/windows-java-version.png) + +--- + +Если вы столкнулись с какими-либо проблемами, попросите помощи в [дискорде Fabric](https://discord.gg/v6v4pMv) в канале `#player-support`. diff --git a/versions/1.20.4/translated/ru_ru/players/installing-mods.md b/versions/1.20.4/translated/ru_ru/players/installing-mods.md new file mode 100644 index 000000000..befa4fbc4 --- /dev/null +++ b/versions/1.20.4/translated/ru_ru/players/installing-mods.md @@ -0,0 +1,67 @@ +--- +title: Установка модов +description: Пошаговая инструкция по установке модов для Fabric. +authors: + - IMB11 +--- + +# Установка модов + +В этом гайде мы расскажем вам об установке модов для Fabric на официальный лаунчер Minecraft. + +Для сторонних лаунчеров вам следует ознакомиться с их документацией. + +## 1. Загрузка модов + +:::warning +Вы должны загружать моды только из источников, которым вы доверяете. Смотрите гайд [Поиск безопасных модов](./finding-mods) для большей информации. +::: + +Для большинства модов также требуется Fabric API, который можно загрузить с [Modrinth](https://modrinth.com/mod/fabric-api) или [CurseForge](https://curseforge.com/minecraft/mc-mods/fabric-api). + +При загрузке модов убедитесь, что: + +- Они работают с той версией Minecraft, на которой вы хотите играть. Например, мод, работающий на версии 1.20, может не работать на версии 1.20.2. +- Они предназначены для Fabric, а не для другого загрузчика модов. +- Кроме того, они предназначены для правильной версии Minecraft (Java Edition). + +## 2. Перемещение мода в папку `mods` + +Папку mods можно найти в следующих местах для каждой операционной системы. + +Обычно вы можете вставить эти пути в адресную строку проводника, чтобы быстро перейти к нужной папке. + +::: code-group + +```:no-line-numbers [Windows] +%appdata%\.minecraft\mods +``` + +```:no-line-numbers [macOS] +~/Library/Application Support/minecraft/mods +``` + +```:no-line-numbers [Linux] +~/.minecraft/mods +``` + +::: + +Как только вы найдете папку `mods`, вы можете переместить в нее `.jar` файл мода. + +![Установленный мод в папке модов](/assets/players/installing-mods.png) + +## 3. Готово! + +Как только вы переместите мод в папку `mods`, вы можете открыть лаунчер Minecraft, выбрать профиль Fabric из списка в левом нижнем углу и нажать Играть! + +![Лаунчер Minecraft с выбранным профилем Fabric](/assets/players/installing-fabric/launcher-screen.png) + +## Исправление ошибок + +Если вы столкнулись с какими-либо проблемами, попросите помощи в [дискорде Fabric](https://discord.gg/v6v4pMv) в канале `#player-support`. + +Вы также можете попытаться устранить проблему самостоятельно, ознакомившись со страницами, посвященными устранению неполадок: + +- [Краш-репорты](./troubleshooting/crash-reports) +- [Загрузка логов](./troubleshooting/uploading-logs) diff --git a/versions/1.20.4/translated/ru_ru/players/troubleshooting/crash-reports.md b/versions/1.20.4/translated/ru_ru/players/troubleshooting/crash-reports.md new file mode 100644 index 000000000..23833a51f --- /dev/null +++ b/versions/1.20.4/translated/ru_ru/players/troubleshooting/crash-reports.md @@ -0,0 +1,104 @@ +--- +title: Краш-репорты +description: Узнайте, что делать с краш-репортами и как их читать. +authors: + - IMB11 +--- + +# Краш-репорты + +:::tip +Если у вас возникли какие-либо трудности с поиском причины краша, вы можете обратиться за помощью в [дискорд Fabric](https://discord.gg/v6v4pMv) в каналах `#player-support` или `#server-admin-support`. +::: + +Краш-репорты являются очень важной частью устранения проблем с вашей игрой или сервером. Они содержат много информации о краше и могут помочь вам найти причину краша. + +## Поиск краш-репортов + +Краш-репорты находятся в папке `crash-reports` в папке вашей игры. Если у вас сервер, то они хранятся в папке `crash-reports` в папке сервера. + +Для сторонних лаунчеров вам следует посмотреть в их документацию, чтобы найти краш-репорты. + +Краш-репорты можно найти по этим путям: + +::: code-group + +```:no-line-numbers [Windows] +%appdata%\.minecraft\crash-reports +``` + +```:no-line-numbers [macOS] +~/Library/Application Support/minecraft/crash-reports +``` + +```:no-line-numbers [Linux] +~/.minecraft/crash-reports +``` + +::: + +## Чтение краш-репортов + +Краш-репорты очень большие, их чтение может быть непонятным. Однако они содержат много информации о краше и могут помочь вам найти причину краша. + +Для этого гайда, мы используем [этот краш-репорт в качестве примера](https://github.com/FabricMC/fabric-docs/blob/main/public/assets/players/crash-report-example.txt). + +### Разделы краш-репорта + +Краш-репорты состоят из нескольких разделов, разделённых заголовками: + +- `---- Minecraft Crash Report ----`, краткое описание краша. Этот раздел содержит основную ошибку, вызвавшую краш, время возникновения и трассировку стека. Это главный раздел краш-репорта, так как трассировка стека обычно содержит мод, который вызывает краш. +- `-- Last Reload --`, этот раздел на самом деле бесполезен, если только краш не произошёл во время перезагрузки ресурсов (F3+T). Этот раздел содержит время последней перезагрузки и трассировки стеков любых ошибок, возникших в процессе перезагрузки. Эти ошибки обычно происходят из-за ресурс-паков, и их можно игнорировать, если только они не вызывают проблем с игрой. +- `-- System Details --`, этот раздел содержит информацию о вашем компьютере, такую как операционная система, версия Java и объем памяти, выделенный для игры. Этот раздел полезен для определения того, используете ли вы правильную версию Java и выделили ли вы игре достаточно памяти. + - В этом разделе Fabric добавит строку `Fabric Mods:` со списком всех установленных модов. Этот раздел полезен для определения конфликтов между модами. + +### Разбор краш-репорта + +Теперь, когда мы знаем, что представляет собой каждый раздел, мы можем начать разбирать краш-репорт и находить причину краша. + +Используя файл выше, мы можем проанализировать краш-репорт и найти причину краша, включая моды, которые вызвали сбой. + +Трассировка стека в разделе `---- Minecraft Crash Report ----` является наиболее важной в данном случае, поскольку она содержит основную ошибку, вызвавшую краш. В нашем случае ошибка - `java.lang.NullPointerException: Cannot invoke "net.minecraft.class_2248.method_9539()" because "net.minecraft.class_2248.field_10540" is null`. + +Учитывая количество модов, упомянутых в стеке, может быть трудно указать на конкретную причину, но первое, что нужно сделать, это найти мод, который вызвал сбой. + +```:no-line-numbers +at snownee.snow.block.ShapeCaches.get(ShapeCaches.java:51) +at snownee.snow.block.SnowWallBlock.method_9549(SnowWallBlock.java:26) // [!code focus] +... +at me.jellysquid.mods.sodium.client.render.chunk.compile.pipeline.BlockOcclusionCache.shouldDrawSide(BlockOcclusionCache.java:52) +at link.infra.indium.renderer.render.TerrainBlockRenderInfo.shouldDrawFaceInner(TerrainBlockRenderInfo.java:31) +... +``` + +В данном случае мод, вызвавший сбой, называется `snownee`, поскольку это первый мод, упомянутый в трассировке стека. + +Однако, учитывая количество упомянутых модов, это может означать, что между модами проблемы с совместимостью, и мод, вызвавший краш, может быть не тем модом, который виноват. В этом случае лучше всего сообщить о краше автору мода и позволить ему изучить краш. + +## Краш миксина + +:::info +Миксины - это способ для модов модифицировать игру без необходимости изменять исходный код игры. Они используются многими модами и являются очень мощным инструментом для разработчиков модов. +::: + +Когда происходит краш миксина, в трассировке стека обычно упоминается миксин и класс, который он модифицирует. + +Метод миксина будет содержать `modid$handlerName` в трассировке стека, где `modid` - айди мода, а `handlerName` - название обработчика миксина. + +```:no-line-numbers +... net.minecraft.class_2248.method_3821$$$modid$handlerName() ... // [!code focus] +``` + +Вы можете использовать эту информацию, чтобы найти мод, вызвавший краш, и сообщить о нём автору мода. + +## Что делать с краш-репортами + +Лучшее, что можно сделать с краш-репортами - это загрузить их на сайт для текстов, а затем отправить ссылку автору мода либо в раздел с проблемами мода, либо через какую-либо форму связи (дискорд и т.д.). + +Это позволит автору мода изучить краш, потенциально воспроизвести его и решить проблему, которая его вызвала. + +Распространенными сайтами для текстов, которые часто используются для краш-репортов, являются: + +- [GitHub Gist](https://gist.github.com/) +- [Pastebin](https://pastebin.com/) +- [mclo.gs](https://mclo.gs/) diff --git a/versions/1.20.4/translated/ru_ru/players/troubleshooting/uploading-logs.md b/versions/1.20.4/translated/ru_ru/players/troubleshooting/uploading-logs.md new file mode 100644 index 000000000..c946e6063 --- /dev/null +++ b/versions/1.20.4/translated/ru_ru/players/troubleshooting/uploading-logs.md @@ -0,0 +1,54 @@ +--- +title: Загрузка логов +description: Как загрузить логи для устранения проблем. +authors: + - IMB11 +--- + +# Загрузка логов + +При устранении проблем часто бывает необходимо предоставить логи, которые помогут определить причину проблемы. + +## Почему я должен загружать журналы? + +Загрузка логов позволяет другим людям в устранении проблем гораздо быстрее, чем просто вставка логов в сообщение в чате или на форуме. Это также позволяет вам делиться своими логами с другими людьми без необходимости копировать и вставлять их. + +Некоторые сайты для текстов также предоставляют подсветку синтаксиса для логов, что облегчает их чтение, а также они могут подвергать цензуре конфиденциальную информацию, например, системную информацию или ваш ник. + +## Краш-репорты + +Краш-репорты генерируются автоматически при краше игры. Они содержат только информацию о краше, а не фактические логи игры. Они находятся в папке `crash-reports` в папке игры. + +Дополнительные сведения о краш-репортах смотрите [в гайде о краш-репортах](./crash-reports). + +## Поиск логов + +Этот гайд относится к официальному лаунчеру (или же "ванильный лаунчер"). Для сторонних лаунчеров вам следует ознакомиться с их документацией. + +Логи находятся в папке `logs` в папке игры, которую можно найти в следующих местах, в зависимости от вашей операционной системы: + +::: code-group + +```:no-line-numbers [Windows] +%appdata%\.minecraft +``` + +```:no-line-numbers [macOS] +~/Library/Application Support/minecraft +``` + +```:no-line-numbers [Linux] +~/.minecraft +``` + +::: + +Файл с последними логами называется `latest.log`, предыдущие логи называются по шаблону `гггг-мм-дд_номер.log.gz`. + +## Загрузка логов + +Логи могут быть загружены в различные сервисы, такие как: + +- [Pastebin](https://pastebin.com/) +- [GitHub Gist](https://gist.github.com/) +- [mclo.gs](https://mclo.gs/) diff --git a/versions/1.20.4/translated/ru_ru/players/updating-fabric.md b/versions/1.20.4/translated/ru_ru/players/updating-fabric.md new file mode 100644 index 000000000..5185aaaae --- /dev/null +++ b/versions/1.20.4/translated/ru_ru/players/updating-fabric.md @@ -0,0 +1,41 @@ +--- +title: Обновление Fabric +description: Пошаговая инструкция по обновлению Fabric. +authors: + - IMB11 + - modmuss50 +--- + +# Обновление Fabric + +В этом гайде мы расскажем вам об обновлении Fabric на официальном лаунчере Minecraft. + +Для сторонних лаунчеров вам следует ознакомиться с их документацией. + +Обновление Fabric - это процесс, очень похожий на установку Fabric, поэтому части этого гайда будут такими же, как и в гайде [Установка Fabric](./installing-fabric). + +## Почему я должен обновлять загрузчик Fabric? + +Для работы с новыми модами может потребоваться более новая версия загрузчика Fabric, поэтому важно поддерживать её в актуальном состоянии, чтобы вы могли использовать последние версии модов. + + + + + +Чтобы обновить Fabric, просто убедитесь в правильности версии игры и загрузчика, а затем нажмите `Установить`. + +**Обязательно снимите флажок `Создать профиль` при установке, иначе появится новый профиль, который в данном случае нам не нужен.** + +## 3. Откройте профиль в лаунчере Minecraft + +Как только установка завершится, вы можете открыть лаунчер Minecraft и перейти во вкладку `Установки`. Вам следует зайти в профиль Fabric и открыть экран редактирования. + +Замените версию загрузчика на новую, которую вы только что установили, и нажмите `Сохранить`. + +![Обновление версии загрузчика Fabric в лаунчере Minecraft](/assets/players/updating-fabric.png) + +## 4. Готово! + +Как только вы выполните все действия, вы можете вернуться в главную вкладку, выбрать профиль Fabric из списка в левом нижнем углу и нажать Играть! + +Если вы столкнулись с какими-либо проблемами, попросите помощи в [дискорде Fabric](https://discord.gg/v6v4pMv) в канале `#player-support`. diff --git a/versions/1.20.4/translated/ru_ru/sidebar_translations.json b/versions/1.20.4/translated/ru_ru/sidebar_translations.json new file mode 100644 index 000000000..caa1037a9 --- /dev/null +++ b/versions/1.20.4/translated/ru_ru/sidebar_translations.json @@ -0,0 +1,47 @@ +{ + "players.title": "Руководства для игроков", + "players.faq": "Часто задаваемые вопросы", + "players.installingJava": "Установка Java", + "players.installingJava.windows": "Windows", + "players.installingJava.macOS": "macOS", + "players.installingJava.linux": "Linux", + "players.installingFabric": "Установка Fabric", + "players.findingMods": "Поиск безопасных модов", + "players.installingMods": "Установка модов", + "players.troubleshooting": "Устранение неполадок", + "players.troubleshooting.uploadingLogs": "Загрузка журналов", + "players.troubleshooting.crashReports": "Сообщения о сбоях", + "players.updatingFabric": "Обновление Fabric", + "develop.title": "Руководства для разработчиков", + "develop.gettingStarted": "Начало работы", + "develop.gettingStarted.introduction": "Введение в Fabric и создание модов", + "develop.gettingStarted.devEnvSetup": "Настройка среды разработки", + "develop.gettingStarted.creatingProject": "Создание проекта", + "develop.gettingStarted.projectStructure": "Структура проекта", + "develop.gettingStarted.launchGame": "Запуск игры", + "develop.items": "Предметы", + "develop.items.potions": "Зелья", + "develop.entities": "Сущности", + "develop.entities.effects": "Эффекты состояния", + "develop.entities.damage-types": "Типы урона", + "develop.commands": "Команды", + "develop.commands.basics": "Создание команд", + "develop.commands.arguments": "Аргументы команд", + "develop.commands.suggestions": "Подсказки к командам", + "develop.rendering": "Отрисовка", + "develop.rendering.basicConcepts": "Основные концепции отрисовки", + "develop.rendering.drawContext": "Использование Drawing Context", + "develop.rendering.hud": "Отрисовка в HUD", + "develop.rendering.gui": "Интерфейсы и экраны", + "develop.rendering.gui.customScreens": "Собственные экраны", + "develop.rendering.gui.customWidgets": "Собственные виджеты", + "develop.rendering.particles": "Частицы", + "develop.rendering.particles.creatingParticles": "Создание своих частиц", + "develop.misc": "Прочие страницы", + "develop.misc.codecs": "Кодеки", + "develop.misc.events": "События", + "develop.sounds": "Звуки", + "develop.sounds.using-sounds": "Воспроизведение SoundEvents", + "develop.sounds.custom": "Создание своих звуков", + "github.edit": "Отредактировать эту страницу на GitHub" +} \ No newline at end of file diff --git a/versions/1.20.4/translated/ru_ru/website_translations.json b/versions/1.20.4/translated/ru_ru/website_translations.json new file mode 100644 index 000000000..f032c36bf --- /dev/null +++ b/versions/1.20.4/translated/ru_ru/website_translations.json @@ -0,0 +1,8 @@ +{ + "title": "Документация Fabric", + "home": "Главная", + "download": "Скачать", + "contribute": "Внести вклад", + "contribute.api": "Fabric API", + "version_switcher": "Сменить версию" +} \ No newline at end of file diff --git a/versions/1.20.4/translated/tr_tr/develop/index.md b/versions/1.20.4/translated/tr_tr/develop/index.md new file mode 100644 index 000000000..d1b7fb00d --- /dev/null +++ b/versions/1.20.4/translated/tr_tr/develop/index.md @@ -0,0 +1,12 @@ +--- +title: Geliştirici Rehberleri +description: Topluluk tarafından yazılmış geliştirici rehberlerimiz, development ortamını hazırlamaktan render ve network gibi daha karmaşık konulara kadar giden pek çok konuyu içerir. +--- + +# Geliştirici Rehberleri + +Topluluk tarafından yazılmış geliştirici rehberlerimiz, development ortamını hazırlamaktan render ve network gibi daha karmaşık konulara kadar giden pek çok konuyu içerir. + +Okunabilir bütün geliştirici rehberlerine kenar çubuğundan gözatabilirsiniz. Eğer daha özel bir şey arıyorsan üstteki arama çubuğuna istediğin şeyi yazıp bulabilirsin. + +Eğer Fabric Documentation'a yardım etmek istersen, kaynak kodu ve ilgili [katkıda bulunma kılavuzu](../contributing)nu [GitHub](https://github.com/FabricMC/fabric-docs)'da bulabilirsin diff --git a/versions/1.20.4/translated/uk_ua/contributing.md b/versions/1.20.4/translated/uk_ua/contributing.md new file mode 100644 index 000000000..8ee248ec3 --- /dev/null +++ b/versions/1.20.4/translated/uk_ua/contributing.md @@ -0,0 +1,181 @@ +# Правила внесення внесків до документації Fabric + +Цей вебсайт використовує [VitePress](https://vitepress.dev/) для генерації статичного HTML з різних файлів Markdown. Вам слід ознайомитися з розширеннями Markdown, які підтримує VitePress, [тут](https://vitepress.dev/guide/markdown#features). + +## Зміст + +- [Правила внесення внесків до документації Fabric](#fabric-documentation-contribution-guidelines) + - [Як зробити внесок](#how-to-contribute) + - [Внески до фреймворку](#contributing-framework) + - [Внески до контенту](#contributing-content) + - [Рекомендації щодо стилю](#style-guidelines) + - [Напрямки для розширення](#guidance-for-expansion) + - [Перевірка вмісту](#content-verification) + - [Завершення](#cleanup) + - [Переклад документації](#translating-documentation) + +## Як зробити внесок + +Рекомендується створювати нову гілку у своєму форку репозиторію для кожного запиту на злиття, який ви робите. Це полегшує управління кількома запитами на злиття одночасно. + +**Якщо ви хочете переглянути свої зміни локально, вам потрібно встановити [Node.js 18+](https://nodejs.org/en/)** + +Перш ніж виконувати будь-які з цих команд, переконайтеся, що ви виконали `npm install`, щоб встановити всі залежності. + +**Запуск сервера розробки:** + +Це дозволить вам переглянути свої зміни локально за адресою `localhost:3000` і автоматично перезавантажить сторінку при внесенні змін. + +```sh +npm run dev +``` + +**Побудова вебсайту:** + +Це скомпілює всі файли Markdown у статичні HTML-файли та помістить їх у папку `.vitepress/dist` + +```sh +npm run build +``` + +**Перегляд побудованого вебсайту:** + +Це запустить локальний сервер на порту 3000, який буде обслуговувати вміст, знайдений у папці `.vitepress/dist` + +```sh +npm run preview +``` + +## Внески до фреймворку + +Термін "фреймворк" належить до внутрішньої структури вебсайту. Будь-які запити на злиття, які модифікують фреймворк вебсайту, повинні мати мітку framework. + +Вам слід робити запити на злиття фреймворку лише після консультації з командою документації у [Discord-сервері Fabric](https://discord.gg/v6v4pMv) або через створення проблеми. + +**Примітка: Зміни в файлах бічної панелі та конфігурації панелі навігації не вважаються запитами на зміни в фреймворку.** + +## Внески до вмісту + +Внесок контенту є основним способом внесення у документацію Fabric. + +Весь вміст повинен відповідати нашим стилевим вимогам. + +### Рекомендації щодо стилю + +Всі сторінки на вебсайті документації Fabric повинні дотримуватися стилевого керівництва. Якщо ви не впевнені в чомусь, ви можете запитати у [Discord-сервері Fabric](https://discord.gg/v6v4pMv) або через обговорення на GitHub. + +Стилеве керівництво: + +1. На всіх сторінках повинен бути заголовок та опис на початку файлу. + + ```md + --- + title: This is the title of the page + description: This is the description of the page + authors: + - GitHubUsernameHere + --- + + # ... + ``` + +2. Якщо ви створюєте або модифікуєте сторінки з кодом, помістіть код у відповідне місце в довідковому модулі (розташованому у папці `/reference`). Потім використовуйте функціонал вставки коду, пропонований [VitePress](https://vitepress.dev/guide/markdown#import-code-snippets), або, якщо вам потрібно більше контролю, можете використовувати функцію [`transclude` з `markdown-it-vuepress-code-snippet-enhanced`](https://github.com/fabioaanthony/markdown-it-vuepress-code-snippet-enhanced). + + **Наприклад:** + + ```md + <<< @/reference/latest/src/main/java/com/example/docs/FabricDocsReference.java{15-21 java} + ``` + + Це вбудує рядки 15-21 файлу `FabricDocsReference.java` у довідковий модуль. + + Отриманий фрагмент коду буде виглядати таким чином: + + ```java + @Override + public void onInitialize() { + // This code runs as soon as Minecraft is in a mod-load-ready state. + // However, some things (like resources) may still be uninitialized. + // Proceed with mild caution. + + LOGGER.info("Hello Fabric world!"); + } + ``` + + Приклад функції `transclude`: + + ```md + @[code transcludeWith=#test_transclude](@/reference/.../blah.java) + ``` + + Це вбудує розділи `blah.java`, які позначені тегом `#test_transclude`. + + Наприклад: + + ```java + public final String test = "Bye World!" + + // #test_transclude + public void test() { + System.out.println("Hello World!"); + } + // #test_transclude + ``` + + Буде вбудовано лише код між тегами `#test_transclude`. + + ```java + public void test() { + System.out.println("Hello World!"); + } + ``` + +3. Вся оригінальна документація пишеться англійською мовою, дотримуючись американських правил граматики. Ви можете використовувати [LanguageTool](https://languagetool.org/) для перевірки граматики під час набору тексту, але не переживайте занадто за це. Наша команда документації перегляне та виправить граматичні помилки під час етапу завершення. Проте, спроба правильно сформулювати текст відразу може зекономити наш час. + +4. Якщо ви створюєте новий розділ, ви повинні створити нову бічну панель у папці `.vitepress/sidebars` та додати її до файлу `config.mts`. Якщо вам потрібна допомога з цим, будь ласка, запитайте у каналі `#docs` у [Discord-сервері Fabric](https://discord.gg/v6v4pMv). + +5. При створенні нової сторінки ви повинні додати її до відповідної бічної панелі у папці `.vitepress/sidebars`. Знову ж таки, якщо вам потрібна допомога, запитайте у каналі `#docs` у [Discord-сервері Fabric](https://discord.gg/v6v4pMv). + +6. Будь-які зображення повинні бути розміщені у відповідному місці у папці `/assets`. + +7. ⚠️ **При посиланні на інші сторінки використовуйте відносні посилання.** ⚠️ + + Це через систему версіювання, яка буде обробляти посилання, щоб додати значення версії. Якщо ви використовуєте абсолютні посилання, значення версії не буде додано до посилання. + + Наприклад, для сторінки у папці `/players`, щоб посилатися на сторінку `installing-fabric`, що знаходиться у `/players/installing-fabric.md`, потрібно зробити так: + + ```md + [Це посилання на іншу сторінку](./installing-fabric) + ``` + + Ви **НЕ ПОВИННІ** робити наступне: + + ```md + [Це посилання на іншу сторінку](/players/installing-fabric) + ``` + +Всі внески вмісту проходять три етапи: + +1. Напрямки для розширення (якщо можливо) +2. Перевірка вмісту +3. Завершення (виправлення граматики й так далі) + +### Напрямки для розширення + +Якщо команда документації вважає, що ви можете розширити свій запит на злиття, член команди додасть мітку розширення до вашого запиту на злиття поряд із коментарем, пояснюючи, що, на їхню думку, можна було б розширити. Якщо ви згодні з пропозицією, ви можете розширити свій запит на злиття. + +**Не відчувайте тиску на розширення свого запиту на злиття.** Якщо ви не хочете розширювати свій запит на злиття, ви можете просто попросити видалити мітку розширення. + +Якщо ви не хочете розширювати свій запит на злиття, але ви згодні, щоб хтось інший розширив його в майбутньому, найкраще створити питання на [сторінці запитів](https://github.com/FabricMC/fabric-docs/issues) та пояснити, що, на вашу думку, можна було б розширити. + +### Перевірка вмісту + +Всі запити на злиття, які додають вміст, проходять перевірку вмісту. Це найважливіший етап, оскільки він забезпечує точність контенту та відповідність стилевому керівництву документації Fabric. + +### Завершення + +На цьому етапі команда документації виправить будь-які граматичні помилки та внесе будь-які інші зміни, які вони вважають необхідними, перед злиттям запиту на злиття! + +## Переклад документації + +Якщо ви бажаєте перекласти документацію на свою мову, ви можете це зробити на [сторінці Fabric Crowdin](https://crowdin.com/project/fabricmc). diff --git a/versions/1.20.4/translated/uk_ua/develop/commands/suggestions.md b/versions/1.20.4/translated/uk_ua/develop/commands/suggestions.md new file mode 100644 index 000000000..a627f2683 --- /dev/null +++ b/versions/1.20.4/translated/uk_ua/develop/commands/suggestions.md @@ -0,0 +1,45 @@ +--- +title: Пропозиції команд +description: Дізнайтеся як пропонувати користувачам можливі значення аргументу команди. +authors: + - IMB11 +--- + +# Пропозиції команд + +Minecraft має потужну систему пропозицій команд, що використовується у багатьох місцях, таких як команда `/give`. Ця система дозволяє пропонувати гравцю значення аргументу, які вони можуть вибрати, що є гарним засобом створення більш зручних та ергономічних команд. + +## Постачальники пропозицій + +Клас `SuggestionProvider` використовується для створення списку пропозицій, які будуть надіслані гравцю. Постачальник пропозицій - це функція, що приймає об'єкти `CommandContext` та `SuggestionBuilder`, та повертає об'єкт `Suggestions`. `SuggestionProvider` повертає об'єкт `CompletableFuture` тому, що пропозиції можуть бути не доступні відразу. + +## Використання постачальників пропозицій + +Для використання постачальника пропозицій треба викликати метод `suggests` в об'єкта `ArgumentBuilder`. Цей метод приймає об'єкт `SuggestionProvider` та повертає свій `ArgumentBuilder` з доданим постачальником пропозицій. + +@[code java transcludeWith=:::9 highlight={4}](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +## Вбудовані постачальники пропозицій + +Minecraft надає декілька вбудованих постачальників пропозицій: + +| Постачальник | Опис | +| ----------------------------------------- | -------------------------------------------------------------- | +| `SuggestionProviders.SUMMONABLE_ENTITIES` | Пропонує всі істоти, що можуть бути викликані. | +| `SuggestionProviders.AVAILABLE_SOUNDS` | Пропонує всі звуки, що можуть бути зіграні. | +| `LootCommand.SUGGESTION_PROVIDER` | Пропонує всі доступні таблиці луту. | +| `SuggestionProviders.ALL_BIOMES` | Пропонує всі доступні біоми. | + +## Створення користувальницького постачальника пропозицій + +Якщо вбудовані постачальники пропозицій не підходять, ви можете створити свій постачальник. Для цього треба створити клас, який реалізує інтерфейс `SuggestionProvider` і перевизначає метод `getSuggestions`. + +Для цього прикладу ми зробимо постачальник, який пропонує імена гравців на сервері. + +@[code java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/command/PlayerSuggestionProvider.java) + +Щоб скористатися цим постачальником, треба просто передати його об'єкт у метод `.suggests` у `ArgumentBuilder`. + +Звісно, що постачальники пропозицій можуть бути складнішими, оскільки вони також можуть зчитувати контекст команди та надавати пропозиції на основі її стану - наприклад, аргументи, що вже були надані. + +Це може також зчитувати інвентар гравця та пропонувати предмети, або істот, які неподалік від гравця. diff --git a/versions/1.20.4/translated/uk_ua/index.md b/versions/1.20.4/translated/uk_ua/index.md new file mode 100644 index 000000000..a1601905f --- /dev/null +++ b/versions/1.20.4/translated/uk_ua/index.md @@ -0,0 +1,27 @@ +--- +title: Документація Fabric +description: Офіційна документація для Fabric, інструментарію модифікацій для Minecraft. +layout: home +hero: + name: Документація Fabric + tagline: Офіційна документація для Fabric, інструментарію модифікацій для Minecraft. +features: + - title: Developer Guides + icon: 🛠️ + details: Our curated developer guides, written by the community, span a wide range of topics from setting up a development environment to more advanced topics, such as rendering and networking. + link: ./develop/index + linkText: Розпочати + - title: Посібник для гравців + icon: 📚 + details: Ви гравець що хоче використовувати моди для Fabric? Наш посібник для гравців допоможе вам. Цей посібник допоможе вам в завантаженні, використовувати та виправляти неполадки модів Fabric. + link: ./players/index + linkText: Читати більше +--- + +
+ +## Бажаєте внести свій вклад? + +If you want to contribute to the Fabric Documentation, you can find the source code on [GitHub](https://github.com/FabricMC/fabric-docs), and the relevant [contribution guidelines](./contributing). + +
diff --git a/versions/1.20.4/translated/uk_ua/players/faq.md b/versions/1.20.4/translated/uk_ua/players/faq.md new file mode 100644 index 000000000..9aa179843 --- /dev/null +++ b/versions/1.20.4/translated/uk_ua/players/faq.md @@ -0,0 +1,31 @@ +--- +title: Поширені питання +description: Поширені запитання для гравців і адміністраторів серверів, пов’язані з Fabric. +--- + +# Поширені питання + +Є багато запитань, які часто задають, тому ми склали їх список тут. + +## Загальні питання + +### Які версії Minecraft підтримує Fabric? + +Офіційно Fabric підтримує всі версії Minecraft починаючи зі снапшоту `18w43b` та релізу `1.14` та вище. + +### Де я можу завантажити моди для Fabric? + +:::info +Ви завжди маєте перевіряти чи моди з надійного джерела. Щоб дізнатися більше, перегляньте інструкцію [Пошук надійних модів](./finding-mods). +::: + +Більшість авторів публікують свої моди на [Modrinth](https://modrinth.com/mods?g=categories:%27fabric%27) та [CurseForge](https://www.curseforge.com/minecraft/search?class=mc-mods&gameVersionTypeId=4), але деякі автори викладають їх на свої веб-сайти або інші платформи, такі як репозиторії GitHub. + +### Де я можу знайти готові модпаки для Fabric? + +Ви можете знайти готові мод-паки для Fabric на платформах, таких як: + +- [Modrinth](https://modrinth.com/modpacks?g=categories:%27fabric%27) +- [CurseForge](https://www.curseforge.com/minecraft/search?class=modpacks&gameVersionTypeId=4) +- [Feed The Beast](https://www.feed-the-beast.com/ftb-app) +- [Technic](https://www.technicpack.net/modpacks) diff --git a/versions/1.20.4/translated/uk_ua/players/finding-mods.md b/versions/1.20.4/translated/uk_ua/players/finding-mods.md new file mode 100644 index 000000000..4613bdf9a --- /dev/null +++ b/versions/1.20.4/translated/uk_ua/players/finding-mods.md @@ -0,0 +1,34 @@ +--- +title: Пошук надійних модів +description: Інструкція із пошуку модів Fabric за допомогою надійних джерел. +authors: + - IMB11 +--- + +# Пошук надійних модів + +По-перше, довіра суб’єктивна, і ви завжди повинні керуватися власним судженням, завантажуючи моди. Однак є деякі речі, які ви можете зробити, щоб допомогти вам знайти надійні моди. + +## 1. Використовуйте джерело, яке заслуговує довіри + +Більшість авторів публікують свої моди на [Modrinth](https://modrinth.com/mods?g=categories:%27fabric%27) та [CurseForge](https://www.curseforge.com/minecraft/search?class=mc-mods&gameVersionTypeId=4). + +Ці веб-сайти перевіряють, чи моди є такими, якими вони є, і що вони не містять шкідливого коду. Ви також можете повідомити про шкідливі моди на цих веб-сайтах, і вони відносно швидко вживуть заходів. + +## 2. Перевірте в інших! + +Якщо ви завантажуєте мод з джерела, яке, як відомо, не заслуговує довіри, вам слід перевірити в інших, чи завантажували вони модифікацію раніше з того місця, звідки ви завантажуєте, і чи виникали у них проблеми з цим. + +Якщо ви сумніваєтесь, ви завжди можете запитати в [Діскорд сервері Fabric](https://discord.gg/v6v4pMv) в каналі `#player-support`. + +## 3. Уникайте поширених сайтів з вірусами! + +:::info +Подібні сайти можуть бути не очевидними для всіх. Якщо ви не впевнені, ви можете запитити думки інших або покладатися лише на перевірені джерела, такі як Modrinth та Curseforge. +::: + +Існує багато веб-сайтів, які стверджують, що мають моди для Minecraft, але насправді це лише сайти з вірусами. Вам слід оминати подібні сайти. + +Ви можете використовувати антивіруси або вебсайти, такі як [Windows Defender](https://www.microsoft.com/en-us/windows/comprehensive-security) або [VirusTotal](https://www.virustotal.com/) щоб перевіряти завантажені моди. Але не покладайтеся повністю на них, тому що вони не завжди коректні. + +Знову ж таки, якщо ви сумніваєтеся, ви можете запитати в [Діскорд сервері Fabric](https://discord.gg/v6v4pMv) в каналі `#player-support`. diff --git a/versions/1.20.4/translated/uk_ua/players/index.md b/versions/1.20.4/translated/uk_ua/players/index.md new file mode 100644 index 000000000..d7eea5cb3 --- /dev/null +++ b/versions/1.20.4/translated/uk_ua/players/index.md @@ -0,0 +1,12 @@ +--- +title: Посібник для гравців +description: Посібник по встановленню та використанню Fabric для гравців та адміністраторів серверів. +--- + +# Посібник для гравців + +Ця секція документації Fabric присвячена гравцям та адміністраторам серверів які хочуть навчитися встановлювати, використовувати та виправляти неполадки Fabric. + +Перегляньте список усіх доступних інструкцій на бічній панелі. + +Якщо у вас виникли проблеми, повідомте про них [на GitHub](https://github.com/FabricMC/fabric-docs) або зверніться по допомогу в [Діскорд сервері Fabric](https://discord.gg/v6v4pMv) у канали `#player-support` або `#server-admin-support`. diff --git a/versions/1.20.4/translated/uk_ua/players/installing-fabric.md b/versions/1.20.4/translated/uk_ua/players/installing-fabric.md new file mode 100644 index 000000000..1ffeeffe8 --- /dev/null +++ b/versions/1.20.4/translated/uk_ua/players/installing-fabric.md @@ -0,0 +1,55 @@ +--- +title: Встановлення Fabric +description: Покрокова інструкція з встановлення Fabric. +authors: + - IMB11 +--- + +# Встановлення Fabric + +Ця інструкція допоможе вам встановити Fabric для офіційного лаунчера Minecraft. + +Для неофіційних лаунчерів слід ознайомитися з їх документацією. + +## 1. Завантаження інсталятора Fabric + +Ви можете завантажити Інсталятор Fabric з [вебсайту Fabric](https://fabricmc.net/use/). + +Якщо ви користуєтеся Windows, завантажте версію `.exe` (`Download For Windows`), оскільки для цього не потрібно інсталювати Java у вашій системі. Натомість він використовує Java, яка постачається з офіційним лаунчером. + +Для macOS та Linux вам слід завантажити `jar` версію. Іноді перед цим кроком потрібно встановити Java. + +## 2. Запуск інсталятора Fabric + +:::warning +Спочатку закрийте Minecraft та його лаунчер перед встановленням. +::: + +:::details Інформація для користувачів MacOS + +У macOS вам може знадобитися клацнути правою кнопкою миші файл `.jar` у каталозі завантажень і натиснути `Відкрити`, щоб запустити його. + +![Інсталятор Fabric із виділеним пунктом «Встановити»](/assets/players/installing-fabric/macos-downloads.png) + +Коли вас запитають «Ви впевнені, що хочете відкрити?», знову натисніть `Відкрити`. +::: + +Відкривши інсталятор, ви повинні побачити такий екран: + +![Інсталятор Fabric із виділеним пунктом «Встановити»](/assets/players/installing-fabric/installer-screen.png) + +Щоб установити Fabric, просто виберіть свою версію гри зі спадного меню та натисніть `Встановити`. + +**Переконайтеся, що встановлено прапорець «Створити профіль».** + +## 3. Готово! + +Після завершення встановлення ви можете відкрити лаунчер Minecraft і вибрати профіль Fabric зі спадного списку в нижньому лівому куті та натиснути «Грати»! + +![Лаунчер Minecraft з вибраним профілем Fabric](/assets/players/installing-fabric/launcher-screen.png) + +## Наступні кроки + +Тепер коли ви встановили Fabric, ви можете додавати моди до своєї гри! Щоб дізнатися більше, перегляньте інструкцію [Пошук надійних модів](./finding-mods). + +Якщо під час виконання цієї інструкції у вас виникнуть проблеми, ви можете звернутися за допомогою в [Діскорд сервері Fabric](https://discord.gg/v6v4pMv) в каналі `#player-support`. diff --git a/versions/1.20.4/translated/uk_ua/players/installing-mods.md b/versions/1.20.4/translated/uk_ua/players/installing-mods.md new file mode 100644 index 000000000..553bc4c87 --- /dev/null +++ b/versions/1.20.4/translated/uk_ua/players/installing-mods.md @@ -0,0 +1,67 @@ +--- +title: Встановлення модів +description: Покрокова інструкція по установці модів для Fabric. +authors: + - IMB11 +--- + +# Встановлення модів + +Ця інструкція допоможе вам встановити моди для Fabric якщо ви використовуєте лаунчер Minecraft. + +Для неофіційних лаунчерів слід ознайомитися з їх документацією. + +## 1. Завантаження модів + +:::warning +Ви повинні завантажувати моди тільки з джерел, яким ви довіряєте. Додаткову інформацію про пошук модів ви можете знайти в даній інструкції: [Пошук модів](./finding-mods). +::: + +Більшість модів також потребує Fabric API, що може бути завантажено з [Modrinth](https://modrinth.com/mod/fabric-api) або [CurseForge](https://curseforge.com/minecraft/mc-mods/fabric-api). + +При завантаженні модів переконайтеся, що: + +- Вони працюють з версією Minecraft, на якій ви хочете грати. Наприклад, мод що працює на версії 1.20, може не працювати на версії 1.20.2. +- Вони призначені для Fabric, а не для іншого завантажувача модів. +- Вони призначені для правильної версії Minecraft (Java Edition). + +## 2. Перемістіть мод в теку `mods` + +Папку mods можна знайти в наступних місцях для кожної операційної системи. + +Зазвичай ви можете вставити ці шляхи в адресний рядок провідника файлів, щоб швидко перейти до папки. + +::: code-group + +```:no-line-numbers [Windows] +%appdata%\.minecraft\mods +``` + +```:no-line-numbers [macOS] +~/Library/Application Support/minecraft/mods +``` + +```:no-line-numbers [Linux] +~/.minecraft/mods +``` + +::: + +Коли ви знайдете папку `mods`, ви можете перемістити туди файли `.jar` мода. + +![Встановлені моди в теці mods](/assets/players/installing-mods.png) + +## 3. Готово! + +Після встановлення модів в теку `mods` ви можете відкрити лаунчер Minecraft і вибрати профіль Fabric зі спадного списку в нижньому лівому куті та натиснути «Грати»! + +![Лаунчер Minecraft з вибраним профілем Fabric](/assets/players/installing-fabric/launcher-screen.png) + +## Усунення проблем + +Якщо під час виконання цієї інструкції у вас виникнуть проблеми, ви можете звернутися за допомогою в [Діскорд сервері Fabric](https://discord.gg/v6v4pMv) в каналі `#player-support`. + +Ви також можете спробувати вирішити проблему самостійно, прочитавши сторінки усунення несправностей: + +- [Звіти про збої](./troubleshooting/crash-reports) +- [Поширення логів](./troubleshooting/uploading-logs) diff --git a/versions/1.20.4/translated/uk_ua/players/updating-fabric.md b/versions/1.20.4/translated/uk_ua/players/updating-fabric.md new file mode 100644 index 000000000..09ebdc091 --- /dev/null +++ b/versions/1.20.4/translated/uk_ua/players/updating-fabric.md @@ -0,0 +1,41 @@ +--- +title: Оновлення Fabric +description: Покрокова інструкція з оновлення Fabric. +authors: + - IMB11 + - modmuss50 +--- + +# Оновлення Fabric + +Ця інструкція допоможе вам оновити Fabric для офіційного лаунчера Minecraft. + +Для неофіційних лаунчерів слід ознайомитися з їх документацією. + +Процес оновлення Fabric дуже схожий на процес встановлення Fabric, тому частина цього посібника буде такою самою, як інструція [Встановлення Fabric](./installing-fabric). + +## Чому я маю оновлювати Fabric Loader? + +Нові моди можуть потребувати новішу версію Fabric Loader для роботи, тому важливо мати актуальну версію, щоб мати можливість використовувати найновіші моди. + + + + + +Щоб оновити Fabric, переконайтеся що версія гри та версія завантажувача правильні, а потім натисніть `Встановити`. + +**Під час запуску інсталятора обов’язково зніміть прапорець «Створити профіль», інакше буде створено новий профіль, який у цьому випадку нам не потрібен.** + +## 3. Відкрийте профіль в лаунчері Minecraft + +Після завершення встановлення ви можете відкрити лаунчер Minecraft і перейти на вкладку `Встановлення`. Ви повинні перейти до свого профілю Fabric і відкрити екран редагування. + +Замініть версію новою версією Fabric Loader, яку ви щойно встановили, і натисніть `Зберегти`. + +![Оновлення версії Fabric Loader у лаунчері Minecraft](/assets/players/updating-fabric.png) + +## 4. Готово! + +Виконавши дані кроки, ви можете повернутися на вкладку `Грати`, вибрати профіль Fabric зі спадного меню в нижньому лівому куті та натиснути кнопку `Грати`! + +Якщо під час виконання цієї інструкції у вас виникнуть проблеми, ви можете звернутися за допомогою в [Діскорд сервері Fabric](https://discord.gg/v6v4pMv) в каналі `#player-support`. diff --git a/versions/1.20.4/translated/uk_ua/sidebar_translations.json b/versions/1.20.4/translated/uk_ua/sidebar_translations.json new file mode 100644 index 000000000..8088687da --- /dev/null +++ b/versions/1.20.4/translated/uk_ua/sidebar_translations.json @@ -0,0 +1,46 @@ +{ + "players.title": "Посібник для гравців", + "players.faq": "Поширені питання", + "players.installingJava": "Встановлення Java", + "players.installingJava.windows": "Windows", + "players.installingJava.macOS": "macOS", + "players.installingJava.linux": "Linux", + "players.installingFabric": "Встановлення Fabric", + "players.findingMods": "Пошук надійних модів", + "players.installingMods": "Встановлення модів", + "players.troubleshooting": "Усунення проблем", + "players.troubleshooting.uploadingLogs": "Поширення логів", + "players.troubleshooting.crashReports": "Звіти про збої", + "players.updatingFabric": "Оновлення Fabric", + "develop.title": "Посібник для розробників", + "develop.gettingStarted": "Перші кроки", + "develop.gettingStarted.introduction": "Знайомство з Fabric та створенням модів", + "develop.gettingStarted.devEnvSetup": "Налаштовування середовища розробки", + "develop.gettingStarted.creatingProject": "Створення проєкту", + "develop.gettingStarted.projectStructure": "Структура проєкту", + "develop.gettingStarted.launchGame": "Запуск гри", + "develop.items": "Предмети", + "develop.items.potions": "Зілля", + "develop.entities": "Істоти", + "develop.entities.effects": "Ефекти", + "develop.entities.damage-types": "Типи ушкоджень", + "develop.commands": "Команди", + "develop.commands.basics": "Створення команд", + "develop.commands.arguments": "Аргументи", + "develop.commands.suggestions": "Пропозиції", + "develop.rendering": "Рендеринг", + "develop.rendering.basicConcepts": "Базові концепції рендерингу", + "develop.rendering.drawContext": "Використання DrawContext", + "develop.rendering.hud": "Рендеринг інтерфейсу гри", + "develop.rendering.gui": "Графічні інтерфейси та екрани", + "develop.rendering.gui.customScreens": "Користувальницькі екрани", + "develop.rendering.gui.customWidgets": "Користувальницькі віджети", + "develop.rendering.particles": "Частинки", + "develop.rendering.particles.creatingParticles": "Створення власних частинок", + "develop.misc": "Інші сторінки", + "develop.misc.codecs": "Кодеки", + "develop.misc.events": "Івенти", + "develop.sounds": "Звуки", + "develop.sounds.using-sounds": "Відтворення звуків", + "develop.sounds.custom": "Створення користувальницьких звуків" +} \ No newline at end of file diff --git a/versions/1.20.4/translated/vi_vn/contributing.md b/versions/1.20.4/translated/vi_vn/contributing.md new file mode 100644 index 000000000..19cd06caa --- /dev/null +++ b/versions/1.20.4/translated/vi_vn/contributing.md @@ -0,0 +1,176 @@ +# Tài Liệu Hướng Dẫn Cách Đóng Góp Fabric + +Trang này sử dụng [VitePress](https://vitepress.dev/) để tạo văn bản HTML tĩnh từ nhiều tệp markdown khác nhau. Bạn nên làm quen với những tiện ích markdown mà VitePress hỗ trợ tại [đây](https://vitepress.dev/guide/markdown#features). + +## Mục Lục + +- [Tài Liệu Hướng Dẫn Cách Đóng Góp Fabric](#tài-liệu-hướng-dẫn-cách-đóng-góp-fabric) + - [Cách Đóng Góp](#cách-đóng-góp) + - [Đóng Góp Framework](#đóng-góp-framework) + - [Đóng Góp Nội Dung](#đóng-góp-nội-dung) + - [Phong Cách Ghi Tài Liệu](#phong-cách-ghi-tài-liệu) + - [Hướng Dẫn Mở Rộng](#hướng-dẫn-mở-rộng) + - [Xác Minh Nội Dung](#xác-minh-nội-dung) + - [Làm Gọn](#làm-gọn) + +## Cách Đóng Góp + +Chúng tôi khuyên bạn nên tạo một nhánh mới trên bản fork của kho lưu trữ cho mỗi lần tạo pull request. Điều này sẽ giúp bạn dễ quản lý khi thực hiện nhiều pull request cùng một lúc. + +**Nếu bạn muốn xem trước những thay đổi bạn tạo trên máy nội bộ của bạn, bạn cần phải cài đặt [Node.js 18+](https://nodejs.org/en/)** + +Trước khi chạy bất kì lệnh nào, hãy đảm bảo chạy lệnh `npm install` để cài đầy đủ các gói hỗ trợ. + +**Chạy máy chủ phát triển nội bộ:** + +Điều này sẽ cho phép bạn xem trước các thay đổi bạn đã làm trên thiết bị của bạn tại địa chỉ `localhost:3000` và sẽ tự động tải lại trang khi bạn thực hiện các thay đổi. + +```sh +npm run dev +``` + +**Xây dựng trang web:** + +Lệnh dưới đây sẽ biên dịch toàn bộ tập tin markdown thành những tệp HTML tĩnh và đặt chúng trong `.vitepress/dist` + +```sh +npm run build +``` + +**Xem trước trang web đã tạo:** + +Lệnh dưới sẽ khởi động một máy chủ nội bộ trên cổng 3000 để hiển thị nội dụng được tìm thấy ở `.vitepress/dist` + +```sh +npm run preview +``` + +## Đóng Góp Framework + +Framework ám chỉ cấu trúc bên trong của một trang web, bất kì pull request nào chỉnh sử framework của trang web nên được đánh dấu với nhãn `framework`. + +Bạn thật sự chỉ nên tạo các pull request về framework sau khi tham khảo ý kiến của đội ngũ biên soạn tài liệu trong [Discord Fabric](https://discord.gg/v6v4pMv) hoặc thông qua trang issue. + +**Chú ý: Việc chỉnh sửa các tập tin thanh bên và thanh định hướng không được tính là một pull request của framework.** + +## Đóng Góp Nội Dung + +Đóng góp nội dung là cách chính để đóng góp vào Tài liệu Fabric. + +Tất cả các nội dung nên theo phong cách ghi tài liệu của chúng tôi. + +### Phong Cách Ghi Tài Liệu + +Tất cả các trang trên trang web bộ tài liệu Fabric nên thống nhất về một phong cách ghi. Nếu bạn không chắc điều gì, bạn có thể hỏi tại [Discord Fabric](https://discord.gg/v6v4pMv) hoặc thông qua mục Discussions của Github. + +Quy định về phong cách như sau: + +1. Tất cả trang phải có tiêu đề và dòng mô tả theo định dạng frontmatter. + + ```md + --- + title: Đây là tiêu đề của trang + description: Đây là dòng mô tả của trang + authors: + - TênNgườiDùngGithub + --- + + # ... + ``` + +2. Nếu bạn muốn tạo hoặc chỉnh sửa đoạn mã của trang, hãy đặt đoạn mã ở một vị trí thích hợp ở trong bản mod có liên quan (được đặt ở thư mục `/reference` của kho lưu trữ). Sau đó, sử dụng [tính năng tạo định nghĩa cho mã được cung cấp bởi VitePress](https://vitepress.dev/guide/markdown#import-code-snippets) để nhúng mã, hoặc nếu bạn cần nhiều sự kiểm soát hơn, bạn có thể sử dụng tính năng transclude từ [`markdown-it-vuepress-code-snippet-enhanced`](https://github.com/fabioaanthony/markdown-it-vuepress-code-snippet-enhanced). + + **Ví dụ:** + + ```md + <<< @/reference/latest/src/main/java/com/example/docs/FabricDocsReference.java{15-21 java} + ``` + + Điều này sẽ nhúng mã từ dòng 15 đến 21 của tệp `FabricDocsReference.java` trong tập tin mod có liên quan. + + Kết quả sau khi tạo định nghĩa cho mã sẽ như này: + + ```java + @Override + public void onInitialize() { + // This code runs as soon as Minecraft is in a mod-load-ready state. + // However, some things (like resources) may still be uninitialized. + // Proceed with mild caution. + + LOGGER.info("Hello Fabric world!"); + } + ``` + + **Ví Dụ Về Transclude:** + + ```md + @[code transcludeWith=#test_transclude](@/reference/.../blah.java) + ``` + + Mã trên sẽ nhúng phần được chọn của `blah.java` mà đã được đánh dấu với nhãn `#test_transclude`. + + Ví dụ: + + ```java + public final String test = "Bye World!" + + // #test_transclude + public void test() { + System.out.println("Hello World!"); + } + // #test_transclude + ``` + + Chỉ có phần mã ở giữa nhãn `#test_transclude` mới được nhúng. + + ```java + public void test() { + System.out.println("Hello World!"); + } + ``` + +3. Chúng tôi tuân theo ngữ pháp tiếng Anh. Mặc dù bạn cũng có thể sử dụng công cụ [LanguageTool](https://languagetool.org/) để kiểm tra ngữ pháp khi viết, nhưng đừng quá căng thẳng về điều đó. Đội ngũ biên soạn của chúng tôi sẽ luôn xem xét và sửa lại chúng trong bước làm gọn. Tuy vậy, bạn nên dành gia một chút thời gian kiểm tra từ đầu và điều đó giúp chúng tôi tiết kiệm thêm thời gian. + +4. Nếu bạn đang tạo một mục mới, bạn nên tạo thêm một thanh bên mới trong thư mục `.vitepress/sidebars` và thêm nó trong tệp `config.mts`. Nếu bạn cần sự hỗ trợ để làm điều này, vui lòng hỏi trong kênh `#wiki` ở [Discord Fabric](https://discord.gg/v6v4pMv). + +5. Khi tạo một trang mới, bạn nên thêm nó vào thanh bên nằm ở thư mục `.vitepress/sidebars`. Một lần nữa, nếu bạn cần sự trợ giúp, hãy hỏi ở kênh `#wiki` trong Discord Fabric. + +6. Tât cả hình ảnh nên được đặt ở thư mục `/assets` phù hợp. + +7. ⚠️ **Khi liên kết các trang khác, hãy sử dụng liên kết tương đối.** ⚠️ + + Điều này là do hệ thống lập phiên bản tại chỗ, sẽ xử lý các liên kết để thêm phiên bản trước. Nếu bạn sử dụng liên kết tuyệt đối, số phiên bản sẽ không được thêm vào liên kết. + + Ví dụ, đối với trang ở thư mục `/players`, để liên kết trang `installing-fabric` được tạo ở `/players/installing-fabric.md`, bạn sẽ phải làm như sau: + + ```md + [Đây là liên kết dẫn đến trang khác](./installing-fabric) + ``` + + Bạn **KHÔNG ĐƯỢC** làm như sau: + + ```md + [Đây là liên kết dẫn đến trang khác](/players/installing-fabric) + ``` + +Tất cả sự đóng góp nội dung sẽ lần lượt đi qua ba bước: + +1. Hướng dẫn mở rộng (nếu có thể) +2. Xác Minh Nội Dung +3. Làm gọn (ngữ pháp, ...) + +### Hướng Dẫn Mở Rộng + +Nếu đội ngũ biên soạn nghĩ rằng bạn có thể mở rộng thêm trong pull request của bạn, một thành viên của đội ngũ sẽ thêm nhãn `expansion` cho pull request của bạn cùng với một bình luận giải thích những thứ mà bạn có thể mở rộng thêm nữa. Nếu bạn đồng ý sự đề xuất này, bạn có thể mở rộng thêm pull request của bạn. + +**Cũng đừng cảm thấy quá áp lực khi mở rộng thêm pull request của bạn.** Nếu bạn không muốn mở rộng thêm, bạn có thể yêu cầu xoá nhãn `expansion`. + +Nếu bạn không muốn mở rộng thêm pull request của bạn, nhưng bạn sẵn sàng cho người khác làm điều đó vào lúc sau, điều tốt nhất là hãy tạo một issue trong [trang Issues](https://github.com/FabricMC/fabric-docs/issues) và giải thích những gì mà bạn nghĩ có thể mở rộng thêm. + +### Xác Minh Nội Dung + +Tất cả pull requests mà thêm nội dung đều sẽ trải qua bước xác minh nội dung, đây là bước quan trọng nhất vì nó đảm bảo tất cả nội dung phải chính xác và tuân theo quy định về phong cách ghi Tài liệu Fabric. + +### Làm Gọn + +Đây là giai đoạn mà đội ngũ biên soạn sẽ sửa chữa bất kỳ lỗi ngữ pháp nào được tìm thấy và thực hiện bất kỳ thay đổi nào khác mà họ cho là cần thiết trước khi hợp nhất pull request! diff --git a/versions/1.20.4/translated/vi_vn/develop/commands/arguments.md b/versions/1.20.4/translated/vi_vn/develop/commands/arguments.md new file mode 100644 index 000000000..70f12b2e7 --- /dev/null +++ b/versions/1.20.4/translated/vi_vn/develop/commands/arguments.md @@ -0,0 +1,56 @@ +--- +title: Tham Số Câu Lệnh +description: Học cách tạo ra câu lệnh với tham số phức tạp. +--- + +# Tham Số Câu Lệnh + +Hầu hết các câu lệnh đều có tham số. Nhiều khi tham số đó không bắt buộc, bạn không cần phải đưa vào câu lệnh nhưng nó vẫn chạy. Một node có thể có nhiều loại tham số, nhưng bạn nên tránh xảy ra trường hợp kiểu dữ liệu của tham số không rõ. + +@[code lang=java highlight={3} transcludeWith=:::4](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +Trong trường hợp này, sau `/argtater`, bạn cần đưa ra một số nguyên làm tham số. Chẳng hạn, khi bạn chạy `/argtater 3`, bạn sẽ nhận được thông báo `Called /argtater with value = 3`. Khị bạn nhập `/argtater` mà không đưa ra tham số, câu lệnh trên sẽ không chạy được. + +Chúng ta có thể thêm vào đối số không bắt buộc thứ hai: + +@[code lang=java highlight={3,13} transcludeWith=:::5](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +Giờ đây, bạn có thể nhập một hoặc hai số nguyên làm tham số. Nếu bạn đưa vào một số nguyên, bạn sẽ nhận được thông báo với một giá trị. Nếu là hai số nguyên, thông báo sẽ đưa ra hai giá trị. + +Có thể bạn thấy việc viết hai quy trình xử lý dữ liệu giống nhau là không cần thiết. Ta có thể tạo một method sử dụng trong cả hai tham số. + +@[code lang=java highlight={3,5,6,7} transcludeWith=:::6](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +## Kiểu Tham Số Tùy Chỉnh + +Nếu bạn không tìm thấy kiểu tham số bạn cần trong vanilla, bạn có thể tự tạo kiểu của riêng mình. Bạn cần tạo một class mà kế thừa interface `ArgumentType`, với `T` là kiểu tham số. + +Bạn cần phải thêm method `parse` để xử lý tham số từ kiểu xâu ký tự sang kiểu tham số mà bạn cần. + +Giả sử bạn cần một kiểu tham số cho ra `BlockPos` khi người dùng nhập: `{x, y, z}` + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/command/BlockPosArgumentType.java) + +### Đăng Ký Kiểu Tham Số Tùy Chỉnh + +:::warning +Câu lệnh của bạn sẽ không hoạt động nếu bạn không đăng ký kiểu tham số tùy chỉnh trên cả máy chủ lẫn máy khách! +::: + +Bạn có thể đăng ký kiểu tham số tùy chỉnh trong khi mod của bạn đang khởi động trong method `onInitialize`, sử dụng class `ArgumentTypeRegistry`: + +@[code lang=java transcludeWith=:::11](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +### Sử Dụng Kiểu Tham Số Tùy Chỉnh + +Bạn có thể sử dụng kiểu tham số tùy chỉnh trong một câu lệnh bằng cách đưa một instance của nó vào method `.argument` khi đang xây dựng một câu lệnh. + +@[code lang=java transcludeWith=:::10 highlight={3}](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +Thử chạy câu lệnh xem kiểu tham số của chúng ta có hoạt động không: + +![Tham số không hợp lệ](/assets/develop/commands/custom-arguments_fail.png) + +![Tham số hợp lệ](/assets/develop/commands/custom-arguments_valid.png) + +![Kết quả câu lệnh](/assets/develop/commands/custom-arguments_result.png) diff --git a/versions/1.20.4/translated/vi_vn/index.md b/versions/1.20.4/translated/vi_vn/index.md new file mode 100644 index 000000000..4e9e55f79 --- /dev/null +++ b/versions/1.20.4/translated/vi_vn/index.md @@ -0,0 +1,27 @@ +--- +title: Tài Liệu Fabric +description: Tài liệu chính thức của Fabric, một công cụ modding dành cho Minecraft. +layout: home +hero: + name: Tài Liệu Fabric + tagline: Tài liệu chính thức của Fabric, một công cụ modding dành cho Minecraft. +features: + - title: Developer Guides + icon: 🛠️ + details: Our curated developer guides, written by the community, span a wide range of topics from setting up a development environment to more advanced topics, such as rendering and networking. + link: ./develop/index + linkText: Khởi Đầu + - title: Hướng Dẫn Cho Người Chơi + icon: 📚 + details: Có phải bạn đang tìm kiếm cách chạy các bản mod dành cho Fabric? Bộ hướng dẫn của chúng tôi sẽ giúp bạn điều đó. Những cách này sẽ giúp bạn trong việc tải xuống, cài đặt và khắc phục sự cố khi dùng mod Fabric. + link: ./players/index + linkText: Đọc Thêm +--- + +
+ +## Muốn đóng góp? + +If you want to contribute to the Fabric Documentation, you can find the source code on [GitHub](https://github.com/FabricMC/fabric-docs), and the relevant [contribution guidelines](./contributing). + +
diff --git a/versions/1.20.4/translated/vi_vn/players/index.md b/versions/1.20.4/translated/vi_vn/players/index.md new file mode 100644 index 000000000..216968c17 --- /dev/null +++ b/versions/1.20.4/translated/vi_vn/players/index.md @@ -0,0 +1,12 @@ +--- +title: Hướng Dẫn Cho Người Chơi +description: Một bộ tài liệu hướng dẫn cho người chơi và quản trị viên máy chủ về cách cài đặt và sử dụng Fabric. +--- + +# Hướng Dẫn Cho Người Chơi + +Phần này của Tài liệu Fabric dành riêng cho người chơi và quản trị viên máy chủ muốn tìm hiểu cách cài đặt, sử dụng và khắc phục sự cố Fabric. + +Bạn nên tham khảo các phần ở thanh bên để biết danh sách tất cả các hướng dẫn có sẵn. + +Nếu bạn gặp bất cứ sự cố nào, vui lòng báo cáo chúng trên [GitHub](https://github.com/FabricMC/fabric-docs) hoặc xin sự trợ giúp từ kênh `#player-support` hay kênh `#server-admin-support` trong [Discord Fabric](https://discord.gg/v6v4pMv). diff --git a/versions/1.20.4/translated/vi_vn/players/installing-fabric.md b/versions/1.20.4/translated/vi_vn/players/installing-fabric.md new file mode 100644 index 000000000..64ca01703 --- /dev/null +++ b/versions/1.20.4/translated/vi_vn/players/installing-fabric.md @@ -0,0 +1,55 @@ +--- +title: Cài Đặt Fabric +description: Bộ hướng dẫn từng bước để cài đặt Fabric. +authors: + - IMB11 +--- + +# Cài Đặt Fabric + +Bài hướng dẫn này sẽ giúp bạn cài đặt Fabric cho trình Launcher Minecraft chính thức. + +Đối với các trình launcher bên thứ ba, bạn nên tham khảo tài liệu của họ. + +## 1. Tải xuống Trình cài đặt Fabric + +Bạn có thể tải trình cài đặt Fabric từ [trang chủ Fabric](https://fabricmc.net/use/). + +Nếu bạn sử dụng Windows, hãy tải phiên bản có đuôi `.exe` (`Download For Windows`), bởi vì nó không yêu cầu Java phải được cài trước đó trên hệ thống của bạn. Nó sẽ sử dụng phiên bản Java đi cùng trình launcher chính thức. + +Đối với macOS và Linux, bạn nên tải phiên bản có đuôi `.jar`. Đôi khi, cách này sẽ yêu cầu Java phải được cài đặt trước đó. + +## 2. Chạy Trình cài đặt Fabric + +:::warning +Hãy đóng Minecraft và trình Launcher của Minecraft trước khi cài đặt. +::: + +:::details Thông tin cho người dùng MacOS + +Trên macOS, bạn có thể cần bấm chuột phải vào tập tin `.jar` trong thư mục tải xuống của mình và bấm `Open` để chạy nó. + +![Trình cài đặt Fabric với chữ "Cài đặt" được tô đậm](/assets/players/installing-fabric/macos-downloads.png) + +Khi được hỏi "Bạn có muốn mở nó không?", bấm `Open` lần nữa. +::: + +Ngay khi bạn mở trình cài đặt, bạn sẽ thấy màn hình như thế này: + +![Trình cài đặt Fabric với chữ "Cài đặt" được tô đậm](/assets/players/installing-fabric/installer-screen.png) + +Để cài đặt Fabric, hãy chọn phiên bản trò chơi bạn muốn từ danh sách thả xuống, và bấm `install`. + +**Hãy đảm bảo đã chọn 'Create Profile'.** + +## 3. Hoàn tất! + +Sau khi trình cài đặt hoàn tất, bạn có thể mở trình Launcher Minecraft và chọn hồ sơ Fabric từ danh sách thả xuống ở góc trái bên dưới và bấm nút Chơi! + +![Trình Launcher Minecraft với hồ sơ Fabric được chọn](/assets/players/installing-fabric/launcher-screen.png) + +## Bước Tiếp Theo + +Bây giờ bạn đã hoàn tất việc cài Fabric, bạn có thể thêm mod vào trong trò chơi! Check out the [Finding Mods](./finding-mods) guide for more information. + +Nếu bạn gặp bất cứ vấn đề nào khi đang làm theo bài hướng dẫn này, bạn có thể xin sự trợ giúp từ kênh `#player-support` trong [Discord Fabric](https://discord.gg/v6v4pMv). diff --git a/versions/1.20.4/translated/vi_vn/players/installing-mods.md b/versions/1.20.4/translated/vi_vn/players/installing-mods.md new file mode 100644 index 000000000..796e7353c --- /dev/null +++ b/versions/1.20.4/translated/vi_vn/players/installing-mods.md @@ -0,0 +1,67 @@ +--- +title: Cài Đặt Mod +description: Bộ hướng dẫn từng bước để cài đặt mod cho Fabric. +authors: + - IMB11 +--- + +# Cài Đặt Mod + +Bài hướng dẫn này sẽ giúp bạn cài đặt các bản mod Fabric cho trình Launcher Minecraft chính thức. + +Đối với các trình launcher bên thứ ba, bạn nên tham khảo tài liệu của họ. + +## 1. Tải Mod + +:::warning +Bạn chỉ nên tải mod từ các nguồn uy tín. Để biết thêm thông tin về cách tìm mod, hãy tham khảo tài liệu [Tìm Mod](./finding-mods). +::: + +Phần lớn các bản mod đều yêu cầu Fabric API, thứ mà có thể được tải từ [Modrinth](https://modrinth.com/mod/fabric-api) hoặc [CurseForge](https://curseforge.com/minecraft/mc-mods/fabric-api) + +Khi chuẩn bị tải mod, cần lưu ý: + +- Chúng phải hỗ trợ phiên bản Minecraft bạn muốn chơi. Ví dụ một bản mod mà hoạt động tốt ở bản 1.20, có thể không hoạt động được ở bản 1.20.2. +- Chúng phải dùng được cho Fabric và không phải là các trình mod khác. +- Thêm vào đó, chúng phải đúng phiên bản Minecraft (Phiên bản Java). + +## 2. Di chuyển tệp mod vào trong thư mục `mods` + +Thư mục mods có thể được tìm thấy ở các địa chỉ bên dưới ứng với mỗi hệ điều hành. + +Bạn có thể dán những đường dẫn đó vào thanh địa chỉ của explorer để nhanh chóng điều hướng đến thư mục. + +::: code-group + +```:no-line-numbers [Windows] +%appdata%\.minecraft\mods +``` + +```:no-line-numbers [macOS] +~/Library/Application Support/minecraft/mods +``` + +```:no-line-numbers [Linux] +~/.minecraft/mods +``` + +::: + +Khi bạn đã tìm thấy thư mục `mods`, bạn có thể di chuyển tệp mod `.jar` vào trong đó. + +![Cài đặt mod ở thư mục mods](/assets/players/installing-mods.png) + +## 3. Bạn đã hoàn tất! + +Sau khi bạn đã di chuyển tệp mod vào trong thư mục `mods`, bạn có thể mở trình Launcher Minecraft và chọn hồ sơ Fabric từ danh sách thả xuống ở góc trái bên dưới và bấm nút chơi! + +![Trình Launcher Minecraft với hồ sơ Fabric được chọn](/assets/players/installing-fabric/launcher-screen.png) + +## Khắc Phục Sự Cố + +Nếu bạn gặp bất cứ vấn đề nào khi đang làm theo bài hướng dẫn này, bạn có thể xin sự trợ giúp từ kênh `#player-support` trong [Discord Fabric](https://discord.gg/v6v4pMv). + +Bạn cũng có thể tự sửa chữa lỗi bằng cách tham khảo các trang khắc phục sự cố sau: + +- [Báo Cáo Dừng Đột Ngột](./troubleshooting/crash-reports) +- [Tải Lên Tệp Log](./troubleshooting/uploading-logs) diff --git a/versions/1.20.4/translated/vi_vn/players/updating-fabric.md b/versions/1.20.4/translated/vi_vn/players/updating-fabric.md new file mode 100644 index 000000000..2811f9d1e --- /dev/null +++ b/versions/1.20.4/translated/vi_vn/players/updating-fabric.md @@ -0,0 +1,42 @@ +--- +title: Cập Nhật Fabric +description: Bộ hướng dẫn từng bước để cập nhật Fabric. +authors: + - IMB11 + - modmuss50 +--- + +# Cập Nhật Fabric + +Bài hướng dẫn này sẽ giúp bạn cập nhật Fabric cho trình Launcher Minecraft chính thức. + +Đối với các trình launcher bên thứ ba, bạn nên tham khảo tài liệu của họ. + +Việc cập nhật Fabric là một quá trình khá tương đồng so với việc cài đặt Fabric, vì vậy đa phần bài hướng dẫn này sẽ giống với +bài [Cài Đặt Fabric](./installing-fabric). + +## Vì sao tôi phải cập nhật Fabric Loader? + +Những bản mod mới có thể yêu cầu phiên bản mới hơn của Fabric Loader để hoạt động, vì vậy bạn nên liên tục cập nhật nó để có thể sử dụng nhiều bản mod mới nhất. + + + + + +Để cập nhật Fabric, đảm bảo chọn đúng cả phiên bản trò chơi và phiên bản loader rồi sau đó bấm `Cài Đặt`. + +**Hãy đảm bảo bỏ chọn `Tạo Hồ Sơ` khi chạy trình cài đặt, nếu không, nó sẽ tạo hồ sơ mới mà có thể chúng ta không cần.** + +## 3. Mở phần Hồ Sơ ở trình Launcher Minecraft + +Khi trình cài đặt hoàn tất, bạn có thể mở trình Launcher Minecraft và đi đến tab `Cài Đặt`. Chọn hồ sơ Fabric của bạn và mở màn hình chỉnh sửa. + +Thay thể phiên bản cũ với một phiên bản mới hơn của Fabric Loader mà bạn đã cài trước đó, và bấm `Lưu`. + +![Cập nhật phiên bản Fabric Loader ở trình Launcher Minecraft](/assets/players/updating-fabric.png) + +## 4. Bạn đã hoàn tất! + +Sau khi bạn đã hoàn thành xong các bước, bạn có thể quay trở lại tab `Chơi`, chọn hồ sơ Fabric từ danh sách thả xuống ở góc trái bên dưới và bấm nút chơi! + +Nếu bạn gặp bất cứ vấn đề nào khi đang làm theo bài hướng dẫn này, bạn có thể xin sự trợ giúp từ kênh `#player-support` trong [Discord Fabric](https://discord.gg/v6v4pMv). diff --git a/versions/1.20.4/translated/vi_vn/sidebar_translations.json b/versions/1.20.4/translated/vi_vn/sidebar_translations.json new file mode 100644 index 000000000..e044d0684 --- /dev/null +++ b/versions/1.20.4/translated/vi_vn/sidebar_translations.json @@ -0,0 +1,47 @@ +{ + "players.title": "Hướng Dẫn Cho Người Chơi", + "players.faq": "Các Câu Hỏi Thường Gặp", + "players.installingJava": "Đang Cài Java", + "players.installingJava.windows": "Windows", + "players.installingJava.macOS": "macOS", + "players.installingJava.linux": "Linux", + "players.installingFabric": "Đang Cài Fabric", + "players.findingMods": "Đang Tìm Các Mod Đáng Tin Cậy", + "players.installingMods": "Đang Cài Các Mod", + "players.troubleshooting": "Khắc Phục Sự Cố", + "players.troubleshooting.uploadingLogs": "Tải Lên Tệp Log Của Bạn", + "players.troubleshooting.crashReports": "Báo Cáo Dừng Đột Ngột", + "players.updatingFabric": "Đang Cập Nhật Fabric", + "develop.title": "Hướng Dẫn Cho Nhà Phát Triển", + "develop.gettingStarted": "Khởi Đầu", + "develop.gettingStarted.introduction": "Giới thiệu về Fabric và Modding", + "develop.gettingStarted.devEnvSetup": "Thiết lập Môi trường Phát triển", + "develop.gettingStarted.creatingProject": "Tạo một Dự án", + "develop.gettingStarted.projectStructure": "Cấu trúc Dự án", + "develop.gettingStarted.launchGame": "Chạy Game", + "develop.items": "Vật Phẩm", + "develop.items.potions": "Thuốc", + "develop.entities": "Thực Thể", + "develop.entities.effects": "Trạng Thái Các Hiệu Ứng", + "develop.entities.damage-types": "Các Loại Sát Thương", + "develop.commands": "Lệnh", + "develop.commands.basics": "Tạo Lệnh", + "develop.commands.arguments": "Đối số", + "develop.commands.suggestions": "Gợi Ý", + "develop.rendering": "Kết Xuất", + "develop.rendering.basicConcepts": "Các Khái Niệm Kết Xuất Cơ Bản", + "develop.rendering.drawContext": "Sử Dụng Bối Cảnh Vẽ", + "develop.rendering.hud": "Kết Xuất Trên Hud", + "develop.rendering.gui": "GUI và Màn Hình", + "develop.rendering.gui.customScreens": "Màn hình Tuỳ Chỉnh", + "develop.rendering.gui.customWidgets": "Tiện Ích Tuỳ Chỉnh", + "develop.rendering.particles": "Hạt Hiệu Ứng", + "develop.rendering.particles.creatingParticles": "Tạo Các Hạt Hiệu Ứng", + "develop.misc": "Trang Khác", + "develop.misc.codecs": "Codecs", + "develop.misc.events": "Sự Kiện", + "develop.sounds": "Âm thanh", + "develop.sounds.using-sounds": "Chạy SoundEvent", + "develop.sounds.custom": "Tạo Âm thanh Tùy chỉnh", + "github.edit": "Sửa trang này trên GitHub" +} \ No newline at end of file diff --git a/versions/1.20.4/translated/vi_vn/website_translations.json b/versions/1.20.4/translated/vi_vn/website_translations.json new file mode 100644 index 000000000..17f120302 --- /dev/null +++ b/versions/1.20.4/translated/vi_vn/website_translations.json @@ -0,0 +1,8 @@ +{ + "title": "Tài Liệu Tham Khảo Fabric", + "home": "Trang Chủ", + "download": "Tải", + "contribute": "Đóng Góp", + "contribute.api": "Fabric API", + "version_switcher": "Thay Đổi Phiên Bản" +} \ No newline at end of file diff --git a/versions/1.20.4/translated/zh_cn/contributing.md b/versions/1.20.4/translated/zh_cn/contributing.md new file mode 100644 index 000000000..fa8dddc2e --- /dev/null +++ b/versions/1.20.4/translated/zh_cn/contributing.md @@ -0,0 +1,181 @@ +# Fabric 文档贡献指南 + +此网站使用 [VitePress](https://vitepress.dev/) 从多个 Markdown 文件生成静态 HTML 网页。 您应该熟悉 VitePress 所支持的 Markdown 扩展语法,参见[此链接](https://vitepress.dev/guide/markdown#features)。 + +## 目录 + +- [Fabric 文档贡献指南](#fabric-documentation-contribution-guidelines) + - [如何贡献](#how-to-contribute) + - [贡献网页框架](#contributing-framework) + - [贡献内容](#contributing-content) + - [风格指南](#style-guidelines) + - [扩展指南](#guidance-for-expansion) + - [内容验证](#content-verification) + - [清理](#cleanup) + - [翻译文档](#translating-documentation) + +## 如何贡献 + +建议您在存储库的分支上为您发出的每个拉取请求创建一个新分支。 这样一次性管理多个拉取请求将更简单。 + +**如果您需要本地预览您的更改,您需要安装 [Node.js 18+](https://nodejs.org/en/)** + +在运行这些指令之前,请确保运行 `npm install` 以安装所有依赖。 + +**运行开发服务器:** + +这将允许您在本地地址 `localhost:3000` 预览您的更改,并自动在修改时重载页面。 + +```sh +npm run dev +``` + +**构建网站:** + +这将编译所有 Markdown 文件为静态 HTML 页面并保存至 `.vitepress/dist` + +```sh +npm run build +``` + +**预览已构建的网站:** + +这将在端口 3000 启动本地服务器并展示 `.vitepress/dist` 中的网页 + +```sh +npm run preview +``` + +## 贡献网页框架 + +“框架”指的是网站的内部结构,任何修改网站框架的拉取请求都应该用 `framework` 标签标记。 + +您应该在咨询了 [Fabric Discord](https://discord.gg/v6v4pMv) 上的文档团队或通过一个 issue 后再发起框架相关的拉取请求。 + +**注意:修改侧边栏文件和导航栏配置不算作框架拉取请求。** + +## 贡献内容 + +贡献内容是最主要的向 Fabric 文档贡献的方式。 + +所有的内容都应当遵循我们的风格指南。 + +### 风格指南 + +在 Fabric 文档网站中的所有页面都应该遵循风格指南。 如果你有任何疑问,请在 [Fabric Discord](https://discord.gg/v6v4pMv) 或 GitHub Discussions 中提出。 + +风格指南如下: + +1. 所有页面必须在 frontmatter 中有一个标题和描述。 + + ```md + --- + title: 这是页面的标题 + description: 这是页面的描述 + authors: + - 这是GitHub用户名 + --- + + # ... + ``` + +2. 如果您创建或修改了包含代码的页面,请将代码放置在参考模组内的适当位置(位于存储库的 `/reference` 文件夹中)。 然后使用 [VuePress 提供的代码片段功能](https://vitepress.dev/zh/guide/markdown#import-code-snippets) 来嵌入代码。如果您需要更大范围的控制,可以使用 [来自 `markdown-it-vuepress-code-snippet-enhanced` 的 transclude 功能](https://github.com/fabioaanthony/markdown-it-vuepress-code-snippet-enhanced)。 + + **例如:** + + ```md + <<< @/reference/latest/src/main/java/com/example/docs/FabricDocsReference.java{15-21 java} + ``` + + 这会嵌入参考模组中 `FabricDocsReference.java` 的第 15-21 行。 + + 最终的代码片段将看起来像这样: + + ```java + @Override + public void onInitialize() { + // This code runs as soon as Minecraft is in a mod-load-ready state. + // However, some things (like resources) may still be uninitialized. + // Proceed with mild caution. + + LOGGER.info("Hello Fabric world!"); + } + ``` + + **Transclude 示例** + + ```md + @[code transcludeWith=#test_transclude](@/reference/.../blah.java) + ``` + + 这将嵌入标记有 `#test_transclude` 标签的 `blah.java` 文件中的部分。 + + 例如: + + ```java + public final String test = "Bye World!" + + // #test_transclude + public void test() { + System.out.println("Hello World!"); + } + // #test_transclude + ``` + + 只有 `#test_transclude` 标签之间的代码会被嵌入。 + + ```java + public void test() { + System.out.println("Hello World!"); + } + ``` + +3. 所有原始文档都使用英文书写,跟随美国的语法规则。 虽然你可以使用 [LanguageTool](https://languagetool.org/) 检查你的语法,但不要过于担心。 我们的文档团队会在清理阶段审查并纠正语法。 不过,一开始就努力做到正确可以为我们节省时间。 + +4. 如果您正在创建新的部分,您应当在 `.vitepress/sidebars` 文件夹中创建新的侧边栏,并将它添加到 `config.mts` 文件中。 如果您需要帮助,请在 [Fabric Discord](https://discord.gg/v6v4pMv) 的 `#docs` 频道提问。 + +5. 创建新页面时,您应当将其添加到 `.vitepress/sidebars` 文件夹中相关的侧边栏中。 重复,如果您需要帮助,请在 Fabric Discord 的 `#docs` 频道提问。 + +6. 任何图片都应该放在 `/assets` 文件夹中的适当位置。 + +7. ⚠️ **当链接其他页面时,使用相对链接。** ⚠️ + + 这是因为现有的版本控制系统会预处理链接,以便事先添加版本号。 如果您使用绝对链接,版本号将不会添加到链接中。 + + 例如,对于 `/players` 文件夹中的页面,要链接到位于 `/players/installing-fabric.md` 的 `installing-fabric` 页面,您需要进行以下操作: + + ```md + [这是一个其他页面的链接](./installing-fabric) + ``` + + 您**不**应当进行以下操作: + + ```md + [这是一个其他页面的链接](/players/installing-fabric) + ``` + +所有内容贡献都会经历三个阶段: + +1. 扩展指南(如果可能) +2. 内容验证 +3. 清理(语法等) + +### 扩展指南 + +如果文档团队认为您需要拓展您的拉去请求,团队成员将添加 `expansion` 标签到您的拉去请求,并附上一条评论解释为什么他认为可以拓展。 如果你同意这条建议,你可以拓展你的拉取请求。 + +**不要对拓展拉取请求感到有压力。** 如果您不想拓展您的拉取请求,您可以简单地请求移除 `expansion` 标签。 + +如果您不想拓展您的拉取请求,但您乐于让其他人在未来拓展它,最好在 [Issues page](https://github.com/FabricMC/fabric-docs/issues) 创建一个 issue,并解释您想如何拓展。 + +### 内容验证 + +所有添加内容的拉取请求都会经过内容验证,这是最重要的阶段,因为它确保内容准确且遵循Fabric文档的风格指南。 + +### 清理 + +这个阶段是文档团队会修正任何语法问题并在合并拉取请求之前进行他们认为必要的任何其他修改的时候! + +## 翻译文档 + +如果您想将该文档翻译为您的语言,您可以在 [Fabric Crowdin 页面](https://crowdin.com/project/fabricmc) 做这件事。 diff --git a/versions/1.20.4/translated/zh_cn/develop/codecs.md b/versions/1.20.4/translated/zh_cn/develop/codecs.md new file mode 100644 index 000000000..191dec369 --- /dev/null +++ b/versions/1.20.4/translated/zh_cn/develop/codecs.md @@ -0,0 +1,400 @@ +--- +title: Codec +description: 用于理解和使用 Mojang 的 codec 系统以序列化和反序列化对象的全面指南。 +authors: + - enjarai + - Syst3ms +--- + +# Codec + +Codec 是一个为了简单地解析 Java 对象的系统,它被包含在 Mojang 的 DataFixerUpper (DFU) 库中,DFU 被包含在 Minecraft 中。 在模组环境中,当读取和写入自定义 JSON 文件时,codec 可用作 GSON 和 Jankson 的替代品,尽管这些开始越来越相关,因为 Mojang 正在重写大量旧代码以使用 Codec。 + +Codec 与 DFU 的另一个 API `DynamicOps` 一起使用。 一个 codec 定义一个对象的结构,而 dynamic ops 用于定义一个序列化格式,例如 json 或 NBT。 这意味着任何 codec 都可以与任何 dynamic ops 一起使用,反之亦然,这样使其极其灵活。 + +## 使用 Codec + +### 序列化和反序列化 {#serializing-and-deserializing} + +Codec 的基本用法是将对象序列化为特定格式或反序列化为特定格式。 + +一些原版的类已经定义了 codec,这些我们可以用作例子。 Mojang 默认提供了两个动态操作类 `JsonOps` 和 `NbtOps`,它们可以涵盖大部分的使用场景。 + +假设现在我们要把一个 `BlockPos` 对象序列化成 json 再反序列化回对象。 我们可以分别使用 `BlockPos.CODEC` 中的静态方法 `Codec#encodeStart` 和 `Codec#parse`。 + +```java +BlockPos pos = new BlockPos(1, 2, 3); + +// 序列化该 BlockPos 为 JsonElement +DataResult result = BlockPos.CODEC.encodeStart(JsonOps.INSTANCE, pos); +``` + +使用 codec 时,返回的结果为 `DataResult` 的形式。 这是个包装,可以代表成功或者失败。 有几种方式使用:如果只想要我们序列化的值, `DataResult#result` 会简单返回一个包含我们的值的 `Optional` ,而 `DataResult#resultOrPartial` 还允许我们提供一个函数来处理可能发生的任何错误。 后者对于自定义数据包资源尤其有用,因为我们想要记录错误,而不会在其他地方引起问题。 + +那么,让我们获取我们的序列化值,并将其转换回 `BlockPos` : + +```java +// 实际编写模组时,你当然会想要适当地处理空的 Optional。 +JsonElement json = result.resultOrPartial(LOGGER::error).orElseThrow(); + +// 这里我们有我们的 json 值,应该对应于 `[1, 2, 3]`, +// 因为这是 BlockPos codec 使用的格式。 +LOGGER.info("Serialized BlockPos: {}", json); + +// 现在将 JsonElement 反序列化为 BlockPos +DataResult result = BlockPos.CODEC.parse(JsonOps.INSTANCE, json); + +// 我们将再次只是从 result 中获取我们的值 +BlockPos pos = result.resultOrPartial(LOGGER::error).orElseThrow(); + +// 接下来我们可以看到我们成功序列化和反序列化我们的 BlockPos! +LOGGER.info("Deserialized BlockPos: {}", pos); +``` + +### 内置的 Codec + +正如之前所说,Mojang 已经为几个原版和标准 Java 类定义了 codec,包括但不限于 `BlockPos`、`BlockState`、`ItemStack`、`Identifier`、`Text` 和正则表达式 `Pattern`。 Mojang 自己的 codec 通常可以在类内找到名为 `CODEC` 的静态字段,其他的保持在 `Codecs` 类。 还要注意,所有原版注册表都包含 `getCodec()` 方法,例如,你可以使用 `Registries.BLOCK.getCodec()` 获取一个 `Codec`,可用于序列化为方块 id 或是反过来。 + +Codec API 自己包含了一些 基础类型的 codec,就像 `Codec.INT` 和 `Codec.STRING`。 这些都在 `Codec` 类中作为静态字段存在,通常用作更多复杂 codec 的基础,会在下方做出解释。 + +## 构建 Codec + +现在我们已经知道如何使用 codec,让我们看看我们如何构建自己的 codec。 例如,让我们尝试序列化单链列表。 这种表示列表的方式由一组节点组成,这些节点既包含一个值,也包含对列表中下一个节点的引用。 然后列表由其第一个节点表示,遍历列表是通过跟随下一个节点来完成的,直到没有剩余节点。 以下是存储整数的节点的简单实现。 + +```java +public class CoolBeansClass { + + private final int beansAmount; + private final Item beanType; + private final List beanPositions; + + public CoolBeansClass(int beansAmount, Item beanType, List beanPositions) {...} + + public int getBeansAmount() { return this.beansAmount; } + public Item getBeanType() { return this.beanType; } + public List getBeanPositions() { return this.beanPositions; } +} +``` + +相应的 json 文件可能如下所示: + +```json +{ + "beans_amount": 5, + "bean_type": "beanmod:mythical_beans", + "bean_positions": [ + [1, 2, 3], + [4, 5, 6] + ] +} +``` + +我们可以通过将多个较小的 Codec 组合成一个较大的 Codec 来为此类制作一个 Codec。 在这种情况下,我们的每个字段都需要: + +- 一个 `Codec` +- 一个 `Codec` +- 一个 `Codec>` + +第一个可以从前面提到的 `Codec` 类中的基本类型 codec 中得到,也就是 `Codec.INT`。 而第二个可以从 `Registries.ITEM` 注册表中获取,它有 `getCodec()` 方法,返回 `Codec`。 我们没有用于 `List` 的默认 codec,但我们可以从 `BlockPos.CODEC` 制作一个。 + +### List + +`Codec#listOf` 可用于创建任意 codec 的列表版本。 + +```java +Codec> listCodec = BlockPos.CODEC.listOf(); +``` + +应该注意的是,以这种方式创建的 codec 总是会反序列化为一个 `ImmutableList`。 如果需要的是可变的列表,可以利用 [xmap](#mutually-convertible-types)在反序列化期间转换为可变列表。 + +### 合并用于类似 Record 类的 Codec + +现在我们有每个字段单独的 codec,我们可以为我们的类使用 `RecordCodecBuilder` 合并它们为一个 codec。 假定我们的类有一个包含想序列化的所有字段的构造方法,并且每个字段都有相应的 getter 方法。 所以与 record 一起使用会非常适合,但也可以用于常规类。 + +来看看如何为我们的 `CoolBeansClass` 创建一个 codec: + +```java +public static final Codec CODEC = RecordCodecBuilder.create(instance -> instance.group( + Codec.INT.fieldOf("beans_amount").forGetter(CoolBeansClass::getBeansAmount), + Registries.ITEM.getCodec().fieldOf("bean_type").forGetter(CoolBeansClass::getBeanType), + BlockPos.CODEC.listOf().fieldOf("bean_positions").forGetter(CoolBeansClass::getBeanPositions) + // 最多可以在这里声明 16 个字段 +).apply(instance, CoolBeansClass::new)); +``` + +在 group 中的每一行指定 codec、字段名称和 getter 方法。 在 group 中的每一行指定一个 codec,一个字段名和一个 getter 方法。 `Codec#fieldOf` 调用用于将编解码器转换为 [map codec](#mapcodec),而 `forGetter` 调用指定了用于从类的实例中检索字段值的 `getter` 方法。 与此同时,`apply` 调用指定了用于创建新实例的构造函数。 需要注意的是在 group 中的字段顺序需要和构造方法的参数顺序保持一致。 同时,调用 `apply` 则指定了用于创建新实例的构造函数。 注意 group 中的字段的顺序应与构造函数中参数的顺序相同。 + +这里也可以使用 `Codec#optionalFieldOf` 使字段可选,在 [可选字段](#optional-fields) 章节会有解释。 + +### 不要将 MapCodec 与 Codec&lt;Map&gt; 混淆 {#mapcodec} + +调用 `Codec#fieldOf` 会将 `Codec` 转换成 `MapCodec`,这是 `Codec` 的一个变体,但不是直接实现。 正如其名称所示,`MapCodec` 保证序列化为 +键到值的映射,或所使用的 `DynamicOps` 类似类型。 一些函数可能需要使用 `MapCodec` 而不是常规的 codec。 + +这种创建 `MapCodec` 的特殊方式本质上是在一个映射中封装源 codec 的值,并使用给定的字段名作为键。 这种创建 `MapCodec` 的特殊方式本质上是在一个map中封装源 codec 的值,使用给定的字段名作为键。 例如,一个 `Codec` 序列化为 json 时看起来像是这样: 例如,一个 `Codec` 序列化为 json 时看起来像是这样: + +```json +[1, 2, 3] +``` + +但当使用 `BlockPos.CODEC.fieldOf("pos")` 转换为 `MapCodec` 时,看起来像是这样: + +```json +{ + "pos": [1, 2, 3] +} +``` + +虽然 map codec 最常见的用途是与其他 map codec 合并以构造一个完整类字段的 codec,如前文的 [合并用于类似 Record 类的 Codec](#merging-codecs-for-record-like-classes) 章节所述,但也可以通过使用 `MapCodec#codec` 再次转换成常规的 codec,这将保持封装输入值的相同行为。 + +#### 可选字段 + +`Codec#optionalFieldOf` 可用于创建一个可选的 map codec。 反序列化过程中,当特定字段不存在于容器中时,反序列化为一个空的 `Optional`,或指定的默认值。 + +```java +// 无默认值 +MapCodec> optionalCodec = BlockPos.CODEC.optionalFieldOf("pos"); + +// 有默认值 +MapCodec optionalCodec = BlockPos.CODEC.optionalFieldOf("pos", BlockPos.ORIGIN); +``` + +需要注意,可选字段会默默忽略可能发生的任何错误。 这意味着如果这个字段存在,但值无效,该字段总是会被反序列化为默认值。 + +**从 1.20.2 开始**,Minecraft 自己 (不是 DFU!) 却确实提供`Codecs#createStrictOptionalFieldCodec`, +如果字段值无效,则反序列化失败。 + +### 常量、约束和组合 + +#### Unit + +`Codec.unit` 可被用于创建一个总是反序列化为一个常量值的 codec,无论输入如何。 序列化时什么也不做。 + +```java +Codec theMeaningOfCodec = Codec.unit(42); +``` + +#### 数值范围 + +`Codec.intRange` 及其伙伴 `Codec.floatRange` 和 `Codec.doubleRange` 可用于创建一个只接受在指定**包含**范围内的数字值的 codec。 这适用于序列化和反序列化。 这适用于序列化和反序列化。 这适用于序列化和反序列化。 + +```java +// 不能大于 2 +Codec amountOfFriendsYouHave = Codec.intRange(0, 2); +``` + +#### Pair + +`Codec.pair` 将两个 codec `Codec
` 和 `Codec` 合并为 `Codec>`。 `Codec#dispatch` 让我们可以定义一个 codec 的注册表,并根据序列化数据中字段的值分派到一个特定的 codec。 当反序列化具有不同字段的对象,这些字段依赖于它们的类型,但仍代表相同的事物时,这非常有用。 当反序列化具有不同字段的对象,这些字段依赖于它们的类型,但仍代表相同的事物时,这非常有用。 +结果 codec 将序列化为结合了两个使用的 codec 字段的 map。 + +例如,运行这些代码: + +```java +// 创建两个单独的装箱的 codec +Codec firstCodec = Codec.INT.fieldOf("i_am_number").codec(); +Codec secondCodec = Codec.BOOL.fieldOf("this_statement_is_false").codec(); + +// 将其合并为 pair codec +Codec> pairCodec = Codec.pair(firstCodec, secondCodec); + +// 用它序列化数据 +DataResult result = pairCodec.encodeStart(JsonOps.INSTANCE, Pair.of(23, true)); +``` + +将输出该 json: + +```json +{ + "i_am_number": 23, + "this_statement_is_false": true +} +``` + +#### Either + +`Codec.either` 将两个 codec `Codec` 和 `Codec` 组合为 `Codec>`。 当使用 codec 的时候,结果以 `DataResult` 的形式返回。 这是一个可以代表成功或者失败的包装。 我们可以通过几种方式使用这个:如果我们只想要我们序列化的值, `DataResult#result` 会简单地返回一个包含我们值的 `Optional` ,而 `DataResult#resultOrPartial` 还允许我们提供一个函数来处理可能发生的任何错误。 后者对于自定义数据包资源尤其有用,因为我们想要记录错误,而不会在其他地方引起问题。 +如果第二个也失败,则会返回第二个 codec 的错误。 + +#### Map + +对于处理具有任意键的 map,如 `HashMaps`,可以使用 `Codec.unboundedMap`。 引用 生成的 codec 将序列化为 JSON 对象,或当前 dynamic ops 可用的任何等效对象。 + +由于JSON和NBT的限制,使用的密钥Codec必须序列化为字符串。 这包含类型不是 string 但序列化为他们自身的 codec,例如 `Identifier.CODEC`。 在下面的示例中: 这包括类型自身不是字符串但会序列化为字符串的 codec,例如 `Identifier.CODEC`。 看看下面的例子: + +```java +// 创建一个 Identifier 到 Integer 的 map 的 codec +Codec> mapCodec = Codec.unboundedMap(Identifier.CODEC, Codec.INT); + +// 使用它序列化数据 +DataResult result = mapCodec.encodeStart(JsonOps.INSTANCE, Map.of( + new Identifier("example", "number"), 23, + new Identifier("example", "the_cooler_number"), 42 +)); +``` + +将输出该 json: + +```json +{ + "example:number": 23, + "example:the_cooler_number": 42 +} +``` + +正如你所见,因为 `Identifier.CODEC` 直接序列化到字符串,所以这样做有效。 正如你所见,因为 `Identifier.CODEC` 直接序列化到字符串,所以可以工作。 对于无法序列化为字符串的简单对象,可以使用[XMAP及其友元](#mutually-convertible-types-and-you)进行转换,从而实现类似的效果。 + +### 相互可转换的类型与您 + +#### `xmap` + +我们有两个可以互相转换的类,但没有继承关系。 例如,原版的 `BlockPos` 和 `Vec3d`。 如果我们有其中一个 codec,我们可以使用 `Codec#xmap` 创建一个双向的特定转换函数。 + +`BlockPos` 已有 codec,但让我们假装它不存在。 我们可以基于 `Vec3d` 的 codec 这样为它创建一个: + +```java +Codec blockPosCodec = Vec3d.CODEC.xmap( + // 转换 Vec3d 到 BlockPos + vec -> new BlockPos(vec.x, vec.y, vec.z), + // 转换 BlockPos 到 Vec3d + pos -> new Vec3d(pos.getX(), pos.getY(), pos.getZ()) +); + +// 当转换一个存在的类 (比如 `X`)到您自己的类 (`Y`) +// 最好是在 `Y` 类中添加 `toX` 和静态的 `fromX` 方法 +// 并且使用在您的 `xmap` 调用中使用方法引用 +``` + +#### flatComapMap、comapFlatMap 与 flatXMap + +`flatComapMap`、`comapFlatMap` 与 `flatXMap` 类似于 xmap,但是他们允许一个或多个转换函数返回 DataResult。 这在实践中很有用,因为特定的对象实例可能并不总是适合转换。 这在实践中很有用,因为特定的对象实例可能并不总是适合转换。 这在实践中很有用,因为特定的对象实例可能并不总是适合转换。 + +以原版的 `Identifier` 为例。 以原版的 `Identifier` 为例。 以原版的 `Identifier` 为例。 虽然所有的标识符都可以转换为字符串,但并不是所有的字符串都是有效的标识符,所以使用 xmap 意味着当转换失败时会抛出不雅观的异常。 +正因为此,它的内置编解码器实际上是 `Codec.STRING` 上的一个 `comapFlatMap`,很好地说明了如何使用它: +正因为此,它的内置编解码器实际上是 `Codec.STRING` 上的一个 `comapFlatMap`,很好地说明了如何使用它: +正因为此,它的内置编解码器实际上是 `Codec.STRING` 上的一个 `comapFlatMap`,很好地说明了如何使用它: + +```java +public class Identifier { + public static final Codec CODEC = Codec.STRING.comapFlatMap( + Identifier::validate, Identifier::toString + ); + + // ... + + public static DataResult validate(String id) { + try { + return DataResult.success(new Identifier(id)); + } catch (InvalidIdentifierException e) { + return DataResult.error("Not a valid resource location: " + id + " " + e.getMessage()); + } + } + + // ... +} +``` + +虽然这些方法非常有用,但方法名称有点让人困惑,所以这里有一个表格帮助你记住应该使用哪一个: + +| 方法 | A -> B 总是有效? | B -> A 总是有效? | +| ----------------------- | ------------ | ------------ | +| `Codec#xmap` | 是 | 是 | +| `Codec#comapFlatMap` | 否 | 是 | +| `Codec#flatComapMap` | 是 | 否 | +| `Codec#flatXMap` | 否 | 否 | + +### 注册表分派 + +`Codec#dispatch` 让我们可以定义一个 codec 的注册表,并根据序列化数据中字段的值分派到一个特定的 codec。 当反序列化有不同字段的对象,而这些字段依赖于类型,但不同类型仍代表相同的事物时,这非常有用。 + +例如我们有一个抽象的 `Bean` 接口与两个实现类:`StringyBean` 和 `CountingBean`。 为了用注册表分派序列化他们,我们需要一些事: + +- 每个 bean 类型的独立 codec。 +- 一个 `BeanType` 类或 record,代表 bean 的类型并可返回它的 codec。 +- 一个在 `Bean` 中可以用于检索其 `BeanType` 的函数。 +- 一个 `Identifier` 到 `BeanType` 的 map 或注册表 +- 一个基于该注册表的 `Codec>`。 一个基于改注册表的 `Codec>`。 如果你使用 `net.minecraft.registry.Registry` 可以简单的调用 `Registry#getCodec`。 + +有了这些,就可以创建一个 bean 的注册表分派 codec。 + +@[code transcludeWith=:::](@/reference/latest/src/main/java/com/example/docs/codec/Bean.java) +@[code transcludeWith=:::](@/reference/latest/src/main/java/com/example/docs/codec/BeanType.java) +@[code transcludeWith=:::](@/reference/latest/src/main/java/com/example/docs/codec/StringyBean.java) +@[code transcludeWith=:::](@/reference/latest/src/main/java/com/example/docs/codec/CountingBean.java) +@[code transcludeWith=:::](@/reference/latest/src/main/java/com/example/docs/codec/BeanTypes.java) + +```java +// 现在我们可以创建一个用于 bean 类型的 codec +// 基于之前创建的注册表 +Codec> beanTypeCodec = BeanType.REGISTRY.getCodec(); + +// 基于那个,这是我们用于 bean 的注册表分派 codec! +// 第一个参数是这个 bean 类型的字段名 +// 当省略时默认是 "type"。 +Codec beanCodec = beanTypeCodec.dispatch("type", Bean::getType, BeanType::getCodec); +``` + +我们的新 codec 将会这样将 bean 类序列化为 json,仅抓取与特定类型相关的字段: + +```json +{ + "type": "example:stringy_bean", + "stringy_string": "This bean is stringy!" +} +``` + +```json +{ + "type": "example:counting_bean", + "counting_number": 42 +} +``` + +### 递归Codec + +有时,使用自身来解码特定字段的Codec很有用,例如在处理某些递归数据结构时。 在原始代码中,这用于`Text`对象,它可以将其他`Text`存储为子对象。 可以使用`Codecs#createRecursive`构建这样的Codec。 在原版代码中,这用于 `Text` 对象,可能会存储其他的 `Text` 作为子对象。 可以使用 `Codecs#createRecursive` 构建这样的 codec。 + +例如,让我们尝试序列化单链列表。 列表是由一组节点的表示的,这些节点既包含一个值,也包含对列表中下一个节点的引用。 然后列表由其第一个节点表示,遍历列表是通过跟随下一个节点来完成的,直到没有剩余节点。 以下是存储整数的节点的简单实现。 + +```java +public record ListNode(int value, ListNode next) {} +``` + +我们无法通过普通方法为此构建codec,因为我们会对`next`字段使用什么codec? 我们需要一个`Codec`,这就是我们正在构建的! `Codecs#createRecursive` 让我们使用一个神奇的 lambda 来实现这一点: 我们需要一个 `Codec`,这就是我们还在构建的! 序列化与反序列化 + +```java +Codec codec = Codecs.createRecursive( + "ListNode", // codec的名称 + selfCodec -> { + // 这里,`selfCodec` 代表 `Codec`,就像它已经构造好了一样 + // 这个 lambda 应该返回我们从一开始就想要使用的codec, + // 通过`selfCodec`引用自身 + return RecordCodecBuilder.create(instance -> + instance.group( + Codec.INT.fieldOf("value").forGetter(ListNode::value), + // `next`字段将使用自编解码器递归处理 + Codecs.createStrictOptionalFieldCodec(selfCodec, "next", null).forGetter(ListNode::next) + ).apply(instance, ListNode::new) + ); + } +); +``` + +序列化的 `ListNode` 可能看起来像这样: + +```json +{ + "value": 2, + "next": { + "value": 3, + "next" : { + "value": 5 + } + } +} +``` + +## 参考{#references} + +- 关于编解码器及相关API的更全面的文档,可以在[非官方DFU JavaDoc](https://kvverti.github.io/Documented-DataFixerUpper/snapshot/com/mojang/serialization/Codec)中找到。 +- 本指南的总体结构受到了 [Forge 社区 Wiki 关于 Codec 的页面](https://forge.gemwire.uk/wiki/Codecs)的重大启发,这是对同一主题的更具 Forge 特色的解读。 diff --git a/versions/1.20.4/translated/zh_cn/develop/commands/arguments.md b/versions/1.20.4/translated/zh_cn/develop/commands/arguments.md new file mode 100644 index 000000000..c0ef3c77a --- /dev/null +++ b/versions/1.20.4/translated/zh_cn/develop/commands/arguments.md @@ -0,0 +1,56 @@ +--- +title: 命令参数 +description: 学习如何创建带有复杂参数的命令。 +--- + +# 命令参数 + +大多数的命令都有参数。 有些时候他们是可选的,这意味着如果你不提供这些参数命令照样可以工作 一个节点可能有多种参数类型,此时有可能使用户困惑,请注意避免这个问题。 + +@[code lang=java highlight={3} transcludeWith=:::4](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +在这个情况里,在命令`/argtater`之后,您应该输入一个整型数字。 举个例子,如果您输入了`/argtater 3`,您应该会收到一条消息:`Called /argtater with value = 3`。 如果您输入了 `/argtataer` 并且没有任何参数,那么这个命令将不会被正确解析。 + +接下来我们将添加第二个可选的参数: + +@[code lang=java highlight={3,13} transcludeWith=:::5](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +现在您可以输入一个或者两个整型数字了。 如果您提供了一个整型数字,那么会打印单个值的反馈文本。 如果您提供了两个整型数字,那么会打印有两个值的反馈文本。 + +您可能会发现没有必要指定两次相似的执行。 因此,我们可以创建一个方法同时用于两种执行。 + +@[code lang=java highlight={3,5,6,7} transcludeWith=:::6](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +## 自定义参数类型 + +如果原版并没有提供您想要的命令参数类型,您可以创建您自己的类型。 为此,您需要创建一个继承`ArgumentType < T >` 接口的类,其中 `T` 是参数的类型。 + +您需要实现 `parse` 这个方法,这个方法会把输入的字符串解析为期望的类型。 + +举个例子,您可以创建一个可以把格式形如 `{x, y, z}` 的字符串解析为一个 `BlockPos` 参数类型。 + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/command/BlockPosArgumentType.java) + +### 注册自定义参数类型 + +:::warning +您需要同时在服务端和客户端注册您的自定义参数类型,否则您的命令将不会工作! +::: + +您可以在您的模组的初始化方法 `onInitialize` 中使用 `ArgumentTypeRegistry` 类来注册: + +@[code lang=java transcludeWith=:::11](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +### 使用自定义参数类型 + +我们可以在命令中使用我们的自定义参数类型──通过在 command builder 中传递实例到 `.argument` 方法。 + +@[code lang=java transcludeWith=:::10 highlight={3}](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +运行命令,我们可以测试我们的参数类型是否可以正常工作: + +![Invalid argument](/assets/develop/commands/custom-arguments_fail.png) + +![Valid argument](/assets/develop/commands/custom-arguments_valid.png) + +![Command result](/assets/develop/commands/custom-arguments_result.png) diff --git a/versions/1.20.4/translated/zh_cn/develop/commands/basics.md b/versions/1.20.4/translated/zh_cn/develop/commands/basics.md new file mode 100644 index 000000000..dc1f259cc --- /dev/null +++ b/versions/1.20.4/translated/zh_cn/develop/commands/basics.md @@ -0,0 +1,164 @@ +--- +title: 创建命令 +description: 创建带有复杂参数和行为的命令。 +authors: + - dicedpixels + - i509VCB + - pyrofab + - natanfudge + - Juuxel + - solidblock + - modmuss50 + - technici4n + - atakku + - haykam + - mschae23 + - treeways + - xpple +--- + +# 创建命令 + +创建命令可以允许模组开发者添加一些可以通过命令使用的功能。 这个指南将会教会你如何注册命令和 Brigadier 的一般命令结构。 + +:::info +Brigadier是一款由Mojang为Minecraft编写的命令解析器和调度器。 它是一款基于树的命令库,让您可以通过构建树的方式来构建您的命令和参数。 Brigadier是开源的: +::: + +## `Command` 接口 + +`com.mojang.brigadier.Command` 是一个可以执行指定行为的函数式接口, 并且在某些情况下会抛出 `CommandSyntaxException` 异常。 它有一个泛型参数 `S`,定义了_命令来源_的类型。 +命令来源提供了命令运行的上下文。 在 Minecraft 中,命令来源通常是代表服务器的 `ServerCommandSource`,命令方块,远程连接(RCON),玩家或者实体。 + +`Command` 中的单个方法 `run(CommandContext)` 将 `CommandContext` 作为唯一参数并返回一个整型数字。 命令上下文持有来自 `S` 命令来源类型并允许您获取参数,查看解析的命令节点并查看此命令中使用的输入。 + +像是其他的函数式接口,它一般用作 lambda 或者方法引用: + +```java +Command command = context -> { + return 0; +}; +``` + +该整型数字可以被认为是命令的执行结果。 通常,小于或等于零的值表示命令失败并将继续执行并且什么也不做。 大于零的值则意味着命令被成功执行并做了某些事情。 Brigadier 提供了一个常量来表示执行成功: `Command#SINGLE_SUCCESS`。 + +### `ServerCommandSource` 可以做什么? + +当执行时 `ServerCommandSource` 提供了一些额外的特殊实现的上下文。 它有获得执行命令的实体、在哪个世界运行或者在哪个服务器上运行的能力。 + +您可以通过在 `CommandContext` 实例上调用 `getSource()` 方法来获得命令上下文中的命令源。 + +```java +Command command = context -> { + ServerCommandSource source = context.getSource(); + return 0; +}; +``` + +## 注册一个基本命令 + +可以通过 Fabric API 提供的 `CommandRegistrationCallback` 来注册命令 。 + +:::info +更多注册回调的信息,请查看 [事件](../events) 指南。 +::: + +该事件应该在您的 mod 的初始化程序中注册。 + +回调一共有三个参数: + +- `CommandDispatcher dispatcher` - 用于注册,解析,执行命令。 `S` 是分发器支持的命令源类型。 +- `CommandRegistryAccess registryAccess` - 为可传递给某些命令参数方法的注册表提供一个抽象概念 +- `CommandManager.RegistrationEnvironment environment` - 标识注册命令的服务器类型。 + +在 mod 初始化程序中,我们只注册两个简单的命令: + +@[code lang=java transcludeWith=:::_1](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +在 `sendFeedback()` 方法之中,第一个参数是要发送的文本, 并且这是一个 `Supplier` 可以用于避免在不必要的时候实例化 Text 对象。 + +第二个参数决定是否广播反馈给其他的管理员。 一般来讲,如果一个命令只是查询一些东西而不会改变世界,比如说查询世界的时间或者玩家的分数,它应该是 `false` 的。 如果一个命令做了一些事情,比如说改变时间或者修改一些人的分数,它应该是 `true`。 + +如果一个命令失败了,您可以直接抛出任何异常而不是调用 `sendFeedback()`,服务器会妥善处理。 + +通常抛出 `CommandSyntaxException` 异常来指示语法异常或者参数异常。 你也可以实现一个专属的异常类型。 + +为了执行这个命令,您必须输入大小写敏感的 `/foo`。 + +### 注册环境 + +如果需要,您还可以确保仅在某些特定情况下注册命令,例如仅在专用环境中: + +@[code lang=java highlight={2} transcludeWith=:::2](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +### 命令需求 + +假设您有一个只希望管理员可以执行的命令。 有一个 `requires()` 方法可以做到这一点。 `requires()` 方法有一个 `Predicate` 参数,它将提供一个 `ServerCommandSource` 测试并确定 `CommandSource` 是否可以执行该命令。 + +@[code lang=java highlight={3} transcludeWith=:::3](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +这个命令只会在命令源至少为 2 级管理员(包括命令方块)时才会执行。 在其他情况下,命令并不会被注册。 + +这样做的副作用是不会向不具备 2 级管理员的人显示此命令。 这也是您为什么在未开启作弊模式的情况下不能使用 tab 补全绝大多数命令的原因。 + +### 子命令 + +要添加子命令,通常需要注册该命令的第一个字面量节点。 为了添加一个子命令,您必须将下一个字面量节点添加到一个已经存在的节点上。 + +@[code lang=java highlight={3} transcludeWith=:::7](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +类似参数,子命令也可被设置为可选。 在以下情况下,`/subtater` 和 `/subtater subcommand` 都是有效的。 + +@[code lang=java highlight={2,8} transcludeWith=:::8](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +## 客户端命令 + +Fabric API 有一个存在于 `net.fabricmc.fabric.api.client.command.v2` 包中的 `ClientCommandManager`,可以帮助您注册客户端端的命令。 代码应当仅存在于客户端端的代码中。 + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/client/java/com/example/docs/client/command/FabricDocsReferenceClientCommands.java) + +## 命令重定向 + +命令重定向(也称为别名)是将一个命令的功能重定向到另一个命令的方法。 这在您想更改命令名称但仍希望支持旧名称时非常有用。 + +@[code lang=java transcludeWith=:::12](@/reference/latest/src/client/java/com/example/docs/client/command/FabricDocsReferenceClientCommands.java) + +## 常见问题 + +
+ +### 为什么我的代码不可以被编译? + +- 捕捉或者抛出 `CommandSyntaxException` - `CommandSyntaxException` 并不是一个 `RuntimeException`。 如果你抛出了它, 抛出它的地方应该是在方法签名中抛出 `CommandSyntaxException` 的方法中,或者被捕获。 + Brigadier 将处理已检查的异常并为您转发游戏中正确的错误消息。 如果抛出异常, + 那么应该在方法签名中声明该方法会抛出 `CommandSyntaxException`,或者应该对其进行捕获处理。 + Brigadier 将处理已检查的异常并为您转发游戏中正确的错误消息。 + +- 泛型问题──您可能有时候会遇到泛型的问题。 泛型问题──您可能有时候会遇到泛型的问题。 如果您要注册服务器命令(大多数情况),请确保使用 `CommandManager.literal` 或者 `CommandManager.argument` 而不是 `LiteralArgumentBuilder.literal` 或者 `RequiredArgumentBuilder.argument`。 + +- 检查 `sendFeedback()` 方法 - 您可能忘记提供布尔值作为第二个参数。 检查 `sendFeedback()` 方法 - 您可能忘记提供布尔值作为第二个参数。 请您谨记,自从 Minecraft 1.20 版本开始, 第一个参数是类型 `Supplier` 而不是 `Text`。 + +- 命令应当返回一个整型数字 - 注册命令时,`executes()` 方法接受一个 `Command` 对象,该对象通常是 lambda。 lambda 应该返回一个整型数字,而不是其他类型。 lambda 应该返回一个整型数字,而不是其他类型。 + +### 我可以在运行时注册命令吗? + +::: warning +You can do this, but it is not recommended. You would get the `CommandManager` from the server and add anything commands +you wish to its `CommandDispatcher`. + +之后,需要使用 `CommandManager.sendCommandTree(ServerPlayerEntity)` 将命令树再次发送给每个玩家。 + +这是必须的,因为客户端只会在玩家登录时本地缓存命令树(或者发送操作包时)以完成丰富的错误信息补全。 +::: + +### 我可以在运行时注销命令吗? + +::: warning +You can also do this, however, it is much less stable than registering commands at runtime and could cause unwanted side +effects. + +为了保持事情简单,你需要对 Brigadier 使用反射来移除节点。 为了保持事情简单,你需要对 Brigadier 使用反射来移除节点。 在那之后,您需要使用 `sendCommandTree(ServerPlayerEntity)` 将命令树再次发送给所有玩家。 + +如果您不发送更新后的命令树,客户端可能认为命令依然存在,即使服务器会执行失败。 +::: +::: diff --git a/versions/1.20.4/translated/zh_cn/develop/commands/suggestions.md b/versions/1.20.4/translated/zh_cn/develop/commands/suggestions.md new file mode 100644 index 000000000..69f21159a --- /dev/null +++ b/versions/1.20.4/translated/zh_cn/develop/commands/suggestions.md @@ -0,0 +1,45 @@ +--- +title: 命令提示 +description: 学习如何向用户提示命令参数的值。 +authors: + - IMB11 +--- + +# 命令提示 + +Minecraft 有一个使用在了很多地方的十分强大的命令建议系统,比如说 `/give` 命令。 该系统允许您向用户提示命令参数的值,然后他们可以从中选择 —— 这是使您的命令更加用户友好且符合人体工学的好办法。 该系统允许您向用户提示命令参数的值,然后他们可以从中选择 —— 这是使您的命令更加用户友好且符合人体工学的好办法。 + +## 提示提供器 + +提示所有可用的战利品表。 `SuggestionProvider` 用于创建发送给客户端的提示列表。 提示提供器是一个函数式接口,它使用 `CommandContext` 和 `SuggestionBuilder` 并返回 `Suggestions`。 `SuggestionProvider` 返回 `CompletableFuture` 因为提示可能不会立即可用。 `SuggestionProvider` 返回 `CompletableFuture` 因为提示可能不会立即可用。 + +## 使用提示提供器 + +要使用提示提供器,您可以在参数构造器上调用 `suggests` 方法。 此方法接受一个 `SuggestionProvider`,返回一个新的参数构造器,并附加提示提供器。 此方法接受一个 `SuggestionProvider`,返回一个新的参数构造器,并附加提示提供器。 + +@[code java transcludeWith=:::9 highlight={4}](@/reference/latest/src/main/java/com/example/docs/command/FabricDocsReferenceCommands.java) + +## 内建的提示提供器 + +您可以使用一些内建的提示提供器: + +| 提示提供器 | 描述 | +| ----------------------------------------- | ------------ | +| `SuggestionProviders.SUMMONABLE_ENTITIES` | 提示所有可被召唤的实体。 | +| `SuggestionProviders.AVAILABLE_SOUNDS` | 提示所有可被播放的声音。 | +| `LootCommand.SUGGESTION_PROVIDER` | 提示所有可用的战利品表。 | +| `SuggestionProviders.ALL_BIOMES` | 提示所有可用的生物群系。 | + +## 创建一个自定义的提示提供器 + +如果内建的提供器无法满足您的需要,您可以创建您自己的提示提供器。 为此,您需要创建一个实现 `SuggestionProvider` 接口的类,并重写 `getSuggestions` 方法。 为此,您需要创建一个实现 `SuggestionProvider` 接口的类,并重写 `getSuggestions` 方法。 + +对此示例,我们需要制作一个提示提供器提示所有在服务器上的玩家的名称。 + +@[code java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/command/PlayerSuggestionProvider.java) + +要使用该提示提供器,您只需将它的实例传递到参数构造器的 `.suggests` 方法。 + +显然,建议提供者可能更复杂,因为它们还可以读取命令上下文以根据命令的状态(例如已经提供的参数)提供建议。 + +这可以是读取玩家的背包或提示玩家附近的物品或实体的形式。 diff --git a/versions/1.20.4/translated/zh_cn/develop/entities/damage-types.md b/versions/1.20.4/translated/zh_cn/develop/entities/damage-types.md new file mode 100644 index 000000000..ba20b6ebb --- /dev/null +++ b/versions/1.20.4/translated/zh_cn/develop/entities/damage-types.md @@ -0,0 +1,96 @@ +--- +title: 伤害类型 +description: 学习如何添加自定义伤害类型。 +authors: + - dicedpixels + - hiisuuii + - mattidragon +--- + +# 伤害类型 + +有些伤害类型能够无视护甲,无视状态效果等等。 伤害类型的这些属性是由标签控制的。 有些伤害类型能够无视护甲,无视状态效果等等。 伤害类型的这些属性是由标签控制的。 伤害类型定义了实体能受到的伤害的种类。 从 Minecraft 1.19.4 开始,创建新的伤害类型的方式已经变为数据驱动的,也就是说它们由 JSON 文件创建。 + +## 创建一种伤害类型 + +让我们创建一种叫 _土豆_ 的伤害类型。 让我们创建一种叫 _土豆_ 的伤害类型。 我们先从为你的自定义伤害创建 JSON 文件开始。 这个文件将被放在你的模组的 `data` 目录下的 `damage_type` 子目录。 这个文件将被放在你的模组的 `data` 目录下的 `damage_type` 子目录。 + +```:no-line-numbers +resources/data/fabric-docs-reference/damage_type/tater.json +``` + +它有以下的结构: + +@[code lang=json](@/reference/latest/src/main/generated/data/fabric-docs-reference/damage_type/tater.json) + +这个自定义伤害类型在玩家每次受到来自非玩家的生物(例:方块)造成的伤害时增加 0.1 [消耗度](https://zh.minecraft.wiki/w/饥饿#饥饿因素)。 此外,造成的伤害量将随存档难度而变化。 此外,造成的伤害量将随存档难度而变化。 此外,造成的伤害量将随存档难度而变化。 + +::: info + +所有可用的键值详见 [Minecraft Wiki](https://zh.minecraft.wiki/w/伤害类型/JSON格式)。 + +::: + +### 通过代码访问伤害类型 + +当我们需要在代码中访问我们的自定义伤害类型时,我们将用它的 `RegistryKey` 来创建一个 `DamageSource` 实例。 + +所需的 `RegistryKey` 可用以下方式获取: + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/damage/FabricDocsReferenceDamageTypes.java) + +### 使用伤害类型 + +为了演示自定义伤害类型如何使用,我们将使用一个自定义方块 _土豆块_ 。 让我们实现当生物踩在 _土豆块_ 上时,它会对生物造成 _土豆_ 伤害。 + +你可以重写 `onSteppedOn` 方法来造成这个伤害。 + +我们从创建一个属于我们的自定义伤害类型的 `DamageSource` 开始。 + +@[code lang=java transclude={21-24}](@/reference/latest/src/main/java/com/example/docs/damage/TaterBlock.java) + +然后,我们调用 `entity.damage()` 并传入 我们的 `DamageSource` 和伤害量。 + +@[code lang=java transclude={25-25}](@/reference/latest/src/main/java/com/example/docs/damage/TaterBlock.java) + +方块的完整实现: + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/damage/TaterBlock.java) + +现在,每当生物踩在我们的自定义方块上时,它将受到使用我们的自定义伤害类型的 5 点伤害(2.5 颗心)。 + +### 自定义死亡信息 + +你可以在你的模组的 `en_us.json` 文件中以 `death.attack.` 的格式定义伤害类型的死亡信息。 + +@[code lang=json transclude={4-4}](@/reference/latest/src/main/resources/assets/fabric-docs-reference/lang/en_us.json) + +当死因是我们的伤害类型时,你将会看到如下的死亡信息: + +![玩家物品栏内的效果](/assets/develop/tater-damage-death.png) + +### 伤害类型标签 + +有些伤害类型能够无视护甲,无视状态效果等等。 伤害类型的这些属性是由标签控制的。 + +你可以在 `data/minecraft/tags/damage_type` 中找到既有的伤害类型标签。 + +::: info + +全部伤害类型的列表详见 [Minecraft Wiki](https://zh.minecraft.wiki/w/标签#伤害类型)。 + +::: + +让我们把我们的土豆伤害类型加入伤害类型标签 `bypasses_armor`。 + +为了把我们的伤害类型加入这些标签,我们需要在 `minecraft` 命名空间下创建一个 JSON 文件。 + +```:no-line-numbers +data/minecraft/tags/damage_type/bypasses_armor.json +``` + +包含以下内容: + +@[code lang=json](@/reference/latest/src/main/generated/data/minecraft/tags/damage_type/bypasses_armor.json) + +将 `replace` 设置为 `false` 以确保你的标签不会替换既有的标签。 diff --git a/versions/1.20.4/translated/zh_cn/develop/entities/effects.md b/versions/1.20.4/translated/zh_cn/develop/entities/effects.md new file mode 100644 index 000000000..805cd3ca4 --- /dev/null +++ b/versions/1.20.4/translated/zh_cn/develop/entities/effects.md @@ -0,0 +1,70 @@ +--- +title: 状态效果 +description: 学习如何添加自定义状态效果。 +authors: + - dicedpixels + - YanisBft + - FireBlast + - Friendly-Banana + - SattesKrokodil +authors-nogithub: + - siglong + - tao0lu +--- + +# 状态效果 + +状态效果,又称效果,是一种可以影响实体的条件。 它们的性质可以是正面的,负面的或者中性的。 游戏本体通过许多不同的方式应用这些效果,如食物和药水等等。 + +命令 `/effect` 可被用于给实体应用效果。 + +## 自定义状态效果 + +在这篇教程中我们将加入一个叫 _土豆_ 的新状态效果,它会每游戏刻给你 1 点经验。 + +### 继承 `StatusEffect` + +让我们通过继承所有状态效果的基类 `StatusEffect` 来创建一个自定义状态效果类。 + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/effect/TaterEffect.java) + +### 注册你的自定义状态效果 + +与注册方块和物品类似,我们使用 `Registry.register` 将我们的自定义状态效果注册到 `STATUS_EFFECT` 注册表。 这可以在我们的模组入口点内完成。 这可以在我们的模组入口点内完成。 + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/effect/FabricDocsReferenceEffects.java) + +### 本地化与纹理 + +您可以为您的状态效果指定名称并提供一个纹理(texture)图标,这将显示在玩家背包中。 + +#### **纹理** + +状态效果图标是 18x18 的 PNG。 将您的自定义图标放在: 将您的自定义图标放在: + +```:no-line-numbers +resources/assets/fabric-docs-reference/textures/mob_effect/tater.png +``` + +![在玩家背包中的效果](/assets/develop/tater-effect.png) + +#### **翻译** + +像其它翻译一样,您可以添加一个 ID 格式的条目 `"effect..": "Value"` 到语言文件中。 + +::: code-group + +```json[assets/fabric-docs-reference/lang/en_us.json] +{ + "effect.fabric-docs-reference.tater": "Tater" +} +``` + +### 测试 + +使用命令 `/effect give @p fabric-docs-reference:tater` 为玩家提供 Tater 效果。 +使用命令 `/effect give @p fabric-docs-reference:tater` 为玩家提供 Tater 效果。 使用 `/effect clear` 移除该效果。 + +::: info +要创建使用此效果的药水,请参阅[药水](../items/potions)指南。 +::: diff --git a/versions/1.20.4/translated/zh_cn/develop/getting-started/creating-a-project.md b/versions/1.20.4/translated/zh_cn/develop/getting-started/creating-a-project.md new file mode 100644 index 000000000..a3a636323 --- /dev/null +++ b/versions/1.20.4/translated/zh_cn/develop/getting-started/creating-a-project.md @@ -0,0 +1,68 @@ +--- +title: 创建项目 +description: 关于如何使用 Fabric 模板模组生成器创建新的模组项目的逐步指南。 +authors: + - IMB11 +--- + +# 创建项目{#creating-a-project} + +Fabric 提供了一种简单的方法来使用 Fabric 模板模组生成器来创建新的模组项目——如果你愿意,你可以使用示例模组代码仓库手动创建一个新项目,请参考[手动创建项目](#manual-project-creation)章节。 + +## 生成项目{#generating-a-project} + +你可以使用 [Fabric 模板模组生成器](https://fabricmc.net/develop/template/)为你的模组生成一个新项目——你应该填写必要的字段,比如包名和模组名称,以及你想要基于开发的 Minecraft 版本。 + +![生成器预览图](/assets/develop/getting-started/template-generator.png) + +如果你想要使用 Kotlin 语言开发,或者想要添加数据生成器,可以在“Advanced Options”部分中选择对应的选项。 + +![“Advanced Options”部分](/assets/develop/getting-started/template-generator-advanced.png) + +填写好了必需的字段后,单击“Generate”按钮,生成器将以 zip 文件的形式创建新项目供你使用。 + +你需要将这个 zip 文件解压到你想要的位置,然后在 IntelliJ IDEA 中打开解压的文件夹: + +![打开项目按钮提示](/assets/develop/getting-started/open-project.png) + +## 导入项目{#importing-the-project} + +你在 IntelliJ IDEA 中打开了项目之后,IDEA 会自动加载项目的 Gradle 配置并执行必要的初始化任务。 + +如果收到一个关于 Gradle 构建脚本的通知,应该点击 `Import Gradle Project` 按钮: + +![Gradle 按钮提示](/assets/develop/getting-started/gradle-prompt.png) + +项目导入好之后,你可以在项目资源管理器中看到项目的文件,就能够开始开发你的模组了。 + +## 手动创建项目{#manual-project-creation} + +:::warning +你需要安装 [Git](https://git-scm.com/) 来克隆示例模组代码仓库。 +::: + +如果不能使用 Fabric 模板模组生成器,可以按以下步骤手动创建新项目。 + +首先,使用 Git 克隆示例模组代码仓库: + +```sh +git clone https://github.com/FabricMC/fabric-example-mod/ my-mod-project +``` + +这会将代码仓库克隆进一个叫 `my-mod-project`的新文件夹。 + +然后,您应该删除`.git`文件夹,并在IntelliJ IDEA中打开项目。 如果你找不到`.git`文件夹,你需要在你的文件资源管理器中启用显示隐藏文件。 如果你找不到`.git`文件夹,你需要在你的文件资源管理器中启用显示隐藏文件。 如果 `.git` 文件夹没有出现,需要在你的文件资源管理器中启用显示隐藏文件。 + +在 IntelliJ IDEA 中打开了项目之后,IDEA 会自动加载项目的 Gradle 配置并执行必要的初始化任务。 + +强调一遍,如上所述,如果你收到一个关于 Gradle 构建脚本的通知,你应该点击 `Import Gradle Project` 按钮: + +### 修改模板{#modifying-the-template} + +项目导入好后,你需要修改项目的细节,以匹配你的模组的信息: + +- 修改项目的 `gradle.properties` 文件,把 `maven_group` 和 `archive_base_name` 修改为匹配你的模组的信息。 +- 修改项目中的 `fabric.mod.json` 文件,把 `id`、`name` 和 `description` 修改为匹配你的模组的信息。 +- 确保修改你的项目的Minecraft的版本,映射,Fabric模组加载器和Fabric loom——所有这些都可以通过https://fabricmc.net/develop/查询,以匹配您希望的目标版本。 + +你还可以修改包名和模组的主类来匹配你的模组的细节。 diff --git a/versions/1.20.4/translated/zh_cn/develop/getting-started/introduction-to-fabric-and-modding.md b/versions/1.20.4/translated/zh_cn/develop/getting-started/introduction-to-fabric-and-modding.md new file mode 100644 index 000000000..995ec5d63 --- /dev/null +++ b/versions/1.20.4/translated/zh_cn/develop/getting-started/introduction-to-fabric-and-modding.md @@ -0,0 +1,65 @@ +--- +title: Fabric 和模组简介 +description: Minecraft:Java 版中 Fabric 和模组的简要介绍。 +authors: + - IMB11 + - itsmiir +authors-nogithub: + - basil4088 +--- + +# Fabric 和模组简介 + +## 先决条件 + +在开始学习之前,你应该对 Java 开发有基本的了解,并对面向对象编程(OOP)有所认识。 + +如果你不熟悉这些概念,在开始开发之前,你可能需要了解一些有关 Java 和 OOP 的教程,以下是可以用来学习 Java 和 OOP 的一些资源: + +- [W3: Java Tutorials](https://www.w3schools.com/java/) +- [Codecademy: Learn Java](https://www.codecademy.com/learn/learn-java) +- [W3: Java OOP](https://www.w3schools.com/java/java_oop.asp) +- [Medium: Introduction to OOP](https://medium.com/@Adekola_Olawale/beginners-guide-to-object-oriented-programming-a94601ea2fbd) + +### 术语 + +开始之前,先来看看使用 Fabric 编写模组时会遇到的一些术语: + +- **模组(Mod)**: 对游戏的修改,添加新功能或更改现有功能。 +- **模组加载器(Mod Loader)**: 将模组载入游戏的工具,例如 Fabric Loader。 +- **Mixin**: 运行时修改游戏代码的工具——更多信息请参阅 [Mixin 介绍](https://fabricmc.net/wiki/zh_cn::tutorial:mixin_introduction) 。 +- **Gradle**: 用于构建和编译模组的自动化构建工具,Fabric 用其构建模组。 +- **映射(Mappings)**: 将被混淆的代码转化为人类可读代码的映射的集合。 +- **混淆(Obfuscation)**: 使代码无法被人类阅读的过程,Mojang 用其来保护 Minecraft 的源代码。 +- **重映射(Remapping)**: 将混淆代码映射为人类可读代码的过程。 + +## Fabric 是什么? {#what-is-fabric} + +Fabric 是用于 Minecraft: Java Edition 的轻量级模组开发工具链。 + +Fabric 旨在成为简单易用的模组开发平台。 Fabric 是由社区驱动的项目,而且开源,这意味着任何人都可以为项目做出贡献。 + +你应该了解的 Fabric 的四个主要组成部分: + +- **Fabric Loader**: 灵活的独立于平台的模组加载器,专为 Minecraft 及其他游戏和应用程序而设计。 +- **Fabric Loom**:Gradle 插件,使开发者能够轻松开发和调试模组。 +- **Fabric API**:一套 API 和工具,供模组开发者在创建模组时使用。 +- **Yarn**: 一套开放的 Minecraft 映射表,在 Creative Commons Zero 许可证下供所有人任意使用。 + +## 为什么开发 Minecraft 模组需要 Fabric? {#why-is-fabric-necessary-to-mod-minecraft} + +> “模组(Modding)”是指修改游戏以改变其行为或添加新功能的过程,就 Minecraft 而言,这可以是添加新物品、方块或实体,也可以是改变游戏机制或添加新的游戏模式。 + +Minecraft: Java Edition 被 Mojang 混淆,因此很难单独修改。 不过,在 Fabric 等模组开发工具的帮助下,修改变得更加容易。 有一些映射系统可以协助这一过程。 + +Loom 使用这些映射将混淆代码重映射为人类可读的格式,使模组开发者更容易理解和修改游戏代码。 在这方面,Yarn 是一个富有人气且十分优秀的映射选择,但也有其他选择。 每个映射表项目都有自己的优势和侧重点。 + +Loom 可让你轻松开发且编译重映射模组的代码,而 Fabric Loader 可让你将这些模组加载到游戏中。 + +## Fabric API 提供哪些功能,为什么需要它? {#what-does-fabric-api-provide-and-why-is-it-needed} + +> Fabric API 是一套 API 和工具,供模组开发者在创建模组时使用。 + +Fabric API 在 Minecraft 现有功能的基础上提供了一系列使开发更方便的 API。例如,提供新的 Hook 和事件供开发者使用,或提供新的实用程序和工具让魔改变得更容易,如访问加宽器(Access Wideners)和访问内部注册表(如可堆肥物品注册表)的能力。 + +虽然 Fabric API 提供了强大的功能,但有些任务,如基本的方块注册,不使用 Fabric API 也能完成。 diff --git a/versions/1.20.4/translated/zh_cn/develop/getting-started/launching-the-game.md b/versions/1.20.4/translated/zh_cn/develop/getting-started/launching-the-game.md new file mode 100644 index 000000000..f97287da9 --- /dev/null +++ b/versions/1.20.4/translated/zh_cn/develop/getting-started/launching-the-game.md @@ -0,0 +1,63 @@ +--- +title: 启动游戏 +description: 了解如何利用各种启动配置文件在实时游戏环境中启动和调试你的模组。 +authors: + - IMB11 +--- + +# 启动游戏{#launching-the-game} + +Fabric Loom 提供了各种启动配置文件,可以帮助你在实时游戏环境中启动以及调试你的模组。 本指南将介绍各种启动配置文件以及如何用它们来调试和在游戏中测试你的模组。 + +## 启动配置文件{#launch-profiles} + +如果在使用 IntelliJ IDEA,那么可以从窗口右上角找到启动配置文件。 单击下拉菜单可以查看可用的启动配置文件。 + +应该有一个客户端和服务器配置文件,可以选择正常运行或在调试模式下运行它: + +![启动配置文件](/assets/develop/getting-started/launch-profiles.png) + +## Gradle 任务{#gradle-tasks} + +如果使用的是命令行,则可以使用以下 Gradle 命令启动游戏: + +- `./gradlew runClient` - 以客户端模式启动游戏。 +- `./gradlew runServer` - 以服务器模式启动游戏。 + +这种方法的唯一问题是无法轻松调试代码。 如果要调试代码,则需要使用 IntelliJ IDEA 中的启动配置文件或通过你所使用的 IDE 中的 Gradle 集成。 + +## 热交换类{#hotswapping-classes} + +在调试模式下运行游戏时,可以热交换你的类而无需重启游戏。 这对于快速测试代码的更改很有用。 + +但你仍然受到很大限制: + +- 你无法添加或移除方法 +- 你无法更改方法参数 +- 你无法添加或移除字段 + +## 热交换 Mixin{#hotswapping-mixins} + +如果正在使用 Mixin,则可以热交换 Mixin 类而无需重启游戏。 这对于快速测试 Mixin 的更改很有用。 + +但是你需要安装 Mixin Java 代理才能使其正常工作。 + +### 1. 找到 Mixin 库 Jar{#1-locate-the-mixin-library-jar} + +在 IntelliJ IDEA 中,你可以在“项目”部分的“外部库”部分中找到 mixin 库 jar: + +![Mixin 库](/assets/develop/getting-started/mixin-library.png) + +你需要复制 jar 的“绝对路径”以供下一步使用。 + +### 2. 添加 `-javaagent` VM 参数{#2-add-the--javaagent-vm-argument} + +在你的“Minecraft 客户端”和/或“Minecraft 服务器”运行配置中,将以下内容添加到 VM 参数选项: + +```:no-line-numbers +-javaagent:"此处为 mixin 库 jar 的路径" +``` + +![VM 参数屏幕截图](/assets/develop/getting-started/vm-arguments.png) + +现在,你应该能够在调试期间修改 mixin 方法的内容,并且无需重启游戏即可使更改生效。 diff --git a/versions/1.20.4/translated/zh_cn/develop/getting-started/project-structure.md b/versions/1.20.4/translated/zh_cn/develop/getting-started/project-structure.md new file mode 100644 index 000000000..2b8074870 --- /dev/null +++ b/versions/1.20.4/translated/zh_cn/develop/getting-started/project-structure.md @@ -0,0 +1,59 @@ +--- +title: 项目结构 +description: Fabric 模组项目结构概述 +authors: + - IMB11 +--- + +# 项目结构{#project-structure} + +本页将介绍 Fabric 模组项目的结构以及项目中每个文件和文件夹的用途。 + +## `fabric.mod.json`{#fabric-mod-json} + +`fabric.mod.json` 是向 Fabric Loader 描述你的模组的主要文件, 包含模组的 ID、版本、依赖等信息。 + +`fabric.mod.json` 文件最重要的字段是: + +- `id`:模组的 ID,必须是独特的,不能和其他模组重复。 +- `name`:模组的显示名称。 +- `environment`:模组运行环境,可以是 `client`(仅客户端)、`server`(仅服务端)和 `*`(双端)。 +- `entrypoints`:模组提供的入口点,例如 `main` 和 `client` 等。 +- `depends`:模组的依赖模组/库。 +- `mixins`:模组提供的 Mixin。 + +下面看到的是示例的 `fabric.mod.json` 文件——这是该文档的开发参考项目的 `fabric.mod.json` 文件。 + +:::details 参考项目 `fabric.mod.json` +@[code lang=json](@/reference/latest/src/main/resources/fabric.mod.json) +::: + +## 入口点{#entrypoints} + +如前所述,`fabric.mod.json` 文件包含一个名为 `entrypoints` 的字段——该字段用于指定你的模组提供的入口点。 + +模组开发模板生成器默认创建 `main` 和 `client` 入口点——`main` 入口点用于双端共用部分,`client` 入口点用于客户端特定部分。 这些入口点将会在游戏启动时依次调用。 + +@[code lang=java transcludeWith=#entrypoint](@/reference/latest/src/main/java/com/example/docs/FabricDocsReference.java) + +上面是一个简单的 `main` 入口点的使用示例,会在游戏开始时记录一条消息到控制台。 + +## `src/main/resources`{#src-main-resources} + +`src/main/resources` 用于存储模组的资源文件,例如纹理、模型和声音。 + +它也是 `fabric.mod.json` 和模组使用的 Mixin 配置文件的存放位置。 + +资源文件存储在与资源包结构相似的结构中——例如,方块的纹理会存放在 `assets/modid/textures/block/block.png` 中。 + +## `src/client/resources`{#src-client-resources} + +`src/client/resources` 文件夹用于存储客户端特定的资源,例如仅在客户端使用的纹理、模型和音效。 + +## `src/main/java`{#src-main-java} + +`src/main/java` 文件夹用于存储模组的 Java 源代码——在客户端和服务端环境中都存在。 + +## `src/client/java`{#src-client-java} + +`src/client/java` 文件夹用于存储客户端专属的 Java 源代码,例如渲染代码或客户端逻辑——例如方块颜色提供程序。 diff --git a/versions/1.20.4/translated/zh_cn/develop/getting-started/setting-up-a-development-environment.md b/versions/1.20.4/translated/zh_cn/develop/getting-started/setting-up-a-development-environment.md new file mode 100644 index 000000000..b0ccf89e1 --- /dev/null +++ b/versions/1.20.4/translated/zh_cn/develop/getting-started/setting-up-a-development-environment.md @@ -0,0 +1,55 @@ +--- +title: 设置开发环境 +description: 关于如何搭建 Fabric 开发环境的逐步指南。 +authors: + - IMB11 + - andrew6rant + - SolidBlock-cn + - modmuss50 + - daomephsta + - liach + - telepathicgrunt + - 2xsaiko + - natanfudge + - mkpoli + - falseresync + - asiekierka +authors-nogithub: + - siglong +--- + +# 设置开发环境{#setting-up-a-development-environment} + +要开始使用 Fabric 开发模组,需要使用 IntelliJ IDEA 设置开发环境。 + +## 安装 JDK 17{#installing-jdk-17} + +为 Minecraft 1.20.4 开发模组需要 JDK 17。 + +如果需要安装 Java 方面的帮助,可以参考[玩家指南部分](../../players/index)中的各种 Java 安装指南。 + +## 安装 IntelliJ IDEA{#installing-intellij-idea} + +:::info +你显然可以使用其他 IDE, 比如 Eclipse 或 Visual Studio Code,但本文档站点上的大多数页面都假定你使用的是 IntelliJ IDEA - 如果你使用的是其他 IDE,则应参考那些 IDE 的文档。 +::: + +如果没有安装 IntelliJ IDEA,可以从[官方网站](https://www.jetbrains.com/idea/download/)下载 - 按照你的操作系统的安装步骤操作。 + +IntelliJ IDEA 的社区版是免费且开源的,是使用 Fabric 开发模组的推荐版本。 + +你可能需要向下滚动才能找到社区版下载链接 - 如下所示: + +![IDEA 社区版下载提示](/assets/develop/getting-started/idea-community.png) + +## 安装 IDEA 插件{#installing-idea-plugins} + +这些插件虽然不是绝对必要的,但可以让使用 Fabric 开发模组更容易 - 应该要考虑安装。 + +### Minecraft Development {#minecraft-development} + +Minecraft Development 插件为使用 Fabric 开发模组提供支持,是要安装的最重要的插件。 + +如要安装,可以打开 IntelliJ IDEA,然后在搜索栏中导航到 `文件 > 设置 > 插件 > Marketplace T标签页` - 在搜索框中搜索 `Minecraft Development`,然后点击 `安装` 按钮。 + +或者你可以从[插件页面](https://plugins.jetbrains.com/plugin/8327-minecraft-development) 下载它,然后依次点击 `文件 > 设置 > 插件 > 从硬盘上安装插件` 来安装。 diff --git a/versions/1.20.4/translated/zh_cn/develop/index.md b/versions/1.20.4/translated/zh_cn/develop/index.md new file mode 100644 index 000000000..f3df19383 --- /dev/null +++ b/versions/1.20.4/translated/zh_cn/develop/index.md @@ -0,0 +1,12 @@ +--- +title: 开发者指南 +description: 由社区精心撰写的开发者指南,涉及模组开发的方方面面,从搭建开发环境到更高级的主题,比如渲染和网络交互。 +--- + +# 开发者指南 + +由社区精心撰写的开发者指南,涉及模组开发的方方面面,从搭建开发环境到更高级的主题,比如渲染和网络交互。 + +不妨看看侧边栏的指南列表。 如果您在寻找某个具体的话题,您可以使用页面顶部的搜索栏。 + +如果您想给 Fabric 文档做贡献,您可以在[GitHub](https://github.com/FabricMC/fabric-docs) 找到本项目的源码,以及相关的[贡献指南](../contributing)。 diff --git a/versions/1.20.4/translated/zh_cn/develop/items/first-item.md b/versions/1.20.4/translated/zh_cn/develop/items/first-item.md new file mode 100644 index 000000000..71fbd78b1 --- /dev/null +++ b/versions/1.20.4/translated/zh_cn/develop/items/first-item.md @@ -0,0 +1,151 @@ +--- +title: 创建你的第一个物品 +description: 学习如何注册简单的物品,以及如何给物品添加纹理、模型和名称。 +authors: + - IMB11 + - dicedpixels +--- + +# 创建你的第一个物品{#creating-your-first-item} + +本页会带你介绍物品的一些关键概念,以及如果注册物品、添加纹理、添加模型、命名。 + +如果你还不知道的话,Minecraft 中的一切都存储在注册表中,物品也不例外。 + +## 准备你的物品类 {#preparing-your-items-class} + +要简化物品注册,可以创建一个方法,接收一个物品实例和字符串 id。 + +这个方法会用提供的 id 创建物品并在游戏的物品注册表中注册。 + +你可以将这个方法放在叫做 `ModItems` 的类中(也可以是其他你想要的名称)。 + +Mojang 也是对物品这么做的! 看看 `Items` 类以了解。 + +@[code transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/item/ModItems.java) + +## 注册物品{#registering-an-item} + +你现在可以用这个方法注册物品 + +物品的构造方法会接收一个 `Items.Settings` 类的实例作为参数。 这个类允许你通过一系列构造器方法配置物品的属性。 + +::: tip +If you want to change your item's stack size, you can use the `maxCount` method in the `Items.Settings`/`FabricItemSettings` class. + +如果将物品标记为可被破坏,那么这就不会生效,因为可被破坏的物品的堆叠大小永远是 1 以避免重复损坏。 +::: + +@[code transcludeWith=:::2](@/reference/latest/src/main/java/com/example/docs/item/ModItems.java) + +但是,进到游戏后,你会发现我们的物品不存在! 这是因为你还没有静态初始化类。 + +你可以在你的类中添加一个 public static 的初始化方法,然后在你的 `ModInitializer` 类中调用。 当前,方法不需要里面有任何东西。 + +@[code transcludeWith=:::3](@/reference/latest/src/main/java/com/example/docs/item/ModItems.java) + +@[code transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/item/FabricDocsReferenceItems.java) + +对类调用一个方法会静态初始化,如果还没有加载的话——这意味着所有的 `static` 字段都会计算。 这就是这个占位的 `initialize` 的方法的目的。 + +## 将物品添加到物品组{#adding-the-item-to-an-item-group} + +:::info +如果想要将物品添加到自定义的 `ItemGroup`,请参阅[自定义物品组](./item-groups)页面以了解更多。 +::: + +这里为举例,我们将这个物品添加到原材料物品组中,你需要使用 Fabric API 的 item group event——也就是 `ItemGroupEvents.modifyEntriesEvent`。 + +你可以在你的物品类的 `initialize` 方法中完成。 + +@[code transcludeWith=:::4](@/reference/latest/src/main/java/com/example/docs/item/ModItems.java) + +载入游戏,你会看到我们的物品已经注册好了,并且在原材料物品组中。 + +![原材料组中的物品](/assets/develop/items/first_item_0.png) + +然而,还缺这些: + +- 物品模型 +- 纹理 +- 翻译(名称) + +## 给物品命名{#naming-the-item} + +物品当前还没有翻译,所以需要添加。 Minecraft 已经提供好了翻译键:`item.mod_id.suspicious_substance`。 + +创建新的 JSON 文件:`src/main/resources/assets//lang/en_us.json`,并将翻译键和名称放在里面: + +```json +{ + "item.mod_id.suspicious_substance": "Suspicious Substance" +} +``` + +要应用更改,可以重启游戏,或者构建模组并按下F3 + T。 + +## 添加纹理和模型{#adding-a-texture-and-model} + +要给你的物品纹理和模型,先简单地为物品创建一个16x16的纹理图像,并存储在 `assets//textures/item` 文件夹中。 根据物品的 id 命名纹理文件的名字,但要有 `.png` 扩展名。 + +例如,将示例纹理用于 `suspicious_substance.png`。 + + + +重启或重新加载游戏时,你会发现物品还没有纹理,这是因为需要添加一个使用了此纹理的模型。 + +简单创建一个 `item/generated` 模型,接收一个输入纹理,没有其他的。 + +在 `assets//models/item` 文件夹内创建模型 JSON,名称与物品相同, `suspicious_substance.json` + +@[code](@/reference/latest/src/main/resources/assets/fabric-docs-reference/models/item/suspicious_substance.json) + +### 逐个分析模型 JSON{#breaking-down-the-model-json} + +- `parent`:模型要继承的模型。 在这个例子中,是 `item/generated` 模型。 +- `textures`:为模型定义纹理的地方。 `layer0` 键是模型使用的纹理。 + +大多物品继承的模型是 `item/generate`,因为这是显示纹理的简单模型。 + +也有其他的,比如 `item/handheld`,用于拿在玩家手中的物品,例如工具。 + +你的物品在游戏内看上去应该是这样: + +![模型正确的物品](/assets/develop/items/first_item_2.png) + +## 让物品可堆肥或作燃料 {#making-the-item-compostable-or-a-fuel} + +Fabric API 添加了各种注册表,可用于为物品添加额外属性。 + +例如,要让物品可堆肥,可以使用 `CompostableItemRegistry`: + +@[code transcludeWith=:::_10](@/reference/latest/src/main/java/com/example/docs/item/ModItems.java) + +又如,如果要让物品可作燃料,可以使用 `FuelRegistry` 类。 + +@[code transcludeWith=:::_11](@/reference/latest/src/main/java/com/example/docs/item/ModItems.java) + +## 添加基本的合成配方 {#adding-a-basic-crafting-recipe} + + + +如果要为你的物品添加合成配方,需要将配方 JSON 文件放在 `data//recipes` 文件夹中。 + +更多关于配方格式的信息,可参考以下资源: + +- [配方 JSON 生成器](https://crafting.thedestruc7i0n.ca/) +- [中文 Minecraft Wiki - 配方 JSON](https://zh.minecraft.wiki/w/配方#JSON格式) + +## 自定义物品提示 {#custom-tooltips} + +如果要让你的物品有自定义的物品提示,需要创建继承了 `Item` 的类,并覆盖 `appendTooltip` 方法。 + +:::info +这个例子使用 `LightningStick` 类,这是在[自定义物品交互](./custom-item-interactions)页面创建的。 +::: + +@[code lang=java transcludeWith=:::3](@/reference/latest/src/main/java/com/example/docs/item/custom/LightningStick.java) + +每次调用 `add()` 都会添加一行提示。 + +![物品提示演示](/assets/develop/items/first_item_3.png) diff --git a/versions/1.20.4/translated/zh_cn/develop/items/food.md b/versions/1.20.4/translated/zh_cn/develop/items/food.md new file mode 100644 index 000000000..d6274a2fe --- /dev/null +++ b/versions/1.20.4/translated/zh_cn/develop/items/food.md @@ -0,0 +1,51 @@ +--- +title: 食物物品 +description: 学会如何给物品添加 FoodComponent 以让它可食物,并配置。 +authors: + - IMB11 +--- + +# 食物物品{#food-items} + +食物是生存 Minecraft 的核心方面,所以创建可食用的物品时,需要考虑食物的用途以及其他可食用物品。 + +除非是在制作有过于强的物品的模型,否则应该考虑: + +- 你的可食用物品会添加或减少多少饥饿值。 +- 会给予什么药水效果? +- 是在游戏早期还是末期可用的? + +## 添加食物组件{#adding-the-food-component} + +要为物品添加食物组件,可以先传递到 `FabricItemSettings` 实例: + +```java +new FabricItemSettings().food(new FoodComponent.Builder().build()) +``` + +现在,只要让物品可食用,没有别的。 + +`FoodComponent` 类有很多方法,允许你修改玩家吃你的物品时发生的事情: + +| 方法 | 描述 | +| -------------------- | -------------------------------------------------------- | +| `hunger` | 设置你的物品会补充的饥饿值的数量。 | +| `saturationModifier` | 设置你的物品会增加的饱和度的数量。 | +| `meat` | 将你的物品描述为肉。 食肉动物,例如狼,将能够吃。 | +| `alwaysEdible` | 允许无论饥饿值均能吃你的物品。 | +| `snack` | 将你的物品描述为零食。 | +| `statusEffect` | 吃你的物品时添加状态效果。 通常传递到此方法的是一个状态效果实例和概率,其中概率是小数(`1f = 100%`) | + +按照自己的喜欢修改了 builder 后,可以调用 `build()` 方法以获得 `FoodComponent` + +使用[创建你的第一个物品](./first-item)页面中创建的例子,并为 builder 使用以下选项: + +@[code transcludeWith=:::5](@/reference/latest/src/main/java/com/example/docs/item/ModItems.java) + +这会让物品: + +- 总是可食用,无论饥饿值均可以吃。 +- 是“零食”。 +- 吃完会总会给予 6 秒中毒 II。 + + diff --git a/translated/zh_cn/develop/items/potions.md b/versions/1.20.4/translated/zh_cn/develop/items/potions.md similarity index 100% rename from translated/zh_cn/develop/items/potions.md rename to versions/1.20.4/translated/zh_cn/develop/items/potions.md diff --git a/translated/zh_cn/develop/rendering/basic-concepts.md b/versions/1.20.4/translated/zh_cn/develop/rendering/basic-concepts.md similarity index 100% rename from translated/zh_cn/develop/rendering/basic-concepts.md rename to versions/1.20.4/translated/zh_cn/develop/rendering/basic-concepts.md diff --git a/versions/1.20.4/translated/zh_cn/develop/rendering/draw-context.md b/versions/1.20.4/translated/zh_cn/develop/rendering/draw-context.md new file mode 100644 index 000000000..2a31aad9e --- /dev/null +++ b/versions/1.20.4/translated/zh_cn/develop/rendering/draw-context.md @@ -0,0 +1,94 @@ +--- +title: 使用绘制上下文 +description: 学习如何使用 DrawContext 类来渲染各种图形、文字、纹理。 +authors: + - IMB11 +--- + +# 使用绘制上下文 + +本文假设您已经看过[基本渲染概念](./basic-concepts)。 + +`DrawContext` 是控制渲染的核心类。 它提供了诸多渲染图形、文字、纹理的方法,此外还用来操纵 `MatrixStack` 和 `BufferBuilder`。 + +## 绘制图形 + +使用 `DrawContext` 绘制**矩形**十分容易。 如果您想绘制三角形或其他不规则图形,您需要使用 `BufferBuilder` 手动添加图形顶点信息。 + +### 绘制矩形 + +您可以使用 `DrawContext#fill` 方法来绘制一个实心矩形。 + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/client/java/com/example/docs/rendering/DrawContextExampleScreen.java) + +![矩形](/assets/develop/rendering/draw-context-rectangle.png) + +### 绘制边框 + +假设我们想勾勒出我们刚才绘制的矩形的轮廓。 我们可以使用 `DrawContext#drawBorder` 方法来绘制轮廓。 + +@[code lang=java transcludeWith=:::2](@/reference/latest/src/client/java/com/example/docs/rendering/DrawContextExampleScreen.java) + +![带边框的矩形](/assets/develop/rendering/draw-context-rectangle-border.png) + +### 绘制线条 + +我们可以使用 `DrawContext#drawHorizontalLine` 和 `DrawContext#drawVerticalLine` 来绘制线条。 + +@[code lang=java transcludeWith=:::3](@/reference/latest/src/client/java/com/example/docs/rendering/DrawContextExampleScreen.java) + +![线条](/assets/develop/rendering/draw-context-lines.png) + +## 裁剪 + +`DrawContext` 有一套内建的裁剪功能。 它可以用来裁剪渲染区域。 这个功能在绘制某些元素时十分有用,比如悬浮提示,或者其他不应该超出指定渲染区域的界面元素。 + +### 使用裁剪功能 + +:::tip +裁剪区域可以内嵌! 但是请一定配对 `enableScissor` 和 `disableScissor`,否则错误的裁剪区域将影响到其他界面元素。 +::: + +要启用裁剪功能,只需调用 `DrawContext#enableScissor` 方法。 同样地,调用 `DrawContext#disableScissor` 方法以禁用裁剪功能。 + +@[code lang=java transcludeWith=:::4](@/reference/latest/src/client/java/com/example/docs/rendering/DrawContextExampleScreen.java) + +![裁剪区域](/assets/develop/rendering/draw-context-scissor.png) + +如您所见,即使我们让游戏尝试用渐变色铺满整个界面,它却只能在裁剪区域内绘制。 + +## 绘制纹理 + +注意,不存在唯一“正确”的绘制纹理的方法,因为 `drawTexture` 有很多重载。 本节内容只会涵盖最常用的方法。 + +### 绘制整个纹理 + +一般来说,我们推荐您使用需要指定 `textureWidth` 和 `textureHeight` 参数的 `drawTexture` 方法重载。 因为如果使用不指定的重载, `DrawContext` 会假设您的纹理文件尺寸是 256x256,而您的纹理文件不一定是这个尺寸,于是渲染结果就不一定正确。 + +@[code lang=java transcludeWith=:::5](@/reference/latest/src/client/java/com/example/docs/rendering/DrawContextExampleScreen.java) + +![绘制整个纹理](/assets/develop/rendering/draw-context-whole-texture.png) + +### 绘制纹理的一部分 + +在这个情形中,我们需要指定纹理区域的 `u` 和 `v`。 这俩参数用于指定纹理区域左上角的坐标。另外,`regionWidth` 和 `regionHeight` 参数用于指定纹理区域的尺寸。 + +我们以此纹理为例。 + +![配方书纹理](/assets/develop/rendering/draw-context-recipe-book-background.png) + +如果我们只希望绘制包含放大镜的区域,我们可以使用如下 `u`、`v`、`regionWidth`、`regionHeight` 值: + +@[code lang=java transcludeWith=:::6](@/reference/latest/src/client/java/com/example/docs/rendering/DrawContextExampleScreen.java) + +![绘制纹理的一部分](/assets/develop/rendering/draw-context-region-texture.png) + +## 绘制文字 + +`DrawContext` 提供了许多不言自明的渲染文字的方法,您可以自行尝试,此处不再赘述。 + +假设我们想在界面上绘制 `Hello World`。 我们可以使用 `DrawContext#drawText` 方法来完成。 + +@[code lang=java transcludeWith=:::7](@/reference/latest/src/client/java/com/example/docs/rendering/DrawContextExampleScreen.java) + +![绘制文字](/assets/develop/rendering/draw-context-text.png) diff --git a/versions/1.20.4/translated/zh_cn/develop/rendering/gui/custom-screens.md b/versions/1.20.4/translated/zh_cn/develop/rendering/gui/custom-screens.md new file mode 100644 index 000000000..6dd5cd5a7 --- /dev/null +++ b/versions/1.20.4/translated/zh_cn/develop/rendering/gui/custom-screens.md @@ -0,0 +1,64 @@ +--- +title: 自定义界面 +description: 学习如何给你的模组创建自定义界面。 +authors: + - IMB11 +--- + +# 自定义界面 + +:::info +本文所述均指一般的、未涉及同步的界面,这类界面是由玩家独自在客户端打开的,不需要服务端的参与。 +::: + +界面是指玩家可以交互的 GUI,比如标题界面、暂停界面等。 + +您可以创建自己的界面来展示自定义内容、自定义配置目录等。 + +## 创建界面 + +要创建界面,您需要继承 `Screen` 类并覆写 `init` 方法。您可能还需要覆写 `render` 方法,但是请保证调用 `super.render`, 否则背景和组件都不会渲染。 + +您需要注意: + +- 组件不应该在 `Screen` 的构造方法里创建,因为此时界面还没有初始化,并且某些变量(比如界面的宽 `width` 和高 `height`)也还没有正确地初始化。 +- 当界面正在初始化时,`init` 方法将被调用,这是创建组件对象的最佳时机。 + - 您可以通过 `addDrawableChild` 方法来添加组件,这个方法接收任何实现了 `Drawable` 和 `Element` 接口的组件对象。 +- `render` 方法将在每一帧被调用,您可以在这个方法里获取诸多上下文,比如鼠标的位置。 + +举个例子,我们可以创建一个简单的界面,这个界面有一个按钮和一个按钮的标签。 + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/client/java/com/example/docs/rendering/screens/CustomScreen.java) + +![自定义界面 1](/assets/develop/rendering/gui/custom-1-example.png) + +## 打开界面 + +您可以使用 `MinecraftClient` 类的 `setScreen` 方法来打开您的界面。您可以在许多地方做这件事,比如当一个按键触发时,当一条命令执行时,或者当客户端收到一个网络包时。 + +```java +MinecraftClient.getInstance().setScreen( + new CustomScreen(Text.empty()) +); +``` + +## 关闭界面 + +当您想要关闭界面时,只需将界面设为 `null` 即可: + +```java +MinecraftClient.getInstance().setScreen(null); +``` + +如果您希望在关闭界面时回退到上一个界面,您可以将当前界面对象传入自定义的 `CustomScreen` 构造方法,把它保存为字段,然后覆写 `close` 方法,将实现修改为 `this.client.setScreen(/* 您保存的上一个界面 */)` 即可。 + +@[code lang=java transcludeWith=:::2](@/reference/latest/src/client/java/com/example/docs/rendering/screens/CustomScreen.java) + +现在,当您按照上面的步骤打开界面时,您可以给构造方法的第二个参数传入当前界面对象,这样当您调用 `CustomScreen#close` 的时候,游戏就会回到上一个界面。 + +```java +Screen currentScreen = MinecraftClient.getInstance().currentScreen; +MinecraftClient.getInstance().setScreen( + new CustomScreen(Text.empty(), currentScreen) +); +``` diff --git a/versions/1.20.4/translated/zh_cn/develop/rendering/gui/custom-widgets.md b/versions/1.20.4/translated/zh_cn/develop/rendering/gui/custom-widgets.md new file mode 100644 index 000000000..a0f1bf8b2 --- /dev/null +++ b/versions/1.20.4/translated/zh_cn/develop/rendering/gui/custom-widgets.md @@ -0,0 +1,39 @@ +--- +title: 自定义组件 +description: 学习如何给您的界面创建自定义组件。 +authors: + - IMB11 +--- + +# 自定义组件 + +组件是一类容器化的界面元素,它们可以被添加到界面上供玩家交互,交互方式包括鼠标点击、键盘输入等。 + +## 创建组件 + +有很多种创建组件的方式,最常用的是继承自 `ClickableWidget`。 这个类提供了许多实用功能,比如控制组件的尺寸和位置,以及接收用户输入事件。事实上这些功能由 `Drawable`、`Element`、`Narratable`、`Selectable` 接口规定: + +- `Drawable` 用于指定渲染逻辑。当一个组件实现此接口时,您可以通过 `Screen#addDrawableChild` 将组件对象添加至界面中。 +- `Element` 用于接收用户输入事件,比如鼠标点击、键盘输入等。 +- `Narratable` 用于提供无障碍信息,无障碍功能(如复述)通过此接口访问组件内容。 +- `Selectable` 用于聚焦组件,实现此接口后组件可以由 `Tab` 键选中,这也是一种无障碍功能。 + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/client/java/com/example/docs/rendering/screens/CustomWidget.java) + +## 将组件添加至界面 + +如同其他组件,您需要使用 `Screen#addDrawableChild` 来将组件添加到界面中。 请确保这一步在 `Screen#init` 方法中完成。 + +@[code lang=java transcludeWith=:::3](@/reference/latest/src/client/java/com/example/docs/rendering/screens/CustomScreen.java) + +![界面上的自定义组件](/assets/develop/rendering/gui/custom-widget-example.png) + +## 用户输入事件 + +您可以自定义用户输入事件的处理逻辑,比如覆写 `onMouseClicked`、`onMouseReleased`、`onKeyPressed` 等方法。 + +举个例子,您可以使用 `ClickableWidget#isHovered` 方法来使组件在鼠标悬停时变色。 + +@[code lang=java transcludeWith=:::2](@/reference/latest/src/client/java/com/example/docs/rendering/screens/CustomWidget.java) + +![鼠标悬停事件](/assets/develop/rendering/gui/custom-widget-events.webp) diff --git a/translated/zh_cn/develop/rendering/hud.md b/versions/1.20.4/translated/zh_cn/develop/rendering/hud.md similarity index 100% rename from translated/zh_cn/develop/rendering/hud.md rename to versions/1.20.4/translated/zh_cn/develop/rendering/hud.md diff --git a/versions/1.20.4/translated/zh_cn/develop/sounds/custom.md b/versions/1.20.4/translated/zh_cn/develop/sounds/custom.md new file mode 100644 index 000000000..ca0352f0b --- /dev/null +++ b/versions/1.20.4/translated/zh_cn/develop/sounds/custom.md @@ -0,0 +1,63 @@ +--- +title: 创建自定义音效 +description: 了解如何通过注册表添加和使用新音效。 +authors: + - JR1811 +--- + +# 创建自定义音效 + +## 准备音频文件 + +你的音频文件需要转化为特定格式。 你的音频文件需要转化为特定格式。 OGG Vorbis 是一种用于音频等多媒体数据的开放式容器格式,Minecraft 的声音文件就使用了这种格式。 为了避免 Minecraft 处理声音传播距离的问题,你的音频必须只有单声道 (Mono)。 为了避免 Minecraft 处理声音传播距离的问题,你的音频必须只有单声道 (Mono)。 + +整理工作 大部分现代 DAW (数字音频工作站) 软件都可以使用这种格式进行导入和导出。 在下面的例子中,我们将使用免费开源软件“[Audacity](https://www.audacityteam.org/)”将音频文件转换成规定的格式,当然其他的 DAW 也可以做到。 + +![Audacity 中未准备好的音频文件](/assets/develop/sounds/custom_sounds_0.png) + +在本例中,[哨声](https://freesound.org/people/strongbot/sounds/568995/) 被作为例子导入 Audacity。 它目前被保存为`.wav`格式的文件,有两个音频通道 (立体声) 。 按照自己的需求编辑音频,并确保使用“音轨头”顶部的下拉元素删除其中一个音频通道。 它目前被保存为`.wav`格式的文件,有两个音频通道 (立体声) 。 按照自己的需求编辑音频,并确保使用“音轨头”顶部的下拉元素删除其中一个音频通道。 + +![分割立体声轨](/assets/develop/sounds/custom_sounds_1.png) + +![删除一个音频通道](/assets/develop/sounds/custom_sounds_2.png) + +导出或渲染音频文件时,请确认选择的是 OGG 文件格式。 有些 DAW (如 REAPER) 可能支持多种 OGG 音频层格式。 在这种情况下,选择 OGG Vorbis 即可。 根据注册表项的数量,入口点类可能很快就会变得十分杂乱。 为了避免这种情况,我们可以使用一个新的辅助类。 在这种情况下,选择 OGG Vorbis 即可。 + +![导出为 OGG 文件](/assets/develop/sounds/custom_sounds_3.png) + +另外,音频文件过大会导致模组文件也更大。 如有必要,在编辑和导出文件时适量压缩音频本身,以尽量减小导出的文件大小。 如有必要,在编辑和导出文件时适量压缩音频本身,以尽量减小导出的文件大小。 + +## 加载音频文件 + +要在你的模组中使用音频文件,要添加新的 `resources/assets//sounds` 目录,并将导出的音频文件 `metal_whistle.ogg` 放入该目录中。 + +如果 `resources/assets//sounds.json` 文件还未生成,继续创建该文件,并将你的音效添加到音效条目中。 + +@[code lang=json](@/reference/latest/src/main/resources/assets/fabric-docs-reference/sounds.json) + +声音字幕 (subtitle) 条目为玩家提供了更多的关于该声音的信息。 声音字幕 (subtitle) 条目为玩家提供了更多的关于该声音的信息。 声音字幕翻译键会在 `resources/assets//lang` 目录下的语言文件中用到,如果游戏内字幕设置已打开且正在播放自定义声音,则会显示该翻译键在语言文件内对应的值,如果找不到,那么会直接显示该声音字幕的翻译键。 + +## 注册自定义音效 + +要将自定义音效添加到模组里,请在实现了 `ModInitializer` 入口点的类中注册一个 SoundEvent。 + +```java +Registry.register(Registries.SOUND_EVENT, new Identifier(MOD_ID, "metal_whistle"), + SoundEvent.of(new Identifier(MOD_ID, "metal_whistle"))); +``` + +## 规范化 + +根据注册表项的数量,入口点类可能很快就会变得十分杂乱。 为了避免这种情况,我们可以使用一个新的辅助类。 + +在新创建的辅助类中添加两个新方法: 一个用于注册所有音效,一个用于初始化该类。 之后就可以根据需要,添加新的自定义 `SoundEvent` 常量了。 + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/sound/CustomSounds.java) + +如此,在实现了 `ModInitializer` 的入口点类中,只需调用一行即可注册所有的自定义 SoundEvents。 + +@[code lang=java transcludeWith=:::2](@/reference/latest/src/main/java/com/example/docs/sound/FabricDocsReferenceSounds.java) + +## 使用自定义的 SoundEvent + +使用辅助类去访问自定义的 SoundEvent。 查看 [播放声音事件(SoundEvent)](./using-sounds) 页面,了解如何播放声音。 diff --git a/versions/1.20.4/translated/zh_cn/develop/sounds/using-sounds.md b/versions/1.20.4/translated/zh_cn/develop/sounds/using-sounds.md new file mode 100644 index 000000000..dd884fbbe --- /dev/null +++ b/versions/1.20.4/translated/zh_cn/develop/sounds/using-sounds.md @@ -0,0 +1,32 @@ +--- +title: 播放声音事件(SoundEvent) +description: 学习如何播放声音事件(SoundEvent)。 +--- + +# 播放声音事件(SoundEvent) + +Minecraft 有大量的声音供您选择。 查看 `SoundEvents` 类以查看 Mojang 提供的所有原版声音事件实例。 + +## 在您的模组中使用声音 + +使用声音时请确保在逻辑服务端执行 `playSound()` 方法。 + +在此示例中,自定义交互项的 `useOnEntity()` 和 `useOnBlock()` 方法用于播放“放置铜块”和掠夺者声音。 + +@[code lang=java transcludeWith=:::1](@/reference/latest/src/main/java/com/example/docs/item/CustomSoundItem.java) + +`playerSound()` 方法与 `LivingEntity` 对象一起使用。 只需要指定 SoundEvent、音量(volume)和音高(pitch)。 您还可以使用世界实例中的 `playSound()` 方法以获得更高级别的控制。 + +@[code lang=java transcludeWith=:::2](@/reference/latest/src/main/java/com/example/docs/item/CustomSoundItem.java) + +### 声音事件与声音组(SoundCategory) + +声音事件定义了播放哪个声音。 您也可以[注册您自己的声音事件](./custom)以包含您自己的声音。 + +Minecraft 在游戏设置中有多个音频滑块。 `SoundCategory` 枚举类用于确定哪个滑块可以调整您声音的音量。 + +### 音量和音高 + +音量参数可能有些误导。 在 `0.0f - 1.0f` 的范围内可以改变声音的实际音量。 如果数字大于这个范围,将使用 `1.0f` 的音量,并且仅使用您所在的距离。可以听到声音,进行调整。 通过 `volume * 16` 可以粗略算出方块距离。 + +音高参数会增加或减少音高数值,还会改变声音的持续时间。 在 `(0.5f - 1.0f)` 范围内,音高和速度会减小,而较大的数字会增加音高和速度。 `0.5f` 以下的数字将保持 `0.5f`。 diff --git a/versions/1.20.4/translated/zh_cn/index.md b/versions/1.20.4/translated/zh_cn/index.md new file mode 100644 index 000000000..f8d0498e7 --- /dev/null +++ b/versions/1.20.4/translated/zh_cn/index.md @@ -0,0 +1,27 @@ +--- +title: Fabric 文档 +description: 为 Fabric —— 一套 Minecraft 模组工具链 —— 精心撰写的官方文档。 +layout: home +hero: + name: Fabric 文档 + tagline: 为 Fabric —— 一套 Minecraft 模组工具链 —— 精心撰写的官方文档。 +features: + - title: 开发者指南 + icon: 🛠️ + details: 由社区精心撰写的开发者指南,涉及模组开发的方方面面,从搭建开发环境到更高级的主题,比如渲染和网络交互。 + link: ./develop/index + linkText: 快速上手 + - title: 玩家指南 + icon: 📚 + details: 您在考虑使用 Fabric 模组吗? 我们的玩家指南将全程为您服务。 这些指南将从 Fabric 模组的下载、安装、错误排除等方面帮助您。 + link: ./players/index + linkText: 详情 +--- + +
+ +## 如何贡献? {#contribute} + +如果您想给 Fabric 文档做贡献,您可以在[GitHub](https://github.com/FabricMC/fabric-docs) 找到本项目的源码,以及相关的[贡献指南](./contributing)。 + +
diff --git a/versions/1.20.4/translated/zh_cn/players/faq.md b/versions/1.20.4/translated/zh_cn/players/faq.md new file mode 100644 index 000000000..f4f699057 --- /dev/null +++ b/versions/1.20.4/translated/zh_cn/players/faq.md @@ -0,0 +1,31 @@ +--- +title: 玩家常见问题 +description: 玩家和服务器管理员有关 Fabric 的常见问题。 +--- + +# 玩家常见问题 + +有很多问题经常被问到,因此我们在此整理了一份问题清单。 + +## 常规问题 + +### Fabric支持哪些Minecraft版本? + +Fabric 官方支持从快照 `18w43b` 和正式版 `1.14` 及以上的所有 Minecraft 版本。 + +### 在哪里可以下载已发布的 Fabric 模组? + +:::info +您应始终检查模组是否来自可信的来源。 您应始终检查模组是否来自可信的来源。 如果你想要获取更多信息,请查看 [寻找可受信的模组](./finding-mods) 指南。 +::: + +大多数作者都会将自己的模组发布到 [Modrinth](https://modrinth.com/mods?g=categories:%27fabric%27) 和 [CurseForge](https://www.curseforge.com/minecraft/search?class=mc-mods&gameVersionTypeId=4) 上,但也有一些作者会选择将它们上传到个人网站或其他平台,如 GitHub 仓库。 + +### 在哪里可以找到现成的 Fabric 整合包? + +您可以在各种平台上找到现成的 Fabric 整合包,例如 + +- [Modrinth](https://modrinth.com/modpacks?g=categories:%27fabric%27) +- [CurseForge](https://www.curseforge.com/minecraft/search?class=modpacks&gameVersionTypeId=4) +- [Feed The Beast](https://www.feed-the-beast.com/ftb-app) +- [Technic](https://www.technicpack.net/modpacks) diff --git a/versions/1.20.4/translated/zh_cn/players/finding-mods.md b/versions/1.20.4/translated/zh_cn/players/finding-mods.md new file mode 100644 index 000000000..65de5786c --- /dev/null +++ b/versions/1.20.4/translated/zh_cn/players/finding-mods.md @@ -0,0 +1,34 @@ +--- +title: 寻找可信赖的模组 +description: 本指南教你如何使用可信任的来源找到 Fabric 模组 +authors: + - IMB11 +--- + +# 寻找可信赖的模组{#finding-mods} + +首先,信任是主观的,当下载模组时你应该始终根据自己的判断。 但是,有一些方法可以帮助你找到可信赖的模组。 + +## 1. 使用众所周知的可信任来源{#trustworthy-source} + +大部分作者都将他们的模组发布在 [Modrinth](https://modrinth.com/mods?g=categories:%27fabric%27) 和 [CurseForge](https://www.curseforge.com/minecraft/search?class=mc-mods\\&gameVersionTypeId=4) 上。 + +这些网站会检查模组是否为他们所说的,以及是否包含恶意代码。 你还可以向那些网站举报恶意模组,他们会较快地行动。 + +## 2. 与其他人讨论! {#with-others} + +如果要从并非已知可靠的来源下载模组,应该先向他人询问,看看他们是否曾从你下载的地方下载过该模组,以及他们是否遇到过任何问题。 + +如遇问题,欢迎在 [Fabric Discord](https://discord.gg/v6v4pMv) 的 `#player-support` 频道提问。 + +## 3. 避免常见的恶意网站! {#avoid-malware} + +:::info +恶意软件网站并非人人都能辨别。 如果不确定,应征求他人的意见,或避免使用该网站,只依靠值得信赖的来源,例如 Modrinth 和 CurseForge。 +::: + +有很多网站声称它们收录 Minecraft 模组,但实际上只是恶意软件分发网站。 你应该尽量避免使用此类网站。 + +你可以使用 [Windows Defender](https://www.microsoft.com/en-us/windows/comprehensive-security) 或 [VirusTotal](https://www.virustotal.com/) 等杀毒软件或网站来检查下载的模组。 但是,不要完全依赖这些方法,因为有时可能不正确。 + +最后,如遇问题,欢迎在 [Fabric Discord](https://discord.gg/v6v4pMv) 的 `#player-support` 频道提问。 diff --git a/versions/1.20.4/translated/zh_cn/players/index.md b/versions/1.20.4/translated/zh_cn/players/index.md new file mode 100644 index 000000000..238a297ac --- /dev/null +++ b/versions/1.20.4/translated/zh_cn/players/index.md @@ -0,0 +1,12 @@ +--- +title: 玩家指南 +description: 为玩家和服务器管理员制作的安装和使用 Fabic 的指南合集。 +--- + +# 玩家指南{#player-guides} + +这部分的 Fabric 文档是专门为玩家和服务器管理员准备的,旨在帮助他们学习如何安装、使用 Fabric 以及排除故障。 + +所有可用的指南列表请参见侧边栏。 + +如果遇到任何问题,请在 [GitHub 上](https://github.com/FabricMC/fabric-docs) 报告问题,或者在 [Fabric Discord](https://discord.gg/v6v4pMv) 的 `#player-support` 或 `#server-admin-support` 频道寻求帮助。 diff --git a/versions/1.20.4/translated/zh_cn/players/installing-fabric.md b/versions/1.20.4/translated/zh_cn/players/installing-fabric.md new file mode 100644 index 000000000..5a916a80f --- /dev/null +++ b/versions/1.20.4/translated/zh_cn/players/installing-fabric.md @@ -0,0 +1,53 @@ +--- +title: 安装 Fabric +description: 如何安装 Fabric 的手把手指南。 +authors: + - IMB11 +--- + +# 安装 Fabric{#installing-fabric} + +本指南将引导你在官方 Minecraft 启动器上安装 Fabric。 + +对于第三方启动器,你应该查阅它们的文档。 + +## 1. 下载 Fabric 安装程序{#1-download-the-fabric-installer} + +可以从 [Fabric 网站](https://fabricmc.net/use/) 下载 Fabric 的安装程序。 + +如果使用 Windows,下载 `.exe` 版本 (`Download For Windows`),因为不需要你的系统已安装 Java, 而是使用官方启动器附带的 Java。 + +对于 macOS 和 Linux,您应该下载 `.jar` 版本。 有时,此步骤之前需要安装 Java。 + +## 2. 运行 Fabric 安装程序{#2-run-the-fabric-installer} + +:::warning +在安装之前,请先关闭 Minecraft 和 Minecraft Launcher。 +::: + +:::details macOS 用户须知 + +在 macOS 上,可能需要右键点击下载目录中的 `.jar`,然后点击 `Open` 来运行。 + +![Fabric 安装程序中的 MacOS 上下文菜单](/assets/players/installing-fabric/macos-downloads.png) + +问到“Are you sure you want to open it?”时,再次点击 `Open`。 +::: + +打开安装器后,应该会看到这样的屏幕: + +![高亮 "Install" 的 Fabric 安装程序](/assets/players/installing-fabric/installer-screen.png) + +要安装 Fabric,只需从下拉列表中选择您的游戏版本,然后单击 `Install`。 + +**确保选中'Create Profile'。** + +## 3. 搞定! {#3-you-re-done} + +安装程序完成后,可以打开 Minecraft Launcher,从左下角的下拉列表中选择 Fabric 配置文件,然后按下 `Play`! + +![选中了 Fabric 配置的 Minecraft Launcher](/assets/players/installing-fabric/launcher-screen.png) + +现在安装好了 Fabric,就可以向你的游戏添加模组了! 更多信息请查看[寻找可信赖的模组](./finding-mods)指南。 + +如果在遵循本指南时遇到任何问题,可以在 [Fabric Discord](https://discord.gg/v6v4pMv) 的 `#player-support` 频道中寻求帮助。 diff --git a/versions/1.20.4/translated/zh_cn/players/installing-java/linux.md b/versions/1.20.4/translated/zh_cn/players/installing-java/linux.md new file mode 100644 index 000000000..87ef196d0 --- /dev/null +++ b/versions/1.20.4/translated/zh_cn/players/installing-java/linux.md @@ -0,0 +1,91 @@ +--- +title: 在 Linux 上安装 Java +description: 手把手指导如何在 Linux 上安装 Java。 +authors: + - IMB11 +--- + +# 在 Linux 上安装 Java + +这个指南将会指引您在 Linux 上安装 Java 17。 + +## 1. 验证 Java 是否已经安装 + +打开终端输入 `java -version` 并按下 `回车`。 + +![输入 "java -version" 的终端](/assets/players/installing-java/linux-java-version.png) + +:::warning +要使用大多数现代 Minecraft 版本,您至少需要安装 Java 17。 如果此命令显示版本低于 17,您需要更新您的现有 Java。 +::: + +## 2. 下载并安装 Java 17 + +我们推荐使用 OpenJDK 17,他可以在大多数 Linux 发行版中可用。 + +### Arch Linux + +:::info +更多在 Arch Linux 上安装 Java 的信息可以参考 [Arch Linux 中文维基](https://wiki.archlinuxcn.org/wiki/Java)。 +::: + +您可以从官方仓库安装最新版 JRE: + +```sh +sudo pacman -S jre-openjdk +``` + +如果您正在运行服务器不需要图形化用户接口,您可以安装 headless 版本: + +```sh +sudo pacman -S jre-openjdk-headless +``` + +如果您计划开发模组,您需要安装 JDK: + +```sh +sudo pacman -S jdk-openjdk +``` + +### Debian/Ubuntu + +您可以用以下命令使用 `apt` 安装 Java17: + +```sh +sudo apt update +sudo apt install openjdk-17-jdk +``` + +### Fedora + +您可以用以下命令使用 `dnf` 安装 Java17: + +```sh +sudo dnf install java-17-openjdk +``` + +如果您不需要图形化接口,您可以安装 headless 版本: + +```sh +sudo dnf install java-17-openjdk-headless +``` + +如果您计划开发模组,您需要安装 JDK: + +```sh +sudo dnf install java-17-openjdk-devel +``` + +### 其他 Linux 发行版 + +如果您的发行版未在上文列出,您可以从 [Adoptium](https://adoptium.net/zh-CN/temurin/) 下载最新版 JRE。 + +如果您计划开发模组,您应该参考您的发行版的替代指南。 + +## 3. 验证是否已安装 Java 17 + +安装完成后,您可以打开终端并输入 `java -version` 来验证 Java 17 是否已安装。 + +如果指令成功执行,您可以看到类似前文所示的内容,java 版本被展示出来: + +![输入 "java -version" 的终端](/assets/players/installing-java/linux-java-version.png) diff --git a/versions/1.20.4/translated/zh_cn/players/installing-java/windows.md b/versions/1.20.4/translated/zh_cn/players/installing-java/windows.md new file mode 100644 index 000000000..09a74d9d8 --- /dev/null +++ b/versions/1.20.4/translated/zh_cn/players/installing-java/windows.md @@ -0,0 +1,65 @@ +--- +title: 在 Windows 上安装 Java +description: 在 Windows 上安装 Java 的逐步指南。 +authors: + - IMB11 +--- + +# 在 Windows 上安装 Java + +这个指南将会指引您在 Windows 上安装 Java 17。 + +Minecraft 启动器附带了自己的 Java 安装,因此这部分只在你想使用 Fabric 的 `.jar` 安装程序,或者你想使用 Minecraft 服务器的 `.jar` 时有关。 + +## 1. 检查 Java 是否已被安装 + +要检查 Java 是否已安装,你首先必须打开命令提示符。 + +你可以通过按下 Win + R 并在出现的对话框中输入 `cmd.exe` 来实现它。 + +![Windows运行对话框中的「cmd.exe」](/assets/players/installing-java/windows-run-dialog.png) + +打开命令提示符后,输入 `java -version` 并按下 Enter 键。 + +如果命令成功运行,你会看到类似这样的内容。 如果命令运行失败,请继续进行下一步。 + +![命令提示符中输入了「java -version」](/assets/players/installing-java/windows-java-version.png) + +:::warning +要使用较新的 Minecraft (1.19.x 及以上) 版本,你至少需要安装版本 ≥ 17 的 Java。 如果运行该命令后显示 Java 版本低于 17,你需要更新设备上现有 Java。 +::: + +## 2. 下载 Java 17 安装程序 + +要安装 Java 17,你需要从 [Adoptium](https://adoptium.net/en-GB/temurin/releases/?os=windows&package=jdk&version=17) 下载安装程序。 + +你需要下载 `Windows Installer (.msi)` 版本: + +![Adoptium 下载页面,使用了 Windows 安装程序 (.msi)](/assets/players/installing-java/windows-download-java.png) + +如果你有 32 位操作系统,应该选择 `x86`;如果你有 64 位操作系统,则应该选择 `x64`。 + +现代大多数电脑都运行 64 位操作系统。 如果你不确定,请尝试使用 64 位的下载。 + +## 3. 运行安装程序! + +按照安装程序的步骤安装 Java 17。 当你到达这个页面时,你应该将以下功能设置为「整个功能将安装在本机硬盘上」: + +- `Set JAVA_HOME environment variable` - 这将加入到你的PATH中。 +- `JavaSoft (Oracle) registry keys` + +![Java 17 安装程序,具有「Set JAVA_HOME variable」和「JavaSoft (Oracle) registry keys」](/assets/players/installing-java/windows-wizard-screenshot.png) + +完成后,你可以按 `下一步` 继续安装。 + +## 4. 检查 Java 17 是否已被正确安装 + +安装完成后,您可以打开终端并输入 `java -version` 来验证 Java 17 是否已安装。 + +如果命令成功执行,你可以看到类似前文所示的内容,Java 版本被显示出来: + +![命令提示符中输入了「java -version」](/assets/players/installing-java/windows-java-version.png) + +--- + +如果遇到任何问题,你可以在 [Fabric Discord](https://discord.gg/v6v4pMv) 的 `#player-support` 频道中寻求帮助。 diff --git a/versions/1.20.4/translated/zh_cn/players/installing-mods.md b/versions/1.20.4/translated/zh_cn/players/installing-mods.md new file mode 100644 index 000000000..6a9776704 --- /dev/null +++ b/versions/1.20.4/translated/zh_cn/players/installing-mods.md @@ -0,0 +1,67 @@ +--- +title: 安装模组 +description: Fabric 模组安装的逐步指南 +authors: + - IMB11 +--- + +# 安装模组{#installing-mods} + +这个指南将引导你使用 Minecraft 启动器安装 Fabric 模组。 + +对于第三方启动器,应该参见这些第三方启动器的文档。 + +## 1. 下载模组{#1-download-the-mod} + +:::warning +你应该只从你信任的来源下载模组。 关于寻找模组的更多信息,请看[寻找可信任的模组](./finding-mods)指南。 +::: + +大多数模组都需要 Fabric API,可从 [Modrinth](https://modrinth.com/mod/fabric-api) 或 [CurseForge](https://curseforge.com/minecraft/mc-mods/fabric-api) 下载。 + +下载模组时,请确保: + +- 能在你想玩的 Minecraft 版本上运行。 例如,在 1.20 运行的模组在 1.20.2 可能无法运行。 +- 模组是用于 Fabric 的,而不是其他模组加载器。 +- 此外,适用于正确的 Minecraft(Java 版)的版本。 + +## 2. 将模组移到 `mods` 文件夹{#2-move-the-mod-to-the-mods-folder} + +各个操作系统中,模组文件夹的位置如下所示: + +你通常可以将这些路径粘贴到文件资源管理器的地址栏中,以快速导航到文件夹。 + +::: code-group + +```:no-line-numbers [Windows] +%appdata%\.minecraft\mods +``` + +```:no-line-numbers [macOS] +~/Library/Application Support/minecraft/mods +``` + +```:no-line-numbers [Linux] +~/.minecraft/mods +``` + +::: + +找到 `mods` 文件夹后,就可以将模组 `.jar` 文件移入其中。 + +![已在模组文件夹中安装模组](/assets/players/installing-mods.png) + +## 3. 搞定! {#3-you-re-done} + +将模组移入 `mods` 文件夹后,你可以打开 Minecraft 启动器,从左下角的下拉菜单中选择 Fabric 配置文件,然后按下 `Play`! + +![选择了 Fabric 配置的官方启动器](/assets/players/installing-fabric/launcher-screen.png) + +## 疑难解答{#troubleshooting} + +如果在遵循本指南时遇到任何问题,可以在 [Fabric Discord](https://discord.gg/v6v4pMv) 的 `#player-support` 频道中寻求帮助。 + +也可以尝试阅读疑难解答页面,尝试自己解决问题: + +- [崩溃报告](./troubleshooting/crash-reports) +- [上传日志](./troubleshooting/uploading-logs) diff --git a/versions/1.20.4/translated/zh_cn/players/troubleshooting/crash-reports.md b/versions/1.20.4/translated/zh_cn/players/troubleshooting/crash-reports.md new file mode 100644 index 000000000..cf100898c --- /dev/null +++ b/versions/1.20.4/translated/zh_cn/players/troubleshooting/crash-reports.md @@ -0,0 +1,104 @@ +--- +title: 崩溃报告 +description: 学习如何处理崩溃报告以及如何阅读它们。 +authors: + - IMB11 +--- + +# 崩溃报告 + +:::tip +如果你在查找崩溃原因时遇到困难,可以在 [Fabric Discord](https://discord.gg/v6v4pMv) 的 `#player-support` 或 `#server-admin-support` 频道中寻求帮助。 +::: + +崩溃报告是解决游戏或服务器问题的重要部分。 它包含大量关于崩溃的信息,可以帮助你找到崩溃的原因。 它包含大量关于崩溃的信息,可以帮助你找到崩溃的原因。 + +## 寻找崩溃报告 + +它们位于游戏根目录中的 `crash-reports` 文件夹中。 如果是服务器,它们会存储在服务器实例根目录下的 `crash-reports` 文件夹中。 如果是服务器,它们会存储在服务器实例根目录下的 `crash-reports` 文件夹中。 + +对于第三方启动器,你应该参考其文档,了解在哪里可以找到崩溃报告。 + +崩溃报告可能在以下位置被找到: + +::: code-group + +```:no-line-numbers [Windows] +%appdata%\.minecraft\crash-reports +``` + +```:no-line-numbers [macOS] +~/Library/Application Support/minecraft/crash-reports +``` + +```:no-line-numbers [Linux] +~/.minecraft/crash-reports +``` + +::: + +## 阅读崩溃报告 + +崩溃报告的篇幅很长,读起来十分费解。 但无论怎样,它包含着大量关于崩溃的信息,可以帮助你找到崩溃的原因,因此你不得不阅读它。 但无论怎样,它包含着大量关于崩溃的信息,可以帮助你找到崩溃的原因,因此你不得不阅读它。 + +在本指南中,我们将以 [该崩溃报告](https://github.com/FabricMC/fabric-docs/blob/main/public/assets/players/crash-report-example.txt) 为例。 + +### 崩溃报告的各部分 + +崩溃报告由几个部分组成,每个部分都用标题来分隔: + +- `---- Minecraft Crash Report ----`,报告摘要部分。 该部分包含导致崩溃的主要错误原因、发生时间和相关堆栈跟踪。 这是崩溃报告中最重要的部分,因为堆栈跟踪通常会提及到导致崩溃的模组。 该部分包含导致崩溃的主要错误原因、发生时间和相关堆栈跟踪。 这是崩溃报告中最重要的部分,因为堆栈跟踪通常会提及到导致崩溃的模组。 +- `-- Last Reload --`,除非崩溃发生在资源重载过程中 (F3+T) ,否则这部分并没有什么用处。 该部分将包含上次重载的发生时间,以及重载过程中出现的任何错误的相关堆栈跟踪。 这些错误通常是由资源包引起的,可以忽略不计,除非它们导致游戏出现问题。 +- `-- System Details --`,本部分包含有关设备的信息,如操作系统、Java 版本和分配给游戏的内存量。 该部分有助于确定你使用的 Java 版本是否正确,以及是否为游戏分配了足够的内存。 该部分有助于确定你使用的 Java 版本是否正确,以及是否为游戏分配了足够的内存。 + - 在此部分中,Fabric 将插入一些自定义内容,其标题为 `Fabric Mods:`,后面是所有已安装模组的列表。 该部分有助于判断模组之间是否有可能发生冲突。 该部分有助于判断模组之间是否有可能发生冲突。 + +### 分解崩溃报告 + +既然我们已经知道崩溃报告的每个部分代表着什么,我们就可以开始分解崩溃报告并找出崩溃原因。 + +利用上面链接的崩溃示例,我们可以分析崩溃报告并找到崩溃原因,包括导致崩溃的模组。 + +`-- Last Reload --`,除非崩溃发生在资源重载过程中 (F3+T) ,否则这部分并没有什么用处。 该部分将包含上次重载的发生时间,以及重载过程中出现的任何错误的相关堆栈跟踪。 这些错误通常是由资源包引起的,可以忽略不计,除非它们导致游戏出现问题。 在这种情况下,`---- Minecraft Crash Report ----` 部分中的堆栈跟踪最为重要,因为它包含导致崩溃的主要错误。 在这里,错误为`java.lang.NullPointerException: Cannot invoke "net.minecraft.class_2248.method_9539()" because "net.minecraft.class_2248.field_10540" is null`. + +由于堆栈跟踪中提到了大量的模组,因此很难指认崩溃"凶手",不过,首先要做的是查找导致崩溃的部分。 + +```:no-line-numbers +at snownee.snow.block.ShapeCaches.get(ShapeCaches.java:51) +at snownee.snow.block.SnowWallBlock.method_9549(SnowWallBlock.java:26) // [!code focus] +... +at me.jellysquid.mods.sodium.client.render.chunk.compile.pipeline.BlockOcclusionCache.shouldDrawSide(BlockOcclusionCache.java:52) +at link.infra.indium.renderer.render.TerrainBlockRenderInfo.shouldDrawFaceInner(TerrainBlockRenderInfo.java:31) +... +``` + +在这里,导致崩溃的模组是 `snownee`,因为它是堆栈跟踪中提到的第一个模组。 + +不过,从堆栈追踪中提到的模组数量来看,这可能意味着模组之间存在一些兼容性问题,导致崩溃的模组可能并不是出错的模组。 在这种情况下,最好向模组作者报告崩溃情况,让他们调查崩溃原因。 在这种情况下,最好向模组作者报告崩溃情况,让他们调查崩溃原因。 + +## Mixin崩溃 + +:::info +Mixin 是一种修改游戏的方式,使模组无需破坏性的直接修改游戏的源代码。 它被许多模组使用,对于开发者来说是一款非常强大的工具。 它被许多模组使用,对于开发者来说是一款非常强大的工具。 +::: + +当有 Mixin 引起的崩溃时,通常会在堆栈跟踪中提到该 Mixin 类以及该 Mixin 类修改的类。 + +方法 Mixin 的标识 `modid$handlerName` 将被包含在堆栈跟踪中,其中 `modid` 是模组的 ID,而 `handlerName` 是 Mixin 处理部分的名称。 + +```:no-line-numbers +... net.minecraft.class_2248.method_3821$$$modid$handlerName() ... // [!code focus] +``` + +你可以使用此信息找到导致崩溃的模组,并向模组作者报告崩溃情况。 + +## 如何处理崩溃报告 + +处理崩溃报告的最佳方法是将其上传到在线粘贴板网站,然后在问题追踪处或通过某种联系方式 (Discord 等) 向修改器作者提供崩溃报告网站链接。 + +这可以让模组作者调查崩溃原因、重现崩溃状况并解决导致崩溃的问题。 + +常用的崩溃报告粘贴网站有: + +- [GitHub Gist](https://gist.github.com/) +- [Pastebin](https://pastebin.com/) +- [mclo.gs](https://mclo.gs/) diff --git a/versions/1.20.4/translated/zh_cn/players/troubleshooting/uploading-logs.md b/versions/1.20.4/translated/zh_cn/players/troubleshooting/uploading-logs.md new file mode 100644 index 000000000..19a4db55c --- /dev/null +++ b/versions/1.20.4/translated/zh_cn/players/troubleshooting/uploading-logs.md @@ -0,0 +1,54 @@ +--- +title: 上传日志 +description: 如何上传日志以进行疑难解答。 +authors: + - IMB11 +--- + +# 上传日志 + +在进行疑难解答时,通常需要提供日志以帮助寻找问题的原因。 + +## 为什么我应该上传日志? + +上传日志可以让其他人更快地帮助您疑难解答,而不是简单地将日志粘贴到聊天或论坛帖子中。 它还允许你与其他人分享你的日志,而无需拷贝和粘贴它们。 它还允许你与其他人分享你的日志,而无需拷贝和粘贴它们。 + +有些文本分享网站还为日志提供语法高亮显示,使日志更容易阅读,但可能会审查敏感信息,如用户名或系统信息。 + +## 崩溃报告 + +当游戏崩溃时,会自动生成崩溃报告。 它们只包含崩溃信息,而不包含游戏的实际日志。 它们位于游戏目录中的 `crash-reports` 文件夹中。 它们只包含崩溃信息,而不包含游戏的实际日志。 它们位于游戏目录中的 `crash-reports` 文件夹中。 + +有关崩溃报告的更多信息,请参阅[崩溃报告](./crash-reports)。 + +## 寻找日志 + +本指南涵盖了官方 Minecraft 启动器(通常称为“原版启动器”),对于第三方启动器,你应该参阅其文档。 + +日志位于游戏目录下的 logs 文件夹中,游戏目录可以在以下位置找到,具体取决于你的操作系统: + +::: code-group + +```:no-line-numbers [Windows] +%appdata%\.minecraft +``` + +```:no-line-numbers [macOS] +~/Library/Application Support/minecraft +``` + +```:no-line-numbers [Linux] +~/.minecraft +``` + +::: + +最新的日志文件名为 `latest.log`,先前的日志使用命名格式 `yyyy-mm-dd_number.log.gz`。 + +## 上传日志 + +日志可以上传到各种服务,例如: + +- [Pastebin](https://pastebin.com/) +- [GitHub Gist](https://gist.github.com/) +- [mclo.gs](https://mclo.gs/) diff --git a/versions/1.20.4/translated/zh_cn/players/updating-fabric.md b/versions/1.20.4/translated/zh_cn/players/updating-fabric.md new file mode 100644 index 000000000..1b120ef62 --- /dev/null +++ b/versions/1.20.4/translated/zh_cn/players/updating-fabric.md @@ -0,0 +1,43 @@ +--- +title: 更新 Fabric +description: 更新 Fabric 的手把手的指南 +authors: + - IMB11 + - modmuss50 +--- + +# 更新 Fabric{#updating-fabric} + +这篇指南将引导您在 Minecraft 启动器中更新 Fabric。 + +对于第三方启动器,应该参见这些第三方启动器的文档。 + +更新 Fabric 和安装 Fabric 的过程非常相似,所以该指南的一部分与 [安装 Fabric](./installing-fabric) 指南完全一致。 + +## 为什么应该更新 Fabric Loader? {#why-should-i-update-fabric-loader} + +新的模组可能需要新版本的 Fabric Loader 才能运行,所以保持更新很重要,从而确保能够使用最新的模组。 + + + + + +更新 Fabric,简单地确认游戏版本和加载器版本是正确的,然后点击 `安装` 。 + +:::important +**运行安装程序时,请确保没有选中“创建新的启动器配置”,否则将创建新的配置文件,而这种情况下我们不需要。** +::: + +## 3. 在 Minecraft 启动器中打开配置{#3-open-the-profile-in-the-minecraft-launcher} + +安装程度完成后,可以打开 Minecraft 启动器并前往 `Installations(安装)` 选项。 您应当前往您的 Fabric 配置并打开编辑界面。 + +将该版本替换为刚才安装的 Fabric 加载器版本并点击 `保存`。 + +![在 Minecraft 启动器中更新 Fabric](/assets/players/updating-fabric.png) + +## 4. 搞定! {#4-you-re-done} + +完成这些步骤后,就可以回到 `Play` 选项卡,从左下角的下拉菜单中选择 Fabric 配置文件,然后按下启动按钮! + +如果在遵循本指南时遇到任何问题,可以在 [Fabric Discord](https://discord.gg/v6v4pMv) 的 `#player-support` 频道中寻求帮助。 diff --git a/versions/1.20.4/translated/zh_cn/sidebar_translations.json b/versions/1.20.4/translated/zh_cn/sidebar_translations.json new file mode 100644 index 000000000..740e6369f --- /dev/null +++ b/versions/1.20.4/translated/zh_cn/sidebar_translations.json @@ -0,0 +1,53 @@ +{ + "players.title": "玩家指南", + "players.faq": "常见问题", + "players.installingJava": "安装 Java", + "players.installingJava.windows": "Windows", + "players.installingJava.macOS": "macOS", + "players.installingJava.linux": "Linux", + "players.installingFabric": "安装 Fabric", + "players.findingMods": "寻找可信赖的模组", + "players.installingMods": "安装模组", + "players.troubleshooting": "疑难解答", + "players.troubleshooting.uploadingLogs": "上传你的日志", + "players.troubleshooting.crashReports": "崩溃报告", + "players.updatingFabric": "更新 Fabric", + "develop.title": "开发者指南", + "develop.gettingStarted": "入门", + "develop.gettingStarted.introduction": "Fabric 和模组简介", + "develop.gettingStarted.devEnvSetup": "设置开发环境", + "develop.gettingStarted.creatingProject": "创建项目", + "develop.gettingStarted.projectStructure": "项目结构", + "develop.gettingStarted.launchGame": "启动游戏", + "develop.items": "物品", + "develop.items.first-item": "创建你的第一个物品", + "develop.items.food": "食物物品", + "develop.items.custom-armor": "自定义盔甲", + "develop.items.custom-tools": "自定义工具", + "develop.items.custom-item-groups": "自定义物品组", + "develop.items.custom-item-interactions": "自定义物品交互", + "develop.items.potions": "药水", + "develop.entities": "实体", + "develop.entities.effects": "状态效果", + "develop.entities.damage-types": "伤害类型", + "develop.commands": "命令", + "develop.commands.basics": "创建命令", + "develop.commands.arguments": "参数", + "develop.commands.suggestions": "建议", + "develop.rendering": "渲染", + "develop.rendering.basicConcepts": "基本的渲染概念", + "develop.rendering.drawContext": "使用绘图上下文", + "develop.rendering.hud": "在 HUD 中渲染", + "develop.rendering.gui": "GUI 与界面", + "develop.rendering.gui.customScreens": "自定义界面", + "develop.rendering.gui.customWidgets": "自定义控件", + "develop.rendering.particles": "粒子", + "develop.rendering.particles.creatingParticles": "创建自定义的粒子", + "develop.misc": "杂项", + "develop.misc.codecs": "Codecs", + "develop.misc.events": "事件", + "develop.misc.text-and-translations": "文本和翻译", + "develop.sounds": "声音", + "develop.sounds.using-sounds": "播放声音事件", + "develop.sounds.custom": "创建自定义声音" +} \ No newline at end of file diff --git a/versions/1.20.4/translated/zh_tw/contributing.md b/versions/1.20.4/translated/zh_tw/contributing.md new file mode 100644 index 000000000..9b8625212 --- /dev/null +++ b/versions/1.20.4/translated/zh_tw/contributing.md @@ -0,0 +1,179 @@ +# Fabric 文件貢獻指南 + +這個網站使用 [VitePress](https://vitepress.dev/) 來將各種 Markdown 檔案轉換成靜態 HTML。 這個網站使用 [VitePress](https://vitepress.dev/) 來從各種 Markdown 檔案轉換成靜態 HTML。 這個網站使用 [VitePress](https://vitepress.dev/) 來從各種 Markdown 檔案轉換成靜態 HTML。 這個網站使用 [VitePress](https://vitepress.dev/) 來從各種 Markdown 檔案轉換成靜態 HTML。 這個網站使用 [VitePress](https://vitepress.dev/) 來從各種 Markdown 檔案轉換成靜態 HTML。 你應該熟悉 VitePress 支援的 Markdown 擴充功能,詳細內容請參閱[這裡](https://vitepress.dev/guide/markdown#features)。 + +## 目錄 + +- [Fabric 文件貢獻指南](#fabric-documentation-contribution-guidelines) + - [如何貢獻](#how-to-contribute) + - [貢獻框架](#contributing-framework) + - [貢獻內容](#contributing-content) + - [格式指南](#style-guidelines) + - [擴充指南](#guidance-for-expansion) + - [內容驗證](#guidance-for-expansion) + - [清理](#cleanup) + - [翻譯文件](#translating-documentation) + +## 如何貢獻 + +我們建議每次送出合併請求時,都在你的儲存庫中新增一個分支。 這讓同時管理多個合併請求變得更加容易。 + +如果你想在本機預覽你的變更,你需要安裝 [Node.js 18+](https://nodejs.org/zh-tw/)。 + +在執行以下指令前,請先執行 `npm install` 來安裝所有相依項。 + +**正在執行程式開發伺服器:** + +這將讓你能在本機預覽你的變更,網址是 `localhost:3000`,並且在你進行變更時會自動重新載入頁面。 + +```sh +npm run dev +``` + +**建構網站:** + +這將把所有的 Markdown 檔案編譯成靜態 HTML 檔案,並將它們放置在 `.vitepress/dist` 資料夾中。 + +```sh +npm run build +``` + +**預覽已建置的網站:** + +這將在連接埠 3000 上啟動本機伺服器,提供在 `.vitepress/dist` 中找到的內容。 + +```sh +npm run preview +``` + +## 貢獻框架 + +框架指的是網站的內部結構,任何修改網站框架的合併請求應該標記為 `framework` 標籤。 + +在進行框架合併請求前,你應該先與 [Fabric Discord](https://discord.gg/v6v4pMv) 上的文件團隊諮詢,或者透過提出問題進行討論。 + +**備註:修改側邊欄檔案和導覽列配置不算作框架合併請求。** + +## 貢獻內容 + +貢獻內容是貢獻 Fabric 文件的主要方式。 + +所有內容應遵循我們的風格指南。 + +### 風格指南 + +所有 Fabric 文件網站上的頁面都應遵循風格指南。 所有 Fabric 文件網站上的頁面都應遵循風格指南。 如果你對任何事情感到不確定,可以在 [Fabric Discord](https://discord.gg/v6v4pMv) 或 GitHub 討論中提問。 所有 Fabric 文件網站上的頁面都應遵循風格指南。 所有 Fabric 文件網站上的頁面都應遵循風格指南。 如果你對任何事情感到不確定,可以在 [Fabric Discord](https://discord.gg/v6v4pMv) 或 GitHub 討論中提問。 所有 Fabric 文件網站上的頁面都應遵循風格指南。 所有 Fabric 文件網站上的頁面都應遵循風格指南。 如果你對任何事情感到不確定,可以在 [Fabric Discord](https://discord.gg/v6v4pMv) 或 GitHub 討論中提問。 所有 Fabric 文件網站上的頁面都應遵循風格指南。 如果你對任何事情感到不確定,可以在 [Fabric Discord](https://discord.gg/v6v4pMv) 或 GitHub 討論中提問。 + +風格指南如下: + +1. 所有頁面必須在 frontmatter 中包含標題和描述。 + + ```md + --- + title: 這是頁面的標題 + description: 這是頁面的描述 + authors: + - GitHub 使用者名稱 + --- + ``` + +2. 如果你建立或修改包含程式碼的頁面,請將程式碼放置在參考模組的適當位置(位於儲存庫的 `/reference` 資料夾中)。 如果你建立或修改包含程式碼的頁面,請將程式碼放置在參考模組的適當位置(位於儲存庫的 `/reference` 資料夾中)。 接著,使用 VitePress 提供的 [程式碼片段功能](https://vitepress.dev/guide/markdown#import-code-snippets) 嵌入程式碼,或者如果你需要更大的控制範圍,可以使用 `markdown-it-vuepress-code-snippet-enhanced` 的 [轉入功能](https://github.com/fabioaanthony/markdown-it-vuepress-code-snippet-enhanced)。 + + **範例:** + + ```md + <<< @/reference/latest/src/main/java/com/example/docs/FabricDocsReference.java{15-21 java} + ``` + + 這將在參考模組中嵌入 `FabricDocsReference.java` 檔案的第 15 至 21 行程式碼。 + + 產生的程式碼片段將如下所示: + + ```java + @Override + public void onInitialize() { + // 當 Minecraft 達到模組載入就緒的狀態時,這個程式碼將立即執行。 + // 但是,某些事物(如資源)可能仍未初始化。 + // 請小心謹慎地進行。 + + LOGGER.info("你好,Fabric 世界!"); + } + ``` + + **轉入範例:** + + ```md + @[code transcludeWith=#test_transclude](@/reference/.../blah.java) + ``` + + 這將嵌入標記為 `#test_transclude` 的 `blah.java` 檔案的部分。 + + 例如: + + ```java + public final String test = "再見,世界!"; + + // #test_transclude + public void test() { + System.out.println("你好,世界!"); + } + // #test_transclude + ``` + + 只有位於 `#test_transclude` 標籤之間的程式碼將被嵌入。 + + ```java + public void test() { + System.out.println("你好,世界!"); + } + ``` + +3. 所有的原始文件都會以英語撰寫,並遵循美式英語的文法規則。 你可以使用 [LanguageTool](https://languagetool.org/) 在輸入時檢查你的語法,但不要太擔心。 我們的文件團隊將在清理階段審查並更正文法錯誤。 然而,一開始就努力做到正確可以節省我們的時間。 我們的文件團隊將在清理階段審查並更正文法錯誤。 然而,一開始就努力做到正確可以節省我們的時間。 + +4. 如果你正在建立新章節,你應該在 `.vitepress/sidebars` 資料夾中建立一個新的側邊欄,並將其新增到 `config.mts` 檔案中。 如果你需要幫助,請在 [Fabric Discord](https://discord.gg/v6v4pMv) 的 `#wiki` 頻道中提問。 如果你需要幫助,請在 [Fabric Discord](https://discord.gg/v6v4pMv) 的 `#docs` 頻道中提問。 + +5. 當建立新頁面時,你應將其新增到 `.vitepress/sidebars` 資料夾中相關的側邊欄中。 同上,如果你需要幫助,請在Fabric Discord上的`#docs`頻道中提問。 + +6. 任何影像應該放置在 `/assets` 資料夾中的適當位置。 + +7. ⚠️ **連結其他頁面時,請使用相對連結。** ⚠️ + + 這是因為系統中存在的版本控制系統,該系統將處理連結以在前面新增版本號。 如果你使用絕對連結,則不會將版本號新增到連結中。 如果你使用絕對連結,則不會將版本號新增到連結中。 + + 例如,對於位於 `/players` 資料夾中的頁面,要連結到 `/players/installing-fabric.md` 中的 `installing-fabric` 頁面,你應該執行以下動作: + + ```md + [這是指向另一個頁面的連結](./installing-fabric) + ``` + + 你**不應該**執行以下動作: + + ```md + [這是指向另一個頁面的連結](/players/installing-fabric) + ``` + +所有內容貢獻經歷三個階段: + +1. 擴充指導(如果可能) +2. 內容驗證 +3. 清理(語法等) + +### 擴充指南 + +如果文件團隊認為你可以擴充你的合併請求,團隊成員將在你的合併請求中新增 `expansion` 標籤,並附上一則留言,解釋他們認為你可以擴展的內容。 如果你同意這個建議,你可以擴充你的合併請求。 + +**不要感到被迫擴充你的合併請求。**如果你不想擴充你的合併請求,你可以簡單地要求移除 `expansion` 標籤。 + +如果你不想擴展你的合併請求,但你願意讓其他人在以後擴展它,最好是在[議題頁面](https://github.com/FabricMC/fabric-docs/issues)上建立一個問題,並解釋你認為可以擴展的內容。 + +### 內容驗證 + +所有新增內容的合併請求都經過內容驗證,這是最重要的階段,因為它確保內容準確無誤並符合 Fabric 文件的風格指南。 + +### 清理 + +在這個階段,文件團隊將在合併之前修復任何文法問題並進行他們認為必要的任何其他變更! + +## 翻譯文件 + +如果想將文件翻譯成別的語言,你可以在[Fabric Crowdin](https://crowdin.com/project/fabricmc)頁面上翻譯。 diff --git a/versions/1.20.4/translated/zh_tw/index.md b/versions/1.20.4/translated/zh_tw/index.md new file mode 100644 index 000000000..26baaa307 --- /dev/null +++ b/versions/1.20.4/translated/zh_tw/index.md @@ -0,0 +1,27 @@ +--- +title: Fabric 文件 +description: Fabric 的官方精選文件,這是 Minecraft 的一個模組製作工具鏈。 +layout: home +hero: + name: Fabric 文件 + tagline: Fabric 的官方精選文件,這是 Minecraft 的一個模組製作工具鏈。 +features: + - title: 開發人員指南 + icon: 🛠️ + details: 我們的精選開發人員指南,由社群撰寫,涵蓋了從建立開發環境到更進階的主題,如繪製和網路等廣泛範疇的議題。 + link: ./develop/index + linkText: 開始使用 + - title: 玩家指南 + icon: 📚 + details: 你是一位希望使用由 Fabric 驅動的模組的玩家嗎?我們的玩家指南可以滿足你的需求。這些指南將幫助你下載、安裝和疑難排解 Fabric 模組。 我們的玩家指南可以滿足你的需求。 這些指南將幫助你下載、安裝和疑難排解 Fabric 模組。 + link: ./players/index + linkText: 閱讀更多 +--- + +
+ +## 想要貢獻嗎? + +如果你想為 Fabric 文件做出貢獻,你可以在 [GitHub](https://github.com/FabricMC/fabric-docs) 找到原始碼,以及相關的[貢獻指南](./contributing)。 + +
diff --git a/versions/1.20.4/translated/zh_tw/navbar_translations.json b/versions/1.20.4/translated/zh_tw/navbar_translations.json new file mode 100644 index 000000000..7c6dde312 --- /dev/null +++ b/versions/1.20.4/translated/zh_tw/navbar_translations.json @@ -0,0 +1,8 @@ +{ + "title": "Fabric 文件", + "home": "主頁", + "download": "下載", + "contribute": "貢獻", + "contribute.api": "Fabric API", + "version_switcher": "切換版本" +} \ No newline at end of file diff --git a/versions/1.20.4/translated/zh_tw/players/faq.md b/versions/1.20.4/translated/zh_tw/players/faq.md new file mode 100644 index 000000000..f901138bb --- /dev/null +++ b/versions/1.20.4/translated/zh_tw/players/faq.md @@ -0,0 +1,31 @@ +--- +title: 玩家常見問題 +description: 關於 Fabric 的玩家和伺服器管理員常見問題解答手冊。 +--- + +# 常見問題 + +有許多常見問題被頻繁地提出,所以我們在這裡整理了一份清單。 + +## 一般問題 + +### Fabric 支援哪些 Minecraft 版本? + +官方支援的 Fabric 版本包括從 `18w43b` 開始的所有快照版本,以及 `1.14` 及以上的正式版本。 + +### 我在哪裡可以下載已發佈的 Fabric 模組? + +:::info +你都應該檢查模組是否來自可信賴的來源。 請參閱[尋找可信賴的模組](./finding-mods)指南以獲得更多資訊。 +::: + +大多數作者會將他們的模組發布到 [Modrinth](https://modrinth.com/mods?g=categories:%27fabric%27) 和 [CurseForge](https://www.curseforge.com/minecraft/search?class=mc-mods&gameVersionTypeId=4),但有些可能選擇將它們上傳到他們的個人網站,或者其他平台,如 GitHub 存儲庫。 + +### 我在哪裡可以找到預製的 Fabric 模組包? + +你可以在各種平台上找到預製的 Fabric 模組包,例如: + +- [Modrinth](https://modrinth.com/modpacks?g=categories:%27fabric%27) +- [CurseForge](https://www.curseforge.com/minecraft/search?class=modpacks&gameVersionTypeId=4) +- [Feed The Beast](https://www.feed-the-beast.com/ftb-app) +- [Technic](https://www.technicpack.net/modpacks) diff --git a/versions/1.20.4/translated/zh_tw/players/finding-mods.md b/versions/1.20.4/translated/zh_tw/players/finding-mods.md new file mode 100644 index 000000000..b39903453 --- /dev/null +++ b/versions/1.20.4/translated/zh_tw/players/finding-mods.md @@ -0,0 +1,34 @@ +--- +title: 尋找可信賴的模組 +description: 本指南教你如何使用可信賴的來源找到 Fabric 模組。 +authors: + - IMB11 +--- + +# 尋找可信賴的模組 + +首先,信任是主觀的,當下載模組時你應該始終根據自己的判斷。 但是,有一些方法可以幫助您找到可信任的模組。 但是,有一些方法可以幫助您找到可信任的模組。 + +## 1. 使用眾所周知的可信任來源 + +大多數作者會將他們的模組發布到 [Modrinth](https://modrinth.com/mods?g=categories:%27fabric%27) 和 [CurseForge](https://www.curseforge.com/minecraft/search?class=mc-mods&gameVersionTypeId=4) + +這些網站會檢查模組是否符合其宣稱,並且不含有惡意程式碼。 你也可以在這些網站上回報惡意模組,他們會相對迅速地採取行動。 你也可以在這些網站上回報惡意模組,他們會相對迅速地採取行動。 + +## 2. 與他人討論! + +如果你從不被認為是可信任的來源下載模組,你應該與他人討論,看看他們是否曾經從你下載的位置下載過模組,以及他們是否遇到過任何問題。 + +如果你有疑問,歡迎在 [Fabric Discord](https://discord.gg/v6v4pMv) 的 `#player-support` 頻道中詢問。 + +## 3. 避免常見的惡意軟體網站! + +:::info +惡意軟體網站對於每個人來說可能不是很明顯。 如果您不確定,你應該向他人尋求意見,或者完全避免該網站,僅依賴於可信任的來源,例如 Modrinth 和 CurseForge。 +::: + +有許多聲稱提供 Minecraft 模組的網站,實際上只是惡意軟體網站。 你應該盡量避免這些網站。 你應該盡量避免這些網站。 你應該盡量避免這些網站。 + +你可以使用防病毒軟體和像 [Windows Defender](https://www.microsoft.com/zh-tw/windows/comprehensive-security) 或 [VirusTotal](https://www.virustotal.com/) 這樣的網站來檢查下載的模組。 但是,不要完全依賴這些方法,因為有時候它們可能不準確。 但是,不要完全依賴這些方法,因為有時候它們可能不準確。 但是,不要完全依賴這些方法,因為有時候它們可能不準確。 + +同樣地,如果你有疑問,歡迎在 [Fabric Discord](https://discord.gg/v6v4pMv) 的 `#player-support` 頻道中尋求意見。 diff --git a/versions/1.20.4/translated/zh_tw/players/index.md b/versions/1.20.4/translated/zh_tw/players/index.md new file mode 100644 index 000000000..47819dbf5 --- /dev/null +++ b/versions/1.20.4/translated/zh_tw/players/index.md @@ -0,0 +1,12 @@ +--- +title: 玩家指南 +description: 一系列的指南,供玩家和伺服器管理員安裝和使用Fabric。 +--- + +# 玩家指南 + +這部分 Fabric 文件專門為想要學習如何安裝、使用和疑難排解 Fabric 的玩家和伺服器管理員而設。 + +你可以參考側邊欄中提供的所有指南清單。 + +如果你遇到任何問題,請在 [GitHub](https://github.com/FabricMC/fabric-docs) 上回報問題,或在 [Fabric Discord](https://discord.gg/v6v4pMv) 的 `#player-support` 或 `#server-admin-support` 頻道中尋求幫助。 diff --git a/versions/1.20.4/translated/zh_tw/players/installing-java/linux.md b/versions/1.20.4/translated/zh_tw/players/installing-java/linux.md new file mode 100644 index 000000000..1ae92d28f --- /dev/null +++ b/versions/1.20.4/translated/zh_tw/players/installing-java/linux.md @@ -0,0 +1,91 @@ +--- +title: 在 Linux 上安裝 Java +description: 在 Linux 上安裝 Java 的逐步指南。 +authors: + - IMB11 +--- + +# 在 Linux 上安裝 Java + +這個指南將引導你在 Linux 上安裝 Java 17。 + +## 1. 驗證 Java 是否安裝 + +開啟終端機,輸入 `java -version`,然後按下 Enter 鍵。 + +![終端機中輸入了「java -version」](/assets/players/installing-java/linux-java-version.png) + +:::warning +要使用大多數現代的 Minecraft,你需要至少安裝 Java 17。 如果這個命令顯示低於 17 的任何版本,你需要更新現有的 Java 安裝。 如果你打算開發模組,你應參考另一個指南。 如果你打算開發模組,你應參考另一個指南。 如果你打算開發模組,你應參考另一個指南。 +::: + +## 2. 下載並安裝 Java 17 + +我們建議使用 OpenJDK 17,在大多數 Linux 發行版中都可用。 + +### Arch Linux + +:::info +有關在 Arch Linux 上安裝 Java 的更多資訊,請參閱 [Arch Linux Wiki](https://wiki.archlinuxcn.org/wiki/Java)。 +::: + +你可以從官方儲存庫安裝最新的 JRE: + +```sh +sudo pacman -S jre-openjdk +``` + +如果你在沒有圖形化介面的伺服器上執行,則可以安裝無頭版本: + +```sh +sudo pacman -S jre-openjdk-headless +``` + +如果你打算開發模組,則需要 JDK: + +```sh +sudo pacman -S jdk-openjdk +``` + +### Debian/Ubuntu + +你可以使用 apt 安裝 Java 17,使用以下命令: + +```sh +sudo apt update +sudo apt install openjdk-17-jdk +``` + +### Fedora + +你可以使用 dnf 安裝 Java 17,使用以下命令: + +```sh +sudo dnf install java-17-openjdk +``` + +如果你不需要圖形化介面,則可以安裝無頭版本: + +```sh +sudo dnf install java-17-openjdk-headless +``` + +如果你打算開發模組,則需要 JDK: + +```sh +sudo dnf install java-17-openjdk-devel +``` + +### 其他 Linux 發行版 + +如果你的發行版未在上述清單中,你可以從 [Eclipse Temurin](https://adoptium.net/temurin/) 下載最新的 JRE。 + +如果你打算開發模組,你應參考另一個指南。 + +## 3. 驗證 Java 17 是否安裝 + +安裝完成後,你可以開啟終端機,輸入 `java -version` 來驗證是否安裝了 Java 17。 + +如果這個命令成功執行,你將看到類似於以前顯示的內容,其中顯示了 Java 版本: + +![終端機中輸入了「java -version」](/assets/players/installing-java/linux-java-version.png) diff --git a/versions/1.20.4/translated/zh_tw/players/installing-java/windows.md b/versions/1.20.4/translated/zh_tw/players/installing-java/windows.md new file mode 100644 index 000000000..a5791b445 --- /dev/null +++ b/versions/1.20.4/translated/zh_tw/players/installing-java/windows.md @@ -0,0 +1,65 @@ +--- +title: 在 Windows 上安裝 Java +description: 在 Windows 上安裝 Java 的逐步指南。 +authors: + - IMB11 +--- + +# 在 Windows 上安裝 Java + +這個指南將引導你在 Windows 上安裝 Java 17。 + +Minecraft 啟動器附帶了自己的 Java 安裝,因此這部分只在你想使用 Fabric 的 `.jar` 安裝程式,或者你想使用 Minecraft 伺服器的 `.jar` 時相關。 + +## 1. 驗證 Java 是否安裝 + +要檢查 Java 是否已安裝,你首先必須開啟命令提示字元。 + +你可以透過按下 Win + R 並在出現的對話方塊中輸入 `cmd.exe` 來執行此動作。 + +![Windows執行對話方塊中的「cmd.exe」](/assets/players/installing-java/windows-run-dialog.png) + +開啟命令提示字元後,輸入 `java -version` 並按下 Enter 鍵。 + +如果命令成功執行,你會看到類似這樣的內容。如果命令失敗,請繼續進行下一步。 如果命令失敗,請繼續進行下一步。 如果命令失敗,請繼續進行下一步。 + +![命令提示字元中輸入了「java -version」](/assets/players/installing-java/windows-java-version.png) + +:::warning +要使用大多數現代的 Minecraft,你需要至少安裝 Java 17。 如果這個命令顯示低於 17 的任何版本,你需要更新現有的 Java 安裝。 要檢查 Java 是否已安裝,你首先必須開啟命令提示字元。 +::: + +## 2. 下載 Java 17 安裝程式 + +要安裝 Java 17,你需要從 [Adoptium](https://adoptium.net/en-GB/temurin/releases/?os=windows&package=jdk&version=17) 下載安裝程式。 + +你需要下載 `Windows Installer (.msi)` 版本: + +![Adoptium 下載頁面,突顯了 Windows 安裝程式 (.msi)](/assets/players/installing-java/windows-download-java.png) + +如果你有 32 位元作業系統,應該選擇 `x86`;如果你有 64 位元作業系統,則應該選擇 `x64`。 + +現代大多數電腦都執行 64 位元作業系統。 如果你不確定,請嘗試使用 64 位元的下載。 如果你不確定,請嘗試使用 64 位元的下載。 + +## 3. 執行安裝程式! + +依照安裝程式中的步驟安裝 Java 17。 當你到達這個頁面時,你應該將以下功能設定為「整個功能將安裝在本機硬碟上」: 當你到達這個頁面時,你應該將以下功能設定為「整個功能將安裝在本機硬碟上」: + +- `Set JAVA_HOME environment variable` - 這將加入到你的 PATH 中。 +- `JavaSoft (Oracle) registry keys` + +![Java 17 安裝程式,凸顯了「Set JAVA_HOME variable」和「JavaSoft (Oracle) registry keys」](/assets/players/installing-java/windows-wizard-screenshot.png) + +完成後,你可以按 `下一步` 繼續安裝。 + +## 4. 驗證 Java 17 是否安裝 + +安裝完成後,你可以再次開啟命令提示字元,並輸入 `java -version` 來驗證 Java 17 是否已安裝。 + +如果這個命令成功執行,你將看到類似於以前顯示的內容,其中顯示了 Java 版本: + +![命令提示字元中輸入了「java -version」](/assets/players/installing-java/windows-java-version.png) + +--- + +如果遇到任何問題,你可以在 [Fabric Discord](https://discord.gg/v6v4pMv) 的 `#player-support` 頻道中尋求幫助。 diff --git a/versions/1.20.4/translated/zh_tw/players/troubleshooting/crash-reports.md b/versions/1.20.4/translated/zh_tw/players/troubleshooting/crash-reports.md new file mode 100644 index 000000000..1c328b34a --- /dev/null +++ b/versions/1.20.4/translated/zh_tw/players/troubleshooting/crash-reports.md @@ -0,0 +1,103 @@ +--- +title: 崩潰報告 +description: 了解如何處理崩潰報告,以及如何閱讀它們。 +authors: + - IMB11 +--- + +# 崩潰報告 + +:::tip +如果你在尋找崩潰原因時遇到任何困難,你可以在 [Fabric Discord](https://discord.gg/v6v4pMv) 的 `#player-support` 或 `#server-admin-support` 頻道中尋求幫助。 +::: + +崩潰報告是排解遊戲或伺服器問題的非常重要的一部分。 它們包含了關於崩潰的大量資訊,可以幫助你找到崩潰的原因。 + +## 尋找崩潰報告 + +崩潰報告儲存在遊戲目錄中的 crash-reports 資料夾中。 如果您正在使用伺服器,則它們儲存在伺服器目錄中的 `crash-reports` 資料夾中。 如果您正在使用伺服器,則它們儲存在伺服器目錄中的 `crash-reports` 資料夾中。 如果您正在使用伺服器,則它們儲存在伺服器目錄中的 `crash-reports` 資料夾中。 + +對於第三方啟動器,你應參考它們的文件以找到崩潰報告的位置。 + +崩潰報告可以在以下位置找到: + +::: code-group + +```:no-line-numbers [Windows] +%appdata%\.minecraft\crash-reports +``` + +```:no-line-numbers [macOS] +~/Library/Application Support/minecraft/crash-reports +``` + +```:no-line-numbers [Linux] +~/.minecraft/crash-reports +``` + +::: + +## 閱讀崩潰報告 + +崩潰報告非常長,且讀起來可能會很困難。 然而,它們包含了許多關於崩潰的資訊,可以幫助你找出崩潰的原因。 + +在本指南中,我們將使用[這個崩潰報告作為範例](https://github.com/FabricMC/fabric-docs/blob/main/public/assets/players/crash-report-example.txt)。 + +### 崩潰報告部分 + +崩潰報告由幾個部分組成,每個部分都使用標題分隔: + +- `---- Minecraft Crash Report ----`,報告的摘要。 這個部分包含導致崩潰的主要錯誤、發生時間以及相關的堆疊追蹤。 這是崩潰報告中最重要的部分,因為堆疊追蹤通常包含導致崩潰的模組的參考。 這個部分包含導致崩潰的主要錯誤、發生時間以及相關的堆疊追蹤。 這是崩潰報告中最重要的部分,因為堆疊追蹤通常包含導致崩潰的模組的參考。 這個部分包含導致崩潰的主要錯誤、發生時間以及相關的堆疊追蹤。 這是崩潰報告中最重要的部分,因為堆疊追蹤通常包含導致崩潰的模組的參考。 +- `-- Last Reload --`,這個部分除非崩潰發生在資源重新載入期間(F3+T),否則沒有什麼用。 這個部分將包含上次重新載入的時間以及重新載入過程中發生的任何錯誤的相關堆疊追踪。 這些錯誤通常是由資源包引起的,除非它們對遊戲造成問題,否則可以忽略。 +- `-- System Details --`,這個部分包含有關你系統的資訊,例如作業系統、Java 版本和配置給遊戲的記憶體。 這個部分對於確定你是否使用正確的 Java 版本以及是否為遊戲配置足夠的記憶體很有用。 這個部分對於確定你是否使用正確的 Java 版本以及是否為遊戲配置足夠的記憶體很有用。 這個部分對於確定你是否使用正確的 Java 版本以及是否為遊戲配置足夠的記憶體很有用。 + - 在這一部分,Fabric 將包括一個自訂行,其中說明了 `Fabric Mods:`,後面跟著您安裝的所有模組的清單。 這個部分對於確定模組之間是否可能發生衝突很有用。 + +### 分解崩潰報告 + +現在我們知道崩潰報告的每個部分是什麼,我們可以開始分解崩潰報告,找出崩潰的原因。 + +使用上面連結的範例,我們可以分析崩潰報告,找出崩潰的原因,包括導致崩潰的模組。 + +崩潰報告是排解遊戲或伺服器問題的非常重要的一部分。 它們包含了關於崩潰的大量資訊,可以幫助你找到崩潰的原因。 `---- Minecraft Crash Report ----` 部分中的堆棧跟踪在這種情況下最重要,因為它包含導致崩潰的主要錯誤。 在這個案例中,錯誤是 `java.lang.NullPointerException: Cannot invoke "net.minecraft.class_2248.method_9539()" because "net.minecraft.class_2248.field_10540" is null`。 在這個案例中,錯誤是 `java.lang.NullPointerException: Cannot invoke "net.minecraft.class_2248.method_9539()" because "net.minecraft.class_2248.field_10540" is null`。 + +由於堆疊追蹤中提到了大量的模組,要指出責任者可能有些困難,但首先要做的是尋找導致崩潰的模組。 + +```:no-line-numbers +at snownee.snow.block.ShapeCaches.get(ShapeCaches.java:51) +at snownee.snow.block.SnowWallBlock.method_9549(SnowWallBlock.java:26) // [!code focus] +... +at me.jellysquid.mods.sodium.client.render.chunk.compile.pipeline.BlockOcclusionCache.shouldDrawSide(BlockOcclusionCache.java:52) +at link.infra.indium.renderer.render.TerrainBlockRenderInfo.shouldDrawFaceInner(TerrainBlockRenderInfo.java:31) +``` + +在這種情況下,導致崩潰的模組是 `snownee`,因為它是堆疊追蹤中首先提到的模組。 + +然而,由於堆疊追蹤中提到了大量的模組,這可能表示模組之間存在一些相容性問題,並且導致崩潰的模組可能不是真正的問題所在。 在這種情況下,最好將崩潰報告提交給模組作者,並讓他們調查崩潰。 + +## Mixin 崩潰 + +:::info +Mixin 是一種讓模組無需修改遊戲原始碼即可修改遊戲的方法。 它們被許多模組使用,是模組開發人員非常強大的工具。 它們被許多模組使用,是模組開發人員非常強大的工具。 它們被許多模組使用,是模組開發人員非常強大的工具。 +::: + +當 mixin 崩潰時,堆疊追蹤通常會提到 mixin 和被修改的類。 + +方法 mixin 將在堆疊追蹤中包含 `modid$handlerName`,其中 `modid` 是模組的 ID,`handlerName` 是 mixin 處理程序的名稱。 + +```:no-line-numbers +... net.minecraft.class_2248.method_3821$$$modid$handlerName() ... // [!code focus] +``` + +你可以使用這個資訊找到導致崩潰的模組,並將崩潰報告提交給模組作者。 + +## 處理崩潰報告 + +處理崩潰報告的最佳方法是將它上傳至文字分享網站,並將連結分享給模組作者、錯誤追蹤器或透過某種形式的交流(Discord 等)。 + +這將使模組作者能夠調查崩潰,可能重現它並解決導致崩潰的問題。 + +常見的文字分享網站為: + +- [GitHub Gist](https://gist.github.com/) +- [Pastebin](https://pastebin.com/) +- [mclo.gs](https://mclo.gs/) diff --git a/versions/1.20.4/translated/zh_tw/players/troubleshooting/uploading-logs.md b/versions/1.20.4/translated/zh_tw/players/troubleshooting/uploading-logs.md new file mode 100644 index 000000000..44fc9a124 --- /dev/null +++ b/versions/1.20.4/translated/zh_tw/players/troubleshooting/uploading-logs.md @@ -0,0 +1,54 @@ +--- +title: 上傳記錄檔 +description: 如何上傳記錄檔以進行疑難排解。 +authors: + - IMB11 +--- + +# 上傳記錄檔 + +在進行疑難排解時,通常需要提供記錄檔以幫助尋找問題的原因。 + +## 為什麼我應該上傳記錄檔? + +上傳記錄檔而不是只在論壇貼文中貼上記錄檔,讓其他人更快地解決你的問題。 它還允許你與他人分享你的記錄檔,而無需複製和貼上它們。 + +某些文字分享網站還會對記錄檔進行語法突顯,使其更易於閱讀,並且可能會對敏感資訊(例如你的使用者名稱或系統資訊)進行審查。 + +## 崩潰報告 + +當遊戲崩潰時,會自動產生崩潰報告。 它們只包含崩潰資訊,而不包含遊戲的實際記錄檔。 它們位於遊戲目錄中的 `crash-reports` 資料夾中。 它們只包含崩潰資訊,而不包含遊戲的實際記錄檔。 它們位於遊戲目錄中的 `crash-reports` 資料夾中。 + +有關崩潰報告的更多資訊,請參閱[崩潰報告](./crash-reports)。 + +## 尋找記錄檔 + +本指南涵蓋了官方 Minecraft 啟動器(通常稱為「原版啟動器」),對於第三方啟動器,你應該參閱其文件。 + +記錄檔位於遊戲目錄中的 logs 資料夾中,遊戲目錄可以在以下位置找到,具體取決於你的作業系統: + +::: code-group + +```:no-line-numbers [Windows] +%appdata%\.minecraft +``` + +```:no-line-numbers [macOS] +~/Library/Application Support/minecraft +``` + +```:no-line-numbers [Linux] +~/.minecraft +``` + +::: + +最新的記錄檔名為 `latest.log`,以及先前的記錄檔使用命名模式 `yyyy-mm-dd_number.log.gz`。 + +## 上傳記錄檔 + +記錄檔可以上傳到各種服務,例如: + +- [Pastebin](https://pastebin.com/) +- [GitHub Gist](https://gist.github.com/) +- [mclo.gs](https://mclo.gs/) diff --git a/versions/1.20.4/translated/zh_tw/sidebar_translations.json b/versions/1.20.4/translated/zh_tw/sidebar_translations.json new file mode 100644 index 000000000..d1631f521 --- /dev/null +++ b/versions/1.20.4/translated/zh_tw/sidebar_translations.json @@ -0,0 +1,47 @@ +{ + "players.title": "玩家指南", + "players.faq": "常見問題", + "players.installingJava": "安裝 Java", + "players.installingJava.windows": "Windows", + "players.installingJava.macOS": "macOS", + "players.installingJava.linux": "Linux", + "players.installingFabric": "安裝 Fabric", + "players.findingMods": "尋找可信賴的模組", + "players.installingMods": "安裝模組", + "players.troubleshooting": "疑難排解", + "players.troubleshooting.uploadingLogs": "上傳你的記錄檔", + "players.troubleshooting.crashReports": "崩潰報告", + "players.updatingFabric": "更新 Fabric", + "develop.title": "開發人員指南", + "develop.gettingStarted": "開始使用", + "develop.gettingStarted.introduction": "Fabric 和模組簡介", + "develop.gettingStarted.devEnvSetup": "設置你的開發環境", + "develop.gettingStarted.creatingProject": "建立一個專案", + "develop.gettingStarted.projectStructure": "專案結構", + "develop.gettingStarted.launchGame": "啟動你的遊戲", + "develop.items": "物品", + "develop.items.potions": "藥水", + "develop.entities": "實體", + "develop.entities.effects": "狀態效果", + "develop.entities.damage-types": "傷害類型", + "develop.commands": "指令", + "develop.commands.basics": "建立指令", + "develop.commands.arguments": "引數", + "develop.commands.suggestions": "建議", + "develop.rendering": "渲染", + "develop.rendering.basicConcepts": "基礎的渲染概念", + "develop.rendering.drawContext": "使用繪圖上下文", + "develop.rendering.hud": "在抬頭顯示器中渲染", + "develop.rendering.gui": "圖形使用者介面和畫面", + "develop.rendering.gui.customScreens": "自訂畫面", + "develop.rendering.gui.customWidgets": "自訂小工具", + "develop.rendering.particles": "粒子", + "develop.rendering.particles.creatingParticles": "建立自訂粒子", + "develop.misc": "雜項頁面", + "develop.misc.codecs": "解編碼器", + "develop.misc.events": "事件", + "develop.sounds": "音效", + "develop.sounds.using-sounds": "撥放音效事件", + "develop.sounds.custom": "建立自訂音效", + "github.edit": "在 GitHub 上編輯此頁面" +} \ No newline at end of file