### Starting a GameTest in Java Source: https://github.com/tt432/12101mcmojang/blob/master/net_minecraft_gametest_framework_GameTestInfo.java.md This method initializes the game test by setting the `started` flag to true and executing the test function's `run` method. It ensures the test is only started once and catches any exceptions that occur during the initial test setup, failing the test if an error occurs. ```Java private void startTest() { if (!this.started) { this.started = true; try { this.testFunction.run(new GameTestHelper(this)); } catch (Exception exception) { this.fail(exception); } } } ``` -------------------------------- ### Initializing NeoForge Registry Setup in Java Source: https://github.com/tt432/12101mcmojang/blob/master/net_neoforged_neoforge_registries_NeoForgeRegistriesSetup.java.md This synchronized method initializes the NeoForge registry setup process. It ensures that the setup is executed only once to prevent redundant calls and registers event listeners for `NewRegistryEvent` and `ModifyRegistriesEvent` to handle subsequent registry operations. ```java public static synchronized void setup(IEventBus modEventBus) { if (setup) throw new IllegalStateException("Setup has already been called!"); setup = true; modEventBus.addListener(NeoForgeRegistriesSetup::registerRegistries); modEventBus.addListener(NeoForgeRegistriesSetup::modifyRegistries); } ``` -------------------------------- ### Getting Start Time in Nanoseconds (Java) Source: https://github.com/tt432/12101mcmojang/blob/master/net_minecraft_util_profiling_FilledProfileResults.java.md This method overrides getStartTimeNano() to return the start time of the profiling session in nanoseconds, stored in the startTimeNano field. ```Java @Override public long getStartTimeNano() { return this.startTimeNano; } ``` -------------------------------- ### Launching Minecraft Client with Dynamic Asset Configuration (Java) Source: https://github.com/tt432/12101mcmojang/blob/master/mcp_client_Start.java.md This snippet defines the `main` method, the entry point for the Minecraft client application. It dynamically determines the asset directory and index by attempting to read from `assets.json` or falling back to environment variables or a default value. It then constructs and passes a comprehensive set of command-line arguments, including version, access token, asset paths, and user properties, to `net.minecraft.client.main.Main.main` to initiate the game. Dependencies include `java.io.*`, `java.util.Arrays`, `com.google.gson.*`, and `net.minecraft.client.main.Main`. ```java public static void main(String[] args) { /* * start minecraft game application * --version is just used as 'launched version' in snoop data and is required * Working directory is used as gameDir if not provided */ String assets = null; String assetIndex = "17"; try (InputStream assetsInput = Start.class.getClassLoader().getResourceAsStream("assets.json")) { if (assetsInput != null) { JsonElement element = JsonParser.parseReader(new InputStreamReader(assetsInput)); assets = element.getAsJsonObject().get("assets").getAsString(); assetIndex = element.getAsJsonObject().get("asset_index").getAsString(); } } catch (IOException e) { e.printStackTrace(); } if (assets == null) { assets = System.getenv().containsKey("assetDirectory") ? System.getenv("assetDirectory") : "assets"; } Main.main(concat(new String[] { "--version", "mcp", "--accessToken", "0", "--assetsDir", assets, "--assetIndex", assetIndex, "--userProperties", "{}" }, args)); } ``` -------------------------------- ### Configuring Game and User Data (Java) Source: https://github.com/tt432/12101mcmojang/blob/master/net_minecraft_client_main_Main.java.md This snippet parses command-line arguments to construct `User` and `GameConfig` objects, which encapsulate user details, display settings, folder paths, and quick play data. It handles potential `Throwable` exceptions during this initial setup, generating crash reports if errors occur. ```Java String s8 = optionset.valueOf(optionspec14); String s9 = optionset.valueOf(optionspec15); String s10 = parseArgument(optionset, optionspec1); String s11 = unescapeJavaArgument(parseArgument(optionset, optionspec2)); String s12 = unescapeJavaArgument(parseArgument(optionset, optionspec3)); String s13 = unescapeJavaArgument(parseArgument(optionset, optionspec4)); User user = new User( optionspec12.value(optionset), uuid, optionspec16.value(optionset), emptyStringToEmptyOptional(s8), emptyStringToEmptyOptional(s9), user$type ); gameconfig = new GameConfig( new GameConfig.UserData(user, propertymap, propertymap1, proxy), new DisplayData(i, j, optionalint, optionalint1, flag), new GameConfig.FolderData(file1, file3, file2, s7), new GameConfig.GameData(flag1, s, s6, flag2, flag3), new GameConfig.QuickPlayData(s10, s11, s12, s13) ); Util.startTimerHackThread(); completablefuture.join(); } catch (Throwable throwable1) { CrashReport crashreport = CrashReport.forThrowable(throwable1, s1); CrashReportCategory crashreportcategory = crashreport.addCategory("Initialization"); NativeModuleLister.addCrashSection(crashreportcategory); Minecraft.fillReport(null, null, s, null, crashreport); Minecraft.crash(null, file1, crashreport); return; } ``` -------------------------------- ### Getting All Structure Starts in Java Source: https://github.com/tt432/12101mcmojang/blob/master/net_minecraft_world_level_chunk_ImposterProtoChunk.java.md This method retrieves a map of all `Structure` objects to their corresponding `StructureStart` instances from the wrapped object. It provides a comprehensive view of all structure starts. ```Java @Override public Map getAllStarts() { return this.wrapped.getAllStarts(); } ``` -------------------------------- ### Getting Start Time in Ticks (Java) Source: https://github.com/tt432/12101mcmojang/blob/master/net_minecraft_util_profiling_FilledProfileResults.java.md This method overrides getStartTimeTicks() to return the start time of the profiling session in game ticks, stored in the startTimeTicks field. ```Java @Override public int getStartTimeTicks() { return this.startTimeTicks; } ``` -------------------------------- ### Implementing Open Inventory Tutorial Step in NeoForge Client Source: https://github.com/tt432/12101mcmojang/blob/master/net_minecraft_client_tutorial_OpenInventoryTutorialStep.java.md This Java class, `OpenInventoryTutorialStep`, defines a client-side tutorial step for guiding players to open their inventory. It extends `TutorialStepInstance`, manages a `TutorialToast` hint that appears after a delay, and transitions the tutorial to `CRAFT_PLANKS` upon the `onOpenInventory` event, provided the player is in survival mode. ```java package net.minecraft.client.tutorial; import net.minecraft.client.gui.components.toasts.TutorialToast; import net.minecraft.network.chat.Component; import net.neoforged.api.distmarker.Dist; import net.neoforged.api.distmarker.OnlyIn; @OnlyIn(Dist.CLIENT) public class OpenInventoryTutorialStep implements TutorialStepInstance { private static final int HINT_DELAY = 600; private static final Component TITLE = Component.translatable("tutorial.open_inventory.title"); private static final Component DESCRIPTION = Component.translatable("tutorial.open_inventory.description", Tutorial.key("inventory")); private final Tutorial tutorial; private TutorialToast toast; private int timeWaiting; public OpenInventoryTutorialStep(Tutorial tutorial) { this.tutorial = tutorial; } @Override public void tick() { this.timeWaiting++; if (!this.tutorial.isSurvival()) { this.tutorial.setStep(TutorialSteps.NONE); } else { if (this.timeWaiting >= 600 && this.toast == null) { this.toast = new TutorialToast(TutorialToast.Icons.RECIPE_BOOK, TITLE, DESCRIPTION, false); this.tutorial.getMinecraft().getToasts().addToast(this.toast); } } } @Override public void clear() { if (this.toast != null) { this.toast.hide(); this.toast = null; } } @Override public void onOpenInventory() { this.tutorial.setStep(TutorialSteps.CRAFT_PLANKS); } } ``` -------------------------------- ### Setting Up NeoForge Registries and Startup Notification - NeoForge - Java Source: https://github.com/tt432/12101mcmojang/blob/master/net_neoforged_neoforge_common_NeoForgeMod.java.md Performs essential setup for NeoForge's internal registries and adds a startup notification message. This ensures that all necessary registries are initialized and provides immediate feedback to the user about the mod's version. ```Java NeoForgeRegistriesSetup.setup(modEventBus); StartupNotificationManager.addModMessage("NeoForge version " + NeoForgeVersion.getVersion()); ``` -------------------------------- ### Getting Structure Start for Structure in Java Source: https://github.com/tt432/12101mcmojang/blob/master/net_minecraft_world_level_chunk_ChunkAccess.java.md This method retrieves the `StructureStart` object associated with a specific `Structure` type within the chunk. It returns `null` if no start is found for the given structure. ```Java @Nullable @Override public StructureStart getStartForStructure(Structure structure) { return this.structureStarts.get(structure); } ``` -------------------------------- ### Defining LinkFileSystem Class and Constructor - Java Source: https://github.com/tt432/12101mcmojang/blob/master/net_minecraft_server_packs_linkfs_LinkFileSystem.java.md This snippet defines the `LinkFileSystem` class, which extends `java.nio.file.FileSystem`, and its constructor. It initializes the file system with a given name and a root directory entry, setting up the internal `FileStore` and the root `LinkFSPath`. It also includes necessary imports and static fields. ```java package net.minecraft.server.packs.linkfs; import com.google.common.base.Splitter; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import java.nio.file.FileStore; import java.nio.file.FileSystem; import java.nio.file.Path; import java.nio.file.PathMatcher; import java.nio.file.WatchService; import java.nio.file.attribute.UserPrincipalLookupService; import java.nio.file.spi.FileSystemProvider; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.Nullable; public class LinkFileSystem extends FileSystem { private static final Set VIEWS = Set.of("basic"); public static final String PATH_SEPARATOR = "/"; private static final Splitter PATH_SPLITTER = Splitter.on('/'); private final FileStore store; private final FileSystemProvider provider = new LinkFSProvider(); private final LinkFSPath root; LinkFileSystem(String name, LinkFileSystem.DirectoryEntry root) { this.store = new LinkFSFileStore(name); this.root = buildPath(root, this, "", null); } ``` -------------------------------- ### Initiating Backup Download Process (Java) Source: https://github.com/tt432/12101mcmojang/blob/master/com_mojang_realmsclient_gui_screens_RealmsBackupScreen.java.md This Java method handles the action when the download button is clicked. It displays an info popup to confirm the download, and upon confirmation, transitions the user to a `RealmsLongRunningMcoTaskScreen` to execute a `DownloadTask` for the selected server's backup, providing server details for the download process. ```Java private void downloadClicked() { this.minecraft .setScreen( RealmsPopups.infoPopupScreen( this, Component.translatable("mco.configure.world.restore.download.question.line1"), p_344114_ -> this.minecraft .setScreen( new RealmsLongRunningMcoTaskScreen( this.lastScreen.getNewScreen(), new DownloadTask( this.serverData.id, this.slotId, this.serverData.name + " (" + this.serverData.slots.get(this.serverData.activeSlot).getSlotName(this.serverData.activeSlot) + ")", this ) ) ) ) ); } ``` -------------------------------- ### Getting Shader Fog Start in Java Source: https://github.com/tt432/12101mcmojang/blob/master/com_mojang_blaze3d_systems_RenderSystem.java.md Retrieves the current starting distance for shader-based fog. This value indicates where the fog effect begins. The method asserts execution on the render thread. ```Java public static float getShaderFogStart() { assertOnRenderThread(); return shaderFogStart; } ``` -------------------------------- ### Initializing FileZipper for Java Source: https://github.com/tt432/12101mcmojang/blob/master/net_minecraft_util_FileZipper.java.md This constructor initializes a new `FileZipper` instance, setting up the output and temporary file paths. It then creates a new ZIP file system provider linked to the temporary file, preparing it for content addition. An `UncheckedIOException` is thrown if the file system creation fails. ```java public FileZipper(Path outputFile) { this.outputFile = outputFile; this.tempFile = outputFile.resolveSibling(outputFile.getFileName().toString() + "_tmp"); try { this.fs = Util.ZIP_FILE_SYSTEM_PROVIDER.newFileSystem(this.tempFile, ImmutableMap.of("create", "true")); } catch (IOException ioexception) { throw new UncheckedIOException(ioexception); } } ``` -------------------------------- ### Getting Structure Start from Accessor in Java Source: https://github.com/tt432/12101mcmojang/blob/master/net_minecraft_world_level_StructureManager.java.md This method retrieves a `StructureStart` object for a given `Structure` from a `StructureAccess` at a specified `SectionPos`. It acts as a direct lookup, returning the stored start or `null` if not found. ```java @Nullable public StructureStart getStartForStructure(SectionPos sectionPos, Structure structure, StructureAccess structureAccess) { return structureAccess.getStartForStructure(structure); } ``` -------------------------------- ### Getting Start Node for Flying Mob Pathfinding - Minecraft - Java Source: https://github.com/tt432/12101mcmojang/blob/master/net_minecraft_world_level_pathfinder_FlyNodeEvaluator.java.md Determines the starting `Node` for pathfinding. It handles cases where the mob is in water (if it can float) by adjusting the Y-coordinate upwards until out of water. If the initial position is not valid, it iterates through candidate positions around the mob to find a suitable starting point. ```java @Override public Node getStart() { int i; if (this.canFloat() && this.mob.isInWater()) { i = this.mob.getBlockY(); BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(this.mob.getX(), (double)i, this.mob.getZ()); for (BlockState blockstate = this.currentContext.getBlockState(blockpos$mutableblockpos); blockstate.is(Blocks.WATER); blockstate = this.currentContext.getBlockState(blockpos$mutableblockpos) ) { blockpos$mutableblockpos.set(this.mob.getX(), (double)(++i), this.mob.getZ()); } } else { i = Mth.floor(this.mob.getY() + 0.5); } BlockPos blockpos1 = BlockPos.containing(this.mob.getX(), (double)i, this.mob.getZ()); if (!this.canStartAt(blockpos1)) { for (BlockPos blockpos : this.iteratePathfindingStartNodeCandidatePositions(this.mob)) { if (this.canStartAt(blockpos)) { return super.getStartNode(blockpos); } } } return super.getStartNode(blockpos1); } ``` -------------------------------- ### Initializing Render Thread and Running Game (Java) Source: https://github.com/tt432/12101mcmojang/blob/master/net_minecraft_client_main_Main.java.md This block initializes the render thread, creates a `Minecraft` instance with the previously configured `GameConfig`, and then runs the game. It includes error handling for `SilentInitException` and other `Throwable` exceptions during window creation or game initialization, generating crash reports as needed. ```Java Minecraft minecraft = null; try { Thread.currentThread().setName("Render thread"); RenderSystem.initRenderThread(); RenderSystem.beginInitialization(); minecraft = new Minecraft(gameconfig); RenderSystem.finishInitialization(); } catch (SilentInitException silentinitexception) { Util.shutdownExecutors(); logger.warn("Failed to create window: ", (Throwable)silentinitexception); return; } catch (Throwable throwable) { CrashReport crashreport1 = CrashReport.forThrowable(throwable, "Initializing game"); CrashReportCategory crashreportcategory1 = crashreport1.addCategory("Initialization"); NativeModuleLister.addCrashSection(crashreportcategory1); Minecraft.fillReport(minecraft, null, gameconfig.game.launchVersion, null, crashreport1); Minecraft.crash(minecraft, gameconfig.location.gameDirectory, crashreport1); return; } Minecraft minecraft1 = minecraft; minecraft.run(); BufferUploader.reset(); try { minecraft1.stop(); } finally { minecraft.destroy(); } ``` -------------------------------- ### Getting All Structure Starts in Java Source: https://github.com/tt432/12101mcmojang/blob/master/net_minecraft_world_level_chunk_ChunkAccess.java.md This method returns an unmodifiable map containing all `Structure` to `StructureStart` mappings stored within the chunk. This prevents external code from directly modifying the internal structure starts data. ```Java public Map getAllStarts() { return Collections.unmodifiableMap(this.structureStarts); } ``` -------------------------------- ### Setting Up Network Registry in NeoForge Java Source: https://github.com/tt432/12101mcmojang/blob/master/net_neoforged_neoforge_network_registration_NetworkRegistry.java.md The `setup()` method initializes the network registry. It ensures that the setup process is executed only once, throwing an `IllegalStateException` if called multiple times. During setup, it posts a `RegisterPayloadHandlersEvent` using `ModLoader`, allowing other modules to register their custom payload handlers. This method marks the beginning of the payload registration phase. ```Java public static void setup() { if (setup) { throw new IllegalStateException("The network registry can only be setup once."); } ModLoader.postEvent(new RegisterPayloadHandlersEvent()); setup = true; } ``` -------------------------------- ### Executing Game Bootstrap and Pre-Initialization Steps (Java) Source: https://github.com/tt432/12101mcmojang/blob/master/net_minecraft_client_main_Main.java.md This block handles critical game initialization. It conditionally starts a JVM profiler, measures load times using Stopwatch, detects game version, optimizes data fixers, preloads crash reporting, and performs the main Bootstrap process. It also logs any unrecognized command-line arguments. ```Java try { if (optionset.has(optionspec)) { JvmProfiler.INSTANCE.start(Environment.CLIENT); } Stopwatch stopwatch = Stopwatch.createStarted(Ticker.systemTicker()); Stopwatch stopwatch1 = Stopwatch.createStarted(Ticker.systemTicker()); GameLoadTimesEvent.INSTANCE.beginStep(TelemetryProperty.LOAD_TIME_TOTAL_TIME_MS, stopwatch); GameLoadTimesEvent.INSTANCE.beginStep(TelemetryProperty.LOAD_TIME_PRE_WINDOW_MS, stopwatch1); SharedConstants.tryDetectVersion(); CompletableFuture completablefuture = DataFixers.optimize(DataFixTypes.TYPES_FOR_LEVEL_LIST); CrashReport.preload(); logger = LogUtils.getLogger(); s1 = "Bootstrap"; net.neoforged.fml.loading.BackgroundWaiter.runAndTick(()->Bootstrap.bootStrap(), net.neoforged.fml.loading.FMLLoader.progressWindowTick); GameLoadTimesEvent.INSTANCE.setBootstrapTime(Bootstrap.bootstrapDuration.get()); Bootstrap.validate(); s1 = "Argument parsing"; List list = optionset.valuesOf(optionspec27); if (!list.isEmpty()) { logger.info("Completely ignored arguments: {}", list); } ``` -------------------------------- ### Getting Tooltip Border Start Color in Java Source: https://github.com/tt432/12101mcmojang/blob/master/net_neoforged_neoforge_client_event_RenderTooltipEvent.java.md Retrieves the current gradient start color for the tooltip's border (top edge). This method provides access to the `borderStart` property, which defines the initial color of the border gradient. ```Java public int getBorderStart() { return borderStart; } ``` -------------------------------- ### Defining BundleTutorial Class and Constructor in Java Source: https://github.com/tt432/12101mcmojang/blob/master/net_minecraft_client_tutorial_BundleTutorial.java.md This snippet defines the `BundleTutorial` class, responsible for guiding players on using bundle items. It includes necessary imports, class annotations for client-side execution, and the constructor which initializes the tutorial with references to the main `Tutorial` system and client `Options`. ```java package net.minecraft.client.tutorial; import javax.annotation.Nullable; import net.minecraft.client.Options; import net.minecraft.client.gui.components.toasts.TutorialToast; import net.minecraft.network.chat.Component; import net.minecraft.world.inventory.ClickAction; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.neoforged.api.distmarker.Dist; import net.neoforged.api.distmarker.OnlyIn; @OnlyIn(Dist.CLIENT) public class BundleTutorial { private final Tutorial tutorial; private final Options options; @Nullable private TutorialToast toast; public BundleTutorial(Tutorial tutorial, Options options) { this.tutorial = tutorial; this.options = options; } } ``` -------------------------------- ### Getting Tooltip Background Start Color in Java Source: https://github.com/tt432/12101mcmojang/blob/master/net_neoforged_neoforge_client_event_RenderTooltipEvent.java.md Retrieves the current gradient start color for the tooltip's background (top edge). This method provides access to the `backgroundStart` property, which defines the initial color of the background gradient. ```Java public int getBackgroundStart() { return backgroundStart; } ``` -------------------------------- ### Initializing RealmsBackupScreen UI - Java Source: https://github.com/tt432/12101mcmojang/blob/master/com_mojang_realmsclient_gui_screens_RealmsBackupScreen.java.md Overrides the `init()` method to set up the screen's user interface components. It adds a title header, initializes the backup list, and creates 'Download Latest' and 'Back' buttons, with the download button initially disabled. Finally, it repositions elements and initiates fetching of Realms backups. ```Java @Override public void init() { this.layout.addTitleHeader(TITLE, this.font); this.backupList = this.layout.addToContents(new RealmsBackupScreen.BackupObjectSelectionList()); LinearLayout linearlayout = this.layout.addToFooter(LinearLayout.horizontal().spacing(8)); this.downloadButton = linearlayout.addChild(Button.builder(DOWNLOAD_LATEST, p_88185_ -> this.downloadClicked()).build()); this.downloadButton.active = false; linearlayout.addChild(Button.builder(CommonComponents.GUI_BACK, p_329634_ -> this.onClose()).build()); this.layout.visitWidgets(p_329637_ -> { AbstractWidget abstractwidget = this.addRenderableWidget(p_329637_); }); this.repositionElements(); this.fetchRealmsBackups(); } ``` -------------------------------- ### Starting and Stopping LongDistancePatrolGoal in Java Source: https://github.com/tt432/12101mcmojang/blob/master/net_minecraft_world_entity_monster_PatrollingMonster.java.md These methods define the behavior when the `LongDistancePatrolGoal` starts or stops. In this implementation, they are empty, indicating no specific setup or teardown is required beyond the `tick` method's continuous logic for patrol management. ```Java @Override public void start() { } @Override public void stop() { } ``` -------------------------------- ### Getting Original Tooltip Border Start Color in Java Source: https://github.com/tt432/12101mcmojang/blob/master/net_neoforged_neoforge_client_event_RenderTooltipEvent.java.md Retrieves the initial gradient start color for the tooltip's border as it was originally set. This method provides access to the `originalBorderStart` property, useful for reverting or referencing the default state. ```Java public int getOriginalBorderStart() { return originalBorderStart; } ``` -------------------------------- ### Setting Up Keyboard Callbacks - InputConstants - Java Source: https://github.com/tt432/12101mcmojang/blob/master/net_minecraft_client_KeyboardHandler.java.md This method initializes keyboard input callbacks for a given window. It registers two lambda functions with `InputConstants.setupKeyboardCallbacks`: one for key press events (`keyPress`) and another for character typed events (`charTyped`), both executed on the Minecraft client thread. ```Java public void setup(long window) { InputConstants.setupKeyboardCallbacks( window, (p_90939_, p_90940_, p_90941_, p_90942_, p_90943_) -> this.minecraft.execute(() -> this.keyPress(p_90939_, p_90940_, p_90941_, p_90942_, p_90943_)), (p_90935_, p_90936_, p_90937_) -> this.minecraft.execute(() -> this.charTyped(p_90935_, p_90936_, p_90937_)) ); } ``` -------------------------------- ### Getting Original Tooltip Background Start Color in Java Source: https://github.com/tt432/12101mcmojang/blob/master/net_neoforged_neoforge_client_event_RenderTooltipEvent.java.md Retrieves the initial gradient start color for the tooltip's background as it was originally set. This method provides access to the `originalBackground` property, useful for reverting or referencing the default state. ```Java public int getOriginalBackgroundStart() { return originalBackground; } ``` -------------------------------- ### Initializing Server Environment (NeoForge) Source: https://github.com/tt432/12101mcmojang/blob/master/net_neoforged_neoforge_server_ServerLifecycleHooks.java.md This snippet handles initial server setup, including loading mod languages, registering GameTests (unless it's a GameTestServer), initializing the PermissionAPI, and posting the ServerStartingEvent to the NeoForge event bus. It ensures essential modding components are ready when the server begins. ```Java if (FMLEnvironment.dist.isDedicatedServer()) { LanguageHook.loadModLanguages(server); // GameTestServer requires the gametests to be registered earlier, so it is done in main and should not be done twice. if (!(server instanceof GameTestServer)) GameTestHooks.registerGametests(); } PermissionAPI.initializePermissionAPI(); NeoForge.EVENT_BUS.post(new ServerStartingEvent(server)); ``` -------------------------------- ### Server Starting Event Class Definition - NeoForge Java Source: https://github.com/tt432/12101mcmojang/blob/master/net_neoforged_neoforge_event_server_ServerStartingEvent.java.md This Java class defines the `ServerStartingEvent`, an event fired by NeoForge after the server is about to start but before it has fully started. It extends `ServerLifecycleEvent` and provides a constructor that takes a `MinecraftServer` instance, allowing for server-wide customizations. Developers can use this event to perform setup tasks or modify server properties at an early stage of its lifecycle. ```java /* * Copyright (c) Forge Development LLC and contributors * SPDX-License-Identifier: LGPL-2.1-only */ package net.neoforged.neoforge.event.server; import net.minecraft.server.MinecraftServer; import net.neoforged.neoforge.event.RegisterCommandsEvent; /** * Called after {@link ServerAboutToStartEvent} and before {@link ServerStartedEvent}. * This event allows for customizations of the server. * * If you need to add commands use {@link RegisterCommandsEvent}. * * @author cpw */ public class ServerStartingEvent extends ServerLifecycleEvent { public ServerStartingEvent(final MinecraftServer server) { super(server); } } ``` -------------------------------- ### Setting Up and Executing BlockEntity Rendering in Java Source: https://github.com/tt432/12101mcmojang/blob/master/net_minecraft_client_renderer_blockentity_BlockEntityRenderDispatcher.java.md The `setupAndRender` static helper method prepares the rendering environment by determining the light color at the block entity's position. It then invokes the `render` method of the specific `BlockEntityRenderer`, passing all necessary rendering parameters including the pose stack, buffer source, light, and overlay textures, ensuring the block entity is drawn correctly in the world. ```java private static void setupAndRender( BlockEntityRenderer renderer, T blockEntity, float partialTick, PoseStack poseStack, MultiBufferSource bufferSource ) { Level level = blockEntity.getLevel(); int i; if (level != null) { i = LevelRenderer.getLightColor(level, blockEntity.getBlockPos()); } else { i = 15728880; } renderer.render(blockEntity, partialTick, poseStack, bufferSource, i, OverlayTexture.NO_OVERLAY); } ``` -------------------------------- ### Starting Chase Client (Java) Source: https://github.com/tt432/12101mcmojang/blob/master/net_minecraft_server_commands_ChaseCommand.java.md This method connects the command source as a 'chase client' to a specified host and port. It first verifies no chase is already active. If free, it initializes and starts a `ChaseClient`, informing the user of successful connection and instructions to stop. ```Java private static int follow(CommandSourceStack source, String host, int port) { if (alreadyRunning(source)) { return 0; } else { chaseClient = new ChaseClient(host, port, source.getServer()); chaseClient.start(); source.sendSuccess( () -> Component.literal( "You are now chasing " + host + ":" + port + ". If that server does '/chase lead' then you will automatically go to the same position. Use '/chase stop' to stop chasing." ), false ); return 0; } } ``` -------------------------------- ### Extracting Substring from Offset to End in Java Source: https://github.com/tt432/12101mcmojang/blob/master/net_minecraft_server_commands_data_DataCommands.java.md This overloaded method extracts a substring from a specified `start` index to the end of the `source` string. It calculates the absolute `start` offset using `getOffset` and then delegates to `validatedSubstring` to perform the extraction. This is useful for getting a suffix of a string. ```Java private static String substring(String source, int start) throws CommandSyntaxException { int i = source.length(); return validatedSubstring(source, getOffset(start, i), i); } ``` -------------------------------- ### Starting GameTest Execution in Java Source: https://github.com/tt432/12101mcmojang/blob/master/net_minecraft_gametest_framework_GameTestInfo.java.md This method initiates the execution of the game test. It calculates the `startTick` based on the current game time, the test function's setup ticks, and an optional delay. It also starts an internal `Stopwatch` to measure the test duration. ```java public GameTestInfo startExecution(int delay) { this.startTick = this.level.getGameTime() + this.testFunction.setupTicks() + (long)delay; this.timer.start(); return this; } ``` -------------------------------- ### Initializing Minecraft Demo Intro Screen (Java) Source: https://github.com/tt432/12101mcmojang/blob/master/net_minecraft_client_gui_screens_DemoIntroScreen.java.md This code defines the `DemoIntroScreen` class, which is a GUI screen displayed at the start of the Minecraft demo. It initializes buttons for purchasing the game or continuing, and creates `MultiLineLabel` instances to display instructions for movement controls and information about the demo's duration. It overrides `init()`, `renderBackground()`, and `render()` methods to set up the screen's layout and drawing. ```java package net.minecraft.client.gui.screens; import net.minecraft.Util; import net.minecraft.client.Options; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.components.Button; import net.minecraft.client.gui.components.MultiLineLabel; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import net.minecraft.util.CommonLinks; import net.neoforged.api.distmarker.Dist; import net.neoforged.api.distmarker.OnlyIn; @OnlyIn(Dist.CLIENT) public class DemoIntroScreen extends Screen { private static final ResourceLocation DEMO_BACKGROUND_LOCATION = ResourceLocation.withDefaultNamespace("textures/gui/demo_background.png"); private MultiLineLabel movementMessage = MultiLineLabel.EMPTY; private MultiLineLabel durationMessage = MultiLineLabel.EMPTY; public DemoIntroScreen() { super(Component.translatable("demo.help.title")); } @Override protected void init() { int i = -16; this.addRenderableWidget(Button.builder(Component.translatable("demo.help.buy"), p_351651_ -> { p_351651_.active = false; Util.getPlatform().openUri(CommonLinks.BUY_MINECRAFT_JAVA); }).bounds(this.width / 2 - 116, this.height / 2 + 62 + -16, 114, 20).build()); this.addRenderableWidget(Button.builder(Component.translatable("demo.help.later"), p_280798_ -> { this.minecraft.setScreen(null); this.minecraft.mouseHandler.grabMouse(); }).bounds(this.width / 2 + 2, this.height / 2 + 62 + -16, 114, 20).build()); Options options = this.minecraft.options; this.movementMessage = MultiLineLabel.create( this.font, Component.translatable( "demo.help.movementShort", options.keyUp.getTranslatedKeyMessage(), options.keyLeft.getTranslatedKeyMessage(), options.keyDown.getTranslatedKeyMessage(), options.keyRight.getTranslatedKeyMessage() ), Component.translatable("demo.help.movementMouse"), Component.translatable("demo.help.jump", options.keyJump.getTranslatedKeyMessage()), Component.translatable("demo.help.inventory", options.keyInventory.getTranslatedKeyMessage()) ); this.durationMessage = MultiLineLabel.create(this.font, Component.translatable("demo.help.fullWrapped"), 218); } @Override public void renderBackground(GuiGraphics p_283391_, int p_295532_, int p_296277_, float p_295918_) { super.renderBackground(p_283391_, p_295532_, p_296277_, p_295918_); int i = (this.width - 248) / 2; int j = (this.height - 166) / 2; p_283391_.blit(DEMO_BACKGROUND_LOCATION, i, j, 0, 0, 248, 166); } @Override public void render(GuiGraphics p_281247_, int p_281844_, int p_283693_, float p_281842_) { super.render(p_281247_, p_281844_, p_283693_, p_281842_); int i = (this.width - 248) / 2 + 10; int j = (this.height - 166) / 2 + 8; p_281247_.drawString(this.font, this.title, i, j, 2039583, false); j = this.movementMessage.renderLeftAlignedNoShadow(p_281247_, i, j + 12, 12, 5197647); this.durationMessage.renderLeftAlignedNoShadow(p_281247_, i, j + 20, 9, 2039583); } } ``` -------------------------------- ### Getting Word Position from Specific Index in Java Source: https://github.com/tt432/12101mcmojang/blob/master/net_minecraft_client_gui_components_EditBox.java.md This private overloaded method calculates the starting index of a word located a specified number of words away from a given starting position. It further delegates to a more comprehensive overload, enabling control over skipping consecutive spaces. ```Java private int getWordPosition(int numWords, int pos) { return this.getWordPosition(numWords, pos, true); } ``` -------------------------------- ### Initializing Backup List Entry (Java) Source: https://github.com/tt432/12101mcmojang/blob/master/com_mojang_realmsclient_gui_screens_RealmsBackupScreen.java.md This Java constructor initializes an individual entry for the `RealmsBackupScreen`'s backup list. It stores the `Backup` object, populates a change list, and conditionally creates a 'changes' button if the backup has recorded changes. This button, when clicked, navigates to a `RealmsBackupInfoScreen` to display detailed backup information. ```Java public Entry(Backup backup) { this.backup = backup; this.populateChangeList(backup); if (!backup.changeList.isEmpty()) { this.changesButton = Button.builder( RealmsBackupScreen.HAS_CHANGES_TOOLTIP, p_344115_ -> RealmsBackupScreen.this.minecraft.setScreen(new RealmsBackupInfoScreen(RealmsBackupScreen.this, this.backup)) ) .width(8 + RealmsBackupScreen.this.font.width(RealmsBackupScreen.HAS_CHANGES_TOOLTIP)) .createNarration( p_329639_ -> CommonComponents.joinForNarration( Component.translatable("mco.backup.narration", this.getShortBackupDate()), p_329639_.get() ) ) .build(); this.children.add(this.changesButton); } if (!RealmsBackupScreen.this.serverData.expired) { } ``` -------------------------------- ### Starting Container Open Event - Minecraft NeoForge - Java Source: https://github.com/tt432/12101mcmojang/blob/master/net_minecraft_world_CompoundContainer.java.md This method overrides `startOpen(Player player)` and delegates the call to both `container1` and `container2`. It notifies both underlying containers that a player has started interacting with the combined inventory, allowing them to perform any necessary setup or state changes. ```java @Override public void startOpen(Player player) { this.container1.startOpen(player); this.container2.startOpen(player); } ``` -------------------------------- ### Creating NetworkPayloadSetup from Negotiation Results in NeoForge Java Source: https://github.com/tt432/12101mcmojang/blob/master/net_neoforged_neoforge_network_registration_NetworkPayloadSetup.java.md The `from()` static factory method constructs a `NetworkPayloadSetup` instance based on the results of network negotiation. It takes a map of `ConnectionProtocol` to `NegotiationResult` and processes each result to build an immutable map of `ResourceLocation` to `NetworkChannel` for each protocol, effectively populating the network setup with negotiated channels. ```java /** * {@return A modded network with the given configuration and play channels.} */ public static NetworkPayloadSetup from(Map results) { ImmutableMap.Builder> channels = ImmutableMap.builder(); for (Map.Entry result : results.entrySet()) { ImmutableMap.Builder protocolChannels = ImmutableMap.builder(); result.getValue().components().forEach(component -> { protocolChannels.put(component.id(), new NetworkChannel(component.id(), component.version())); }); channels.put(result.getKey(), protocolChannels.build()); } return new NetworkPayloadSetup(channels.build()); } ``` -------------------------------- ### Starting Chase Server (Java) Source: https://github.com/tt432/12101mcmojang/blob/master/net_minecraft_server_commands_ChaseCommand.java.md This method initiates a 'chase server' on a specified port and bind address. It first checks if a chase operation is already active. If not, it creates and starts a `ChaseServer` instance, sending a success message upon successful startup or a failure message if an `IOException` occurs. ```Java private static int lead(CommandSourceStack source, String bindAddress, int port) { if (alreadyRunning(source)) { return 0; } else { chaseServer = new ChaseServer(bindAddress, port, source.getServer().getPlayerList(), 100); try { chaseServer.start(); source.sendSuccess( () -> Component.literal("Chase server is now running on port " + port + ". Clients can follow you using /chase follow "), false ); } catch (IOException ioexception) { LOGGER.error("Failed to start chase server", (Throwable)ioexception); source.sendFailure(Component.literal("Failed to start chase server on port " + port)); chaseServer = null; } return 0; } } ``` -------------------------------- ### Starting Illusioner Blindness Spell Goal in Java Source: https://github.com/tt432/12101mcmojang/blob/master/net_minecraft_world_entity_monster_Illusioner.java.md This method initiates the blindness spell goal for the Illusioner. It calls the `start` method of its superclass, which typically handles common setup logic for spellcasting goals. This marks the beginning of the spell's execution phase. ```Java @Override public void start() { super.start(); ``` -------------------------------- ### Initializing ShareToLanScreen UI and Publishing Logic - Java Source: https://github.com/tt432/12101mcmojang/blob/master/net_minecraft_client_gui_screens_ShareToLanScreen.java.md This `init()` method sets up the interactive elements of the Share to LAN screen. It initializes cycle buttons for game mode and command toggling, creates a button to start the LAN server, and adds an `EditBox` for port input. The method also includes the logic for publishing the server and handling port validation feedback. ```java @Override protected void init() { IntegratedServer integratedserver = this.minecraft.getSingleplayerServer(); this.gameMode = integratedserver.getDefaultGameType(); this.commands = integratedserver.getWorldData().isAllowCommands(); this.addRenderableWidget( CycleButton.builder(GameType::getShortDisplayName) .withValues(GameType.SURVIVAL, GameType.SPECTATOR, GameType.CREATIVE, GameType.ADVENTURE) .withInitialValue(this.gameMode) .create(this.width / 2 - 155, 100, 150, 20, GAME_MODE_LABEL, (p_169429_, p_169430_) -> this.gameMode = p_169430_) ); this.addRenderableWidget( CycleButton.onOffBuilder(this.commands) .create(this.width / 2 + 5, 100, 150, 20, ALLOW_COMMANDS_LABEL, (p_169432_, p_169433_) -> this.commands = p_169433_) ); Button button = Button.builder(Component.translatable("lanServer.start"), p_280826_ -> { this.minecraft.setScreen(null); Component component; if (integratedserver.publishServer(this.gameMode, this.commands, this.port)) { component = PublishCommand.getSuccessMessage(this.port); } else { component = Component.translatable("commands.publish.failed"); } this.minecraft.gui.getChat().addMessage(component); this.minecraft.updateTitle(); }).bounds(this.width / 2 - 155, this.height - 28, 150, 20).build(); this.portEdit = new EditBox(this.font, this.width / 2 - 75, 160, 150, 20, Component.translatable("lanServer.port")); this.portEdit.setResponder(p_258130_ -> { Component component = this.tryParsePort(p_258130_); this.portEdit.setHint(Component.literal(this.port + "").withStyle(ChatFormatting.DARK_GRAY)); if (component == null) { this.portEdit.setTextColor(14737632); this.portEdit.setTooltip(null); button.active = true; } else { this.portEdit.setTextColor(16733525); this.portEdit.setTooltip(Tooltip.create(component)); button.active = false; } }); this.portEdit.setHint(Component.literal(this.port + "").withStyle(ChatFormatting.DARK_GRAY)); this.addRenderableWidget(this.portEdit); this.addRenderableWidget(button); this.addRenderableWidget( Button.builder(CommonComponents.GUI_CANCEL, p_329722_ -> this.onClose()).bounds(this.width / 2 + 5, this.height - 28, 150, 20).build() ); } ``` -------------------------------- ### Providing Command Suggestions and Examples in Java Source: https://github.com/tt432/12101mcmojang/blob/master/net_minecraft_commands_arguments_blocks_BlockPredicateArgument.java.md These methods are part of the `ArgumentType` interface implementation. `listSuggestions` provides asynchronous suggestions to the command builder using `BlockStateParser.fillSuggestions`, while `getExamples` returns a predefined collection of example strings to guide users on valid argument formats. ```java @Override public CompletableFuture listSuggestions(CommandContext context, SuggestionsBuilder builder) { return BlockStateParser.fillSuggestions(this.blocks, builder, true, true); } @Override public Collection getExamples() { return EXAMPLES; } ``` -------------------------------- ### Starting JFR Recording - Java Source: https://github.com/tt432/12101mcmojang/blob/master/net_minecraft_util_profiling_jfr_JfrProfiler.java.md Initiates a new JFR recording using a provided configuration. It sets up custom events, enables dump-on-exit and disk persistence, names the recording, sets its destination path, and then starts it, also configuring a summary listener. It handles parsing and I/O exceptions during setup. ```Java private boolean start(Reader reader, Environment environment) { if (this.isRunning()) { LOGGER.warn("Profiling already in progress"); return false; } else { try { Configuration configuration = Configuration.create(reader); String s = DATE_TIME_FORMATTER.format(Instant.now()); this.recording = Util.make(new Recording(configuration), p_185311_ -> { CUSTOM_EVENTS.forEach(p_185311_::enable); p_185311_.setDumpOnExit(true); p_185311_.setToDisk(true); p_185311_.setName(String.format(Locale.ROOT, "%s-%s-%s", environment.getDescription(), SharedConstants.getCurrentVersion().getName(), s)); }); Path path = Paths.get(String.format(Locale.ROOT, "debug/%s-%s.jfr", environment.getDescription(), s)); FileUtil.createDirectoriesSafe(path.getParent()); this.recording.setDestination(path); this.recording.start(); this.setupSummaryListener(); } catch (ParseException | IOException ioexception) { LOGGER.warn("Failed to start jfr profiling", (Throwable)ioexception); return false; } LOGGER.info( "Started flight recorder profiling id({}):name({}) - will dump to {} on exit or stop command", this.recording.getId(), this.recording.getName(), this.recording.getDestination() ); return true; } } ``` -------------------------------- ### Getting Current Ticks - Java Source: https://github.com/tt432/12101mcmojang/blob/master/net_minecraft_client_renderer_LevelRenderer.java.md Returns the current tick count of the game client. This value typically represents the number of game updates that have occurred since the client started. ```Java public int getTicks() { return this.ticks; } ``` -------------------------------- ### Initializing UI Components and Download Check in RealmsDownloadLatestWorldScreen (Java) Source: https://github.com/tt432/12101mcmojang/blob/master/com_mojang_realmsclient_gui_screens_RealmsDownloadLatestWorldScreen.java.md The `init` method is called when the screen is initialized. It sets up the "Cancel" button and then calls `checkDownloadSize()` to perform a preliminary check on the world download size before proceeding with the actual download. ```java @Override public void init() { this.cancelButton = this.addRenderableWidget( Button.builder(CommonComponents.GUI_CANCEL, p_344127_ -> this.onClose()).bounds((this.width - 200) / 2, this.height - 42, 200, 20).build() ); this.checkDownloadSize(); } ``` -------------------------------- ### Initializing UI Components in DirectJoinServerScreen (Java) Source: https://github.com/tt432/12101mcmojang/blob/master/net_minecraft_client_gui_screens_DirectJoinServerScreen.java.md The `init` method sets up the screen's UI elements. It creates an `EditBox` for IP input, sets its properties (max length, initial value from `lastMpIp`), and adds a responder to update button status. It also adds 'Select' and 'Cancel' buttons with their respective bounds and actions. ```java @Override protected void init() { this.ipEdit = new EditBox(this.font, this.width / 2 - 100, 116, 200, 20, Component.translatable("addServer.enterIp")); this.ipEdit.setMaxLength(128); this.ipEdit.setValue(this.minecraft.options.lastMpIp); this.ipEdit.setResponder(p_95983_ -> this.updateSelectButtonStatus()); this.addWidget(this.ipEdit); this.selectButton = this.addRenderableWidget( Button.builder(Component.translatable("selectServer.select"), p_95981_ -> this.onSelect()) .bounds(this.width / 2 - 100, this.height / 4 + 96 + 12, 200, 20) .build() ); this.addRenderableWidget( Button.builder(CommonComponents.GUI_CANCEL, p_95977_ -> this.callback.accept(false)) .bounds(this.width / 2 - 100, this.height / 4 + 120 + 12, 200, 20) .build() ); this.updateSelectButtonStatus(); } ``` -------------------------------- ### Checking GameTest Started Status (Java) Source: https://github.com/tt432/12101mcmojang/blob/master/net_minecraft_gametest_framework_GameTestInfo.java.md This method indicates whether the game test has begun its execution. It returns `true` if the `startTest()` method has been called and the test's initial setup is complete. ```Java public boolean hasStarted() { return this.started; } ``` -------------------------------- ### Pre-Initialization Event Handler - NeoForge - Java Source: https://github.com/tt432/12101mcmojang/blob/master/net_neoforged_neoforge_common_NeoForgeMod.java.md Handles the `FMLCommonSetupEvent` during the pre-initialization phase. This method is used to start the version checker, ensuring the mod's compatibility and notifying users of updates. ```Java public void preInit(FMLCommonSetupEvent evt) { VersionChecker.startVersionCheck(); } ``` -------------------------------- ### Getting TrialSpawner Required Player Range in Java Source: https://github.com/tt432/12101mcmojang/blob/master/net_minecraft_world_level_block_entity_trialspawner_TrialSpawner.java.md This method returns the integer value representing the required player range for the `TrialSpawner` to be active or to trigger certain behaviors, such as starting a new wave. ```Java public int getRequiredPlayerRange() { return this.requiredPlayerRange; } ``` -------------------------------- ### Getting Screen Rectangle in Java Source: https://github.com/tt432/12101mcmojang/blob/master/net_minecraft_client_gui_screens_Screen.java.md This method, overriding an interface, returns a `ScreenRectangle` object representing the dimensions of the current screen. The rectangle starts at (0,0) and extends to the screen's width and height. ```Java @Override public ScreenRectangle getRectangle() { return new ScreenRectangle(0, 0, this.width, this.height); } ```