mirror of
https://github.com/MinecraftForge/MinecraftForge.git
synced 2026-11-22 05:02:18 +00:00
Move old tests.
This commit is contained in:
665 files changed
+337
-5622
No files matched your search
@@ -0,0 +1,179 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.commontest;
|
||||
|
||||
import com.electronwill.nightconfig.core.file.CommentedFileConfig;
|
||||
import com.electronwill.nightconfig.core.io.WritingMode;
|
||||
import com.google.common.base.Stopwatch;
|
||||
import com.google.common.collect.Lists;
|
||||
import net.minecraftforge.common.ForgeConfigSpec;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Field;
|
||||
import java.nio.file.Files;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class ForgeConfigSpecTest
|
||||
{
|
||||
private final String TEST_CONFIG_PATH_TEMPLATE = "./tests/config/%s.toml";
|
||||
private final int TEST_SIZE = 10000;
|
||||
private static final Field useCachesField;
|
||||
|
||||
static {
|
||||
try {
|
||||
useCachesField = ForgeConfigSpec.ConfigValue.class.getDeclaredField("USE_CACHES");
|
||||
useCachesField.setAccessible(true);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static void setUseCachesField(boolean value) {
|
||||
try {
|
||||
useCachesField.setBoolean(null, value);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void simpleSpeedTest() throws IOException
|
||||
{
|
||||
executeSpeedTest("test", "someDefaultValue", "simpleSpeedTest");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void objectSpeedTest() throws IOException
|
||||
{
|
||||
executeSpeedTest("test", Lists.newArrayList(Lists.newArrayList("someValue")), "objectSpeedTest");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void deepKeySpeedTest() throws IOException
|
||||
{
|
||||
executeSpeedTest("test.test.test.test.test.test.test.test.test.test", "deepKeyValue", "deepKeySpeedTest");
|
||||
}
|
||||
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public void allEmptyCommentTest() throws IllegalStateException
|
||||
{
|
||||
final ForgeConfigSpec.Builder builder = new ForgeConfigSpec.Builder();
|
||||
final ForgeConfigSpec.ConfigValue<String> simpleValue = builder.comment("", "").define("allEmptyCommentTest", "someDefaultValue");
|
||||
final ForgeConfigSpec spec = builder.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void topPaddedCommentTest()
|
||||
{
|
||||
final ForgeConfigSpec.Builder builder = new ForgeConfigSpec.Builder();
|
||||
final ForgeConfigSpec.ConfigValue<String> simpleValue = builder.comment("", "Test").define("topPaddedCommentTest", "someDefaultValue");
|
||||
final ForgeConfigSpec spec = builder.build();
|
||||
}
|
||||
|
||||
private <T> void executeSpeedTest(final String configKey, final T defaultKeyValue, final String testName) throws IOException
|
||||
{
|
||||
final ForgeConfigSpec.Builder builder = new ForgeConfigSpec.Builder();
|
||||
final ForgeConfigSpec.ConfigValue<T> simpleValue = builder.define(configKey, defaultKeyValue);
|
||||
final ForgeConfigSpec spec = builder.build();
|
||||
|
||||
final String configPath = String.format(Locale.ROOT, TEST_CONFIG_PATH_TEMPLATE, testName);
|
||||
final File configFile = new File(configPath);
|
||||
configFile.getParentFile().mkdirs();
|
||||
configFile.createNewFile();
|
||||
final CommentedFileConfig configData = CommentedFileConfig.builder(configPath)
|
||||
.sync()
|
||||
.preserveInsertionOrder()
|
||||
.onFileNotFound((newfile, configFormat) -> {
|
||||
Files.createFile(newfile);
|
||||
return true;
|
||||
})
|
||||
.writingMode(WritingMode.REPLACE)
|
||||
.build();
|
||||
spec.setConfig(configData);
|
||||
|
||||
final List<TestResult> results = runTestHarness(defaultKeyValue, testName, simpleValue, spec, 3, 20);
|
||||
final double averageEnabled = results.stream().mapToLong(value -> value.enabledWatch.elapsed(TimeUnit.NANOSECONDS)).average().getAsDouble();
|
||||
final double averageDisabled = results.stream().mapToLong(value -> value.disabledWatch.elapsed(TimeUnit.NANOSECONDS)).average().getAsDouble();
|
||||
final double maxEnabledDeviation = results.stream().mapToLong(value -> value.enabledWatch.elapsed(TimeUnit.NANOSECONDS))
|
||||
.mapToDouble(e -> e - averageEnabled)
|
||||
.map(Math::abs)
|
||||
.max()
|
||||
.getAsDouble();
|
||||
final double maxDisabledDeviation = results.stream().mapToLong(value -> value.disabledWatch.elapsed(TimeUnit.NANOSECONDS))
|
||||
.mapToDouble(e -> e - averageDisabled)
|
||||
.map(Math::abs)
|
||||
.max()
|
||||
.getAsDouble();
|
||||
|
||||
System.out.printf("Computed test results for: %s:%n", testName);
|
||||
System.out.printf(" > Enabled: ~%10.2f ns. +- %10.2f ns.%n", averageEnabled, maxEnabledDeviation);
|
||||
System.out.printf(" > Disabled: ~%10.2f ns. +- %10.2f ns.%n", averageDisabled, maxDisabledDeviation);
|
||||
|
||||
configFile.delete();
|
||||
}
|
||||
|
||||
private <T> List<TestResult> runTestHarness(final T defaultKeyValue, final String testName, final ForgeConfigSpec.ConfigValue<T> simpleValue, final ForgeConfigSpec spec, final int warmupRounds, final int testRounds)
|
||||
{
|
||||
final List<TestResult> results = new ArrayList<>();
|
||||
|
||||
for (int i = 0; i < warmupRounds; i++)
|
||||
{
|
||||
//Run a bunch of warm up rounds and ignore the results.
|
||||
runTestOnce(defaultKeyValue, testName, simpleValue, spec);
|
||||
}
|
||||
|
||||
for (int i = 0; i < testRounds; i++)
|
||||
{
|
||||
results.add(runTestOnce(defaultKeyValue, testName, simpleValue, spec));
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
private <T> TestResult runTestOnce(final T defaultKeyValue, final String testName, final ForgeConfigSpec.ConfigValue<T> simpleValue, final ForgeConfigSpec spec)
|
||||
{
|
||||
spec.afterReload();
|
||||
setUseCachesField(true);
|
||||
final Stopwatch watchDisabled = Stopwatch.createStarted();
|
||||
for (int i = 0; i < TEST_SIZE; i++)
|
||||
{
|
||||
Assert.assertEquals(defaultKeyValue, simpleValue.get());
|
||||
}
|
||||
watchDisabled.stop();
|
||||
|
||||
spec.afterReload();
|
||||
setUseCachesField(false);
|
||||
final Stopwatch watchEnabled = Stopwatch.createStarted();
|
||||
for (int i = 0; i < TEST_SIZE; i++)
|
||||
{
|
||||
Assert.assertEquals(defaultKeyValue, simpleValue.get());
|
||||
}
|
||||
watchEnabled.stop();
|
||||
|
||||
final TestResult result = new TestResult(watchEnabled, watchDisabled);
|
||||
|
||||
System.out.printf("Test result for: %s (Disabled: %s vs. Enabled: %s)%n", testName, watchDisabled.toString(), watchEnabled.toString());
|
||||
return result;
|
||||
}
|
||||
|
||||
private final static class TestResult {
|
||||
|
||||
private final Stopwatch enabledWatch;
|
||||
private final Stopwatch disabledWatch;
|
||||
|
||||
public TestResult(final Stopwatch enabledWatch, final Stopwatch disabledWatch)
|
||||
{
|
||||
this.enabledWatch = enabledWatch;
|
||||
this.disabledWatch = disabledWatch;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug;
|
||||
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.server.packs.PackType;
|
||||
import net.minecraft.server.packs.PathPackResources.PathResourcesSupplier;
|
||||
import net.minecraft.server.packs.repository.Pack;
|
||||
import net.minecraft.server.packs.repository.PackSource;
|
||||
import net.minecraftforge.event.AddPackFindersEvent;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.fml.ModList;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
|
||||
@Mod(AddPackFinderEventTest.MODID)
|
||||
public class AddPackFinderEventTest {
|
||||
private static final boolean ENABLE = false;
|
||||
public static final String MODID = "add_pack_finders_test";
|
||||
|
||||
public AddPackFinderEventTest() {
|
||||
if (!ENABLE)
|
||||
return;
|
||||
|
||||
FMLJavaModLoadingContext.get().getModEventBus().register(this);
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public void addPackFinders(AddPackFindersEvent event) {
|
||||
if (event.getPackType() == PackType.CLIENT_RESOURCES) {
|
||||
var resourcePath = ModList.get().getModFileById(MODID).getFile().findResource("test_nested_resource_pack");
|
||||
var supplier = new PathResourcesSupplier(resourcePath, false);
|
||||
var pack = Pack.readMetaAndCreate("builtin/add_pack_finders_test", Component.literal("display name"), false, supplier, PackType.CLIENT_RESOURCES, Pack.Position.BOTTOM, PackSource.BUILT_IN);
|
||||
event.addRepositorySource((packConsumer) -> packConsumer.accept(pack));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug;
|
||||
|
||||
import net.minecraft.world.level.block.Blocks;
|
||||
import net.minecraftforge.event.level.AlterGroundEvent;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
|
||||
@Mod("alter_ground_event_test")
|
||||
@Mod.EventBusSubscriber
|
||||
public class AlterGroundEventTest {
|
||||
public static final boolean ENABLE = true;
|
||||
|
||||
@SubscribeEvent
|
||||
public static void onAlterGround(AlterGroundEvent event)
|
||||
{
|
||||
if (ENABLE) {
|
||||
if (event.getOriginalAlteredState().is(Blocks.PODZOL)) {
|
||||
event.setNewAlteredState(Blocks.REDSTONE_BLOCK.defaultBlockState());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug;
|
||||
|
||||
import net.minecraft.Util;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.core.Direction;
|
||||
import net.minecraft.core.Registry;
|
||||
import net.minecraft.nbt.IntTag;
|
||||
import net.minecraft.nbt.Tag;
|
||||
import net.minecraft.network.chat.ChatType;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.block.entity.BlockEntity;
|
||||
import net.minecraft.world.level.chunk.LevelChunk;
|
||||
import net.minecraftforge.api.distmarker.Dist;
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.common.capabilities.*;
|
||||
import net.minecraftforge.common.util.LazyOptional;
|
||||
import net.minecraftforge.event.AttachCapabilitiesEvent;
|
||||
import net.minecraftforge.event.TickEvent;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.util.thread.EffectiveSide;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
|
||||
@Mod(CapabilitiesTest.MODID)
|
||||
public class CapabilitiesTest
|
||||
{
|
||||
public static final String MODID = "capabilities_test";
|
||||
|
||||
private static final boolean ENABLED = false;
|
||||
|
||||
public static Capability<CapClass> INSTANCE = CapabilityManager.get(new CapabilityToken<>(){});
|
||||
|
||||
private static ResourceLocation TEST_CAP_ID = new ResourceLocation("capabilities_test:test");
|
||||
|
||||
private static final ConcurrentLinkedQueue<String> messages = new ConcurrentLinkedQueue<>();
|
||||
|
||||
public CapabilitiesTest()
|
||||
{
|
||||
if (ENABLED)
|
||||
{
|
||||
new AttachTest<>(BlockEntity.class);
|
||||
new AttachTest<>(Entity.class);
|
||||
new AttachTest<>(ItemStack.class);
|
||||
new AttachTest<>(LevelChunk.class);
|
||||
new AttachTest<>(Level.class);
|
||||
}
|
||||
}
|
||||
|
||||
public static class CapClass
|
||||
{
|
||||
private final Object o;
|
||||
|
||||
public CapClass(Object o)
|
||||
{
|
||||
this.o = o;
|
||||
}
|
||||
}
|
||||
|
||||
public static class AttachTest<T extends ICapabilityProviderImpl<T>>
|
||||
{
|
||||
private final Class<T> cls;
|
||||
|
||||
public AttachTest(Class<T> cls)
|
||||
{
|
||||
this.cls = cls;
|
||||
|
||||
MinecraftForge.EVENT_BUS.addGenericListener(cls, this::attach);
|
||||
}
|
||||
|
||||
public void attach(AttachCapabilitiesEvent<T> event)
|
||||
{
|
||||
event.addCapability(TEST_CAP_ID, new ICapabilitySerializable<>()
|
||||
{
|
||||
final LazyOptional<CapClass> instance = LazyOptional.of(() -> new CapClass(this));
|
||||
|
||||
@Override
|
||||
public Tag serializeNBT()
|
||||
{
|
||||
return IntTag.valueOf(1);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deserializeNBT(Tag nbt)
|
||||
{
|
||||
if (nbt.getId() != Tag.TAG_INT)
|
||||
throw new IllegalStateException("Unexpected tag type");
|
||||
if (!(nbt instanceof IntTag it))
|
||||
throw new IllegalStateException("Unexpected tag class");
|
||||
if(it.getAsInt() != 1)
|
||||
throw new IllegalStateException("Unexpected tag type");
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public <T> LazyOptional<T> getCapability(@NotNull Capability<T> cap, @Nullable Direction side)
|
||||
{
|
||||
if (cap == INSTANCE)
|
||||
return instance.cast();
|
||||
return LazyOptional.empty();
|
||||
}
|
||||
});
|
||||
|
||||
messages.add(String.format(Locale.ENGLISH, "Attached capability to %s in %s", event.getObject().getClass(), EffectiveSide.get()));
|
||||
}
|
||||
}
|
||||
|
||||
@Mod.EventBusSubscriber(value= Dist.CLIENT, modid = CapabilitiesTest.MODID, bus= Mod.EventBusSubscriber.Bus.FORGE)
|
||||
public static class ClientEvents
|
||||
{
|
||||
@SubscribeEvent
|
||||
public static void clientTick(TickEvent.ClientTickEvent event)
|
||||
{
|
||||
if (event.phase == TickEvent.Phase.END && Minecraft.getInstance().level != null)
|
||||
{
|
||||
while(messages.size() > 0)
|
||||
{
|
||||
Minecraft.getInstance().getChatListener().handleSystemMessage(Component.literal(Objects.requireNonNull(messages.poll())), false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug;
|
||||
|
||||
import net.minecraft.world.level.material.Fluids;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.nbt.NbtOps;
|
||||
import net.minecraftforge.fluids.FluidStack;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
/**
|
||||
* Created to host any custom codecs forge may be adding.
|
||||
*/
|
||||
@Mod("forge_codecs_test")
|
||||
public class CodecsTest
|
||||
{
|
||||
public static final boolean ENABLE = true;
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
|
||||
public CodecsTest()
|
||||
{
|
||||
if (ENABLE)
|
||||
{
|
||||
testFluidStackCodec();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes sure FluidStack.CODEC produces the same data as FluidStack.write
|
||||
*/
|
||||
private void testFluidStackCodec()
|
||||
{
|
||||
FluidStack noTag = new FluidStack(Fluids.WATER, 10);
|
||||
FluidStack withTag = new FluidStack(Fluids.LAVA, 10);
|
||||
withTag.getOrCreateChildTag("test").putString("value", "This is a test");
|
||||
|
||||
CompoundTag noTag_write = noTag.writeToNBT(new CompoundTag());
|
||||
CompoundTag withTag_write = withTag.writeToNBT(new CompoundTag());
|
||||
|
||||
CompoundTag noTag_encode = (CompoundTag)FluidStack.CODEC.encodeStart(NbtOps.INSTANCE, noTag).getOrThrow(false, error -> {
|
||||
LOGGER.error("Error encoding noTag: {}", error);
|
||||
});
|
||||
CompoundTag withTag_encode = (CompoundTag)FluidStack.CODEC.encodeStart(NbtOps.INSTANCE, withTag).getOrThrow(false, error -> {
|
||||
LOGGER.error("Error encoding withTag: {}", error);
|
||||
});
|
||||
|
||||
if (!noTag_write.equals(noTag_encode))
|
||||
throw new IllegalStateException("Encoded noTag does not match");
|
||||
if (!withTag_write.equals(withTag_encode))
|
||||
throw new IllegalStateException("Encoded withTag does not match");
|
||||
|
||||
FluidStack noTag_decode = FluidStack.CODEC.decode(NbtOps.INSTANCE, noTag_encode).getOrThrow(false, error -> {
|
||||
LOGGER.error("Error decoding noTag: {}", error);
|
||||
}).getFirst();
|
||||
FluidStack withTag_decode = FluidStack.CODEC.decode(NbtOps.INSTANCE, withTag_encode).getOrThrow(false, error -> {
|
||||
LOGGER.error("Error decoding withTag: {}", error);
|
||||
}).getFirst();
|
||||
|
||||
if (!noTag.isFluidStackIdentical(noTag_decode))
|
||||
throw new IllegalStateException("Decoded noTag does not match");
|
||||
if (!withTag.isFluidStackIdentical(withTag_decode))
|
||||
throw new IllegalStateException("Decoded withTag does not match");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug;
|
||||
|
||||
import net.minecraftforge.fml.CrashReportCallables;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
|
||||
/**
|
||||
* Test features and guards of crash-callables.
|
||||
* <ul>
|
||||
* <li>The "AlwaysActiveCrashCallable" must always be printed to the crash report</li>
|
||||
* <li>The "ToggleableCrashCallable" must only be printed to the crash report when the {@code ENABLED} flag is {@code true}</li>
|
||||
* <li>The "BadContentCrashCallable" must always print "BadContentCrashCallable: ERR" to the crash report and
|
||||
* print an exception to the log (relies on a try-catch in vanilla code)</li>
|
||||
* <li>The "BadFlagCrashCallable" must never print to the crash report and must print an exception to the log</li>
|
||||
* </ul>
|
||||
* To initiate a debug crash to test this, hold F3 + C for 10 seconds.
|
||||
*/
|
||||
@Mod("crash_callable_test")
|
||||
public class CrashCallableTest
|
||||
{
|
||||
private static final boolean ENABLED = true;
|
||||
|
||||
public CrashCallableTest()
|
||||
{
|
||||
CrashReportCallables.registerCrashCallable("AlwaysActiveCrashCallable", () -> "test");
|
||||
CrashReportCallables.registerCrashCallable("ToggleableCrashCallable", () -> "active", () -> ENABLED);
|
||||
CrashReportCallables.registerCrashCallable("BadContentCrashCallable", () ->
|
||||
{
|
||||
throw new UnsupportedOperationException();
|
||||
});
|
||||
CrashReportCallables.registerCrashCallable("BadFlagCrashCallable", () -> "why am I here?!", () ->
|
||||
{
|
||||
throw new UnsupportedOperationException();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug;
|
||||
|
||||
import java.util.List;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.world.item.CreativeModeTab;
|
||||
import net.minecraft.world.item.CreativeModeTab.TabVisibility;
|
||||
import net.minecraft.world.item.CreativeModeTabs;
|
||||
import net.minecraft.world.item.DyeColor;
|
||||
import net.minecraft.world.item.DyeItem;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.level.ItemLike;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.Blocks;
|
||||
import net.minecraftforge.event.BuildCreativeModeTabContentsEvent;
|
||||
import net.minecraftforge.eventbus.api.IEventBus;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
import net.minecraftforge.registries.RegisterEvent;
|
||||
|
||||
@Mod(CreativeModeTabTest.MOD_ID)
|
||||
public class CreativeModeTabTest
|
||||
{
|
||||
public static final String MOD_ID = "creative_mode_tab_test";
|
||||
private static final boolean ENABLED = true;
|
||||
|
||||
private static final ResourceKey<CreativeModeTab> LOGS = ResourceKey.create(Registries.CREATIVE_MODE_TAB, new ResourceLocation(MOD_ID, "logs"));
|
||||
private static final ResourceKey<CreativeModeTab> STONE = ResourceKey.create(Registries.CREATIVE_MODE_TAB, new ResourceLocation(MOD_ID, "stone"));
|
||||
|
||||
public CreativeModeTabTest()
|
||||
{
|
||||
if (!ENABLED)
|
||||
return;
|
||||
|
||||
IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus();
|
||||
|
||||
modEventBus.addListener(CreativeModeTabTest::onCreativeModeTabRegister);
|
||||
modEventBus.addListener(CreativeModeTabTest::onCreativeModeTabBuildContents);
|
||||
}
|
||||
|
||||
private static void onCreativeModeTabRegister(RegisterEvent event)
|
||||
{
|
||||
event.register(Registries.CREATIVE_MODE_TAB, helper -> {
|
||||
helper.register(LOGS, CreativeModeTab.builder().icon(() -> new ItemStack(Blocks.ACACIA_LOG))
|
||||
.title(Component.literal("Logs"))
|
||||
.withLabelColor(0x00FF00)
|
||||
.displayItems((params, output) -> {
|
||||
output.accept(new ItemStack(Blocks.ACACIA_LOG));
|
||||
output.accept(new ItemStack(Blocks.BIRCH_LOG));
|
||||
output.accept(new ItemStack(Blocks.DARK_OAK_LOG));
|
||||
output.accept(new ItemStack(Blocks.JUNGLE_LOG));
|
||||
output.accept(new ItemStack(Blocks.OAK_LOG));
|
||||
output.accept(new ItemStack(Blocks.SPRUCE_LOG));
|
||||
})
|
||||
.build());
|
||||
helper.register(STONE, CreativeModeTab.builder().icon(() -> new ItemStack(Blocks.STONE))
|
||||
.title(Component.literal("Stone"))
|
||||
.withLabelColor(0x0000FF)
|
||||
.displayItems((params, output) -> {
|
||||
output.accept(new ItemStack(Blocks.STONE));
|
||||
output.accept(new ItemStack(Blocks.GRANITE));
|
||||
output.accept(new ItemStack(Blocks.DIORITE));
|
||||
output.accept(new ItemStack(Blocks.ANDESITE));
|
||||
})
|
||||
.withTabsAfter(CreativeModeTabs.BUILDING_BLOCKS)
|
||||
.build());
|
||||
|
||||
helper.register(new ResourceLocation(MOD_ID, "colors"), CreativeModeTab.builder().title(Component.literal("Colors"))
|
||||
.displayItems((params, output) ->
|
||||
{
|
||||
for (DyeColor color : DyeColor.values())
|
||||
{
|
||||
output.accept(DyeItem.byColor(color));
|
||||
}
|
||||
})
|
||||
.withTabFactory(CreativeModeColorTab::new)
|
||||
.withTabsBefore(CreativeModeTabs.COLORED_BLOCKS)
|
||||
.build()
|
||||
);
|
||||
|
||||
List<Block> blocks = List.of(Blocks.GRANITE, Blocks.DIORITE, Blocks.ANDESITE, Blocks.COBBLESTONE);
|
||||
for (int i = 0; i < blocks.size(); i++)
|
||||
{
|
||||
Block block = blocks.get(i);
|
||||
helper.register(new ResourceLocation(MOD_ID, "dummy" + i), CreativeModeTab.builder()
|
||||
.title(Component.literal("Dummy " + i))
|
||||
.icon(() -> new ItemStack(block))
|
||||
.displayItems((params, output) -> output.accept(block))
|
||||
.build()
|
||||
);
|
||||
}
|
||||
|
||||
//final ResourceLocation custom_tabs_image = new ResourceLocation(MOD_ID, "textures/gui/container/creative_inventory/custom_tabs.png");
|
||||
helper.register(new ResourceLocation(MOD_ID, "with_tabs_image"), CreativeModeTab.builder()
|
||||
.title(Component.translatable("itemGroup.with_tabs_image"))
|
||||
.icon(() -> new ItemStack(Blocks.BRICKS))
|
||||
.displayItems((params, output) -> output.accept(Blocks.BRICKS))
|
||||
//.withTabsImage(custom_tabs_image)
|
||||
.build());
|
||||
});
|
||||
}
|
||||
|
||||
private static ItemStack i(ItemLike item) { return new ItemStack(item); }
|
||||
|
||||
private static void onCreativeModeTabBuildContents(BuildCreativeModeTabContentsEvent event)
|
||||
{
|
||||
var entries = event.getEntries();
|
||||
var vis = TabVisibility.PARENT_AND_SEARCH_TABS;
|
||||
if (event.getTabKey() == LOGS)
|
||||
{
|
||||
entries.putAfter(i(Blocks.ACACIA_LOG), i(Blocks.STRIPPED_ACACIA_LOG), vis);
|
||||
entries.putAfter(i(Blocks.BIRCH_LOG), i(Blocks.STRIPPED_BIRCH_LOG), vis);
|
||||
entries.putAfter(i(Blocks.DARK_OAK_LOG), i(Blocks.STRIPPED_DARK_OAK_LOG), vis);
|
||||
entries.putAfter(i(Blocks.JUNGLE_LOG), i(Blocks.STRIPPED_JUNGLE_LOG), vis);
|
||||
entries.putAfter(i(Blocks.OAK_LOG), i(Blocks.STRIPPED_OAK_LOG), vis);
|
||||
entries.putAfter(i(Blocks.SPRUCE_LOG), i(Blocks.STRIPPED_SPRUCE_LOG), vis);
|
||||
}
|
||||
|
||||
if (event.getTabKey() == STONE)
|
||||
{
|
||||
entries.putBefore(i(Blocks.STONE), i(Blocks.SMOOTH_STONE), vis);
|
||||
entries.putBefore(i(Blocks.GRANITE), i(Blocks.POLISHED_GRANITE), vis);
|
||||
entries.putBefore(i(Blocks.DIORITE), i(Blocks.POLISHED_DIORITE), vis);
|
||||
entries.putBefore(i(Blocks.ANDESITE), i(Blocks.POLISHED_ANDESITE), vis);
|
||||
}
|
||||
}
|
||||
|
||||
private static class CreativeModeColorTab extends CreativeModeTab
|
||||
{
|
||||
private final ItemStack[] iconItems;
|
||||
|
||||
public CreativeModeColorTab(CreativeModeTab.Builder builder)
|
||||
{
|
||||
super(builder);
|
||||
|
||||
DyeColor[] colors = DyeColor.values();
|
||||
iconItems = new ItemStack[colors.length];
|
||||
for (int i = 0; i < colors.length; i++)
|
||||
{
|
||||
iconItems[i] = new ItemStack(DyeItem.byColor(colors[i]));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack getIconItem()
|
||||
{
|
||||
int idx = (int)(System.currentTimeMillis() / 1200) % iconItems.length;
|
||||
return iconItems[idx];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug;
|
||||
|
||||
import net.minecraft.world.level.GameRules;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
|
||||
/**
|
||||
* Simple test to ensure custom game rules can be registered correctly and used in game.
|
||||
* <p>
|
||||
* To test these game rules use the following commands.
|
||||
* <br>If the game rules are registered correctly, they should show up as auto-completion values and be able to be changed to valid values based on their types.
|
||||
* <br>These game rules should also show up and be editable under the {@code Edit Game Rules} screen, when creating a new world.
|
||||
* <br>{@code Create new world > More (tab) > Game Rules > Misc}
|
||||
* <ul>
|
||||
* <li><pre>{@code /gamerule custom_game_rule_test:custom_boolean_game_rule <true|false>}</pre></li>
|
||||
* Should be able to be set to either {@code true} or {@code false} (Defaulting to {@code true}).
|
||||
*
|
||||
* <li><pre>{@code /gamerule custom_game_rule_test:custom_integer_game_rule <some integer>}</pre></li>
|
||||
* Should be able to be set to any integer value (Defaulting to {@code 1337}).
|
||||
* </ul>
|
||||
*/
|
||||
@Mod(CustomGameRuleTest.TEST_ID)
|
||||
public class CustomGameRuleTest
|
||||
{
|
||||
public static final String TEST_ID = "custom_game_rule_test";
|
||||
public static final GameRules.Key<GameRules.BooleanValue> CUSTOM_BOOLEAN_GAME_RULE = GameRules.register("%s:custom_boolean_game_rule".formatted(TEST_ID), GameRules.Category.MISC, GameRules.BooleanValue.create(true));
|
||||
public static final GameRules.Key<GameRules.IntegerValue> CUSTOM_INTEGER_GAME_RULE = GameRules.register("%s:custom_integer_game_rule".formatted(TEST_ID), GameRules.Category.MISC, GameRules.IntegerValue.create(1337));
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug;
|
||||
|
||||
import net.minecraft.world.item.CreativeModeTabs;
|
||||
import net.minecraft.world.level.block.state.BlockBehaviour;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.SoundType;
|
||||
import net.minecraft.world.level.material.MapColor;
|
||||
import net.minecraft.world.item.BlockItem;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.sounds.SoundEvent;
|
||||
import net.minecraftforge.common.util.ForgeSoundType;
|
||||
import net.minecraftforge.event.BuildCreativeModeTabContentsEvent;
|
||||
import net.minecraftforge.eventbus.api.IEventBus;
|
||||
import net.minecraftforge.registries.RegistryObject;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
import net.minecraftforge.registries.DeferredRegister;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
|
||||
@Mod(CustomSoundTypeTest.MODID)
|
||||
public class CustomSoundTypeTest
|
||||
{
|
||||
static final String MODID = "custom_sound_type_test";
|
||||
|
||||
private static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, MODID);
|
||||
private static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, MODID);
|
||||
private static final DeferredRegister<SoundEvent> SOUND_EVENTS = DeferredRegister.create(ForgeRegistries.SOUND_EVENTS, MODID);
|
||||
|
||||
private static final RegistryObject<SoundEvent> TEST_STEP_EVENT = SOUND_EVENTS.register("test_step",
|
||||
() -> SoundEvent.createVariableRangeEvent(new ResourceLocation(MODID, "block.sound_type_test.step")));
|
||||
private static final SoundType TEST_SOUND_TYPE = new ForgeSoundType(1.0F, 1.0F, TEST_STEP_EVENT, TEST_STEP_EVENT, TEST_STEP_EVENT, TEST_STEP_EVENT, TEST_STEP_EVENT);
|
||||
|
||||
private static final RegistryObject<Block> TEST_STEP_BLOCK = BLOCKS.register("test_block",
|
||||
() -> new Block(BlockBehaviour.Properties.of().mapColor(MapColor.WOOD).sound(TEST_SOUND_TYPE)));
|
||||
|
||||
private static final RegistryObject<Item> TEST_STEP_BLOCK_ITEM = ITEMS.register("test_block",
|
||||
() -> new BlockItem(TEST_STEP_BLOCK.get(), new Item.Properties()));
|
||||
|
||||
public CustomSoundTypeTest()
|
||||
{
|
||||
final IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus();
|
||||
BLOCKS.register(modEventBus);
|
||||
ITEMS.register(modEventBus);
|
||||
SOUND_EVENTS.register(modEventBus);
|
||||
modEventBus.addListener(this::addCreative);
|
||||
}
|
||||
|
||||
private void addCreative(BuildCreativeModeTabContentsEvent event)
|
||||
{
|
||||
if (event.getTabKey() == CreativeModeTabs.INGREDIENTS)
|
||||
event.accept(TEST_STEP_BLOCK_ITEM);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,115 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug;
|
||||
|
||||
import java.util.Set;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.tags.TagKey;
|
||||
import net.minecraft.world.item.CreativeModeTabs;
|
||||
import net.minecraft.world.item.crafting.RecipeType;
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.event.BuildCreativeModeTabContentsEvent;
|
||||
import net.minecraftforge.event.server.ServerStartedEvent;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.levelgen.structure.templatesystem.PosRuleTestType;
|
||||
import net.minecraft.world.level.material.MapColor;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.data.DataGenerator;
|
||||
import net.minecraft.world.item.BlockItem;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraftforge.client.model.generators.BlockStateProvider;
|
||||
import net.minecraftforge.eventbus.api.IEventBus;
|
||||
import net.minecraftforge.registries.RegistryObject;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.data.event.GatherDataEvent;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
import net.minecraftforge.registries.DeferredRegister;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
import net.minecraftforge.registries.IForgeRegistry;
|
||||
import net.minecraftforge.registries.RegistryBuilder;
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
@Mod(DeferredRegistryTest.MODID)
|
||||
public class DeferredRegistryTest {
|
||||
static final String MODID = "deferred_registry_test";
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
|
||||
private static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, MODID);
|
||||
private static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, MODID);
|
||||
private static final DeferredRegister<Custom> CUSTOMS = DeferredRegister.create(new ResourceLocation(MODID, "test_registry"), MODID);
|
||||
private static final DeferredRegister<Object> DOESNT_EXIST_REG = DeferredRegister.createOptional(new ResourceLocation(MODID, "doesnt_exist"), MODID);
|
||||
private static final DeferredRegister<RecipeType<?>> RECIPE_TYPES = DeferredRegister.create(ForgeRegistries.RECIPE_TYPES, MODID);
|
||||
// Vanilla Registry - filled directly after all RegistryEvent.Register events are fired
|
||||
private static final DeferredRegister<PosRuleTestType<?>> POS_RULE_TEST_TYPES = DeferredRegister.create(Registries.POS_RULE_TEST, MODID);
|
||||
|
||||
private static final RegistryObject<Block> BLOCK = BLOCKS.register("test", () -> new Block(Block.Properties.of().mapColor(MapColor.STONE)));
|
||||
private static final RegistryObject<Item> ITEM = ITEMS .register("test", () -> new BlockItem(BLOCK.get(), new Item.Properties()));
|
||||
private static final RegistryObject<Custom> CUSTOM = CUSTOMS.register("test", () -> new Custom(){});
|
||||
// Should never be created as the registry doesn't exist - this should silently fail and remain empty
|
||||
private static final RegistryObject<Object> DOESNT_EXIST = DOESNT_EXIST_REG.register("test", Object::new);
|
||||
private static final RegistryObject<RecipeType<?>> RECIPE_TYPE = RECIPE_TYPES.register("test", () -> new RecipeType<>() {});
|
||||
private static final RegistryObject<PosRuleTestType<?>> POS_RULE_TEST_TYPE = POS_RULE_TEST_TYPES.register("test", () -> () -> null);
|
||||
|
||||
private static final TagKey<Custom> CUSTOM_TAG_KEY = CUSTOMS.createOptionalTagKey("test_tag", Set.of(CUSTOM));
|
||||
private static final Supplier<IForgeRegistry<Custom>> CUSTOM_REG = CUSTOMS.makeRegistry(() ->
|
||||
new RegistryBuilder<Custom>().disableSaving().setMaxID(Integer.MAX_VALUE - 1).hasTags()
|
||||
.onAdd((owner, stage, id, key, obj, old) -> LOGGER.info("Custom Added: " + id + " " + obj.foo()))
|
||||
);
|
||||
|
||||
public DeferredRegistryTest() {
|
||||
IEventBus modBus = FMLJavaModLoadingContext.get().getModEventBus();
|
||||
BLOCKS.register(modBus);
|
||||
ITEMS.register(modBus);
|
||||
CUSTOMS.register(modBus);
|
||||
RECIPE_TYPES.register(modBus);
|
||||
POS_RULE_TEST_TYPES.register(modBus);
|
||||
modBus.addListener(this::gatherData);
|
||||
|
||||
MinecraftForge.EVENT_BUS.addListener(this::serverStarted);
|
||||
modBus.addListener(this::addCreative);
|
||||
}
|
||||
|
||||
private void addCreative(BuildCreativeModeTabContentsEvent event)
|
||||
{
|
||||
if (event.getTabKey() == CreativeModeTabs.INGREDIENTS)
|
||||
event.accept(ITEM);
|
||||
}
|
||||
|
||||
public void serverStarted(ServerStartedEvent event)
|
||||
{
|
||||
// Validate all the RegistryObjects are filled / not filled
|
||||
BLOCK.get();
|
||||
ITEM.get();
|
||||
CUSTOM.get();
|
||||
if (DOESNT_EXIST.isPresent())
|
||||
throw new IllegalStateException("DeferredRegistryTest#DOESNT_EXIST should not be present!");
|
||||
RECIPE_TYPE.get();
|
||||
//POS_RULE_TEST_TYPE.get();
|
||||
//PLACED_FEATURE.get();
|
||||
}
|
||||
|
||||
public void gatherData(GatherDataEvent event) {
|
||||
DataGenerator gen = event.getGenerator();
|
||||
|
||||
gen.addProvider(event.includeClient(), new BlockStateProvider(gen.getPackOutput(), MODID, event.getExistingFileHelper()) {
|
||||
@Override
|
||||
protected void registerStatesAndModels() {
|
||||
simpleBlockWithItem(BLOCK.get(), models().cubeAll(BLOCK.getId().getPath(), mcLoc("block/furnace_top")));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static class Custom {
|
||||
public String foo() {
|
||||
return this.getClass().getName();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug;
|
||||
|
||||
import com.mojang.logging.LogUtils;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
/**
|
||||
* Tests that the {@link net.minecraftforge.fml.DeferredWorkQueue} properly executes enqueued tasks and
|
||||
* forwards any exceptions thrown by those tasks
|
||||
*/
|
||||
@Mod(DeferredWorkQueueTest.MOD_ID)
|
||||
@Mod.EventBusSubscriber(modid = DeferredWorkQueueTest.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD)
|
||||
public class DeferredWorkQueueTest
|
||||
{
|
||||
public static final String MOD_ID = "deferred_work_queue_test";
|
||||
private static final boolean ENABLE = false;
|
||||
private static final Logger LOGGER = LogUtils.getLogger();
|
||||
|
||||
public DeferredWorkQueueTest() { }
|
||||
|
||||
@SubscribeEvent
|
||||
public static void onCommonSetup(final FMLCommonSetupEvent event)
|
||||
{
|
||||
if (!ENABLE)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
event.enqueueWork(() -> LOGGER.info("Enqueued runnable ran"));
|
||||
event.enqueueWork(() -> "Enqueued supplier ran").thenAccept(LOGGER::info);
|
||||
|
||||
event.enqueueWork(DeferredWorkQueueTest::executeThrowingRunnable);
|
||||
event.enqueueWork(DeferredWorkQueueTest::executeThrowingSupplier).thenAccept(s ->
|
||||
LOGGER.error("This must not be printed")
|
||||
);
|
||||
}
|
||||
|
||||
private static void executeThrowingRunnable()
|
||||
{
|
||||
LOGGER.info("Enqueued throwing runnable ran");
|
||||
throw new IllegalStateException("Throwing runnable ran");
|
||||
}
|
||||
|
||||
private static String executeThrowingSupplier()
|
||||
{
|
||||
LOGGER.info("Enqueued throwing supplier ran");
|
||||
throw new IllegalStateException("Throwing supplier ran");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug;
|
||||
|
||||
import com.google.common.collect.Sets;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.tags.TagKey;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.Blocks;
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.event.server.ServerStartedEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
import java.util.Set;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* Tests that the values for defaulted optional tags defined in multiple places are combined.
|
||||
*
|
||||
* <p>The optional tag defined by this mod is deliberately not defined in a data pack, to cause it to 'default' and
|
||||
* trigger the behavior being tested.</p>
|
||||
*
|
||||
* @see <a href="https://github.com/MinecraftForge/MinecraftForge/issues/7570">MinecraftForge/MinecraftForge#7570</>
|
||||
*/
|
||||
@Mod(DuplicateOptionalTagTest.MODID)
|
||||
public class DuplicateOptionalTagTest
|
||||
{
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
|
||||
static final String MODID = "duplicate_optional_tag_test";
|
||||
private static final ResourceLocation TAG_NAME = new ResourceLocation(MODID, "test_optional_tag");
|
||||
|
||||
private static final Set<Supplier<Block>> TAG_A_DEFAULTS = Stream.of(Blocks.BEDROCK)
|
||||
.map(ForgeRegistries.BLOCKS::getDelegateOrThrow)
|
||||
.collect(Collectors.toUnmodifiableSet());
|
||||
private static final Set<Supplier<Block>> TAG_B_DEFAULTS = Stream.of(Blocks.WHITE_WOOL)
|
||||
.map(ForgeRegistries.BLOCKS::getDelegateOrThrow)
|
||||
.collect(Collectors.toUnmodifiableSet());
|
||||
|
||||
private static final TagKey<Block> TAG_A = ForgeRegistries.BLOCKS.tags().createOptionalTagKey(TAG_NAME, TAG_A_DEFAULTS);
|
||||
private static final TagKey<Block> TAG_B = ForgeRegistries.BLOCKS.tags().createOptionalTagKey(TAG_NAME, TAG_B_DEFAULTS);
|
||||
|
||||
public DuplicateOptionalTagTest()
|
||||
{
|
||||
MinecraftForge.EVENT_BUS.addListener(this::onServerStarted);
|
||||
}
|
||||
|
||||
private void onServerStarted(ServerStartedEvent event)
|
||||
{
|
||||
Set<Block> tagAValues = ForgeRegistries.BLOCKS.tags().getTag(TAG_A).stream().collect(Collectors.toUnmodifiableSet());
|
||||
Set<Block> tagBValues = ForgeRegistries.BLOCKS.tags().getTag(TAG_B).stream().collect(Collectors.toUnmodifiableSet());
|
||||
|
||||
if (!tagAValues.equals(tagBValues))
|
||||
{
|
||||
LOGGER.error("Values of both optional tag instances are not the same: first instance: {}, second instance: {}", tagAValues, tagBValues);
|
||||
return;
|
||||
}
|
||||
|
||||
final Set<Block> expected = Sets.union(TAG_A_DEFAULTS, TAG_B_DEFAULTS).stream()
|
||||
.map(Supplier::get)
|
||||
.collect(Collectors.toUnmodifiableSet());
|
||||
if (!tagAValues.equals(expected))
|
||||
{
|
||||
IllegalStateException e = new IllegalStateException("Optional tag values do not match!");
|
||||
LOGGER.error("Values of the optional tag do not match the expected union of their defaults: expected {}, got {}", expected, tagAValues, e);
|
||||
return;
|
||||
}
|
||||
|
||||
LOGGER.info("Optional tag instances match each other and the expected union of their defaults");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug;
|
||||
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.Items;
|
||||
import net.minecraft.world.level.material.Fluid;
|
||||
import net.minecraft.world.level.material.Fluids;
|
||||
import net.minecraftforge.fluids.FluidStack;
|
||||
import net.minecraftforge.fluids.FluidUtil;
|
||||
import net.minecraftforge.fluids.capability.templates.FluidTank;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
import net.minecraftforge.items.ItemStackHandler;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
|
||||
/**
|
||||
* Various tests for {@link FluidUtil}, that run when the mod is loaded.
|
||||
* If one of the tests fails, an expection will be thrown, and mod loading will fail with an error.
|
||||
* If all tests pass, the mod will load successfully.
|
||||
*/
|
||||
@Mod(FluidUtilTest.MODID)
|
||||
public class FluidUtilTest
|
||||
{
|
||||
public static final String MODID = "fluid_util_test";
|
||||
|
||||
public FluidUtilTest()
|
||||
{
|
||||
FMLJavaModLoadingContext.get().getModEventBus().addListener(FluidUtilTest::runTests);
|
||||
}
|
||||
|
||||
private static void runTests(FMLCommonSetupEvent commonSetupEvent)
|
||||
{
|
||||
test_tryEmptyContainer();
|
||||
test_tryFillContainer();
|
||||
test_tryEmptyContainerAndStow_stackable();
|
||||
|
||||
LogManager.getLogger().info("FluidUtilTest ok!");
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures that tryEmptyContainer doesn't change the target fluid handler when simulating.
|
||||
* Regression test for the root cause of <a href="https://github.com/MinecraftForge/MinecraftForge/issues/6796">issue #6796</a>.
|
||||
*/
|
||||
private static void test_tryEmptyContainer()
|
||||
{
|
||||
var sourceStack = new ItemStack(Items.WATER_BUCKET, 2);
|
||||
var targetTank = new FluidTank(10000);
|
||||
|
||||
// Simulate is not supposed to modify anything
|
||||
var simulateResult = FluidUtil.tryEmptyContainer(sourceStack, targetTank, 1000, null, false);
|
||||
if (!simulateResult.isSuccess())
|
||||
throw new AssertionError("Failed to transfer.");
|
||||
checkItemStack(simulateResult.getResult(), Items.BUCKET, 1);
|
||||
// Tank and stack shouldn't be modified
|
||||
checkItemStack(sourceStack, Items.WATER_BUCKET, 2);
|
||||
checkFluidStack(targetTank.getFluid(), Fluids.EMPTY, 0);
|
||||
|
||||
// Execute should modify
|
||||
var executeResult = FluidUtil.tryEmptyContainer(sourceStack, targetTank, 1000, null, true);
|
||||
if (!executeResult.isSuccess())
|
||||
throw new AssertionError("Failed to transfer.");
|
||||
checkItemStack(executeResult.getResult(), Items.BUCKET, 1);
|
||||
checkFluidStack(targetTank.getFluid(), Fluids.WATER, 1000);
|
||||
checkItemStack(sourceStack, Items.WATER_BUCKET, 2); // Apparently the stack is not supposed to be modified
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures that tryFillContainer doesn't change the target fluid handler when simulating.
|
||||
* Ant that the result of the simulated transfver is valid.
|
||||
* Regression test for the root cause of <a href="https://github.com/MinecraftForge/MinecraftForge/issues/6796">issue #6796</a>.
|
||||
*/
|
||||
private static void test_tryFillContainer()
|
||||
{
|
||||
var targetStack = new ItemStack(Items.BUCKET, 2);
|
||||
var sourceTank = new FluidTank(10000);
|
||||
sourceTank.setFluid(new FluidStack(Fluids.WATER, 5000));
|
||||
|
||||
// Simulate is not supposed to modify anything
|
||||
var simulateResult = FluidUtil.tryFillContainer(targetStack, sourceTank, 1000, null, false);
|
||||
if (!simulateResult.isSuccess())
|
||||
throw new AssertionError("Failed to transfer.");
|
||||
checkItemStack(simulateResult.getResult(), Items.WATER_BUCKET, 1);
|
||||
// Tank and stack shouldn't be modified
|
||||
checkItemStack(targetStack, Items.BUCKET, 2);
|
||||
checkFluidStack(sourceTank.getFluid(), Fluids.WATER, 5000);
|
||||
|
||||
// Execute should modify
|
||||
var executeResult = FluidUtil.tryFillContainer(targetStack, sourceTank, 1000, null, true);
|
||||
if (!executeResult.isSuccess())
|
||||
throw new AssertionError("Failed to transfer.");
|
||||
checkItemStack(executeResult.getResult(), Items.WATER_BUCKET, 1);
|
||||
checkFluidStack(sourceTank.getFluid(), Fluids.WATER, 4000);
|
||||
checkItemStack(targetStack, Items.BUCKET, 2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures that tryEmptyContainerAndStow doesn't duplicate fluids in the target when the container is stackable.
|
||||
* Regression test for <a href="https://github.com/MinecraftForge/MinecraftForge/issues/6796">issue #6796</a>.
|
||||
*/
|
||||
private static void test_tryEmptyContainerAndStow_stackable()
|
||||
{
|
||||
var sourceStack = new ItemStack(Items.WATER_BUCKET, 2);
|
||||
var targetTank = new FluidTank(10000);
|
||||
var overflowInventory = new ItemStackHandler(1);
|
||||
|
||||
// Simulate first: it's not supposed to modify anything!
|
||||
var simulateResult = FluidUtil.tryEmptyContainerAndStow(sourceStack, targetTank, overflowInventory, 1000, null, false);
|
||||
if (!simulateResult.isSuccess())
|
||||
throw new AssertionError("Failed to transfer.");
|
||||
checkItemStack(simulateResult.getResult(), Items.WATER_BUCKET, 1);
|
||||
// Tank and inv shouldn't be modified for simulate
|
||||
checkItemStack(sourceStack, Items.WATER_BUCKET, 2);
|
||||
checkFluidStack(targetTank.getFluid(), Fluids.EMPTY, 0);
|
||||
checkItemStack(overflowInventory.getStackInSlot(0), Items.AIR, 0);
|
||||
|
||||
// Now test with execute
|
||||
var executeResult = FluidUtil.tryEmptyContainerAndStow(sourceStack, targetTank, overflowInventory, 1000, null, true);
|
||||
if (!executeResult.isSuccess())
|
||||
throw new AssertionError("Failed to transfer.");
|
||||
checkItemStack(executeResult.getResult(), Items.WATER_BUCKET, 1);
|
||||
checkFluidStack(targetTank.getFluid(), Fluids.WATER, 1000);
|
||||
checkItemStack(overflowInventory.getStackInSlot(0), Items.BUCKET, 1);
|
||||
}
|
||||
|
||||
private static void checkItemStack(ItemStack stack, Item item, int count)
|
||||
{
|
||||
if (stack.getItem() != item)
|
||||
throw new AssertionError("Expected item " + ForgeRegistries.ITEMS.getKey(item) + ", got: " + ForgeRegistries.ITEMS.getKey(stack.getItem()));
|
||||
if (stack.getCount() != count)
|
||||
throw new AssertionError("Expected count " + count + ", got: " + stack.getCount());
|
||||
}
|
||||
|
||||
private static void checkFluidStack(FluidStack stack, Fluid fluid, int amount)
|
||||
{
|
||||
if (stack.getFluid() != fluid)
|
||||
throw new AssertionError("Expected fluid " + ForgeRegistries.FLUIDS.getKey(fluid) + ", got: " + ForgeRegistries.FLUIDS.getKey(stack.getFluid()));
|
||||
if (stack.getAmount() != amount)
|
||||
throw new AssertionError("Expected amount " + amount + ", got: " + stack.getAmount());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug;
|
||||
|
||||
import com.mojang.blaze3d.platform.InputConstants;
|
||||
import net.minecraft.client.KeyMapping;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.item.Items;
|
||||
import net.minecraftforge.api.distmarker.Dist;
|
||||
import net.minecraftforge.client.event.RegisterKeyMappingsEvent;
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.event.TickEvent;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.event.lifecycle.FMLConstructModEvent;
|
||||
|
||||
@Mod("keymapping_test")
|
||||
public class KeyMappingTest
|
||||
{
|
||||
@Mod.EventBusSubscriber(modid = "keymapping_test", value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD)
|
||||
public static class ClientStuff {
|
||||
// these are two separate keys to stand in for keys added by different
|
||||
// mods that each do something similar with a held item from the
|
||||
// respective mod, so the user wants them on the same physical key.
|
||||
static KeyMapping stickKey = new KeyMapping("stick_key", InputConstants.KEY_BACKSLASH, KeyMapping.CATEGORY_MISC);
|
||||
static KeyMapping rockKey = new KeyMapping("rock_key", InputConstants.KEY_BACKSLASH, KeyMapping.CATEGORY_MISC);
|
||||
@SubscribeEvent
|
||||
public static void init(FMLConstructModEvent event) {
|
||||
MinecraftForge.EVENT_BUS.addListener(ClientStuff::tick);
|
||||
}
|
||||
@SubscribeEvent
|
||||
public static void initKeys(RegisterKeyMappingsEvent event) {
|
||||
event.register(stickKey);
|
||||
event.register(rockKey);
|
||||
}
|
||||
public static void tick(TickEvent.ClientTickEvent event) {
|
||||
if(event.phase != TickEvent.Phase.START) return;
|
||||
if(stickKey.consumeClick()) {
|
||||
Player player = Minecraft.getInstance().player;
|
||||
if(player != null && player.getMainHandItem().is(Items.STICK))
|
||||
player.sendSystemMessage(Component.literal("stick found!"));
|
||||
}
|
||||
if(rockKey.consumeClick()) {
|
||||
Player player = Minecraft.getInstance().player;
|
||||
if(player != null && player.getMainHandItem().is(Items.COBBLESTONE))
|
||||
player.sendSystemMessage(Component.literal("rock found!"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug;
|
||||
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.world.effect.MobEffect;
|
||||
import net.minecraft.world.effect.MobEffectCategory;
|
||||
import net.minecraft.world.entity.LivingEntity;
|
||||
import net.minecraft.world.entity.animal.MushroomCow;
|
||||
import net.minecraft.world.item.CreativeModeTab;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.Items;
|
||||
import net.minecraft.world.item.SuspiciousStewItem;
|
||||
import net.minecraft.world.item.alchemy.PotionUtils;
|
||||
import net.minecraft.world.level.block.SuspiciousEffectHolder;
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
|
||||
import net.minecraftforge.eventbus.api.IEventBus;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
import net.minecraftforge.fml.util.ObfuscationReflectionHelper;
|
||||
import net.minecraftforge.registries.DeferredRegister;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
import net.minecraftforge.registries.RegisterEvent;
|
||||
import net.minecraftforge.registries.RegistryObject;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Registers 255 mob effects that log every tick on the client.
|
||||
* Used to test the patches for saving MobEffects to NBT.
|
||||
*
|
||||
* To verify correct function:
|
||||
* - Check that the Potion item and suspicious stew item provided via the creative tab function correctly
|
||||
* - Check that the effect given by the above items can persist on an entity as well as on ItemStacks in inventories
|
||||
* - Right click a Mushroom Cow using the above given Potion Item. Verify that it obtained the effect by right-clicking
|
||||
* it again using an empty hand before and after reloading the world.
|
||||
*/
|
||||
@Mod(ManyMobEffectsTest.MODID)
|
||||
public class ManyMobEffectsTest {
|
||||
static final String MODID = "many_mob_effects_test";
|
||||
|
||||
private static final boolean ENABLED = true;
|
||||
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
|
||||
private static final DeferredRegister<MobEffect> MOB_EFFECTS = DeferredRegister.create(ForgeRegistries.MOB_EFFECTS, MODID);
|
||||
private static final RegistryObject<MobEffect> LAST_EFFECT;
|
||||
|
||||
static {
|
||||
RegistryObject<MobEffect> effect = null;
|
||||
for (int i = 0; i < 255; i++) {
|
||||
final var index = i;
|
||||
effect = MOB_EFFECTS.register("effect_" + i, () -> new MobEffect(MobEffectCategory.NEUTRAL, 0xFF0000) {
|
||||
@SuppressWarnings("resource")
|
||||
@Override
|
||||
public void applyEffectTick(LivingEntity entity, int amplifier) {
|
||||
if (entity.level().isClientSide) {
|
||||
LOGGER.info("Effect Tick for {} on the client", index);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean shouldApplyEffectTickThisTick(int duration, int amplifier) {
|
||||
return true;
|
||||
}
|
||||
});
|
||||
}
|
||||
LAST_EFFECT = effect;
|
||||
}
|
||||
|
||||
public ManyMobEffectsTest() {
|
||||
if (!ENABLED) return;
|
||||
IEventBus modBus = FMLJavaModLoadingContext.get().getModEventBus();
|
||||
MOB_EFFECTS.register(modBus);
|
||||
MinecraftForge.EVENT_BUS.addListener(ManyMobEffectsTest::mobInteract);
|
||||
modBus.addListener((final RegisterEvent event) -> event.register(Registries.CREATIVE_MODE_TAB, helper ->
|
||||
helper.register(new ResourceLocation(MODID, "many_mob_effects_test"), CreativeModeTab.builder().withSearchBar()
|
||||
.icon(() -> new ItemStack(Items.POTION))
|
||||
.displayItems((params, output) -> {
|
||||
var effect = new SuspiciousEffectHolder.EffectEntry(LAST_EFFECT.get(), 1000);
|
||||
var stack = new ItemStack(Items.POTION);
|
||||
PotionUtils.setCustomEffects(stack, List.of(effect.createEffectInstance()));
|
||||
output.accept(stack);
|
||||
|
||||
stack = new ItemStack(Items.SUSPICIOUS_STEW);
|
||||
SuspiciousStewItem.saveMobEffects(stack, List.of(effect));
|
||||
output.accept(stack);
|
||||
})
|
||||
.build())));
|
||||
}
|
||||
|
||||
private static void mobInteract(PlayerInteractEvent.EntityInteract event) {
|
||||
if (!event.getTarget().level().isClientSide() && event.getTarget() instanceof MushroomCow cow) {
|
||||
var heldItem = event.getEntity().getItemInHand(event.getHand());
|
||||
if (heldItem.is(Items.POTION)) {
|
||||
var effects = PotionUtils.getMobEffects(heldItem);
|
||||
if (!effects.isEmpty()) {
|
||||
ObfuscationReflectionHelper.setPrivateValue(MushroomCow.class, cow, effects.get(0).getEffect(), "f_289" + "09_");
|
||||
ObfuscationReflectionHelper.setPrivateValue(MushroomCow.class, cow, effects.get(0).getDuration(), "f_289" + "10_");
|
||||
}
|
||||
} else if (heldItem.isEmpty()) {
|
||||
var effect = ((MobEffect) ObfuscationReflectionHelper.getPrivateValue(MushroomCow.class, cow, "f_289" + "09_"));
|
||||
if (effect != null) {
|
||||
event.getEntity().sendSystemMessage(Component.literal(String.valueOf(ForgeRegistries.MOB_EFFECTS.getKey(effect))));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug;
|
||||
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.Commands;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.util.StringRepresentable;
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.event.RegisterCommandsEvent;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.server.permission.PermissionAPI;
|
||||
import net.minecraftforge.server.permission.events.PermissionGatherEvent;
|
||||
import net.minecraftforge.server.permission.nodes.PermissionDynamicContext;
|
||||
import net.minecraftforge.server.permission.nodes.PermissionNode;
|
||||
import net.minecraftforge.server.permission.nodes.PermissionTypes;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
@Mod("permissiontest")
|
||||
public class PermissionTest
|
||||
{
|
||||
private static final boolean ENABLED = true;
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
|
||||
private static final PermissionNode<Boolean> boolPerm = new PermissionNode<>("permissiontest", "test.blob", PermissionTypes.BOOLEAN, (player, playerUUID, context) -> true);
|
||||
private static final PermissionNode<String> stringPerm = new PermissionNode<>("permissiontest", "test.blobText", PermissionTypes.STRING, (player, playerUUID, context) -> "Hello World");
|
||||
private static final PermissionNode<Integer> intPerm = new PermissionNode<>("permissiontest", "test.blob.integer", PermissionTypes.INTEGER, (player, playerUUID, context) -> 3);
|
||||
private static final PermissionNode<Component> componentPerm = new PermissionNode<>("permissiontest", "test.blob.component", PermissionTypes.COMPONENT, (player, playerUUID, context) -> Component.literal("This is a component"));
|
||||
|
||||
private static final PermissionNode<Boolean> unregisteredPerm = new PermissionNode<>("permissiontest", "test.unregistered", PermissionTypes.BOOLEAN, (player, playerUUID, context) -> false);
|
||||
|
||||
|
||||
public PermissionTest()
|
||||
{
|
||||
if (ENABLED)
|
||||
{
|
||||
MinecraftForge.EVENT_BUS.register(this);
|
||||
}
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public void registerNodes(PermissionGatherEvent.Nodes event)
|
||||
{
|
||||
event.addNodes(boolPerm, stringPerm, intPerm, componentPerm);
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public void registerCommands(RegisterCommandsEvent event)
|
||||
{
|
||||
event.getDispatcher().register(Commands.literal("permtest")
|
||||
.requires(src -> canUseCommand(src, boolPerm))
|
||||
.executes(context -> {
|
||||
context.getSource().sendSuccess(() -> Component.literal("Blob"), false);
|
||||
context.getSource().sendSuccess(() -> Component.literal("String:" + PermissionAPI.getPermission((ServerPlayer) context.getSource().getEntity(), stringPerm)), false);
|
||||
context.getSource().sendSuccess(() -> Component.literal("Int: " + PermissionAPI.getPermission((ServerPlayer) context.getSource().getEntity(), intPerm)), false);
|
||||
context.getSource().sendSuccess(() -> PermissionAPI.getPermission((ServerPlayer) context.getSource().getEntity(), componentPerm), false);
|
||||
|
||||
return 1;
|
||||
}));
|
||||
|
||||
//This command should not be usable as the command isn't registered.
|
||||
//It should also print an error
|
||||
event.getDispatcher().register(Commands.literal("permtesterr")
|
||||
.requires(src -> canUseCommand(src, unregisteredPerm))
|
||||
.executes(context -> {
|
||||
context.getSource().sendSuccess(() -> Component.literal("Blob"), false);
|
||||
return 1;
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Simple utility to catch exceptions with the test commands above.
|
||||
* Without that, the expected UnregisteredPermissionNode exception, triggers further exceptions and therefore isn't visible anymore.
|
||||
* This is only required to handle the intended error in the permission API, and should not be necessary with correct use.
|
||||
*/
|
||||
private static boolean canUseCommand(CommandSourceStack src, PermissionNode<Boolean> booleanPermission, PermissionDynamicContext<?>... context)
|
||||
{
|
||||
try
|
||||
{
|
||||
return src.getEntity() != null && src.getEntity() instanceof ServerPlayer && PermissionAPI.getPermission((ServerPlayer) src.getEntity(), booleanPermission, context);
|
||||
} catch (Exception e)
|
||||
{
|
||||
LOGGER.error(e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.Items;
|
||||
import net.minecraft.world.item.crafting.Ingredient;
|
||||
import net.minecraftforge.common.brewing.BrewingRecipeRegistry;
|
||||
import net.minecraftforge.event.entity.living.MobEffectEvent;
|
||||
import net.minecraftforge.eventbus.api.Event.Result;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
|
||||
@Mod("potion_event_test")
|
||||
@Mod.EventBusSubscriber
|
||||
public class PotionEventTest
|
||||
{
|
||||
private static Logger LOGGER = LogManager.getLogger(PotionEventTest.class);
|
||||
|
||||
public PotionEventTest()
|
||||
{
|
||||
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onSetup);
|
||||
}
|
||||
|
||||
private void onSetup(FMLCommonSetupEvent event)
|
||||
{
|
||||
BrewingRecipeRegistry.addRecipe(Ingredient.of(Items.ICE), Ingredient.of(Items.LAVA_BUCKET), new ItemStack(Items.OBSIDIAN));
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public static void onPotionAdded(MobEffectEvent.Added event)
|
||||
{
|
||||
if (!event.getEntity().getCommandSenderWorld().isClientSide)
|
||||
LOGGER.info("{} has a new PotionEffect {} from {}, the old one was {}", event.getEntity(), event.getEffectInstance(), event.getEffectSource(), event.getOldEffectInstance());
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public static void isPotionApplicable(MobEffectEvent.Applicable event)
|
||||
{
|
||||
if (!event.getEntity().getCommandSenderWorld().isClientSide)
|
||||
{
|
||||
event.setResult(Result.ALLOW);
|
||||
LOGGER.info("Allowed Potion {} for Entity {}", event.getEffectInstance(), event.getEntity());
|
||||
}
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public static void onPotionRemove(MobEffectEvent.Remove event)
|
||||
{
|
||||
if (!event.getEntity().getCommandSenderWorld().isClientSide)
|
||||
LOGGER.info("Effect {} got Removed from {}", event.getEffectInstance(), event.getEntity());
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public static void onPotionExpiry(MobEffectEvent.Expired event)
|
||||
{
|
||||
if (!event.getEntity().getCommandSenderWorld().isClientSide)
|
||||
LOGGER.info("Effect {} expired from {}", event.getEffectInstance(), event.getEntity());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug;
|
||||
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraftforge.eventbus.api.IEventBus;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
import net.minecraftforge.registries.RegistryObject;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
/**
|
||||
* Checks that {@link RegistryObject} works correctly, specifically that get() functions immediately
|
||||
* after construction, if registries are already populated.
|
||||
*/
|
||||
@Mod(RegistryObjectTest.MODID)
|
||||
public class RegistryObjectTest
|
||||
{
|
||||
|
||||
static final String MODID = "registry_object_test";
|
||||
|
||||
private static final boolean ENABLED = true;
|
||||
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
|
||||
public RegistryObjectTest()
|
||||
{
|
||||
if (!ENABLED) return;
|
||||
|
||||
IEventBus modBus = FMLJavaModLoadingContext.get().getModEventBus();
|
||||
modBus.addListener(this::commonSetup);
|
||||
}
|
||||
|
||||
public void commonSetup(FMLCommonSetupEvent event)
|
||||
{
|
||||
LOGGER.info("Stone 1: {}", RegistryObject.create(new ResourceLocation("minecraft", "stone"), ForgeRegistries.BLOCKS).get());
|
||||
LOGGER.info("Stone 2: {}", RegistryObject.create(new ResourceLocation("minecraft", "stone"), ForgeRegistries.Keys.BLOCKS, MODID).get());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug;
|
||||
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.data.DataGenerator;
|
||||
import net.minecraft.data.tags.ItemTagsProvider;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.tags.BlockTags;
|
||||
import net.minecraft.tags.ItemTags;
|
||||
import net.minecraft.tags.TagKey;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.item.Items;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.Blocks;
|
||||
import net.minecraftforge.common.data.BlockTagsProvider;
|
||||
import net.minecraftforge.common.data.ExistingFileHelper;
|
||||
import net.minecraftforge.eventbus.api.IEventBus;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
import net.minecraftforge.data.event.GatherDataEvent;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
|
||||
@Mod(RemoveTagDatagenTest.MODID)
|
||||
public class RemoveTagDatagenTest {
|
||||
|
||||
public static final String MODID = "remove_tag_datagen_test";
|
||||
public static final TagKey<Block> TEST_TAG = BlockTags.create(new ResourceLocation("test_tag"));
|
||||
|
||||
public RemoveTagDatagenTest() {
|
||||
IEventBus modBus = FMLJavaModLoadingContext.get().getModEventBus();
|
||||
modBus.addListener(this::onGatherData);
|
||||
}
|
||||
|
||||
private void onGatherData(GatherDataEvent event) {
|
||||
DataGenerator generator = event.getGenerator();
|
||||
ExistingFileHelper helper = event.getExistingFileHelper();
|
||||
|
||||
var blocks = new BlockTagsProvider(generator.getPackOutput(), event.getLookupProvider(), MODID, helper) {
|
||||
@SuppressWarnings("unchecked")
|
||||
@Override
|
||||
protected void addTags(HolderLookup.Provider provider) {
|
||||
this.tag(TEST_TAG)
|
||||
.remove(key(Blocks.DIRT))
|
||||
.remove(key(Blocks.OAK_DOOR), key(Blocks.DARK_OAK_DOOR))
|
||||
.remove(key(Blocks.ANVIL))
|
||||
.remove(key(Blocks.BASALT), key(Blocks.POLISHED_ANDESITE))
|
||||
.remove(BlockTags.BEEHIVES)
|
||||
.remove(BlockTags.BANNERS, BlockTags.BEDS);
|
||||
}
|
||||
};
|
||||
|
||||
generator.addProvider(event.includeServer(), blocks);
|
||||
|
||||
generator.addProvider(event.includeServer(), new ItemTagsProvider(generator.getPackOutput(), event.getLookupProvider(), blocks.contentsGetter(), MODID, helper) {
|
||||
@Override
|
||||
protected void addTags(HolderLookup.Provider provider) {
|
||||
// This is for testing if it is functional, remove spruce_planks from planks, which makes us unable to craft beds with them.
|
||||
this.tag(ItemTags.PLANKS).remove(key(Blocks.SPRUCE_PLANKS));
|
||||
// This is for testing deep values, removing a entry in a tag that is referenced by another tag
|
||||
// Remove MUSIC_DISC_CAT from the MUSIC_DISCS tag, which is added by MUSIC_DISCS reference to the CREEPER_DROP_MUSIC_DISCS tag
|
||||
// This will make MUSIC_DISK_CAT unable to be played in a jukebox.
|
||||
// It will still remove the record from the player because RecordItem just blindly deletes, but it won't play music.
|
||||
this.tag(ItemTags.MUSIC_DISCS).remove(key(Items.MUSIC_DISC_CAT));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static ResourceLocation key(Block value) {
|
||||
return ForgeRegistries.BLOCKS.getKey(value);
|
||||
}
|
||||
|
||||
private static ResourceLocation key(Item value) {
|
||||
return ForgeRegistries.ITEMS.getKey(value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug;
|
||||
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.gameevent.GameEvent;
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.event.VanillaGameEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
/**
|
||||
* Tests {@link VanillaGameEvent} by listening for and printing out any uses of shears in the overworld.
|
||||
*/
|
||||
@Mod(VanillaGameEventTest.MODID)
|
||||
public class VanillaGameEventTest
|
||||
{
|
||||
|
||||
static final String MODID = "vanilla_game_event_test";
|
||||
|
||||
private static final boolean ENABLED = true;
|
||||
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
|
||||
public VanillaGameEventTest()
|
||||
{
|
||||
if (!ENABLED) return;
|
||||
|
||||
MinecraftForge.EVENT_BUS.addListener(this::vanillaEvent);
|
||||
}
|
||||
|
||||
public void vanillaEvent(VanillaGameEvent event)
|
||||
{
|
||||
if (event.getVanillaEvent() == GameEvent.SHEAR && event.getLevel().dimension() == Level.OVERWORLD)
|
||||
{
|
||||
Entity cause = event.getCause();
|
||||
if (cause == null)
|
||||
{
|
||||
//One case this will be fired is when a dispenser shears an entity like a sheep
|
||||
LOGGER.info("Target at {} in the overworld was sheared.", event.getEventPosition());
|
||||
}
|
||||
else
|
||||
{
|
||||
//This will be fired if a player shears an entity like a sheep or carves a block like a pumpkin
|
||||
LOGGER.info("{} sheared a target at {} in the overworld.", cause, event.getEventPosition());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.block;
|
||||
|
||||
import net.minecraft.world.entity.item.FallingBlockEntity;
|
||||
import net.minecraftforge.event.level.BlockEvent;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
|
||||
@Mod("base_block_place_event_test")
|
||||
@Mod.EventBusSubscriber
|
||||
public class BasePlaceEventTest
|
||||
{
|
||||
@SubscribeEvent
|
||||
public static void onBlockPlaced(BlockEvent.EntityPlaceEvent event)
|
||||
{
|
||||
if (event.getEntity() instanceof FallingBlockEntity)
|
||||
event.setCanceled(true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.block;
|
||||
|
||||
import com.mojang.logging.LogUtils;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.world.InteractionHand;
|
||||
import net.minecraft.world.InteractionResult;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.item.*;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.block.*;
|
||||
import net.minecraft.world.level.block.entity.*;
|
||||
import net.minecraft.world.level.block.state.BlockBehaviour.Properties;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.material.MapColor;
|
||||
import net.minecraft.world.phys.BlockHitResult;
|
||||
import net.minecraftforge.event.BuildCreativeModeTabContentsEvent;
|
||||
import net.minecraftforge.eventbus.api.IEventBus;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
import net.minecraftforge.registries.RegistryObject;
|
||||
import net.minecraftforge.registries.DeferredRegister;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
@Mod("be_onload_test")
|
||||
public class BlockEntityOnLoadTest
|
||||
{
|
||||
private static final boolean ENABLED = true;
|
||||
private static final Logger LOGGER = LogUtils.getLogger();
|
||||
|
||||
private static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, "be_onload_test");
|
||||
private static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, "be_onload_test");
|
||||
private static final DeferredRegister<BlockEntityType<?>> BE_TYPES = DeferredRegister.create(ForgeRegistries.BLOCK_ENTITY_TYPES, "be_onload_test");
|
||||
|
||||
private static final RegistryObject<Block> TEST_BLOCK = BLOCKS.register("be_onload_testblock", () -> new TestBlock(Properties.of().mapColor(MapColor.SAND)));
|
||||
private static final RegistryObject<Item> TEST_BLOCK_ITEM = ITEMS.register("be_onload_testblock", () -> new BlockItem(TEST_BLOCK.get(), new Item.Properties()));
|
||||
private static final RegistryObject<BlockEntityType<TestBlockEntity>> TEST_BE_TYPE = BE_TYPES.register("be_onload_testbe", () -> BlockEntityType.Builder.of(TestBlockEntity::new, TEST_BLOCK.get()).build(null));
|
||||
|
||||
public BlockEntityOnLoadTest()
|
||||
{
|
||||
if (ENABLED)
|
||||
{
|
||||
IEventBus modBus = FMLJavaModLoadingContext.get().getModEventBus();
|
||||
BLOCKS.register(modBus);
|
||||
ITEMS.register(modBus);
|
||||
BE_TYPES.register(modBus);
|
||||
modBus.addListener(this::addCreative);
|
||||
}
|
||||
}
|
||||
|
||||
private void addCreative(BuildCreativeModeTabContentsEvent event)
|
||||
{
|
||||
if (event.getTabKey() == CreativeModeTabs.BUILDING_BLOCKS)
|
||||
event.accept(TEST_BLOCK_ITEM);
|
||||
}
|
||||
|
||||
private static class TestBlock extends Block implements EntityBlock
|
||||
{
|
||||
public TestBlock(Properties props) { super(props); }
|
||||
|
||||
@Override
|
||||
public InteractionResult use(BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit)
|
||||
{
|
||||
LOGGER.info("[BE_ONLOAD] Block#use at pos {} for {}", pos, level.getBlockEntity(pos));
|
||||
return super.use(state, level, pos, player, hand, hit);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public BlockEntity newBlockEntity(BlockPos pos, BlockState state)
|
||||
{
|
||||
return new TestBlockEntity(pos, state);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public <T extends BlockEntity> BlockEntityTicker<T> getTicker(Level level, BlockState state, BlockEntityType<T> type)
|
||||
{
|
||||
return (beLevel, bePos, beState, be) -> ((TestBlockEntity) be).tick();
|
||||
}
|
||||
}
|
||||
|
||||
private static class TestBlockEntity extends BlockEntity
|
||||
{
|
||||
private boolean loaded = false;
|
||||
|
||||
public TestBlockEntity(BlockPos pos, BlockState state)
|
||||
{
|
||||
super(TEST_BE_TYPE.get(), pos, state);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onLoad()
|
||||
{
|
||||
LOGGER.info("[BE_ONLOAD] BlockEntity#onLoad at pos {} for {}", worldPosition, this);
|
||||
getLevel().setBlockAndUpdate(worldPosition.above(), Blocks.SAND.defaultBlockState());
|
||||
loaded = true;
|
||||
}
|
||||
|
||||
private boolean first = true;
|
||||
public void tick()
|
||||
{
|
||||
if (first)
|
||||
{
|
||||
first = false;
|
||||
LOGGER.info("[BE_ONLOAD] TestBlockEntity#tick at pos {} for {}", worldPosition, this);
|
||||
if (!loaded)
|
||||
{
|
||||
throw new IllegalStateException(String.format(Locale.ENGLISH, "BlockEntity at %s ticked before onLoad()!", getBlockPos()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.block;
|
||||
|
||||
import net.minecraft.client.model.SkullModel;
|
||||
import net.minecraft.client.model.geom.ModelLayerLocation;
|
||||
import net.minecraft.client.renderer.blockentity.SkullBlockRenderer;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.Direction;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.world.item.*;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.SkullBlock;
|
||||
import net.minecraft.world.level.block.WallSkullBlock;
|
||||
import net.minecraft.world.level.block.entity.BlockEntity;
|
||||
import net.minecraft.world.level.block.entity.BlockEntityType;
|
||||
import net.minecraft.world.level.block.entity.SkullBlockEntity;
|
||||
import net.minecraft.world.level.block.state.BlockBehaviour;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraftforge.api.distmarker.Dist;
|
||||
import net.minecraftforge.client.event.EntityRenderersEvent;
|
||||
import net.minecraftforge.common.util.Lazy;
|
||||
import net.minecraftforge.event.BuildCreativeModeTabContentsEvent;
|
||||
import net.minecraftforge.eventbus.api.IEventBus;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus;
|
||||
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
import net.minecraftforge.registries.DeferredRegister;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
import net.minecraftforge.registries.RegistryObject;
|
||||
|
||||
/**
|
||||
* Adds a blaze head block and item to test the event for registering a custom skull model and to demonstrate the proper way to register a custom mob skull.
|
||||
*
|
||||
* To test it, locate "blaze_head", and test the item model, the model in the players head slot, the model in an armor stand, the wall block model, and the floor block model.
|
||||
* Should appear identical in shape to vanilla heads such as zombies or skeletons, but use the blaze skin.
|
||||
*/
|
||||
@Mod(CustomHeadTest.MODID)
|
||||
public class CustomHeadTest
|
||||
{
|
||||
static final String MODID = "custom_head_test";
|
||||
private static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, MODID);
|
||||
private static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, MODID);
|
||||
private static final DeferredRegister<BlockEntityType<?>> BLOCK_ENTITIES = DeferredRegister.create(ForgeRegistries.BLOCK_ENTITY_TYPES, MODID);
|
||||
private static final RegistryObject<Block> BLAZE_HEAD = BLOCKS.register("blaze_head", () -> new CustomSkullBlock(SkullType.BLAZE, BlockBehaviour.Properties.of().strength(1.0F)));
|
||||
private static final RegistryObject<Block> BLAZE_HEAD_WALL = BLOCKS.register("blaze_wall_head", () -> new CustomWallSkullBlock(SkullType.BLAZE, BlockBehaviour.Properties.of().strength(1.0F).lootFrom(BLAZE_HEAD)));
|
||||
private static final RegistryObject<Item> BLAZE_HEAD_ITEM = ITEMS.register("blaze_head", () -> new StandingAndWallBlockItem(BLAZE_HEAD.get(), BLAZE_HEAD_WALL.get(), new Item.Properties().rarity(Rarity.UNCOMMON), Direction.DOWN));
|
||||
private static final RegistryObject<BlockEntityType<CustomSkullBlockEntity>> CUSTOM_SKULL = BLOCK_ENTITIES.register("custom_skull", () -> BlockEntityType.Builder.of(CustomSkullBlockEntity::new, BLAZE_HEAD.get(), BLAZE_HEAD_WALL.get()).build(null));
|
||||
|
||||
public CustomHeadTest()
|
||||
{
|
||||
IEventBus modBus = FMLJavaModLoadingContext.get().getModEventBus();
|
||||
BLOCKS.register(modBus);
|
||||
ITEMS.register(modBus);
|
||||
BLOCK_ENTITIES.register(modBus);
|
||||
modBus.addListener(this::addCreative);
|
||||
}
|
||||
|
||||
private void addCreative(BuildCreativeModeTabContentsEvent event)
|
||||
{
|
||||
if (event.getTabKey() == CreativeModeTabs.BUILDING_BLOCKS)
|
||||
event.accept(BLAZE_HEAD_ITEM);
|
||||
}
|
||||
|
||||
private static class CustomSkullBlock extends SkullBlock
|
||||
{
|
||||
public CustomSkullBlock(Type type, Properties props)
|
||||
{
|
||||
super(type, props);
|
||||
}
|
||||
|
||||
@Override
|
||||
public BlockEntity newBlockEntity(BlockPos pos, BlockState state)
|
||||
{
|
||||
return new CustomSkullBlockEntity(pos, state);
|
||||
}
|
||||
}
|
||||
|
||||
private static class CustomWallSkullBlock extends WallSkullBlock
|
||||
{
|
||||
public CustomWallSkullBlock(SkullBlock.Type type, Properties props)
|
||||
{
|
||||
super(type, props);
|
||||
}
|
||||
|
||||
@Override
|
||||
public BlockEntity newBlockEntity(BlockPos pos, BlockState state)
|
||||
{
|
||||
return new CustomSkullBlockEntity(pos, state);
|
||||
}
|
||||
}
|
||||
|
||||
private static class CustomSkullBlockEntity extends SkullBlockEntity
|
||||
{
|
||||
public CustomSkullBlockEntity(BlockPos pos, BlockState state)
|
||||
{
|
||||
super(pos, state);
|
||||
}
|
||||
|
||||
@Override
|
||||
public BlockEntityType<?> getType()
|
||||
{
|
||||
return CUSTOM_SKULL.get();
|
||||
}
|
||||
}
|
||||
|
||||
private enum SkullType implements SkullBlock.Type
|
||||
{
|
||||
BLAZE
|
||||
}
|
||||
|
||||
@Mod.EventBusSubscriber(value= Dist.CLIENT, bus = Bus.MOD, modid = MODID)
|
||||
private static class ClientEvents
|
||||
{
|
||||
static final ModelLayerLocation BLAZE_HEAD_LAYER = new ModelLayerLocation(BLAZE_HEAD.getId(), "main");
|
||||
|
||||
@SubscribeEvent
|
||||
static void registerLayerDefinitions(EntityRenderersEvent.RegisterLayerDefinitions event)
|
||||
{
|
||||
event.registerLayerDefinition(BLAZE_HEAD_LAYER, Lazy.of(SkullModel::createMobHeadLayer));
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
static void registerLayerDefinitions(EntityRenderersEvent.RegisterRenderers event)
|
||||
{
|
||||
event.registerBlockEntityRenderer(CUSTOM_SKULL.get(), SkullBlockRenderer::new);
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
static void clientSetupEvent(FMLClientSetupEvent event)
|
||||
{
|
||||
event.enqueueWork(() -> SkullBlockRenderer.SKIN_BY_TYPE.put(SkullType.BLAZE, new ResourceLocation("textures/entity/blaze.png")));
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
static void registerSkullModel(EntityRenderersEvent.CreateSkullModels event)
|
||||
{
|
||||
event.registerSkullModel(SkullType.BLAZE, new SkullModel(event.getEntityModelSet().bakeLayer(ClientEvents.BLAZE_HEAD_LAYER)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.block;
|
||||
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.block.FlowerBlock;
|
||||
import net.minecraft.world.level.block.SoundType;
|
||||
import net.minecraft.world.level.material.MapColor;
|
||||
import net.minecraft.world.item.BlockItem;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.effect.MobEffects;
|
||||
import net.minecraft.core.Direction;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.world.level.BlockGetter;
|
||||
import net.minecraft.world.level.LevelReader;
|
||||
import net.minecraftforge.common.IPlantable;
|
||||
import net.minecraftforge.common.PlantType;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
import net.minecraftforge.registries.ObjectHolder;
|
||||
import net.minecraftforge.registries.RegisterEvent;
|
||||
|
||||
@Mod(CustomPlantTypeTest.MODID)
|
||||
@Mod.EventBusSubscriber(bus = Bus.MOD)
|
||||
public class CustomPlantTypeTest
|
||||
{
|
||||
static final String MODID = "custom_plant_type_test";
|
||||
private static final String CUSTOM_SOIL_BLOCK = "test_custom_block";
|
||||
private static final String CUSTOM_PLANT_BLOCK = "test_custom_plant";
|
||||
|
||||
@ObjectHolder(registryName = "block", value = CUSTOM_SOIL_BLOCK)
|
||||
public static Block CUSTOM_SOIL;
|
||||
@ObjectHolder(registryName = "block", value = CUSTOM_PLANT_BLOCK)
|
||||
public static Block CUSTOM_PLANT;
|
||||
|
||||
@SubscribeEvent
|
||||
public static void registerBlocks(RegisterEvent event)
|
||||
{
|
||||
event.register(ForgeRegistries.Keys.BLOCKS, helper ->
|
||||
{
|
||||
helper.register(CUSTOM_SOIL_BLOCK, new CustomBlock());
|
||||
helper.register(CUSTOM_PLANT_BLOCK, new CustomPlantBlock());
|
||||
});
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public static void registerItems(RegisterEvent event)
|
||||
{
|
||||
event.register(ForgeRegistries.Keys.ITEMS, helper ->
|
||||
{
|
||||
helper.register(CUSTOM_SOIL_BLOCK, new BlockItem(CUSTOM_SOIL, new Item.Properties()));
|
||||
helper.register(CUSTOM_PLANT_BLOCK, new BlockItem(CUSTOM_PLANT, new Item.Properties()));
|
||||
});
|
||||
}
|
||||
|
||||
public static class CustomBlock extends Block
|
||||
{
|
||||
public CustomBlock()
|
||||
{
|
||||
super(Properties.of().mapColor(MapColor.STONE));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canSustainPlant(BlockState state, BlockGetter level, BlockPos pos, Direction facing, IPlantable plantable)
|
||||
{
|
||||
PlantType type = plantable.getPlantType(level, pos.relative(facing));
|
||||
if (type != null && type == CustomPlantBlock.pt)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
return super.canSustainPlant(state, level, pos, facing, plantable);
|
||||
}
|
||||
}
|
||||
|
||||
public static class CustomPlantBlock extends FlowerBlock implements IPlantable
|
||||
{
|
||||
public static PlantType pt = PlantType.get("custom_plant_type");
|
||||
|
||||
public CustomPlantBlock()
|
||||
{
|
||||
super(MobEffects.WEAKNESS, 9, Properties.of().mapColor(MapColor.PLANT).noCollission().sound(SoundType.GRASS));
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlantType getPlantType(BlockGetter level, BlockPos pos)
|
||||
{
|
||||
return pt;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BlockState getPlant(BlockGetter level, BlockPos pos)
|
||||
{
|
||||
return defaultBlockState();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos)
|
||||
{
|
||||
BlockState soil = world.getBlockState(pos.below());
|
||||
return soil.canSustainPlant(world, pos, Direction.UP, this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean mayPlaceOn(BlockState state, BlockGetter worldIn, BlockPos pos)
|
||||
{
|
||||
Block block = state.getBlock();
|
||||
return block == CUSTOM_SOIL;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.block;
|
||||
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.world.InteractionHand;
|
||||
import net.minecraft.world.InteractionResult;
|
||||
import net.minecraft.world.entity.EntityType;
|
||||
import net.minecraft.world.entity.LivingEntity;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.item.BlockItem;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.LevelReader;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.RespawnAnchorBlock;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.material.MapColor;
|
||||
import net.minecraft.world.phys.BlockHitResult;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
import net.minecraftforge.eventbus.api.IEventBus;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
import net.minecraftforge.registries.RegistryObject;
|
||||
import net.minecraftforge.registries.DeferredRegister;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@Mod(CustomRespawnTest.MODID)
|
||||
public class CustomRespawnTest
|
||||
{
|
||||
public static final boolean ENABLE = true;
|
||||
public static final String MODID = "custom_respawn_test";
|
||||
|
||||
private static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, MODID);
|
||||
public static final RegistryObject<Block> TEST_RESPAWN_BLOCK = BLOCKS.register("test_respawn_block", () -> new CustomRespawnBlock(Block.Properties.of().mapColor(MapColor.WOOD)));
|
||||
|
||||
private static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, MODID);
|
||||
public static final RegistryObject<Item> TEST_RESPAWN_BLOCK_ITEM = ITEMS.register("test_respawn_block", () -> new BlockItem(TEST_RESPAWN_BLOCK.get(), (new Item.Properties())));
|
||||
|
||||
public CustomRespawnTest()
|
||||
{
|
||||
if (ENABLE)
|
||||
{
|
||||
final IEventBus eventBus = FMLJavaModLoadingContext.get().getModEventBus();
|
||||
BLOCKS.register(eventBus);
|
||||
ITEMS.register(eventBus);
|
||||
}
|
||||
}
|
||||
|
||||
public static class CustomRespawnBlock extends Block
|
||||
{
|
||||
|
||||
public CustomRespawnBlock(Properties propertiesIn)
|
||||
{
|
||||
super(propertiesIn);
|
||||
}
|
||||
|
||||
@Override
|
||||
public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult blockHitResult)
|
||||
{
|
||||
if (!world.isClientSide && player instanceof ServerPlayer serverPlayer)
|
||||
{
|
||||
serverPlayer.setRespawnPosition(world.dimension(), pos, 0, false, true);
|
||||
}
|
||||
return InteractionResult.sidedSuccess(world.isClientSide);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Vec3> getRespawnPosition(BlockState state, EntityType<?> type, LevelReader levelReader, BlockPos pos, float orientation, @Nullable LivingEntity entity)
|
||||
{
|
||||
return RespawnAnchorBlock.findStandUpPosition(type, levelReader, pos);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.block;
|
||||
|
||||
import net.minecraft.client.renderer.blockentity.BlockEntityRenderers;
|
||||
import net.minecraft.client.renderer.blockentity.HangingSignRenderer;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.world.item.CreativeModeTabs;
|
||||
import net.minecraft.world.item.HangingSignItem;
|
||||
import net.minecraft.world.level.block.CeilingHangingSignBlock;
|
||||
import net.minecraft.world.level.block.WallHangingSignBlock;
|
||||
import net.minecraft.world.level.block.entity.HangingSignBlockEntity;
|
||||
import net.minecraft.world.level.block.state.properties.BlockSetType;
|
||||
import net.minecraft.client.renderer.Sheets;
|
||||
import net.minecraft.client.renderer.blockentity.SignRenderer;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.item.SignItem;
|
||||
import net.minecraft.world.level.block.entity.SignBlockEntity;
|
||||
import net.minecraft.world.level.block.entity.BlockEntity;
|
||||
import net.minecraft.world.level.block.entity.BlockEntityType;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraftforge.event.BuildCreativeModeTabContentsEvent;
|
||||
import net.minecraftforge.eventbus.api.IEventBus;
|
||||
import net.minecraftforge.registries.RegistryObject;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
|
||||
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
import net.minecraftforge.registries.DeferredRegister;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.SoundType;
|
||||
import net.minecraft.world.level.block.StandingSignBlock;
|
||||
import net.minecraft.world.level.block.WallSignBlock;
|
||||
import net.minecraft.world.level.block.state.BlockBehaviour.Properties;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.block.state.properties.WoodType;
|
||||
|
||||
@Mod(CustomSignsTest.MODID)
|
||||
public class CustomSignsTest
|
||||
{
|
||||
public static final boolean ENABLE = false; // TODO fix
|
||||
public static final String MODID = "custom_signs_test";
|
||||
|
||||
public static final WoodType TEST_WOOD_TYPE = WoodType.register(new WoodType(new ResourceLocation(MODID, "test").toString(), BlockSetType.ACACIA));
|
||||
|
||||
private static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, MODID);
|
||||
public static final RegistryObject<CustomStandingSignBlock> TEST_STANDING_SIGN = BLOCKS.register("test_sign", () -> new CustomStandingSignBlock(Properties.of().noCollission().strength(1.0F).sound(SoundType.WOOD), CustomSignsTest.TEST_WOOD_TYPE));
|
||||
public static final RegistryObject<CustomWallSignBlock> TEST_WALL_SIGN = BLOCKS.register("test_wall_sign", () -> new CustomWallSignBlock(Properties.of().noCollission().strength(1.0F).sound(SoundType.WOOD), CustomSignsTest.TEST_WOOD_TYPE));
|
||||
public static final RegistryObject<CustomCeilingHangingSignBlock> TEST_CEILING_HANGING_SIGN = BLOCKS.register("test_hanging_sign", () -> new CustomCeilingHangingSignBlock(Properties.of().noCollission().strength(1.0F).sound(SoundType.WOOD), CustomSignsTest.TEST_WOOD_TYPE));
|
||||
public static final RegistryObject<CustomWallHangingSignBlock> TEST_WALL_HANGING_SIGN = BLOCKS.register("test_wall_hanging_sign", () -> new CustomWallHangingSignBlock(Properties.of().noCollission().strength(1.0F).sound(SoundType.WOOD), CustomSignsTest.TEST_WOOD_TYPE));
|
||||
|
||||
private static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, MODID);
|
||||
public static final RegistryObject<SignItem> TEST_SIGN = ITEMS.register("test_sign", () -> new SignItem((new Item.Properties()).stacksTo(16), TEST_STANDING_SIGN.get(), TEST_WALL_SIGN.get()));
|
||||
public static final RegistryObject<HangingSignItem> TEST_HANGING_SIGN = ITEMS.register("test_hanging_sign", () -> new HangingSignItem(TEST_CEILING_HANGING_SIGN.get(), TEST_WALL_HANGING_SIGN.get(), (new Item.Properties()).stacksTo(16)));
|
||||
|
||||
private static final DeferredRegister<BlockEntityType<?>> BLOCK_ENTITIES = DeferredRegister.create(ForgeRegistries.BLOCK_ENTITY_TYPES, MODID);
|
||||
public static final RegistryObject<BlockEntityType<CustomSignBlockEntity>> CUSTOM_SIGN = BLOCK_ENTITIES.register("custom_sign", () -> BlockEntityType.Builder.of(CustomSignBlockEntity::new, TEST_WALL_SIGN.get(), TEST_STANDING_SIGN.get()).build(null));
|
||||
public static final RegistryObject<BlockEntityType<CustomHangingSignBlockEntity>> CUSTOM_HANGING_SIGN = BLOCK_ENTITIES.register("custom_hanging_sign", () -> BlockEntityType.Builder.of(CustomHangingSignBlockEntity::new, TEST_WALL_HANGING_SIGN.get(), TEST_CEILING_HANGING_SIGN.get()).build(null));
|
||||
|
||||
public CustomSignsTest()
|
||||
{
|
||||
if (ENABLE)
|
||||
{
|
||||
final IEventBus eventBus = FMLJavaModLoadingContext.get().getModEventBus();
|
||||
BLOCKS.register(eventBus);
|
||||
ITEMS.register(eventBus);
|
||||
BLOCK_ENTITIES.register(eventBus);
|
||||
|
||||
eventBus.addListener(this::clientSetup);
|
||||
eventBus.addListener(this::commonSetup);
|
||||
eventBus.addListener(this::addCreative);
|
||||
}
|
||||
}
|
||||
|
||||
private void addCreative(BuildCreativeModeTabContentsEvent event)
|
||||
{
|
||||
if (event.getTabKey() == CreativeModeTabs.BUILDING_BLOCKS)
|
||||
{
|
||||
event.accept(TEST_SIGN);
|
||||
event.accept(TEST_HANGING_SIGN);
|
||||
}
|
||||
}
|
||||
|
||||
private void clientSetup(final FMLClientSetupEvent event)
|
||||
{
|
||||
BlockEntityRenderers.register(CUSTOM_SIGN.get(), SignRenderer::new);
|
||||
BlockEntityRenderers.register(CUSTOM_HANGING_SIGN.get(), HangingSignRenderer::new);
|
||||
event.enqueueWork(() -> {
|
||||
Sheets.addWoodType(TEST_WOOD_TYPE);
|
||||
});
|
||||
}
|
||||
|
||||
private void commonSetup(final FMLCommonSetupEvent event)
|
||||
{
|
||||
event.enqueueWork(() -> WoodType.register(TEST_WOOD_TYPE));
|
||||
}
|
||||
|
||||
public static class CustomStandingSignBlock extends StandingSignBlock
|
||||
{
|
||||
|
||||
public CustomStandingSignBlock(Properties propertiesIn, WoodType woodTypeIn)
|
||||
{
|
||||
super(propertiesIn, woodTypeIn);
|
||||
}
|
||||
|
||||
@Override
|
||||
public BlockEntity newBlockEntity(BlockPos pos, BlockState state)
|
||||
{
|
||||
return new CustomSignBlockEntity(pos, state);
|
||||
}
|
||||
}
|
||||
|
||||
public static class CustomWallSignBlock extends WallSignBlock
|
||||
{
|
||||
|
||||
public CustomWallSignBlock(Properties propertiesIn, WoodType woodTypeIn)
|
||||
{
|
||||
super(propertiesIn, woodTypeIn);
|
||||
}
|
||||
|
||||
@Override
|
||||
public BlockEntity newBlockEntity(BlockPos pos, BlockState state)
|
||||
{
|
||||
return new CustomSignBlockEntity(pos, state);
|
||||
}
|
||||
}
|
||||
|
||||
public static class CustomSignBlockEntity extends SignBlockEntity
|
||||
{
|
||||
public CustomSignBlockEntity(BlockPos pos, BlockState state)
|
||||
{
|
||||
super(pos, state);
|
||||
}
|
||||
|
||||
@Override
|
||||
public BlockEntityType<CustomSignBlockEntity> getType()
|
||||
{
|
||||
return CUSTOM_SIGN.get();
|
||||
}
|
||||
}
|
||||
|
||||
public static class CustomCeilingHangingSignBlock extends CeilingHangingSignBlock
|
||||
{
|
||||
|
||||
public CustomCeilingHangingSignBlock(Properties propertiesIn, WoodType woodTypeIn)
|
||||
{
|
||||
super(propertiesIn, woodTypeIn);
|
||||
}
|
||||
|
||||
@Override
|
||||
public BlockEntity newBlockEntity(BlockPos pos, BlockState state)
|
||||
{
|
||||
return new CustomHangingSignBlockEntity(pos, state);
|
||||
}
|
||||
}
|
||||
|
||||
public static class CustomWallHangingSignBlock extends WallHangingSignBlock
|
||||
{
|
||||
|
||||
public CustomWallHangingSignBlock(Properties propertiesIn, WoodType woodTypeIn)
|
||||
{
|
||||
super(propertiesIn, woodTypeIn);
|
||||
}
|
||||
|
||||
@Override
|
||||
public BlockEntity newBlockEntity(BlockPos pos, BlockState state)
|
||||
{
|
||||
return new CustomHangingSignBlockEntity(pos, state);
|
||||
}
|
||||
}
|
||||
|
||||
public static class CustomHangingSignBlockEntity extends HangingSignBlockEntity
|
||||
{
|
||||
|
||||
public CustomHangingSignBlockEntity(BlockPos pos, BlockState state)
|
||||
{
|
||||
super(pos, state);
|
||||
}
|
||||
|
||||
@Override
|
||||
public BlockEntityType<CustomHangingSignBlockEntity> getType()
|
||||
{
|
||||
return CUSTOM_HANGING_SIGN.get();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.block;
|
||||
|
||||
import net.minecraftforge.event.level.BlockEvent;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
|
||||
@Mod("farmland_trample_test")
|
||||
@Mod.EventBusSubscriber
|
||||
public class FarmlandTrampleEventTest
|
||||
{
|
||||
@SubscribeEvent
|
||||
public static void onFarmlandTrampled(BlockEvent.FarmlandTrampleEvent event)
|
||||
{
|
||||
if(event.getEntity().isCrouching())
|
||||
event.setCanceled(true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.block;
|
||||
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.Blocks;
|
||||
import net.minecraft.world.level.block.FlowerPotBlock;
|
||||
import net.minecraft.world.item.BlockItem;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraftforge.eventbus.api.IEventBus;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.registries.RegisterEvent;
|
||||
import net.minecraftforge.registries.RegistryObject;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
import net.minecraftforge.registries.DeferredRegister;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
|
||||
@Mod(FlowerPotTest.MODID)
|
||||
@Mod.EventBusSubscriber(modid = FlowerPotTest.MODID, bus = Bus.MOD)
|
||||
public class FlowerPotTest
|
||||
{
|
||||
static final String MODID = "flower_pot_test";
|
||||
static final String BLOCK_ID = "test_flower_pot";
|
||||
|
||||
private static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, MODID);
|
||||
private static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, MODID);
|
||||
|
||||
public static final RegistryObject<FlowerPotBlock> EMPTY_FLOWER_POT = BLOCKS.register(BLOCK_ID, () -> new FlowerPotBlock(null, ForgeRegistries.BLOCKS.getDelegateOrThrow(Blocks.AIR), Block.Properties.copy(Blocks.FLOWER_POT)));
|
||||
public static final RegistryObject<FlowerPotBlock> OAK_FLOWER_POT = BLOCKS.<FlowerPotBlock>register(
|
||||
BLOCK_ID + "_oak", () -> new FlowerPotBlock(EMPTY_FLOWER_POT, ForgeRegistries.BLOCKS.getDelegateOrThrow(Blocks.OAK_SAPLING), Block.Properties.copy(Blocks.FLOWER_POT)));
|
||||
|
||||
static
|
||||
{
|
||||
ITEMS.register(BLOCK_ID, () -> new BlockItem(EMPTY_FLOWER_POT.get(), new Item.Properties()));
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public static void onItemRegister(RegisterEvent event)
|
||||
{
|
||||
if (event.getRegistryKey().equals(ForgeRegistries.Keys.ITEMS))
|
||||
{
|
||||
EMPTY_FLOWER_POT.get().addPlant(ForgeRegistries.BLOCKS.getKey(Blocks.OAK_SAPLING), OAK_FLOWER_POT);
|
||||
}
|
||||
}
|
||||
|
||||
public FlowerPotTest()
|
||||
{
|
||||
IEventBus modBus = FMLJavaModLoadingContext.get().getModEventBus();
|
||||
BLOCKS.register(modBus);
|
||||
ITEMS.register(modBus);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,320 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.block;
|
||||
|
||||
import com.google.gson.JsonDeserializationContext;
|
||||
import com.google.gson.JsonObject;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.renderer.RenderType;
|
||||
import net.minecraft.client.renderer.block.model.*;
|
||||
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
|
||||
import net.minecraft.client.resources.model.*;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.Direction;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.network.Connection;
|
||||
import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.stats.Stats;
|
||||
import net.minecraft.util.RandomSource;
|
||||
import net.minecraft.world.InteractionHand;
|
||||
import net.minecraft.world.InteractionResult;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.item.*;
|
||||
import net.minecraft.world.level.BlockGetter;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.block.*;
|
||||
import net.minecraft.world.level.block.entity.BlockEntity;
|
||||
import net.minecraft.world.level.block.entity.BlockEntityType;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.gameevent.GameEvent;
|
||||
import net.minecraft.world.level.material.MapColor;
|
||||
import net.minecraft.world.phys.BlockHitResult;
|
||||
import net.minecraft.world.phys.shapes.CollisionContext;
|
||||
import net.minecraft.world.phys.shapes.VoxelShape;
|
||||
import net.minecraftforge.api.distmarker.Dist;
|
||||
import net.minecraftforge.client.ChunkRenderTypeSet;
|
||||
import net.minecraftforge.client.event.ModelEvent;
|
||||
import net.minecraftforge.client.model.*;
|
||||
import net.minecraftforge.client.model.data.*;
|
||||
import net.minecraftforge.client.model.geometry.IGeometryBakingContext;
|
||||
import net.minecraftforge.client.model.geometry.IGeometryLoader;
|
||||
import net.minecraftforge.client.model.geometry.IUnbakedGeometry;
|
||||
import net.minecraftforge.common.util.ConcatenatedListView;
|
||||
import net.minecraftforge.event.BuildCreativeModeTabContentsEvent;
|
||||
import net.minecraftforge.eventbus.api.IEventBus;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
import net.minecraftforge.registries.RegistryObject;
|
||||
import net.minecraftforge.registries.DeferredRegister;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Mod(FullPotsAccessorDemo.MOD_ID)
|
||||
public class FullPotsAccessorDemo
|
||||
{
|
||||
public static final String MOD_ID = "full_pots_accessor_demo";
|
||||
private static final boolean ENABLED = true;
|
||||
|
||||
private static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, MOD_ID);
|
||||
private static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, MOD_ID);
|
||||
private static final DeferredRegister<BlockEntityType<?>> BLOCK_ENTITIES = DeferredRegister.create(ForgeRegistries.BLOCK_ENTITY_TYPES, MOD_ID);
|
||||
|
||||
private static final RegistryObject<Block> DIORITE_POT = BLOCKS.register("diorite_pot", DioriteFlowerPotBlock::new);
|
||||
private static final RegistryObject<Item> DIORITE_POT_ITEM = ITEMS.register(
|
||||
"diorite_pot",
|
||||
() -> new BlockItem(DIORITE_POT.get(), new Item.Properties())
|
||||
);
|
||||
private static final RegistryObject<BlockEntityType<DioriteFlowerPotBlockEntity>> DIORITE_POT_BLOCK_ENTITY = BLOCK_ENTITIES.register(
|
||||
"diorite_pot",
|
||||
() -> BlockEntityType.Builder.of(DioriteFlowerPotBlockEntity::new, DIORITE_POT.get()).build(null)
|
||||
);
|
||||
|
||||
public FullPotsAccessorDemo()
|
||||
{
|
||||
if (ENABLED)
|
||||
{
|
||||
IEventBus bus = FMLJavaModLoadingContext.get().getModEventBus();
|
||||
BLOCKS.register(bus);
|
||||
ITEMS.register(bus);
|
||||
BLOCK_ENTITIES.register(bus);
|
||||
bus.addListener(this::addCreative);
|
||||
}
|
||||
}
|
||||
|
||||
private void addCreative(BuildCreativeModeTabContentsEvent event)
|
||||
{
|
||||
if (event.getTabKey() == CreativeModeTabs.INGREDIENTS)
|
||||
event.accept(DIORITE_POT_ITEM);
|
||||
}
|
||||
|
||||
private static class DioriteFlowerPotBlock extends Block implements EntityBlock
|
||||
{
|
||||
private static final VoxelShape SHAPE = Block.box(5.0D, 0.0D, 5.0D, 11.0D, 6.0D, 11.0D);
|
||||
|
||||
public DioriteFlowerPotBlock()
|
||||
{
|
||||
super(Properties.of().mapColor(MapColor.NONE).instabreak().noOcclusion());
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("deprecation")
|
||||
public InteractionResult use(BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit)
|
||||
{
|
||||
if (level.getBlockEntity(pos) instanceof DioriteFlowerPotBlockEntity be)
|
||||
{
|
||||
ItemStack stack = player.getItemInHand(hand);
|
||||
boolean isFlower = stack.getItem() instanceof BlockItem item && ((FlowerPotBlock) Blocks.FLOWER_POT).getFullPotsView().containsKey(ForgeRegistries.ITEMS.getKey(item));
|
||||
boolean hasFlower = be.plant != Blocks.AIR;
|
||||
|
||||
if (isFlower != hasFlower)
|
||||
{
|
||||
if (!level.isClientSide())
|
||||
{
|
||||
if (isFlower)
|
||||
{
|
||||
be.setPlant(((BlockItem) stack.getItem()).getBlock());
|
||||
|
||||
player.awardStat(Stats.POT_FLOWER);
|
||||
if (!player.getAbilities().instabuild)
|
||||
{
|
||||
stack.shrink(1);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
ItemStack flowerStack = new ItemStack(be.getPlant());
|
||||
if (stack.isEmpty())
|
||||
{
|
||||
player.setItemInHand(hand, flowerStack);
|
||||
}
|
||||
else if (!player.addItem(flowerStack))
|
||||
{
|
||||
player.drop(flowerStack, false);
|
||||
}
|
||||
|
||||
be.setPlant(Blocks.AIR);
|
||||
}
|
||||
}
|
||||
|
||||
level.gameEvent(player, GameEvent.BLOCK_CHANGE, pos);
|
||||
return InteractionResult.sidedSuccess(level.isClientSide());
|
||||
}
|
||||
else
|
||||
{
|
||||
return InteractionResult.CONSUME;
|
||||
}
|
||||
}
|
||||
return super.use(state, level, pos, player, hand, hit);
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("deprecation")
|
||||
public VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext context)
|
||||
{
|
||||
return SHAPE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BlockEntity newBlockEntity(BlockPos pos, BlockState state)
|
||||
{
|
||||
return new DioriteFlowerPotBlockEntity(pos, state);
|
||||
}
|
||||
}
|
||||
|
||||
private static class DioriteFlowerPotBlockEntity extends BlockEntity
|
||||
{
|
||||
public static final ModelProperty<Block> PLANT_PROPERTY = new ModelProperty<>();
|
||||
|
||||
private ModelData modelData;
|
||||
private Block plant = Blocks.AIR;
|
||||
|
||||
public DioriteFlowerPotBlockEntity(BlockPos pos, BlockState state)
|
||||
{
|
||||
super(DIORITE_POT_BLOCK_ENTITY.get(), pos, state);
|
||||
modelData = ModelData.builder().with(PLANT_PROPERTY, plant).build();
|
||||
}
|
||||
|
||||
public void setPlant(Block plant)
|
||||
{
|
||||
this.plant = plant;
|
||||
//noinspection ConstantConditions
|
||||
level.sendBlockUpdated(getBlockPos(), getBlockState(), getBlockState(), Block.UPDATE_ALL);
|
||||
setChanged();
|
||||
}
|
||||
|
||||
public Block getPlant() { return plant; }
|
||||
|
||||
@Override
|
||||
public ModelData getModelData() {return modelData; }
|
||||
|
||||
@Override
|
||||
public CompoundTag getUpdateTag()
|
||||
{
|
||||
return saveWithFullMetadata();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleUpdateTag(CompoundTag tag)
|
||||
{
|
||||
super.handleUpdateTag(tag);
|
||||
modelData = modelData.derive().with(PLANT_PROPERTY, plant).build();
|
||||
requestModelDataUpdate();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ClientboundBlockEntityDataPacket getUpdatePacket()
|
||||
{
|
||||
return ClientboundBlockEntityDataPacket.create(this, be -> be.getUpdateTag());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDataPacket(Connection net, ClientboundBlockEntityDataPacket pkt)
|
||||
{
|
||||
handleUpdateTag(pkt.getTag());
|
||||
//noinspection ConstantConditions
|
||||
level.sendBlockUpdated(getBlockPos(), getBlockState(), getBlockState(), Block.UPDATE_ALL);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void load(CompoundTag tag)
|
||||
{
|
||||
super.load(tag);
|
||||
plant = ForgeRegistries.BLOCKS.getValue(new ResourceLocation(tag.getString("plant")));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void saveAdditional(CompoundTag tag)
|
||||
{
|
||||
//noinspection ConstantConditions
|
||||
tag.putString("plant", ForgeRegistries.BLOCKS.getKey(plant).toString());
|
||||
super.saveAdditional(tag);
|
||||
}
|
||||
}
|
||||
|
||||
@Mod.EventBusSubscriber(modid = MOD_ID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD)
|
||||
private static class ClientHandler
|
||||
{
|
||||
@SubscribeEvent
|
||||
public static void registerLoader(final ModelEvent.RegisterGeometryLoaders event)
|
||||
{
|
||||
event.register("diorite_pot", new DioritePotGeometryLoader());
|
||||
}
|
||||
|
||||
private static class DioritePotGeometryLoader implements IGeometryLoader<DioritePotModelGeometry>
|
||||
{
|
||||
@Override
|
||||
public DioritePotModelGeometry read(JsonObject jsonObject, JsonDeserializationContext deserializationContext)
|
||||
{
|
||||
JsonObject wrappedModel = jsonObject.getAsJsonObject("model");
|
||||
return new DioritePotModelGeometry(deserializationContext.deserialize(wrappedModel, BlockModel.class));
|
||||
}
|
||||
}
|
||||
|
||||
private record DioritePotModelGeometry(UnbakedModel wrappedModel) implements IUnbakedGeometry<DioritePotModelGeometry>
|
||||
{
|
||||
@Override
|
||||
public BakedModel bake(IGeometryBakingContext context, ModelBaker baker, Function<net.minecraft.client.resources.model.Material, TextureAtlasSprite> spriteGetter, ModelState modelState, ItemOverrides overrides, ResourceLocation modelLocation) {
|
||||
return new DioritePotModel(wrappedModel.bake(baker, spriteGetter, modelState, modelLocation));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void resolveParents(Function<ResourceLocation, UnbakedModel> modelGetter, IGeometryBakingContext context)
|
||||
{
|
||||
wrappedModel.resolveParents(modelGetter);
|
||||
}
|
||||
}
|
||||
|
||||
private static class DioritePotModel extends BakedModelWrapper<BakedModel>
|
||||
{
|
||||
private static final ChunkRenderTypeSet CUTOUT = ChunkRenderTypeSet.of(RenderType.cutout());
|
||||
private static final ResourceLocation POT_TEXTURE = new ResourceLocation("minecraft:block/flower_pot");
|
||||
private static final ResourceLocation DIRT_TEXTURE = new ResourceLocation("minecraft:block/dirt");
|
||||
|
||||
public DioritePotModel(BakedModel wrappedModel) { super(wrappedModel); }
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public List<BakedQuad> getQuads(@Nullable BlockState state, @Nullable Direction side, @NotNull RandomSource rand, @NotNull ModelData extraData, @Nullable RenderType renderType)
|
||||
{
|
||||
List<List<BakedQuad>> quads = new ArrayList<>();
|
||||
quads.add(originalModel.getQuads(state, side, rand, extraData, renderType));
|
||||
|
||||
Block plant = extraData.get(DioriteFlowerPotBlockEntity.PLANT_PROPERTY);
|
||||
if (plant != null && plant != Blocks.AIR)
|
||||
{
|
||||
quads.add(getPlantQuads(plant, side, rand, renderType));
|
||||
}
|
||||
|
||||
return ConcatenatedListView.of(quads);
|
||||
}
|
||||
|
||||
private List<BakedQuad> getPlantQuads(Block plant, @Nullable Direction face, RandomSource rand, @Nullable RenderType renderType)
|
||||
{
|
||||
BlockState potState = ((FlowerPotBlock) Blocks.FLOWER_POT).getFullPotsView().getOrDefault(ForgeRegistries.BLOCKS.getKey(plant), ForgeRegistries.BLOCKS.getDelegateOrThrow(Blocks.AIR)).get().defaultBlockState();
|
||||
BakedModel potModel = Minecraft.getInstance().getBlockRenderer().getBlockModel(potState);
|
||||
|
||||
return potModel.getQuads(potState, face, rand, ModelData.EMPTY, renderType)
|
||||
.stream()
|
||||
.filter(q -> !q.getSprite().contents().name().equals(POT_TEXTURE))
|
||||
.filter(q -> !q.getSprite().contents().name().equals(DIRT_TEXTURE))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
public ChunkRenderTypeSet getRenderTypes(@NotNull BlockState state, @NotNull RandomSource rand, @NotNull ModelData data)
|
||||
{
|
||||
return CUTOUT;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.block;
|
||||
|
||||
import net.minecraft.client.renderer.ItemBlockRenderTypes;
|
||||
import net.minecraft.client.renderer.RenderType;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.Direction;
|
||||
import net.minecraft.world.item.BlockItem;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.level.BlockGetter;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.Blocks;
|
||||
import net.minecraft.world.level.block.SlabBlock;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.block.state.properties.SlabType;
|
||||
import net.minecraftforge.api.distmarker.Dist;
|
||||
import net.minecraftforge.eventbus.api.IEventBus;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
import net.minecraftforge.registries.DeferredRegister;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
import net.minecraftforge.registries.RegistryObject;
|
||||
|
||||
@Mod(HideNeighborFaceTest.MOD_ID)
|
||||
public class HideNeighborFaceTest
|
||||
{
|
||||
public static final String MOD_ID = "hide_neighbor_face_test";
|
||||
|
||||
private static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, MOD_ID);
|
||||
private static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, MOD_ID);
|
||||
|
||||
private static final RegistryObject<Block> GLASS_SLAB = BLOCKS.register("glass_slab", GlassSlab::new);
|
||||
private static final RegistryObject<Item> GLASS_SLAB_ITEM = ITEMS.register("glass_slab", () -> new BlockItem(GLASS_SLAB.get(), new Item.Properties()));
|
||||
|
||||
public HideNeighborFaceTest()
|
||||
{
|
||||
IEventBus bus = FMLJavaModLoadingContext.get().getModEventBus();
|
||||
|
||||
BLOCKS.register(bus);
|
||||
ITEMS.register(bus);
|
||||
}
|
||||
|
||||
private static class GlassSlab extends SlabBlock
|
||||
{
|
||||
public GlassSlab() { super(Properties.copy(Blocks.GLASS)); }
|
||||
|
||||
@Override
|
||||
public boolean skipRendering(BlockState state, BlockState neighborState, Direction face)
|
||||
{
|
||||
SlabType type = state.getValue(TYPE);
|
||||
|
||||
if (neighborState.is(Blocks.GLASS))
|
||||
{
|
||||
return (type == SlabType.BOTTOM && face == Direction.DOWN) ||
|
||||
(type == SlabType.TOP && face == Direction.UP) ||
|
||||
type == SlabType.DOUBLE;
|
||||
}
|
||||
else if (neighborState.is(this))
|
||||
{
|
||||
SlabType neighborType = neighborState.getValue(TYPE);
|
||||
return (type != SlabType.BOTTOM && neighborType != SlabType.TOP && face == Direction.UP) ||
|
||||
(type != SlabType.TOP && neighborType != SlabType.BOTTOM && face == Direction.DOWN) ||
|
||||
(type == neighborType && face.getAxis() != Direction.Axis.Y);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hidesNeighborFace(BlockGetter level, BlockPos pos, BlockState state, BlockState neighborState, Direction dir)
|
||||
{
|
||||
SlabType type = state.getValue(TYPE);
|
||||
|
||||
if (neighborState.is(Blocks.GLASS))
|
||||
{
|
||||
return (type == SlabType.BOTTOM && dir == Direction.DOWN) ||
|
||||
(type == SlabType.TOP && dir == Direction.UP) ||
|
||||
type == SlabType.DOUBLE;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Mod.EventBusSubscriber(value = Dist.CLIENT, modid = MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD)
|
||||
public static class ClientEvents
|
||||
{
|
||||
@SubscribeEvent
|
||||
public static void onClientSetup(final FMLClientSetupEvent event)
|
||||
{
|
||||
ItemBlockRenderTypes.setRenderLayer(GLASS_SLAB.get(), RenderType.cutout());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.block;
|
||||
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.network.Connection;
|
||||
import net.minecraft.network.protocol.Packet;
|
||||
import net.minecraft.network.protocol.game.ClientGamePacketListener;
|
||||
import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket;
|
||||
import net.minecraft.world.InteractionHand;
|
||||
import net.minecraft.world.InteractionResult;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.item.BlockItem;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.level.BlockGetter;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.EntityBlock;
|
||||
import net.minecraft.world.level.block.entity.BlockEntity;
|
||||
import net.minecraft.world.level.block.entity.BlockEntityType;
|
||||
import net.minecraft.world.level.block.state.BlockBehaviour;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.phys.BlockHitResult;
|
||||
import net.minecraftforge.eventbus.api.IEventBus;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
import net.minecraftforge.registries.DeferredRegister;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
import net.minecraftforge.registries.RegistryObject;
|
||||
|
||||
/**
|
||||
* Adds a light source block that can be switched on and off by right-clicking and saves its state in a BlockEntity
|
||||
* to test whether level/pos-sensitive light sources work correctly
|
||||
*/
|
||||
@Mod(LevelSensitiveLightBlockTest.MOD_ID)
|
||||
public class LevelSensitiveLightBlockTest
|
||||
{
|
||||
static final String MOD_ID = "level_sensitive_light_block_test";
|
||||
private static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, MOD_ID);
|
||||
private static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, MOD_ID);
|
||||
private static final DeferredRegister<BlockEntityType<?>> BLOCK_ENTITIES = DeferredRegister.create(ForgeRegistries.BLOCK_ENTITY_TYPES, MOD_ID);
|
||||
|
||||
private static final RegistryObject<Block> LIGHT_BLOCK = BLOCKS.register("light_block", LightBlock::new);
|
||||
private static final RegistryObject<Item> LIGHT_BLOCK_ITEM = ITEMS.register(
|
||||
"light_block", () -> new BlockItem(LIGHT_BLOCK.get(), new Item.Properties())
|
||||
);
|
||||
private static final RegistryObject<BlockEntityType<LightBlockEntity>> LIGHT_BLOCK_ENTITY = BLOCK_ENTITIES.register(
|
||||
"light_block", () -> BlockEntityType.Builder.of(LightBlockEntity::new, LIGHT_BLOCK.get()).build(null)
|
||||
);
|
||||
|
||||
public LevelSensitiveLightBlockTest()
|
||||
{
|
||||
IEventBus bus = FMLJavaModLoadingContext.get().getModEventBus();
|
||||
BLOCKS.register(bus);
|
||||
ITEMS.register(bus);
|
||||
BLOCK_ENTITIES.register(bus);
|
||||
}
|
||||
|
||||
private static class LightBlock extends Block implements EntityBlock
|
||||
{
|
||||
public LightBlock()
|
||||
{
|
||||
super(BlockBehaviour.Properties.of());
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("deprecation")
|
||||
public InteractionResult use(BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit)
|
||||
{
|
||||
if (!level.isClientSide() && level.getBlockEntity(pos) instanceof LightBlockEntity be)
|
||||
{
|
||||
be.switchLight();
|
||||
}
|
||||
return InteractionResult.SUCCESS;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getLightEmission(BlockState state, BlockGetter level, BlockPos pos)
|
||||
{
|
||||
if (pos == BlockPos.ZERO || (level.getExistingBlockEntity(pos) instanceof LightBlockEntity be && be.lit))
|
||||
{
|
||||
return 15;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BlockEntity newBlockEntity(BlockPos pos, BlockState state)
|
||||
{
|
||||
return new LightBlockEntity(pos, state);
|
||||
}
|
||||
}
|
||||
|
||||
private static class LightBlockEntity extends BlockEntity
|
||||
{
|
||||
private boolean lit = false;
|
||||
|
||||
public LightBlockEntity(BlockPos pos, BlockState state)
|
||||
{
|
||||
super(LIGHT_BLOCK_ENTITY.get(), pos, state);
|
||||
}
|
||||
|
||||
public void switchLight()
|
||||
{
|
||||
setLit(!lit);
|
||||
level.sendBlockUpdated(worldPosition, getBlockState(), getBlockState(), Block.UPDATE_ALL);
|
||||
setChanged();
|
||||
}
|
||||
|
||||
private void setLit(boolean lit)
|
||||
{
|
||||
if (lit != this.lit)
|
||||
{
|
||||
this.lit = lit;
|
||||
level.getLightEngine().checkBlock(worldPosition);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Packet<ClientGamePacketListener> getUpdatePacket()
|
||||
{
|
||||
return ClientboundBlockEntityDataPacket.create(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDataPacket(Connection net, ClientboundBlockEntityDataPacket pkt)
|
||||
{
|
||||
CompoundTag tag = pkt.getTag();
|
||||
if (tag != null)
|
||||
{
|
||||
setLit(tag.getBoolean("lit"));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompoundTag getUpdateTag()
|
||||
{
|
||||
CompoundTag tag = super.getUpdateTag();
|
||||
tag.putBoolean("lit", lit);
|
||||
return tag;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleUpdateTag(CompoundTag tag)
|
||||
{
|
||||
super.handleUpdateTag(tag);
|
||||
lit = tag.getBoolean("lit");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void load(CompoundTag tag)
|
||||
{
|
||||
super.load(tag);
|
||||
lit = tag.getBoolean("lit");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void saveAdditional(CompoundTag tag)
|
||||
{
|
||||
super.saveAdditional(tag);
|
||||
tag.putBoolean("lit", lit);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.block;
|
||||
|
||||
import net.minecraft.world.level.block.Blocks;
|
||||
import net.minecraftforge.event.level.BlockEvent.NeighborNotifyEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
//Disables update notification from comparators.
|
||||
|
||||
@Mod("neighbor_notify_event_test")
|
||||
@Mod.EventBusSubscriber
|
||||
public class NeighborNotifyEventTest
|
||||
{
|
||||
private static Logger logger = LogManager.getLogger(NeighborNotifyEventTest.class);
|
||||
|
||||
@SubscribeEvent
|
||||
public static void onNeighborNotify(NeighborNotifyEvent event)
|
||||
{
|
||||
if (event.getState().getBlock() == Blocks.COMPARATOR) {
|
||||
logger.info("{} with face information: {}", event.getPos().toString(), event.getNotifiedSides());
|
||||
event.setCanceled(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.block;
|
||||
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.Direction;
|
||||
import net.minecraft.util.RandomSource;
|
||||
import net.minecraft.world.item.BlockItem;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.level.BlockGetter;
|
||||
import net.minecraft.world.level.LevelReader;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.SaplingBlock;
|
||||
import net.minecraft.world.level.block.state.BlockBehaviour;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.levelgen.feature.configurations.TreeConfiguration;
|
||||
import net.minecraft.world.level.material.MapColor;
|
||||
import net.minecraftforge.common.IPlantable;
|
||||
import net.minecraftforge.common.extensions.IForgeBlockState;
|
||||
import net.minecraftforge.eventbus.api.IEventBus;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
import net.minecraftforge.registries.DeferredRegister;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
import net.minecraftforge.registries.RegistryObject;
|
||||
|
||||
import java.util.function.BiConsumer;
|
||||
|
||||
/**
|
||||
* A test case used to ensure that {@link IForgeBlockState#onTreeGrow(LevelReader, BiConsumer, RandomSource, BlockPos, TreeConfiguration)}
|
||||
* works properly, using a custom grass block that should revert to its custom dirt form after a tree grows on
|
||||
* top of it instead of turning to dirt.
|
||||
*/
|
||||
@Mod(OnTreeGrowBlockTest.ID)
|
||||
public class OnTreeGrowBlockTest
|
||||
{
|
||||
public static final boolean ENABLED = true;
|
||||
|
||||
static final String ID = "on_tree_grow_block_test";
|
||||
|
||||
public static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.Keys.BLOCKS, ID);
|
||||
public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.Keys.ITEMS, ID);
|
||||
|
||||
public static final RegistryObject<Block> TEST_GRASS_BLOCK = BLOCKS.register("test_grass_block", () -> new Block(BlockBehaviour.Properties.of().mapColor(MapColor.COLOR_LIGHT_BLUE).destroyTime(1.5f))
|
||||
{
|
||||
@Override
|
||||
public boolean canSustainPlant(BlockState state, BlockGetter world, BlockPos pos, Direction facing, IPlantable plantable)
|
||||
{
|
||||
return plantable instanceof SaplingBlock;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onTreeGrow(BlockState state, LevelReader level, BiConsumer<BlockPos, BlockState> placeFunction, RandomSource randomSource, BlockPos pos, TreeConfiguration config)
|
||||
{
|
||||
// Respect vanilla behavior for trees that want custom dirt blocks
|
||||
if (config.forceDirt)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
placeFunction.accept(pos, TEST_DIRT.get().defaultBlockState());
|
||||
return true;
|
||||
}
|
||||
}
|
||||
});
|
||||
public static final RegistryObject<Block> TEST_DIRT = BLOCKS.register("test_dirt", () -> new Block(BlockBehaviour.Properties.of().mapColor(MapColor.COLOR_LIGHT_BLUE).destroyTime(1.5f))
|
||||
{
|
||||
@Override
|
||||
public boolean canSustainPlant(BlockState state, BlockGetter world, BlockPos pos, Direction facing, IPlantable plantable)
|
||||
{
|
||||
return plantable instanceof SaplingBlock;
|
||||
}
|
||||
});
|
||||
public static final RegistryObject<Item> TEST_GRASS_BLOCK_ITEM = ITEMS.register("test_grass_block", () -> new BlockItem(TEST_GRASS_BLOCK.get(), new Item.Properties()));
|
||||
public static final RegistryObject<Item> TEST_DIRT_ITEM = ITEMS.register("test_dirt", () -> new BlockItem(TEST_DIRT.get(), new Item.Properties()));
|
||||
|
||||
public OnTreeGrowBlockTest()
|
||||
{
|
||||
if (ENABLED)
|
||||
{
|
||||
IEventBus modBus = FMLJavaModLoadingContext.get().getModEventBus();
|
||||
BLOCKS.register(modBus);
|
||||
ITEMS.register(modBus);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.block;
|
||||
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.Direction;
|
||||
import net.minecraft.data.DataGenerator;
|
||||
import net.minecraft.data.PackOutput;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.world.item.BlockItem;
|
||||
import net.minecraft.world.item.CreativeModeTabs;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.LevelAccessor;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.Blocks;
|
||||
import net.minecraft.world.level.block.piston.PistonBaseBlock;
|
||||
import net.minecraft.world.level.block.piston.PistonStructureResolver;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.material.MapColor;
|
||||
import net.minecraftforge.client.model.generators.BlockStateProvider;
|
||||
import net.minecraftforge.common.data.ExistingFileHelper;
|
||||
import net.minecraftforge.data.event.GatherDataEvent;
|
||||
import net.minecraftforge.event.BuildCreativeModeTabContentsEvent;
|
||||
import net.minecraftforge.event.level.PistonEvent;
|
||||
import net.minecraftforge.event.level.PistonEvent.PistonMoveType;
|
||||
import net.minecraftforge.eventbus.api.IEventBus;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
import net.minecraftforge.registries.DeferredRegister;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
import net.minecraftforge.registries.RegistryObject;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* This test mod blocks pistons from moving cobblestone at all except indirectly
|
||||
* This test mod adds a block that moves upwards when pushed by a piston
|
||||
* This test mod informs the user what will happen the piston and affected blocks when changes are made
|
||||
* This test mod makes black wool pushed by a piston drop after being pushed.
|
||||
*/
|
||||
@Mod.EventBusSubscriber(modid = PistonEventTest.MODID)
|
||||
@Mod(value = PistonEventTest.MODID)
|
||||
public class PistonEventTest
|
||||
{
|
||||
static final boolean ENABLE_PISTON_EVENT_LOGGING = false;
|
||||
|
||||
public static final String MODID = "piston_event_test";
|
||||
public static String blockName = "shiftonmove";
|
||||
private static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, MODID);
|
||||
private static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, MODID);
|
||||
|
||||
private static final RegistryObject<Block> SHIFT_ON_MOVE = BLOCKS.register(blockName, () -> new Block(Block.Properties.of().mapColor(MapColor.STONE)));
|
||||
private static final RegistryObject<Item> SHIFT_ON_MOVE_ITEM = ITEMS.register(blockName, () -> new BlockItem(SHIFT_ON_MOVE.get(), new Item.Properties()));
|
||||
|
||||
public PistonEventTest()
|
||||
{
|
||||
IEventBus modBus = FMLJavaModLoadingContext.get().getModEventBus();
|
||||
BLOCKS.register(modBus);
|
||||
ITEMS.register(modBus);
|
||||
modBus.addListener(this::gatherData);
|
||||
modBus.addListener(this::addCreative);
|
||||
}
|
||||
|
||||
private void addCreative(BuildCreativeModeTabContentsEvent event)
|
||||
{
|
||||
if (event.getTabKey() == CreativeModeTabs.BUILDING_BLOCKS)
|
||||
event.accept(SHIFT_ON_MOVE_ITEM);
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public static void pistonPre(PistonEvent.Pre event)
|
||||
{
|
||||
if (event.getPistonMoveType() == PistonMoveType.EXTEND)
|
||||
{
|
||||
Level world = (Level) event.getLevel();
|
||||
PistonStructureResolver pistonHelper = Objects.requireNonNull(event.getStructureHelper());
|
||||
|
||||
if (pistonHelper.resolve())
|
||||
{
|
||||
sendMessage(world, String.format(Locale.ENGLISH, "Piston will extend moving %d blocks and destroy %d blocks", pistonHelper.getToPush().size(), pistonHelper.getToDestroy().size()));
|
||||
List<BlockPos> posList = pistonHelper.getToPush();
|
||||
for (BlockPos newPos : posList)
|
||||
{
|
||||
BlockState state = event.getLevel().getBlockState(newPos);
|
||||
if (state.getBlock() == Blocks.BLACK_WOOL)
|
||||
{
|
||||
Block.dropResources(state, world, newPos);
|
||||
world.setBlockAndUpdate(newPos, Blocks.AIR.defaultBlockState());
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
sendMessage(world, "Piston won't extend");
|
||||
}
|
||||
|
||||
// Make the block move up and out of the way so long as it won't replace the piston
|
||||
BlockPos pushedBlockPos = event.getFaceOffsetPos();
|
||||
if (world.getBlockState(pushedBlockPos).getBlock() == SHIFT_ON_MOVE.get() && event.getDirection() != Direction.DOWN)
|
||||
{
|
||||
world.setBlockAndUpdate(pushedBlockPos, Blocks.AIR.defaultBlockState());
|
||||
world.setBlockAndUpdate(pushedBlockPos.above(), SHIFT_ON_MOVE.get().defaultBlockState());
|
||||
}
|
||||
|
||||
// Block pushing cobblestone (directly, indirectly works)
|
||||
event.setCanceled(event.getLevel().getBlockState(event.getFaceOffsetPos()).getBlock() == Blocks.COBBLESTONE);
|
||||
}
|
||||
else
|
||||
{
|
||||
boolean isSticky = event.getLevel().getBlockState(event.getPos()).getBlock() == Blocks.STICKY_PISTON;
|
||||
|
||||
if (isSticky)
|
||||
{
|
||||
BlockPos targetPos = event.getFaceOffsetPos().relative(event.getDirection());
|
||||
boolean canPush = PistonBaseBlock.isPushable(event.getLevel().getBlockState(targetPos), (Level) event.getLevel(), event.getFaceOffsetPos(), event.getDirection().getOpposite(), false, event.getDirection());
|
||||
boolean isAir = event.getLevel().isEmptyBlock(targetPos);
|
||||
sendMessage(event.getLevel(), String.format(Locale.ENGLISH, "Piston will retract moving %d blocks", !isAir && canPush ? 1 : 0));
|
||||
}
|
||||
else
|
||||
{
|
||||
sendMessage(event.getLevel(), "Piston will retract");
|
||||
}
|
||||
|
||||
// Offset twice to see if retraction will pull cobblestone
|
||||
event.setCanceled(event.getLevel().getBlockState(event.getFaceOffsetPos().relative(event.getDirection())).getBlock() == Blocks.COBBLESTONE && isSticky);
|
||||
}
|
||||
}
|
||||
|
||||
private static void sendMessage(LevelAccessor levelAccessor, String message)
|
||||
{
|
||||
if (!ENABLE_PISTON_EVENT_LOGGING) return;
|
||||
|
||||
if (!levelAccessor.isClientSide() && levelAccessor instanceof ServerLevel level)
|
||||
{
|
||||
level.getServer().sendSystemMessage(Component.literal(message));
|
||||
}
|
||||
}
|
||||
|
||||
public void gatherData(GatherDataEvent event)
|
||||
{
|
||||
DataGenerator gen = event.getGenerator();
|
||||
|
||||
gen.addProvider(event.includeClient(), new BlockStates(gen.getPackOutput(), event.getExistingFileHelper()));
|
||||
}
|
||||
|
||||
private static class BlockStates extends BlockStateProvider
|
||||
{
|
||||
public BlockStates(PackOutput output, ExistingFileHelper exFileHelper)
|
||||
{
|
||||
super(output, MODID, exFileHelper);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void registerStatesAndModels()
|
||||
{
|
||||
simpleBlockWithItem(SHIFT_ON_MOVE.get(), models().cubeAll(Objects.requireNonNull(SHIFT_ON_MOVE.getId()).getPath(), mcLoc("block/furnace_top")));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.block;
|
||||
|
||||
import net.minecraft.world.level.block.Blocks;
|
||||
import net.minecraftforge.event.level.BlockEvent.EntityPlaceEvent;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
|
||||
@Mod("block_place_event_test")
|
||||
@Mod.EventBusSubscriber
|
||||
public class PlaceEventTest
|
||||
{
|
||||
@SubscribeEvent
|
||||
public static void onBlockPlaced(EntityPlaceEvent event)
|
||||
{
|
||||
if (event.getPlacedBlock().getBlock() == Blocks.CHEST && event.getPlacedAgainst().getBlock() != Blocks.DIAMOND_BLOCK)
|
||||
event.setCanceled(true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.block;
|
||||
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.Direction;
|
||||
import net.minecraft.world.item.BlockItem;
|
||||
import net.minecraft.world.item.CreativeModeTabs;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.level.BlockGetter;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.entity.FurnaceBlockEntity;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraftforge.event.BuildCreativeModeTabContentsEvent;
|
||||
import net.minecraftforge.eventbus.api.IEventBus;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
import net.minecraftforge.registries.DeferredRegister;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
import net.minecraftforge.registries.RegistryObject;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
@Mod(RedstoneSidedConnectivityTest.MODID)
|
||||
public class RedstoneSidedConnectivityTest
|
||||
{
|
||||
public static final boolean ENABLE = true;
|
||||
static final String MODID = "redstone_sided_connectivity_test";
|
||||
static final String BLOCK_ID = "test_east_redstone_connect";
|
||||
|
||||
private static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, MODID);
|
||||
private static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, MODID);
|
||||
|
||||
private static final RegistryObject<Block> TEST_REDSTONE_BLOCK = BLOCKS.register(BLOCK_ID, EastRedstoneBlock::new);
|
||||
private static final RegistryObject<Item> TEST_REDSTONE_BLOCKITEM = ITEMS.register(BLOCK_ID, () -> new BlockItem(TEST_REDSTONE_BLOCK.get(), new Item.Properties()));
|
||||
|
||||
public RedstoneSidedConnectivityTest()
|
||||
{
|
||||
if (!ENABLE)
|
||||
return;
|
||||
|
||||
IEventBus modBus = FMLJavaModLoadingContext.get().getModEventBus();
|
||||
BLOCKS.register(modBus);
|
||||
ITEMS.register(modBus);
|
||||
modBus.addListener(this::addCreative);
|
||||
}
|
||||
|
||||
private void addCreative(BuildCreativeModeTabContentsEvent event)
|
||||
{
|
||||
if (event.getTabKey() == CreativeModeTabs.BUILDING_BLOCKS)
|
||||
event.accept(TEST_REDSTONE_BLOCKITEM);
|
||||
}
|
||||
|
||||
private static class EastRedstoneBlock extends Block
|
||||
{
|
||||
//This block visually connect to redstone dust only on the east side
|
||||
//if a furnace block is placed on top of it
|
||||
|
||||
public EastRedstoneBlock()
|
||||
{
|
||||
super(Properties.of());
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canConnectRedstone(BlockState state, BlockGetter level, BlockPos pos, @Nullable Direction direction)
|
||||
{
|
||||
//The passed direction is relative to the redstone dust
|
||||
//This block connects on the east side relative to this block, which is west for the dust
|
||||
return direction == Direction.WEST &&
|
||||
level.getBlockEntity(pos.relative(Direction.UP)) instanceof FurnaceBlockEntity;
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
@Override
|
||||
public void neighborChanged(BlockState state, Level world, BlockPos pos, Block block, BlockPos fromPos, boolean isMoving)
|
||||
{
|
||||
if (pos.relative(Direction.UP).equals(fromPos))
|
||||
{
|
||||
//Notify neighbors if the redstone connection may change
|
||||
state.updateNeighbourShapes(world, pos, UPDATE_ALL);
|
||||
}
|
||||
|
||||
super.neighborChanged(state, world, pos, block, fromPos, isMoving);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.block;
|
||||
|
||||
import net.minecraft.tags.TagKey;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.block.ScaffoldingBlock;
|
||||
import net.minecraft.world.level.block.SoundType;
|
||||
import net.minecraft.world.level.material.MapColor;
|
||||
import net.minecraft.data.DataGenerator;
|
||||
import net.minecraft.data.PackOutput;
|
||||
import net.minecraft.world.entity.LivingEntity;
|
||||
import net.minecraft.tags.BlockTags;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.world.level.LevelReader;
|
||||
import net.minecraftforge.client.model.generators.BlockStateProvider;
|
||||
import net.minecraftforge.client.model.generators.ConfiguredModel;
|
||||
import net.minecraftforge.client.model.generators.ModelFile;
|
||||
import net.minecraftforge.common.data.ExistingFileHelper;
|
||||
import net.minecraftforge.eventbus.api.IEventBus;
|
||||
import net.minecraftforge.registries.RegistryObject;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.data.event.GatherDataEvent;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
import net.minecraftforge.registries.DeferredRegister;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
|
||||
import net.minecraft.world.level.block.state.BlockBehaviour.Properties;
|
||||
|
||||
/**
|
||||
* This test mod allows a custom scaffolding to move down
|
||||
* while sneaking through a method.
|
||||
*/
|
||||
@Mod(ScaffoldingTest.MODID)
|
||||
public class ScaffoldingTest
|
||||
{
|
||||
static final String MODID = "scaffolding_test";
|
||||
static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, MODID);
|
||||
static final TagKey<Block> SCAFFOLDING = BlockTags.create(new ResourceLocation("forge", "scaffolding"));
|
||||
|
||||
static final RegistryObject<Block> SCAFFOLDING_METHOD_TEST = BLOCKS.register("scaffolding_method_test", () -> new ScaffoldingMethodTestBlock(Properties.of().mapColor(MapColor.SAND).noCollission().sound(SoundType.SCAFFOLDING).dynamicShape()));
|
||||
|
||||
public ScaffoldingTest()
|
||||
{
|
||||
IEventBus modBus = FMLJavaModLoadingContext.get().getModEventBus();
|
||||
BLOCKS.register(modBus);
|
||||
modBus.addListener(this::gatherData);
|
||||
}
|
||||
|
||||
private void gatherData(final GatherDataEvent event)
|
||||
{
|
||||
DataGenerator gen = event.getGenerator();
|
||||
gen.addProvider(event.includeClient(), new ScaffoldingBlockState(gen.getPackOutput(), MODID, event.getExistingFileHelper()));
|
||||
}
|
||||
|
||||
static class ScaffoldingBlockState extends BlockStateProvider
|
||||
{
|
||||
public ScaffoldingBlockState(PackOutput output, String modid, ExistingFileHelper exFileHelper)
|
||||
{
|
||||
super(output, modid, exFileHelper);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void registerStatesAndModels()
|
||||
{
|
||||
this.getVariantBuilder(SCAFFOLDING_METHOD_TEST.get()).forAllStatesExcept((state) -> ConfiguredModel.builder().modelFile(state.getValue(ScaffoldingBlock.BOTTOM) ? new ModelFile.ExistingModelFile(new ResourceLocation("block/scaffolding_unstable"), this.models().existingFileHelper) : new ModelFile.ExistingModelFile(new ResourceLocation("block/scaffolding_stable"), this.models().existingFileHelper)).build(), ScaffoldingBlock.DISTANCE, ScaffoldingBlock.WATERLOGGED);
|
||||
}
|
||||
}
|
||||
|
||||
static class ScaffoldingMethodTestBlock extends ScaffoldingBlock
|
||||
{
|
||||
|
||||
public ScaffoldingMethodTestBlock(Properties properties)
|
||||
{
|
||||
super(properties);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isScaffolding(BlockState state, LevelReader level, BlockPos pos, LivingEntity entity)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.block;
|
||||
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.vehicle.Boat;
|
||||
import net.minecraft.world.item.BlockItem;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.level.LevelReader;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
import net.minecraftforge.registries.ObjectHolder;
|
||||
import net.minecraftforge.registries.RegisterEvent;
|
||||
|
||||
@Mod(SlipperinessTest.MOD_ID)
|
||||
@EventBusSubscriber
|
||||
public class SlipperinessTest
|
||||
{
|
||||
static final String MOD_ID = "slipperiness_test";
|
||||
static final String BLOCK_ID = "test_block";
|
||||
|
||||
@ObjectHolder(registryName = "block", value = BLOCK_ID)
|
||||
public static final Block BB_BLOCK = null;
|
||||
|
||||
@SubscribeEvent
|
||||
public static void registerBlocks(RegisterEvent e)
|
||||
{
|
||||
e.register(ForgeRegistries.Keys.BLOCKS, helper -> helper.register(BLOCK_ID, new Block(Block.Properties.of())
|
||||
{
|
||||
@Override
|
||||
public float getFriction(BlockState state, LevelReader level, BlockPos pos, Entity entity)
|
||||
{
|
||||
return entity instanceof Boat ? 2 : super.getFriction(state, level, pos, entity);
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public static void registerItems(RegisterEvent e)
|
||||
{
|
||||
e.register(ForgeRegistries.Keys.ITEMS, helper -> helper.register(BLOCK_ID, new BlockItem(BB_BLOCK, new Item.Properties())));
|
||||
}
|
||||
|
||||
/*
|
||||
@EventBusSubscriber(value = Dist.CLIENT, modid = MOD_ID)
|
||||
public static class ClientEventHandler
|
||||
{
|
||||
@SubscribeEvent
|
||||
public static void registerModels(ModelRegistryEvent event)
|
||||
{
|
||||
ModelLoader.setCustomStateMapper(BB_BLOCK, block -> Collections.emptyMap());
|
||||
ModelBakery.registerItemVariants(Item.getItemFromBlock(BB_BLOCK));
|
||||
}
|
||||
}
|
||||
*/
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.block;
|
||||
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.Blocks;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.material.MapColor;
|
||||
import net.minecraft.world.item.BlockItem;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.eventbus.api.IEventBus;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
import net.minecraftforge.registries.DeferredRegister;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
import net.minecraftforge.registries.ObjectHolder;
|
||||
import net.minecraftforge.registries.RegisterEvent;
|
||||
import net.minecraftforge.registries.RegistryObject;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
@Mod(StickyBlockTest.MODID)
|
||||
@Mod.EventBusSubscriber(bus = Bus.MOD)
|
||||
public class StickyBlockTest
|
||||
{
|
||||
static final String MODID = "custom_slime_block_test";
|
||||
static final String BLOCK_ID = "test_block";
|
||||
static final String BLOCK_ID_2 = "test_block_2";
|
||||
|
||||
public static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, MODID);
|
||||
public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS.getRegistryName(), MODID);
|
||||
|
||||
public static final RegistryObject<Block> BLUE_BLOCK = BLOCKS.register(BLOCK_ID, () -> new Block(Block.Properties.of().mapColor(MapColor.STONE))
|
||||
{
|
||||
@Override
|
||||
public boolean isStickyBlock(BlockState state)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
});
|
||||
|
||||
public static final RegistryObject<Block> RED_BLOCK = BLOCKS.register(BLOCK_ID_2, () -> new Block(Block.Properties.of().mapColor(MapColor.STONE))
|
||||
{
|
||||
@Override
|
||||
public boolean isStickyBlock(BlockState state)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSlimeBlock(BlockState state)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canStickTo(BlockState state, BlockState other)
|
||||
{
|
||||
if (state.getBlock() == RED_BLOCK.get() && other.getBlock() == Blocks.SLIME_BLOCK) return false;
|
||||
return state.isStickyBlock() || other.isStickyBlock();
|
||||
}
|
||||
});
|
||||
|
||||
public static final RegistryObject<Item> BLUE_BLOCK_ITEM = ITEMS.register(BLOCK_ID, () -> new BlockItem(BLUE_BLOCK.get(), new Item.Properties()));
|
||||
public static final RegistryObject<Item> RED_BLOCK_ITEM = ITEMS.register(BLOCK_ID_2, () -> new BlockItem(RED_BLOCK.get(), new Item.Properties()));
|
||||
|
||||
public StickyBlockTest()
|
||||
{
|
||||
IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus();
|
||||
BLOCKS.register(modEventBus);
|
||||
ITEMS.register(modEventBus);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.block;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.event.level.BlockEvent.BlockToolModificationEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
|
||||
@Mod("tool_interact_test")
|
||||
public class ToolInteractTest
|
||||
{
|
||||
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
|
||||
public ToolInteractTest()
|
||||
{
|
||||
MinecraftForge.EVENT_BUS.addListener(this::onToolInteraction);
|
||||
}
|
||||
|
||||
private void onToolInteraction(final BlockToolModificationEvent event)
|
||||
{
|
||||
//Test 1: No Changes, just test if event is called. State and Final State should be the same
|
||||
LOGGER.info("BlockState {} is modified to {} at position {} by {} with {} simulated={}", event.getState(), event.getFinalState(), event.getPos(), event.getPlayer(), event.getHeldItemStack(), event.isSimulated());
|
||||
|
||||
//Test 2: Canceling, nothing in game should change
|
||||
/*event.setCanceled(true);
|
||||
LOGGER.info("Event has been canceled: {}", event.isCanceled());
|
||||
*/
|
||||
|
||||
//Test 3: Altering
|
||||
/*event.setFinalState(Blocks.ACACIA_FENCE.getDefaultState());
|
||||
LOGGER.info("BlockState {} is modified to {} at position {} by {} with {}", event.getState(), event.getFinalState(), event.getPos(), event.getPlayer(), event.getHeldItemStack());
|
||||
*/
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.block;
|
||||
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.Direction;
|
||||
import net.minecraft.world.item.BlockItem;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.item.context.BlockPlaceContext;
|
||||
import net.minecraft.world.level.LevelReader;
|
||||
import net.minecraft.world.level.block.BaseRailBlock;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.SoundType;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.block.state.StateDefinition;
|
||||
import net.minecraft.world.level.block.state.properties.EnumProperty;
|
||||
import net.minecraft.world.level.block.state.properties.Property;
|
||||
import net.minecraft.world.level.block.state.properties.RailShape;
|
||||
import net.minecraft.world.level.material.FluidState;
|
||||
import net.minecraft.world.level.material.Fluids;
|
||||
import net.minecraftforge.eventbus.api.IEventBus;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
import net.minecraftforge.registries.DeferredRegister;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
import net.minecraftforge.registries.RegistryObject;
|
||||
|
||||
@Mod(ValidRailShapeTest.MOD_ID)
|
||||
public class ValidRailShapeTest
|
||||
{
|
||||
public static final String MOD_ID = "valid_railshape_test";
|
||||
public static final boolean ENABLED = true;
|
||||
|
||||
private static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, MOD_ID);
|
||||
private static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, MOD_ID);
|
||||
|
||||
private static final RegistryObject<Block> RAIL_SLOPE_BLOCK = BLOCKS.register("rail_slope", RailSlopeBlock::new);
|
||||
private static final RegistryObject<Item> RAIL_SLOPE_ITEM = ITEMS.register("rail_slope", () -> new BlockItem(RAIL_SLOPE_BLOCK.get(), new Item.Properties()));
|
||||
|
||||
public ValidRailShapeTest()
|
||||
{
|
||||
if (ENABLED)
|
||||
{
|
||||
IEventBus bus = FMLJavaModLoadingContext.get().getModEventBus();
|
||||
BLOCKS.register(bus);
|
||||
ITEMS.register(bus);
|
||||
}
|
||||
}
|
||||
|
||||
private static class RailSlopeBlock extends BaseRailBlock
|
||||
{
|
||||
private static final EnumProperty<RailShape> ASCENDING_RAIL_SHAPE = EnumProperty.create("shape", RailShape.class, RailShape::isAscending);
|
||||
|
||||
protected RailSlopeBlock()
|
||||
{
|
||||
super(true, Properties.of().noCollission().strength(0.7F).sound(SoundType.METAL));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder)
|
||||
{
|
||||
builder.add(ASCENDING_RAIL_SHAPE, BaseRailBlock.WATERLOGGED);
|
||||
}
|
||||
|
||||
@Override
|
||||
public BlockState getStateForPlacement(BlockPlaceContext context)
|
||||
{
|
||||
RailShape shape = switch (context.getHorizontalDirection())
|
||||
{
|
||||
case NORTH -> RailShape.ASCENDING_NORTH;
|
||||
case EAST -> RailShape.ASCENDING_EAST;
|
||||
case SOUTH -> RailShape.ASCENDING_SOUTH;
|
||||
case WEST -> RailShape.ASCENDING_WEST;
|
||||
default -> throw new IllegalArgumentException("Invalid facing " + context.getHorizontalDirection());
|
||||
};
|
||||
|
||||
FluidState fluid = context.getLevel().getFluidState(context.getClickedPos());
|
||||
|
||||
return defaultBlockState()
|
||||
.setValue(ASCENDING_RAIL_SHAPE, shape)
|
||||
.setValue(BaseRailBlock.WATERLOGGED, fluid.getType() == Fluids.WATER);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canSurvive(BlockState state, LevelReader level, BlockPos pos)
|
||||
{
|
||||
RailShape shape = state.getValue(ASCENDING_RAIL_SHAPE);
|
||||
Direction dir = switch (shape)
|
||||
{
|
||||
case ASCENDING_NORTH -> Direction.NORTH;
|
||||
case ASCENDING_EAST -> Direction.EAST;
|
||||
case ASCENDING_SOUTH -> Direction.SOUTH;
|
||||
case ASCENDING_WEST -> Direction.WEST;
|
||||
default -> throw new IllegalArgumentException("Invalid shape " + shape);
|
||||
};
|
||||
|
||||
if (!canSupportRigidBlock(level, pos.relative(dir)))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return super.canSurvive(state, level, pos);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isValidRailShape(RailShape shape)
|
||||
{
|
||||
return shape.isAscending();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Property<RailShape> getShapeProperty()
|
||||
{
|
||||
return ASCENDING_RAIL_SHAPE;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
@ParametersAreNonnullByDefault
|
||||
@MethodsReturnNonnullByDefault
|
||||
package net.minecraftforge.debug.block;
|
||||
|
||||
import javax.annotation.ParametersAreNonnullByDefault;
|
||||
import net.minecraft.MethodsReturnNonnullByDefault;
|
||||
@@ -0,0 +1,24 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.chat;
|
||||
|
||||
import net.minecraftforge.client.event.ClientChatEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
|
||||
@Mod("client_chat_event_test")
|
||||
@Mod.EventBusSubscriber
|
||||
public class ClientChatEventTest
|
||||
{
|
||||
@SubscribeEvent
|
||||
public static void onPlayerAttemptChat(ClientChatEvent event)
|
||||
{
|
||||
if (event.getMessage().equals("Cancel"))
|
||||
event.setCanceled(true);
|
||||
else if (event.getMessage().equals("Replace this text"))
|
||||
event.setMessage("Text replaced.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.chat;
|
||||
|
||||
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.Commands;
|
||||
import net.minecraft.commands.SharedSuggestionProvider;
|
||||
import net.minecraft.commands.arguments.ObjectiveArgument;
|
||||
import net.minecraft.commands.arguments.ResourceLocationArgument;
|
||||
import net.minecraft.commands.arguments.TeamArgument;
|
||||
import net.minecraft.commands.arguments.coordinates.BlockPosArgument;
|
||||
import net.minecraft.commands.synchronization.SuggestionProviders;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraftforge.debug.client.TestScreen;
|
||||
import net.minecraftforge.client.event.RegisterClientCommandsEvent;
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Mod("client_command_test")
|
||||
public class ClientCommandTest
|
||||
{
|
||||
public ClientCommandTest()
|
||||
{
|
||||
MinecraftForge.EVENT_BUS.addListener(this::init);
|
||||
}
|
||||
|
||||
private void init(RegisterClientCommandsEvent event)
|
||||
{
|
||||
event.getDispatcher().register(
|
||||
Commands.literal("clientcommandtest")
|
||||
// Used for checking suggestion providers that aren't registered
|
||||
.then(Commands.literal("rawsuggest")
|
||||
.then(Commands.argument("block", ResourceLocationArgument.id())
|
||||
.suggests((c, b) -> SharedSuggestionProvider.suggestResource(ForgeRegistries.BLOCKS.getKeys(), b))
|
||||
.executes(this::testCommand)))
|
||||
// Used for checking suggestion providers that are registered
|
||||
.then(Commands.literal("registeredsuggest").then(
|
||||
Commands.argument("block", ResourceLocationArgument.id())
|
||||
.suggests(SuggestionProviders.ALL_RECIPES)
|
||||
.executes(this::testCommand)))
|
||||
// Used for checking if attempting to get the server on the client side errors
|
||||
.then(Commands.literal("server")
|
||||
.executes((context) -> {
|
||||
context.getSource().getServer();
|
||||
context.getSource().sendSuccess(() ->Component.literal("Successfully called getServer should have errored"), false);
|
||||
return 1;
|
||||
}))
|
||||
// Used for checking if attempting to get the server level on the client side errors
|
||||
.then(Commands.literal("level")
|
||||
.executes((context) -> {
|
||||
context.getSource().getLevel();
|
||||
context.getSource().sendSuccess(() ->Component.literal("Successfully called getLevel should have errored"), false);
|
||||
return 1;
|
||||
}))
|
||||
// Used for checking if getting a known objective argument works on the client side
|
||||
.then(Commands.literal("get_objective")
|
||||
.then(Commands.argument("objective", ObjectiveArgument.objective())
|
||||
.executes((context) -> {
|
||||
final Component msg = Component.literal("Regular: ")
|
||||
.append(ObjectiveArgument.getObjective(context, "objective").getFormattedDisplayName());
|
||||
context.getSource().sendSuccess(() -> msg, false);
|
||||
return 1;
|
||||
})))
|
||||
// Used for checking if getting a known advancement works on the client side
|
||||
.then(Commands.literal("get_advancement")
|
||||
.then(Commands.argument("advancement", ResourceLocationArgument.id())
|
||||
.executes((context) -> {
|
||||
final Component msg = ResourceLocationArgument.getAdvancement(context, "advancement").value().name().get();
|
||||
context.getSource().sendSuccess(() -> msg, false);
|
||||
return 1;
|
||||
})))
|
||||
// Used for checking if getting a known recipe works on the client side
|
||||
.then(Commands.literal("get_recipe")
|
||||
.then(Commands.argument("recipe", ResourceLocationArgument.id())
|
||||
.executes((context) -> {
|
||||
final Component msg = ResourceLocationArgument.getRecipe(context, "recipe").value().getResultItem(context.getSource().registryAccess()).getDisplayName();
|
||||
context.getSource()
|
||||
.sendSuccess(() -> msg, false);
|
||||
return 1;
|
||||
})))
|
||||
// Used for checking if getting a team works on the client side
|
||||
.then(Commands.literal("get_team")
|
||||
.then(Commands.argument("team", TeamArgument.team())
|
||||
.executes((context) -> {
|
||||
final Component msg = TeamArgument.getTeam(context, "team").getFormattedDisplayName();
|
||||
context.getSource().sendSuccess(() -> msg, false);
|
||||
return 1;
|
||||
})))
|
||||
// Used for checking if a block position is valid works on the client side
|
||||
.then(Commands.literal("get_loaded_blockpos")
|
||||
.then(Commands.argument("blockpos", BlockPosArgument.blockPos())
|
||||
.executes((context) -> {
|
||||
final Component msg = Component.literal(BlockPosArgument.getLoadedBlockPos(context, "blockpos").toString());
|
||||
context.getSource()
|
||||
.sendSuccess(() -> msg, false);
|
||||
return 1;
|
||||
})))
|
||||
// Used for checking if a command can have a requirement
|
||||
.then(Commands.literal("requires")
|
||||
.requires((source) -> false)
|
||||
.executes((context) -> {
|
||||
context.getSource().sendSuccess(() ->Component.literal("Executed command"), false);
|
||||
return 1;
|
||||
}))
|
||||
// Used for testing the screen after using commands
|
||||
.then(Commands.literal("screentest")
|
||||
.executes((stack) -> TestScreen.open())));
|
||||
|
||||
// Used for testing that client command redirects can only be used with client commands
|
||||
LiteralArgumentBuilder<CommandSourceStack> fork = Commands.literal("clientcommandfork");
|
||||
fork.fork(event.getDispatcher().getRoot(), (context) -> List.of(context.getSource(), context.getSource()))
|
||||
.executes((context) -> {
|
||||
context.getSource().sendSuccess(() ->Component.literal("Executing forked command"), false);
|
||||
return 1;
|
||||
});
|
||||
event.getDispatcher().register(fork);
|
||||
}
|
||||
|
||||
private int testCommand(CommandContext<CommandSourceStack> context)
|
||||
{
|
||||
context.getSource().sendSuccess(() ->Component.literal("Input: " + ResourceLocationArgument.getId(context, "block")), false);
|
||||
context.getSource().sendSuccess(() ->Component.literal("Teams: " + context.getSource().getAllTeams()), false);
|
||||
context.getSource().sendSuccess(() ->Component.literal("Players: " + context.getSource().getOnlinePlayerNames()), false);
|
||||
context.getSource().sendSuccess(() ->Component.literal("First recipe: " + context.getSource().getRecipeNames().findFirst().get()), false);
|
||||
context.getSource().sendSuccess(() ->Component.literal("Levels: " + context.getSource().levels()), false);
|
||||
context.getSource().sendSuccess(() ->Component.literal("Registry Access: " + context.getSource().registryAccess()), false);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.chat;
|
||||
|
||||
import com.mojang.brigadier.CommandDispatcher;
|
||||
import com.mojang.brigadier.context.ParsedCommandNode;
|
||||
import net.minecraft.commands.CommandRuntimeException;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraftforge.event.CommandEvent;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Mod("command_event_test")
|
||||
@Mod.EventBusSubscriber
|
||||
public class CommandEventTest
|
||||
{
|
||||
public final Logger LOGGER = LogManager.getLogger();
|
||||
|
||||
@SubscribeEvent
|
||||
public static void onCommand(CommandEvent event)
|
||||
{
|
||||
CommandDispatcher<CommandSourceStack> dispatcher = event.getParseResults().getContext().getDispatcher();
|
||||
List<ParsedCommandNode<CommandSourceStack>> nodes = event.getParseResults().getContext().getNodes();
|
||||
CommandSourceStack source = event.getParseResults().getContext().getSource();
|
||||
|
||||
// test: when the /time command is used with no arguments, automatically add default arguments (/time set day)
|
||||
if (nodes.size() == 1 && nodes.get(0).getNode() == dispatcher.getRoot().getChild("time"))
|
||||
{
|
||||
event.setParseResults(dispatcher.parse("time set day", source));
|
||||
return;
|
||||
}
|
||||
|
||||
// test: whenever a player uses the /give command, let everyone on the server know
|
||||
if (nodes.size() > 0 && nodes.get(0).getNode() == dispatcher.getRoot().getChild("give"))
|
||||
{
|
||||
String msg = source.getTextName() + " used the give command: " + event.getParseResults().getReader().getString();
|
||||
source.getServer().getPlayerList().getPlayers().forEach(player -> player.sendSystemMessage(Component.literal(msg)));
|
||||
return;
|
||||
}
|
||||
|
||||
// this is annoying so I disabled it
|
||||
// test: when the /kill command is used with no arguments, throw a custom exception
|
||||
// if (nodes.size() == 1 && nodes.get(0).getNode() == dispatcher.getRoot().getChild("kill"))
|
||||
// {
|
||||
// event.setException(new CommandRuntimeException(new TextComponent("You tried to use the /kill command with no arguments")));
|
||||
// event.setCanceled(true);
|
||||
// return;
|
||||
// }
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.chat;
|
||||
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import net.minecraft.advancements.critereon.MinMaxBounds;
|
||||
import net.minecraft.commands.arguments.selector.options.EntitySelectorOptions;
|
||||
import net.minecraft.commands.arguments.selector.EntitySelector;
|
||||
import net.minecraft.commands.arguments.selector.EntitySelectorParser;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.LivingEntity;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraftforge.common.command.EntitySelectorManager;
|
||||
import net.minecraftforge.common.command.IEntitySelectorType;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
|
||||
@Mod("entity_selector_test")
|
||||
public class EntitySelectorTest
|
||||
{
|
||||
public EntitySelectorTest()
|
||||
{
|
||||
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup);
|
||||
}
|
||||
|
||||
public void setup(FMLCommonSetupEvent event)
|
||||
{
|
||||
EntitySelectorOptions.register("health", this::healthArgument, parser -> true, Component.literal("Selects entities based on their current health."));
|
||||
EntitySelectorManager.register("er", new ExampleCustomSelector());
|
||||
}
|
||||
|
||||
/**
|
||||
* Example for a custom selector argument, checks for the health of the entity
|
||||
*/
|
||||
private void healthArgument(EntitySelectorParser parser) throws CommandSyntaxException
|
||||
{
|
||||
MinMaxBounds.Doubles bound = MinMaxBounds.Doubles.fromReader(parser.getReader());
|
||||
parser.addPredicate(entity -> entity instanceof LivingEntity && bound.matches(((LivingEntity) entity).getHealth()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Example for a custom selector type, works like @r but for entities.
|
||||
* Basically does exactly what @e[sorter=random, limit=1, ...] does.
|
||||
*/
|
||||
private class ExampleCustomSelector implements IEntitySelectorType
|
||||
{
|
||||
@Override
|
||||
public EntitySelector build(EntitySelectorParser parser) throws CommandSyntaxException
|
||||
{
|
||||
parser.setOrder(EntitySelectorParser.ORDER_RANDOM);
|
||||
parser.setMaxResults(1);
|
||||
parser.setIncludesEntities(true);
|
||||
parser.addPredicate(Entity::isAlive);
|
||||
parser.setSuggestions((builder, consumer) -> builder.suggest(String.valueOf('[')).buildFuture());
|
||||
if (parser.getReader().canRead() && parser.getReader().peek() == '[')
|
||||
{
|
||||
parser.getReader().skip();
|
||||
parser.setSuggestions((builder, consumer) -> {
|
||||
builder.suggest(String.valueOf(']'));
|
||||
EntitySelectorOptions.suggestNames(parser, builder);
|
||||
return builder.buildFuture();
|
||||
});
|
||||
|
||||
parser.parseOptions();
|
||||
}
|
||||
|
||||
parser.finalizePredicates();
|
||||
return parser.getSelector();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Component getSuggestionTooltip()
|
||||
{
|
||||
return Component.literal("Example: Selects a random entity");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
@ParametersAreNonnullByDefault
|
||||
@MethodsReturnNonnullByDefault
|
||||
package net.minecraftforge.debug.chat;
|
||||
|
||||
import javax.annotation.ParametersAreNonnullByDefault;
|
||||
import net.minecraft.MethodsReturnNonnullByDefault;
|
||||
@@ -0,0 +1,64 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.client;
|
||||
|
||||
import net.minecraft.world.item.BlockItem;
|
||||
import net.minecraft.world.item.CreativeModeTabs;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.state.BlockBehaviour;
|
||||
import net.minecraft.world.level.material.MapColor;
|
||||
import net.minecraftforge.event.BuildCreativeModeTabContentsEvent;
|
||||
import net.minecraftforge.eventbus.api.IEventBus;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
import net.minecraftforge.registries.DeferredRegister;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
import net.minecraftforge.registries.RegistryObject;
|
||||
|
||||
/**
|
||||
* Test mod that demos disabling ambient occlusion on specific faces of "elements" models.
|
||||
*/
|
||||
@Mod(AmbientOcclusionElementsTest.MOD_ID)
|
||||
public class AmbientOcclusionElementsTest
|
||||
{
|
||||
private static final boolean ENABLED = false;
|
||||
|
||||
public static final String MOD_ID = "ambient_occlusion_elements_test";
|
||||
private static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, MOD_ID);
|
||||
private static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, MOD_ID);
|
||||
|
||||
public static final RegistryObject<Block> AO_BLOCK_SHADE = BLOCKS.register("ambient_occlusion_shade", () -> new Block(BlockBehaviour.Properties.of().mapColor(MapColor.STONE)));
|
||||
public static final RegistryObject<Block> AO_BLOCK_NO_SHADE = BLOCKS.register("ambient_occlusion_no_shade", () -> new Block(BlockBehaviour.Properties.of().mapColor(MapColor.STONE)));
|
||||
public static final RegistryObject<Block> NO_AO_BLOCK_SHADE = BLOCKS.register("no_ambient_occlusion_shade", () -> new Block(BlockBehaviour.Properties.of().mapColor(MapColor.STONE)));
|
||||
public static final RegistryObject<Block> NO_AO_BLOCK_NO_SHADE = BLOCKS.register("no_ambient_occlusion_no_shade", () -> new Block(BlockBehaviour.Properties.of().mapColor(MapColor.STONE)));
|
||||
public static final RegistryObject<Item> AO_BLOCK_SHADE_ITEM = ITEMS.register("ambient_occlusion_shade", () -> new BlockItem(AO_BLOCK_SHADE.get(), new Item.Properties()));
|
||||
public static final RegistryObject<Item> AO_BLOCK_NO_SHADE_ITEM = ITEMS.register("ambient_occlusion_no_shade", () -> new BlockItem(AO_BLOCK_NO_SHADE.get(), new Item.Properties()));
|
||||
public static final RegistryObject<Item> NO_AO_BLOCK_SHADE_ITEM = ITEMS.register("no_ambient_occlusion_shade", () -> new BlockItem(NO_AO_BLOCK_SHADE.get(), new Item.Properties()));
|
||||
public static final RegistryObject<Item> NO_AO_BLOCK_NO_SHADE_ITEM = ITEMS.register("no_ambient_occlusion_no_shade", () -> new BlockItem(NO_AO_BLOCK_NO_SHADE.get(), new Item.Properties()));
|
||||
|
||||
public AmbientOcclusionElementsTest()
|
||||
{
|
||||
if (!ENABLED)
|
||||
return;
|
||||
|
||||
IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus();
|
||||
BLOCKS.register(modEventBus);
|
||||
ITEMS.register(modEventBus);
|
||||
modEventBus.addListener(this::addCreative);
|
||||
}
|
||||
|
||||
private void addCreative(BuildCreativeModeTabContentsEvent event)
|
||||
{
|
||||
if (event.getTabKey() == CreativeModeTabs.BUILDING_BLOCKS)
|
||||
{
|
||||
event.accept(AO_BLOCK_SHADE_ITEM);
|
||||
event.accept(AO_BLOCK_NO_SHADE_ITEM);
|
||||
event.accept(NO_AO_BLOCK_SHADE_ITEM);
|
||||
event.accept(NO_AO_BLOCK_NO_SHADE_ITEM);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.client;
|
||||
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.resources.sounds.AbstractSoundInstance;
|
||||
import net.minecraft.client.resources.sounds.Sound;
|
||||
import net.minecraft.client.resources.sounds.SoundInstance;
|
||||
import net.minecraft.client.sounds.AudioStream;
|
||||
import net.minecraft.client.sounds.SoundBufferLibrary;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.sounds.SoundSource;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
import net.minecraftforge.client.event.ClientChatEvent;
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.loading.FMLLoader;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.lwjgl.BufferUtils;
|
||||
|
||||
import javax.sound.sampled.AudioFormat;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
/**
|
||||
* Tests support for custom {@link AudioStream}s ({@link SoundInstance#getStream(SoundBufferLibrary, Sound, boolean)}.
|
||||
*
|
||||
* When the message "sine wave" is sent in chat, this should play a sine wave of 220Hz at the player's current position.
|
||||
*/
|
||||
@Mod(AudioStreamTest.MOD_ID)
|
||||
public class AudioStreamTest
|
||||
{
|
||||
private static final boolean ENABLED = true;
|
||||
static final String MOD_ID = "audio_stream_test";
|
||||
|
||||
public AudioStreamTest()
|
||||
{
|
||||
if (ENABLED && FMLLoader.getDist().isClient())
|
||||
{
|
||||
MinecraftForge.EVENT_BUS.addListener(ClientHandler::onClientChatEvent);
|
||||
}
|
||||
}
|
||||
|
||||
public static class ClientHandler
|
||||
{
|
||||
public static void onClientChatEvent(ClientChatEvent event)
|
||||
{
|
||||
if (event.getMessage().equalsIgnoreCase("sine wave"))
|
||||
{
|
||||
event.setCanceled(true);
|
||||
var mc = Minecraft.getInstance();
|
||||
mc.getSoundManager().play(new SineSound(mc.player.position()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class SineSound extends AbstractSoundInstance
|
||||
{
|
||||
protected SineSound(Vec3 position)
|
||||
{
|
||||
super(new ResourceLocation(MOD_ID, "sine_wave"), SoundSource.BLOCKS, SoundInstance.createUnseededRandom());
|
||||
x = position.x;
|
||||
y = position.y;
|
||||
z = position.z;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public CompletableFuture<AudioStream> getStream(@NotNull SoundBufferLibrary soundBuffers, @NotNull Sound sound, boolean looping)
|
||||
{
|
||||
return CompletableFuture.completedFuture(new SineStream());
|
||||
}
|
||||
}
|
||||
|
||||
public static class SineStream implements AudioStream
|
||||
{
|
||||
private static final AudioFormat FORMAT = new AudioFormat(44100, 8, 1, false, false);
|
||||
private static final double DT = 2 * Math.PI * 220 / 44100;
|
||||
|
||||
private static double value = 0;
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public AudioFormat getFormat()
|
||||
{
|
||||
return FORMAT;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public ByteBuffer read(int capacity)
|
||||
{
|
||||
ByteBuffer buffer = BufferUtils.createByteBuffer(capacity);
|
||||
for(int i = 0; i < capacity; i++)
|
||||
{
|
||||
buffer.put(i, (byte) (Math.sin(value) * 127));
|
||||
value = (value + DT) % Math.PI;
|
||||
}
|
||||
return buffer;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close()
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.client;
|
||||
|
||||
import com.mojang.blaze3d.vertex.PoseStack;
|
||||
import com.mojang.blaze3d.vertex.VertexConsumer;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.model.HumanoidModel;
|
||||
import net.minecraft.client.model.Model;
|
||||
import net.minecraft.client.model.geom.ModelLayers;
|
||||
import net.minecraft.client.renderer.RenderType;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.EquipmentSlot;
|
||||
import net.minecraft.world.entity.LivingEntity;
|
||||
import net.minecraft.world.item.*;
|
||||
import net.minecraft.world.item.Item.Properties;
|
||||
import net.minecraftforge.client.extensions.common.IClientItemExtensions;
|
||||
import net.minecraftforge.common.util.Lazy;
|
||||
import net.minecraftforge.event.BuildCreativeModeTabContentsEvent;
|
||||
import net.minecraftforge.eventbus.api.IEventBus;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
import net.minecraftforge.registries.DeferredRegister;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
import net.minecraftforge.registries.RegistryObject;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
|
||||
@Mod(CustomArmorModelTest.MOD_ID)
|
||||
public class CustomArmorModelTest
|
||||
{
|
||||
static final String MOD_ID = "custom_armor_model_test";
|
||||
private static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, MOD_ID);
|
||||
// demonstrates custom non-humanoid model
|
||||
private static final RegistryObject<Item> RED_LEGGINGS = ITEMS.register("red_leggings", () -> new TintedArmorItem(ArmorMaterials.DIAMOND, ArmorItem.Type.LEGGINGS, new Properties().stacksTo(1)));
|
||||
// demonstrates the properties are copied from the vanilla model
|
||||
private static final RegistryObject<Item> ENDERMAN_CHESTPLATE = ITEMS.register("enderman_chestplate", () -> new EndermanArmorItem(ArmorMaterials.GOLD, ArmorItem.Type.CHESTPLATE, new Properties().stacksTo(1)));
|
||||
private static final RegistryObject<Item> ENDERMAN_BOOTS = ITEMS.register("enderman_boots", () -> new EndermanArmorItem(ArmorMaterials.GOLD, ArmorItem.Type.BOOTS, new Properties().stacksTo(1)));
|
||||
|
||||
public CustomArmorModelTest()
|
||||
{
|
||||
final IEventBus modBus = FMLJavaModLoadingContext.get().getModEventBus();
|
||||
ITEMS.register(modBus);
|
||||
modBus.addListener(this::addCreative);
|
||||
}
|
||||
|
||||
private void addCreative(BuildCreativeModeTabContentsEvent event)
|
||||
{
|
||||
if (event.getTabKey() == CreativeModeTabs.INGREDIENTS)
|
||||
{
|
||||
event.accept(RED_LEGGINGS);
|
||||
event.accept(ENDERMAN_CHESTPLATE);
|
||||
event.accept(ENDERMAN_BOOTS);
|
||||
}
|
||||
}
|
||||
|
||||
private static class TintedArmorItem extends ArmorItem
|
||||
{
|
||||
public TintedArmorItem(ArmorMaterial material, ArmorItem.Type slot, Properties props)
|
||||
{
|
||||
super(material, slot, props);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initializeClient(Consumer<IClientItemExtensions> consumer)
|
||||
{
|
||||
consumer.accept(new IClientItemExtensions()
|
||||
{
|
||||
@Override @NotNull
|
||||
public Model getGenericArmorModel(LivingEntity entityLiving, ItemStack itemStack, EquipmentSlot armorSlot, HumanoidModel<?> _default)
|
||||
{
|
||||
TintedArmorModel.INSTANCE.base = _default;
|
||||
return TintedArmorModel.INSTANCE;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private static class EndermanArmorItem extends ArmorItem
|
||||
{
|
||||
public EndermanArmorItem(ArmorMaterial material, ArmorItem.Type slot, Properties props)
|
||||
{
|
||||
super(material, slot, props);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public String getArmorTexture(ItemStack stack, Entity entity, EquipmentSlot slot, String type)
|
||||
{
|
||||
return "textures/entity/enderman/enderman.png";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initializeClient(Consumer<IClientItemExtensions> consumer)
|
||||
{
|
||||
consumer.accept(new IClientItemExtensions()
|
||||
{
|
||||
@Override
|
||||
public HumanoidModel<?> getHumanoidArmorModel(LivingEntity entityLiving, ItemStack itemStack, EquipmentSlot armorSlot, HumanoidModel<?> _default)
|
||||
{
|
||||
return TintedArmorModel.ENDERMAN.get();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private static class TintedArmorModel extends Model
|
||||
{
|
||||
private static final TintedArmorModel INSTANCE = new TintedArmorModel(RenderType::entityCutoutNoCull);
|
||||
private static final Lazy<HumanoidModel<LivingEntity>> ENDERMAN = Lazy.of(() -> new HumanoidModel<>(Minecraft.getInstance().getEntityModels().bakeLayer(ModelLayers.ENDERMAN)));
|
||||
|
||||
private HumanoidModel<?> base;
|
||||
private TintedArmorModel(Function<ResourceLocation,RenderType> renderTypeFunction)
|
||||
{
|
||||
super(renderTypeFunction);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void renderToBuffer(@NotNull PoseStack poseStack, @NotNull VertexConsumer consumer, int light, int overlay, float red, float green, float blue, float alpha)
|
||||
{
|
||||
if (base != null)
|
||||
{
|
||||
base.renderToBuffer(poseStack, consumer, light, overlay, red, 0, 0, alpha);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.client;
|
||||
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.world.item.BlockItem;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.level.ColorResolver;
|
||||
import net.minecraft.world.level.biome.Biome;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.state.BlockBehaviour;
|
||||
import net.minecraft.world.level.material.MapColor;
|
||||
import net.minecraftforge.api.distmarker.Dist;
|
||||
import net.minecraftforge.client.event.RegisterColorHandlersEvent;
|
||||
import net.minecraftforge.eventbus.api.IEventBus;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
import net.minecraftforge.registries.DeferredRegister;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
import net.minecraftforge.registries.RegistryObject;
|
||||
|
||||
/**
|
||||
* This mod tests custom {@link ColorResolver ColorResolvers} using {@link RegisterColorHandlersEvent.ColorResolvers}.
|
||||
* To test, place the registered test block, it should be tinted blue in biomes with precipitation and red in others.
|
||||
* The color should blend according to the biome blend setting.
|
||||
*/
|
||||
@Mod(CustomColorResolverTest.MOD_ID)
|
||||
public class CustomColorResolverTest
|
||||
{
|
||||
static final String MOD_ID = "custom_color_resolver_test";
|
||||
private static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, MOD_ID);
|
||||
private static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, MOD_ID);
|
||||
|
||||
private static final RegistryObject<Block> BLOCK = BLOCKS.register("test_block", () -> new Block(BlockBehaviour.Properties.of().mapColor(MapColor.STONE)));
|
||||
|
||||
public CustomColorResolverTest()
|
||||
{
|
||||
final IEventBus modBus = FMLJavaModLoadingContext.get().getModEventBus();
|
||||
ITEMS.register(modBus);
|
||||
BLOCKS.register(modBus);
|
||||
|
||||
ITEMS.register("test_block", () -> new BlockItem(BLOCK.get(), new Item.Properties()));
|
||||
}
|
||||
|
||||
@Mod.EventBusSubscriber(value = Dist.CLIENT, modid=MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD)
|
||||
private static class ClientHandler
|
||||
{
|
||||
|
||||
private static final ColorResolver COLOR_RESOLVER = (biome, x, z) -> biome.getPrecipitationAt(BlockPos.containing(x, 0, z)) == Biome.Precipitation.NONE ? 0xFF0000 : 0x0000FF;
|
||||
|
||||
@SubscribeEvent
|
||||
static void registerColorResolver(RegisterColorHandlersEvent.ColorResolvers event)
|
||||
{
|
||||
event.register(COLOR_RESOLVER);
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
static void registerBlockColor(RegisterColorHandlersEvent.Block event)
|
||||
{
|
||||
event.register(((state, btGetter, pos, tintIndex) -> btGetter == null || pos == null ? 0 : btGetter.getBlockTint(pos, COLOR_RESOLVER)), BLOCK.get());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.client;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
import net.minecraft.client.gui.components.Button;
|
||||
import net.minecraft.client.gui.components.Button.OnPress;
|
||||
import net.minecraft.client.gui.screens.Screen;
|
||||
import net.minecraft.client.gui.screens.worldselection.CreateWorldScreen;
|
||||
import net.minecraft.client.gui.screens.worldselection.WorldCreationContext;
|
||||
import net.minecraft.client.gui.screens.worldselection.WorldCreationContext.DimensionsUpdater;
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.core.RegistrySetBuilder;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.data.DataGenerator;
|
||||
import net.minecraft.data.PackOutput;
|
||||
import net.minecraft.data.worldgen.BootstapContext;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.world.level.biome.Biome;
|
||||
import net.minecraft.world.level.biome.BiomeSource;
|
||||
import net.minecraft.world.level.biome.Biomes;
|
||||
import net.minecraft.world.level.biome.FixedBiomeSource;
|
||||
import net.minecraft.world.level.chunk.ChunkGenerator;
|
||||
import net.minecraft.world.level.dimension.BuiltinDimensionTypes;
|
||||
import net.minecraft.world.level.dimension.DimensionType;
|
||||
import net.minecraft.world.level.dimension.LevelStem;
|
||||
import net.minecraft.world.level.levelgen.NoiseBasedChunkGenerator;
|
||||
import net.minecraft.world.level.levelgen.NoiseGeneratorSettings;
|
||||
import net.minecraft.world.level.levelgen.presets.WorldPreset;
|
||||
import net.minecraftforge.api.distmarker.Dist;
|
||||
import net.minecraftforge.client.event.RegisterPresetEditorsEvent;
|
||||
import net.minecraftforge.common.data.DatapackBuiltinEntriesProvider;
|
||||
import net.minecraftforge.data.event.GatherDataEvent;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
|
||||
import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus;
|
||||
|
||||
@Mod(CustomPresetEditorTest.MODID)
|
||||
public class CustomPresetEditorTest
|
||||
{
|
||||
public static final String MODID = "custom_preset_editor_test";
|
||||
public static final ResourceKey<WorldPreset> WORLD_PRESET_KEY = ResourceKey.create(Registries.WORLD_PRESET, new ResourceLocation(MODID, MODID));
|
||||
|
||||
@EventBusSubscriber(modid = MODID, bus = Bus.MOD)
|
||||
public static class CommonModEvents
|
||||
{
|
||||
@SubscribeEvent
|
||||
public static void onGatherData(GatherDataEvent event)
|
||||
{
|
||||
DataGenerator gen = event.getGenerator();
|
||||
PackOutput packOutput = gen.getPackOutput();
|
||||
CompletableFuture<HolderLookup.Provider> lookupProvider = event.getLookupProvider();
|
||||
|
||||
RegistrySetBuilder registrySetBuilder = new RegistrySetBuilder()
|
||||
.add(Registries.WORLD_PRESET, context -> context.register(WORLD_PRESET_KEY, makeWorldPreset(context)));
|
||||
|
||||
gen.addProvider(event.includeServer(), new DatapackBuiltinEntriesProvider(packOutput, lookupProvider, registrySetBuilder, Set.of(MODID))
|
||||
{
|
||||
@Override
|
||||
public String getName()
|
||||
{
|
||||
return MODID + ":" + super.getName(); // dataproviders must have unique names
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static WorldPreset makeWorldPreset(BootstapContext<WorldPreset> context)
|
||||
{
|
||||
Holder<NoiseGeneratorSettings> overworldNoise = context.lookup(Registries.NOISE_SETTINGS)
|
||||
.getOrThrow(NoiseGeneratorSettings.OVERWORLD);
|
||||
Holder<Biome> plains = context.lookup(Registries.BIOME)
|
||||
.getOrThrow(Biomes.PLAINS);
|
||||
Holder<DimensionType> overworldDimensionType = context.lookup(Registries.DIMENSION_TYPE)
|
||||
.getOrThrow(BuiltinDimensionTypes.OVERWORLD);
|
||||
BiomeSource biomeSource = new FixedBiomeSource(plains);
|
||||
ChunkGenerator chunkGenerator = new NoiseBasedChunkGenerator(biomeSource, overworldNoise);
|
||||
LevelStem levelStem = new LevelStem(overworldDimensionType, chunkGenerator);
|
||||
return new WorldPreset(Map.of(LevelStem.OVERWORLD, levelStem));
|
||||
}
|
||||
}
|
||||
|
||||
@EventBusSubscriber(modid = MODID, value = Dist.CLIENT, bus = Bus.MOD)
|
||||
public static class ClientModEvents
|
||||
{
|
||||
@SubscribeEvent
|
||||
public static void onRegisterPresetEditors(RegisterPresetEditorsEvent event)
|
||||
{
|
||||
event.register(WORLD_PRESET_KEY, SwampDesertScreen::new);
|
||||
}
|
||||
}
|
||||
|
||||
public static class SwampDesertScreen extends Screen
|
||||
{
|
||||
private final CreateWorldScreen parent;
|
||||
|
||||
public SwampDesertScreen(CreateWorldScreen parent, WorldCreationContext context)
|
||||
{
|
||||
super(Component.literal(MODID));
|
||||
this.parent = parent;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void init()
|
||||
{
|
||||
// Examples of configuring the world preset via gui controls.
|
||||
// These buttons tell the parent create world screen to replace the overworld with a single-biome dimension when clicked.
|
||||
this.addRenderableWidget(
|
||||
Button.builder(Component.literal("Swamp"), this.onPressBiomeButton(Biomes.SWAMP))
|
||||
.bounds(this.width/2 - 155, this.height - 28, 150, 20)
|
||||
.build());
|
||||
this.addRenderableWidget(
|
||||
Button.builder(Component.literal("Desert"), this.onPressBiomeButton(Biomes.DESERT))
|
||||
.bounds(this.width/2 + 5, this.height - 28, 150, 20)
|
||||
.build());
|
||||
}
|
||||
|
||||
private OnPress onPressBiomeButton(ResourceKey<Biome> biomeKey)
|
||||
{
|
||||
return button -> {
|
||||
this.parent.getUiState().updateDimensions(singleBiomeDimension(biomeKey));
|
||||
this.minecraft.setScreen(this.parent);
|
||||
};
|
||||
}
|
||||
|
||||
private DimensionsUpdater singleBiomeDimension(ResourceKey<Biome> biomeKey)
|
||||
{
|
||||
// The original dimension list from the world preset json is provided to the DimensionsUpdater lambda here.
|
||||
// We can alter which dimensions are present by returning a different list of dimensions.
|
||||
return (registries, oldDimensions) -> {
|
||||
Holder<NoiseGeneratorSettings> overworldNoise = registries.registryOrThrow(Registries.NOISE_SETTINGS)
|
||||
.getHolderOrThrow(NoiseGeneratorSettings.OVERWORLD);
|
||||
Holder<Biome> biome = registries.registryOrThrow(Registries.BIOME).getHolderOrThrow(biomeKey);
|
||||
return oldDimensions.replaceOverworldGenerator(registries, new NoiseBasedChunkGenerator(new FixedBiomeSource(biome), overworldNoise));
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.client;
|
||||
|
||||
import java.util.Random;
|
||||
|
||||
import com.mojang.blaze3d.platform.NativeImage;
|
||||
import net.minecraft.client.renderer.texture.*;
|
||||
import net.minecraft.client.resources.metadata.animation.FrameSize;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.server.packs.resources.Resource;
|
||||
import net.minecraft.server.packs.resources.ResourceMetadata;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraftforge.client.event.RegisterTextureAtlasSpriteLoadersEvent;
|
||||
import net.minecraftforge.client.textures.ForgeTextureMetadata;
|
||||
import net.minecraftforge.client.textures.ITextureAtlasSpriteLoader;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
import net.minecraftforge.fml.loading.FMLLoader;
|
||||
import net.minecraftforge.registries.RegistryObject;
|
||||
import net.minecraftforge.registries.DeferredRegister;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
@Mod(CustomTASTest.MOD_ID)
|
||||
public class CustomTASTest {
|
||||
private static final boolean ENABLED = true;
|
||||
static final String MOD_ID = "custom_tas_test";
|
||||
private static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, MOD_ID);
|
||||
private static final RegistryObject<Item> TEST_ITEM = ITEMS.register("test_item", () -> new Item(new Item.Properties()));
|
||||
|
||||
public CustomTASTest() {
|
||||
if (ENABLED) {
|
||||
if (FMLLoader.getDist().isClient())
|
||||
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::registerTextureAtlasSpriteLoaders);
|
||||
ITEMS.register(FMLJavaModLoadingContext.get().getModEventBus());
|
||||
}
|
||||
}
|
||||
|
||||
private void registerTextureAtlasSpriteLoaders(RegisterTextureAtlasSpriteLoadersEvent event) {
|
||||
event.register("tas_loader", new TasLoader());
|
||||
}
|
||||
|
||||
private static class TasLoader implements ITextureAtlasSpriteLoader {
|
||||
@Override
|
||||
public SpriteContents loadContents(ResourceLocation name, Resource resource, FrameSize frameSize, NativeImage image, ResourceMetadata meta, ForgeTextureMetadata forgeMeta) {
|
||||
final class TASSpriteContents extends SpriteContents {
|
||||
|
||||
public TASSpriteContents(ResourceLocation name, FrameSize size, NativeImage image, ResourceMetadata meta, @Nullable ForgeTextureMetadata forgeMeta) {
|
||||
super(name, size, image, meta, forgeMeta);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull SpriteTicker createTicker() {
|
||||
return new Ticker();
|
||||
}
|
||||
|
||||
class Ticker implements SpriteTicker {
|
||||
final Random random = new Random();
|
||||
|
||||
@Override
|
||||
public void tickAndUpload(int x, int y) {
|
||||
TASSpriteContents.this.byMipLevel[0].fillRect(0, 0, 16, 16, 0xFF000000 | random.nextInt(0xFFFFFF));
|
||||
TASSpriteContents.this.uploadFirstFrame(x, y);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return new TASSpriteContents(name, frameSize, image, meta, forgeMeta);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull TextureAtlasSprite makeSprite(ResourceLocation atlasName, SpriteContents contents, int atlasWidth, int atlasHeight, int spriteX, int spriteY, int mipmapLevel) {
|
||||
final class TASSprite extends TextureAtlasSprite {
|
||||
public TASSprite(ResourceLocation atlasName, SpriteContents contents, int width, int height, int x, int y) {
|
||||
super(atlasName, contents, width, height, x, y);
|
||||
}
|
||||
}
|
||||
|
||||
return new TASSprite(atlasName, contents, atlasWidth, atlasHeight, spriteX, spriteY);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.client;
|
||||
|
||||
import com.mojang.datafixers.util.Either;
|
||||
import net.minecraft.ChatFormatting;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.gui.Font;
|
||||
import net.minecraft.client.gui.GuiGraphics;
|
||||
import net.minecraft.client.gui.components.Button;
|
||||
import net.minecraft.client.gui.screens.Screen;
|
||||
import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipComponent;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.world.InteractionHand;
|
||||
import net.minecraft.world.InteractionResultHolder;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.inventory.tooltip.TooltipComponent;
|
||||
import net.minecraft.world.item.CreativeModeTabs;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.Items;
|
||||
import net.minecraft.world.item.TooltipFlag;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraftforge.api.distmarker.Dist;
|
||||
import net.minecraftforge.client.event.RegisterClientTooltipComponentFactoriesEvent;
|
||||
import net.minecraftforge.client.event.RenderTooltipEvent;
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.event.BuildCreativeModeTabContentsEvent;
|
||||
import net.minecraftforge.eventbus.api.IEventBus;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.fml.DistExecutor;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
import net.minecraftforge.fml.loading.FMLEnvironment;
|
||||
import net.minecraftforge.registries.DeferredRegister;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
import net.minecraftforge.registries.RegistryObject;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
@Mod(CustomTooltipTest.ID)
|
||||
public class CustomTooltipTest {
|
||||
static final boolean ENABLED = true;
|
||||
static final String ID = "custom_tooltip_test";
|
||||
|
||||
private static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, ID);
|
||||
static final RegistryObject<Item> CUSTOM_ITEM = ITEMS.register("test_item", () -> new CustomItemWithTooltip(new Item.Properties()));
|
||||
|
||||
public CustomTooltipTest() {
|
||||
if (ENABLED) {
|
||||
IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus();
|
||||
if (FMLEnvironment.dist.isClient()) {
|
||||
MinecraftForge.EVENT_BUS.register(ClientEventHandler.class);
|
||||
modEventBus.register(ClientModBusEventHandler.class);
|
||||
}
|
||||
ITEMS.register(modEventBus);
|
||||
modEventBus.addListener(this::addCreative);
|
||||
}
|
||||
}
|
||||
|
||||
private void addCreative(BuildCreativeModeTabContentsEvent event) {
|
||||
if (event.getTabKey() == CreativeModeTabs.INGREDIENTS)
|
||||
event.accept(CUSTOM_ITEM);
|
||||
}
|
||||
|
||||
record CustomTooltip(int color) implements TooltipComponent {}
|
||||
|
||||
record CustomClientTooltip(CustomTooltip tooltip) implements ClientTooltipComponent {
|
||||
@Override
|
||||
public int getHeight() {
|
||||
return 10;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getWidth(Font font) {
|
||||
return 10;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void renderImage(Font font, int x, int y, GuiGraphics graphics) {
|
||||
graphics.fill(x, y, x + 10, y + 10,tooltip.color);
|
||||
}
|
||||
}
|
||||
|
||||
static class CustomItemWithTooltip extends Item {
|
||||
public CustomItemWithTooltip(Properties properties) {
|
||||
super(properties);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void appendHoverText(ItemStack stack, @Nullable Level level, List<Component> components, TooltipFlag flag) {
|
||||
super.appendHoverText(stack, level, components, flag);
|
||||
components.add(Component.literal("This is a very very very very very very long hover text that should really really be split across multiple lines.").withStyle(ChatFormatting.YELLOW));
|
||||
}
|
||||
|
||||
@Override
|
||||
public InteractionResultHolder<ItemStack> use(Level level, Player player, InteractionHand hand) {
|
||||
if (level.isClientSide)
|
||||
DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> TooltipTestScreen::show);
|
||||
return InteractionResultHolder.success(player.getItemInHand(hand));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<TooltipComponent> getTooltipImage(ItemStack stack) {
|
||||
return Optional.of(new CustomTooltip(0xFFFF0000));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static class ClientModBusEventHandler {
|
||||
@SubscribeEvent
|
||||
public static void onRegisterClientTooltipComponentFactories(RegisterClientTooltipComponentFactoriesEvent event) {
|
||||
event.register(CustomTooltip.class, CustomClientTooltip::new);
|
||||
}
|
||||
}
|
||||
|
||||
private static class ClientEventHandler {
|
||||
@SubscribeEvent
|
||||
public static void gatherTooltips(RenderTooltipEvent.GatherComponents event) {
|
||||
if (event.getItemStack().getItem() == Items.STICK)
|
||||
event.getTooltipElements().add(Either.right(new CustomTooltip(0xFF0000FF)));
|
||||
if (event.getItemStack().getItem() == Items.CLOCK)
|
||||
event.setMaxWidth(30);
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public static void preTooltip(RenderTooltipEvent.Color event) {
|
||||
if (event.getItemStack().getItem() == Items.APPLE) {
|
||||
event.setBackgroundStart(0xFF0000FF);
|
||||
event.setBackgroundEnd(0xFFFFFF00);
|
||||
event.setBorderStart(0xFFFF0000);
|
||||
event.setBorderEnd(0xFF000011);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static class TooltipTestScreen extends Screen {
|
||||
private ItemStack testStack = ItemStack.EMPTY;
|
||||
private boolean testFont = false;
|
||||
|
||||
protected TooltipTestScreen() {
|
||||
super(Component.literal("TooltipMethodTest"));
|
||||
}
|
||||
|
||||
static void show() {
|
||||
Minecraft.getInstance().setScreen(new TooltipTestScreen());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void render(GuiGraphics graphics, int mouseX, int mouseY, float partialTicks) {
|
||||
this.renderBackground(graphics, mouseX, mouseY, partialTicks);
|
||||
super.render(graphics, mouseX, mouseY, partialTicks);
|
||||
graphics.drawString(font, "* must have Stack, # must have custom font", 0, 0, 0xFFFFFF);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void init() {
|
||||
addRenderableWidget(Button.builder(Component.literal("Toggle Stack: EMPTY"), button -> {
|
||||
this.testStack = this.testStack.isEmpty() ? new ItemStack(Items.APPLE) : ItemStack.EMPTY;
|
||||
button.setMessage(Component.literal("Toggle Stack: " + (testStack.isEmpty() ? "EMPTY" : "Apple")));
|
||||
}).pos(10, 10).size(200, 20).build());
|
||||
addRenderableWidget(Button.builder(Component.literal("Toggle Font: Default"), button -> {
|
||||
this.testFont = !this.testFont;
|
||||
button.setMessage(Component.literal("Toggle Font: " + (this.testFont ? "Unicode" : "Default")));
|
||||
}).pos(220, 10).size(200, 20).build());
|
||||
|
||||
// * must have stack context
|
||||
// # must have custom font
|
||||
List<Map.Entry<String, TooltipTest>> tooltipTests = Arrays.asList(
|
||||
Map.entry(" 1 * ", this::test1),
|
||||
Map.entry(" 2 * ", this::test2),
|
||||
Map.entry(" 3 #", this::test3),
|
||||
Map.entry(" 4 *#", this::test4),
|
||||
Map.entry(" 5 ", this::test5),
|
||||
Map.entry(" 6 ", this::test6),
|
||||
Map.entry(" 7 * ", this::test7),
|
||||
Map.entry(" 8 #", this::test8),
|
||||
Map.entry(" 9 *#", this::test9),
|
||||
Map.entry("10 ", this::test10),
|
||||
Map.entry("11 ", this::test11),
|
||||
Map.entry("12 #", this::test12),
|
||||
Map.entry("13 #", this::test13),
|
||||
Map.entry("14 #", this::test14)
|
||||
);
|
||||
int x = 50;
|
||||
int y = 50;
|
||||
for (var test : tooltipTests) {
|
||||
addRenderableWidget(new Button.Builder(Component.literal(test.getKey()), button -> {})
|
||||
.bounds(x, y, 100, 20).build(b -> new Button(b) {
|
||||
@Override
|
||||
public void renderWidget(GuiGraphics graphics, int mouseX, int mouseY, float partialTick) {
|
||||
super.renderWidget(graphics, mouseX, mouseY, partialTick);
|
||||
|
||||
boolean showTooltip = this.isHovered || this.isFocused() && Minecraft.getInstance().getLastInputType().isKeyboard();
|
||||
if (showTooltip)
|
||||
test.getValue().render(graphics, mouseX, mouseY);
|
||||
}
|
||||
}));
|
||||
y+= 22;
|
||||
if (y >= height - 50) {
|
||||
y = 50;
|
||||
x += 110;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Component getTestComponent(boolean testFont) {
|
||||
return Component.literal("test").withStyle(s -> s.withFont(testFont ? Minecraft.UNIFORM_FONT : Minecraft.DEFAULT_FONT));
|
||||
}
|
||||
|
||||
private void test1(GuiGraphics graphics, int mouseX, int mouseY) {
|
||||
graphics.renderTooltip(this.font, this.testStack, mouseX, mouseY);
|
||||
}
|
||||
|
||||
// renderTooltip with List<Component> and all combinations of ItemStack/Font
|
||||
private void test2(GuiGraphics graphics, int mouseX, int mouseY) {
|
||||
graphics.renderTooltip(this.font, List.of(this.getTestComponent(false)), Optional.empty(), mouseX, mouseY);
|
||||
}
|
||||
|
||||
private void test3(GuiGraphics graphics, int mouseX, int mouseY) {
|
||||
graphics.renderTooltip(this.font, List.of(this.getTestComponent(this.testFont)), Optional.empty(), mouseX, mouseY);
|
||||
}
|
||||
|
||||
private void test4(GuiGraphics graphics, int mouseX, int mouseY) {
|
||||
graphics.renderTooltip(this.font, List.of(this.getTestComponent(this.testFont)), Optional.empty(), mouseX, mouseY);
|
||||
}
|
||||
|
||||
private void test5(GuiGraphics graphics, int mouseX, int mouseY) {
|
||||
graphics.renderTooltip(this.font, List.of(this.getTestComponent(false)), Optional.empty(), mouseX, mouseY);
|
||||
}
|
||||
|
||||
// renderTooltip with just Component
|
||||
private void test6(GuiGraphics graphics, int mouseX, int mouseY) {
|
||||
graphics.renderTooltip(this.font, this.getTestComponent(false), mouseX, mouseY);
|
||||
}
|
||||
|
||||
// renderComponentTooltip with all combinations of ItemStack/Font
|
||||
private void test7(GuiGraphics graphics, int mouseX, int mouseY) {
|
||||
graphics.renderComponentTooltip(this.font, List.of(this.getTestComponent(false)), mouseX, mouseY);
|
||||
}
|
||||
|
||||
private void test8(GuiGraphics graphics, int mouseX, int mouseY) {
|
||||
graphics.renderComponentTooltip(this.font, List.of(this.getTestComponent(this.testFont)), mouseX, mouseY);
|
||||
}
|
||||
|
||||
private void test9(GuiGraphics graphics, int mouseX, int mouseY) {
|
||||
graphics.renderComponentTooltip(this.font, List.of(this.getTestComponent(this.testFont)), mouseX, mouseY);
|
||||
}
|
||||
|
||||
private void test10(GuiGraphics graphics, int mouseX, int mouseY) {
|
||||
graphics.renderComponentTooltip(this.font, List.of(this.getTestComponent(false)), mouseX, mouseY);
|
||||
}
|
||||
|
||||
// renderTooltip with list of FormattedCharSequence
|
||||
private void test11(GuiGraphics graphics, int mouseX, int mouseY) {
|
||||
graphics.renderTooltip(this.font, List.of(this.getTestComponent(false).getVisualOrderText()), mouseX, mouseY);
|
||||
}
|
||||
|
||||
// renderTooltip with list of FormattedCharSequence and Font
|
||||
private void test12(GuiGraphics graphics, int mouseX, int mouseY) {
|
||||
graphics.renderTooltip(this.font, List.of(this.getTestComponent(this.testFont).getVisualOrderText()), mouseX, mouseY);
|
||||
}
|
||||
|
||||
// legacy ToolTip methods
|
||||
private void test13(GuiGraphics graphics, int mouseX, int mouseY) {
|
||||
graphics.renderTooltip(this.font, List.of(this.getTestComponent(this.testFont).getVisualOrderText()), mouseX, mouseY);
|
||||
}
|
||||
|
||||
private void test14(GuiGraphics graphics, int mouseX, int mouseY) {
|
||||
graphics.renderComponentTooltip(this.font, List.of(this.getTestComponent(this.testFont)), mouseX, mouseY);
|
||||
}
|
||||
}
|
||||
|
||||
private interface TooltipTest {
|
||||
void render(GuiGraphics graphics, int mouseX, int mouseY);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.client;
|
||||
|
||||
import net.minecraft.world.item.BlockItem;
|
||||
import net.minecraft.world.item.CreativeModeTabs;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.state.BlockBehaviour;
|
||||
import net.minecraft.world.level.material.MapColor;
|
||||
import net.minecraftforge.event.BuildCreativeModeTabContentsEvent;
|
||||
import net.minecraftforge.eventbus.api.IEventBus;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
import net.minecraftforge.registries.DeferredRegister;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
import net.minecraftforge.registries.RegistryObject;
|
||||
|
||||
/**
|
||||
* Test mod that demos emissivity on "elements" models.
|
||||
*/
|
||||
@Mod(EmissiveElementsTest.MOD_ID)
|
||||
public class EmissiveElementsTest
|
||||
{
|
||||
public static final String MOD_ID = "emissive_elements_test";
|
||||
private static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, MOD_ID);
|
||||
private static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, MOD_ID);
|
||||
|
||||
public static final RegistryObject<Block> TEST_BLOCK = BLOCKS.register("emissive", () -> new Block(BlockBehaviour.Properties.of().mapColor(MapColor.STONE)));
|
||||
public static final RegistryObject<Item> TEST_BLOCK_ITEM = ITEMS.register("emissive", () -> new BlockItem(TEST_BLOCK.get(), new Item.Properties()));
|
||||
|
||||
public EmissiveElementsTest()
|
||||
{
|
||||
IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus();
|
||||
BLOCKS.register(modEventBus);
|
||||
ITEMS.register(modEventBus);
|
||||
modEventBus.addListener(this::addCreative);
|
||||
}
|
||||
|
||||
private void addCreative(BuildCreativeModeTabContentsEvent event)
|
||||
{
|
||||
if (event.getTabKey() == CreativeModeTabs.BUILDING_BLOCKS)
|
||||
event.accept(TEST_BLOCK_ITEM);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.client;
|
||||
|
||||
import net.minecraft.ChatFormatting;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.gui.GuiGraphics;
|
||||
import net.minecraft.client.gui.components.Button;
|
||||
import net.minecraft.client.gui.screens.Screen;
|
||||
import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraftforge.api.distmarker.Dist;
|
||||
import net.minecraftforge.client.event.ScreenEvent;
|
||||
import net.minecraftforge.client.gui.widget.ExtendedButton;
|
||||
import net.minecraftforge.client.gui.widget.ForgeSlider;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
|
||||
import java.util.Random;
|
||||
|
||||
@Mod(GuiLayeringTest.MODID)
|
||||
public class GuiLayeringTest {
|
||||
private static final boolean ENABLED = false;
|
||||
|
||||
private static final Random RANDOM = new Random();
|
||||
public static final String MODID = "gui_layer_test";
|
||||
|
||||
@Mod.EventBusSubscriber(value = Dist.CLIENT, modid = MODID, bus = Mod.EventBusSubscriber.Bus.FORGE)
|
||||
public static class ClientEvents {
|
||||
@SuppressWarnings("unused")
|
||||
@SubscribeEvent
|
||||
public static void guiOpen(ScreenEvent.Init event) {
|
||||
if (event.getScreen() instanceof AbstractContainerScreen && ENABLED) {
|
||||
event.addListener(Button.builder(Component.literal("Test Gui Layering"), btn -> {
|
||||
Minecraft.getInstance().pushGuiLayer(new TestLayer(Component.literal("LayerScreen")));
|
||||
}).pos(2,2).size(150, 20).build());
|
||||
|
||||
event.addListener(Button.builder(Component.literal("Test Gui Normal"), btn -> {
|
||||
Minecraft.getInstance().setScreen(new TestLayer(Component.literal("LayerScreen")));
|
||||
}).pos(2, 25).size(150, 20).build());
|
||||
}
|
||||
}
|
||||
|
||||
public static class TestLayer extends Screen {
|
||||
protected TestLayer(Component titleIn) {
|
||||
super(titleIn);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void render(GuiGraphics graphics, int mouseX, int mouseY, float partialTicks) {
|
||||
this.renderBackground(graphics, mouseX, mouseY, partialTicks);
|
||||
graphics.drawString(this.font, this.title, this.width / 2, 15, 0xFFFFFF);
|
||||
super.render(graphics, mouseX, mouseY, partialTicks);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void init() {
|
||||
int buttonWidth = 150;
|
||||
int buttonHeight = 30;
|
||||
int buttonGap = 4;
|
||||
int buttonSpacing = (buttonHeight + buttonGap);
|
||||
int buttons = 3;
|
||||
|
||||
int xoff = (this.width - buttonWidth);
|
||||
int yoff = (this.height - buttonHeight - buttonSpacing * (buttons - 1));
|
||||
int cnt = 0;
|
||||
|
||||
xoff = RANDOM.nextInt(xoff);
|
||||
yoff = RANDOM.nextInt(yoff);
|
||||
|
||||
this.addRenderableWidget(Button.builder(Component.literal("Push New Layer"), this::pushLayerButton).pos(xoff, yoff + buttonSpacing * (cnt++)).size(buttonWidth, buttonHeight).build(ExtendedButton::new));
|
||||
this.addRenderableWidget(Button.builder(Component.literal("Pop Current Layer"), this::popLayerButton).pos(xoff, yoff + buttonSpacing * (cnt++)).size(buttonWidth, buttonHeight).build(ExtendedButton::new));
|
||||
this.addRenderableWidget(Button.builder(Component.literal("Close entire stack"), this::closeStack).pos(xoff, yoff + buttonSpacing * (cnt++)).size(buttonWidth, buttonHeight).build(ExtendedButton::new));
|
||||
|
||||
this.addRenderableWidget(new ForgeSlider(xoff, yoff + buttonSpacing * cnt, 50, 25, Component.literal("Val: ").withStyle(ChatFormatting.GOLD), Component.literal("some text which will be cut off"), 5, 55, 6, true));
|
||||
}
|
||||
|
||||
private void closeStack(Button button) {
|
||||
this.minecraft.setScreen(null);
|
||||
}
|
||||
|
||||
private void popLayerButton(Button button) {
|
||||
this.minecraft.popGuiLayer();
|
||||
}
|
||||
|
||||
private void pushLayerButton(Button button) {
|
||||
this.minecraft.pushGuiLayer(new TestLayer(Component.literal("LayerScreen")));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.client;
|
||||
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.player.LocalPlayer;
|
||||
import net.minecraft.world.effect.MobEffects;
|
||||
import net.minecraftforge.api.distmarker.Dist;
|
||||
import net.minecraftforge.client.event.ScreenEvent;
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.eventbus.api.Event;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.loading.FMLEnvironment;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Test mod for {@link ScreenEvent.RenderInventoryMobEffects}. When enabled, this mod forces the
|
||||
* potion indicators in the {@linkplain net.minecraft.client.gui.screens.inventory.EffectRenderingInventoryScreen
|
||||
* inventory screen} to either render in compact mode when there are less than or equal to three active effects on the player,
|
||||
* or render in classic mode if there are more than three active effects.
|
||||
*/
|
||||
@Mod(PotionSizeEventTest.MODID)
|
||||
public class PotionSizeEventTest
|
||||
{
|
||||
static final String MODID = "potion_size_event_test";
|
||||
public static final boolean ENABLED = false;
|
||||
|
||||
public PotionSizeEventTest()
|
||||
{
|
||||
if (ENABLED && FMLEnvironment.dist == Dist.CLIENT)
|
||||
{
|
||||
MinecraftForge.EVENT_BUS.register(ClientEventHandler.class);
|
||||
}
|
||||
}
|
||||
|
||||
static final class ClientEventHandler
|
||||
{
|
||||
@SubscribeEvent
|
||||
public static void onPotionSize(ScreenEvent.RenderInventoryMobEffects event)
|
||||
{
|
||||
if (!ENABLED) return;
|
||||
|
||||
final LocalPlayer player = Objects.requireNonNull(Minecraft.getInstance().player);
|
||||
|
||||
if (player.getActiveEffects().size() <= 3)
|
||||
{
|
||||
event.setCompact(true); // Force compact mode for 3 or less active effects
|
||||
}
|
||||
else
|
||||
{
|
||||
event.setCompact(false); // Force classic mode for 4 or more active effects
|
||||
}
|
||||
if (player.hasEffect(MobEffects.MOVEMENT_SLOWDOWN))
|
||||
{
|
||||
event.addHorizontalOffset(20); // Move the effect rendering to the right when slowness is enabled
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.client;
|
||||
|
||||
import com.mojang.brigadier.Command;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.gui.GuiGraphics;
|
||||
import net.minecraft.client.gui.screens.Screen;
|
||||
import net.minecraft.network.chat.Component;
|
||||
|
||||
public class TestScreen extends Screen {
|
||||
public static int open() {
|
||||
Minecraft.getInstance().setScreen(new TestScreen());
|
||||
return Command.SINGLE_SUCCESS;
|
||||
}
|
||||
|
||||
public TestScreen() {
|
||||
super(Component.literal("testscreen"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void render(GuiGraphics graphics, int mouseX, int mouseY, float partialTicks) {
|
||||
renderBackground(graphics, mouseX, mouseY, partialTicks);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.client.model;
|
||||
|
||||
import net.minecraft.client.renderer.ItemBlockRenderTypes;
|
||||
import net.minecraft.client.renderer.RenderType;
|
||||
import net.minecraft.world.item.BlockItem;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.CampfireBlock;
|
||||
import net.minecraft.world.level.block.SoundType;
|
||||
import net.minecraft.world.level.block.state.BlockBehaviour;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.block.state.properties.BlockStateProperties;
|
||||
import net.minecraft.world.level.block.state.properties.NoteBlockInstrument;
|
||||
import net.minecraft.world.level.material.MapColor;
|
||||
import net.minecraftforge.api.distmarker.Dist;
|
||||
import net.minecraftforge.eventbus.api.IEventBus;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
import net.minecraftforge.registries.DeferredRegister;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
import net.minecraftforge.registries.RegistryObject;
|
||||
|
||||
import java.util.function.ToIntFunction;
|
||||
|
||||
@Mod(CalculateNormalsTest.MODID)
|
||||
public class CalculateNormalsTest {
|
||||
public static final String MODID = "calculate_normals_test";
|
||||
public static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, MODID);
|
||||
public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, MODID);
|
||||
|
||||
public static RegistryObject<Block> fire_accurate_normals_test = BLOCKS.register("fire_accurate_normals_test", () ->
|
||||
new CampfireBlock(false, 2, BlockBehaviour.Properties.of().mapColor(MapColor.PODZOL).instrument(NoteBlockInstrument.BASS)
|
||||
.strength(2.0F).sound(SoundType.WOOD).lightLevel(litBlockEmission(10)).noOcclusion().ignitedByLava()));
|
||||
|
||||
public static RegistryObject<Item> fire_accurate_normals_test_item = ITEMS.register("fire_accurate_normals_test", () ->
|
||||
new BlockItem(fire_accurate_normals_test.get(), new Item.Properties()));
|
||||
|
||||
private static ToIntFunction<BlockState> litBlockEmission(int val) {
|
||||
return (blockState) -> {
|
||||
return blockState.getValue(BlockStateProperties.LIT) ? val : 0;
|
||||
};
|
||||
}
|
||||
|
||||
public CalculateNormalsTest() {
|
||||
IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus();
|
||||
|
||||
BLOCKS.register(modEventBus);
|
||||
ITEMS.register(modEventBus);
|
||||
}
|
||||
|
||||
@Mod.EventBusSubscriber(modid = MODID, bus = Mod.EventBusSubscriber.Bus.MOD, value = Dist.CLIENT)
|
||||
public class ClientSetup {
|
||||
@SubscribeEvent
|
||||
public static void onClientSetup(final FMLClientSetupEvent event)
|
||||
{
|
||||
ItemBlockRenderTypes.setRenderLayer(fire_accurate_normals_test.get(), RenderType.cutout());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.client.model;
|
||||
|
||||
import net.minecraft.world.item.*;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.material.MapColor;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.EquipmentSlot;
|
||||
import net.minecraft.world.item.context.BlockPlaceContext;
|
||||
import net.minecraft.world.level.block.state.StateDefinition;
|
||||
import net.minecraft.world.level.block.state.properties.BlockStateProperties;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.world.phys.shapes.CollisionContext;
|
||||
import net.minecraft.world.phys.shapes.VoxelShape;
|
||||
import net.minecraft.world.phys.shapes.Shapes;
|
||||
import net.minecraft.world.level.BlockGetter;
|
||||
import net.minecraftforge.event.BuildCreativeModeTabContentsEvent;
|
||||
import net.minecraftforge.eventbus.api.IEventBus;
|
||||
import net.minecraftforge.registries.RegistryObject;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
import net.minecraftforge.registries.DeferredRegister;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
@Mod(CompositeModelTest.MODID)
|
||||
public class CompositeModelTest
|
||||
{
|
||||
public static final String MODID = "composite_model_test";
|
||||
public static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, MODID);
|
||||
public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, MODID);
|
||||
|
||||
public static RegistryObject<Block> composite_block = BLOCKS.register("composite_block", () ->
|
||||
new Block(Block.Properties.of().mapColor(MapColor.WOOD).strength(10)) {
|
||||
@Override
|
||||
protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder)
|
||||
{
|
||||
builder.add(BlockStateProperties.HORIZONTAL_FACING);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public BlockState getStateForPlacement(BlockPlaceContext context)
|
||||
{
|
||||
return defaultBlockState().setValue(
|
||||
BlockStateProperties.HORIZONTAL_FACING, context.getHorizontalDirection()
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public VoxelShape getShape(BlockState state, BlockGetter worldIn, BlockPos pos, CollisionContext context) {
|
||||
return Shapes.or(
|
||||
box(5.6, 5.6, 5.6, 10.4, 10.4, 10.4),
|
||||
box(0, 0, 0, 4.8, 4.8, 4.8),
|
||||
box(11.2, 0, 0, 16, 4.8, 4.8),
|
||||
box(0, 0, 11.2, 4.8, 4.8, 16),
|
||||
box(11.2, 0, 11.2, 16, 4.8, 16),
|
||||
box(0, 11.2, 0, 4.8, 16, 4.8),
|
||||
box(11.2, 11.2, 0, 16, 16, 4.8),
|
||||
box(0, 11.2, 11.2, 4.8, 16, 16),
|
||||
box(11.2, 11.2, 11.2, 16, 16, 16)
|
||||
);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
public static RegistryObject<Item> composite_item = ITEMS.register("composite_block", () ->
|
||||
new BlockItem(composite_block.get(), new Item.Properties()) {
|
||||
@Override
|
||||
public boolean canEquip(ItemStack stack, EquipmentSlot armorType, Entity entity)
|
||||
{
|
||||
return armorType == EquipmentSlot.HEAD;
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
public CompositeModelTest()
|
||||
{
|
||||
IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus();
|
||||
|
||||
BLOCKS.register(modEventBus);
|
||||
ITEMS.register(modEventBus);
|
||||
modEventBus.addListener(this::addCreative);
|
||||
}
|
||||
|
||||
private void addCreative(BuildCreativeModeTabContentsEvent event)
|
||||
{
|
||||
if (event.getTabKey() == CreativeModeTabs.INGREDIENTS)
|
||||
event.accept(composite_item);
|
||||
}
|
||||
}
|
||||
+306
@@ -0,0 +1,306 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.client.model;
|
||||
|
||||
import com.mojang.blaze3d.vertex.PoseStack;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.renderer.MultiBufferSource;
|
||||
import net.minecraft.client.renderer.blockentity.BlockEntityRenderer;
|
||||
import net.minecraft.client.renderer.blockentity.BlockEntityRendererProvider;
|
||||
import net.minecraft.client.renderer.entity.ItemRenderer;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.Direction;
|
||||
import net.minecraft.data.DataGenerator;
|
||||
import net.minecraft.data.PackOutput;
|
||||
import net.minecraft.data.models.model.ModelLocationUtils;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.network.Connection;
|
||||
import net.minecraft.network.protocol.Packet;
|
||||
import net.minecraft.network.protocol.game.ClientGamePacketListener;
|
||||
import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.world.InteractionHand;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.item.*;
|
||||
import net.minecraft.world.item.context.BlockPlaceContext;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.EntityBlock;
|
||||
import net.minecraft.world.level.block.HorizontalDirectionalBlock;
|
||||
import net.minecraft.world.level.block.RenderShape;
|
||||
import net.minecraft.world.level.block.entity.BlockEntity;
|
||||
import net.minecraft.world.level.block.entity.BlockEntityType;
|
||||
import net.minecraft.world.level.block.state.BlockBehaviour;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.block.state.StateDefinition;
|
||||
import net.minecraftforge.api.distmarker.Dist;
|
||||
import net.minecraftforge.client.event.EntityRenderersEvent;
|
||||
import net.minecraftforge.client.model.generators.*;
|
||||
import net.minecraftforge.common.data.ExistingFileHelper;
|
||||
import net.minecraftforge.event.BuildCreativeModeTabContentsEvent;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
import net.minecraftforge.data.event.GatherDataEvent;
|
||||
import net.minecraftforge.registries.DeferredRegister;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
import net.minecraftforge.registries.RegisterEvent;
|
||||
import net.minecraftforge.registries.RegistryObject;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* Test mod for the custom transform types feature.
|
||||
* This test mod adds an item that should be held in the main hand, while another item is in the offhand.
|
||||
* When right-clicked on a block, the item will "hang" the stack from the offhand slot on the wall.
|
||||
* In addition, a replacement model for the stick is provided in the resources.
|
||||
* If the feature is working, the stick will have a custom transform while hanging on walls,
|
||||
* when compared to similar items such as a fishing rod.
|
||||
* Editing that model json will reflect ingame after a resource reload (F3+T).
|
||||
*/
|
||||
@Mod(CustomItemDisplayContextTest.MODID)
|
||||
public class CustomItemDisplayContextTest
|
||||
{
|
||||
public static final String MODID = "custom_transformtype_test";
|
||||
|
||||
@Mod.EventBusSubscriber(value= Dist.CLIENT, modid = MODID, bus= Mod.EventBusSubscriber.Bus.MOD)
|
||||
private static class RendererEvents
|
||||
{
|
||||
public static final ItemDisplayContext HANGING = ItemDisplayContext.create("custom_transformtype_test_hanging", new ResourceLocation("custom_transformtype_test", "hanging"), null);
|
||||
@SubscribeEvent
|
||||
public static void registerRenderers(EntityRenderersEvent.RegisterRenderers event)
|
||||
{
|
||||
event.registerBlockEntityRenderer(ITEM_HANGER_BE.get(), ItemHangerBlockEntityRenderer::new);
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public static void registerContext(final RegisterEvent event) {
|
||||
event.register(ForgeRegistries.Keys.DISPLAY_CONTEXTS, helper -> helper.register("hanging", HANGING));
|
||||
}
|
||||
|
||||
private static class ItemHangerBlockEntityRenderer
|
||||
implements BlockEntityRenderer<ItemHangerBlockEntity>
|
||||
{
|
||||
public ItemHangerBlockEntityRenderer(BlockEntityRendererProvider.Context context)
|
||||
{
|
||||
}
|
||||
|
||||
@Override
|
||||
public void render(ItemHangerBlockEntity blocken, float partialTicks, PoseStack poseStack, MultiBufferSource bufferSource, int packedLight, int overlayCoord)
|
||||
{
|
||||
var state = blocken.getBlockState();
|
||||
|
||||
if (!(state.getBlock() instanceof ItemHangerBlock)) return;
|
||||
|
||||
poseStack.pushPose();
|
||||
|
||||
poseStack.translate(0.5,0.5,0.5);
|
||||
poseStack.mulPose(state.getValue(ItemHangerBlock.FACING).getRotation());
|
||||
poseStack.translate(-0.5,-0.5,-0.5);
|
||||
|
||||
ItemRenderer itemRenderer = Minecraft.getInstance().getItemRenderer();
|
||||
|
||||
var model = itemRenderer.getModel(blocken.heldItem, blocken.getLevel(), null, 0);
|
||||
|
||||
itemRenderer.render(blocken.heldItem, HANGING, false, poseStack, bufferSource, packedLight, overlayCoord, model);
|
||||
|
||||
poseStack.popPose();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, MODID);
|
||||
public static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, MODID);
|
||||
public static final DeferredRegister<BlockEntityType<?>> BLOCK_ENTITY_TYPES = DeferredRegister.create(ForgeRegistries.BLOCK_ENTITY_TYPES, MODID);
|
||||
|
||||
public static final RegistryObject<Block>
|
||||
ITEM_HANGER_BLOCK = BLOCKS.register("item_hanger", () -> new ItemHangerBlock(BlockBehaviour.Properties.of().noCollission().noOcclusion().noLootTable()));
|
||||
public static final RegistryObject<BlockEntityType<ItemHangerBlockEntity>>
|
||||
ITEM_HANGER_BE = BLOCK_ENTITY_TYPES.register("item_hanger", () -> BlockEntityType.Builder.of(ItemHangerBlockEntity::new, ITEM_HANGER_BLOCK.get()).build(null));
|
||||
public static final RegistryObject<Item>
|
||||
ITEM_HANGER_ITEM = ITEMS.register("item_hanger", () -> new ItemHangerItem(ITEM_HANGER_BLOCK.get(), new Item.Properties()));
|
||||
|
||||
public CustomItemDisplayContextTest()
|
||||
{
|
||||
var modBus = FMLJavaModLoadingContext.get().getModEventBus();
|
||||
modBus.addListener(this::gatherData);
|
||||
BLOCKS.register(modBus);
|
||||
BLOCK_ENTITY_TYPES.register(modBus);
|
||||
ITEMS.register(modBus);
|
||||
modBus.addListener(this::addCreative);
|
||||
}
|
||||
|
||||
private void addCreative(BuildCreativeModeTabContentsEvent event)
|
||||
{
|
||||
if (event.getTabKey() == CreativeModeTabs.INGREDIENTS)
|
||||
event.accept(ITEM_HANGER_ITEM);
|
||||
}
|
||||
|
||||
public void gatherData(GatherDataEvent event)
|
||||
{
|
||||
DataGenerator gen = event.getGenerator();
|
||||
final PackOutput output = gen.getPackOutput();
|
||||
|
||||
gen.addProvider(event.includeClient(), new ItemModels(output, event.getExistingFileHelper()));
|
||||
gen.addProvider(event.includeClient(), new BlockStateModels(output, event.getExistingFileHelper()));
|
||||
}
|
||||
|
||||
public static class BlockStateModels extends BlockStateProvider
|
||||
{
|
||||
|
||||
public BlockStateModels(PackOutput output, ExistingFileHelper exFileHelper)
|
||||
{
|
||||
super(output, MODID, exFileHelper);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void registerStatesAndModels()
|
||||
{
|
||||
{
|
||||
Block block = ITEM_HANGER_BLOCK.get();
|
||||
horizontalBlock(block, models().getExistingFile(ModelLocationUtils.getModelLocation(block)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class ItemModels extends ItemModelProvider
|
||||
{
|
||||
public ItemModels(PackOutput output, ExistingFileHelper existingFileHelper)
|
||||
{
|
||||
super(output, MODID, existingFileHelper);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void registerModels()
|
||||
{
|
||||
basicItem(ITEM_HANGER_ITEM.get());
|
||||
|
||||
basicItem(Items.STICK)
|
||||
.transforms()
|
||||
.transform(RendererEvents.HANGING)
|
||||
.rotation(62, 180 - 33, 40)
|
||||
.translation(-2.25f, 1.5f, -0.25f).scale(0.48f)
|
||||
.end()
|
||||
.end();
|
||||
}
|
||||
}
|
||||
|
||||
private static class ItemHangerBlock extends HorizontalDirectionalBlock implements EntityBlock
|
||||
{
|
||||
public ItemHangerBlock(BlockBehaviour.Properties properties)
|
||||
{
|
||||
super(properties);
|
||||
registerDefaultState(getStateDefinition().any().setValue(FACING, Direction.NORTH));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {
|
||||
builder.add(FACING);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public BlockState getStateForPlacement(BlockPlaceContext ctx)
|
||||
{
|
||||
return defaultBlockState().setValue(FACING, ctx.getHorizontalDirection());
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public BlockEntity newBlockEntity(BlockPos pos, BlockState state)
|
||||
{
|
||||
return new ItemHangerBlockEntity(pos, state);
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
@Override
|
||||
public RenderShape getRenderShape(BlockState state)
|
||||
{
|
||||
return RenderShape.ENTITYBLOCK_ANIMATED;
|
||||
}
|
||||
}
|
||||
|
||||
private static class ItemHangerBlockEntity extends BlockEntity
|
||||
{
|
||||
private ItemStack heldItem;
|
||||
|
||||
public ItemHangerBlockEntity(BlockEntityType<?> type, BlockPos blockPos, BlockState blockState)
|
||||
{
|
||||
super(type, blockPos, blockState);
|
||||
}
|
||||
|
||||
public ItemHangerBlockEntity(BlockPos blockPos, BlockState blockState)
|
||||
{
|
||||
this(ITEM_HANGER_BE.get(), blockPos, blockState);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompoundTag getUpdateTag()
|
||||
{
|
||||
return saveWithoutMetadata();
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public Packet<ClientGamePacketListener> getUpdatePacket()
|
||||
{
|
||||
return ClientboundBlockEntityDataPacket.create(this, BlockEntity::getUpdateTag);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleUpdateTag(CompoundTag tag)
|
||||
{
|
||||
load(tag);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDataPacket(Connection net, ClientboundBlockEntityDataPacket pkt)
|
||||
{
|
||||
handleUpdateTag(pkt.getTag());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void saveAdditional(CompoundTag tag)
|
||||
{
|
||||
var c = new CompoundTag();
|
||||
heldItem.save(c);
|
||||
tag.put("item", c);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void load(CompoundTag tag)
|
||||
{
|
||||
var c = tag.getCompound("item");
|
||||
heldItem = ItemStack.of(c);
|
||||
}
|
||||
}
|
||||
|
||||
private static class ItemHangerItem extends BlockItem
|
||||
{
|
||||
public ItemHangerItem(Block block, Item.Properties properties)
|
||||
{
|
||||
super(block, properties);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean placeBlock(BlockPlaceContext ctx, BlockState state)
|
||||
{
|
||||
Player player = ctx.getPlayer();
|
||||
if (player == null)
|
||||
return false;
|
||||
var hand = ctx.getHand();
|
||||
if (hand != InteractionHand.MAIN_HAND)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (!super.placeBlock(ctx, state))
|
||||
return false;
|
||||
if (ctx.getLevel().getBlockEntity(ctx.getClickedPos()) instanceof ItemHangerBlockEntity be)
|
||||
{
|
||||
be.heldItem = player.getItemInHand(InteractionHand.OFF_HAND);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.client.model;
|
||||
|
||||
import net.minecraft.world.item.CreativeModeTabs;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraftforge.event.BuildCreativeModeTabContentsEvent;
|
||||
import net.minecraftforge.eventbus.api.IEventBus;
|
||||
import net.minecraftforge.registries.RegistryObject;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
import net.minecraftforge.registries.DeferredRegister;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
|
||||
@Mod(DynBucketModelTest.MODID)
|
||||
public class DynBucketModelTest
|
||||
{
|
||||
public static final boolean ENABLE = false; // TODO fix
|
||||
public static final String MODID = "dyn_bucket_model_test";
|
||||
public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, MODID);
|
||||
|
||||
public static final RegistryObject<Item> DRIP_BUCKET = ITEMS.register("drip_bucket", () -> new Item(new Item.Properties()));
|
||||
public static final RegistryObject<Item> LAVA_OBSIDIAN = ITEMS.register("lava_obsidian", () -> new Item(new Item.Properties()));
|
||||
|
||||
public DynBucketModelTest()
|
||||
{
|
||||
if (ENABLE)
|
||||
{
|
||||
IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus();
|
||||
ITEMS.register(modEventBus);
|
||||
modEventBus.addListener(this::addCreative);
|
||||
}
|
||||
}
|
||||
|
||||
private void addCreative(BuildCreativeModeTabContentsEvent event)
|
||||
{
|
||||
if (event.getTabKey() == CreativeModeTabs.INGREDIENTS)
|
||||
{
|
||||
event.accept(DRIP_BUCKET);
|
||||
event.accept(LAVA_OBSIDIAN);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.client.model;
|
||||
|
||||
import com.mojang.math.Transformation;
|
||||
import net.minecraft.client.renderer.RenderType;
|
||||
import net.minecraft.client.renderer.block.model.BakedQuad;
|
||||
import net.minecraft.client.resources.model.BakedModel;
|
||||
import net.minecraft.client.resources.model.ModelResourceLocation;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.Direction;
|
||||
import net.minecraft.util.Mth;
|
||||
import net.minecraft.util.RandomSource;
|
||||
import net.minecraft.world.InteractionHand;
|
||||
import net.minecraft.world.InteractionResult;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.item.BlockItem;
|
||||
import net.minecraft.world.item.CreativeModeTabs;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.EntityBlock;
|
||||
import net.minecraft.world.level.block.entity.BlockEntity;
|
||||
import net.minecraft.world.level.block.entity.BlockEntityType;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.material.MapColor;
|
||||
import net.minecraft.world.phys.BlockHitResult;
|
||||
import net.minecraftforge.api.distmarker.Dist;
|
||||
import net.minecraftforge.client.event.ModelEvent;
|
||||
import net.minecraftforge.client.model.BakedModelWrapper;
|
||||
import net.minecraftforge.client.model.IQuadTransformer;
|
||||
import net.minecraftforge.client.model.QuadTransformers;
|
||||
import net.minecraftforge.client.model.data.ModelData;
|
||||
import net.minecraftforge.client.model.data.ModelProperty;
|
||||
import net.minecraftforge.event.BuildCreativeModeTabContentsEvent;
|
||||
import net.minecraftforge.eventbus.api.IEventBus;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
import net.minecraftforge.registries.DeferredRegister;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
import net.minecraftforge.registries.RegistryObject;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.joml.Quaternionf;
|
||||
import org.joml.Vector3f;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Test mod that demos most Forge-provided model loaders in a single block + item, as well as in-JSON render states
|
||||
* and the refactored immutable ModelData managed by the client level. The block can be found in the decoration tab.
|
||||
* <p>
|
||||
* Additionally, some fields in the JSON have deprecated names, so those MUST be updated in 1.20, or the model will
|
||||
* break. They have all been annotated accordingly.
|
||||
* <ul>
|
||||
* <li>As a block: Composite loader, using 3 child element models, each with a different render type,
|
||||
* some using vanilla's elements loader, and some Forge's</li>
|
||||
* <li>In the right hand: Fluid container with lava (emissive)</li>
|
||||
* <li>In the left hand: Multi-layer item with chainmail chestplate + emissive bow</li>
|
||||
* </ul>
|
||||
* <p>
|
||||
* Clicking on the upper half of the block will make the model move up by a bit, and clicking on the lower half will
|
||||
* move it down.
|
||||
*/
|
||||
@Mod(MegaModelTest.MOD_ID)
|
||||
public class MegaModelTest
|
||||
{
|
||||
public static final String MOD_ID = "mega_model_test";
|
||||
private static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, MOD_ID);
|
||||
private static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, MOD_ID);
|
||||
private static final DeferredRegister<BlockEntityType<?>> BLOCK_ENTITIES = DeferredRegister.create(ForgeRegistries.BLOCK_ENTITY_TYPES, MOD_ID);
|
||||
|
||||
private static final String REG_NAME = "test_block";
|
||||
public static final RegistryObject<Block> TEST_BLOCK = BLOCKS.register(REG_NAME, TestBlock::new);
|
||||
public static final RegistryObject<Item> TEST_BLOCK_ITEM = ITEMS.register(REG_NAME, () -> new BlockItem(TEST_BLOCK.get(), new Item.Properties()));
|
||||
public static final RegistryObject<BlockEntityType<?>> TEST_BLOCK_ENTITY = BLOCK_ENTITIES.register(REG_NAME, () -> new BlockEntityType<>(
|
||||
TestBlock.Entity::new, Set.of(TEST_BLOCK.get()), null
|
||||
));
|
||||
|
||||
public MegaModelTest()
|
||||
{
|
||||
IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus();
|
||||
BLOCKS.register(modEventBus);
|
||||
ITEMS.register(modEventBus);
|
||||
BLOCK_ENTITIES.register(modEventBus);
|
||||
modEventBus.addListener(this::addCreative);
|
||||
}
|
||||
|
||||
private void addCreative(BuildCreativeModeTabContentsEvent event)
|
||||
{
|
||||
if (event.getTabKey() == CreativeModeTabs.BUILDING_BLOCKS)
|
||||
event.accept(TEST_BLOCK_ITEM);
|
||||
}
|
||||
|
||||
@Mod.EventBusSubscriber(value = Dist.CLIENT, modid = MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD)
|
||||
public static class ClientEvents
|
||||
{
|
||||
|
||||
@SubscribeEvent
|
||||
public static void onModelBakingCompleted(ModelEvent.ModifyBakingResult event)
|
||||
{
|
||||
var name = new ModelResourceLocation(MOD_ID, REG_NAME, "");
|
||||
event.getModels().computeIfPresent(name, (n, m) -> new TransformingModelWrapper(m));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static class TestBlock extends Block implements EntityBlock
|
||||
{
|
||||
public TestBlock()
|
||||
{
|
||||
super(Properties.of().mapColor(MapColor.STONE));
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public BlockEntity newBlockEntity(BlockPos pos, BlockState state)
|
||||
{
|
||||
return new Entity(pos, state);
|
||||
}
|
||||
|
||||
@Override
|
||||
public InteractionResult use(BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit)
|
||||
{
|
||||
var entity = level.getBlockEntity(pos);
|
||||
if (entity instanceof Entity e)
|
||||
{
|
||||
e.y += Mth.sign(hit.getLocation().y - pos.getY() - 0.5);
|
||||
e.requestModelDataUpdate();
|
||||
level.sendBlockUpdated(pos, state, state, 8);
|
||||
return InteractionResult.sidedSuccess(level.isClientSide());
|
||||
}
|
||||
return super.use(state, level, pos, player, hand, hit);
|
||||
}
|
||||
|
||||
public static class Entity extends BlockEntity
|
||||
{
|
||||
public int y = 0;
|
||||
|
||||
public Entity(BlockPos pos, BlockState state)
|
||||
{
|
||||
super(TEST_BLOCK_ENTITY.get(), pos, state);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull ModelData getModelData()
|
||||
{
|
||||
return ModelData.builder().with(TestData.PROPERTY, new TestData(new Transformation(
|
||||
new Vector3f(0, y * 0.2f, 0),
|
||||
new Quaternionf(1f, 1f, 1f, 1f),
|
||||
Transformation.identity().getScale(),
|
||||
new Quaternionf(1f, 1f, 1f, 1f)
|
||||
))).build();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private record TestData(Transformation transform)
|
||||
{
|
||||
public static final ModelProperty<TestData> PROPERTY = new ModelProperty<>();
|
||||
}
|
||||
|
||||
private static class TransformingModelWrapper extends BakedModelWrapper<BakedModel>
|
||||
{
|
||||
public TransformingModelWrapper(BakedModel originalModel)
|
||||
{
|
||||
super(originalModel);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull List<BakedQuad> getQuads(@Nullable BlockState state, @Nullable Direction side, @NotNull RandomSource rand, @NotNull ModelData data, @Nullable RenderType renderType)
|
||||
{
|
||||
var quads = super.getQuads(state, side, rand, data, renderType);
|
||||
if (!data.has(TestData.PROPERTY))
|
||||
return quads;
|
||||
return QuadTransformers.applying(data.get(TestData.PROPERTY).transform()).process(quads);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.client.model;
|
||||
|
||||
import net.minecraft.world.item.CreativeModeTabs;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.material.MapColor;
|
||||
import net.minecraft.client.renderer.RenderType;
|
||||
import net.minecraft.client.renderer.ItemBlockRenderTypes;
|
||||
import net.minecraft.world.item.BlockItem;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraftforge.event.BuildCreativeModeTabContentsEvent;
|
||||
import net.minecraftforge.eventbus.api.IEventBus;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
import net.minecraftforge.registries.DeferredRegister;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
import net.minecraftforge.registries.RegistryObject;
|
||||
|
||||
@Mod(MultiLayerModelTest.MODID)
|
||||
public class MultiLayerModelTest
|
||||
{
|
||||
private static final boolean ENABLED = true;
|
||||
public static final String MODID = "forgedebugmultilayermodel";
|
||||
public static final String VERSION = "0.0";
|
||||
|
||||
private static final String blockName = "test_layer_block";
|
||||
|
||||
private static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, MODID);
|
||||
private static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, MODID);
|
||||
private static final RegistryObject<Block> TEST_BLOCK = BLOCKS.register(blockName, () -> new Block(Block.Properties.of().mapColor(MapColor.WOOD).noOcclusion()));
|
||||
private static final RegistryObject<Item> TEST_BLOCK_ITEM = ITEMS.register(blockName, () -> new BlockItem(TEST_BLOCK.get(), new Item.Properties()));
|
||||
|
||||
public MultiLayerModelTest()
|
||||
{
|
||||
if (!ENABLED)
|
||||
return;
|
||||
|
||||
IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus();
|
||||
BLOCKS.register(modEventBus);
|
||||
ITEMS.register(modEventBus);
|
||||
modEventBus.addListener(this::clientSetup);
|
||||
modEventBus.addListener(this::addCreative);
|
||||
}
|
||||
|
||||
private void addCreative(BuildCreativeModeTabContentsEvent event)
|
||||
{
|
||||
if (event.getTabKey() == CreativeModeTabs.INGREDIENTS)
|
||||
event.accept(TEST_BLOCK);
|
||||
}
|
||||
|
||||
private void clientSetup(FMLClientSetupEvent event)
|
||||
{
|
||||
ItemBlockRenderTypes.setRenderLayer(TEST_BLOCK.get(), (layer) -> {
|
||||
return layer == RenderType.solid() || layer == RenderType.translucent();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.client.model;
|
||||
|
||||
import com.google.gson.JsonDeserializationContext;
|
||||
import com.google.gson.JsonObject;
|
||||
import net.minecraft.client.resources.model.ModelBaker;
|
||||
import net.minecraft.data.PackOutput;
|
||||
import net.minecraft.world.item.*;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.material.MapColor;
|
||||
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
|
||||
import net.minecraft.data.DataGenerator;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.EquipmentSlot;
|
||||
import net.minecraft.world.level.block.state.StateDefinition;
|
||||
import net.minecraft.world.level.block.state.properties.BlockStateProperties;
|
||||
import net.minecraft.core.Direction;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.world.phys.shapes.CollisionContext;
|
||||
import net.minecraft.world.phys.shapes.VoxelShape;
|
||||
import net.minecraft.world.level.BlockGetter;
|
||||
import net.minecraftforge.client.event.ModelEvent;
|
||||
import net.minecraftforge.client.model.IModelBuilder;
|
||||
import net.minecraftforge.client.model.geometry.IGeometryBakingContext;
|
||||
import net.minecraftforge.client.model.geometry.IGeometryLoader;
|
||||
import net.minecraftforge.client.model.generators.BlockModelBuilder;
|
||||
import net.minecraftforge.client.model.generators.BlockStateProvider;
|
||||
import net.minecraftforge.client.model.generators.ConfiguredModel;
|
||||
import net.minecraftforge.client.model.generators.ItemModelProvider;
|
||||
import net.minecraftforge.client.model.generators.loaders.ItemLayerModelBuilder;
|
||||
import net.minecraftforge.client.model.generators.loaders.ObjModelBuilder;
|
||||
import net.minecraftforge.client.model.generators.loaders.SeparateTransformsModelBuilder;
|
||||
import net.minecraftforge.client.model.geometry.SimpleUnbakedGeometry;
|
||||
import net.minecraftforge.client.model.pipeline.QuadBakingVertexConsumer;
|
||||
import net.minecraftforge.common.data.ExistingFileHelper;
|
||||
import net.minecraftforge.event.BuildCreativeModeTabContentsEvent;
|
||||
import net.minecraftforge.eventbus.api.IEventBus;
|
||||
import net.minecraftforge.registries.RegistryObject;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.data.event.GatherDataEvent;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
import net.minecraftforge.registries.DeferredRegister;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.function.Function;
|
||||
|
||||
import net.minecraft.client.resources.model.ModelState;
|
||||
import net.minecraft.world.item.context.BlockPlaceContext;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
@Mod(NewModelLoaderTest.MODID)
|
||||
public class NewModelLoaderTest
|
||||
{
|
||||
public static final String MODID = "new_model_loader_test";
|
||||
public static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, MODID);
|
||||
public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, MODID);
|
||||
|
||||
public static RegistryObject<Block> obj_block = BLOCKS.register("obj_block", () ->
|
||||
new Block(Block.Properties.of().mapColor(MapColor.WOOD).strength(10)) {
|
||||
@Override
|
||||
protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder)
|
||||
{
|
||||
builder.add(BlockStateProperties.HORIZONTAL_FACING);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public BlockState getStateForPlacement(BlockPlaceContext context)
|
||||
{
|
||||
return defaultBlockState().setValue(
|
||||
BlockStateProperties.HORIZONTAL_FACING, context.getHorizontalDirection()
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public VoxelShape getShape(BlockState state, BlockGetter worldIn, BlockPos pos, CollisionContext context)
|
||||
{
|
||||
return Block.box(2,2,2,14,14,14);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
public static RegistryObject<Item> obj_item = ITEMS.register("obj_block", () ->
|
||||
new BlockItem(obj_block.get(), new Item.Properties()) {
|
||||
@Override
|
||||
public boolean canEquip(ItemStack stack, EquipmentSlot armorType, Entity entity)
|
||||
{
|
||||
return armorType == EquipmentSlot.HEAD;
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
public static RegistryObject<Item> custom_transforms = ITEMS.register("custom_transforms", () ->
|
||||
new Item(new Item.Properties())
|
||||
);
|
||||
|
||||
public static RegistryObject<Item> custom_vanilla_loader = ITEMS.register("custom_vanilla_loader", () ->
|
||||
new Item(new Item.Properties())
|
||||
);
|
||||
|
||||
public static RegistryObject<Item> custom_loader = ITEMS.register("custom_loader", () ->
|
||||
new Item(new Item.Properties())
|
||||
);
|
||||
|
||||
public static RegistryObject<Item> item_layers = ITEMS.register("item_layers", () ->
|
||||
new Item(new Item.Properties())
|
||||
);
|
||||
|
||||
public static RegistryObject<Item> separate_perspective = ITEMS.register("separate_perspective", () ->
|
||||
new Item(new Item.Properties())
|
||||
);
|
||||
|
||||
public NewModelLoaderTest()
|
||||
{
|
||||
IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus();
|
||||
|
||||
BLOCKS.register(modEventBus);
|
||||
ITEMS.register(modEventBus);
|
||||
|
||||
modEventBus.addListener(this::modelRegistry);
|
||||
modEventBus.addListener(this::datagen);
|
||||
modEventBus.addListener(this::addCreative);
|
||||
}
|
||||
|
||||
private void addCreative(BuildCreativeModeTabContentsEvent event)
|
||||
{
|
||||
if (event.getTabKey() == CreativeModeTabs.INGREDIENTS)
|
||||
{
|
||||
Arrays.asList(
|
||||
obj_item,
|
||||
custom_transforms,
|
||||
custom_vanilla_loader,
|
||||
custom_loader,
|
||||
item_layers,
|
||||
separate_perspective
|
||||
).forEach(event::accept);
|
||||
}
|
||||
}
|
||||
|
||||
public void modelRegistry(ModelEvent.RegisterGeometryLoaders event)
|
||||
{
|
||||
event.register("custom_loader", new TestLoader());
|
||||
}
|
||||
|
||||
static class TestLoader implements IGeometryLoader<TestModel>
|
||||
{
|
||||
@Override
|
||||
public TestModel read(JsonObject jsonObject, JsonDeserializationContext deserializationContext)
|
||||
{
|
||||
return new TestModel();
|
||||
}
|
||||
}
|
||||
|
||||
static class TestModel extends SimpleUnbakedGeometry<TestModel>
|
||||
{
|
||||
@Override
|
||||
protected void addQuads(IGeometryBakingContext owner, IModelBuilder<?> modelBuilder, ModelBaker baker, Function<net.minecraft.client.resources.model.Material, TextureAtlasSprite> spriteGetter, ModelState modelTransform, ResourceLocation modelLocation) {
|
||||
TextureAtlasSprite texture = spriteGetter.apply(owner.getMaterial("particle"));
|
||||
|
||||
var quadBaker = new QuadBakingVertexConsumer.Buffered();
|
||||
|
||||
quadBaker.setDirection(Direction.UP);
|
||||
quadBaker.setSprite(texture);
|
||||
|
||||
quadBaker.vertex(0, 1, 0.5f).color(255, 255, 255, 255).uv(texture.getU(0), texture.getV(0)).uv2(0).normal(0, 0, 0).endVertex();
|
||||
quadBaker.vertex(0, 0, 0.5f).color(255, 255, 255, 255).uv(texture.getU(0), texture.getV(16)).uv2(0).normal(0, 0, 0).endVertex();
|
||||
quadBaker.vertex(1, 0, 0.5f).color(255, 255, 255, 255).uv(texture.getU(16), texture.getV(16)).uv2(0).normal(0, 0, 0).endVertex();
|
||||
quadBaker.vertex(1, 1, 0.5f).color(255, 255, 255, 255).uv(texture.getU(16), texture.getV(0)).uv2(0).normal(0, 0, 0).endVertex();
|
||||
|
||||
modelBuilder.addUnculledFace(quadBaker.getQuad());
|
||||
}
|
||||
}
|
||||
|
||||
private void datagen(GatherDataEvent event)
|
||||
{
|
||||
DataGenerator gen = event.getGenerator();
|
||||
final PackOutput output = gen.getPackOutput();
|
||||
|
||||
// Let blockstate provider see generated item models by passing its existing file helper
|
||||
ItemModelProvider itemModels = new ItemModels(output, event.getExistingFileHelper());
|
||||
gen.addProvider(event.includeClient(), itemModels);
|
||||
gen.addProvider(event.includeClient(), new BlockStates(output, itemModels.existingFileHelper));
|
||||
}
|
||||
|
||||
public static class ItemModels extends ItemModelProvider
|
||||
{
|
||||
public ItemModels(PackOutput output, ExistingFileHelper existingFileHelper)
|
||||
{
|
||||
super(output, MODID, existingFileHelper);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void registerModels()
|
||||
{
|
||||
withExistingParent(NewModelLoaderTest.item_layers.getId().getPath(), "forge:item/default")
|
||||
.texture("particle", "minecraft:block/red_stained_glass")
|
||||
.texture("layer0", "minecraft:item/coal")
|
||||
.texture("layer1", "minecraft:item/stick")
|
||||
.customLoader(ItemLayerModelBuilder::begin)
|
||||
.emissive(15, 15, 1)
|
||||
.end();
|
||||
withExistingParent(NewModelLoaderTest.separate_perspective.getId().getPath(), "forge:item/default")
|
||||
.customLoader(SeparateTransformsModelBuilder::begin)
|
||||
.base(nested().parent(getExistingFile(mcLoc("minecraft:item/coal"))))
|
||||
.perspective(ItemDisplayContext.GUI, nested().parent(getExistingFile(mcLoc("minecraft:item/snowball"))))
|
||||
.perspective(ItemDisplayContext.FIRST_PERSON_LEFT_HAND, nested().parent(getExistingFile(mcLoc("minecraft:item/bone"))))
|
||||
.end();
|
||||
}
|
||||
}
|
||||
|
||||
public static class BlockStates extends BlockStateProvider
|
||||
{
|
||||
public BlockStates(PackOutput output, ExistingFileHelper exFileHelper)
|
||||
{
|
||||
super(output, MODID, exFileHelper);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void registerStatesAndModels()
|
||||
{
|
||||
BlockModelBuilder model = models()
|
||||
.getBuilder(NewModelLoaderTest.obj_block.getId().getPath())
|
||||
.customLoader(ObjModelBuilder::begin)
|
||||
.modelLocation(new ResourceLocation("new_model_loader_test:models/item/sugar_glider.obj"))
|
||||
.flipV(true)
|
||||
.end()
|
||||
.texture("qr", "minecraft:block/oak_planks")
|
||||
.texture("particle", "#qr");
|
||||
getVariantBuilder(NewModelLoaderTest.obj_block.get())
|
||||
.partialState()
|
||||
.with(BlockStateProperties.HORIZONTAL_FACING, Direction.EAST)
|
||||
.addModels(new ConfiguredModel(model, 0, 90, false))
|
||||
.partialState()
|
||||
.with(BlockStateProperties.HORIZONTAL_FACING, Direction.WEST)
|
||||
.addModels(new ConfiguredModel(model, 0, 270, false))
|
||||
.partialState()
|
||||
.with(BlockStateProperties.HORIZONTAL_FACING, Direction.NORTH)
|
||||
.addModels(new ConfiguredModel(model))
|
||||
.partialState()
|
||||
.with(BlockStateProperties.HORIZONTAL_FACING, Direction.SOUTH)
|
||||
.addModels(new ConfiguredModel(model, 0, 180, false))
|
||||
.partialState();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.client.model;
|
||||
|
||||
import java.util.List;
|
||||
import net.minecraft.client.renderer.RenderType;
|
||||
import net.minecraft.util.RandomSource;
|
||||
import net.minecraft.world.item.CreativeModeTabs;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.material.MapColor;
|
||||
import net.minecraft.client.renderer.block.model.BakedQuad;
|
||||
import net.minecraft.client.resources.model.BakedModel;
|
||||
import net.minecraft.client.renderer.block.model.ItemOverrides;
|
||||
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
|
||||
import net.minecraft.world.item.BlockItem;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.core.Direction;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import com.mojang.math.Transformation;
|
||||
import net.minecraftforge.api.distmarker.Dist;
|
||||
import net.minecraftforge.client.event.ModelEvent;
|
||||
import net.minecraftforge.client.model.IQuadTransformer;
|
||||
import net.minecraftforge.client.model.IDynamicBakedModel;
|
||||
import net.minecraftforge.client.model.QuadTransformers;
|
||||
import net.minecraftforge.client.model.data.ModelData;
|
||||
import net.minecraftforge.common.util.TransformationHelper;
|
||||
import net.minecraftforge.event.BuildCreativeModeTabContentsEvent;
|
||||
import net.minecraftforge.eventbus.api.IEventBus;
|
||||
import net.minecraftforge.fml.DistExecutor;
|
||||
import net.minecraftforge.registries.RegistryObject;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
import net.minecraftforge.registries.DeferredRegister;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.joml.Quaternionf;
|
||||
import org.joml.Vector3f;
|
||||
|
||||
@Mod(TRSRTransformerTest.MODID)
|
||||
public class TRSRTransformerTest {
|
||||
public static final String MODID = "trsr_transformer_test";
|
||||
private static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, MODID);
|
||||
private static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, MODID);
|
||||
|
||||
private static final RegistryObject<Block> TEST_BLOCK = BLOCKS.register("test", () -> new Block(Block.Properties.of().mapColor(MapColor.STONE)));
|
||||
@SuppressWarnings("unused")
|
||||
private static final RegistryObject<Item> TEST_ITEM = ITEMS.register("test", () -> new BlockItem(TEST_BLOCK.get(), new Item.Properties()));
|
||||
|
||||
public TRSRTransformerTest() {
|
||||
final IEventBus mod = FMLJavaModLoadingContext.get().getModEventBus();
|
||||
DistExecutor.runWhenOn(Dist.CLIENT, () -> () -> mod.addListener(this::onModelBake));
|
||||
BLOCKS.register(mod);
|
||||
ITEMS.register(mod);
|
||||
mod.addListener(this::addCreative);
|
||||
}
|
||||
|
||||
private void addCreative(BuildCreativeModeTabContentsEvent event)
|
||||
{
|
||||
if (event.getTabKey() == CreativeModeTabs.BUILDING_BLOCKS)
|
||||
event.accept(TEST_ITEM);
|
||||
}
|
||||
|
||||
public void onModelBake(ModelEvent.ModifyBakingResult e) {
|
||||
for (ResourceLocation id : e.getModels().keySet()) {
|
||||
if (MODID.equals(id.getNamespace()) && "test".equals(id.getPath())) {
|
||||
e.getModels().put(id, new MyBakedModel(e.getModels().get(id)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class MyBakedModel implements IDynamicBakedModel {
|
||||
private final BakedModel base;
|
||||
|
||||
public MyBakedModel(BakedModel base) {
|
||||
this.base = base;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<BakedQuad> getQuads(@Nullable BlockState state, @Nullable Direction side, RandomSource rand, ModelData data, @Nullable RenderType renderType) {
|
||||
Quaternionf rot = TransformationHelper.quatFromXYZ(new Vector3f(0, 45, 0), true);
|
||||
Vector3f translation = new Vector3f(0, 0.33f, 0);
|
||||
|
||||
Transformation trans = new Transformation(translation, rot, null, null).blockCenterToCorner();
|
||||
var transformer = QuadTransformers.applying(trans);
|
||||
|
||||
return transformer.process(base.getQuads(state, side, rand, data, renderType));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean useAmbientOcclusion() {
|
||||
return base.useAmbientOcclusion();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isGui3d() {
|
||||
return base.isGui3d();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean usesBlockLight() {
|
||||
return base.usesBlockLight();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isCustomRenderer() {
|
||||
return base.isCustomRenderer();
|
||||
}
|
||||
|
||||
@Override
|
||||
public TextureAtlasSprite getParticleIcon() {
|
||||
return base.getParticleIcon();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemOverrides getOverrides() {
|
||||
return base.getOverrides();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
@ParametersAreNonnullByDefault
|
||||
@MethodsReturnNonnullByDefault
|
||||
package net.minecraftforge.debug.client.model;
|
||||
|
||||
import javax.annotation.ParametersAreNonnullByDefault;
|
||||
import net.minecraft.MethodsReturnNonnullByDefault;
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.client.rendering;
|
||||
|
||||
import com.mojang.blaze3d.systems.RenderSystem;
|
||||
import com.mojang.blaze3d.vertex.PoseStack;
|
||||
|
||||
import net.minecraft.client.gui.Font;
|
||||
import net.minecraft.client.gui.GuiGraphics;
|
||||
import net.minecraft.client.renderer.entity.ItemRenderer;
|
||||
import net.minecraft.util.Mth;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.Items;
|
||||
import net.minecraftforge.api.distmarker.Dist;
|
||||
import net.minecraftforge.client.IItemDecorator;
|
||||
import net.minecraftforge.client.event.RegisterItemDecorationsEvent;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
|
||||
@Mod(CustomItemDecorationsTest.MOD_ID)
|
||||
public class CustomItemDecorationsTest
|
||||
{
|
||||
public static final String MOD_ID = "custom_item_decorations_test";
|
||||
private static final boolean ENABLED = true;
|
||||
|
||||
public CustomItemDecorationsTest() { }
|
||||
|
||||
@Mod.EventBusSubscriber(modid = CustomItemDecorationsTest.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD, value = Dist.CLIENT)
|
||||
public static class ClientEvents
|
||||
{
|
||||
@SubscribeEvent
|
||||
public static void onRegisterItemDecorations(final RegisterItemDecorationsEvent event)
|
||||
{
|
||||
if (ENABLED)
|
||||
event.register(Items.EGG, new StackSizeDurabilityBar());
|
||||
}
|
||||
}
|
||||
|
||||
private static class StackSizeDurabilityBar implements IItemDecorator
|
||||
{
|
||||
@Override
|
||||
public boolean render(GuiGraphics graphics, Font font, ItemStack stack, int xOffset, int yOffset)
|
||||
{
|
||||
RenderSystem.disableBlend();
|
||||
float f = Math.max(0.0F, (float)stack.getCount() / stack.getMaxStackSize());
|
||||
int i = Math.round((float)stack.getCount() * 13.0F / stack.getMaxStackSize());
|
||||
int j = Mth.hsvToRgb(f / 3.0F, 1f, 1f) | 0xFF000000;
|
||||
int x = xOffset + 2;
|
||||
int y = yOffset + 13;
|
||||
graphics.pose().pushPose();
|
||||
graphics.pose().translate(0.0F, 0.0F, ItemRenderer.ITEM_COUNT_BLIT_OFFSET + 1F);
|
||||
graphics.fill(x, y, x + 13, y + 2, 0xFF000000);
|
||||
graphics.fill(x, y, x + i, y + 1, j);
|
||||
graphics.pose().popPose();
|
||||
RenderSystem.enableBlend();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.client.rendering;
|
||||
|
||||
import com.mojang.blaze3d.vertex.BufferBuilder;
|
||||
import com.mojang.blaze3d.vertex.Tesselator;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.multiplayer.ClientLevel;
|
||||
import net.minecraft.client.particle.*;
|
||||
import net.minecraft.client.renderer.texture.TextureManager;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.level.block.Blocks;
|
||||
import net.minecraftforge.api.distmarker.Dist;
|
||||
import net.minecraftforge.event.TickEvent;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
|
||||
@Mod(CustomParticleTypeTest.MOD_ID)
|
||||
public class CustomParticleTypeTest
|
||||
{
|
||||
public static final String MOD_ID = "custom_particle_type_test";
|
||||
private static final boolean ENABLED = true;
|
||||
|
||||
public CustomParticleTypeTest() { }
|
||||
|
||||
@Mod.EventBusSubscriber(modid = CustomParticleTypeTest.MOD_ID, bus = Mod.EventBusSubscriber.Bus.FORGE, value = Dist.CLIENT)
|
||||
public static class ClientEvents
|
||||
{
|
||||
private static final ParticleRenderType CUSTOM_TYPE = new ParticleRenderType()
|
||||
{
|
||||
@Override
|
||||
public void begin(BufferBuilder buffer, TextureManager texMgr)
|
||||
{
|
||||
Minecraft.getInstance().gameRenderer.lightTexture().turnOnLightLayer();
|
||||
ParticleRenderType.TERRAIN_SHEET.begin(buffer, texMgr);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void end(Tesselator tess)
|
||||
{
|
||||
ParticleRenderType.TERRAIN_SHEET.end(tess);
|
||||
}
|
||||
};
|
||||
private static final ParticleRenderType CUSTOM_TYPE_TWO = new ParticleRenderType()
|
||||
{
|
||||
@Override
|
||||
public void begin(BufferBuilder buffer, TextureManager texMgr)
|
||||
{
|
||||
Minecraft.getInstance().gameRenderer.lightTexture().turnOnLightLayer();
|
||||
ParticleRenderType.TERRAIN_SHEET.begin(buffer, texMgr);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void end(Tesselator tess)
|
||||
{
|
||||
ParticleRenderType.TERRAIN_SHEET.end(tess);
|
||||
}
|
||||
};
|
||||
|
||||
private static class CustomParticle extends TerrainParticle
|
||||
{
|
||||
public CustomParticle(ClientLevel level, double x, double y, double z)
|
||||
{
|
||||
super(level, x, y, z, 0, .25, 0, Blocks.OBSIDIAN.defaultBlockState());
|
||||
}
|
||||
|
||||
@Override
|
||||
public ParticleRenderType getRenderType()
|
||||
{
|
||||
return CUSTOM_TYPE;
|
||||
}
|
||||
}
|
||||
private static class AnotherCustomParticle extends TerrainParticle
|
||||
{
|
||||
public AnotherCustomParticle(ClientLevel level, double x, double y, double z)
|
||||
{
|
||||
super(level, x, y, z, 0, .25, 0, Blocks.SAND.defaultBlockState());
|
||||
}
|
||||
|
||||
@Override
|
||||
public ParticleRenderType getRenderType()
|
||||
{
|
||||
return CUSTOM_TYPE_TWO;
|
||||
}
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public static void onClientTick(final TickEvent.ClientTickEvent event)
|
||||
{
|
||||
if (!ENABLED || event.phase != TickEvent.Phase.START) { return; }
|
||||
|
||||
ClientLevel level = Minecraft.getInstance().level;
|
||||
Player player = Minecraft.getInstance().player;
|
||||
if (player == null || level == null || !player.isShiftKeyDown()) { return; }
|
||||
|
||||
Minecraft.getInstance().particleEngine.add(new CustomParticle(level, player.getX(), player.getY(), player.getZ()));
|
||||
Minecraft.getInstance().particleEngine.add(new AnotherCustomParticle(level, player.getX(), player.getY(), player.getZ()));
|
||||
}
|
||||
}
|
||||
}
|
||||
+200
@@ -0,0 +1,200 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.client.rendering;
|
||||
|
||||
import com.mojang.blaze3d.vertex.PoseStack;
|
||||
import com.mojang.blaze3d.vertex.VertexConsumer;
|
||||
import net.minecraft.client.model.EntityModel;
|
||||
import net.minecraft.client.model.geom.ModelLayerLocation;
|
||||
import net.minecraft.client.model.geom.ModelPart;
|
||||
import net.minecraft.client.model.geom.PartPose;
|
||||
import net.minecraft.client.model.geom.builders.*;
|
||||
import net.minecraft.client.renderer.MultiBufferSource;
|
||||
import net.minecraft.client.renderer.entity.EntityRendererProvider;
|
||||
import net.minecraft.client.renderer.entity.LivingEntityRenderer;
|
||||
import net.minecraft.client.renderer.entity.layers.RenderLayer;
|
||||
import net.minecraft.client.renderer.texture.OverlayTexture;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.world.entity.*;
|
||||
import net.minecraft.world.entity.ai.attributes.Attributes;
|
||||
import net.minecraft.world.entity.monster.Monster;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraftforge.api.distmarker.Dist;
|
||||
import net.minecraftforge.client.event.EntityRenderersEvent;
|
||||
import net.minecraftforge.event.entity.EntityAttributeCreationEvent;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
import net.minecraftforge.registries.ObjectHolder;
|
||||
import net.minecraftforge.registries.RegisterEvent;
|
||||
|
||||
import java.util.Collections;
|
||||
|
||||
@Mod("entity_renderer_events_test")
|
||||
@Mod.EventBusSubscriber(modid="entity_renderer_events_test", bus= Mod.EventBusSubscriber.Bus.MOD)
|
||||
public class EntityRendererEventsTest
|
||||
{
|
||||
private static final ResourceLocation MY_ENTITY = new ResourceLocation("entity_renderer_events_test", "test_entity");
|
||||
|
||||
@ObjectHolder(registryName = "entity_type", value = "entity_renderer_events_test:test_entity")
|
||||
public static EntityType<MyEntity> MY_ENTITY_TYPE;
|
||||
|
||||
@SubscribeEvent
|
||||
public static void entityRegistry(RegisterEvent event)
|
||||
{
|
||||
if (event.getRegistryKey().equals(ForgeRegistries.Keys.ENTITY_TYPES))
|
||||
{
|
||||
event.register(ForgeRegistries.Keys.ENTITY_TYPES, MY_ENTITY, () -> EntityType.Builder.of(MyEntity::new, MobCategory.MONSTER).build("test_entity"));
|
||||
}
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public static void entityRegistry(EntityAttributeCreationEvent event)
|
||||
{
|
||||
event.put(MY_ENTITY_TYPE, Monster.createMonsterAttributes().add(Attributes.MAX_HEALTH, 1.0D).build());
|
||||
}
|
||||
|
||||
@Mod.EventBusSubscriber(value= Dist.CLIENT, bus= Mod.EventBusSubscriber.Bus.MOD)
|
||||
private static class EntityRenderEventsTestClientModStuff
|
||||
{
|
||||
private static final ModelLayerLocation MAIN_LAYER = new ModelLayerLocation(MY_ENTITY, "main");
|
||||
private static final ModelLayerLocation OUTER_LAYER = new ModelLayerLocation(MY_ENTITY, "main");
|
||||
private static final ModelLayerLocation ADDED_LAYER = new ModelLayerLocation(MY_ENTITY, "added");
|
||||
|
||||
@SubscribeEvent
|
||||
public static void layerDefinitions(EntityRenderersEvent.RegisterLayerDefinitions event)
|
||||
{
|
||||
event.registerLayerDefinition(MAIN_LAYER, MyEntityModel::createMainLayer);
|
||||
event.registerLayerDefinition(OUTER_LAYER, () -> MyEntityModel.createLayer(new CubeDeformation(1.0f)));
|
||||
event.registerLayerDefinition(ADDED_LAYER, () -> MyEntityModel.createLayer(new CubeDeformation(2.0f)));
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public static void entityRenderers(EntityRenderersEvent.RegisterRenderers event)
|
||||
{
|
||||
event.registerEntityRenderer(MY_ENTITY_TYPE, MyEntityRenderer::new);
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public static void entityLayers(EntityRenderersEvent.AddLayers event)
|
||||
{
|
||||
MyEntityRenderer renderer = event.getRenderer(MY_ENTITY_TYPE);
|
||||
renderer.addLayer(new MyEntityLayer(renderer, new MyEntityModel(event.getEntityModels().bakeLayer(ADDED_LAYER)), 0.5f));
|
||||
}
|
||||
|
||||
private static class MyEntityModel extends EntityModel<MyEntity>
|
||||
{
|
||||
public static final String BODY = "body";
|
||||
public static final String HEAD = "head";
|
||||
|
||||
public static LayerDefinition createMainLayer()
|
||||
{
|
||||
return createLayer(CubeDeformation.NONE);
|
||||
}
|
||||
|
||||
public static LayerDefinition createLayer(CubeDeformation deformation)
|
||||
{
|
||||
MeshDefinition definition = new MeshDefinition();
|
||||
PartDefinition root = definition.getRoot();
|
||||
root.addOrReplaceChild(BODY, CubeListBuilder.create().addBox(-4,0,-4,4,10,4, deformation), PartPose.ZERO);
|
||||
root.addOrReplaceChild(HEAD, CubeListBuilder.create().addBox(-2,10,-2,2,4,2, deformation), PartPose.ZERO);
|
||||
return LayerDefinition.create(definition, 64, 32);
|
||||
}
|
||||
|
||||
private final ModelPart headRenderer;
|
||||
private final ModelPart bodyRenderer;
|
||||
|
||||
public MyEntityModel(ModelPart modelPart)
|
||||
{
|
||||
this.headRenderer = modelPart.getChild(HEAD);
|
||||
this.bodyRenderer = modelPart.getChild(BODY);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setupAnim(MyEntity p_102618_, float p_102619_, float p_102620_, float p_102621_, float p_102622_, float p_102623_)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void renderToBuffer(PoseStack poseStack, VertexConsumer vertexConsumer, int packedLightIn, int packedOverlayIn, float red, float green, float blue, float alpha)
|
||||
{
|
||||
headRenderer.render(poseStack, vertexConsumer, packedLightIn, packedOverlayIn, red, green, blue, alpha);
|
||||
bodyRenderer.render(poseStack, vertexConsumer, packedLightIn, packedOverlayIn, red, green, blue, alpha);
|
||||
}
|
||||
}
|
||||
|
||||
private static class MyEntityRenderer extends LivingEntityRenderer<MyEntity, MyEntityModel>
|
||||
{
|
||||
private static final ResourceLocation TEXTURE = new ResourceLocation("entity_renderer_events_test:textures/entity/test_entity.png");
|
||||
|
||||
public MyEntityRenderer(EntityRendererProvider.Context context)
|
||||
{
|
||||
super(context, new MyEntityModel(context.bakeLayer(MAIN_LAYER)), 1.0f);
|
||||
addLayer(new MyEntityLayer(this, new MyEntityModel(context.bakeLayer(OUTER_LAYER)), 0.1f));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResourceLocation getTextureLocation(MyEntity p_114482_)
|
||||
{
|
||||
return TEXTURE;
|
||||
}
|
||||
}
|
||||
|
||||
private static class MyEntityLayer extends RenderLayer<MyEntity, MyEntityModel>
|
||||
{
|
||||
private final MyEntityModel model;
|
||||
private final float r;
|
||||
|
||||
public MyEntityLayer(MyEntityRenderer renderer, MyEntityModel model, float r)
|
||||
{
|
||||
super(renderer);
|
||||
this.model = model;
|
||||
this.r = r;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void render(PoseStack poseStack, MultiBufferSource bufferSource, int lightness, MyEntity entity, float limbSwing, float limbSwingAmount, float partialTicks, float ageInTicks, float netHeadYaw, float headPitch)
|
||||
{
|
||||
VertexConsumer vertexConsumer = bufferSource.getBuffer(this.getParentModel().renderType(this.getTextureLocation(entity)));
|
||||
model.renderToBuffer(poseStack, vertexConsumer, lightness, OverlayTexture.NO_OVERLAY, r, 1.0f, 1.0f, 1.0f);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static class MyEntity extends LivingEntity
|
||||
{
|
||||
protected MyEntity(EntityType<? extends LivingEntity> p_20966_, Level p_20967_)
|
||||
{
|
||||
super(p_20966_, p_20967_);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Iterable<ItemStack> getArmorSlots()
|
||||
{
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack getItemBySlot(EquipmentSlot p_21127_)
|
||||
{
|
||||
return ItemStack.EMPTY;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setItemSlot(EquipmentSlot p_21036_, ItemStack p_21037_)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public HumanoidArm getMainArm()
|
||||
{
|
||||
return HumanoidArm.LEFT;
|
||||
}
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.client.rendering;
|
||||
|
||||
import net.minecraft.client.gui.screens.TitleScreen;
|
||||
import net.minecraftforge.client.ForgeRenderTypes;
|
||||
import net.minecraftforge.client.event.ScreenEvent.Render;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.api.distmarker.Dist;
|
||||
|
||||
@Mod(LinearTextTextureFilteringTest.MODID)
|
||||
@Mod.EventBusSubscriber(value = Dist.CLIENT)
|
||||
public class LinearTextTextureFilteringTest
|
||||
{
|
||||
public static final String MODID = "text_linear_filtering_test";
|
||||
static final boolean ENABLED = false;
|
||||
|
||||
@SubscribeEvent
|
||||
public static void onGuiRenderPre(Render.Pre event)
|
||||
{
|
||||
if (ENABLED && event.getScreen() instanceof TitleScreen)
|
||||
{
|
||||
ForgeRenderTypes.enableTextTextureLinearFiltering = true;
|
||||
}
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public static void onGuiRenderPost(Render.Post event)
|
||||
{
|
||||
if (ENABLED && event.getScreen() instanceof TitleScreen)
|
||||
{
|
||||
ForgeRenderTypes.enableTextTextureLinearFiltering = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.client.rendering;
|
||||
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.world.entity.animal.Cow;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.ChatFormatting;
|
||||
import net.minecraftforge.client.event.RenderNameTagEvent;
|
||||
import net.minecraftforge.eventbus.api.Event;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.api.distmarker.Dist;
|
||||
|
||||
|
||||
@Mod(NameplateRenderingEventTest.MODID)
|
||||
@Mod.EventBusSubscriber(value = Dist.CLIENT)
|
||||
public class NameplateRenderingEventTest
|
||||
{
|
||||
public static final String MODID = "nameplate_render_test";
|
||||
static final boolean ENABLED = false;
|
||||
|
||||
@SubscribeEvent
|
||||
public static void onNameplateRender(RenderNameTagEvent event)
|
||||
{
|
||||
|
||||
if(!ENABLED)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if(event.getEntity() instanceof Cow)
|
||||
{
|
||||
event.setContent(Component.literal("Evil Cow").withStyle(ChatFormatting.RED));
|
||||
event.setResult(Event.Result.ALLOW);
|
||||
}
|
||||
|
||||
if(event.getEntity() instanceof Player)
|
||||
{
|
||||
event.setContent(event.getEntity().getDisplayName().copy().withStyle(ChatFormatting.GOLD));
|
||||
}
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.client.rendering;
|
||||
|
||||
import net.minecraftforge.fml.loading.FMLLoader;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
|
||||
import net.minecraftforge.client.event.RenderLevelStageEvent;
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
|
||||
@Mod("render_level_stages_test")
|
||||
public class RenderLevelStagesTest
|
||||
{
|
||||
public static final org.apache.logging.log4j.Logger LOGGER = LogManager.getLogger();
|
||||
|
||||
public RenderLevelStagesTest()
|
||||
{
|
||||
if (FMLLoader.getDist().isClient())
|
||||
{
|
||||
MinecraftForge.EVENT_BUS.addListener(this::onRenderLevelStages);
|
||||
}
|
||||
}
|
||||
|
||||
private int count = 0;
|
||||
public void onRenderLevelStages(RenderLevelStageEvent event)
|
||||
{
|
||||
if(count < 10)
|
||||
{
|
||||
LOGGER.info("Render Stage: " + event.getStage());
|
||||
if(event.getStage() == RenderLevelStageEvent.Stage.AFTER_WEATHER)
|
||||
count++;
|
||||
}
|
||||
}
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.client.rendering;
|
||||
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.world.item.Items;
|
||||
import net.minecraft.world.InteractionResult;
|
||||
import net.minecraftforge.api.distmarker.Dist;
|
||||
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
|
||||
@Mod(RenderLocalPlayerTest.MODID)
|
||||
@Mod.EventBusSubscriber(value = Dist.CLIENT)
|
||||
public class RenderLocalPlayerTest
|
||||
{
|
||||
public static final String MODID = "render_local_player_test";
|
||||
static final boolean ENABLED = false;
|
||||
|
||||
@SubscribeEvent
|
||||
public static void onItemRightClickEntity(final PlayerInteractEvent.EntityInteract event)
|
||||
{
|
||||
if (ENABLED && event.getItemStack().getItem() == Items.STICK)
|
||||
{
|
||||
Minecraft mc = Minecraft.getInstance();
|
||||
if (mc.getCameraEntity() == mc.player)
|
||||
{
|
||||
mc.setCameraEntity(event.getTarget());
|
||||
|
||||
event.setCancellationResult(InteractionResult.SUCCESS);
|
||||
event.setCanceled(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public static void onItemRightClick(final PlayerInteractEvent.RightClickItem event)
|
||||
{
|
||||
if (ENABLED && event.getItemStack().getItem() == Items.STICK)
|
||||
{
|
||||
Minecraft mc = Minecraft.getInstance();
|
||||
if (mc.getCameraEntity() != mc.player)
|
||||
{
|
||||
mc.setCameraEntity(mc.player);
|
||||
|
||||
event.setCancellationResult(InteractionResult.SUCCESS);
|
||||
event.setCanceled(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.client.rendering;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import com.mojang.blaze3d.vertex.PoseStack;
|
||||
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.renderer.LightTexture;
|
||||
import net.minecraft.client.renderer.RenderType;
|
||||
import net.minecraft.client.renderer.texture.OverlayTexture;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.server.packs.resources.ResourceManager;
|
||||
import net.minecraft.server.packs.resources.SimplePreparableReloadListener;
|
||||
import net.minecraft.util.profiling.ProfilerFiller;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
import net.minecraftforge.api.distmarker.Dist;
|
||||
import net.minecraftforge.client.ForgeRenderTypes;
|
||||
import net.minecraftforge.client.event.ModelEvent;
|
||||
import net.minecraftforge.client.event.RegisterClientReloadListenersEvent;
|
||||
import net.minecraftforge.client.event.RenderLevelStageEvent;
|
||||
import net.minecraftforge.client.event.RenderLevelStageEvent.Stage;
|
||||
import net.minecraftforge.client.model.geometry.StandaloneGeometryBakingContext;
|
||||
import net.minecraftforge.client.model.data.ModelData;
|
||||
import net.minecraftforge.client.model.obj.ObjLoader;
|
||||
import net.minecraftforge.client.model.obj.ObjModel;
|
||||
import net.minecraftforge.client.model.renderable.BakedModelRenderable;
|
||||
import net.minecraftforge.client.model.renderable.CompositeRenderable;
|
||||
import net.minecraftforge.client.model.renderable.IRenderable;
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
import net.minecraftforge.fml.loading.FMLEnvironment;
|
||||
import org.joml.Matrix4f;
|
||||
|
||||
/**
|
||||
* This mod is testing the use of {@link RenderLevelStageEvent} and is a modifaction of a pre-existing test mod that used the old
|
||||
* RenderLevelLastEvent. To restore the old behavior, set {@link #USE_LEVEL_RENDERER_STAGE} to false.
|
||||
*
|
||||
* When you enter a world, there should be 6 sugar gliders rendering at (0, 120, 0) that test the various stages in {@link RenderLevelStageEvent}.
|
||||
* From left to right (with the sugar gliders facing you) they represent {@link Stage#AFTER_SKY}, {@link Stage#AFTER_SOLID_BLOCKS},
|
||||
* {@link Stage#AFTER_TRANSLUCENT_BLOCKS}, {@link Stage#AFTER_TRIPWIRE_BLOCKS}, {@link Stage#AFTER_PARTICLES}, and {@link Stage#AFTER_WEATHER}.
|
||||
* Due to how weather modifies the projection matrix, it's sugar glider will be positioned weirdly. Below each sugar gliders is a render of
|
||||
* blue stained glass to test translucency with fabulous graphics. {@link Stage#AFTER_PARTICLES} will render the stained glass using
|
||||
* {@link ForgeRenderTypes#TRANSLUCENT_ON_PARTICLES_TARGET}.
|
||||
*/
|
||||
@Mod(RenderableTest.MODID)
|
||||
public class RenderableTest
|
||||
{
|
||||
public static final String MODID = "renderable_test";
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
|
||||
public static final boolean ENABLED = false; // Renders at (0, 120, 0)
|
||||
public RenderableTest()
|
||||
{
|
||||
if (ENABLED)
|
||||
{
|
||||
if (FMLEnvironment.dist == Dist.CLIENT)
|
||||
{
|
||||
Client.init();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static class Client
|
||||
{
|
||||
private static ResourceLocation MODEL_LOC = new ResourceLocation("minecraft:block/blue_stained_glass");
|
||||
|
||||
private static IRenderable<CompositeRenderable.Transforms> renderable;
|
||||
private static IRenderable<ModelData> bakedRenderable;
|
||||
|
||||
public static void init()
|
||||
{
|
||||
var modBus = FMLJavaModLoadingContext.get().getModEventBus();
|
||||
var forgeBus = MinecraftForge.EVENT_BUS;
|
||||
modBus.addListener(Client::registerModels);
|
||||
modBus.addListener(Client::registerReloadListeners);
|
||||
modBus.addListener(Client::registerStage);
|
||||
forgeBus.addListener(Client::renderStage);
|
||||
}
|
||||
|
||||
private static void registerModels(ModelEvent.RegisterAdditional event)
|
||||
{
|
||||
event.register(MODEL_LOC);
|
||||
}
|
||||
|
||||
public static void registerReloadListeners(RegisterClientReloadListenersEvent event)
|
||||
{
|
||||
event.registerReloadListener(new SimplePreparableReloadListener<ObjModel>()
|
||||
{
|
||||
@Override
|
||||
protected ObjModel prepare(ResourceManager resourceManager, ProfilerFiller profilerFiller)
|
||||
{
|
||||
var settings = new ObjModel.ModelSettings(
|
||||
new ResourceLocation("new_model_loader_test:models/item/sugar_glider.obj"),
|
||||
false,
|
||||
true,
|
||||
true,
|
||||
false,
|
||||
null
|
||||
);
|
||||
return ObjLoader.INSTANCE.loadModel(settings);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void apply(ObjModel model, ResourceManager resourceManager, ProfilerFiller profilerFiller)
|
||||
{
|
||||
var config = StandaloneGeometryBakingContext.create(Map.of(
|
||||
"#qr", new ResourceLocation("minecraft:block/quartz_block_top")
|
||||
));
|
||||
renderable = model.bakeRenderable(config);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static void registerStage(RenderLevelStageEvent.RegisterStageEvent event)
|
||||
{
|
||||
var stage = event.register(new ResourceLocation(MODID, "test_stage"), null);
|
||||
LOGGER.info("Registered RenderLevelStageEvent.Stage: {}", stage);
|
||||
}
|
||||
|
||||
private static void renderStage(RenderLevelStageEvent event)
|
||||
{
|
||||
int xOffset = -1;
|
||||
var stage = event.getStage();
|
||||
if (stage == Stage.AFTER_SKY)
|
||||
xOffset = 0;
|
||||
else if (stage == Stage.AFTER_SOLID_BLOCKS)
|
||||
xOffset = 1;
|
||||
else if (stage == Stage.AFTER_TRANSLUCENT_BLOCKS)
|
||||
xOffset = 2;
|
||||
else if (stage == Stage.AFTER_TRIPWIRE_BLOCKS)
|
||||
xOffset = 3;
|
||||
else if (stage == Stage.AFTER_PARTICLES)
|
||||
xOffset = 4;
|
||||
else if (stage == Stage.AFTER_WEATHER)
|
||||
xOffset = 5;
|
||||
|
||||
Vec3 cam = event.getCamera().getPosition();
|
||||
if (xOffset > -1)
|
||||
render(stage, event.getPoseStack(), event.getRenderTick(), event.getPartialTick(), cam.x, cam.y, cam.z, xOffset);
|
||||
}
|
||||
|
||||
private static void render(Stage stage, PoseStack poseStack, int renderTick, float partialTick, double camX, double camY, double camZ, int xOffset)
|
||||
{
|
||||
double x = camX, y = camY, z = camZ;
|
||||
if (!BlockPos.containing(0, y, 0).closerThan(BlockPos.containing(x, y, z), 100))
|
||||
return;
|
||||
|
||||
var profiler = Minecraft.getInstance().getProfiler();
|
||||
profiler.push("renderable_test");
|
||||
if (bakedRenderable == null)
|
||||
{
|
||||
bakedRenderable = BakedModelRenderable.of(MODEL_LOC).withModelDataContext();
|
||||
}
|
||||
|
||||
var bufferSource = Minecraft.getInstance().renderBuffers().bufferSource();
|
||||
|
||||
double time = renderTick + partialTick;
|
||||
|
||||
var map = ImmutableMap.<String, Matrix4f>builder();
|
||||
|
||||
var left = new Matrix4f();
|
||||
left.rotation((float)Math.sin(time * 0.4) * 0.1f, 0, 0, 1);
|
||||
map.put("object_1", left);
|
||||
|
||||
var right = new Matrix4f();
|
||||
right.rotation(-(float)Math.sin(time * 0.4) * 0.1f, 0, 0, 1);
|
||||
map.put("object_9", right);
|
||||
|
||||
var transforms = CompositeRenderable.Transforms.of(map.build());
|
||||
|
||||
poseStack.pushPose();
|
||||
poseStack.translate(0 - x + xOffset, 120 - y, 0 - z);
|
||||
renderable.render(poseStack, bufferSource, RenderType::entitySolid, LightTexture.FULL_BRIGHT, OverlayTexture.NO_OVERLAY, partialTick, transforms);
|
||||
|
||||
poseStack.translate(0, -1, 0);
|
||||
bakedRenderable.render(poseStack, bufferSource, texture -> getRenderType(stage, texture), LightTexture.FULL_BRIGHT, OverlayTexture.NO_OVERLAY, partialTick, ModelData.EMPTY);
|
||||
poseStack.popPose();
|
||||
|
||||
bufferSource.endBatch();
|
||||
profiler.pop();
|
||||
}
|
||||
|
||||
private static RenderType getRenderType(Stage stage, ResourceLocation texture)
|
||||
{
|
||||
if (stage == Stage.AFTER_PARTICLES)
|
||||
return ForgeRenderTypes.TRANSLUCENT_ON_PARTICLES_TARGET.get();
|
||||
return RenderType.entityTranslucent(texture);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.client.rendering;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
|
||||
import com.mojang.blaze3d.vertex.DefaultVertexFormat;
|
||||
import com.mojang.logging.LogUtils;
|
||||
|
||||
import net.minecraft.client.renderer.ShaderInstance;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraftforge.api.distmarker.Dist;
|
||||
import net.minecraftforge.client.event.RegisterShadersEvent;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.fml.DistExecutor;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
import net.minecraftforge.fml.loading.FMLEnvironment;
|
||||
|
||||
@Mod(ShaderResourcesTest.MODID)
|
||||
public class ShaderResourcesTest
|
||||
{
|
||||
private static Logger LOGGER;
|
||||
|
||||
public static final String MODID = "shader_resources_test";
|
||||
private static final boolean ENABLE = false;
|
||||
|
||||
public ShaderResourcesTest()
|
||||
{
|
||||
if (ENABLE)
|
||||
{
|
||||
LOGGER = LogUtils.getLogger();
|
||||
|
||||
DistExecutor.unsafeRunWhenOn(Dist.CLIENT,() -> ClientInit::new);
|
||||
}
|
||||
}
|
||||
|
||||
private class ClientInit
|
||||
{
|
||||
public ClientInit()
|
||||
{
|
||||
final var modEventBus = FMLJavaModLoadingContext.get().getModEventBus();
|
||||
|
||||
modEventBus.addListener(ClientInit::registerShaders);
|
||||
}
|
||||
|
||||
public static void registerShaders(final RegisterShadersEvent event)
|
||||
{
|
||||
if (!ENABLE)
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
event.registerShader(
|
||||
new ShaderInstance(
|
||||
event.getResourceProvider(),
|
||||
new ResourceLocation(MODID, "vertex_cubemap"),
|
||||
DefaultVertexFormat.POSITION),
|
||||
shader ->
|
||||
{
|
||||
LOGGER.info("Completely loaded shader {} with no issues", shader.getName());
|
||||
});
|
||||
|
||||
LOGGER.info("Loaded registered shaders with no exceptions");
|
||||
}
|
||||
catch (IOException e)
|
||||
{
|
||||
LOGGER.error("Failed to load shaders with exception", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.client.rendering;
|
||||
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraftforge.eventbus.api.Event;
|
||||
import net.minecraftforge.fml.DeferredWorkQueue;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
|
||||
@Mod("stencil_enable_test")
|
||||
public class StencilEnableTest {
|
||||
public static boolean ENABLED = true;
|
||||
|
||||
public StencilEnableTest() {
|
||||
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::clientSetup);
|
||||
}
|
||||
|
||||
private void clientSetup(FMLClientSetupEvent event) {
|
||||
if (ENABLED)
|
||||
event.enqueueWork(() -> Minecraft.getInstance().getMainRenderTarget().enableStencil());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
@ParametersAreNonnullByDefault
|
||||
@MethodsReturnNonnullByDefault
|
||||
package net.minecraftforge.debug.client.rendering;
|
||||
|
||||
import javax.annotation.ParametersAreNonnullByDefault;
|
||||
import net.minecraft.MethodsReturnNonnullByDefault;
|
||||
@@ -0,0 +1,52 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.command;
|
||||
|
||||
import net.minecraft.commands.Commands;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.event.RegisterCommandsEvent;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.server.command.EnumArgument;
|
||||
|
||||
import com.mojang.brigadier.arguments.StringArgumentType;
|
||||
|
||||
@Mod("enum_argument_test")
|
||||
public class EnumArgumentTest
|
||||
{
|
||||
public static final boolean ENABLE = true;
|
||||
|
||||
public EnumArgumentTest()
|
||||
{
|
||||
if (ENABLE)
|
||||
MinecraftForge.EVENT_BUS.register(this);
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public void registerCommands(RegisterCommandsEvent event)
|
||||
{
|
||||
event.getDispatcher().register(Commands.literal("enumargumenttest")
|
||||
.then(Commands.argument("string", StringArgumentType.string())
|
||||
.executes(context -> {
|
||||
context.getSource().sendSuccess(() -> Component.literal("string: " + StringArgumentType.getString(context, "string")), false);
|
||||
|
||||
return 1;
|
||||
}))
|
||||
.then(Commands.argument("enum", EnumArgument.enumArgument(ExampleEnum.class))
|
||||
.executes(context -> {
|
||||
context.getSource()
|
||||
.sendSuccess(() -> Component.literal("enum: " + context.getArgument("enum", ExampleEnum.class)), false);
|
||||
|
||||
return 1;
|
||||
})));
|
||||
}
|
||||
|
||||
public enum ExampleEnum
|
||||
{
|
||||
A, B
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
@ParametersAreNonnullByDefault
|
||||
@MethodsReturnNonnullByDefault
|
||||
package net.minecraftforge.debug.command;
|
||||
|
||||
import net.minecraft.MethodsReturnNonnullByDefault;
|
||||
|
||||
import javax.annotation.ParametersAreNonnullByDefault;
|
||||
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.entity;
|
||||
|
||||
import net.minecraft.world.entity.ai.attributes.Attribute;
|
||||
import net.minecraft.world.entity.ai.attributes.RangedAttribute;
|
||||
import net.minecraftforge.event.entity.EntityAttributeModificationEvent;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
import net.minecraftforge.registries.RegistryObject;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
import net.minecraftforge.registries.DeferredRegister;
|
||||
|
||||
@Mod("add_entity_attribute_test")
|
||||
public class AddEntityAttributeTest {
|
||||
public static final boolean ENABLE = true;
|
||||
private static final DeferredRegister<Attribute> ATTRIBUTES = DeferredRegister.create(ForgeRegistries.ATTRIBUTES, "add_entity_attribute_test");
|
||||
public static final RegistryObject<Attribute> TEST_ATTR = ATTRIBUTES.register("test_attr", () -> new RangedAttribute("forge.test_attr", 1.0D, 0.0D, 1024.0D).setSyncable(true));
|
||||
|
||||
public AddEntityAttributeTest() {
|
||||
if (ENABLE) {
|
||||
ATTRIBUTES.register(FMLJavaModLoadingContext.get().getModEventBus());
|
||||
FMLJavaModLoadingContext.get().getModEventBus().register(this);
|
||||
}
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public void entityAttributeSetup(EntityAttributeModificationEvent event) {
|
||||
event.getTypes().forEach(entityType -> {
|
||||
if (!event.has(entityType, TEST_ATTR.get())){
|
||||
event.add(entityType, TEST_ATTR.get());
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.entity;
|
||||
|
||||
import net.minecraft.world.entity.MobCategory;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
|
||||
@Mod("create_entity_classification_test")
|
||||
public class CreateEntityClassificationTest
|
||||
{
|
||||
public static MobCategory test = MobCategory.create("TEST", "test", 1, true, true, 128);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.entity;
|
||||
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.event.entity.EntityTeleportEvent;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
@Mod("entity_teleport_event_test")
|
||||
public class EntityTeleportEventTest
|
||||
{
|
||||
public static final boolean ENABLE = true;
|
||||
public static final Logger LOGGER = LogManager.getLogger();
|
||||
|
||||
public EntityTeleportEventTest()
|
||||
{
|
||||
if (ENABLE)
|
||||
MinecraftForge.EVENT_BUS.register(this);
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public void entityTeleport(EntityTeleportEvent event)
|
||||
{
|
||||
LOGGER.info("{} teleporting from {} to {}", event.getEntity(), event.getPrev(), event.getTarget());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.entity;
|
||||
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.LivingEntity;
|
||||
import net.minecraft.world.entity.projectile.FishingHook;
|
||||
import net.minecraft.world.phys.EntityHitResult;
|
||||
import net.minecraft.world.phys.HitResult;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.event.entity.ProjectileImpactEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
|
||||
@Mod("fishing_bobber_event_test")
|
||||
public class FishingBobberEventTest
|
||||
{
|
||||
public static final boolean ENABLE = true;
|
||||
|
||||
public FishingBobberEventTest()
|
||||
{
|
||||
if (ENABLE)
|
||||
{
|
||||
MinecraftForge.EVENT_BUS.register(this);
|
||||
MinecraftForge.EVENT_BUS.addListener(FishingBobberEventTest::handleImpact);
|
||||
}
|
||||
}
|
||||
|
||||
public static void handleImpact(ProjectileImpactEvent event)
|
||||
{
|
||||
if(!(event.getProjectile() instanceof FishingHook fishingHook)) return;
|
||||
HitResult trace = event.getRayTraceResult();
|
||||
if (trace.getType() == HitResult.Type.ENTITY)
|
||||
{
|
||||
Vec3 vector3d = fishingHook.getDeltaMovement().multiply(1.0D, 0.0D, 1.0D).normalize().scale(0.6);
|
||||
if (vector3d.lengthSqr() > 0.0D)
|
||||
{
|
||||
Entity entity = ((EntityHitResult) trace).getEntity();
|
||||
if (entity instanceof LivingEntity)
|
||||
{
|
||||
entity.push(vector3d.x, 0.3D, vector3d.z);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.entity;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
import net.minecraft.tags.BiomeTags;
|
||||
import net.minecraft.world.entity.ai.attributes.AttributeInstance;
|
||||
import net.minecraft.world.item.CreativeModeTabs;
|
||||
import net.minecraftforge.common.ForgeMod;
|
||||
import net.minecraftforge.event.BuildCreativeModeTabContentsEvent;
|
||||
import net.minecraftforge.registries.DeferredRegister;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
import net.minecraftforge.registries.RegistryObject;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
import com.google.common.collect.Multimap;
|
||||
|
||||
import net.minecraft.client.multiplayer.ClientLevel;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.LivingEntity;
|
||||
import net.minecraft.world.entity.ai.attributes.Attribute;
|
||||
import net.minecraft.world.entity.ai.attributes.AttributeModifier;
|
||||
import net.minecraft.world.entity.ai.attributes.AttributeModifier.Operation;
|
||||
import net.minecraft.world.entity.EquipmentSlot;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.item.Rarity;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.event.TickEvent;
|
||||
import net.minecraftforge.eventbus.api.IEventBus;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
|
||||
import net.minecraft.world.item.Item.Properties;
|
||||
|
||||
@Mod(GravityAttributeTest.MODID)
|
||||
public class GravityAttributeTest
|
||||
{
|
||||
public static final boolean ENABLE = false;
|
||||
public static final String MODID = "gravity_attribute_test";
|
||||
private static Logger logger = LogManager.getLogger(MODID);
|
||||
private int ticks;
|
||||
private static final UUID REDUCED_GRAVITY_ID = UUID.fromString("DEB06000-7979-4242-8888-00000DEB0600");
|
||||
private static final AttributeModifier REDUCED_GRAVITY = (new AttributeModifier(REDUCED_GRAVITY_ID, "Reduced gravity", (double)-0.80, Operation.MULTIPLY_TOTAL));
|
||||
private static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, MODID);
|
||||
private static final RegistryObject<Item> TEST_ITEM = ITEMS.register("gravity_stick", () -> new ItemGravityStick(new Properties().rarity(Rarity.RARE)));
|
||||
|
||||
|
||||
public GravityAttributeTest()
|
||||
{
|
||||
if (ENABLE)
|
||||
{
|
||||
MinecraftForge.EVENT_BUS.register(this);
|
||||
IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus();
|
||||
modEventBus.register(this);
|
||||
ITEMS.register(modEventBus);
|
||||
modEventBus.addListener(this::addCreative);
|
||||
}
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public void worldTick(TickEvent.LevelTickEvent event)
|
||||
{
|
||||
if (!event.level.isClientSide)
|
||||
{
|
||||
if (ticks++ > 60)
|
||||
{
|
||||
ticks = 0;
|
||||
Level w = event.level;
|
||||
List<LivingEntity> list;
|
||||
if(w.isClientSide)
|
||||
{
|
||||
ClientLevel cw = (ClientLevel)w;
|
||||
list = new ArrayList<>(100);
|
||||
for(Entity e : cw.entitiesForRendering())
|
||||
{
|
||||
if(e.isAlive() && e instanceof LivingEntity)
|
||||
list.add((LivingEntity)e);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
ServerLevel sw = (ServerLevel)w;
|
||||
Stream<LivingEntity> s = StreamSupport.stream(sw.getEntities().getAll().spliterator(), false)
|
||||
.filter(Entity::isAlive)
|
||||
.filter(e -> e instanceof LivingEntity)
|
||||
.map(e -> (LivingEntity)e);
|
||||
list = s.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
for(LivingEntity liv : list)
|
||||
{
|
||||
AttributeInstance grav = liv.getAttribute(ForgeMod.ENTITY_GRAVITY.get());
|
||||
|
||||
boolean inPlains = liv.level().getBiome(liv.blockPosition()).is(BiomeTags.IS_FOREST);
|
||||
if (inPlains && !grav.hasModifier(REDUCED_GRAVITY))
|
||||
{
|
||||
logger.info("Granted low gravity to Entity: {}", liv);
|
||||
grav.addTransientModifier(REDUCED_GRAVITY);
|
||||
}
|
||||
else if (!inPlains && grav.hasModifier(REDUCED_GRAVITY))
|
||||
{
|
||||
logger.info("Removed low gravity from Entity: {}", liv);
|
||||
grav.removeModifier(REDUCED_GRAVITY.getId());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private void addCreative(BuildCreativeModeTabContentsEvent event)
|
||||
{
|
||||
if (event.getTabKey() == CreativeModeTabs.TOOLS_AND_UTILITIES)
|
||||
event.accept(TEST_ITEM);
|
||||
}
|
||||
|
||||
public static class ItemGravityStick extends Item
|
||||
{
|
||||
private static final UUID GRAVITY_MODIFIER = UUID.fromString("DEB06001-7979-4242-8888-10000DEB0601");
|
||||
|
||||
public ItemGravityStick(Properties properties)
|
||||
{
|
||||
super(properties);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Multimap<Attribute, AttributeModifier> getDefaultAttributeModifiers(EquipmentSlot slot)
|
||||
{
|
||||
@SuppressWarnings("deprecation")
|
||||
Multimap<Attribute, AttributeModifier> multimap = super.getDefaultAttributeModifiers(slot);
|
||||
if (slot == EquipmentSlot.MAINHAND)
|
||||
multimap.put(ForgeMod.ENTITY_GRAVITY.get(), new AttributeModifier(GRAVITY_MODIFIER, "More Gravity", 1.0D, Operation.ADDITION));
|
||||
|
||||
return multimap;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.entity;
|
||||
|
||||
import net.minecraft.client.renderer.entity.PigRenderer;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.network.protocol.Packet;
|
||||
import net.minecraft.network.protocol.game.ClientGamePacketListener;
|
||||
import net.minecraft.network.protocol.game.ClientboundAddEntityPacket;
|
||||
import net.minecraft.world.damagesource.DamageSource;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.EntityDimensions;
|
||||
import net.minecraft.world.entity.EntityType;
|
||||
import net.minecraft.world.entity.Pose;
|
||||
import net.minecraft.world.entity.MobCategory;
|
||||
import net.minecraft.world.entity.animal.Pig;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
import net.minecraftforge.api.distmarker.Dist;
|
||||
import net.minecraftforge.client.event.EntityRenderersEvent;
|
||||
import net.minecraftforge.entity.PartEntity;
|
||||
import net.minecraftforge.event.entity.EntityAttributeCreationEvent;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
import net.minecraftforge.registries.RegistryObject;
|
||||
import net.minecraftforge.registries.DeferredRegister;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
|
||||
@Mod(value = PartEntityTest.MOD_ID)
|
||||
public class PartEntityTest
|
||||
{
|
||||
static final String MOD_ID = "part_entity_test";
|
||||
static final boolean ENABLED = true;
|
||||
|
||||
private static final DeferredRegister<EntityType<?>> ENTITIES = DeferredRegister.create(ForgeRegistries.ENTITY_TYPES, MOD_ID);
|
||||
private static final RegistryObject<EntityType<TestEntity>> TEST_ENTITY = ENTITIES.register("test_entity", () -> EntityType.Builder.of(TestEntity::new, MobCategory.CREATURE).sized(16.0F, 8.0F).clientTrackingRange(10).build("test_entity"));
|
||||
|
||||
public PartEntityTest()
|
||||
{
|
||||
if (ENABLED)
|
||||
{
|
||||
ENTITIES.register(FMLJavaModLoadingContext.get().getModEventBus());
|
||||
FMLJavaModLoadingContext.get().getModEventBus().register(this);
|
||||
}
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public void onRegisterAttributes(final EntityAttributeCreationEvent event)
|
||||
{
|
||||
event.put(TEST_ENTITY.get(), Pig.createAttributes().build());
|
||||
}
|
||||
|
||||
@Mod.EventBusSubscriber(modid = MOD_ID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD)
|
||||
private static class ClientEvents
|
||||
{
|
||||
@SubscribeEvent
|
||||
public static void onRegisterRenderers(final EntityRenderersEvent.RegisterRenderers event)
|
||||
{
|
||||
if (!ENABLED) return;
|
||||
|
||||
event.registerEntityRenderer(TEST_ENTITY.get(), PigRenderer::new);
|
||||
}
|
||||
}
|
||||
|
||||
private static class TestEntity extends Pig
|
||||
{
|
||||
private final TestEntityPart[] subEntities;
|
||||
public final TestEntityPart head;
|
||||
private final TestEntityPart neck;
|
||||
private final TestEntityPart body;
|
||||
private final TestEntityPart tail1;
|
||||
private final TestEntityPart tail2;
|
||||
private final TestEntityPart tail3;
|
||||
private final TestEntityPart wing1;
|
||||
private final TestEntityPart wing2;
|
||||
|
||||
public TestEntity(EntityType<? extends Pig> entity, Level world)
|
||||
{
|
||||
super(entity, world);
|
||||
this.head = new TestEntityPart(this, 1.0F, 1.0F);
|
||||
this.neck = new TestEntityPart(this, 3.0F, 3.0F);
|
||||
this.body = new TestEntityPart(this, 5.0F, 3.0F);
|
||||
this.tail1 = new TestEntityPart(this, 2.0F, 2.0F);
|
||||
this.tail2 = new TestEntityPart(this, 2.0F, 2.0F);
|
||||
this.tail3 = new TestEntityPart(this, 2.0F, 2.0F);
|
||||
this.wing1 = new TestEntityPart(this, 4.0F, 2.0F);
|
||||
this.wing2 = new TestEntityPart(this, 4.0F, 2.0F);
|
||||
this.subEntities = new TestEntityPart[]{this.head, this.neck, this.body, this.tail1, this.tail2, this.tail3, this.wing1, this.wing2};
|
||||
}
|
||||
|
||||
@Override
|
||||
public void aiStep()
|
||||
{
|
||||
super.aiStep();
|
||||
|
||||
for (TestEntityPart part : this.subEntities)
|
||||
{
|
||||
part.setPos(this.getX(), this.getY(), this.getZ());
|
||||
}
|
||||
|
||||
Vec3[] vec3 = new Vec3[this.subEntities.length];
|
||||
for(int j = 0; j < this.subEntities.length; ++j)
|
||||
{
|
||||
vec3[j] = new Vec3(this.subEntities[j].getX(), this.subEntities[j].getY(), this.subEntities[j].getZ());
|
||||
}
|
||||
|
||||
for(int l = 0; l < this.subEntities.length; ++l)
|
||||
{
|
||||
this.subEntities[l].xo = vec3[l].x;
|
||||
this.subEntities[l].yo = vec3[l].y;
|
||||
this.subEntities[l].zo = vec3[l].z;
|
||||
this.subEntities[l].xOld = vec3[l].x;
|
||||
this.subEntities[l].yOld = vec3[l].y;
|
||||
this.subEntities[l].zOld = vec3[l].z;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isMultipartEntity()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PartEntity<?>[] getParts()
|
||||
{
|
||||
return this.subEntities;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void recreateFromPacket(ClientboundAddEntityPacket packet)
|
||||
{
|
||||
super.recreateFromPacket(packet);
|
||||
PartEntity<?>[] parts = this.getParts();
|
||||
|
||||
for(int i = 0; i < parts.length; ++i)
|
||||
{
|
||||
parts[i].setId(i + packet.getId());
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private static class TestEntityPart extends PartEntity<TestEntity>
|
||||
{
|
||||
public final TestEntity parent;
|
||||
private final EntityDimensions size;
|
||||
|
||||
public TestEntityPart(TestEntity parent, float width, float height)
|
||||
{
|
||||
super(parent);
|
||||
this.size = EntityDimensions.scalable(width, height);
|
||||
this.refreshDimensions();
|
||||
this.parent = parent;
|
||||
}
|
||||
|
||||
protected void defineSynchedData() {}
|
||||
|
||||
protected void readAdditionalSaveData(CompoundTag nbt) {}
|
||||
|
||||
protected void addAdditionalSaveData(CompoundTag nbt) {}
|
||||
|
||||
public boolean isPickable()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean hurt(DamageSource source, float amount)
|
||||
{
|
||||
return !this.isInvulnerableTo(source) && this.parent.hurt(source, amount);
|
||||
}
|
||||
|
||||
public boolean is(Entity entity)
|
||||
{
|
||||
return this == entity || this.parent == entity;
|
||||
}
|
||||
|
||||
public Packet<ClientGamePacketListener> getAddEntityPacket()
|
||||
{
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public EntityDimensions getDimensions(Pose matrix)
|
||||
{
|
||||
return this.size;
|
||||
}
|
||||
|
||||
public boolean shouldBeSaved()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.entity;
|
||||
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.world.Difficulty;
|
||||
import net.minecraft.world.entity.EntityType;
|
||||
import net.minecraft.world.level.ServerLevelAccessor;
|
||||
import net.minecraft.world.level.biome.Biomes;
|
||||
import net.minecraftforge.event.entity.SpawnPlacementRegisterEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
|
||||
import com.mojang.logging.LogUtils;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
@Mod("spawn_placement_test")
|
||||
public class SpawnPlacementTest
|
||||
{
|
||||
public static final boolean ENABLED = false;
|
||||
public static final Logger LOGGER = LogUtils.getLogger();
|
||||
|
||||
public SpawnPlacementTest()
|
||||
{
|
||||
if (ENABLED)
|
||||
{
|
||||
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onSpawnPlacementRegister);
|
||||
}
|
||||
}
|
||||
|
||||
private void onSpawnPlacementRegister(SpawnPlacementRegisterEvent event)
|
||||
{
|
||||
LOGGER.info("Modifying spawn placements!");
|
||||
// AND: require zombies to spawn below y 40
|
||||
event.register(EntityType.ZOMBIE, ((entityType, level, spawnType, pos, random) -> pos.getY() < 40 && validMonsterSpawn(level, pos, entityType)), SpawnPlacementRegisterEvent.Operation.AND);
|
||||
// REPLACE: don't require darkness to spawn creepers
|
||||
event.register(EntityType.CREEPER, ((entityType, level, spawnType, pos, random) -> validMonsterSpawn(level, pos, entityType)), SpawnPlacementRegisterEvent.Operation.REPLACE);
|
||||
// OR: allow slimes to spawn in plains
|
||||
event.register(EntityType.SLIME, (entityType, level, spawnType, pos, random) -> validMonsterSpawn(level, pos, entityType) && level.getBiome(pos).is(Biomes.PLAINS));
|
||||
}
|
||||
|
||||
private static boolean validMonsterSpawn(ServerLevelAccessor level, BlockPos pos, EntityType<?> type)
|
||||
{
|
||||
return level.getDifficulty() != Difficulty.PEACEFUL && level.getBlockState(pos.below()).isValidSpawn(level, pos.below(), type);
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.entity.living;
|
||||
|
||||
import net.minecraft.world.entity.npc.Villager;
|
||||
import net.minecraft.world.entity.monster.piglin.Piglin;
|
||||
import net.minecraft.world.effect.MobEffectInstance;
|
||||
import net.minecraft.world.effect.MobEffects;
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.event.entity.living.LivingConversionEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
|
||||
@Mod("living_conversion_event_test")
|
||||
public class LivingConversionEventTest
|
||||
{
|
||||
public LivingConversionEventTest()
|
||||
{
|
||||
MinecraftForge.EVENT_BUS.addListener(this::canLivingConversion);
|
||||
MinecraftForge.EVENT_BUS.addListener(this::onLivingConversion);
|
||||
}
|
||||
|
||||
public void canLivingConversion(LivingConversionEvent.Pre event)
|
||||
{
|
||||
if (event.getEntity() instanceof Piglin)
|
||||
{
|
||||
event.setCanceled(true);
|
||||
event.setConversionTimer(0);
|
||||
}
|
||||
}
|
||||
|
||||
public void onLivingConversion(LivingConversionEvent.Post event)
|
||||
{
|
||||
if (event.getEntity() instanceof Villager)
|
||||
event.getEntity().addEffect(new MobEffectInstance(MobEffects.LUCK, 20));
|
||||
}
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.entity.living;
|
||||
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.Items;
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.event.entity.living.LivingGetProjectileEvent;
|
||||
import net.minecraftforge.event.entity.player.ArrowLooseEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
@Mod("living_get_projectile_event_test")
|
||||
public class LivingGetProjectileEventTest
|
||||
{
|
||||
public static final boolean ENABLED = true;
|
||||
public static final Logger LOGGER = LogManager.getLogger();
|
||||
|
||||
public LivingGetProjectileEventTest()
|
||||
{
|
||||
if (ENABLED)
|
||||
{
|
||||
MinecraftForge.EVENT_BUS.addListener(this::onLivingGetProjectile);
|
||||
}
|
||||
}
|
||||
|
||||
public void onLivingGetProjectile(LivingGetProjectileEvent event)
|
||||
{
|
||||
LOGGER.info("{} about to fire {} with a {}", event.getEntity(), event.getProjectileItemStack(), event.getProjectileWeaponItemStack());
|
||||
|
||||
// for this test, we're checking if the player has a spectral arrow itemstack in their offhand and if they're firing a normal arrow.
|
||||
// if they do, we're going to use that itemstack. if not, we will create a spectral arrow itemstack
|
||||
// this demonstrates the usage of specific itemstacks with this event. you can use specific itemstacks from the player's inventory in this similar style
|
||||
if (event.getEntity() instanceof Player player && event.getProjectileItemStack().getItem() == Items.ARROW)
|
||||
{
|
||||
ItemStack offhandItem = player.getOffhandItem();
|
||||
event.setProjectileItemStack(offhandItem.getItem() == Items.SPECTRAL_ARROW ? offhandItem : new ItemStack(Items.SPECTRAL_ARROW));
|
||||
}
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.entity.living;
|
||||
|
||||
import net.minecraft.world.entity.ai.behavior.Swim;
|
||||
import net.minecraft.world.entity.monster.piglin.Piglin;
|
||||
import net.minecraft.world.entity.schedule.Activity;
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.common.util.BrainBuilder;
|
||||
import net.minecraftforge.event.entity.living.LivingMakeBrainEvent;
|
||||
import net.minecraftforge.eventtest.internal.EventTest;
|
||||
import net.minecraftforge.eventtest.internal.TestHolder;
|
||||
|
||||
@TestHolder("LivingMakeBrain")
|
||||
public class LivingMakeBrainEventTest extends EventTest
|
||||
{
|
||||
public static final boolean ENABLE = true;
|
||||
|
||||
@Override
|
||||
public void registerEvents() {
|
||||
if(ENABLE)
|
||||
{
|
||||
MinecraftForge.EVENT_BUS.addListener(this::livingMakeBrainEventListener);
|
||||
}
|
||||
}
|
||||
|
||||
public void livingMakeBrainEventListener(LivingMakeBrainEvent event)
|
||||
{
|
||||
if(event.getEntity() instanceof Piglin piglin)
|
||||
{
|
||||
// lets us test in the Overworld
|
||||
piglin.setImmuneToZombification(true);
|
||||
// add the ability to swim to Piglins
|
||||
BrainBuilder<Piglin> brainBuilder = event.getTypedBrainBuilder(piglin);
|
||||
brainBuilder.addBehaviorToActivityByPriority(0, Activity.CORE, new Swim(0.8F));
|
||||
this.pass();
|
||||
}
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.entity.living;
|
||||
|
||||
import net.minecraft.world.entity.monster.piglin.AbstractPiglin;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.item.Items;
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.event.entity.living.LivingChangeTargetEvent;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
|
||||
@Mod("living_set_attack_target_event_test")
|
||||
public class LivingSetAttackTargetEventTest
|
||||
{
|
||||
public static final boolean ENABLE = true;
|
||||
|
||||
public LivingSetAttackTargetEventTest()
|
||||
{
|
||||
if(ENABLE)
|
||||
{
|
||||
MinecraftForge.EVENT_BUS.register(this);
|
||||
}
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public void onLivingChangeTargetEvent(LivingChangeTargetEvent event)
|
||||
{
|
||||
// Prevents the piglin from attacking the player if they hold a stick in their hands.
|
||||
if(event.getNewTarget() instanceof Player player && event.getEntity() instanceof AbstractPiglin piglin && player.getMainHandItem().getItem() == Items.STICK)
|
||||
{
|
||||
event.setCanceled(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.entity.living;
|
||||
|
||||
import net.minecraft.world.item.Items;
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.event.entity.living.LivingSwapItemsEvent;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
@Mod("living_swap_items_event_test")
|
||||
public class LivingSwapItemsEventTest
|
||||
{
|
||||
public static final boolean ENABLE = true;
|
||||
public static final Logger LOGGER = LogManager.getLogger();
|
||||
|
||||
public LivingSwapItemsEventTest()
|
||||
{
|
||||
if (ENABLE)
|
||||
MinecraftForge.EVENT_BUS.register(this);
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public void livingSwapItems(LivingSwapItemsEvent.Hands event)
|
||||
{
|
||||
LOGGER.info("{} swapping hands. To offhand: {}, to main hand: {}", event.getEntity(), event.getItemSwappedToOffHand(), event.getItemSwappedToMainHand());
|
||||
if (event.getEntity().getMainHandItem().is(Items.DIAMOND))
|
||||
event.setCanceled(true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
@ParametersAreNonnullByDefault
|
||||
@MethodsReturnNonnullByDefault
|
||||
package net.minecraftforge.debug.entity;
|
||||
|
||||
import javax.annotation.ParametersAreNonnullByDefault;
|
||||
import net.minecraft.MethodsReturnNonnullByDefault;
|
||||
@@ -0,0 +1,54 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.entity.player;
|
||||
|
||||
import net.minecraft.advancements.AdvancementProgress;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.event.entity.player.AdvancementEvent;
|
||||
import net.minecraftforge.event.entity.player.AdvancementEvent.AdvancementEarnEvent;
|
||||
import net.minecraftforge.event.entity.player.AdvancementEvent.AdvancementProgressEvent;
|
||||
import net.minecraftforge.event.entity.player.AdvancementEvent.AdvancementProgressEvent.ProgressType;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
|
||||
import com.mojang.logging.LogUtils;
|
||||
|
||||
@Mod(AdvancementEventTest.MOD_ID)
|
||||
public class AdvancementEventTest {
|
||||
static final String MOD_ID = "advancement_event_test";
|
||||
private static final boolean ENABLED = false;
|
||||
private static final Logger LOGGER = LogUtils.getLogger();
|
||||
|
||||
public AdvancementEventTest() {
|
||||
if (ENABLED) {
|
||||
MinecraftForge.EVENT_BUS.addListener(this::onAdvancementEarnEvent);
|
||||
MinecraftForge.EVENT_BUS.addListener(this::onAdvancementProgressEvent);
|
||||
}
|
||||
}
|
||||
|
||||
public void onAdvancementEarnEvent(AdvancementEarnEvent event) {
|
||||
var advancement = event.getAdvancement();
|
||||
Player player = event.getEntity();
|
||||
LOGGER.info("Player {} earned advancement {} and was awarded {}", player, advancement.id(), advancement.value().rewards().toString());
|
||||
}
|
||||
|
||||
public void onAdvancementProgressEvent(AdvancementProgressEvent event) {
|
||||
var advancement = event.getAdvancement();
|
||||
Player player = event.getEntity();
|
||||
AdvancementProgress advancementProgress = event.getAdvancementProgress();
|
||||
String criterionName = event.getCriterionName();
|
||||
AdvancementEvent.AdvancementProgressEvent.ProgressType progressType = event.getProgressType();
|
||||
String action;
|
||||
if (progressType == ProgressType.GRANT)
|
||||
action = "granted";
|
||||
else
|
||||
action = "revoked";
|
||||
LOGGER.info("Player {} progressed advancement {}. They were {} progress on {}. They have completed {}% of the achievement",
|
||||
player, advancement.id(), action, criterionName, advancementProgress.getPercent()*100);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.entity.player;
|
||||
|
||||
import com.mojang.blaze3d.vertex.PoseStack;
|
||||
import net.minecraft.client.model.HumanoidModel;
|
||||
import net.minecraft.client.player.LocalPlayer;
|
||||
import net.minecraft.world.InteractionHand;
|
||||
import net.minecraft.world.entity.HumanoidArm;
|
||||
import net.minecraft.world.entity.LivingEntity;
|
||||
import net.minecraft.world.food.FoodProperties;
|
||||
import net.minecraft.world.item.*;
|
||||
import net.minecraftforge.client.extensions.common.IClientItemExtensions;
|
||||
import net.minecraftforge.event.BuildCreativeModeTabContentsEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
import net.minecraftforge.registries.DeferredRegister;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
import net.minecraftforge.registries.RegistryObject;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/**
|
||||
* Tests if item usage animation system works as intended. `item_use_animation_test:thing` is edible item with custom usage animation made with this system.
|
||||
* In game, use `/give @s item_use_animation_test:thing 1` to obtain test item
|
||||
* When you try to eat it, your arm in 3d person should start swinging really fast.
|
||||
* And item in your hand will go down little.
|
||||
*/
|
||||
@Mod(ItemUseAnimationTest.MOD_ID)
|
||||
public class ItemUseAnimationTest
|
||||
{
|
||||
|
||||
public static final String MOD_ID = "item_use_animation_test";
|
||||
|
||||
private static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, MOD_ID);
|
||||
|
||||
private static final RegistryObject<Item> THING = ITEMS.register("thing", () -> new ThingItem(new Item.Properties().food(new FoodProperties.Builder().nutrition(4).alwaysEat().build())));
|
||||
|
||||
public ItemUseAnimationTest()
|
||||
{
|
||||
var modBus = FMLJavaModLoadingContext.get().getModEventBus();
|
||||
ITEMS.register(modBus);
|
||||
modBus.addListener(this::addCreative);
|
||||
}
|
||||
|
||||
private void addCreative(BuildCreativeModeTabContentsEvent event)
|
||||
{
|
||||
if (event.getTabKey() == CreativeModeTabs.COMBAT)
|
||||
event.accept(THING);
|
||||
}
|
||||
|
||||
private static class ThingItem extends Item
|
||||
{
|
||||
|
||||
public ThingItem(Item.Properties props)
|
||||
{
|
||||
super(props);
|
||||
}
|
||||
|
||||
@Override
|
||||
public UseAnim getUseAnimation(ItemStack stack)
|
||||
{
|
||||
return UseAnim.CUSTOM;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initializeClient(Consumer<IClientItemExtensions> consumer)
|
||||
{
|
||||
consumer.accept(new IClientItemExtensions()
|
||||
{
|
||||
|
||||
private static final HumanoidModel.ArmPose SWING_POSE = HumanoidModel.ArmPose.create("SWING", false, (model, entity, arm) -> {
|
||||
if (arm == HumanoidArm.RIGHT)
|
||||
{
|
||||
model.rightArm.xRot = (float) (Math.random() * Math.PI * 2);
|
||||
} else
|
||||
{
|
||||
model.leftArm.xRot = (float) (Math.random() * Math.PI * 2);
|
||||
}
|
||||
});
|
||||
|
||||
@Override
|
||||
public HumanoidModel.ArmPose getArmPose(LivingEntity entityLiving, InteractionHand hand, ItemStack itemStack)
|
||||
{
|
||||
if (!itemStack.isEmpty())
|
||||
{
|
||||
if (entityLiving.getUsedItemHand() == hand && entityLiving.getUseItemRemainingTicks() > 0)
|
||||
{
|
||||
return SWING_POSE;
|
||||
}
|
||||
}
|
||||
return HumanoidModel.ArmPose.EMPTY;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean applyForgeHandTransform(PoseStack poseStack, LocalPlayer player, HumanoidArm arm, ItemStack itemInHand, float partialTick, float equipProcess, float swingProcess) {
|
||||
applyItemArmTransform(poseStack, arm);
|
||||
if (player.getUseItem() != itemInHand) {
|
||||
return true;
|
||||
}
|
||||
if (player.isUsingItem()) {
|
||||
poseStack.translate(0.0, -0.05, 0.0);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private void applyItemArmTransform(PoseStack poseStack, HumanoidArm arm) {
|
||||
int i = arm == HumanoidArm.RIGHT ? 1 : -1;
|
||||
poseStack.translate(i * 0.56F, -0.52F, -0.72F);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.entity.player;
|
||||
|
||||
import net.minecraftforge.event.entity.player.PermissionsChangedEvent;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
@Mod("permissions_changed_event_test")
|
||||
@Mod.EventBusSubscriber
|
||||
public class PermissionsChangedEventTest
|
||||
{
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
|
||||
@SubscribeEvent
|
||||
public static void onPermissionChanged(PermissionsChangedEvent event)
|
||||
{
|
||||
LOGGER.info("{} permission level changed to {} from {}",
|
||||
event.getEntity().getName().getString(),
|
||||
event.getNewLevel(),
|
||||
event.getOldLevel());
|
||||
}
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.entity.player;
|
||||
|
||||
import com.google.common.collect.ArrayListMultimap;
|
||||
import com.google.common.collect.Multimap;
|
||||
import net.minecraft.world.entity.EquipmentSlot;
|
||||
import net.minecraft.world.entity.ai.attributes.Attribute;
|
||||
import net.minecraft.world.entity.ai.attributes.AttributeModifier;
|
||||
import net.minecraft.world.entity.ai.attributes.Attributes;
|
||||
import net.minecraft.world.item.*;
|
||||
import net.minecraftforge.event.BuildCreativeModeTabContentsEvent;
|
||||
import net.minecraftforge.eventbus.api.IEventBus;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
import net.minecraftforge.registries.RegistryObject;
|
||||
import net.minecraftforge.registries.DeferredRegister;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Tests if the patch to PlayerEntity to make it utilize Attributes.ATTACK_KNOCKBACK works
|
||||
* The Knockback Sword adds a modifier to the user's attack knockback
|
||||
* The goal of this patch is to allow modders to more easily add equipment or potion effects that affect the attack knockback of players
|
||||
* As well as allow command users to modify this attribute for a player
|
||||
*/
|
||||
@Mod(PlayerAttackKnockbackTest.MODID)
|
||||
public class PlayerAttackKnockbackTest {
|
||||
|
||||
static final String MODID = "player_attack_knockback_test";
|
||||
|
||||
static final float ATTACK_KNOCKBACK_VALUE = 2.0F; // Change this value for testing, but note that the attribute is capped at 5.0D
|
||||
|
||||
static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, MODID);
|
||||
|
||||
static RegistryObject<Item> KNOCKBACK_SWORD = ITEMS.register("knockback_sword", () ->
|
||||
new KnockbackSwordItem(Tiers.IRON, 3, -2.4F, ATTACK_KNOCKBACK_VALUE, (new Item.Properties()))
|
||||
);
|
||||
|
||||
public PlayerAttackKnockbackTest()
|
||||
{
|
||||
IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus();
|
||||
ITEMS.register(modEventBus);
|
||||
modEventBus.addListener(this::addCreative);
|
||||
}
|
||||
|
||||
private void addCreative(BuildCreativeModeTabContentsEvent event)
|
||||
{
|
||||
if (event.getTabKey() == CreativeModeTabs.COMBAT)
|
||||
event.accept(KNOCKBACK_SWORD);
|
||||
}
|
||||
|
||||
static class KnockbackSwordItem extends SwordItem {
|
||||
private final float attackKnockback;
|
||||
private final Multimap<Attribute, AttributeModifier> defaultModifiers = ArrayListMultimap.create(); // initialize as empty
|
||||
protected static final UUID BASE_ATTACK_KNOCKBACK_UUID = UUID.fromString("01efce91-ab3a-4163-b464-5c7bd1ae5496");
|
||||
|
||||
KnockbackSwordItem(Tier itemTier, int attackDamageIn, float attackSpeedIn, float attackKnockbackIn, Properties properties) {
|
||||
super(itemTier, attackDamageIn, attackSpeedIn, properties);
|
||||
this.attackKnockback = attackKnockbackIn;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Multimap<Attribute, AttributeModifier> getDefaultAttributeModifiers(EquipmentSlot equipmentSlotType) {
|
||||
if(equipmentSlotType == EquipmentSlot.MAINHAND){
|
||||
if(this.defaultModifiers.isEmpty()){
|
||||
Multimap<Attribute, AttributeModifier> oldAttributeModifiers = super.getDefaultAttributeModifiers(equipmentSlotType);
|
||||
this.defaultModifiers.putAll(oldAttributeModifiers);
|
||||
this.defaultModifiers.put(Attributes.ATTACK_KNOCKBACK, new AttributeModifier(BASE_ATTACK_KNOCKBACK_UUID, "Weapon modifier", (double)this.attackKnockback, AttributeModifier.Operation.ADDITION));
|
||||
}
|
||||
return this.defaultModifiers;
|
||||
}
|
||||
else return super.getDefaultAttributeModifiers(equipmentSlotType);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.entity.player;
|
||||
|
||||
import net.minecraft.world.level.GameType;
|
||||
import net.minecraftforge.api.distmarker.Dist;
|
||||
import net.minecraftforge.client.event.ClientPlayerChangeGameTypeEvent;
|
||||
import net.minecraftforge.event.entity.player.PlayerEvent;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
@Mod("player_game_mode_event_test")
|
||||
@Mod.EventBusSubscriber()
|
||||
public class PlayerGameModeEventTest
|
||||
{
|
||||
private static final boolean ENABLE = false;
|
||||
private static final Logger LOGGER = LogManager.getLogger(PlayerGameModeEventTest.class);
|
||||
|
||||
@SubscribeEvent
|
||||
public static void onPlayerChangeGameModeEvent(PlayerEvent.PlayerChangeGameModeEvent event)
|
||||
{
|
||||
if (!ENABLE) return;
|
||||
LOGGER.info("{} changed game mode. Current GameType: {}. New Game Type: {}", event.getEntity(), event.getCurrentGameMode(), event.getNewGameMode());
|
||||
// prevent changing to SURVIVAL
|
||||
if (event.getNewGameMode() == GameType.SURVIVAL)
|
||||
{
|
||||
event.setCanceled(true);
|
||||
}
|
||||
else if (event.getNewGameMode() == GameType.SPECTATOR)
|
||||
{
|
||||
// when changing to SPECTATOR, change to SURVIVAL instead
|
||||
event.setNewGameMode(GameType.SURVIVAL);
|
||||
}
|
||||
}
|
||||
|
||||
@Mod.EventBusSubscriber(modid="player_game_mode_event_test", value=Dist.CLIENT, bus=Mod.EventBusSubscriber.Bus.FORGE)
|
||||
public static class PlayerGameModeEventTestClientForgeEvents
|
||||
{
|
||||
@SubscribeEvent
|
||||
public static void onClientPlayerChangeGameModeEvent(ClientPlayerChangeGameTypeEvent event)
|
||||
{
|
||||
if (!ENABLE) return;
|
||||
LOGGER.info("Client notified of changed game mode from '{}'. Current GameType: {}. New Game Type: {}", event.getInfo().getProfile(), event.getCurrentGameType(), event.getNewGameType());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.debug.entity.player;
|
||||
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraftforge.event.entity.player.PlayerEvent;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
|
||||
@Mod("player_name_event_test")
|
||||
@Mod.EventBusSubscriber()
|
||||
public class PlayerNameEventTest
|
||||
{
|
||||
private static final boolean ENABLE = false;
|
||||
|
||||
@SubscribeEvent
|
||||
public static void onPlayerNameEvent(PlayerEvent.NameFormat event)
|
||||
{
|
||||
if (!ENABLE) return;
|
||||
event.setDisplayname(Component.literal("Test Name"));
|
||||
}
|
||||
}
|
||||
Loaded 100 of 665 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user