Updated Create files to 1.20

This commit is contained in:
Christian Knaapen
2023-09-16 12:42:42 +02:00
parent d8f47db7fa
commit 8c2b9cb240
99 changed files with 2052 additions and 1284 deletions

View File

@@ -1,6 +1,9 @@
package nl.requios.effortlessbuilding.create;
import org.lwjgl.glfw.GLFW;
import com.mojang.blaze3d.platform.InputConstants;
import net.minecraft.client.KeyMapping;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screens.Screen;
@@ -8,10 +11,59 @@ import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.client.event.RegisterKeyMappingsEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import org.lwjgl.glfw.GLFW;
//@EventBusSubscriber(value = Dist.CLIENT, bus = EventBusSubscriber.Bus.MOD)
public class AllKeys {
// TOOL_MENU("toolmenu", GLFW.GLFW_KEY_LEFT_ALT),
// ACTIVATE_TOOL("", GLFW.GLFW_KEY_LEFT_CONTROL),
// TOOLBELT("toolbelt", GLFW.GLFW_KEY_LEFT_ALT),
//
// ;
//
// private KeyMapping keybind;
// private String description;
// private int key;
// private boolean modifiable;
//
// private AllKeys(String description, int defaultKey) {
// this.description = Create.ID + ".keyinfo." + description;
// this.key = defaultKey;
// this.modifiable = !description.isEmpty();
// }
//
// @SubscribeEvent
// public static void register(RegisterKeyMappingsEvent event) {
// for (AllKeys key : values()) {
// key.keybind = new KeyMapping(key.description, key.key, Create.NAME);
// if (!key.modifiable)
// continue;
//
// event.register(key.keybind);
// }
// }
//
// public KeyMapping getKeybind() {
// return keybind;
// }
//
// public boolean isPressed() {
// if (!modifiable)
// return isKeyDown(key);
// return keybind.isDown();
// }
//
// public String getBoundKey() {
// return keybind.getTranslatedKeyMessage()
// .getString()
// .toUpperCase();
// }
//
// public int getBoundCode() {
// return keybind.getKey()
// .getValue();
// }
public static boolean isKeyDown(int key) {
return InputConstants.isKeyDown(Minecraft.getInstance()
.getWindow()

View File

@@ -1,6 +1,7 @@
package nl.requios.effortlessbuilding.create;
import com.mojang.blaze3d.systems.RenderSystem;
import net.minecraft.resources.ResourceLocation;
public enum AllSpecialTextures {

View File

@@ -1,6 +1,9 @@
package nl.requios.effortlessbuilding.create.foundation;
import nl.requios.effortlessbuilding.create.CreateClient;
import nl.requios.effortlessbuilding.create.foundation.sound.SoundScapes;
import nl.requios.effortlessbuilding.create.foundation.utility.LangNumberFormat;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.server.packs.resources.ResourceManagerReloadListener;
@@ -8,7 +11,7 @@ public class ClientResourceReloadListener implements ResourceManagerReloadListen
@Override
public void onResourceManagerReload(ResourceManager resourceManager) {
// CreateClient.invalidateRenderers();
CreateClient.invalidateRenderers();
// SoundScapes.invalidateAll();
LangNumberFormat.numberFormat.update();
}

View File

@@ -1,16 +1,16 @@
package nl.requios.effortlessbuilding.create.foundation;
import java.nio.file.Path;
import net.minecraftforge.forgespi.locating.IModFile;
import net.minecraftforge.resource.PathPackResources;
import java.nio.file.Path;
public class ModFilePackResources extends PathPackResources {
protected final IModFile modFile;
protected final String sourcePath;
public ModFilePackResources(String name, IModFile modFile, String sourcePath) {
super(name, modFile.findResource(sourcePath));
super(name, true, modFile.findResource(sourcePath));
this.modFile = modFile;
this.sourcePath = sourcePath;
}

View File

@@ -1,10 +1,16 @@
package nl.requios.effortlessbuilding.create.foundation.gui;
import java.util.Collection;
import java.util.List;
import com.mojang.blaze3d.platform.InputConstants;
import com.mojang.blaze3d.vertex.PoseStack;
import nl.requios.effortlessbuilding.create.foundation.gui.widget.AbstractSimiWidget;
import nl.requios.effortlessbuilding.create.foundation.utility.Components;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.components.AbstractWidget;
import net.minecraft.client.gui.components.EditBox;
import net.minecraft.client.gui.components.Renderable;
import net.minecraft.client.gui.components.events.GuiEventListener;
import net.minecraft.client.gui.narration.NarratableEntry;
@@ -12,10 +18,6 @@ import net.minecraft.client.gui.screens.Screen;
import net.minecraft.network.chat.Component;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import nl.requios.effortlessbuilding.gui.buildmodifier.ModifiersScreenList;
import java.util.Collection;
import java.util.List;
@OnlyIn(Dist.CLIENT)
public abstract class AbstractSimiScreen extends Screen {
@@ -65,6 +67,13 @@ public abstract class AbstractSimiScreen extends Screen {
}
}
@Override
public boolean mouseClicked(double pMouseX, double pMouseY, int pButton) {
if (getFocused() != null && !getFocused().isMouseOver(pMouseX, pMouseY))
setFocused(null);
return super.mouseClicked(pMouseX, pMouseY, pButton);
}
@Override
public boolean isPauseScreen() {
return false;
@@ -96,17 +105,18 @@ public abstract class AbstractSimiScreen extends Screen {
}
@Override
public void render(PoseStack ms, int mouseX, int mouseY, float partialTicks) {
public void render(GuiGraphics graphics, int mouseX, int mouseY, float partialTicks) {
partialTicks = minecraft.getFrameTime();
PoseStack ms = graphics.pose();
ms.pushPose();
prepareFrame();
renderWindowBackground(ms, mouseX, mouseY, partialTicks);
renderWindow(ms, mouseX, mouseY, partialTicks);
super.render(ms, mouseX, mouseY, partialTicks);
renderWindowForeground(ms, mouseX, mouseY, partialTicks);
renderWindowBackground(graphics, mouseX, mouseY, partialTicks);
renderWindow(graphics, mouseX, mouseY, partialTicks);
super.render(graphics, mouseX, mouseY, partialTicks);
renderWindowForeground(graphics, mouseX, mouseY, partialTicks);
endFrame();
@@ -116,7 +126,7 @@ public abstract class AbstractSimiScreen extends Screen {
@Override
public boolean keyPressed(int keyCode, int scanCode, int modifiers) {
boolean keyPressed = super.keyPressed(keyCode, scanCode, modifiers);
if (keyPressed || getFocused() != null)
if (keyPressed || getFocused() instanceof EditBox)
return keyPressed;
InputConstants.Key mouseKey = InputConstants.getKey(keyCode, scanCode);
@@ -130,37 +140,31 @@ public abstract class AbstractSimiScreen extends Screen {
protected void prepareFrame() {}
protected void renderWindowBackground(PoseStack ms, int mouseX, int mouseY, float partialTicks) {
renderBackground(ms);
protected void renderWindowBackground(GuiGraphics graphics, int mouseX, int mouseY, float partialTicks) {
renderBackground(graphics);
}
protected abstract void renderWindow(PoseStack ms, int mouseX, int mouseY, float partialTicks);
protected abstract void renderWindow(GuiGraphics graphics, int mouseX, int mouseY, float partialTicks);
protected void renderWindowForeground(PoseStack ms, int mouseX, int mouseY, float partialTicks) {
protected void renderWindowForeground(GuiGraphics graphics, int mouseX, int mouseY, float partialTicks) {
for (Renderable widget : renderables) {
if (widget instanceof AbstractSimiWidget simiWidget && simiWidget.isHoveredOrFocused()
if (widget instanceof AbstractSimiWidget simiWidget && simiWidget.isMouseOver(mouseX, mouseY)
&& simiWidget.visible) {
List<Component> tooltip = simiWidget.getToolTip();
if (tooltip.isEmpty())
continue;
int ttx = simiWidget.lockedTooltipX == -1 ? mouseX : simiWidget.lockedTooltipX + simiWidget.x;
int tty = simiWidget.lockedTooltipY == -1 ? mouseY : simiWidget.lockedTooltipY + simiWidget.y;
renderComponentTooltip(ms, tooltip, ttx, tty);
}
//Added
if (widget instanceof ModifiersScreenList list) {
list.renderWindowForeground(ms, mouseX, mouseY, partialTicks);
int ttx = simiWidget.lockedTooltipX == -1 ? mouseX : simiWidget.lockedTooltipX + simiWidget.getX();
int tty = simiWidget.lockedTooltipY == -1 ? mouseY : simiWidget.lockedTooltipY + simiWidget.getY();
graphics.renderComponentTooltip(font, tooltip, ttx, tty);
}
}
}
protected void endFrame() {}
@Deprecated
protected void debugWindowArea(PoseStack matrixStack) {
fill(matrixStack, guiLeft + windowWidth, guiTop + windowHeight, guiLeft, guiTop, 0xD3D3D3D3);
protected void debugWindowArea(GuiGraphics graphics) {
graphics.fill(guiLeft + windowWidth, guiTop + windowHeight, guiLeft, guiTop, 0xD3D3D3D3);
}
@Override

View File

@@ -1,18 +1,165 @@
package nl.requios.effortlessbuilding.create.foundation.gui;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.PoseStack;
import nl.requios.effortlessbuilding.create.Create;
import nl.requios.effortlessbuilding.create.foundation.gui.element.ScreenElement;
import nl.requios.effortlessbuilding.create.foundation.utility.Color;
import net.minecraft.client.gui.GuiComponent;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
public enum AllGuiTextures implements ScreenElement {
// Renderables
// Inventories
// PLAYER_INVENTORY("player_inventory", 176, 108),
// WAND_OF_SYMMETRY("curiosities", 0, 131, 188, 101),
// BLOCKZAPPER("curiosities", 0, 99, 214, 97),
// TERRAINZAPPER("curiosities", 234, 103),
// TERRAINZAPPER_INACTIVE_PARAM("curiosities", 238, 0, 18, 18),
//
// LOGO("logo", 256, 256),
// CURSEFORGE_LOGO("platform_icons/curseforge", 256, 256),
// MODRINTH_LOGO("platform_icons/modrinth", 256, 256),
//
// SCHEMATIC("schematics", 192, 121),
// SCHEMATIC_SLOT("widgets", 54, 0, 16, 16),
// SCHEMATIC_PROMPT("schematics_2", 213, 77),
// HUD_BACKGROUND("overlay", 0, 0, 16, 16),
//
// SCHEMATIC_TABLE("schematics", 0, 121, 214, 83),
// SCHEMATIC_TABLE_PROGRESS("schematics", 0, 204, 84, 16),
//
// SCHEMATICANNON_TOP("schematics_2", 0, 77, 213, 42),
// SCHEMATICANNON_BOTTOM("schematics_2", 0, 119, 213, 99),
// SCHEMATICANNON_PROGRESS("schematics_2", 76, 239, 114, 16),
// SCHEMATICANNON_CHECKLIST_PROGRESS("schematics_2", 191, 240, 16, 14),
// SCHEMATICANNON_HIGHLIGHT("schematics_2", 1, 229, 26, 26),
// SCHEMATICANNON_FUEL("schematics_2", 28, 222, 47, 16),
// SCHEMATICANNON_FUEL_CREATIVE("schematics_2", 28, 239, 47, 16),
//
// STOCKSWITCH("logistics", 182, 95),
// STOCKSWITCH_ARROW_UP("logistics", 191, 0, 7, 24),
// STOCKSWITCH_ARROW_DOWN("logistics", 198, 0, 7, 24),
// STOCKSWITCH_CURSOR("logistics", 206, 0, 7, 16),
// STOCKSWITCH_INTERVAL("logistics", 0, 95, 100, 18),
// STOCKSWITCH_UNPOWERED_LANE("logistics", 37, 20, 100, 18),
// STOCKSWITCH_POWERED_LANE("logistics", 37, 42, 100, 18),
//
// FILTER("filters", 214, 99),
// ATTRIBUTE_FILTER("filters", 0, 99, 241, 85),
//
// TOOLBOX("toolbox", 188, 171),
// TOOLBELT_SLOT("minecraft", "widgets", 24, 23, 22, 22),
// TOOLBELT_SLOT_HIGHLIGHT("minecraft", "widgets", 0, 22, 24, 24),
// TOOLBELT_MAIN_SLOT("widgets", 0, 97, 24, 24),
// TOOLBELT_EMPTY_SLOT("widgets", 27, 98, 22, 22),
// TOOLBELT_INACTIVE_SLOT("widgets", 52, 98, 22, 22),
//
// TOOLBELT_HOTBAR_OFF("widgets", 0, 130, 20, 24),
// TOOLBELT_HOTBAR_ON("widgets", 20, 130, 20, 24),
// TOOLBELT_SELECTED_OFF("widgets", 0, 155, 22, 22),
// TOOLBELT_SELECTED_ON("widgets", 22, 155, 22, 22),
//
// SEQUENCER("sequencer", 173, 161),
// SEQUENCER_INSTRUCTION("sequencer", 0, 16, 162, 22),
// SEQUENCER_DELAY("sequencer", 0, 60, 162, 22),
// SEQUENCER_END("sequencer", 0, 82, 162, 22),
// SEQUENCER_EMPTY("sequencer", 0, 104, 162, 22),
// SEQUENCER_AWAIT("sequencer", 0, 162, 162, 22),
//
// LINKED_CONTROLLER("curiosities_2", 179, 109),
// BLUEPRINT("curiosities_2", 0, 109, 179, 109),
//
// CLIPBOARD("clipboard", 0, 0, 256, 256),
//
// DATA_GATHERER("display_link", 235, 162),
// DATA_AREA_START("display_link", 0, 163, 2, 18),
// DATA_AREA_SPEECH("display_link", 8, 163, 5, 18),
// DATA_AREA("display_link", 3, 163, 1, 18),
// DATA_AREA_END("display_link", 5, 163, 2, 18),
//
// SCHEDULE("schedule", 256, 226),
// SCHEDULE_CARD_DARK("schedule", 5, 233, 1, 1),
// SCHEDULE_CARD_MEDIUM("schedule", 6, 233, 1, 1),
// SCHEDULE_CARD_LIGHT("schedule", 7, 233, 1, 1),
// SCHEDULE_CARD_MOVE_UP("schedule", 51, 230, 12, 12),
// SCHEDULE_CARD_MOVE_DOWN("schedule", 65, 230, 12, 12),
// SCHEDULE_CARD_REMOVE("schedule", 51, 243, 12, 12),
// SCHEDULE_CARD_DUPLICATE("schedule", 65, 243, 12, 12),
// SCHEDULE_CARD_NEW("schedule", 79, 239, 16, 16),
// SCHEDULE_CONDITION_NEW("schedule", 96, 239, 19, 16),
// SCHEDULE_CONDITION_LEFT("schedule", 116, 239, 6, 16),
// SCHEDULE_CONDITION_LEFT_CLEAN("schedule", 147, 239, 2, 16),
// SCHEDULE_CONDITION_MIDDLE("schedule", 123, 239, 1, 16),
// SCHEDULE_CONDITION_ITEM("schedule", 125, 239, 18, 16),
// SCHEDULE_CONDITION_RIGHT("schedule", 144, 239, 2, 16),
// SCHEDULE_CONDITION_APPEND("schedule", 150, 245, 10, 10),
// SCHEDULE_SCROLL_LEFT("schedule", 161, 247, 4, 8),
// SCHEDULE_SCROLL_RIGHT("schedule", 166, 247, 4, 8),
// SCHEDULE_STRIP_DARK("schedule", 5, 235, 3, 1),
// SCHEDULE_STRIP_LIGHT("schedule", 5, 237, 3, 1),
// SCHEDULE_STRIP_WAIT("schedule", 1, 239, 11, 16),
// SCHEDULE_STRIP_TRAVEL("schedule", 12, 239, 11, 16),
// SCHEDULE_STRIP_DOTTED("schedule", 23, 239, 11, 16),
// SCHEDULE_STRIP_END("schedule", 34, 239, 11, 16),
// SCHEDULE_STRIP_ACTION("schedule", 209, 239, 11, 16),
// SCHEDULE_EDITOR("schedule_2", 256, 89),
// SCHEDULE_EDITOR_ADDITIONAL_SLOT("schedule_2", 55, 47, 32, 18),
// SCHEDULE_EDITOR_INACTIVE_SLOT("schedule_2", 0, 91, 18, 18),
// SCHEDULE_POINTER("schedule", 185, 239, 21, 16),
// SCHEDULE_POINTER_OFFSCREEN("schedule", 171, 239, 13, 16),
//
// STATION("schedule_2", 0, 111, 200, 127),
// STATION_ASSEMBLING("assemble", 200, 178),
// STATION_TEXTBOX_TOP("assemble", 1, 179, 150, 18),
// STATION_TEXTBOX_MIDDLE("assemble", 1, 198, 150, 1),
// STATION_TEXTBOX_BOTTOM("assemble", 1, 200, 150, 4),
// STATION_TEXTBOX_SPEECH("assemble", 152, 179, 8, 6),
// STATION_EDIT_NAME("schedule_2", 0, 239, 13, 13),
// STATION_EDIT_TRAIN_NAME("schedule_2", 89, 239, 13, 13),
// I_NEW_TRAIN("schedule_2", 14, 239, 24, 16),
// I_DISASSEMBLE_TRAIN("schedule_2", 39, 239, 24, 16),
// I_ASSEMBLE_TRAIN("schedule_2", 64, 239, 24, 16),
//
// ELEVATOR_CONTACT("display_link", 20, 172, 233, 82),
//
// BRASS_FRAME_TL("value_settings", 65, 9, 4, 4),
// BRASS_FRAME_TR("value_settings", 70, 9, 4, 4),
// BRASS_FRAME_BL("value_settings", 65, 19, 4, 4),
// BRASS_FRAME_BR("value_settings", 70, 19, 4, 4),
// BRASS_FRAME_LEFT("value_settings", 65, 14, 3, 4),
// BRASS_FRAME_RIGHT("value_settings", 71, 14, 3, 4),
// BRASS_FRAME_TOP("value_settings", 0, 24, 256, 3),
// BRASS_FRAME_BOTTOM("value_settings", 0, 27, 256, 3),
//
// VALUE_SETTINGS_MILESTONE("value_settings", 0, 0, 7, 8),
// VALUE_SETTINGS_WIDE_MILESTONE("value_settings", 75, 14, 13, 8),
// VALUE_SETTINGS_BAR("value_settings", 7, 0, 249, 8),
// VALUE_SETTINGS_BAR_BG("value_settings", 75, 9, 1, 1),
// VALUE_SETTINGS_OUTER_BG("value_settings", 80, 9, 1, 1),
// VALUE_SETTINGS_CURSOR_LEFT("value_settings", 0, 9, 3, 14),
// VALUE_SETTINGS_CURSOR("value_settings", 4, 9, 56, 14),
// VALUE_SETTINGS_CURSOR_RIGHT("value_settings", 61, 9, 3, 14),
// VALUE_SETTINGS_CURSOR_ICON("value_settings", 0, 44, 22, 20),
// VALUE_SETTINGS_LABEL_BG("value_settings", 0, 31, 81, 11),
//
// // JEI
// JEI_SLOT("jei/widgets", 18, 18),
// JEI_CHANCE_SLOT("jei/widgets", 20, 156, 18, 18),
// JEI_CATALYST_SLOT("jei/widgets", 0, 156, 18, 18),
// JEI_ARROW("jei/widgets", 19, 10, 42, 10),
// JEI_LONG_ARROW("jei/widgets", 19, 0, 71, 10),
// JEI_DOWN_ARROW("jei/widgets", 0, 21, 18, 14),
// JEI_LIGHT("jei/widgets", 0, 42, 52, 11),
// JEI_QUESTION_MARK("jei/widgets", 0, 178, 12, 16),
// JEI_SHADOW("jei/widgets", 0, 56, 52, 11),
// BLOCKZAPPER_UPGRADE_RECIPE("jei/widgets", 0, 75, 144, 66),
// JEI_HEAT_BAR("jei/widgets", 0, 201, 169, 19),
// JEI_NO_HEAT_BAR("jei/widgets", 0, 221, 169, 19),
// Widgets
BUTTON("widgets", 18, 18),
BUTTON_HOVER("widgets", 18, 0, 18, 18),
BUTTON_DOWN("widgets", 36, 0, 18, 18),
@@ -30,15 +177,21 @@ public enum AllGuiTextures implements ScreenElement {
SPEECH_TOOLTIP_BACKGROUND("widgets", 0, 24, 8, 8),
SPEECH_TOOLTIP_COLOR("widgets", 8, 24, 8, 8),
TRAIN_HUD_SPEED_BG("widgets", 0, 190, 182, 5),
TRAIN_HUD_SPEED("widgets", 0, 185, 182, 5),
TRAIN_HUD_THROTTLE("widgets", 0, 195, 182, 5),
TRAIN_HUD_THROTTLE_POINTER("widgets", 0, 209, 6, 9),
TRAIN_HUD_FRAME("widgets", 0, 200, 186, 7),
TRAIN_HUD_DIRECTION("widgets", 77, 165, 28, 20),
TRAIN_PROMPT_L("widgets", 8, 209, 3, 16),
TRAIN_PROMPT_R("widgets", 11, 209, 3, 16),
TRAIN_PROMPT("widgets", 0, 230, 256, 16),
// TRAIN_HUD_SPEED_BG("widgets", 0, 190, 182, 5),
// TRAIN_HUD_SPEED("widgets", 0, 185, 182, 5),
// TRAIN_HUD_THROTTLE("widgets", 0, 195, 182, 5),
// TRAIN_HUD_THROTTLE_POINTER("widgets", 0, 209, 6, 9),
// TRAIN_HUD_FRAME("widgets", 0, 200, 186, 7),
// TRAIN_HUD_DIRECTION("widgets", 77, 165, 28, 20),
// TRAIN_PROMPT_L("widgets", 8, 209, 3, 16),
// TRAIN_PROMPT_R("widgets", 11, 209, 3, 16),
// TRAIN_PROMPT("widgets", 0, 230, 256, 16),
// PlacementIndicator
// PLACEMENT_INDICATOR_SHEET("placement_indicator", 0, 0, 16, 256),
// ComputerCraft
// COMPUTER("computer", 200, 102);
;
@@ -74,22 +227,14 @@ public enum AllGuiTextures implements ScreenElement {
}
@OnlyIn(Dist.CLIENT)
@Override
public void render(PoseStack ms, int x, int y) {
bind();
GuiComponent.blit(ms, x, y, 0, startX, startY, width, height, 256, 256);
public void render(GuiGraphics graphics, int x, int y) {
graphics.blit(location, x, y, startX, startY, width, height);
}
@OnlyIn(Dist.CLIENT)
public void render(PoseStack ms, int x, int y, GuiComponent component) {
public void render(GuiGraphics graphics, int x, int y, Color c) {
bind();
component.blit(ms, x, y, startX, startY, width, height);
}
@OnlyIn(Dist.CLIENT)
public void render(PoseStack ms, int x, int y, Color c) {
bind();
UIRenderHelper.drawColoredTexture(ms, c, x, y, startX, startY, width, height);
UIRenderHelper.drawColoredTexture(graphics, c, x, y, startX, startY, width, height);
}
}

View File

@@ -1,14 +1,16 @@
package nl.requios.effortlessbuilding.create.foundation.gui;
import org.joml.Matrix4f;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.blaze3d.vertex.VertexConsumer;
import org.joml.Matrix4f;
import nl.requios.effortlessbuilding.create.Create;
import nl.requios.effortlessbuilding.create.foundation.gui.element.DelegatedStencilElement;
import nl.requios.effortlessbuilding.create.foundation.gui.element.ScreenElement;
import nl.requios.effortlessbuilding.create.foundation.utility.Color;
import net.minecraft.client.gui.GuiComponent;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.renderer.LightTexture;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.RenderType;
@@ -19,7 +21,7 @@ import net.minecraftforge.api.distmarker.OnlyIn;
public class AllIcons implements ScreenElement {
public static final ResourceLocation ICON_ATLAS = Create.asResource("textures/gui/create_icons.png");
public static final ResourceLocation ICON_ATLAS = Create.asResource("textures/gui/icons.png");
public static final int ICON_ATLAS_SIZE = 256;
private static int x = 0, y = -1;
@@ -81,7 +83,7 @@ public class AllIcons implements ScreenElement {
public static final AllIcons
I_TOOL_DEPLOY = newRow(),
I_SKIP_MISSING = next(),
I_SKIP_TILES = next(),
I_SKIP_BLOCK_ENTITIES = next(),
I_DICE = next(),
I_TUNNEL_SPLIT = next(),
I_TUNNEL_FORCED_SPLIT = next(),
@@ -104,6 +106,10 @@ public class AllIcons implements ScreenElement {
I_ADD_INVERTED_ATTRIBUTE = next(),
I_FLIP = next(),
I_ROLLER_PAVE = next(),
I_ROLLER_FILL = next(),
I_ROLLER_WIDE_FILL = next(),
I_PLAY = newRow(),
I_PAUSE = next(),
I_STOP = next(),
@@ -123,8 +129,13 @@ public class AllIcons implements ScreenElement {
I_FOLLOW_DIAGONAL = next(),
I_FOLLOW_MATERIAL = next(),
I_CLEAR_CHECKED = next(),
I_SCHEMATIC = newRow(),
I_SEQ_REPEAT = next(),
VALUE_BOX_HOVER_6PX = next(),
VALUE_BOX_HOVER_4PX = next(),
VALUE_BOX_HOVER_8PX = next(),
I_MTD_LEFT = newRow(),
I_MTD_CLOSE = next(),
@@ -173,20 +184,13 @@ public class AllIcons implements ScreenElement {
@OnlyIn(Dist.CLIENT)
@Override
public void render(PoseStack matrixStack, int x, int y) {
bind();
GuiComponent.blit(matrixStack, x, y, 0, iconX, iconY, 16, 16, 256, 256);
}
@OnlyIn(Dist.CLIENT)
public void render(PoseStack matrixStack, int x, int y, GuiComponent component) {
bind();
component.blit(matrixStack, x, y, iconX, iconY, 16, 16);
public void render(GuiGraphics graphics, int x, int y) {
graphics.blit(ICON_ATLAS, x, y, 0, iconX, iconY, 16, 16, 256, 256);
}
@OnlyIn(Dist.CLIENT)
public void render(PoseStack ms, MultiBufferSource buffer, int color) {
VertexConsumer builder = buffer.getBuffer(RenderType.textSeeThrough(ICON_ATLAS));
VertexConsumer builder = buffer.getBuffer(RenderType.text(ICON_ATLAS));
Matrix4f matrix = ms.last().pose();
Color rgb = new Color(color);
int light = LightTexture.FULL_BRIGHT;

View File

@@ -1,20 +1,24 @@
package nl.requios.effortlessbuilding.create.foundation.gui;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import javax.annotation.Nonnull;
import org.lwjgl.opengl.GL30;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.PoseStack;
import nl.requios.effortlessbuilding.create.foundation.gui.element.BoxElement;
import nl.requios.effortlessbuilding.create.foundation.gui.element.TextStencilElement;
import nl.requios.effortlessbuilding.create.foundation.gui.widget.BoxWidget;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.network.chat.FormattedText;
import net.minecraft.network.chat.Style;
import org.lwjgl.opengl.GL30;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
public class ConfirmationScreen extends AbstractSimiScreen {
@@ -173,11 +177,12 @@ public class ConfirmationScreen extends AbstractSimiScreen {
}
@Override
protected void renderWindow(PoseStack ms, int mouseX, int mouseY, float partialTicks) {
textBackground.render(ms);
protected void renderWindow(GuiGraphics graphics, int mouseX, int mouseY, float partialTicks) {
textBackground.render(graphics);
int offset = font.lineHeight + 1;
int lineY = y - offset;
PoseStack ms = graphics.pose();
ms.pushPose();
ms.translate(0, 0, 200);
@@ -185,21 +190,21 @@ public class ConfirmationScreen extends AbstractSimiScreen {
lineY += offset;
if (line == null)
continue;
font.draw(ms, line.getString(), x, lineY, 0xeaeaea);
graphics.drawString(font, line.getString(), x, lineY, 0xeaeaea, false);
}
ms.popPose();
}
@Override
protected void renderWindowBackground(PoseStack ms, int mouseX, int mouseY, float partialTicks) {
protected void renderWindowBackground(GuiGraphics graphics, int mouseX, int mouseY, float partialTicks) {
endFrame();
source.render(ms, 0, 0, 10); // zero mouse coords to prevent further tooltips
source.render(graphics, 0, 0, 10); // zero mouse coords to prevent further tooltips
prepareFrame();
this.fillGradient(ms, 0, 0, this.width, this.height, 0x70101010, 0x80101010);
graphics.fillGradient(0, 0, this.width, this.height, 0x70101010, 0x80101010);
}

View File

@@ -1,9 +1,11 @@
package nl.requios.effortlessbuilding.create.foundation.gui;
import com.mojang.blaze3d.systems.RenderSystem;
import org.joml.Matrix4f;
import org.joml.Vector3f;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.math.Axis;
public class CustomLightingSettings implements ILightingSettings {
private Vector3f light1;
@@ -19,20 +21,20 @@ public class CustomLightingSettings implements ILightingSettings {
}
protected void init(float yRot1, float xRot1, float yRot2, float xRot2, boolean doubleLight) {
light1 = Vector3f.ZP.copy();
light1.transform(Vector3f.YP.rotationDegrees(yRot1));
light1.transform(Vector3f.XN.rotationDegrees(xRot1));
light1 = new Vector3f(0, 0, 1);
light1.rotate(Axis.YP.rotationDegrees(yRot1));
light1.rotate(Axis.XN.rotationDegrees(xRot1));
if (doubleLight) {
light2 = Vector3f.ZP.copy();
light2.transform(Vector3f.YP.rotationDegrees(yRot2));
light2.transform(Vector3f.XN.rotationDegrees(xRot2));
light2 = new Vector3f(0, 0, 1);
light2.rotate(Axis.YP.rotationDegrees(yRot2));
light2.rotate(Axis.XN.rotationDegrees(xRot2));
} else {
light2 = Vector3f.ZERO;
light2 = new Vector3f();
}
lightMatrix = new Matrix4f();
lightMatrix.setIdentity();
lightMatrix.identity();
}
@Override

View File

@@ -0,0 +1,115 @@
package nl.requios.effortlessbuilding.create.foundation.gui;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import nl.requios.effortlessbuilding.create.foundation.gui.widget.ScrollInput;
import nl.requios.effortlessbuilding.create.foundation.gui.widget.TooltipArea;
import nl.requios.effortlessbuilding.create.foundation.utility.Couple;
import nl.requios.effortlessbuilding.create.foundation.utility.Pair;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.components.AbstractWidget;
import net.minecraft.client.gui.components.EditBox;
import net.minecraft.client.gui.components.Renderable;
import net.minecraft.client.gui.components.events.GuiEventListener;
import net.minecraft.client.gui.narration.NarratableEntry;
import net.minecraft.nbt.CompoundTag;
public class ModularGuiLine {
List<Pair<AbstractWidget, String>> widgets;
List<Couple<Integer>> customBoxes;
boolean speechBubble;
public ModularGuiLine() {
widgets = new ArrayList<>();
customBoxes = new ArrayList<>();
speechBubble = false;
}
public void renderWidgetBG(int guiLeft, GuiGraphics graphics) {
boolean first = true;
if (!customBoxes.isEmpty()) {
for (Couple<Integer> couple : customBoxes) {
int x = couple.getFirst() + guiLeft;
int width = couple.getSecond();
box(graphics, x, width, first & speechBubble);
first = false;
}
return;
}
for (Pair<AbstractWidget, String> pair : widgets) {
if (pair.getSecond()
.equals("Dummy"))
continue;
AbstractWidget aw = pair.getFirst();
int x = aw.getX();
int width = aw.getWidth();
if (aw instanceof EditBox) {
x -= 5;
width += 9;
}
box(graphics, x, width, first & speechBubble);
first = false;
}
}
private void box(GuiGraphics graphics, int x, int width, boolean b) {
UIRenderHelper.drawStretched(graphics, x, 0, width, 18, 0, AllGuiTextures.DATA_AREA);
if (b)
AllGuiTextures.DATA_AREA_SPEECH.render(graphics, x - 3, 0);
else
AllGuiTextures.DATA_AREA_START.render(graphics, x, 0);
AllGuiTextures.DATA_AREA_END.render(graphics, x + width - 2, 0);
}
public void saveValues(CompoundTag data) {
for (Pair<AbstractWidget, String> pair : widgets) {
AbstractWidget w = pair.getFirst();
String key = pair.getSecond();
if (w instanceof EditBox eb)
data.putString(key, eb.getValue());
if (w instanceof ScrollInput si)
data.putInt(key, si.getState());
}
}
@SuppressWarnings("unchecked")
public <T extends GuiEventListener & Renderable & NarratableEntry> void loadValues(CompoundTag data,
Consumer<T> addRenderable, Consumer<T> addRenderableOnly) {
for (Pair<AbstractWidget, String> pair : widgets) {
AbstractWidget w = pair.getFirst();
String key = pair.getSecond();
if (w instanceof EditBox eb)
eb.setValue(data.getString(key));
if (w instanceof ScrollInput si)
si.setState(data.getInt(key));
if (w instanceof TooltipArea)
addRenderableOnly.accept((T) w);
else
addRenderable.accept((T) w);
}
}
public void forEach(Consumer<GuiEventListener> callback) {
widgets.forEach(p -> callback.accept(p.getFirst()));
}
public void clear() {
widgets.clear();
customBoxes.clear();
}
public void add(Pair<AbstractWidget, String> pair) {
widgets.add(pair);
}
}

View File

@@ -0,0 +1,91 @@
package nl.requios.effortlessbuilding.create.foundation.gui;
import java.util.function.BiConsumer;
import nl.requios.effortlessbuilding.create.foundation.gui.widget.Label;
import nl.requios.effortlessbuilding.create.foundation.gui.widget.ScrollInput;
import nl.requios.effortlessbuilding.create.foundation.gui.widget.SelectionScrollInput;
import nl.requios.effortlessbuilding.create.foundation.gui.widget.TooltipArea;
import nl.requios.effortlessbuilding.create.foundation.utility.Components;
import nl.requios.effortlessbuilding.create.foundation.utility.Couple;
import nl.requios.effortlessbuilding.create.foundation.utility.Pair;
import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.components.EditBox;
public class ModularGuiLineBuilder {
private ModularGuiLine target;
private Font font;
private int x;
private int y;
public ModularGuiLineBuilder(Font font, ModularGuiLine target, int x, int y) {
this.font = font;
this.target = target;
this.x = x;
this.y = y;
}
public ModularGuiLineBuilder addScrollInput(int x, int width, BiConsumer<ScrollInput, Label> inputTransform,
String dataKey) {
ScrollInput input = new ScrollInput(x + this.x, y - 4, width, 18);
addScrollInput(input, inputTransform, dataKey);
return this;
}
public ModularGuiLineBuilder addSelectionScrollInput(int x, int width,
BiConsumer<SelectionScrollInput, Label> inputTransform, String dataKey) {
SelectionScrollInput input = new SelectionScrollInput(x + this.x, y - 4, width, 18);
addScrollInput(input, inputTransform, dataKey);
return this;
}
public ModularGuiLineBuilder customArea(int x, int width) {
target.customBoxes.add(Couple.create(x, width));
return this;
}
public ModularGuiLineBuilder speechBubble() {
target.speechBubble = true;
return this;
}
private <T extends ScrollInput> void addScrollInput(T input, BiConsumer<T, Label> inputTransform, String dataKey) {
Label label = new Label(input.getX() + 5, y, Components.immutableEmpty());
label.withShadow();
inputTransform.accept(input, label);
input.writingTo(label);
target.add(Pair.of(label, "Dummy"));
target.add(Pair.of(input, dataKey));
}
public ModularGuiLineBuilder addIntegerTextInput(int x, int width, BiConsumer<EditBox, TooltipArea> inputTransform,
String dataKey) {
return addTextInput(x, width, inputTransform.andThen((editBox, $) -> editBox.setFilter(s -> {
if (s.isEmpty())
return true;
try {
Integer.parseInt(s);
return true;
} catch (NumberFormatException e) {
return false;
}
})), dataKey);
}
public ModularGuiLineBuilder addTextInput(int x, int width, BiConsumer<EditBox, TooltipArea> inputTransform,
String dataKey) {
EditBox input = new EditBox(font, x + this.x + 5, y, width - 9, 8, Components.immutableEmpty());
input.setBordered(false);
input.setTextColor(0xffffff);
input.setFocused(false);
input.mouseClicked(0, 0, 0);
TooltipArea tooltipArea = new TooltipArea(this.x + x, y - 4, width, 18);
inputTransform.accept(input, tooltipArea);
target.add(Pair.of(input, dataKey));
target.add(Pair.of(tooltipArea, "Dummy"));
return this;
}
}

View File

@@ -1,10 +1,18 @@
package nl.requios.effortlessbuilding.create.foundation.gui;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nonnull;
import org.joml.Matrix4f;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.blaze3d.vertex.Tesselator;
import org.joml.Matrix4f;
import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipComponent;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.network.chat.FormattedText;
@@ -12,13 +20,9 @@ import net.minecraft.network.chat.Style;
import net.minecraft.world.item.ItemStack;
import net.minecraftforge.client.ForgeHooksClient;
import net.minecraftforge.client.event.RenderTooltipEvent;
import net.minecraftforge.client.gui.ScreenUtils;
import net.minecraftforge.client.extensions.IForgeGuiGraphics;
import net.minecraftforge.common.MinecraftForge;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.List;
public class RemovedGuiUtils {
@Nonnull
private static ItemStack cachedTooltipStack = ItemStack.EMPTY;
@@ -31,41 +35,43 @@ public class RemovedGuiUtils {
cachedTooltipStack = ItemStack.EMPTY;
}
public static void drawHoveringText(PoseStack mStack, List<? extends FormattedText> textLines, int mouseX,
public static void drawHoveringText(GuiGraphics graphics, List<? extends FormattedText> textLines, int mouseX,
int mouseY, int screenWidth, int screenHeight, int maxTextWidth, Font font) {
drawHoveringText(mStack, textLines, mouseX, mouseY, screenWidth, screenHeight, maxTextWidth,
ScreenUtils.DEFAULT_BACKGROUND_COLOR, ScreenUtils.DEFAULT_BORDER_COLOR_START, ScreenUtils.DEFAULT_BORDER_COLOR_END,
drawHoveringText(graphics, textLines, mouseX, mouseY, screenWidth, screenHeight, maxTextWidth,
IForgeGuiGraphics.DEFAULT_BACKGROUND_COLOR, IForgeGuiGraphics.DEFAULT_BORDER_COLOR_START, IForgeGuiGraphics.DEFAULT_BORDER_COLOR_END,
font);
}
public static void drawHoveringText(PoseStack mStack, List<? extends FormattedText> textLines, int mouseX,
public static void drawHoveringText(GuiGraphics graphics, List<? extends FormattedText> textLines, int mouseX,
int mouseY, int screenWidth, int screenHeight, int maxTextWidth, int backgroundColor, int borderColorStart,
int borderColorEnd, Font font) {
drawHoveringText(cachedTooltipStack, mStack, textLines, mouseX, mouseY, screenWidth, screenHeight, maxTextWidth,
drawHoveringText(cachedTooltipStack, graphics, textLines, mouseX, mouseY, screenWidth, screenHeight, maxTextWidth,
backgroundColor, borderColorStart, borderColorEnd, font);
}
public static void drawHoveringText(@Nonnull final ItemStack stack, PoseStack mStack,
public static void drawHoveringText(@Nonnull final ItemStack stack, GuiGraphics graphics,
List<? extends FormattedText> textLines, int mouseX, int mouseY, int screenWidth, int screenHeight,
int maxTextWidth, Font font) {
drawHoveringText(stack, mStack, textLines, mouseX, mouseY, screenWidth, screenHeight, maxTextWidth,
ScreenUtils.DEFAULT_BACKGROUND_COLOR, ScreenUtils.DEFAULT_BORDER_COLOR_START, ScreenUtils.DEFAULT_BORDER_COLOR_END,
drawHoveringText(stack, graphics, textLines, mouseX, mouseY, screenWidth, screenHeight, maxTextWidth,
IForgeGuiGraphics.DEFAULT_BACKGROUND_COLOR, IForgeGuiGraphics.DEFAULT_BORDER_COLOR_START, IForgeGuiGraphics.DEFAULT_BORDER_COLOR_END,
font);
}
public static void drawHoveringText(@Nonnull final ItemStack stack, PoseStack pStack,
public static void drawHoveringText(@Nonnull final ItemStack stack, GuiGraphics graphics,
List<? extends FormattedText> textLines, int mouseX, int mouseY, int screenWidth, int screenHeight,
int maxTextWidth, int backgroundColor, int borderColorStart, int borderColorEnd, Font font) {
if (textLines.isEmpty())
return;
List<ClientTooltipComponent> list = ForgeHooksClient.gatherTooltipComponents(stack, textLines,
stack.getTooltipImage(), mouseX, screenWidth, screenHeight, font, font);
stack.getTooltipImage(), mouseX, screenWidth, screenHeight, font);
RenderTooltipEvent.Pre event =
new RenderTooltipEvent.Pre(stack, pStack, mouseX, mouseY, screenWidth, screenHeight, font, list);
new RenderTooltipEvent.Pre(stack, graphics, mouseX, mouseY, screenWidth, screenHeight, font, list, null);
if (MinecraftForge.EVENT_BUS.post(event))
return;
PoseStack pStack = graphics.pose();
mouseX = event.getX();
mouseY = event.getY();
screenWidth = event.getScreenWidth();
@@ -144,7 +150,7 @@ public class RemovedGuiUtils {
tooltipY = screenHeight - tooltipHeight - 4;
final int zLevel = 400;
RenderTooltipEvent.Color colorEvent = new RenderTooltipEvent.Color(stack, pStack, tooltipX, tooltipY,
RenderTooltipEvent.Color colorEvent = new RenderTooltipEvent.Color(stack, graphics, tooltipX, tooltipY,
font, backgroundColor, borderColorStart, borderColorEnd, list);
MinecraftForge.EVENT_BUS.post(colorEvent);
backgroundColor = colorEvent.getBackgroundStart();
@@ -154,24 +160,24 @@ public class RemovedGuiUtils {
pStack.pushPose();
Matrix4f mat = pStack.last()
.pose();
ScreenUtils.drawGradientRect(mat, zLevel, tooltipX - 3, tooltipY - 4, tooltipX + tooltipTextWidth + 3,
tooltipY - 3, backgroundColor, backgroundColor);
ScreenUtils.drawGradientRect(mat, zLevel, tooltipX - 3, tooltipY + tooltipHeight + 3,
tooltipX + tooltipTextWidth + 3, tooltipY + tooltipHeight + 4, backgroundColor, backgroundColor);
ScreenUtils.drawGradientRect(mat, zLevel, tooltipX - 3, tooltipY - 3, tooltipX + tooltipTextWidth + 3,
tooltipY + tooltipHeight + 3, backgroundColor, backgroundColor);
ScreenUtils.drawGradientRect(mat, zLevel, tooltipX - 4, tooltipY - 3, tooltipX - 3, tooltipY + tooltipHeight + 3,
backgroundColor, backgroundColor);
ScreenUtils.drawGradientRect(mat, zLevel, tooltipX + tooltipTextWidth + 3, tooltipY - 3,
tooltipX + tooltipTextWidth + 4, tooltipY + tooltipHeight + 3, backgroundColor, backgroundColor);
ScreenUtils.drawGradientRect(mat, zLevel, tooltipX - 3, tooltipY - 3 + 1, tooltipX - 3 + 1,
tooltipY + tooltipHeight + 3 - 1, borderColorStart, borderColorEnd);
ScreenUtils.drawGradientRect(mat, zLevel, tooltipX + tooltipTextWidth + 2, tooltipY - 3 + 1,
tooltipX + tooltipTextWidth + 3, tooltipY + tooltipHeight + 3 - 1, borderColorStart, borderColorEnd);
ScreenUtils.drawGradientRect(mat, zLevel, tooltipX - 3, tooltipY - 3, tooltipX + tooltipTextWidth + 3,
tooltipY - 3 + 1, borderColorStart, borderColorStart);
ScreenUtils.drawGradientRect(mat, zLevel, tooltipX - 3, tooltipY + tooltipHeight + 2,
tooltipX + tooltipTextWidth + 3, tooltipY + tooltipHeight + 3, borderColorEnd, borderColorEnd);
graphics.fillGradient(tooltipX - 3, tooltipY - 4, tooltipX + tooltipTextWidth + 3,
tooltipY - 3, zLevel, backgroundColor, backgroundColor);
graphics.fillGradient(tooltipX - 3, tooltipY + tooltipHeight + 3,
tooltipX + tooltipTextWidth + 3, tooltipY + tooltipHeight + 4, zLevel, backgroundColor, backgroundColor);
graphics.fillGradient(tooltipX - 3, tooltipY - 3, tooltipX + tooltipTextWidth + 3,
tooltipY + tooltipHeight + 3, zLevel, backgroundColor, backgroundColor);
graphics.fillGradient(tooltipX - 4, tooltipY - 3, tooltipX - 3, tooltipY + tooltipHeight + 3,
zLevel, backgroundColor, backgroundColor);
graphics.fillGradient(tooltipX + tooltipTextWidth + 3, tooltipY - 3,
tooltipX + tooltipTextWidth + 4, tooltipY + tooltipHeight + 3, zLevel, backgroundColor, backgroundColor);
graphics.fillGradient(tooltipX - 3, tooltipY - 3 + 1, tooltipX - 3 + 1,
tooltipY + tooltipHeight + 3 - 1, zLevel, borderColorStart, borderColorEnd);
graphics.fillGradient(tooltipX + tooltipTextWidth + 2, tooltipY - 3 + 1,
tooltipX + tooltipTextWidth + 3, tooltipY + tooltipHeight + 3 - 1, zLevel, borderColorStart, borderColorEnd);
graphics.fillGradient(tooltipX - 3, tooltipY - 3, tooltipX + tooltipTextWidth + 3,
tooltipY - 3 + 1, zLevel, borderColorStart, borderColorStart);
graphics.fillGradient(tooltipX - 3, tooltipY + tooltipHeight + 2,
tooltipX + tooltipTextWidth + 3, tooltipY + tooltipHeight + 3, zLevel, borderColorEnd, borderColorEnd);
MultiBufferSource.BufferSource renderType = MultiBufferSource.immediate(Tesselator.getInstance()
.getBuilder());

View File

@@ -1,11 +1,17 @@
package nl.requios.effortlessbuilding.create.foundation.gui;
import nl.requios.effortlessbuilding.create.foundation.utility.Color;
import nl.requios.effortlessbuilding.create.foundation.utility.Couple;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.*;
import nl.requios.effortlessbuilding.create.foundation.utility.Color;
import nl.requios.effortlessbuilding.create.foundation.utility.Couple;
public class Theme {

View File

@@ -1,22 +1,26 @@
package nl.requios.effortlessbuilding.create.foundation.gui;
import org.joml.Matrix4f;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL30;
import com.mojang.blaze3d.pipeline.RenderTarget;
import com.mojang.blaze3d.platform.GlConst;
import com.mojang.blaze3d.platform.GlStateManager;
import com.mojang.blaze3d.platform.Window;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.*;
import org.joml.Matrix4f;
import org.joml.Vector3f;
import com.mojang.blaze3d.vertex.BufferBuilder;
import com.mojang.blaze3d.vertex.DefaultVertexFormat;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.blaze3d.vertex.Tesselator;
import com.mojang.blaze3d.vertex.VertexFormat;
import com.mojang.math.Axis;
import nl.requios.effortlessbuilding.create.foundation.utility.Color;
import nl.requios.effortlessbuilding.create.foundation.utility.Couple;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GameRenderer;
import net.minecraftforge.client.gui.ScreenUtils;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL30;
import javax.annotation.Nonnull;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.renderer.GameRenderer;
public class UIRenderHelper {
@@ -53,14 +57,14 @@ public class UIRenderHelper {
GlStateManager._glBindFramebuffer(GlConst.GL_FRAMEBUFFER, dst.frameBufferId);
}
public static void streak(PoseStack ms, float angle, int x, int y, int breadth, int length) {
streak(ms, angle, x, y, breadth, length, Theme.i(Theme.Key.STREAK));
public static void streak(GuiGraphics graphics, float angle, int x, int y, int breadth, int length) {
streak(graphics, angle, x, y, breadth, length, Theme.i(Theme.Key.STREAK));
}
// angle in degrees; 0° -> fading to the right
// x and y specify the middle point of the starting edge
// breadth is the total width of the streak
public static void streak(PoseStack ms, float angle, int x, int y, int breadth, int length, int color) {
public static void streak(GuiGraphics graphics, float angle, int x, int y, int breadth, int length, int color) {
int a1 = 0xa0 << 24;
int a2 = 0x80 << 24;
int a3 = 0x10 << 24;
@@ -72,59 +76,60 @@ public class UIRenderHelper {
int c3 = a3 | color;
int c4 = a4 | color;
PoseStack ms = graphics.pose();
ms.pushPose();
ms.translate(x, y, 0);
ms.mulPose(Vector3f.ZP.rotationDegrees(angle - 90));
ms.mulPose(Axis.ZP.rotationDegrees(angle - 90));
streak(ms, breadth / 2, length, c1, c2, c3, c4);
streak(graphics, breadth / 2, length, c1, c2, c3, c4);
ms.popPose();
}
public static void streak(PoseStack ms, float angle, int x, int y, int breadth, int length, Color c) {
public static void streak(GuiGraphics graphics, float angle, int x, int y, int breadth, int length, Color c) {
Color color = c.copy().setImmutable();
int c1 = color.scaleAlpha(0.625f).getRGB();
int c2 = color.scaleAlpha(0.5f).getRGB();
int c3 = color.scaleAlpha(0.0625f).getRGB();
int c4 = color.scaleAlpha(0f).getRGB();
PoseStack ms = graphics.pose();
ms.pushPose();
ms.translate(x, y, 0);
ms.mulPose(Vector3f.ZP.rotationDegrees(angle - 90));
ms.mulPose(Axis.ZP.rotationDegrees(angle - 90));
streak(ms, breadth / 2, length, c1, c2, c3, c4);
streak(graphics, breadth / 2, length, c1, c2, c3, c4);
ms.popPose();
}
private static void streak(PoseStack ms, int width, int height, int c1, int c2, int c3, int c4) {
private static void streak(GuiGraphics graphics, int width, int height, int c1, int c2, int c3, int c4) {
double split1 = .5;
double split2 = .75;
Matrix4f model = ms.last().pose();
ScreenUtils.drawGradientRect(model, 0, -width, 0, width, (int) (split1 * height), c1, c2);
ScreenUtils.drawGradientRect(model, 0, -width, (int) (split1 * height), width, (int) (split2 * height), c2, c3);
ScreenUtils.drawGradientRect(model, 0, -width, (int) (split2 * height), width, height, c3, c4);
graphics.fillGradient(-width, 0, width, (int) (split1 * height), 0, c1, c2);
graphics.fillGradient(-width, (int) (split1 * height), width, (int) (split2 * height), 0, c2, c3);
graphics.fillGradient(-width, (int) (split2 * height), width, height, 0, c3, c4);
}
/**
* @see #angledGradient(MatrixStack, float, int, int, int, int, int, Color, Color)
*/
public static void angledGradient(@Nonnull PoseStack ms, float angle, int x, int y, int breadth, int length, Couple<Color> c) {
angledGradient(ms, angle, x, y, 0, breadth, length, c);
public static void angledGradient(GuiGraphics graphics, float angle, int x, int y, int breadth, int length, Couple<Color> c) {
angledGradient(graphics, angle, x, y, 0, breadth, length, c);
}
/**
* @see #angledGradient(MatrixStack, float, int, int, int, int, int, Color, Color)
*/
public static void angledGradient(@Nonnull PoseStack ms, float angle, int x, int y, int z, int breadth, int length, Couple<Color> c) {
angledGradient(ms, angle, x, y, z, breadth, length, c.getFirst(), c.getSecond());
public static void angledGradient(GuiGraphics graphics, float angle, int x, int y, int z, int breadth, int length, Couple<Color> c) {
angledGradient(graphics, angle, x, y, z, breadth, length, c.getFirst(), c.getSecond());
}
/**
* @see #angledGradient(MatrixStack, float, int, int, int, int, int, Color, Color)
*/
public static void angledGradient(@Nonnull PoseStack ms, float angle, int x, int y, int breadth, int length, Color color1, Color color2) {
angledGradient(ms, angle, x, y, 0, breadth, length, color1, color2);
public static void angledGradient(GuiGraphics graphics, float angle, int x, int y, int breadth, int length, Color color1, Color color2) {
angledGradient(graphics, angle, x, y, 0, breadth, length, color1, color2);
}
/**
@@ -135,31 +140,32 @@ public class UIRenderHelper {
* @param color2 the color at the ending edge
* @param breadth the total width of the gradient
*/
public static void angledGradient(@Nonnull PoseStack ms, float angle, int x, int y, int z, int breadth, int length, Color color1, Color color2) {
public static void angledGradient(GuiGraphics graphics, float angle, int x, int y, int z, int breadth, int length, Color color1, Color color2) {
PoseStack ms = graphics.pose();
ms.pushPose();
ms.translate(x, y, z);
ms.mulPose(Vector3f.ZP.rotationDegrees(angle - 90));
ms.mulPose(Axis.ZP.rotationDegrees(angle - 90));
Matrix4f model = ms.last().pose();
int w = breadth / 2;
ScreenUtils.drawGradientRect(model, 0, -w, 0, w, length, color1.getRGB(), color2.getRGB());
graphics.fillGradient(-w, 0, w, length, 0, color1.getRGB(), color2.getRGB());
ms.popPose();
}
public static void breadcrumbArrow(PoseStack matrixStack, int x, int y, int z, int width, int height, int indent, Couple<Color> colors) {breadcrumbArrow(matrixStack, x, y, z, width, height, indent, colors.getFirst(), colors.getSecond());}
public static void breadcrumbArrow(GuiGraphics graphics, int x, int y, int z, int width, int height, int indent, Couple<Color> colors) {breadcrumbArrow(graphics, x, y, z, width, height, indent, colors.getFirst(), colors.getSecond());}
// draws a wide chevron-style breadcrumb arrow pointing left
public static void breadcrumbArrow(PoseStack matrixStack, int x, int y, int z, int width, int height, int indent, Color startColor, Color endColor) {
public static void breadcrumbArrow(GuiGraphics graphics, int x, int y, int z, int width, int height, int indent, Color startColor, Color endColor) {
PoseStack matrixStack = graphics.pose();
matrixStack.pushPose();
matrixStack.translate(x - indent, y, z);
breadcrumbArrow(matrixStack, width, height, indent, startColor, endColor);
breadcrumbArrow(graphics, width, height, indent, startColor, endColor);
matrixStack.popPose();
}
private static void breadcrumbArrow(PoseStack ms, int width, int height, int indent, Color c1, Color c2) {
private static void breadcrumbArrow(GuiGraphics graphics, int width, int height, int indent, Color c1, Color c2) {
/*
* 0,0 x1,y1 ********************* x4,y4 ***** x7,y7
@@ -189,7 +195,7 @@ public class UIRenderHelper {
Color fc3 = Color.mixColors(c1, c2, (indent + width) / (width + 2f * indent));
Color fc4 = Color.mixColors(c1, c2, 1);
RenderSystem.disableTexture();
// RenderSystem.disableTexture();
RenderSystem.enableBlend();
RenderSystem.disableCull();
RenderSystem.defaultBlendFunc();
@@ -197,7 +203,7 @@ public class UIRenderHelper {
Tesselator tessellator = Tesselator.getInstance();
BufferBuilder bufferbuilder = tessellator.getBuilder();
Matrix4f model = ms.last().pose();
Matrix4f model = graphics.pose().last().pose();
bufferbuilder.begin(VertexFormat.Mode.TRIANGLES, DefaultVertexFormat.POSITION_COLOR);
bufferbuilder.vertex(model, x0, y0, 0).color(fc1.getRed(), fc1.getGreen(), fc1.getBlue(), fc1.getAlpha()).endVertex();
@@ -227,27 +233,34 @@ public class UIRenderHelper {
tessellator.end();
RenderSystem.enableCull();
RenderSystem.disableBlend();
RenderSystem.enableTexture();
// RenderSystem.enableTexture();
}
//just like AbstractGui#drawTexture, but with a color at every vertex
public static void drawColoredTexture(PoseStack ms, Color c, int x, int y, int tex_left, int tex_top, int width, int height) {
drawColoredTexture(ms, c, x, y, 0, (float) tex_left, (float) tex_top, width, height, 256, 256);
public static void drawColoredTexture(GuiGraphics graphics, Color c, int x, int y, int tex_left, int tex_top, int width, int height) {
drawColoredTexture(graphics, c, x, y, 0, (float) tex_left, (float) tex_top, width, height, 256, 256);
}
public static void drawColoredTexture(PoseStack ms, Color c, int x, int y, int z, float tex_left, float tex_top, int width, int height, int sheet_width, int sheet_height) {
drawColoredTexture(ms, c, x, x + width, y, y + height, z, width, height, tex_left, tex_top, sheet_width, sheet_height);
public static void drawColoredTexture(GuiGraphics graphics, Color c, int x, int y, int z, float tex_left, float tex_top, int width, int height, int sheet_width, int sheet_height) {
drawColoredTexture(graphics, c, x, x + width, y, y + height, z, width, height, tex_left, tex_top, sheet_width, sheet_height);
}
public static void drawStretched(PoseStack ms, int left, int top, int w, int h, int z, AllGuiTextures tex) {
public static void drawStretched(GuiGraphics graphics, int left, int top, int w, int h, int z, AllGuiTextures tex) {
tex.bind();
drawTexturedQuad(ms.last()
drawTexturedQuad(graphics.pose().last()
.pose(), Color.WHITE, left, left + w, top, top + h, z, tex.startX / 256f, (tex.startX + tex.width) / 256f,
tex.startY / 256f, (tex.startY + tex.height) / 256f);
}
private static void drawColoredTexture(PoseStack ms, Color c, int left, int right, int top, int bot, int z, int tex_width, int tex_height, float tex_left, float tex_top, int sheet_width, int sheet_height) {
drawTexturedQuad(ms.last().pose(), c, left, right, top, bot, z, (tex_left + 0.0F) / (float) sheet_width, (tex_left + (float) tex_width) / (float) sheet_width, (tex_top + 0.0F) / (float) sheet_height, (tex_top + (float) tex_height) / (float) sheet_height);
public static void drawCropped(GuiGraphics graphics, int left, int top, int w, int h, int z, AllGuiTextures tex) {
tex.bind();
drawTexturedQuad(graphics.pose().last()
.pose(), Color.WHITE, left, left + w, top, top + h, z, tex.startX / 256f, (tex.startX + w) / 256f,
tex.startY / 256f, (tex.startY + h) / 256f);
}
private static void drawColoredTexture(GuiGraphics graphics, Color c, int left, int right, int top, int bot, int z, int tex_width, int tex_height, float tex_left, float tex_top, int sheet_width, int sheet_height) {
drawTexturedQuad(graphics.pose().last().pose(), c, left, right, top, bot, z, (tex_left + 0.0F) / (float) sheet_width, (tex_left + (float) tex_width) / (float) sheet_width, (tex_top + 0.0F) / (float) sheet_height, (tex_top + (float) tex_height) / (float) sheet_height);
}
private static void drawTexturedQuad(Matrix4f m, Color c, int left, int right, int top, int bot, int z, float u1, float u2, float v1, float v2) {
@@ -266,7 +279,7 @@ public class UIRenderHelper {
}
public static void flipForGuiRender(PoseStack poseStack) {
poseStack.mulPoseMatrix(Matrix4f.createScaleMatrix(1, -1, 1));
poseStack.mulPoseMatrix(new Matrix4f().scaling(1, -1, 1));
}
public static class CustomRenderTarget extends RenderTarget {
@@ -291,7 +304,7 @@ public class UIRenderHelper {
float tx = (float) viewWidth / (float) width;
float ty = (float) viewHeight / (float) height;
RenderSystem.enableTexture();
// RenderSystem.enableTexture();
RenderSystem.enableDepthTest();
RenderSystem.setShader(() -> Minecraft.getInstance().gameRenderer.blitShader);
RenderSystem.getShader().setSampler("DiffuseSampler", colorTextureId);

View File

@@ -1,35 +0,0 @@
package nl.requios.effortlessbuilding.create.foundation.gui.container;
import nl.requios.effortlessbuilding.create.foundation.networking.SimplePacketBase;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.server.level.ServerPlayer;
import net.minecraftforge.network.NetworkEvent.Context;
import java.util.function.Supplier;
public class ClearContainerPacket extends SimplePacketBase {
public ClearContainerPacket() {}
public ClearContainerPacket(FriendlyByteBuf buffer) {}
@Override
public void write(FriendlyByteBuf buffer) {}
@Override
public void handle(Supplier<Context> context) {
context.get()
.enqueueWork(() -> {
ServerPlayer player = context.get()
.getSender();
if (player == null)
return;
if (!(player.containerMenu instanceof IClearableContainer))
return;
((IClearableContainer) player.containerMenu).clearContents();
});
context.get()
.setPacketHandled(true);
}
}

View File

@@ -1,14 +0,0 @@
package nl.requios.effortlessbuilding.create.foundation.gui.container;
//import nl.requios.effortlessbuilding.create.foundation.networking.AllPackets;
public interface IClearableContainer {
default void sendClearPacket() {
// AllPackets.channel.sendToServer(new ClearContainerPacket());
}
@Deprecated //warning: does not work
public void clearContents();
}

View File

@@ -1,10 +1,17 @@
package nl.requios.effortlessbuilding.create.foundation.gui.element;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.*;
import org.joml.Matrix4f;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.BufferBuilder;
import com.mojang.blaze3d.vertex.DefaultVertexFormat;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.blaze3d.vertex.Tesselator;
import com.mojang.blaze3d.vertex.VertexFormat;
import nl.requios.effortlessbuilding.create.foundation.utility.Color;
import nl.requios.effortlessbuilding.create.foundation.utility.Couple;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.renderer.GameRenderer;
public class BoxElement extends RenderElement {
@@ -60,8 +67,8 @@ public class BoxElement extends RenderElement {
}
@Override
public void render(PoseStack ms) {
renderBox(ms);
public void render(GuiGraphics graphics) {
renderBox(graphics.pose());
}
//total box width = 1 * 2 (outer border) + 1 * 2 (inner color border) + 2 * borderOffset + width
@@ -83,7 +90,7 @@ public class BoxElement extends RenderElement {
* |_____________|
*
* */
RenderSystem.disableTexture();
// RenderSystem.disableTexture();
RenderSystem.enableBlend();
RenderSystem.defaultBlendFunc();
RenderSystem.setShader(GameRenderer::getPositionColorShader);
@@ -148,6 +155,6 @@ public class BoxElement extends RenderElement {
tessellator.end();
RenderSystem.disableBlend();
RenderSystem.enableTexture();
// RenderSystem.enableTexture();
}
}

View File

@@ -1,8 +1,10 @@
package nl.requios.effortlessbuilding.create.foundation.gui.element;
import javax.annotation.Nonnull;
import com.mojang.blaze3d.vertex.PoseStack;
import javax.annotation.Nonnull;
import net.minecraft.client.gui.GuiGraphics;
public class CombinedStencilElement extends StencilElement {
@@ -43,26 +45,27 @@ public class CombinedStencilElement extends StencilElement {
}
@Override
protected void renderStencil(PoseStack ms) {
protected void renderStencil(GuiGraphics graphics) {
PoseStack ms = graphics.pose();
ms.pushPose();
element1.transform(ms);
element1.withBounds(width, height);
element1.renderStencil(ms);
element1.renderStencil(graphics);
ms.popPose();
ms.pushPose();
element2.transform(ms);
element2.withBounds(width, height);
element2.renderStencil(ms);
element2.renderStencil(graphics);
ms.popPose();
}
@Override
protected void renderElement(PoseStack ms) {
protected void renderElement(GuiGraphics graphics) {
if (mode.rendersFirst())
element1.<StencilElement>withBounds(width, height).renderElement(ms);
element1.<StencilElement>withBounds(width, height).renderElement(graphics);
if (mode.rendersSecond())
element2.<StencilElement>withBounds(width, height).renderElement(ms);
element2.<StencilElement>withBounds(width, height).renderElement(graphics);
}
public enum ElementMode {

View File

@@ -1,13 +1,14 @@
package nl.requios.effortlessbuilding.create.foundation.gui.element;
import com.mojang.blaze3d.vertex.PoseStack;
import nl.requios.effortlessbuilding.create.foundation.gui.UIRenderHelper;
import nl.requios.effortlessbuilding.create.foundation.utility.Color;
import net.minecraft.client.gui.GuiGraphics;
public class DelegatedStencilElement extends StencilElement {
protected static final ElementRenderer EMPTY_RENDERER = (ms, width, height, alpha) -> {};
protected static final ElementRenderer DEFAULT_ELEMENT = (ms, width, height, alpha) -> UIRenderHelper.angledGradient(ms, 0, -3, 5, height+4, width+6, new Color(0xff_10dd10).scaleAlpha(alpha), new Color(0xff_1010dd).scaleAlpha(alpha));
protected static final ElementRenderer EMPTY_RENDERER = (graphics, width, height, alpha) -> {};
protected static final ElementRenderer DEFAULT_ELEMENT = (graphics, width, height, alpha) -> UIRenderHelper.angledGradient(graphics, 0, -3, 5, height+4, width+6, new Color(0xff_10dd10).scaleAlpha(alpha), new Color(0xff_1010dd).scaleAlpha(alpha));
protected ElementRenderer stencil;
protected ElementRenderer element;
@@ -35,18 +36,18 @@ public class DelegatedStencilElement extends StencilElement {
}
@Override
protected void renderStencil(PoseStack ms) {
stencil.render(ms, width, height, 1);
protected void renderStencil(GuiGraphics graphics) {
stencil.render(graphics, width, height, 1);
}
@Override
protected void renderElement(PoseStack ms) {
element.render(ms, width, height, alpha);
protected void renderElement(GuiGraphics graphics) {
element.render(graphics, width, height, alpha);
}
@FunctionalInterface
public interface ElementRenderer {
void render(PoseStack ms, int width, int height, float alpha);
void render(GuiGraphics graphics, int width, int height, float alpha);
}
}

View File

@@ -1,31 +1,35 @@
package nl.requios.effortlessbuilding.create.foundation.gui.element;
import javax.annotation.Nullable;
import com.jozufozu.flywheel.core.PartialModel;
import com.jozufozu.flywheel.core.model.ModelUtil;
import com.mojang.blaze3d.platform.GlStateManager;
import com.mojang.blaze3d.platform.GlStateManager.DestFactor;
import com.mojang.blaze3d.platform.GlStateManager.SourceFactor;
import com.mojang.blaze3d.platform.Lighting;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.PoseStack;
import org.joml.Vector3f;
//import nl.requios.effortlessbuilding.create.foundation.fluid.FluidRenderer;
import com.mojang.math.Axis;
import nl.requios.effortlessbuilding.create.foundation.gui.ILightingSettings;
import nl.requios.effortlessbuilding.create.foundation.gui.UIRenderHelper;
import nl.requios.effortlessbuilding.create.foundation.utility.Color;
import nl.requios.effortlessbuilding.create.foundation.utility.VecHelper;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.renderer.LightTexture;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.Sheets;
import net.minecraft.client.renderer.block.BlockRenderDispatcher;
import net.minecraft.client.renderer.block.model.ItemTransforms;
import net.minecraft.client.renderer.entity.ItemRenderer;
import net.minecraft.client.renderer.texture.OverlayTexture;
import net.minecraft.client.resources.model.BakedModel;
import net.minecraft.core.BlockPos;
import net.minecraft.util.RandomSource;
import net.minecraft.world.inventory.InventoryMenu;
import net.minecraft.world.item.ItemDisplayContext;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.ItemLike;
import net.minecraft.world.level.block.BaseFireBlock;
@@ -37,8 +41,6 @@ import net.minecraft.world.phys.Vec3;
import net.minecraftforge.client.RenderTypeHelper;
import net.minecraftforge.fluids.FluidStack;
import javax.annotation.Nullable;
public class GuiGameElement {
public static GuiRenderBuilder of(ItemStack stack) {
@@ -125,9 +127,9 @@ public class GuiGameElement {
matrixStack.translate(xLocal, yLocal, zLocal);
UIRenderHelper.flipForGuiRender(matrixStack);
matrixStack.translate(rotationOffset.x, rotationOffset.y, rotationOffset.z);
matrixStack.mulPose(Vector3f.ZP.rotationDegrees((float) zRot));
matrixStack.mulPose(Vector3f.XP.rotationDegrees((float) xRot));
matrixStack.mulPose(Vector3f.YP.rotationDegrees((float) yRot));
matrixStack.mulPose(Axis.ZP.rotationDegrees((float) zRot));
matrixStack.mulPose(Axis.XP.rotationDegrees((float) xRot));
matrixStack.mulPose(Axis.YP.rotationDegrees((float) yRot));
matrixStack.translate(-rotationOffset.x, -rotationOffset.y, -rotationOffset.z);
}
@@ -162,7 +164,8 @@ public class GuiGameElement {
}
@Override
public void render(PoseStack matrixStack) {
public void render(GuiGraphics graphics) {
PoseStack matrixStack = graphics.pose();
prepareMatrix(matrixStack);
Minecraft mc = Minecraft.getInstance();
@@ -231,7 +234,7 @@ public class GuiGameElement {
// FluidRenderer.renderFluidBox(new FluidStack(blockState.getFluidState()
// .getType(), 1000), 0, 0, 0, 1, 1, 1, buffer, ms, LightTexture.FULL_BRIGHT, false);
// buffer.endBatch();
buffer.endBatch();
}
}
@@ -256,7 +259,8 @@ public class GuiGameElement {
}
@Override
public void render(PoseStack matrixStack) {
public void render(GuiGraphics graphics) {
PoseStack matrixStack = graphics.pose();
prepareMatrix(matrixStack);
transformMatrix(matrixStack);
renderItemIntoGUI(matrixStack, stack, customLighting == null);
@@ -270,10 +274,11 @@ public class GuiGameElement {
renderer.textureManager.getTexture(InventoryMenu.BLOCK_ATLAS).setFilter(false, false);
RenderSystem.setShaderTexture(0, InventoryMenu.BLOCK_ATLAS);
RenderSystem.enableBlend();
RenderSystem.blendFunc(SourceFactor.SRC_ALPHA, DestFactor.ONE_MINUS_SRC_ALPHA);
RenderSystem.enableCull();
RenderSystem.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA);
RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F);
matrixStack.pushPose();
matrixStack.translate(0, 0, 100.0F + renderer.blitOffset);
matrixStack.translate(0, 0, 100.0F);
matrixStack.translate(8.0F, -8.0F, 0.0F);
matrixStack.scale(16.0F, 16.0F, 16.0F);
MultiBufferSource.BufferSource buffer = Minecraft.getInstance().renderBuffers().bufferSource();
@@ -282,8 +287,10 @@ public class GuiGameElement {
Lighting.setupForFlatItems();
}
renderer.render(stack, ItemTransforms.TransformType.GUI, false, matrixStack, buffer, LightTexture.FULL_BRIGHT, OverlayTexture.NO_OVERLAY, bakedModel);
renderer.render(stack, ItemDisplayContext.GUI, false, matrixStack, buffer, LightTexture.FULL_BRIGHT, OverlayTexture.NO_OVERLAY, bakedModel);
RenderSystem.disableDepthTest();
buffer.endBatch();
RenderSystem.enableDepthTest();
if (useDefaultLighting && flatLighting) {
Lighting.setupFor3DItems();

View File

@@ -1,12 +1,12 @@
package nl.requios.effortlessbuilding.create.foundation.gui.element;
import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.gui.GuiGraphics;
public abstract class RenderElement implements ScreenElement {
public static final RenderElement EMPTY = new RenderElement() {
@Override
public void render(PoseStack ms) {
public void render(GuiGraphics graphics) {
}
};
@@ -66,11 +66,11 @@ public abstract class RenderElement implements ScreenElement {
return z;
}
public abstract void render(PoseStack ms);
public abstract void render(GuiGraphics graphics);
@Override
public void render(PoseStack ms, int x, int y) {
this.at(x, y).render(ms);
public void render(GuiGraphics graphics, int x, int y) {
this.at(x, y).render(graphics);
}
public static class SimpleRenderElement extends RenderElement {
@@ -82,8 +82,8 @@ public abstract class RenderElement implements ScreenElement {
}
@Override
public void render(PoseStack ms) {
renderable.render(ms, (int) x, (int) y);
public void render(GuiGraphics graphics) {
renderable.render(graphics, (int) x, (int) y);
}
}
}

View File

@@ -1,12 +1,12 @@
package nl.requios.effortlessbuilding.create.foundation.gui.element;
import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
public interface ScreenElement {
@OnlyIn(Dist.CLIENT)
void render(PoseStack ms, int x, int y);
void render(GuiGraphics graphics, int x, int y);
}

View File

@@ -1,27 +1,31 @@
package nl.requios.effortlessbuilding.create.foundation.gui.element;
import org.lwjgl.opengl.GL11;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.Minecraft;
import org.lwjgl.opengl.GL11;
import net.minecraft.client.gui.GuiGraphics;
public abstract class StencilElement extends RenderElement {
@Override
public void render(PoseStack ms) {
public void render(GuiGraphics graphics) {
PoseStack ms = graphics.pose();
ms.pushPose();
transform(ms);
prepareStencil(ms);
renderStencil(ms);
renderStencil(graphics);
prepareElement(ms);
renderElement(ms);
renderElement(graphics);
cleanUp(ms);
ms.popPose();
}
protected abstract void renderStencil(PoseStack ms);
protected abstract void renderStencil(GuiGraphics graphics);
protected abstract void renderElement(PoseStack ms);
protected abstract void renderElement(GuiGraphics graphics);
protected void transform(PoseStack ms) {
ms.translate(x, y, z);

View File

@@ -2,7 +2,9 @@ package nl.requios.effortlessbuilding.create.foundation.gui.element;
import com.mojang.blaze3d.vertex.PoseStack;
import nl.requios.effortlessbuilding.create.foundation.utility.Components;
import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.network.chat.MutableComponent;
public class TextStencilElement extends DelegatedStencilElement {
@@ -45,8 +47,7 @@ public class TextStencilElement extends DelegatedStencilElement {
}
@Override
protected void renderStencil(PoseStack ms) {
protected void renderStencil(GuiGraphics graphics) {
float x = 0, y = 0;
if (centerHorizontally)
x = width / 2f - font.width(component) / 2f;
@@ -54,11 +55,11 @@ public class TextStencilElement extends DelegatedStencilElement {
if (centerVertically)
y = height / 2f - (font.lineHeight - 1) / 2f;
font.draw(ms, component, x, y, 0xff_000000);
graphics.drawString(font, component, Math.round(x), Math.round(y), 0xff_000000, false);
}
@Override
protected void renderElement(PoseStack ms) {
protected void renderElement(GuiGraphics graphics) {
float x = 0, y = 0;
if (centerHorizontally)
x = width / 2f - font.width(component) / 2f;
@@ -66,9 +67,10 @@ public class TextStencilElement extends DelegatedStencilElement {
if (centerVertically)
y = height / 2f - (font.lineHeight - 1) / 2f;
PoseStack ms = graphics.pose();
ms.pushPose();
ms.translate(x, y, 0);
element.render(ms, font.width(component), font.lineHeight + 2, alpha);
element.render(graphics, font.width(component), font.lineHeight + 2, alpha);
ms.popPose();
}

View File

@@ -1,11 +1,19 @@
package nl.requios.effortlessbuilding.create.foundation.gui.container;
package nl.requios.effortlessbuilding.create.foundation.gui.menu;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import javax.annotation.ParametersAreNonnullByDefault;
import com.mojang.blaze3d.platform.InputConstants;
import com.mojang.blaze3d.vertex.PoseStack;
import nl.requios.effortlessbuilding.create.foundation.gui.AllGuiTextures;
import nl.requios.effortlessbuilding.create.foundation.gui.TickableGuiEventListener;
import nl.requios.effortlessbuilding.create.foundation.gui.widget.AbstractSimiWidget;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.components.AbstractWidget;
import net.minecraft.client.gui.components.EditBox;
import net.minecraft.client.gui.components.Renderable;
import net.minecraft.client.gui.components.events.GuiEventListener;
import net.minecraft.client.gui.narration.NarratableEntry;
@@ -18,11 +26,6 @@ import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import javax.annotation.ParametersAreNonnullByDefault;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
@OnlyIn(Dist.CLIENT)
@ParametersAreNonnullByDefault
public abstract class AbstractSimiContainerScreen<T extends AbstractContainerMenu> extends AbstractContainerScreen<T> {
@@ -91,34 +94,34 @@ public abstract class AbstractSimiContainerScreen<T extends AbstractContainerMen
}
@Override
public void render(PoseStack matrixStack, int mouseX, int mouseY, float partialTicks) {
public void render(GuiGraphics graphics, int mouseX, int mouseY, float partialTicks) {
partialTicks = minecraft.getFrameTime();
renderBackground(matrixStack);
renderBackground(graphics);
super.render(matrixStack, mouseX, mouseY, partialTicks);
super.render(graphics, mouseX, mouseY, partialTicks);
renderForeground(matrixStack, mouseX, mouseY, partialTicks);
renderForeground(graphics, mouseX, mouseY, partialTicks);
}
@Override
protected void renderLabels(PoseStack poseStack, int mouseX, int mouseY) {
protected void renderLabels(GuiGraphics graphics, int mouseX, int mouseY) {
// no-op to prevent screen- and inventory-title from being rendered at incorrect
// location
// could also set this.titleX/Y and this.playerInventoryTitleX/Y to the proper
// values instead
}
protected void renderForeground(PoseStack ms, int mouseX, int mouseY, float partialTicks) {
renderTooltip(ms, mouseX, mouseY);
protected void renderForeground(GuiGraphics graphics, int mouseX, int mouseY, float partialTicks) {
renderTooltip(graphics, mouseX, mouseY);
for (Renderable widget : renderables) {
if (widget instanceof AbstractSimiWidget simiWidget && simiWidget.isHoveredOrFocused()) {
if (widget instanceof AbstractSimiWidget simiWidget && simiWidget.isMouseOver(mouseX, mouseY)) {
List<Component> tooltip = simiWidget.getToolTip();
if (tooltip.isEmpty())
continue;
int ttx = simiWidget.lockedTooltipX == -1 ? mouseX : simiWidget.lockedTooltipX + simiWidget.x;
int tty = simiWidget.lockedTooltipY == -1 ? mouseY : simiWidget.lockedTooltipY + simiWidget.y;
renderComponentTooltip(ms, tooltip, ttx, tty);
int ttx = simiWidget.lockedTooltipX == -1 ? mouseX : simiWidget.lockedTooltipX + simiWidget.getX();
int tty = simiWidget.lockedTooltipY == -1 ? mouseY : simiWidget.lockedTooltipY + simiWidget.getY();
graphics.renderComponentTooltip(font, tooltip, ttx, tty);
}
}
}
@@ -127,19 +130,26 @@ public abstract class AbstractSimiContainerScreen<T extends AbstractContainerMen
return leftPos - windowXOffset + (imageWidth - textureWidth) / 2;
}
// public void renderPlayerInventory(PoseStack ms, int x, int y) {
// AllGuiTextures.PLAYER_INVENTORY.render(ms, x, y, this);
// font.draw(ms, playerInventoryTitle, x + 8, y + 6, 0x404040);
// }
public void renderPlayerInventory(GuiGraphics graphics, int x, int y) {
AllGuiTextures.PLAYER_INVENTORY.render(graphics, x, y);
graphics.drawString(font, playerInventoryTitle, x + 8, y + 6, 0x404040, false);
}
@Override
public boolean keyPressed(int pKeyCode, int pScanCode, int pModifiers) {
InputConstants.Key mouseKey = InputConstants.getKey(pKeyCode, pScanCode);
if (getFocused() != null && this.minecraft.options.keyInventory.isActiveAndMatches(mouseKey))
if (getFocused() instanceof EditBox && this.minecraft.options.keyInventory.isActiveAndMatches(mouseKey))
return false;
return super.keyPressed(pKeyCode, pScanCode, pModifiers);
}
@Override
public boolean mouseClicked(double pMouseX, double pMouseY, int pButton) {
if (getFocused() != null && !getFocused().isMouseOver(pMouseX, pMouseY))
setFocused(null);
return super.mouseClicked(pMouseX, pMouseY, pButton);
}
@Override
public GuiEventListener getFocused() {
GuiEventListener focused = super.getFocused();
@@ -160,14 +170,14 @@ public abstract class AbstractSimiContainerScreen<T extends AbstractContainerMen
}
@Deprecated
protected void debugWindowArea(PoseStack matrixStack) {
fill(matrixStack, leftPos + imageWidth, topPos + imageHeight, leftPos, topPos, 0xD3D3D3D3);
protected void debugWindowArea(GuiGraphics graphics) {
graphics.fill(leftPos + imageWidth, topPos + imageHeight, leftPos, topPos, 0xD3D3D3D3);
}
@Deprecated
protected void debugExtraAreas(PoseStack matrixStack) {
protected void debugExtraAreas(GuiGraphics graphics) {
for (Rect2i area : getExtraAreas()) {
fill(matrixStack, area.getX() + area.getWidth(), area.getY() + area.getHeight(), area.getX(), area.getY(),
graphics.fill(area.getX() + area.getWidth(), area.getY() + area.getHeight(), area.getX(), area.getY(),
0xD3D3D3D3);
}
}

View File

@@ -0,0 +1,31 @@
package nl.requios.effortlessbuilding.create.foundation.gui.menu;
import nl.requios.effortlessbuilding.create.foundation.networking.SimplePacketBase;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.server.level.ServerPlayer;
import net.minecraftforge.network.NetworkEvent.Context;
public class ClearMenuPacket extends SimplePacketBase {
public ClearMenuPacket() {}
public ClearMenuPacket(FriendlyByteBuf buffer) {}
@Override
public void write(FriendlyByteBuf buffer) {}
@Override
public boolean handle(Context context) {
context.enqueueWork(() -> {
ServerPlayer player = context.getSender();
if (player == null)
return;
if (!(player.containerMenu instanceof IClearableMenu))
return;
((IClearableMenu) player.containerMenu).clearContents();
});
return true;
}
}

View File

@@ -1,4 +1,4 @@
package nl.requios.effortlessbuilding.create.foundation.gui.container;
package nl.requios.effortlessbuilding.create.foundation.gui.menu;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.world.entity.player.Inventory;
@@ -10,15 +10,15 @@ import net.minecraft.world.item.ItemStack;
import net.minecraftforge.items.ItemHandlerHelper;
import net.minecraftforge.items.ItemStackHandler;
public abstract class GhostItemContainer<T> extends ContainerBase<T> implements IClearableContainer {
public abstract class GhostItemMenu<T> extends MenuBase<T> implements IClearableMenu {
public ItemStackHandler ghostInventory;
protected GhostItemContainer(MenuType<?> type, int id, Inventory inv, FriendlyByteBuf extraData) {
protected GhostItemMenu(MenuType<?> type, int id, Inventory inv, FriendlyByteBuf extraData) {
super(type, id, inv, extraData);
}
protected GhostItemContainer(MenuType<?> type, int id, Inventory inv, T contentHolder) {
protected GhostItemMenu(MenuType<?> type, int id, Inventory inv, T contentHolder) {
super(type, id, inv, contentHolder);
}

View File

@@ -1,13 +1,12 @@
package nl.requios.effortlessbuilding.create.foundation.gui.container;
package nl.requios.effortlessbuilding.create.foundation.gui.menu;
import nl.requios.effortlessbuilding.create.foundation.networking.SimplePacketBase;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.item.ItemStack;
import net.minecraftforge.network.NetworkEvent.Context;
import java.util.function.Supplier;
public class GhostItemSubmitPacket extends SimplePacketBase {
private final ItemStack item;
@@ -30,23 +29,18 @@ public class GhostItemSubmitPacket extends SimplePacketBase {
}
@Override
public void handle(Supplier<Context> context) {
context.get()
.enqueueWork(() -> {
ServerPlayer player = context.get()
.getSender();
if (player == null)
return;
public boolean handle(Context context) {
context.enqueueWork(() -> {
ServerPlayer player = context.getSender();
if (player == null)
return;
if (player.containerMenu instanceof GhostItemContainer) {
GhostItemContainer<?> c = (GhostItemContainer<?>) player.containerMenu;
c.ghostInventory.setStackInSlot(slot, item);
c.getSlot(36 + slot).setChanged();
}
});
context.get()
.setPacketHandled(true);
if (player.containerMenu instanceof GhostItemMenu<?> menu) {
menu.ghostInventory.setStackInSlot(slot, item);
menu.getSlot(36 + slot).setChanged();
}
});
return true;
}
}

View File

@@ -0,0 +1,13 @@
package nl.requios.effortlessbuilding.create.foundation.gui.menu;
import nl.requios.effortlessbuilding.create.AllPackets;
public interface IClearableMenu {
default void sendClearPacket() {
// AllPackets.getChannel().sendToServer(new ClearMenuPacket());
}
public void clearContents();
}

View File

@@ -1,6 +1,7 @@
package nl.requios.effortlessbuilding.create.foundation.gui.container;
package nl.requios.effortlessbuilding.create.foundation.gui.menu;
import nl.requios.effortlessbuilding.create.foundation.utility.IInteractionChecker;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player;
@@ -10,18 +11,18 @@ import net.minecraft.world.inventory.Slot;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
public abstract class ContainerBase<T> extends AbstractContainerMenu {
public abstract class MenuBase<T> extends AbstractContainerMenu {
public Player player;
public Inventory playerInventory;
public T contentHolder;
protected ContainerBase(MenuType<?> type, int id, Inventory inv, FriendlyByteBuf extraData) {
protected MenuBase(MenuType<?> type, int id, Inventory inv, FriendlyByteBuf extraData) {
super(type, id);
init(inv, createOnClient(extraData));
}
protected ContainerBase(MenuType<?> type, int id, Inventory inv, T contentHolder) {
protected MenuBase(MenuType<?> type, int id, Inventory inv, T contentHolder) {
super(type, id);
init(inv, contentHolder);
}

View File

@@ -1,20 +1,25 @@
package nl.requios.effortlessbuilding.create.foundation.gui.widget;
import com.mojang.blaze3d.vertex.PoseStack;
import nl.requios.effortlessbuilding.create.foundation.gui.TickableGuiEventListener;
import nl.requios.effortlessbuilding.create.foundation.utility.Components;
import net.minecraft.client.gui.components.AbstractWidget;
import net.minecraft.client.gui.narration.NarrationElementOutput;
import net.minecraft.network.chat.Component;
import javax.annotation.Nonnull;
import java.util.LinkedList;
import java.util.List;
import java.util.function.BiConsumer;
import javax.annotation.Nonnull;
import nl.requios.effortlessbuilding.create.foundation.gui.TickableGuiEventListener;
import nl.requios.effortlessbuilding.create.foundation.utility.Components;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.components.AbstractWidget;
import net.minecraft.client.gui.narration.NarrationElementOutput;
import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipPositioner;
import net.minecraft.client.gui.screens.inventory.tooltip.DefaultTooltipPositioner;
import net.minecraft.network.chat.Component;
public abstract class AbstractSimiWidget extends AbstractWidget implements TickableGuiEventListener {
public static final int HEADER_RGB = 0x5391E1;
public static final int HINT_RGB = 0x96B7E0;
protected float z;
protected boolean wasHovered = false;
@@ -36,6 +41,11 @@ public abstract class AbstractSimiWidget extends AbstractWidget implements Ticka
super(x, y, width, height, message);
}
@Override
protected ClientTooltipPositioner createTooltipPositioner() {
return DefaultTooltipPositioner.INSTANCE;
}
public <T extends AbstractSimiWidget> T withCallback(BiConsumer<Integer, Integer> cb) {
this.onClick = cb;
//noinspection unchecked
@@ -60,26 +70,22 @@ public abstract class AbstractSimiWidget extends AbstractWidget implements Ticka
public void tick() {}
@Override
public void render(@Nonnull PoseStack ms, int mouseX, int mouseY, float partialTicks) {
if (visible) {
isHovered = mouseX >= x && mouseY >= y && mouseX < x + width && mouseY < y + height;
beforeRender(ms, mouseX, mouseY, partialTicks);
renderButton(ms, mouseX, mouseY, partialTicks);
afterRender(ms, mouseX, mouseY, partialTicks);
wasHovered = isHoveredOrFocused();
}
public void renderWidget(@Nonnull GuiGraphics graphics, int mouseX, int mouseY, float partialTicks) {
beforeRender(graphics, mouseX, mouseY, partialTicks);
renderButton(graphics, mouseX, mouseY, partialTicks);
afterRender(graphics, mouseX, mouseY, partialTicks);
wasHovered = isHoveredOrFocused();
}
protected void beforeRender(@Nonnull PoseStack ms, int mouseX, int mouseY, float partialTicks) {
ms.pushPose();
protected void beforeRender(@Nonnull GuiGraphics graphics, int mouseX, int mouseY, float partialTicks) {
graphics.pose().pushPose();
}
@Override
public void renderButton(@Nonnull PoseStack ms, int mouseX, int mouseY, float partialTicks) {
protected void renderButton(@Nonnull GuiGraphics graphics, int mouseX, int mouseY, float partialTicks) {
}
protected void afterRender(@Nonnull PoseStack ms, int mouseX, int mouseY, float partialTicks) {
ms.popPose();
protected void afterRender(@Nonnull GuiGraphics graphics, int mouseX, int mouseY, float partialTicks) {
graphics.pose().popPose();
}
public void runCallback(double mouseX, double mouseY) {
@@ -92,7 +98,7 @@ public abstract class AbstractSimiWidget extends AbstractWidget implements Ticka
}
@Override
public void updateNarration(NarrationElementOutput pNarrationElementOutput) {
public void updateWidgetNarration(NarrationElementOutput pNarrationElementOutput) {
defaultButtonNarrationText(pNarrationElementOutput);
}
}

View File

@@ -1,6 +1,7 @@
package nl.requios.effortlessbuilding.create.foundation.gui.widget;
import com.mojang.blaze3d.vertex.PoseStack;
import java.util.function.Function;
import nl.requios.effortlessbuilding.create.foundation.gui.Theme;
import nl.requios.effortlessbuilding.create.foundation.gui.Theme.Key;
import nl.requios.effortlessbuilding.create.foundation.gui.UIRenderHelper;
@@ -10,8 +11,7 @@ import nl.requios.effortlessbuilding.create.foundation.utility.Color;
import nl.requios.effortlessbuilding.create.foundation.utility.Couple;
import nl.requios.effortlessbuilding.create.foundation.utility.animation.LerpedFloat;
import javax.annotation.Nonnull;
import java.util.function.Function;
import net.minecraft.client.gui.GuiGraphics;
public class BoxWidget extends ElementWidget {
@@ -98,8 +98,8 @@ public class BoxWidget extends ElementWidget {
}
@Override
protected void beforeRender(@Nonnull PoseStack ms, int mouseX, int mouseY, float partialTicks) {
super.beforeRender(ms, mouseX, mouseY, partialTicks);
protected void beforeRender(GuiGraphics graphics, int mouseX, int mouseY, float partialTicks) {
super.beforeRender(graphics, mouseX, mouseY, partialTicks);
if (isHovered != wasHovered) {
startGradientAnimation(
@@ -121,7 +121,7 @@ public class BoxWidget extends ElementWidget {
}
@Override
public void renderButton(@Nonnull PoseStack ms, int mouseX, int mouseY, float partialTicks) {
public void renderButton(GuiGraphics graphics, int mouseX, int mouseY, float partialTicks) {
float fadeValue = fade.getValue(partialTicks);
if (fadeValue < .1f)
return;
@@ -129,11 +129,11 @@ public class BoxWidget extends ElementWidget {
box.withAlpha(fadeValue);
box.withBackground(customBackground != null ? customBackground : Theme.c(Theme.Key.PONDER_BACKGROUND_TRANSPARENT))
.gradientBorder(gradientColor1, gradientColor2)
.at(x, y, z)
.at(getX(), getY(), z)
.withBounds(width, height)
.render(ms);
.render(graphics);
super.renderButton(ms, mouseX, mouseY, partialTicks);
super.renderButton(graphics, mouseX, mouseY, partialTicks);
wasHovered = isHovered;
}
@@ -146,7 +146,7 @@ public class BoxWidget extends ElementWidget {
float padX = 2 + paddingX;
float padY = 2 + paddingY;
return x - padX <= mX && y - padY <= mY && mX < x + padX + width && mY < y + padY + height;
return getX() - padX <= mX && getY() - padY <= mY && mX < getX() + padX + width && mY < getY() + padY + height;
}
@Override

View File

@@ -1,13 +1,14 @@
package nl.requios.effortlessbuilding.create.foundation.gui.widget;
import java.util.function.Consumer;
import java.util.function.UnaryOperator;
import com.mojang.blaze3d.vertex.PoseStack;
import nl.requios.effortlessbuilding.create.foundation.gui.element.RenderElement;
import nl.requios.effortlessbuilding.create.foundation.gui.element.ScreenElement;
import nl.requios.effortlessbuilding.create.foundation.utility.animation.LerpedFloat;
import javax.annotation.Nonnull;
import java.util.function.Consumer;
import java.util.function.UnaryOperator;
import net.minecraft.client.gui.GuiGraphics;
public class ElementWidget extends AbstractSimiWidget {
@@ -117,21 +118,22 @@ public class ElementWidget extends AbstractSimiWidget {
}
@Override
protected void beforeRender(@Nonnull PoseStack ms, int mouseX, int mouseY, float partialTicks) {
super.beforeRender(ms, mouseX, mouseY, partialTicks);
protected void beforeRender(GuiGraphics graphics, int mouseX, int mouseY, float partialTicks) {
super.beforeRender(graphics, mouseX, mouseY, partialTicks);
isHovered = isMouseOver(mouseX, mouseY);
float fadeValue = fade.getValue(partialTicks);
element.withAlpha(fadeValue);
if (fadeValue < 1) {
ms.translate((1 - fadeValue) * fadeModX, (1 - fadeValue) * fadeModY, 0);
graphics.pose().translate((1 - fadeValue) * fadeModX, (1 - fadeValue) * fadeModY, 0);
}
}
@Override
public void renderButton(@Nonnull PoseStack ms, int mouseX, int mouseY, float partialTicks) {
public void renderButton(GuiGraphics graphics, int mouseX, int mouseY, float partialTicks) {
PoseStack ms = graphics.pose();
ms.pushPose();
ms.translate(x + paddingX, y + paddingY, z);
ms.translate(getX() + paddingX, getY() + paddingY, z);
float innerWidth = width - 2 * paddingX;
float innerHeight = height - 2 * paddingY;
float eX = element.getX(), eY = element.getY();
@@ -143,7 +145,7 @@ public class ElementWidget extends AbstractSimiWidget {
innerWidth /= xScale;
innerHeight /= yScale;
}
element.withBounds((int) innerWidth, (int) innerHeight).render(ms);
element.withBounds((int) innerWidth, (int) innerHeight).render(graphics);
ms.popPose();
if (rescaleElement) {
element.at(eX, eY);

View File

@@ -1,12 +1,11 @@
package nl.requios.effortlessbuilding.create.foundation.gui.widget;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.PoseStack;
import nl.requios.effortlessbuilding.create.foundation.gui.AllGuiTextures;
import nl.requios.effortlessbuilding.create.foundation.gui.element.ScreenElement;
import net.minecraft.network.chat.Component;
import javax.annotation.Nonnull;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.network.chat.Component;
public class IconButton extends AbstractSimiWidget {
@@ -22,22 +21,21 @@ public class IconButton extends AbstractSimiWidget {
}
@Override
public void renderButton(@Nonnull PoseStack matrixStack, int mouseX, int mouseY, float partialTicks) {
public void renderButton(GuiGraphics graphics, int mouseX, int mouseY, float partialTicks) {
if (visible) {
isHovered = mouseX >= x && mouseY >= y && mouseX < x + width && mouseY < y + height;
isHovered = mouseX >= getX() && mouseY >= getY() && mouseX < getX() + width && mouseY < getY() + height;
AllGuiTextures button = !active ? AllGuiTextures.BUTTON_DOWN
: isHoveredOrFocused() ? AllGuiTextures.BUTTON_HOVER : AllGuiTextures.BUTTON;
: isMouseOver(mouseX, mouseY) ? AllGuiTextures.BUTTON_HOVER : AllGuiTextures.BUTTON;
RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F);
drawBg(matrixStack, button);
icon.render(matrixStack, x + 1, y + 1);
drawBg(graphics, button);
icon.render(graphics, getX() + 1, getY() + 1);
}
}
protected void drawBg(PoseStack matrixStack, AllGuiTextures button) {
AllGuiTextures.BUTTON.bind();
blit(matrixStack, x, y, button.startX, button.startY, button.width, button.height);
protected void drawBg(GuiGraphics graphics, AllGuiTextures button) {
graphics.blit(button.location, getX(), getY(), button.startX, button.startY, button.width, button.height);
}
public void setToolTip(Component text) {

View File

@@ -1,11 +1,10 @@
package nl.requios.effortlessbuilding.create.foundation.gui.widget;
import com.google.common.collect.ImmutableList;
import com.mojang.blaze3d.vertex.PoseStack;
import nl.requios.effortlessbuilding.create.foundation.gui.AllGuiTextures;
import net.minecraft.network.chat.Component;
import javax.annotation.Nonnull;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.network.chat.Component;
public class Indicator extends AbstractSimiWidget {
@@ -13,12 +12,12 @@ public class Indicator extends AbstractSimiWidget {
public Indicator(int x, int y, Component tooltip) {
super(x, y, AllGuiTextures.INDICATOR.width, AllGuiTextures.INDICATOR.height);
this.toolTip = ImmutableList.of(tooltip);
this.toolTip = toolTip.isEmpty() ? ImmutableList.of() : ImmutableList.of(tooltip);
this.state = State.OFF;
}
@Override
public void render(@Nonnull PoseStack matrixStack, int mouseX, int mouseY, float partialTicks ) {
public void render(GuiGraphics graphics, int mouseX, int mouseY, float partialTicks ) {
if (!visible)
return;
AllGuiTextures toDraw;
@@ -30,7 +29,7 @@ public class Indicator extends AbstractSimiWidget {
case GREEN: toDraw = AllGuiTextures.INDICATOR_GREEN; break;
default: toDraw = AllGuiTextures.INDICATOR; break;
}
toDraw.render(matrixStack, x, y, this);
toDraw.render(graphics, getX(), getY());
}
public enum State {

View File

@@ -1,15 +1,16 @@
package nl.requios.effortlessbuilding.create.foundation.gui.widget;
import javax.annotation.Nonnull;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.PoseStack;
import nl.requios.effortlessbuilding.create.foundation.utility.Components;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
import javax.annotation.Nonnull;
public class Label extends AbstractSimiWidget {
public Component text;
@@ -70,7 +71,7 @@ public class Label extends AbstractSimiWidget {
}
@Override
public void renderButton(@Nonnull PoseStack matrixStack, int mouseX, int mouseY, float partialTicks) {
protected void renderButton(@Nonnull GuiGraphics graphics, int mouseX, int mouseY, float partialTicks) {
if (text == null || text.getString().isEmpty())
return;
@@ -79,10 +80,7 @@ public class Label extends AbstractSimiWidget {
if (suffix != null && !suffix.isEmpty())
copy.append(suffix);
if (hasShadow)
font.drawShadow(matrixStack, copy, x, y, color);
else
font.draw(matrixStack, copy, x, y, color);
graphics.drawString(font, copy, getX(), getY(), color, hasShadow);
}
}

View File

@@ -1,18 +1,20 @@
package nl.requios.effortlessbuilding.create.foundation.gui.widget;
import nl.requios.effortlessbuilding.create.AllKeys;
//import nl.requios.effortlessbuilding.create.AllSoundEvents;
import nl.requios.effortlessbuilding.create.foundation.utility.Components;
import nl.requios.effortlessbuilding.create.foundation.utility.Lang;
import net.minecraft.ChatFormatting;
import net.minecraft.client.Minecraft;
//import net.minecraft.client.resources.sounds.SimpleSoundInstance;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
import java.util.function.Consumer;
import java.util.function.Function;
import nl.requios.effortlessbuilding.create.AllKeys;
import nl.requios.effortlessbuilding.create.AllSoundEvents;
import nl.requios.effortlessbuilding.create.foundation.blockEntity.behaviour.scrollValue.ScrollValueBehaviour.StepContext;
import nl.requios.effortlessbuilding.create.foundation.utility.Components;
import nl.requios.effortlessbuilding.create.foundation.utility.Lang;
import net.minecraft.ChatFormatting;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.sounds.SimpleSoundInstance;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
public class ScrollInput extends AbstractSimiWidget {
protected Consumer<Integer> onScroll;
@@ -20,8 +22,10 @@ public class ScrollInput extends AbstractSimiWidget {
protected Component title = Lang.translateDirect("gui.scrollInput.defaultTitle");
protected final Component scrollToModify = Lang.translateDirect("gui.scrollInput.scrollToModify");
protected final Component shiftScrollsFaster = Lang.translateDirect("gui.scrollInput.shiftScrollsFaster");
protected Component hint = null;
protected Label displayLabel;
protected boolean inverted;
protected boolean soundPlayed;
protected Function<Integer, Component> formatter;
protected int min, max;
@@ -36,6 +40,7 @@ public class ScrollInput extends AbstractSimiWidget {
shiftStep = 5;
step = standardStep();
formatter = i -> Components.literal(String.valueOf(i));
soundPlayed = false;
}
public Function<StepContext, Integer> standardStep() {
@@ -74,6 +79,12 @@ public class ScrollInput extends AbstractSimiWidget {
return this;
}
public ScrollInput addHint(MutableComponent hint) {
this.hint = hint;
updateTooltip();
return this;
}
public ScrollInput withStepFunction(Function<StepContext, Integer> step) {
this.step = step;
return this;
@@ -86,6 +97,12 @@ public class ScrollInput extends AbstractSimiWidget {
return this;
}
@Override
public void tick() {
super.tick();
soundPlayed = false;
}
public int getState() {
return state;
}
@@ -106,8 +123,6 @@ public class ScrollInput extends AbstractSimiWidget {
@Override
public boolean mouseScrolled(double mouseX, double mouseY, double delta) {
if (!this.visible || !this.isHovered) return false; //Added
if (inverted)
delta *= -1;
@@ -128,12 +143,16 @@ public class ScrollInput extends AbstractSimiWidget {
clampState();
if (priorState != state) {
// Minecraft.getInstance().getSoundManager().play(SimpleSoundInstance.forUI(AllSoundEvents.SCROLL_VALUE.getMainEvent(), 1.5f + 0.1f * (state-min)/(max-min)));
// if (!soundPlayed)
// Minecraft.getInstance()
// .getSoundManager()
// .play(SimpleSoundInstance.forUI(AllSoundEvents.SCROLL_VALUE.getMainEvent(),
// 1.5f + 0.1f * (state - min) / (max - min)));
// soundPlayed = true;
onChanged();
}
// return priorState != state;
return true; //Changed
return priorState != state;
}
protected void clampState() {
@@ -161,6 +180,9 @@ public class ScrollInput extends AbstractSimiWidget {
return;
toolTip.add(title.plainCopy()
.withStyle(s -> s.withColor(HEADER_RGB)));
if (hint != null)
toolTip.add(hint.plainCopy()
.withStyle(s -> s.withColor(HINT_RGB)));
toolTip.add(scrollToModify.plainCopy()
.withStyle(ChatFormatting.ITALIC, ChatFormatting.DARK_GRAY));
toolTip.add(shiftScrollsFaster.plainCopy()

View File

@@ -1,14 +1,15 @@
package nl.requios.effortlessbuilding.create.foundation.gui.widget;
import nl.requios.effortlessbuilding.create.foundation.utility.Components;
import nl.requios.effortlessbuilding.create.foundation.utility.Lang;
import net.minecraft.ChatFormatting;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
import java.util.ArrayList;
import java.util.List;
import nl.requios.effortlessbuilding.create.foundation.utility.Components;
import nl.requios.effortlessbuilding.create.foundation.utility.Lang;
import net.minecraft.ChatFormatting;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
public class SelectionScrollInput extends ScrollInput {
private final MutableComponent scrollToSelect = Lang.translateDirect("gui.scrollInput.scrollToSelect");
@@ -42,7 +43,8 @@ public class SelectionScrollInput extends ScrollInput {
if (this.min + 1 == min)
min--;
if (min > this.min)
toolTip.add(Components.literal("> ...").withStyle(ChatFormatting.GRAY));
toolTip.add(Components.literal("> ...")
.withStyle(ChatFormatting.GRAY));
if (this.max - 1 == max)
max++;
for (int i = min; i < max; i++) {
@@ -58,8 +60,12 @@ public class SelectionScrollInput extends ScrollInput {
.withStyle(ChatFormatting.GRAY));
}
if (max < this.max)
toolTip.add(Components.literal("> ...").withStyle(ChatFormatting.GRAY));
toolTip.add(Components.literal("> ...")
.withStyle(ChatFormatting.GRAY));
if (hint != null)
toolTip.add(hint.plainCopy()
.withStyle(s -> s.withColor(HINT_RGB)));
toolTip.add(scrollToSelect.plainCopy()
.withStyle(ChatFormatting.DARK_GRAY, ChatFormatting.ITALIC));
}

View File

@@ -1,10 +1,10 @@
package nl.requios.effortlessbuilding.create.foundation.gui.widget;
import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.network.chat.Component;
import java.util.List;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.network.chat.Component;
public class TooltipArea extends AbstractSimiWidget {
public TooltipArea(int x, int y, int width, int height) {
@@ -12,9 +12,9 @@ public class TooltipArea extends AbstractSimiWidget {
}
@Override
public void renderButton(PoseStack ms, int mouseX, int mouseY, float partialTicks) {
public void renderWidget(GuiGraphics graphics, int mouseX, int mouseY, float partialTicks) {
if (visible)
isHovered = mouseX >= x && mouseY >= y && mouseX < x + width && mouseY < y + height;
isHovered = mouseX >= getX() && mouseY >= getY() && mouseX < getX() + width && mouseY < getY() + height;
}
public TooltipArea withTooltip(List<Component> tooltip) {

View File

@@ -1,182 +1,253 @@
package nl.requios.effortlessbuilding.create.foundation.item;
import net.minecraft.ChatFormatting;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
import nl.requios.effortlessbuilding.create.foundation.utility.Components;
import nl.requios.effortlessbuilding.create.foundation.utility.Lang;
import static net.minecraft.ChatFormatting.DARK_GRAY;
import static net.minecraft.ChatFormatting.GRAY;
import static net.minecraft.ChatFormatting.WHITE;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
import static net.minecraft.ChatFormatting.*;
import static nl.requios.effortlessbuilding.create.foundation.item.TooltipHelper.cutStringTextComponent;
import static nl.requios.effortlessbuilding.create.foundation.item.TooltipHelper.cutTextComponent;
import org.apache.commons.lang3.tuple.Pair;
import org.jetbrains.annotations.Nullable;
public class ItemDescription {
import com.google.common.collect.ImmutableList;
import nl.requios.effortlessbuilding.create.foundation.item.TooltipHelper.Palette;
import nl.requios.effortlessbuilding.create.foundation.utility.Components;
import nl.requios.effortlessbuilding.create.foundation.utility.Lang;
public static final ItemDescription MISSING = new ItemDescription(null);
public static Component trim = Components.literal(" ").withStyle(WHITE, STRIKETHROUGH);
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.resources.language.I18n;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.world.item.Item;
import net.minecraft.world.level.ItemLike;
import net.minecraftforge.event.entity.player.ItemTooltipEvent;
public enum Palette {
public record ItemDescription(ImmutableList<Component> lines, ImmutableList<Component> linesOnShift, ImmutableList<Component> linesOnCtrl) {
private static final Map<Item, Supplier<String>> CUSTOM_TOOLTIP_KEYS = new IdentityHashMap<>();
Blue(BLUE, AQUA),
Green(DARK_GREEN, GREEN),
Yellow(GOLD, YELLOW),
Red(DARK_RED, RED),
Purple(DARK_PURPLE, LIGHT_PURPLE),
Gray(DARK_GRAY, GRAY),
@Nullable
public static ItemDescription create(Item item, Palette palette) {
return create(getTooltipTranslationKey(item), palette);
}
;
private Palette(ChatFormatting primary, ChatFormatting highlight) {
color = primary;
hColor = highlight;
@Nullable
public static ItemDescription create(String translationKey, Palette palette) {
if (!canFillBuilder(translationKey)) {
return null;
}
public ChatFormatting color;
public ChatFormatting hColor;
Builder builder = new Builder(palette);
fillBuilder(builder, translationKey);
return builder.build();
}
private List<Component> lines;
private List<Component> linesOnShift;
private List<Component> linesOnCtrl;
private Palette palette;
public ItemDescription(Palette palette) {
this.palette = palette;
lines = new ArrayList<>();
linesOnShift = new ArrayList<>();
linesOnCtrl = new ArrayList<>();
public static boolean canFillBuilder(String translationKey) {
return I18n.exists(translationKey);
}
public ItemDescription withSummary(Component summary) {
addStrings(linesOnShift, cutTextComponent(summary, palette.color, palette.hColor));
return this;
}
public static String makeProgressBar(int length, int filledLength) {
String bar = " ";
int emptySpaces = length - filledLength;
for (int i = 0; i < filledLength; i++)
bar += "\u2588";
for (int i = 0; i < emptySpaces; i++)
bar += "\u2592";
return bar + " ";
}
public ItemDescription withBehaviour(String condition, String behaviour) {
add(linesOnShift, Components.literal(condition).withStyle(GRAY));
addStrings(linesOnShift, cutStringTextComponent(behaviour, palette.color, palette.hColor, 1));
return this;
}
public ItemDescription withControl(String condition, String action) {
add(linesOnCtrl, Components.literal(condition).withStyle(GRAY));
addStrings(linesOnCtrl, cutStringTextComponent(action, palette.color, palette.hColor, 1));
return this;
}
public ItemDescription createTabs() {
boolean hasDescription = !linesOnShift.isEmpty();
boolean hasControls = !linesOnCtrl.isEmpty();
if (hasDescription || hasControls) {
String[] holdDesc = Lang.translateDirect("tooltip.holdForDescription", "$")
.getString()
.split("\\$");
String[] holdCtrl = Lang.translateDirect("tooltip.holdForControls", "$")
.getString()
.split("\\$");
MutableComponent keyShift = Lang.translateDirect("tooltip.keyShift");
MutableComponent keyCtrl = Lang.translateDirect("tooltip.keyCtrl");
for (List<Component> list : Arrays.asList(lines, linesOnShift, linesOnCtrl)) {
boolean shift = list == linesOnShift;
boolean ctrl = list == linesOnCtrl;
if (holdDesc.length != 2 || holdCtrl.length != 2) {
list.add(0, Components.literal("Invalid lang formatting!"));
continue;
}
if (hasControls) {
MutableComponent tabBuilder = Components.empty();
tabBuilder.append(Components.literal(holdCtrl[0]).withStyle(DARK_GRAY));
tabBuilder.append(keyCtrl.plainCopy()
.withStyle(ctrl ? WHITE : GRAY));
tabBuilder.append(Components.literal(holdCtrl[1]).withStyle(DARK_GRAY));
list.add(0, tabBuilder);
}
if (hasDescription) {
MutableComponent tabBuilder = Components.empty();
tabBuilder.append(Components.literal(holdDesc[0]).withStyle(DARK_GRAY));
tabBuilder.append(keyShift.plainCopy()
.withStyle(shift ? WHITE : GRAY));
tabBuilder.append(Components.literal(holdDesc[1]).withStyle(DARK_GRAY));
list.add(0, tabBuilder);
}
if (shift || ctrl)
list.add(hasDescription && hasControls ? 2 : 1, Components.immutableEmpty());
}
public static void fillBuilder(Builder builder, String translationKey) {
// Summary
String summaryKey = translationKey + ".summary";
if (I18n.exists(summaryKey)) {
builder.addSummary(I18n.get(summaryKey));
}
if (!hasDescription)
linesOnShift = lines;
if (!hasControls)
linesOnCtrl = lines;
// Behaviours
for (int i = 1; i < 100; i++) {
String conditionKey = translationKey + ".condition" + i;
String behaviourKey = translationKey + ".behaviour" + i;
if (!I18n.exists(conditionKey))
break;
builder.addBehaviour(I18n.get(conditionKey), I18n.get(behaviourKey));
}
return this;
// Actions
for (int i = 1; i < 100; i++) {
String controlKey = translationKey + ".control" + i;
String actionKey = translationKey + ".action" + i;
if (!I18n.exists(controlKey))
break;
builder.addAction(I18n.get(controlKey), I18n.get(actionKey));
}
}
public static String hightlight(String s, Palette palette) {
return palette.hColor + s + palette.color;
public static void useKey(Item item, Supplier<String> supplier) {
CUSTOM_TOOLTIP_KEYS.put(item, supplier);
}
public static void addStrings(List<Component> infoList, List<Component> textLines) {
textLines.forEach(s -> add(infoList, s));
public static void useKey(ItemLike item, String string) {
useKey(item.asItem(), () -> string);
}
public static void add(List<Component> infoList, List<Component> textLines) {
infoList.addAll(textLines);
public static void referKey(ItemLike item, Supplier<? extends ItemLike> otherItem) {
useKey(item.asItem(), () -> otherItem.get()
.asItem()
.getDescriptionId());
}
public static void add(List<Component> infoList, Component line) {
infoList.add(line);
public static String getTooltipTranslationKey(Item item) {
if (CUSTOM_TOOLTIP_KEYS.containsKey(item)) {
return CUSTOM_TOOLTIP_KEYS.get(item).get() + ".tooltip";
}
return item.getDescriptionId() + ".tooltip";
}
public Palette getPalette() {
return palette;
}
public List<Component> addInformation(List<Component> tooltip) {
public ImmutableList<Component> getCurrentLines() {
if (Screen.hasShiftDown()) {
tooltip.addAll(linesOnShift);
return tooltip;
return linesOnShift;
} else if (Screen.hasControlDown()) {
return linesOnCtrl;
} else {
return lines;
}
}
public static class Builder {
protected final Palette palette;
protected final List<String> summary = new ArrayList<>();
protected final List<Pair<String, String>> behaviours = new ArrayList<>();
protected final List<Pair<String, String>> actions = new ArrayList<>();
public Builder(Palette palette) {
this.palette = palette;
}
if (Screen.hasControlDown()) {
tooltip.addAll(linesOnCtrl);
return tooltip;
public Builder addSummary(String summaryLine) {
summary.add(summaryLine);
return this;
}
tooltip.addAll(lines);
return tooltip;
public Builder addBehaviour(String condition, String behaviour) {
behaviours.add(Pair.of(condition, behaviour));
return this;
}
public Builder addAction(String condition, String action) {
actions.add(Pair.of(condition, action));
return this;
}
public ItemDescription build() {
List<Component> lines = new ArrayList<>();
List<Component> linesOnShift = new ArrayList<>();
List<Component> linesOnCtrl = new ArrayList<>();
for (String summaryLine : summary) {
linesOnShift.addAll(TooltipHelper.cutStringTextComponent(summaryLine, palette));
}
if (!behaviours.isEmpty()) {
linesOnShift.add(Components.immutableEmpty());
}
for (Pair<String, String> behaviourPair : behaviours) {
String condition = behaviourPair.getLeft();
String behaviour = behaviourPair.getRight();
linesOnShift.add(Components.literal(condition).withStyle(GRAY));
linesOnShift.addAll(TooltipHelper.cutStringTextComponent(behaviour, palette.primary(), palette.highlight(), 1));
}
for (Pair<String, String> actionPair : actions) {
String condition = actionPair.getLeft();
String action = actionPair.getRight();
linesOnCtrl.add(Components.literal(condition).withStyle(GRAY));
linesOnCtrl.addAll(TooltipHelper.cutStringTextComponent(action, palette.primary(), palette.highlight(), 1));
}
boolean hasDescription = !linesOnShift.isEmpty();
boolean hasControls = !linesOnCtrl.isEmpty();
if (hasDescription || hasControls) {
String[] holdDesc = Lang.translateDirect("tooltip.holdForDescription", "$")
.getString()
.split("\\$");
String[] holdCtrl = Lang.translateDirect("tooltip.holdForControls", "$")
.getString()
.split("\\$");
MutableComponent keyShift = Lang.translateDirect("tooltip.keyShift");
MutableComponent keyCtrl = Lang.translateDirect("tooltip.keyCtrl");
for (List<Component> list : Arrays.asList(lines, linesOnShift, linesOnCtrl)) {
boolean shift = list == linesOnShift;
boolean ctrl = list == linesOnCtrl;
if (holdDesc.length != 2 || holdCtrl.length != 2) {
list.add(0, Components.literal("Invalid lang formatting!"));
continue;
}
if (hasControls) {
MutableComponent tabBuilder = Components.empty();
tabBuilder.append(Components.literal(holdCtrl[0]).withStyle(DARK_GRAY));
tabBuilder.append(keyCtrl.plainCopy()
.withStyle(ctrl ? WHITE : GRAY));
tabBuilder.append(Components.literal(holdCtrl[1]).withStyle(DARK_GRAY));
list.add(0, tabBuilder);
}
if (hasDescription) {
MutableComponent tabBuilder = Components.empty();
tabBuilder.append(Components.literal(holdDesc[0]).withStyle(DARK_GRAY));
tabBuilder.append(keyShift.plainCopy()
.withStyle(shift ? WHITE : GRAY));
tabBuilder.append(Components.literal(holdDesc[1]).withStyle(DARK_GRAY));
list.add(0, tabBuilder);
}
if (shift || ctrl)
list.add(hasDescription && hasControls ? 2 : 1, Components.immutableEmpty());
}
}
if (!hasDescription) {
linesOnCtrl.clear();
linesOnShift.addAll(lines);
}
if (!hasControls) {
linesOnCtrl.clear();
linesOnCtrl.addAll(lines);
}
return new ItemDescription(ImmutableList.copyOf(lines), ImmutableList.copyOf(linesOnShift), ImmutableList.copyOf(linesOnCtrl));
}
}
public List<Component> getLines() {
return lines;
}
public static class Modifier implements TooltipModifier {
protected final Item item;
protected final Palette palette;
protected String cachedLanguage;
protected ItemDescription description;
public List<Component> getLinesOnCtrl() {
return linesOnCtrl;
}
public Modifier(Item item, Palette palette) {
this.item = item;
this.palette = palette;
}
public List<Component> getLinesOnShift() {
return linesOnShift;
}
@Override
public void modify(ItemTooltipEvent context) {
if (checkLocale()) {
description = create(item, palette);
}
if (description == null) {
return;
}
context.getToolTip().addAll(1, description.getCurrentLines());
}
protected boolean checkLocale() {
String currentLanguage = Minecraft.getInstance()
.getLanguageManager()
.getSelected();
if (!currentLanguage.equals(cachedLanguage)) {
cachedLanguage = currentLanguage;
return true;
}
return false;
}
}
}

View File

@@ -1,6 +1,16 @@
package nl.requios.effortlessbuilding.create.foundation.item;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
import javax.annotation.Nullable;
import org.apache.commons.lang3.mutable.MutableInt;
import nl.requios.effortlessbuilding.create.foundation.utility.Pair;
import net.minecraft.core.BlockPos;
import net.minecraft.core.NonNullList;
import net.minecraft.util.Mth;
@@ -10,16 +20,17 @@ import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.world.level.Level;
import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.ItemHandlerHelper;
import org.apache.commons.lang3.mutable.MutableInt;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
public class ItemHelper {
public static boolean sameItem(ItemStack stack, ItemStack otherStack) {
return !otherStack.isEmpty() && stack.is(otherStack.getItem());
}
public static Predicate<ItemStack> sameItemPredicate(ItemStack stack) {
return s -> sameItem(stack, s);
}
public static void dropContents(Level world, BlockPos pos, IItemHandler inv) {
for (int slot = 0; slot < inv.getSlots(); slot++)
Containers.dropItemStack(world, pos.getX(), pos.getY(), pos.getZ(), inv.getStackInSlot(slot));
@@ -122,7 +133,7 @@ public class ItemHelper {
return true;
if (stacks1.length == stacks2.length) {
for (int i = 0; i < stacks1.length; i++)
if (!ItemStack.isSame(stacks1[i], stacks2[i]))
if (!ItemStack.isSameItem(stacks1[i], stacks2[i]))
return false;
return true;
}

View File

@@ -1,10 +1,7 @@
package nl.requios.effortlessbuilding.create.foundation.item;
import net.minecraft.core.NonNullList;
import net.minecraft.tags.TagKey;
import net.minecraft.world.item.CreativeModeTab;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.registries.tags.ITagManager;
@@ -17,12 +14,6 @@ public class TagDependentIngredientItem extends Item {
this.tag = tag;
}
@Override
public void fillItemCategory(CreativeModeTab tab, NonNullList<ItemStack> list) {
if (!shouldHide())
super.fillItemCategory(tab, list);
}
public boolean shouldHide() {
ITagManager<Item> tagManager = ForgeRegistries.ITEMS.tags();
return !tagManager.isKnownTagName(tag) || tagManager.getTag(tag).isEmpty();

View File

@@ -1,36 +1,28 @@
package nl.requios.effortlessbuilding.create.foundation.item;
import java.text.BreakIterator;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import com.google.common.base.Strings;
import com.mojang.bridge.game.Language;
import nl.requios.effortlessbuilding.create.foundation.item.ItemDescription.Palette;
//import nl.requios.effortlessbuilding.create.content.equipment.goggles.IHaveGoggleInformation;
import nl.requios.effortlessbuilding.create.foundation.utility.Components;
import nl.requios.effortlessbuilding.create.foundation.utility.Couple;
import nl.requios.effortlessbuilding.create.foundation.utility.FontHelper;
import nl.requios.effortlessbuilding.create.foundation.utility.Lang;
import net.minecraft.ChatFormatting;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Font;
import net.minecraft.client.resources.language.I18n;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.ItemLike;
import java.text.BreakIterator;
import java.util.*;
import java.util.function.Supplier;
import net.minecraft.network.chat.Style;
public class TooltipHelper {
public static final int maxWidthPerLine = 200;
public static final Map<String, ItemDescription> cachedTooltips = new HashMap<>();
public static Language cachedLanguage;
private static boolean gogglesMode;
private static final Map<Item, Supplier<String>> tooltipReferrals = new HashMap<>();
public static final int MAX_WIDTH_PER_LINE = 200;
public static MutableComponent holdShift(Palette color, boolean highlighted) {
public static MutableComponent holdShift(Palette palette, boolean highlighted) {
return Lang.translateDirect("tooltip.holdForDescription", Lang.translateDirect("tooltip.keyShift")
.withStyle(ChatFormatting.GRAY))
.withStyle(ChatFormatting.DARK_GRAY);
@@ -42,87 +34,64 @@ public class TooltipHelper {
.append(Lang.translateDirect(hintKey + ".title"))
.withStyle(ChatFormatting.GOLD));
Component hint = Lang.translateDirect(hintKey);
List<Component> cutComponent = TooltipHelper.cutTextComponent(hint, ChatFormatting.GRAY, ChatFormatting.WHITE);
List<Component> cutComponent = cutTextComponent(hint, Palette.GRAY_AND_WHITE);
for (Component component : cutComponent)
tooltip.add(spacing.plainCopy()
.append(component));
}
public static void referTo(ItemLike item, Supplier<? extends ItemLike> itemWithTooltip) {
tooltipReferrals.put(item.asItem(), () -> itemWithTooltip.get()
.asItem()
.getDescriptionId());
public static String makeProgressBar(int length, int filledLength) {
String bar = " ";
int emptySpaces = length - filledLength;
for (int i = 0; i < filledLength; i++)
bar += "\u2588";
for (int i = 0; i < emptySpaces; i++)
bar += "\u2592";
return bar + " ";
}
public static void referTo(ItemLike item, String string) {
tooltipReferrals.put(item.asItem(), () -> string);
public static Style styleFromColor(ChatFormatting color) {
return Style.EMPTY.applyFormat(color);
}
@Deprecated
public static List<String> cutString(Component s, ChatFormatting defaultColor, ChatFormatting highlightColor) {
return cutString(s.getString(), defaultColor, highlightColor, 0);
public static Style styleFromColor(int hex) {
return Style.EMPTY.withColor(hex);
}
@Deprecated
public static List<String> cutString(String s, ChatFormatting defaultColor, ChatFormatting highlightColor,
int indent) {
// Apply markup
String markedUp = s.replaceAll("_([^_]+)_", highlightColor + "$1" + defaultColor);
// Split words
List<String> words = new LinkedList<>();
BreakIterator iterator = BreakIterator.getLineInstance(Minecraft.getInstance().getLocale());
iterator.setText(markedUp);
int start = iterator.first();
for (int end = iterator.next(); end != BreakIterator.DONE; start = end, end = iterator.next()) {
String word = markedUp.substring(start, end);
words.add(word);
}
Font font = Minecraft.getInstance().font;
List<String> lines = FontHelper.cutString(font, markedUp, maxWidthPerLine);
// Format
String lineStart = Strings.repeat(" ", indent);
List<String> formattedLines = new ArrayList<>(lines.size());
String format = defaultColor.toString();
for (String line : lines) {
String formattedLine = format + lineStart + line;
formattedLines.add(formattedLine);
// format = TextFormatting.getFormatString(formattedLine);
}
return formattedLines;
public static List<Component> cutStringTextComponent(String s, Palette palette) {
return cutTextComponent(Components.literal(s), palette);
}
public static List<Component> cutStringTextComponent(String c, ChatFormatting defaultColor,
ChatFormatting highlightColor) {
return cutTextComponent(Components.literal(c), defaultColor, highlightColor, 0);
public static List<Component> cutTextComponent(Component c, Palette palette) {
return cutTextComponent(c, palette.primary(), palette.highlight());
}
public static List<Component> cutTextComponent(Component c, ChatFormatting defaultColor,
ChatFormatting highlightColor) {
return cutTextComponent(c, defaultColor, highlightColor, 0);
public static List<Component> cutStringTextComponent(String s, Style primaryStyle,
Style highlightStyle) {
return cutTextComponent(Components.literal(s), primaryStyle, highlightStyle);
}
public static List<Component> cutStringTextComponent(String c, ChatFormatting defaultColor,
ChatFormatting highlightColor, int indent) {
return cutTextComponent(Components.literal(c), defaultColor, highlightColor, indent);
public static List<Component> cutTextComponent(Component c, Style primaryStyle,
Style highlightStyle) {
return cutTextComponent(c, primaryStyle, highlightStyle, 0);
}
public static List<Component> cutTextComponent(Component c, ChatFormatting defaultColor,
ChatFormatting highlightColor, int indent) {
public static List<Component> cutStringTextComponent(String c, Style primaryStyle,
Style highlightStyle, int indent) {
return cutTextComponent(Components.literal(c), primaryStyle, highlightStyle, indent);
}
public static List<Component> cutTextComponent(Component c, Style primaryStyle,
Style highlightStyle, int indent) {
String s = c.getString();
// Apply markup
String markedUp = s;// .replaceAll("_([^_]+)_", highlightColor + "$1" + defaultColor);
// Split words
List<String> words = new LinkedList<>();
BreakIterator iterator = BreakIterator.getLineInstance(Minecraft.getInstance().getLocale());
iterator.setText(markedUp);
iterator.setText(s);
int start = iterator.first();
for (int end = iterator.next(); end != BreakIterator.DONE; start = end, end = iterator.next()) {
String word = markedUp.substring(start, end);
String word = s.substring(start, end);
words.add(word);
}
@@ -133,7 +102,7 @@ public class TooltipHelper {
int width = 0;
for (String word : words) {
int newWidth = font.width(word.replaceAll("_", ""));
if (width + newWidth > maxWidthPerLine) {
if (width + newWidth > MAX_WIDTH_PER_LINE) {
if (width > 0) {
String line = currentLine.toString();
lines.add(line);
@@ -153,16 +122,16 @@ public class TooltipHelper {
// Format
MutableComponent lineStart = Components.literal(Strings.repeat(" ", indent));
lineStart.withStyle(defaultColor);
lineStart.withStyle(primaryStyle);
List<Component> formattedLines = new ArrayList<>(lines.size());
Couple<ChatFormatting> f = Couple.create(highlightColor, defaultColor);
Couple<Style> styles = Couple.create(highlightStyle, primaryStyle);
boolean currentlyHighlighted = false;
for (String string : lines) {
MutableComponent currentComponent = lineStart.plainCopy();
String[] split = string.split("_");
for (String part : split) {
currentComponent.append(Components.literal(part).withStyle(f.get(currentlyHighlighted)));
currentComponent.append(Components.literal(part).withStyle(styles.get(currentlyHighlighted)));
currentlyHighlighted = !currentlyHighlighted;
}
@@ -173,140 +142,25 @@ public class TooltipHelper {
return formattedLines;
}
// public static List<ITextComponent> cutTextComponentOld(ITextComponent c, TextFormatting defaultColor,
// TextFormatting highlightColor, int indent) {
// IFormattableTextComponent lineStart = StringTextComponent.EMPTY.copy();
// for (int i = 0; i < indent; i++)
// lineStart.append(" ");
// lineStart.formatted(defaultColor);
//
// List<ITextComponent> lines = new ArrayList<>();
// String rawText = getUnformattedDeepText(c);
// String[] words = rawText.split(" ");
// String word;
// IFormattableTextComponent currentLine = lineStart.copy();
//
// boolean firstWord = true;
// boolean lastWord;
//
// // Apply hard wrap
// for (int i = 0; i < words.length; i++) {
// word = words[i];
// lastWord = i == words.length - 1;
//
// if (!lastWord && !firstWord && getComponentLength(currentLine) + word.length() > maxCharsPerLine) {
// lines.add(currentLine);
// currentLine = lineStart.copy();
// firstWord = true;
// }
//
// currentLine.append(new StringTextComponent((firstWord ? "" : " ") + word.replace("_", ""))
// .formatted(word.matches("_([^_]+)_") ? highlightColor : defaultColor));
// firstWord = false;
// }
//
// if (!firstWord) {
// lines.add(currentLine);
// }
//
// return lines;
// }
public record Palette(Style primary, Style highlight) {
public static final Palette STANDARD_CREATE = new Palette(styleFromColor(0xC9974C), styleFromColor(0xF1DD79));
private static void checkLocale() {
Language currentLanguage = Minecraft.getInstance()
.getLanguageManager()
.getSelected();
if (cachedLanguage != currentLanguage) {
cachedTooltips.clear();
cachedLanguage = currentLanguage;
public static final Palette BLUE = ofColors(ChatFormatting.BLUE, ChatFormatting.AQUA);
public static final Palette GREEN = ofColors(ChatFormatting.DARK_GREEN, ChatFormatting.GREEN);
public static final Palette YELLOW = ofColors(ChatFormatting.GOLD, ChatFormatting.YELLOW);
public static final Palette RED = ofColors(ChatFormatting.DARK_RED, ChatFormatting.RED);
public static final Palette PURPLE = ofColors(ChatFormatting.DARK_PURPLE, ChatFormatting.LIGHT_PURPLE);
public static final Palette GRAY = ofColors(ChatFormatting.DARK_GRAY, ChatFormatting.GRAY);
public static final Palette ALL_GRAY = ofColors(ChatFormatting.GRAY, ChatFormatting.GRAY);
public static final Palette GRAY_AND_BLUE = ofColors(ChatFormatting.GRAY, ChatFormatting.BLUE);
public static final Palette GRAY_AND_WHITE = ofColors(ChatFormatting.GRAY, ChatFormatting.WHITE);
public static final Palette GRAY_AND_GOLD = ofColors(ChatFormatting.GRAY, ChatFormatting.GOLD);
public static final Palette GRAY_AND_RED = ofColors(ChatFormatting.GRAY, ChatFormatting.RED);
public static Palette ofColors(ChatFormatting primary, ChatFormatting highlight) {
return new Palette(styleFromColor(primary), styleFromColor(highlight));
}
}
public static boolean hasTooltip(ItemStack stack, Player player) {
checkLocale();
String key = getTooltipTranslationKey(stack);
if (cachedTooltips.containsKey(key))
return cachedTooltips.get(key) != ItemDescription.MISSING;
return findTooltip(stack);
}
public static ItemDescription getTooltip(ItemStack stack) {
checkLocale();
String key = getTooltipTranslationKey(stack);
if (cachedTooltips.containsKey(key)) {
ItemDescription itemDescription = cachedTooltips.get(key);
if (itemDescription != ItemDescription.MISSING)
return itemDescription;
}
return null;
}
private static boolean findTooltip(ItemStack stack) {
String key = getTooltipTranslationKey(stack);
if (I18n.exists(key)) {
cachedTooltips.put(key, buildToolTip(key, stack));
return true;
}
cachedTooltips.put(key, ItemDescription.MISSING);
return false;
}
private static ItemDescription buildToolTip(String translationKey, ItemStack stack) {
ItemDescription tooltip = new ItemDescription(Palette.Blue);
String summaryKey = translationKey + ".summary";
// Summary
if (I18n.exists(summaryKey))
tooltip = tooltip.withSummary(Components.literal(I18n.get(summaryKey)));
// Requirements
// if (stack.getItem() instanceof BlockItem) {
// BlockItem item = (BlockItem) stack.getItem();
// if (item.getBlock() instanceof IRotate || item.getBlock() instanceof EngineBlock) {
// tooltip = tooltip.withKineticStats(item.getBlock());
// }
// }
// Behaviours
for (int i = 1; i < 100; i++) {
String conditionKey = translationKey + ".condition" + i;
String behaviourKey = translationKey + ".behaviour" + i;
if (!I18n.exists(conditionKey))
break;
if (i == 1)
tooltip.getLinesOnShift()
.add(Components.immutableEmpty());
tooltip.withBehaviour(I18n.get(conditionKey), I18n.get(behaviourKey));
}
// Controls
for (int i = 1; i < 100; i++) {
String controlKey = translationKey + ".control" + i;
String actionKey = translationKey + ".action" + i;
if (!I18n.exists(controlKey))
break;
tooltip.withControl(I18n.get(controlKey), I18n.get(actionKey));
}
return tooltip.createTabs();
}
public static String getTooltipTranslationKey(ItemStack stack) {
Item item = stack.getItem();
if (tooltipReferrals.containsKey(item))
return tooltipReferrals.get(item)
.get() + ".tooltip";
return item.getDescriptionId(stack) + ".tooltip";
}
// private static int getComponentLength(ITextComponent component) {
// AtomicInteger l = new AtomicInteger();
// TextProcessing.visitFormatted(component, Style.EMPTY, (s, style, charConsumer) -> {
// l.getAndIncrement();
// return true;
// });
// return l.get();
// }
}

View File

@@ -0,0 +1,43 @@
package nl.requios.effortlessbuilding.create.foundation.item;
import org.jetbrains.annotations.Nullable;
import nl.requios.effortlessbuilding.create.foundation.utility.AttachedRegistry;
import net.minecraft.world.item.Item;
import net.minecraftforge.event.entity.player.ItemTooltipEvent;
import net.minecraftforge.registries.ForgeRegistries;
public interface TooltipModifier {
AttachedRegistry<Item, TooltipModifier> REGISTRY = new AttachedRegistry<>(ForgeRegistries.ITEMS);
TooltipModifier EMPTY = new TooltipModifier() {
@Override
public void modify(ItemTooltipEvent context) {
}
@Override
public TooltipModifier andThen(TooltipModifier after) {
return after;
}
};
void modify(ItemTooltipEvent context);
default TooltipModifier andThen(TooltipModifier after) {
if (after == EMPTY) {
return this;
}
return tooltip -> {
modify(tooltip);
after.modify(tooltip);
};
}
static TooltipModifier mapNull(@Nullable TooltipModifier modifier) {
if (modifier == null) {
return EMPTY;
}
return modifier;
}
}

View File

@@ -1,12 +0,0 @@
package nl.requios.effortlessbuilding.create.foundation.item.render;
import nl.requios.effortlessbuilding.create.Create;
import net.minecraft.client.resources.model.BakedModel;
public abstract class CreateCustomRenderedItemModel extends CustomRenderedItemModel {
public CreateCustomRenderedItemModel(BakedModel template, String basePath) {
super(template, Create.ID, basePath);
}
}

View File

@@ -1,29 +1,15 @@
package nl.requios.effortlessbuilding.create.foundation.item.render;
import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.renderer.block.model.ItemTransforms;
import net.minecraft.client.resources.model.BakedModel;
import net.minecraft.client.resources.model.BlockModelRotation;
import net.minecraft.client.resources.model.ModelBakery;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.client.event.ModelEvent;
import net.minecraft.world.item.ItemDisplayContext;
import net.minecraftforge.client.model.BakedModelWrapper;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class CustomRenderedItemModel extends BakedModelWrapper<BakedModel> {
public abstract class CustomRenderedItemModel extends BakedModelWrapper<BakedModel> {
protected String namespace;
protected String basePath;
protected Map<String, BakedModel> partials = new HashMap<>();
public CustomRenderedItemModel(BakedModel template, String namespace, String basePath) {
super(template);
this.namespace = namespace;
this.basePath = basePath;
public CustomRenderedItemModel(BakedModel originalModel) {
super(originalModel);
}
@Override
@@ -32,43 +18,16 @@ public abstract class CustomRenderedItemModel extends BakedModelWrapper<BakedMod
}
@Override
public BakedModel applyTransform(ItemTransforms.TransformType cameraTransformType, PoseStack mat, boolean leftHand) {
// Super call returns originalModel, but we want to return this, else ISTER
public BakedModel applyTransform(ItemDisplayContext cameraItemDisplayContext, PoseStack mat,
boolean leftHand) {
// Super call returns originalModel, but we want to return this, else BEWLR
// won't be used.
super.applyTransform(cameraTransformType, mat, leftHand);
super.applyTransform(cameraItemDisplayContext, mat, leftHand);
return this;
}
public final BakedModel getOriginalModel() {
public BakedModel getOriginalModel() {
return originalModel;
}
public BakedModel getPartial(String name) {
return partials.get(name);
}
public final List<ResourceLocation> getModelLocations() {
return partials.keySet().stream().map(this::getPartialModelLocation).collect(Collectors.toList());
}
protected void addPartials(String... partials) {
for (String name : partials)
this.partials.put(name, null);
}
public void loadPartials(ModelEvent.BakingCompleted event) {
ModelBakery modelLoader = event.getModelBakery();
for (String name : partials.keySet())
partials.put(name, loadPartial(modelLoader, name));
}
@SuppressWarnings("deprecation")
protected BakedModel loadPartial(ModelBakery modelLoader, String name) {
return modelLoader.bake(getPartialModelLocation(name), BlockModelRotation.X0_Y0);
}
protected ResourceLocation getPartialModelLocation(String name) {
return new ResourceLocation(namespace, "item/" + basePath + "/" + name);
}
}

View File

@@ -0,0 +1,33 @@
package nl.requios.effortlessbuilding.create.foundation.item.render;
import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.BlockEntityWithoutLevelRenderer;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.world.item.ItemDisplayContext;
import net.minecraft.world.item.ItemStack;
public abstract class CustomRenderedItemModelRenderer extends BlockEntityWithoutLevelRenderer {
public CustomRenderedItemModelRenderer() {
super(null, null);
}
@Override
public void renderByItem(ItemStack stack, ItemDisplayContext transformType, PoseStack ms, MultiBufferSource buffer, int light, int overlay) {
CustomRenderedItemModel mainModel = (CustomRenderedItemModel) Minecraft.getInstance()
.getItemRenderer()
.getModel(stack, null, null, 0);
PartialItemModelRenderer renderer = PartialItemModelRenderer.of(stack, transformType, ms, buffer, overlay);
ms.pushPose();
ms.translate(0.5F, 0.5F, 0.5F);
render(stack, mainModel, renderer, transformType, ms, buffer, light, overlay);
ms.popPose();
}
protected abstract void render(ItemStack stack, CustomRenderedItemModel model, PartialItemModelRenderer renderer, ItemDisplayContext transformType,
PoseStack ms, MultiBufferSource buffer, int light, int overlay);
}

View File

@@ -4,14 +4,15 @@ import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.blaze3d.vertex.VertexConsumer;
import nl.requios.effortlessbuilding.create.foundation.render.RenderTypes;
import nl.requios.effortlessbuilding.create.foundation.utility.Iterate;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.block.model.ItemTransforms;
import net.minecraft.client.renderer.entity.ItemRenderer;
import net.minecraft.client.resources.model.BakedModel;
import net.minecraft.core.Direction;
import net.minecraft.util.RandomSource;
import net.minecraft.world.item.ItemDisplayContext;
import net.minecraft.world.item.ItemStack;
import net.minecraftforge.client.extensions.common.IClientItemExtensions;
import net.minecraftforge.client.model.data.ModelData;
@@ -23,12 +24,12 @@ public class PartialItemModelRenderer {
private final RandomSource random = RandomSource.create();
private ItemStack stack;
private ItemTransforms.TransformType transformType;
private ItemDisplayContext transformType;
private PoseStack ms;
private MultiBufferSource buffer;
private int overlay;
public static PartialItemModelRenderer of(ItemStack stack, ItemTransforms.TransformType transformType,
public static PartialItemModelRenderer of(ItemStack stack, ItemDisplayContext transformType,
PoseStack ms, MultiBufferSource buffer, int overlay) {
PartialItemModelRenderer instance = INSTANCE;
instance.stack = stack;
@@ -47,13 +48,13 @@ public class PartialItemModelRenderer {
render(model, RenderTypes.getItemPartialSolid(), light);
}
// public void renderSolidGlowing(BakedModel model, int light) {
// render(model, RenderTypes.getGlowingSolid(), light);
// }
//
// public void renderGlowing(BakedModel model, int light) {
// render(model, RenderTypes.getGlowingTranslucent(), light);
// }
public void renderSolidGlowing(BakedModel model, int light) {
render(model, RenderTypes.getGlowingSolid(), light);
}
public void renderGlowing(BakedModel model, int light) {
render(model, RenderTypes.getGlowingTranslucent(), light);
}
public void render(BakedModel model, RenderType type, int light) {
if (stack.isEmpty())

View File

@@ -0,0 +1,13 @@
package nl.requios.effortlessbuilding.create.foundation.mixin.accessor;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Invoker;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.level.Level;
@Mixin(Entity.class)
public interface EntityAccessor {
@Invoker("setLevel")
void create$callSetLevel(Level level);
}

View File

@@ -0,0 +1,13 @@
package nl.requios.effortlessbuilding.create.foundation.mixin.accessor;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Invoker;
import net.minecraft.client.Camera;
import net.minecraft.client.renderer.GameRenderer;
@Mixin(GameRenderer.class)
public interface GameRendererAccessor {
@Invoker("getFov")
double create$callGetFov(Camera camera, float partialTicks, boolean useFOVSetting);
}

View File

@@ -1,5 +1,9 @@
package nl.requios.effortlessbuilding.create.foundation.networking;
import java.util.HashSet;
//import nl.requios.effortlessbuilding.create.AllPackets;
import net.minecraft.client.Minecraft;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.FriendlyByteBuf;
@@ -7,13 +11,14 @@ import net.minecraft.world.entity.Entity;
import net.minecraftforge.network.NetworkEvent.Context;
import net.minecraftforge.network.PacketDistributor;
import java.util.HashSet;
import java.util.function.Supplier;
public interface ISyncPersistentData {
void onPersistentDataUpdated();
// default void syncPersistentDataWithTracking(Entity self) {
// AllPackets.getChannel().send(PacketDistributor.TRACKING_ENTITY.with(() -> self), new PersistentDataPacket(self));
// }
public static class PersistentDataPacket extends SimplePacketBase {
private int entityId;
@@ -37,19 +42,17 @@ public interface ISyncPersistentData {
}
@Override
public void handle(Supplier<Context> context) {
context.get()
.enqueueWork(() -> {
Entity entityByID = Minecraft.getInstance().level.getEntity(entityId);
CompoundTag data = entityByID.getPersistentData();
new HashSet<>(data.getAllKeys()).forEach(data::remove);
data.merge(readData);
if (!(entityByID instanceof ISyncPersistentData))
return;
((ISyncPersistentData) entityByID).onPersistentDataUpdated();
});
context.get()
.setPacketHandled(true);
public boolean handle(Context context) {
context.enqueueWork(() -> {
Entity entityByID = Minecraft.getInstance().level.getEntity(entityId);
CompoundTag data = entityByID.getPersistentData();
new HashSet<>(data.getAllKeys()).forEach(data::remove);
data.merge(readData);
if (!(entityByID instanceof ISyncPersistentData))
return;
((ISyncPersistentData) entityByID).onPersistentDataUpdated();
});
return true;
}
}

View File

@@ -3,12 +3,10 @@ package nl.requios.effortlessbuilding.create.foundation.networking;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraftforge.network.NetworkEvent.Context;
import java.util.function.Supplier;
public abstract class SimplePacketBase {
public abstract void write(FriendlyByteBuf buffer);
public abstract void handle(Supplier<Context> context);
public abstract boolean handle(Context context);
}

View File

@@ -2,9 +2,8 @@ package nl.requios.effortlessbuilding.create.foundation.render;
import com.jozufozu.flywheel.core.model.ModelUtil;
import com.jozufozu.flywheel.core.model.ShadeSeparatedBufferedData;
import com.jozufozu.flywheel.util.Pair;
import com.mojang.blaze3d.vertex.BufferBuilder.RenderedBuffer;
import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.block.BlockRenderDispatcher;
import net.minecraft.client.resources.model.BakedModel;

View File

@@ -1,16 +1,23 @@
package nl.requios.effortlessbuilding.create.foundation.render;
import java.util.Iterator;
import javax.annotation.Nullable;
import org.joml.Matrix4f;
import org.joml.Vector4f;
import com.jozufozu.flywheel.backend.Backend;
import com.jozufozu.flywheel.backend.instancing.InstancedRenderRegistry;
import com.jozufozu.flywheel.config.BackendType;
import com.jozufozu.flywheel.core.virtual.VirtualRenderWorld;
import com.jozufozu.flywheel.util.transform.TransformStack;
import com.mojang.blaze3d.vertex.PoseStack;
import org.joml.Matrix4f;
import org.joml.Vector4f;
import nl.requios.effortlessbuilding.create.Create;
import nl.requios.effortlessbuilding.create.foundation.utility.AnimationTickHolder;
import nl.requios.effortlessbuilding.create.foundation.utility.RegisteredObjects;
import nl.requios.effortlessbuilding.create.infrastructure.config.AllConfigs;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.LevelRenderer;
import net.minecraft.client.renderer.MultiBufferSource;
@@ -20,43 +27,40 @@ import net.minecraft.core.BlockPos;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.entity.BlockEntity;
import javax.annotation.Nullable;
import java.util.Iterator;
public class BlockEntityRenderHelper {
public class TileEntityRenderHelper {
public static void renderTileEntities(Level world, Iterable<BlockEntity> customRenderTEs, PoseStack ms,
public static void renderBlockEntities(Level world, Iterable<BlockEntity> customRenderBEs, PoseStack ms,
MultiBufferSource buffer) {
renderTileEntities(world, null, customRenderTEs, ms, null, buffer);
renderBlockEntities(world, null, customRenderBEs, ms, null, buffer);
}
public static void renderTileEntities(Level world, Iterable<BlockEntity> customRenderTEs, PoseStack ms,
public static void renderBlockEntities(Level world, Iterable<BlockEntity> customRenderBEs, PoseStack ms,
MultiBufferSource buffer, float pt) {
renderTileEntities(world, null, customRenderTEs, ms, null, buffer, pt);
renderBlockEntities(world, null, customRenderBEs, ms, null, buffer, pt);
}
public static void renderTileEntities(Level world, @Nullable VirtualRenderWorld renderWorld,
Iterable<BlockEntity> customRenderTEs, PoseStack ms, @Nullable Matrix4f lightTransform, MultiBufferSource buffer) {
renderTileEntities(world, renderWorld, customRenderTEs, ms, lightTransform, buffer,
public static void renderBlockEntities(Level world, @Nullable VirtualRenderWorld renderWorld,
Iterable<BlockEntity> customRenderBEs, PoseStack ms, @Nullable Matrix4f lightTransform, MultiBufferSource buffer) {
renderBlockEntities(world, renderWorld, customRenderBEs, ms, lightTransform, buffer,
AnimationTickHolder.getPartialTicks());
}
public static void renderTileEntities(Level world, @Nullable VirtualRenderWorld renderWorld,
Iterable<BlockEntity> customRenderTEs, PoseStack ms, @Nullable Matrix4f lightTransform, MultiBufferSource buffer,
public static void renderBlockEntities(Level world, @Nullable VirtualRenderWorld renderWorld,
Iterable<BlockEntity> customRenderBEs, PoseStack ms, @Nullable Matrix4f lightTransform, MultiBufferSource buffer,
float pt) {
Iterator<BlockEntity> iterator = customRenderTEs.iterator();
Iterator<BlockEntity> iterator = customRenderBEs.iterator();
while (iterator.hasNext()) {
BlockEntity tileEntity = iterator.next();
if (Backend.getBackendType() == BackendType.INSTANCING && Backend.isFlywheelWorld(renderWorld) && InstancedRenderRegistry.shouldSkipRender(tileEntity))
BlockEntity blockEntity = iterator.next();
if (Backend.getBackendType() == BackendType.INSTANCING && Backend.isFlywheelWorld(renderWorld) && InstancedRenderRegistry.shouldSkipRender(blockEntity))
continue;
BlockEntityRenderer<BlockEntity> renderer = Minecraft.getInstance().getBlockEntityRenderDispatcher().getRenderer(tileEntity);
BlockEntityRenderer<BlockEntity> renderer = Minecraft.getInstance().getBlockEntityRenderDispatcher().getRenderer(blockEntity);
if (renderer == null) {
iterator.remove();
continue;
}
BlockPos pos = tileEntity.getBlockPos();
BlockPos pos = blockEntity.getBlockPos();
ms.pushPose();
TransformStack.cast(ms)
.translate(pos);
@@ -66,22 +70,22 @@ public class TileEntityRenderHelper {
if (renderWorld != null) {
// Swap the real world for the render world so that the renderer gets contraption-local information
tileEntity.setLevel(renderWorld);
renderer.render(tileEntity, pt, ms, buffer, worldLight, OverlayTexture.NO_OVERLAY);
tileEntity.setLevel(world);
blockEntity.setLevel(renderWorld);
renderer.render(blockEntity, pt, ms, buffer, worldLight, OverlayTexture.NO_OVERLAY);
blockEntity.setLevel(world);
} else {
renderer.render(tileEntity, pt, ms, buffer, worldLight, OverlayTexture.NO_OVERLAY);
renderer.render(blockEntity, pt, ms, buffer, worldLight, OverlayTexture.NO_OVERLAY);
}
} catch (Exception e) {
iterator.remove();
String message = "BlockEntity " + RegisteredObjects.getKeyOrThrow(tileEntity.getType())
String message = "BlockEntity " + RegisteredObjects.getKeyOrThrow(blockEntity.getType())
.toString() + " could not be rendered virtually.";
// if (AllConfigs.CLIENT.explainRenderErrors.get())
Create.LOGGER.error(message, e);
// if (AllConfigs.client().explainRenderErrors.get())
// Create.LOGGER.error(message, e);
// else
// Create.LOGGER.error(message);
Create.LOGGER.error(message);
}
ms.popPose();
@@ -91,7 +95,7 @@ public class TileEntityRenderHelper {
private static BlockPos getLightPos(@Nullable Matrix4f lightTransform, BlockPos contraptionPos) {
if (lightTransform != null) {
Vector4f lightVec = new Vector4f(contraptionPos.getX() + .5f, contraptionPos.getY() + .5f, contraptionPos.getZ() + .5f, 1);
lightVec.transform(lightTransform);
lightVec.mul(lightTransform);
return BlockPos.containing(lightVec.x(), lightVec.y(), lightVec.z());
} else {
return contraptionPos;

View File

@@ -1,28 +1,29 @@
package nl.requios.effortlessbuilding.create.foundation.render;
import static net.minecraft.world.level.block.state.properties.BlockStateProperties.FACING;
import java.util.function.Supplier;
import org.apache.commons.lang3.tuple.Pair;
import com.jozufozu.flywheel.core.PartialModel;
import com.jozufozu.flywheel.util.transform.TransformStack;
import com.mojang.blaze3d.vertex.PoseStack;
import nl.requios.effortlessbuilding.EffortlessBuildingClient;
import nl.requios.effortlessbuilding.create.CreateClient;
import nl.requios.effortlessbuilding.create.foundation.render.SuperByteBufferCache.Compartment;
import nl.requios.effortlessbuilding.create.foundation.utility.AngleHelper;
import net.minecraft.core.Direction;
import net.minecraft.world.level.block.state.BlockState;
import org.apache.commons.lang3.tuple.Pair;
import java.util.function.Supplier;
import static net.minecraft.world.level.block.state.properties.BlockStateProperties.FACING;
public class CachedBufferer {
public static final Compartment<BlockState> GENERIC_TILE = new Compartment<>();
public static final Compartment<BlockState> GENERIC_BLOCK = new Compartment<>();
public static final Compartment<PartialModel> PARTIAL = new Compartment<>();
public static final Compartment<Pair<Direction, PartialModel>> DIRECTIONAL_PARTIAL = new Compartment<>();
public static SuperByteBuffer block(BlockState toRender) {
return block(GENERIC_TILE, toRender);
return block(GENERIC_BLOCK, toRender);
}
public static SuperByteBuffer block(Compartment<BlockState> compartment, BlockState toRender) {

View File

@@ -1,10 +1,11 @@
package nl.requios.effortlessbuilding.create.foundation.render;
import com.jozufozu.flywheel.util.DiffuseLightCalculator;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import javax.annotation.Nullable;
import com.jozufozu.flywheel.util.DiffuseLightCalculator;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
public final class ForcedDiffuseState {
private static final ThreadLocal<ObjectArrayList<DiffuseLightCalculator>> FORCED_DIFFUSE = ThreadLocal.withInitial(ObjectArrayList::new);

View File

@@ -1,32 +1,33 @@
package nl.requios.effortlessbuilding.create.foundation.render;
import java.io.IOException;
import com.mojang.blaze3d.vertex.DefaultVertexFormat;
import com.mojang.blaze3d.vertex.VertexFormat;
import nl.requios.effortlessbuilding.create.AllSpecialTextures;
import nl.requios.effortlessbuilding.create.Create;
import net.minecraft.client.renderer.RenderStateShard;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.ShaderInstance;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.server.packs.resources.ResourceProvider;
import net.minecraft.world.inventory.InventoryMenu;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.client.event.RegisterShadersEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import java.io.IOException;
// TODO 1.17: use custom shaders instead of vanilla ones
public class RenderTypes extends RenderStateShard {
// public static final ShaderStateShard GLOWING_SHADER = new ShaderStateShard(() -> Shaders.glowingShader);
public static final RenderStateShard.ShaderStateShard GLOWING_SHADER = new RenderStateShard.ShaderStateShard(() -> Shaders.glowingShader);
private static final RenderType OUTLINE_SOLID =
RenderType.create(createLayerName("outline_solid"), DefaultVertexFormat.NEW_ENTITY, VertexFormat.Mode.QUADS, 256, false,
false, RenderType.CompositeState.builder()
.setShaderState(RENDERTYPE_ENTITY_SOLID_SHADER)
.setTextureState(new TextureStateShard(AllSpecialTextures.BLANK.getLocation(), false, false))
.setTextureState(new RenderStateShard.TextureStateShard(AllSpecialTextures.BLANK.getLocation(), false, false))
.setCullState(CULL)
.setLightmapState(LIGHTMAP)
.setOverlayState(OVERLAY)
@@ -40,7 +41,7 @@ public class RenderTypes extends RenderStateShard {
return RenderType.create(createLayerName("outline_translucent" + (cull ? "_cull" : "")),
DefaultVertexFormat.NEW_ENTITY, VertexFormat.Mode.QUADS, 256, false, true, RenderType.CompositeState.builder()
.setShaderState(cull ? RENDERTYPE_ENTITY_TRANSLUCENT_CULL_SHADER : RENDERTYPE_ENTITY_TRANSLUCENT_SHADER)
.setTextureState(new TextureStateShard(texture, false, false))
.setTextureState(new RenderStateShard.TextureStateShard(texture, false, false))
.setTransparencyState(TRANSLUCENT_TRANSPARENCY)
.setCullState(cull ? CULL : NO_CULL)
.setLightmapState(LIGHTMAP)
@@ -49,38 +50,38 @@ public class RenderTypes extends RenderStateShard {
.createCompositeState(false));
}
// public static RenderType getGlowingSolid(ResourceLocation texture) {
// return RenderType.create(createLayerName("glowing_solid"), DefaultVertexFormat.NEW_ENTITY, VertexFormat.Mode.QUADS, 256,
// true, false, RenderType.CompositeState.builder()
// .setShaderState(GLOWING_SHADER)
// .setTextureState(new TextureStateShard(texture, false, false))
// .setCullState(CULL)
// .setLightmapState(LIGHTMAP)
// .setOverlayState(OVERLAY)
// .createCompositeState(true));
// }
//
// private static final RenderType GLOWING_SOLID_DEFAULT = getGlowingSolid(InventoryMenu.BLOCK_ATLAS);
//
// public static RenderType getGlowingSolid() {
// return GLOWING_SOLID_DEFAULT;
// }
public static RenderType getGlowingSolid(ResourceLocation texture) {
return RenderType.create(createLayerName("glowing_solid"), DefaultVertexFormat.NEW_ENTITY, VertexFormat.Mode.QUADS, 256,
true, false, RenderType.CompositeState.builder()
.setShaderState(GLOWING_SHADER)
.setTextureState(new RenderStateShard.TextureStateShard(texture, false, false))
.setCullState(CULL)
.setLightmapState(LIGHTMAP)
.setOverlayState(OVERLAY)
.createCompositeState(true));
}
// public static RenderType getGlowingTranslucent(ResourceLocation texture) {
// return RenderType.create(createLayerName("glowing_translucent"), DefaultVertexFormat.NEW_ENTITY, VertexFormat.Mode.QUADS,
// 256, true, true, RenderType.CompositeState.builder()
// .setShaderState(GLOWING_SHADER)
// .setTextureState(new TextureStateShard(texture, false, false))
// .setTransparencyState(TRANSLUCENT_TRANSPARENCY)
// .setLightmapState(LIGHTMAP)
// .setOverlayState(OVERLAY)
// .createCompositeState(true));
// }
private static final RenderType GLOWING_SOLID_DEFAULT = getGlowingSolid(InventoryMenu.BLOCK_ATLAS);
public static RenderType getGlowingSolid() {
return GLOWING_SOLID_DEFAULT;
}
public static RenderType getGlowingTranslucent(ResourceLocation texture) {
return RenderType.create(createLayerName("glowing_translucent"), DefaultVertexFormat.NEW_ENTITY, VertexFormat.Mode.QUADS,
256, true, true, RenderType.CompositeState.builder()
.setShaderState(GLOWING_SHADER)
.setTextureState(new RenderStateShard.TextureStateShard(texture, false, false))
.setTransparencyState(TRANSLUCENT_TRANSPARENCY)
.setLightmapState(LIGHTMAP)
.setOverlayState(OVERLAY)
.createCompositeState(true));
}
private static final RenderType ADDITIVE = RenderType.create(createLayerName("additive"), DefaultVertexFormat.BLOCK,
VertexFormat.Mode.QUADS, 256, true, true, RenderType.CompositeState.builder()
.setShaderState(BLOCK_SHADER)
.setTextureState(new TextureStateShard(InventoryMenu.BLOCK_ATLAS, false, false))
.setShaderState(RENDERTYPE_SOLID_SHADER)
.setTextureState(new RenderStateShard.TextureStateShard(InventoryMenu.BLOCK_ATLAS, false, false))
.setTransparencyState(ADDITIVE_TRANSPARENCY)
.setCullState(NO_CULL)
.setLightmapState(LIGHTMAP)
@@ -91,11 +92,11 @@ public class RenderTypes extends RenderStateShard {
return ADDITIVE;
}
// private static final RenderType GLOWING_TRANSLUCENT_DEFAULT = getGlowingTranslucent(InventoryMenu.BLOCK_ATLAS);
private static final RenderType GLOWING_TRANSLUCENT_DEFAULT = getGlowingTranslucent(InventoryMenu.BLOCK_ATLAS);
// public static RenderType getGlowingTranslucent() {
// return GLOWING_TRANSLUCENT_DEFAULT;
// }
public static RenderType getGlowingTranslucent() {
return GLOWING_TRANSLUCENT_DEFAULT;
}
private static final RenderType ITEM_PARTIAL_SOLID =
RenderType.create(createLayerName("item_partial_solid"), DefaultVertexFormat.NEW_ENTITY, VertexFormat.Mode.QUADS, 256, true,
@@ -146,15 +147,15 @@ public class RenderTypes extends RenderStateShard {
super(null, null, null);
}
// @EventBusSubscriber(value = Dist.CLIENT, bus = EventBusSubscriber.Bus.MOD)
// private static class Shaders {
// private static ShaderInstance glowingShader;
//
// @SubscribeEvent
// public static void onRegisterShaders(RegisterShadersEvent event) throws IOException {
// ResourceManager resourceManager = event.getResourceManager();
// event.registerShader(new ShaderInstance(resourceManager, Create.asResource("glowing_shader"), DefaultVertexFormat.NEW_ENTITY), shader -> glowingShader = shader);
// }
// }
@EventBusSubscriber(value = Dist.CLIENT, bus = EventBusSubscriber.Bus.MOD)
private static class Shaders {
private static ShaderInstance glowingShader;
@SubscribeEvent
public static void onRegisterShaders(RegisterShadersEvent event) throws IOException {
ResourceProvider resourceProvider = event.getResourceProvider();
event.registerShader(new ShaderInstance(resourceProvider, Create.asResource("glowing_shader"), DefaultVertexFormat.NEW_ENTITY), shader -> glowingShader = shader);
}
}
}

View File

@@ -2,6 +2,7 @@ package nl.requios.effortlessbuilding.create.foundation.render;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.blaze3d.vertex.VertexConsumer;
import net.minecraft.client.renderer.LightTexture;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.RenderType;

View File

@@ -1,8 +1,15 @@
package nl.requios.effortlessbuilding.create.foundation.render;
import java.nio.ByteBuffer;
import java.util.function.IntPredicate;
import org.joml.Matrix3f;
import org.joml.Matrix4f;
import org.joml.Quaternionf;
import org.joml.Vector3f;
import org.joml.Vector4f;
import com.jozufozu.flywheel.api.vertex.ShadedVertexList;
import com.jozufozu.flywheel.api.vertex.VertexList;
import com.jozufozu.flywheel.backend.ShadersModHandler;
@@ -14,11 +21,6 @@ import com.jozufozu.flywheel.util.transform.Transform;
import com.mojang.blaze3d.vertex.BufferBuilder;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.blaze3d.vertex.VertexConsumer;
import org.joml.Matrix3f;
import org.joml.Matrix4f;
import org.joml.Quaternionf;
import org.joml.Vector3f;
import org.joml.Vector4f;
import nl.requios.effortlessbuilding.create.foundation.block.render.SpriteShiftEntry;
import nl.requios.effortlessbuilding.create.foundation.utility.Color;
@@ -96,25 +98,22 @@ public class SuperByteBuffer implements Transform<SuperByteBuffer>, TStack<Super
if (isEmpty())
return;
Matrix4f modelMat = input.last()
.pose()
.copy();
Matrix4f modelMat = new Matrix4f(input.last()
.pose());
Matrix4f localTransforms = transforms.last()
.pose();
modelMat.multiply(localTransforms);
.pose();
modelMat.mul(localTransforms);
Matrix3f normalMat;
if (fullNormalTransform) {
normalMat = input.last()
.normal()
.copy();
normalMat = new Matrix3f(input.last()
.normal());
Matrix3f localNormalTransforms = transforms.last()
.normal();
.normal();
normalMat.mul(localNormalTransforms);
} else {
normalMat = transforms.last()
.normal()
.copy();
normalMat = new Matrix3f(transforms.last()
.normal());
}
if (useWorldLight) {
@@ -127,7 +126,7 @@ public class SuperByteBuffer implements Transform<SuperByteBuffer>, TStack<Super
DiffuseLightCalculator diffuseCalculator = ForcedDiffuseState.getForcedCalculator();
final boolean disableDiffuseMult =
this.disableDiffuseMult || (ShadersModHandler.isShaderPackInUse() && diffuseCalculator == null);
this.disableDiffuseMult || (ShadersModHandler.isShaderPackInUse() && diffuseCalculator == null);
if (diffuseCalculator == null) {
diffuseCalculator = this.diffuseCalculator;
if (diffuseCalculator == null) {
@@ -142,7 +141,7 @@ public class SuperByteBuffer implements Transform<SuperByteBuffer>, TStack<Super
float z = template.getZ(i);
pos.set(x, y, z, 1F);
pos.transform(modelMat);
pos.mul(modelMat);
builder.vertex(pos.x(), pos.y(), pos.z());
float normalX = template.getNX(i);
@@ -150,7 +149,7 @@ public class SuperByteBuffer implements Transform<SuperByteBuffer>, TStack<Super
float normalZ = template.getNZ(i);
normal.set(normalX, normalY, normalZ);
normal.transform(normalMat);
normal.mul(normalMat);
float nx = normal.x();
float ny = normal.y();
float nz = normal.z();
@@ -192,9 +191,9 @@ public class SuperByteBuffer implements Transform<SuperByteBuffer>, TStack<Super
int light;
if (useWorldLight) {
lightPos.set(((x - .5f) * 15 / 16f) + .5f, (y - .5f) * 15 / 16f + .5f, (z - .5f) * 15 / 16f + .5f, 1f);
lightPos.transform(localTransforms);
lightPos.mul(localTransforms);
if (lightTransform != null) {
lightPos.transform(lightTransform);
lightPos.mul(lightTransform);
}
light = getLight(Minecraft.getInstance().level, lightPos);
@@ -290,40 +289,40 @@ public class SuperByteBuffer implements Transform<SuperByteBuffer>, TStack<Super
@Override
public SuperByteBuffer mulPose(Matrix4f pose) {
transforms.last()
.pose()
.multiply(pose);
.pose()
.mul(pose);
return this;
}
@Override
public SuperByteBuffer mulNormal(Matrix3f normal) {
transforms.last()
.normal()
.mul(normal);
.normal()
.mul(normal);
return this;
}
public SuperByteBuffer transform(PoseStack stack) {
transforms.last()
.pose()
.multiply(stack.last()
.pose());
.pose()
.mul(stack.last()
.pose());
transforms.last()
.normal()
.mul(stack.last()
.normal());
.normal()
.mul(stack.last()
.normal());
return this;
}
public SuperByteBuffer rotateCentered(Direction axis, float radians) {
translate(.5f, .5f, .5f).rotate(axis, radians)
.translate(-.5f, -.5f, -.5f);
.translate(-.5f, -.5f, -.5f);
return this;
}
public SuperByteBuffer rotateCentered(Quaternionf q) {
translate(.5f, .5f, .5f).multiply(q)
.translate(-.5f, -.5f, -.5f);
.translate(-.5f, -.5f, -.5f);
return this;
}
@@ -378,13 +377,13 @@ public class SuperByteBuffer implements Transform<SuperByteBuffer>, TStack<Super
public SuperByteBuffer shiftUVScrolling(SpriteShiftEntry entry, float scrollU, float scrollV) {
this.spriteShiftFunc = (builder, u, v) -> {
float targetU = u - entry.getOriginal()
.getU0() + entry.getTarget()
.getU0()
+ scrollU;
.getU0() + entry.getTarget()
.getU0()
+ scrollU;
float targetV = v - entry.getOriginal()
.getV0() + entry.getTarget()
.getV0()
+ scrollV;
.getV0() + entry.getTarget()
.getV0()
+ scrollV;
builder.uv(targetU, targetV);
};
return this;
@@ -393,9 +392,9 @@ public class SuperByteBuffer implements Transform<SuperByteBuffer>, TStack<Super
public SuperByteBuffer shiftUVtoSheet(SpriteShiftEntry entry, float uTarget, float vTarget, int sheetSize) {
this.spriteShiftFunc = (builder, u, v) -> {
float targetU = entry.getTarget()
.getU((SpriteShiftEntry.getUnInterpolatedU(entry.getOriginal(), u) / sheetSize) + uTarget * 16);
.getU((SpriteShiftEntry.getUnInterpolatedU(entry.getOriginal(), u) / sheetSize) + uTarget * 16);
float targetV = entry.getTarget()
.getV((SpriteShiftEntry.getUnInterpolatedV(entry.getOriginal(), v) / sheetSize) + vTarget * 16);
.getV((SpriteShiftEntry.getUnInterpolatedV(entry.getOriginal(), v) / sheetSize) + vTarget * 16);
builder.uv(targetU, targetV);
};
return this;

View File

@@ -1,26 +1,28 @@
package nl.requios.effortlessbuilding.create.foundation.render;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
public class SuperByteBufferCache {
protected final Map<Compartment<?>, Cache<Object, SuperByteBuffer>> caches = new HashMap<>();
public synchronized void registerCompartment(Compartment<?> compartment) {
caches.put(compartment, CacheBuilder.newBuilder()
.<Object, SuperByteBuffer>removalListener(n -> n.getValue().delete())
.build());
}
public synchronized void registerCompartment(Compartment<?> compartment, long ticksUntilExpired) {
caches.put(compartment, CacheBuilder.newBuilder()
.expireAfterAccess(ticksUntilExpired * 50, TimeUnit.MILLISECONDS)
.<Object, SuperByteBuffer>removalListener(n -> n.getValue().delete())
.build());
}

View File

@@ -1,7 +1,10 @@
package nl.requios.effortlessbuilding.create.foundation.render;
import java.util.SortedMap;
import com.mojang.blaze3d.vertex.BufferBuilder;
import com.mojang.blaze3d.vertex.VertexConsumer;
import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap;
import net.minecraft.Util;
import net.minecraft.client.renderer.ChunkBufferBuilderPack;
@@ -10,8 +13,6 @@ import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.Sheets;
import net.minecraft.client.resources.model.ModelBakery;
import java.util.SortedMap;
public class SuperRenderTypeBuffer implements MultiBufferSource {
private static final SuperRenderTypeBuffer INSTANCE = new SuperRenderTypeBuffer();
@@ -83,7 +84,7 @@ public class SuperRenderTypeBuffer implements MultiBufferSource {
put(map, p_173062_);
});
});
private final BufferSource bufferSource = MultiBufferSource.immediateWithBuffers(fixedBuffers, new BufferBuilder(256));
private final MultiBufferSource.BufferSource bufferSource = MultiBufferSource.immediateWithBuffers(fixedBuffers, new BufferBuilder(256));
private static void put(Object2ObjectLinkedOpenHashMap<RenderType, BufferBuilder> map, RenderType type) {
map.put(type, new BufferBuilder(type.bufferSize()));

View File

@@ -1,5 +1,10 @@
package nl.requios.effortlessbuilding.create.foundation.utility;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import javax.annotation.Nullable;
import net.minecraft.core.BlockPos;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.entity.LivingEntity;
@@ -8,10 +13,6 @@ import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraftforge.event.ForgeEventFactory;
import javax.annotation.Nullable;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
public abstract class AbstractBlockBreakQueue {
protected Consumer<BlockPos> makeCallbackFor(Level world, float effectChance, ItemStack toDamage,
@Nullable Player playerEntity, BiConsumer<BlockPos, ItemStack> drop) {

View File

@@ -1,6 +1,9 @@
package nl.requios.effortlessbuilding.create.foundation.utility;
import nl.requios.effortlessbuilding.create.foundation.ponder.PonderWorld;
import nl.requios.effortlessbuilding.create.foundation.ponder.ui.PonderUI;
import nl.requios.effortlessbuilding.create.foundation.utility.worldWrappers.WrappedClientWorld;
import net.minecraft.client.Minecraft;
import net.minecraft.world.level.LevelAccessor;
@@ -43,7 +46,7 @@ public class AnimationTickHolder {
public static int getTicks(LevelAccessor world) {
if (world instanceof WrappedClientWorld)
return getTicks(((WrappedClientWorld) world).getWrappedWorld());
return getTicks();
return /*world instanceof PonderWorld ? PonderUI.ponderTicks : */getTicks();
}
public static float getRenderTime(LevelAccessor world) {
@@ -51,6 +54,6 @@ public class AnimationTickHolder {
}
public static float getPartialTicks(LevelAccessor world) {
return getPartialTicks();
return /*world instanceof PonderWorld ? PonderUI.getPartialTicks() : */getPartialTicks();
}
}

View File

@@ -0,0 +1,146 @@
package nl.requios.effortlessbuilding.create.foundation.utility;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import org.jetbrains.annotations.Nullable;
import nl.requios.effortlessbuilding.create.Create;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.registries.IForgeRegistry;
public class AttachedRegistry<K, V> {
private static final List<AttachedRegistry<?, ?>> ALL = new ArrayList<>();
protected final IForgeRegistry<K> objectRegistry;
protected final Map<ResourceLocation, V> idMap = new HashMap<>();
protected final Map<K, V> objectMap = new IdentityHashMap<>();
protected final Map<ResourceLocation, Function<K, V>> deferredRegistrations = new HashMap<>();
protected boolean unwrapped = false;
public AttachedRegistry(IForgeRegistry<K> objectRegistry) {
this.objectRegistry = objectRegistry;
ALL.add(this);
}
public void register(ResourceLocation id, V value) {
if (!unwrapped) {
idMap.put(id, value);
} else {
K object = objectRegistry.getValue(id);
if (object != null) {
objectMap.put(object, value);
} else {
Create.LOGGER.warn("Could not get object for id '" + id + "' in AttachedRegistry after unwrapping!");
}
}
}
public void register(K object, V value) {
if (unwrapped) {
objectMap.put(object, value);
} else {
ResourceLocation id = objectRegistry.getKey(object);
if (id != null) {
idMap.put(id, value);
} else {
Create.LOGGER.warn("Could not get id of object '" + object + "' in AttachedRegistry before unwrapping!");
}
}
}
public void registerDeferred(ResourceLocation id, Function<K, V> func) {
if (!unwrapped) {
deferredRegistrations.put(id, func);
} else {
K object = objectRegistry.getValue(id);
if (object != null) {
objectMap.put(object, func.apply(object));
} else {
Create.LOGGER.warn("Could not get object for id '" + id + "' in AttachedRegistry after unwrapping!");
}
}
}
public void registerDeferred(K object, Function<K, V> func) {
if (unwrapped) {
objectMap.put(object, func.apply(object));
} else {
ResourceLocation id = objectRegistry.getKey(object);
if (id != null) {
deferredRegistrations.put(id, func);
} else {
Create.LOGGER.warn("Could not get id of object '" + object + "' in AttachedRegistry before unwrapping!");
}
}
}
@Nullable
public V get(ResourceLocation id) {
if (!unwrapped) {
return idMap.get(id);
} else {
K object = objectRegistry.getValue(id);
if (object != null) {
return objectMap.get(object);
} else {
Create.LOGGER.warn("Could not get object for id '" + id + "' in AttachedRegistry after unwrapping!");
return null;
}
}
}
@Nullable
public V get(K object) {
if (unwrapped) {
return objectMap.get(object);
} else {
ResourceLocation id = objectRegistry.getKey(object);
if (id != null) {
return idMap.get(id);
} else {
Create.LOGGER.warn("Could not get id of object '" + object + "' in AttachedRegistry before unwrapping!");
return null;
}
}
}
public boolean isUnwrapped() {
return unwrapped;
}
protected void unwrap() {
deferredRegistrations.forEach((id, func) -> {
K object = objectRegistry.getValue(id);
if (object != null) {
objectMap.put(object, func.apply(object));
} else {
Create.LOGGER.warn("Could not get object for id '" + id + "' in AttachedRegistry during unwrapping!");
}
});
idMap.forEach((id, value) -> {
K object = objectRegistry.getValue(id);
if (object != null) {
objectMap.put(object, value);
} else {
Create.LOGGER.warn("Could not get object for id '" + id + "' in AttachedRegistry during unwrapping!");
}
});
deferredRegistrations.clear();
idMap.clear();
unwrapped = true;
}
public static void unwrapAll() {
for (AttachedRegistry<?, ?> registry : ALL) {
registry.unwrap();
}
}
}

View File

@@ -1,6 +1,7 @@
package nl.requios.effortlessbuilding.create.foundation.utility;
import nl.requios.effortlessbuilding.create.foundation.utility.animation.LerpedFloat;
import net.minecraft.client.Minecraft;
import net.minecraft.util.Mth;

View File

@@ -1,12 +1,15 @@
package nl.requios.effortlessbuilding.create.foundation.utility;
import com.google.common.hash.Hashing;
import org.joml.Vector3f;
import net.minecraft.util.Mth;
import net.minecraft.world.phys.Vec3;
import java.util.function.UnaryOperator;
import javax.annotation.Nonnull;
import java.util.function.UnaryOperator;
import org.joml.Vector3f;
import com.google.common.hash.Hashing;
import net.minecraft.util.Mth;
import net.minecraft.world.phys.Vec3;
public class Color {
public final static Color TRANSPARENT_BLACK = new Color(0, 0, 0, 0).setImmutable();

View File

@@ -0,0 +1,39 @@
package nl.requios.effortlessbuilding.create.foundation.utility;
import java.util.Vector;
import com.mojang.blaze3d.platform.InputConstants;
import nl.requios.effortlessbuilding.create.AllKeys;
import net.minecraft.client.KeyMapping;
import net.minecraft.client.Minecraft;
import net.minecraft.client.Options;
public class ControlsUtil {
private static Vector<KeyMapping> standardControls;
public static Vector<KeyMapping> getControls() {
if (standardControls == null) {
Options gameSettings = Minecraft.getInstance().options;
standardControls = new Vector<>(6);
standardControls.add(gameSettings.keyUp);
standardControls.add(gameSettings.keyDown);
standardControls.add(gameSettings.keyLeft);
standardControls.add(gameSettings.keyRight);
standardControls.add(gameSettings.keyJump);
standardControls.add(gameSettings.keyShift);
}
return standardControls;
}
public static boolean isActuallyPressed(KeyMapping kb) {
InputConstants.Key key = kb.getKey();
if (key.getType() == InputConstants.Type.MOUSE) {
return AllKeys.isMouseButtonDown(key.getValue());
} else {
return AllKeys.isKeyDown(key.getValue());
}
}
}

View File

@@ -1,14 +1,20 @@
package nl.requios.effortlessbuilding.create.foundation.utility;
import com.google.common.collect.ImmutableList;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import java.util.Iterator;
import java.util.List;
import java.util.function.*;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Stream;
import com.google.common.collect.ImmutableList;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
public class Couple<T> extends Pair<T, T> implements Iterable<T> {
private static final Couple<Boolean> TRUE_AND_FALSE = Couple.create(true, false);

View File

@@ -1,102 +0,0 @@
package nl.requios.effortlessbuilding.create.foundation.utility;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.registries.IForgeRegistry;
import nl.requios.effortlessbuilding.EffortlessBuilding;
import nl.requios.effortlessbuilding.create.Create;
import org.jetbrains.annotations.Nullable;
import java.util.*;
public class CreateRegistry<K, V> {
private static final List<CreateRegistry<?, ?>> ALL = new ArrayList<>();
protected final IForgeRegistry<K> objectRegistry;
protected final Map<ResourceLocation, V> locationMap = new HashMap<>();
protected final Map<K, V> objectMap = new IdentityHashMap<>();
protected boolean unwrapped = false;
public CreateRegistry(IForgeRegistry<K> objectRegistry) {
this.objectRegistry = objectRegistry;
ALL.add(this);
}
public void register(ResourceLocation location, V value) {
if (!unwrapped) {
locationMap.put(location, value);
} else {
K object = objectRegistry.getValue(location);
if (object != null) {
objectMap.put(object, value);
} else {
Create.LOGGER.warn("Could not get object for location '" + location + "' in CreateRegistry after unwrapping!");
}
}
}
public void register(K object, V value) {
if (unwrapped) {
objectMap.put(object, value);
} else {
ResourceLocation location = objectRegistry.getKey(object);
if (location != null) {
locationMap.put(location, value);
} else {
Create.LOGGER.warn("Could not get location of object '" + object + "' in CreateRegistry before unwrapping!");
}
}
}
@Nullable
public V get(ResourceLocation location) {
if (!unwrapped) {
return locationMap.get(location);
} else {
K object = objectRegistry.getValue(location);
if (object != null) {
return objectMap.get(object);
} else {
Create.LOGGER.warn("Could not get object for location '" + location + "' in CreateRegistry after unwrapping!");
return null;
}
}
}
@Nullable
public V get(K object) {
if (unwrapped) {
return objectMap.get(object);
} else {
ResourceLocation location = objectRegistry.getKey(object);
if (location != null) {
return locationMap.get(location);
} else {
Create.LOGGER.warn("Could not get location of object '" + object + "' in CreateRegistry before unwrapping!");
return null;
}
}
}
public boolean isUnwrapped() {
return unwrapped;
}
protected void unwrap() {
for (Map.Entry<ResourceLocation, V> entry : locationMap.entrySet()) {
ResourceLocation location = entry.getKey();
K object = objectRegistry.getValue(location);
if (object != null) {
objectMap.put(object, entry.getValue());
} else {
Create.LOGGER.warn("Could not get object for location '" + location + "' in CreateRegistry during unwrapping!");
}
}
unwrapped = true;
}
public static void unwrapAll() {
for (CreateRegistry<?, ?> registry : ALL) {
registry.unwrap();
}
}
}

View File

@@ -1,6 +1,7 @@
package nl.requios.effortlessbuilding.create.foundation.utility;
import nl.requios.effortlessbuilding.create.Create;
import net.minecraft.ChatFormatting;
import net.minecraft.client.Minecraft;
import net.minecraft.network.chat.Component;

View File

@@ -1,12 +1,13 @@
package nl.requios.effortlessbuilding.create.foundation.utility;
import java.util.Map;
import com.google.common.collect.ImmutableMap;
import net.minecraft.world.item.DyeColor;
import net.minecraft.world.level.ItemLike;
import net.minecraft.world.level.block.Blocks;
import java.util.Map;
public class DyeHelper {
public static ItemLike getWoolOfDye(DyeColor color) {

View File

@@ -5,6 +5,7 @@ import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import nl.requios.effortlessbuilding.create.Create;
import net.minecraft.commands.CommandSource;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.core.BlockPos;

View File

@@ -1,20 +1,22 @@
package nl.requios.effortlessbuilding.create.foundation.utility;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.internal.Streams;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import nl.requios.effortlessbuilding.create.Create;
import net.minecraft.nbt.CompoundTag;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import net.minecraft.nbt.CompoundTag;
public class FilesHelper {
@@ -26,15 +28,15 @@ public class FilesHelper {
}
}
public static String findFirstValidFilename(String name, String folderPath, String extension) {
public static String findFirstValidFilename(String name, Path folderPath, String extension) {
int index = 0;
String filename;
String filepath;
Path filepath;
do {
filename = slug(name) + ((index == 0) ? "" : "_" + index) + "." + extension;
index++;
filepath = folderPath + "/" + filename;
} while (Files.exists(Paths.get(filepath)));
filepath = folderPath.resolve(filename);
} while (Files.exists(filepath));
return filename;
}

View File

@@ -1,17 +1,19 @@
package nl.requios.effortlessbuilding.create.foundation.utility;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.blaze3d.vertex.Tesselator;
import org.joml.Matrix4f;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Font;
import net.minecraft.client.renderer.LightTexture;
import net.minecraft.client.renderer.MultiBufferSource;
import java.text.BreakIterator;
import java.util.LinkedList;
import java.util.List;
import org.joml.Matrix4f;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.blaze3d.vertex.Tesselator;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Font;
import net.minecraft.client.renderer.LightTexture;
import net.minecraft.client.renderer.MultiBufferSource;
public final class FontHelper {
private FontHelper() {}
@@ -78,7 +80,7 @@ public final class FontHelper {
MultiBufferSource.BufferSource irendertypebuffer$impl = MultiBufferSource.immediate(Tesselator.getInstance()
.getBuilder());
int i = font.drawInBatch(p_228078_1_, p_228078_2_, p_228078_3_, p_228078_4_, p_228078_6_, p_228078_5_,
irendertypebuffer$impl, false, 0, LightTexture.FULL_BRIGHT);
irendertypebuffer$impl, Font.DisplayMode.NORMAL, 0, LightTexture.FULL_BRIGHT);
irendertypebuffer$impl.endBatch();
return i;
}

View File

@@ -1,10 +1,10 @@
package nl.requios.effortlessbuilding.create.foundation.utility;
import net.minecraft.nbt.CompoundTag;
import java.util.Comparator;
import java.util.function.Function;
import net.minecraft.nbt.CompoundTag;
public class IntAttached<V> extends Pair<Integer, V> {
protected IntAttached(Integer first, V second) {

View File

@@ -1,13 +1,13 @@
package nl.requios.effortlessbuilding.create.foundation.utility;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.Direction.Axis;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.Direction.Axis;
public class Iterate {
public static final boolean[] trueAndFalse = { true, false };
@@ -17,7 +17,7 @@ public class Iterate {
public static final Direction[] directions = Direction.values();
public static final Direction[] horizontalDirections = getHorizontals();
public static final Axis[] axes = Axis.values();
public static final EnumSet<Axis> axisSet = EnumSet.allOf(Axis.class);
public static final EnumSet<Direction.Axis> axisSet = EnumSet.allOf(Direction.Axis.class);
private static Direction[] getHorizontals() {
Direction[] directions = new Direction[4];
@@ -45,4 +45,13 @@ public class Iterate {
public static List<BlockPos> hereBelowAndAbove(BlockPos pos) {
return Arrays.asList(pos, pos.below(), pos.above());
}
public static <T> T cycleValue(List<T> list, T current) {
int currentIndex = list.indexOf(current);
if (currentIndex == -1) {
throw new IllegalArgumentException("Current value not found in list");
}
int nextIndex = (currentIndex + 1) % list.size();
return list.get(nextIndex);
}
}

View File

@@ -1,16 +1,17 @@
package nl.requios.effortlessbuilding.create.foundation.utility;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import nl.requios.effortlessbuilding.create.Create;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.fluids.FluidStack;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class Lang {
/**

View File

@@ -1,13 +1,13 @@
package nl.requios.effortlessbuilding.create.foundation.utility;
import java.util.List;
import joptsimple.internal.Strings;
import net.minecraft.ChatFormatting;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.world.entity.player.Player;
import java.util.List;
public class LangBuilder {
String namespace;

View File

@@ -1,10 +1,11 @@
package nl.requios.effortlessbuilding.create.foundation.utility;
import net.minecraft.client.Minecraft;
import java.text.NumberFormat;
import java.util.Locale;
import net.minecraft.client.Minecraft;
import net.minecraft.util.Mth;
public class LangNumberFormat {
private NumberFormat format = NumberFormat.getNumberInstance(Locale.ROOT);
@@ -17,7 +18,6 @@ public class LangNumberFormat {
public void update() {
format = NumberFormat.getInstance(Minecraft.getInstance()
.getLanguageManager()
.getSelected()
.getJavaLocale());
format.setMaximumFractionDigits(2);
format.setMinimumFractionDigits(0);
@@ -25,6 +25,8 @@ public class LangNumberFormat {
}
public static String format(double d) {
if (Mth.equal(d, 0))
d = 0;
return numberFormat.get()
.format(d)
.replace("\u00A0", " ");

View File

@@ -1,16 +1,22 @@
package nl.requios.effortlessbuilding.create.foundation.utility;
import net.minecraft.core.Vec3i;
import net.minecraft.nbt.*;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.phys.AABB;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import javax.annotation.Nonnull;
import net.minecraft.core.Vec3i;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.FloatTag;
import net.minecraft.nbt.IntTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.nbt.Tag;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.phys.AABB;
public class NBTHelper {
public static void putMarker(CompoundTag nbt, String marker) {
@@ -103,4 +109,22 @@ public class NBTHelper {
return new CompoundTag();
}
public static CompoundTag intToCompound(int i) {
CompoundTag compoundTag = new CompoundTag();
compoundTag.putInt("V", i);
return compoundTag;
}
public static int intFromCompound(CompoundTag compoundTag) {
return compoundTag.getInt("V");
}
public static void writeResourceLocation(CompoundTag nbt, String key, ResourceLocation location) {
nbt.putString(key, location.toString());
}
public static ResourceLocation readResourceLocation(CompoundTag nbt, String key) {
return new ResourceLocation(nbt.getString(key));
}
}

View File

@@ -1,18 +1,24 @@
package nl.requios.effortlessbuilding.create.foundation.utility;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.function.UnaryOperator;
import javax.annotation.Nullable;
//import nl.requios.effortlessbuilding.create.AllBlockEntityTypes;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.nbt.Tag;
import net.minecraft.network.chat.Component;
import net.minecraft.world.item.EnchantedBookItem;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.entity.SpawnerBlockEntity;
import javax.annotation.Nullable;
import java.util.HashMap;
import java.util.Map;
import java.util.function.UnaryOperator;
public final class NBTProcessors {
private static final Map<BlockEntityType<?>, UnaryOperator<CompoundTag>> processors = new HashMap<>();
@@ -22,7 +28,8 @@ public final class NBTProcessors {
processors.put(type, processor);
}
public static synchronized void addSurvivalProcessor(BlockEntityType<?> type, UnaryOperator<CompoundTag> processor) {
public static synchronized void addSurvivalProcessor(BlockEntityType<?> type,
UnaryOperator<CompoundTag> processor) {
survivalProcessors.put(type, processor);
}
@@ -53,30 +60,79 @@ public final class NBTProcessors {
}
return data;
});
// addProcessor(AllBlockEntityTypes.CREATIVE_CRATE.get(), itemProcessor("Filter"));
// addProcessor(AllBlockEntityTypes.PLACARD.get(), itemProcessor("Item"));
}
public static UnaryOperator<CompoundTag> itemProcessor(String tagKey) {
return data -> {
CompoundTag compound = data.getCompound(tagKey);
if (!compound.contains("tag", 10))
return data;
CompoundTag itemTag = compound.getCompound("tag");
if (itemTag == null)
return data;
HashSet<String> keys = new HashSet<>(itemTag.getAllKeys());
for (String key : keys)
if (isUnsafeItemNBTKey(key))
itemTag.remove(key);
if (itemTag.isEmpty())
compound.remove("tag");
return data;
};
}
public static ItemStack withUnsafeNBTDiscarded(ItemStack stack) {
if (stack.getTag() == null)
return stack;
ItemStack copy = stack.copy();
stack.getTag()
.getAllKeys()
.stream()
.filter(NBTProcessors::isUnsafeItemNBTKey)
.forEach(copy::removeTagKey);
if (copy.getTag()
.isEmpty())
copy.setTag(null);
return copy;
}
public static boolean isUnsafeItemNBTKey(String name) {
if (name.equals(EnchantedBookItem.TAG_STORED_ENCHANTMENTS))
return false;
if (name.equals("Enchantments"))
return false;
if (name.contains("Potion"))
return false;
if (name.contains("Damage"))
return false;
if (name.equals("display"))
return false;
return true;
}
public static boolean textComponentHasClickEvent(String json) {
Component component = Component.Serializer.fromJson(json.isEmpty() ? "\"\"" : json);
return component != null && component.getStyle() != null && component.getStyle().getClickEvent() != null;
return component != null && component.getStyle() != null && component.getStyle()
.getClickEvent() != null;
}
private NBTProcessors() {
}
private NBTProcessors() {}
@Nullable
public static CompoundTag process(BlockEntity tileEntity, CompoundTag compound, boolean survival) {
public static CompoundTag process(BlockEntity blockEntity, CompoundTag compound, boolean survival) {
if (compound == null)
return null;
BlockEntityType<?> type = tileEntity.getType();
BlockEntityType<?> type = blockEntity.getType();
if (survival && survivalProcessors.containsKey(type))
compound = survivalProcessors.get(type)
.apply(compound);
if (compound != null && processors.containsKey(type))
return processors.get(type)
.apply(compound);
if (tileEntity instanceof SpawnerBlockEntity)
if (blockEntity instanceof SpawnerBlockEntity)
return compound;
if (tileEntity.onlyOpCanSetNbt())
if (blockEntity.onlyOpCanSetNbt())
return null;
return compound;
}

View File

@@ -1,5 +1,7 @@
package nl.requios.effortlessbuilding.create.foundation.utility;
import java.util.function.Predicate;
import net.minecraft.core.BlockPos;
import net.minecraft.core.BlockPos.MutableBlockPos;
import net.minecraft.core.Direction;
@@ -12,8 +14,6 @@ import net.minecraft.world.level.Level;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.Vec3;
import java.util.function.Predicate;
public class RaycastHelper {
public static BlockHitResult rayTraceRange(Level worldIn, Player playerIn, double range) {

View File

@@ -1,5 +1,7 @@
package nl.requios.effortlessbuilding.create.foundation.utility;
import org.jetbrains.annotations.NotNull;
import net.minecraft.core.particles.ParticleType;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.EntityType;
@@ -11,7 +13,6 @@ import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.material.Fluid;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.registries.IForgeRegistry;
import org.jetbrains.annotations.NotNull;
public final class RegisteredObjects {
// registry argument for easier porting to 1.19

View File

@@ -1,9 +1,9 @@
package nl.requios.effortlessbuilding.create.foundation.utility;
import net.minecraftforge.common.util.NonNullSupplier;
import java.util.function.Supplier;
import net.minecraftforge.common.util.NonNullSupplier;
public class ResetableLazy<T> implements Supplier<T> {
private final NonNullSupplier<T> supplier;

View File

@@ -0,0 +1,46 @@
package nl.requios.effortlessbuilding.create.foundation.utility;
import java.util.Locale;
public class StringHelper {
public static String snakeCaseToCamelCase(String text) {
StringBuilder builder = new StringBuilder();
builder.append(text.substring(0, 1).toUpperCase(Locale.ROOT));
for (int i = 1; i < text.length(); i++) {
int j = text.indexOf('_', i);
if (j == -1) {
builder.append(text.substring(i));
break;
}
builder.append(text.substring(i, j).toLowerCase(Locale.ROOT));
builder.append(text.substring(j + 1, j + 2).toUpperCase(Locale.ROOT));
i = j + 1;
}
return builder.toString();
}
public static String camelCaseToSnakeCase(String text) {
StringBuilder builder = new StringBuilder();
for (char c : text.toCharArray()) {
if (Character.isUpperCase(c)) {
builder.append('_');
builder.append(Character.toLowerCase(c));
} else {
builder.append(c);
}
}
if (builder.length() > 0 && builder.charAt(0) == '_')
builder.deleteCharAt(0);
return builder.toString();
}
}

View File

@@ -1,7 +1,12 @@
package nl.requios.effortlessbuilding.create.foundation.utility;
import javax.annotation.Nullable;
import org.joml.Quaternionf;
import org.joml.Vector3f;
import nl.requios.effortlessbuilding.create.foundation.mixin.accessor.GameRendererAccessor;
import net.minecraft.client.Camera;
import net.minecraft.client.Minecraft;
import net.minecraft.core.BlockPos;
@@ -20,8 +25,6 @@ import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.block.Mirror;
import net.minecraft.world.phys.Vec3;
import javax.annotation.Nullable;
public class VecHelper {
public static final Vec3 CENTER_OF_ORIGIN = new Vec3(.5, .5, .5);
@@ -184,7 +187,7 @@ public class VecHelper {
}
public static Vec3 clamp(Vec3 vec, float maxLength) {
return vec.length() > maxLength ? vec.normalize()
return vec.lengthSqr() > maxLength * maxLength ? vec.normalize()
.scale(maxLength) : vec;
}
@@ -205,6 +208,14 @@ public class VecHelper {
Mth.clamp(vec.z, -maxLength, maxLength));
}
public static Vec3 componentMin(Vec3 vec1, Vec3 vec2) {
return new Vec3(Math.min(vec1.x, vec2.x), Math.min(vec1.y, vec2.y), Math.min(vec1.z, vec2.z));
}
public static Vec3 componentMax(Vec3 vec1, Vec3 vec2) {
return new Vec3(Math.max(vec1.x, vec2.x), Math.max(vec1.y, vec2.y), Math.max(vec1.z, vec2.z));
}
public static Vec3 project(Vec3 vec, Vec3 ontoVec) {
if (ontoVec.equals(Vec3.ZERO))
return Vec3.ZERO;
@@ -215,7 +226,7 @@ public class VecHelper {
public static Vec3 intersectSphere(Vec3 origin, Vec3 lineDirection, Vec3 sphereCenter, double radius) {
if (lineDirection.equals(Vec3.ZERO))
return null;
if (lineDirection.length() != 1)
if (lineDirection.lengthSqr() != 1)
lineDirection = lineDirection.normalize();
Vec3 diff = origin.subtract(sphereCenter);
@@ -237,13 +248,12 @@ public class VecHelper {
*/
Camera ari = Minecraft.getInstance().gameRenderer.getMainCamera();
Vec3 camera_pos = ari.getPosition();
Quaternionf camera_rotation_conj = ari.rotation()
.copy();
camera_rotation_conj.conj();
Quaternionf camera_rotation_conj = new Quaternionf(ari.rotation());
camera_rotation_conj.conjugate();
Vector3f result3f = new Vector3f((float) (camera_pos.x - target.x), (float) (camera_pos.y - target.y),
(float) (camera_pos.z - target.z));
result3f.transform(camera_rotation_conj);
result3f.rotate(camera_rotation_conj);
// ----- compensate for view bobbing (if active) -----
// the following code adapted from GameRenderer::applyBobbing (to invert it)
@@ -258,23 +268,23 @@ public class VecHelper {
float f1 = -(distwalked_modified + f * partialTicks);
float f2 = Mth.lerp(partialTicks, playerentity.oBob, playerentity.bob);
Quaternionf q2 =
new Quaternionf(Vector3f.XP, Math.abs(Mth.cos(f1 * (float) Math.PI - 0.2F) * f2) * 5.0F, true);
q2.conj();
result3f.transform(q2);
com.mojang.math.Axis.XP.rotationDegrees(Math.abs(Mth.cos(f1 * (float) Math.PI - 0.2F) * f2) * 5.0F);
q2.conjugate();
result3f.rotate(q2);
Quaternionf q1 = new Quaternionf(Vector3f.ZP, Mth.sin(f1 * (float) Math.PI) * f2 * 3.0F, true);
q1.conj();
result3f.transform(q1);
Quaternionf q1 = com.mojang.math.Axis.ZP.rotationDegrees(Mth.sin(f1 * (float) Math.PI) * f2 * 3.0F);
q1.conjugate();
result3f.rotate(q1);
Vector3f bob_translation = new Vector3f((Mth.sin(f1 * (float) Math.PI) * f2 * 0.5F),
(-Math.abs(Mth.cos(f1 * (float) Math.PI) * f2)), 0.0f);
bob_translation.setY(-bob_translation.y()); // this is weird but hey, if it works
bob_translation.y = -bob_translation.y(); // this is weird but hey, if it works
result3f.add(bob_translation);
}
}
// ----- adjust for fov -----
float fov = 70;//(float) ((GameRendererAccessor) mc.gameRenderer).create$callGetFov(ari, partialTicks, true);
float fov = (float) ((GameRendererAccessor) mc.gameRenderer).create$callGetFov(ari, partialTicks, true);
float half_height = (float) mc.getWindow()
.getGuiScaledHeight() / 2;
@@ -308,7 +318,7 @@ public class VecHelper {
return null;
if (intersect[0] < 0 || intersect[1] < 0)
return null;
if (intersect[0] > pDiff.length() || intersect[1] > qDiff.length())
if (intersect[0] * intersect[0] > pDiff.lengthSqr() || intersect[1] * intersect[1] > qDiff.lengthSqr())
return null;
return intersect;
}

View File

@@ -1,5 +1,12 @@
package nl.requios.effortlessbuilding.create.foundation.utility;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import org.apache.commons.lang3.mutable.MutableObject;
import net.minecraft.core.Direction;
import net.minecraft.core.Direction.Axis;
import net.minecraft.core.Direction.AxisDirection;
@@ -7,12 +14,6 @@ import net.minecraft.world.level.block.Block;
import net.minecraft.world.phys.Vec3;
import net.minecraft.world.phys.shapes.Shapes;
import net.minecraft.world.phys.shapes.VoxelShape;
import org.apache.commons.lang3.mutable.MutableObject;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
public class VoxelShaper {

View File

@@ -1,8 +1,5 @@
package nl.requios.effortlessbuilding.create.foundation.utility;
import net.minecraft.world.level.LevelAccessor;
import javax.annotation.Nonnull;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
@@ -12,6 +9,10 @@ import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import javax.annotation.Nonnull;
import net.minecraft.world.level.LevelAccessor;
public class WorldAttached<T> {
// weak references to prevent leaking hashmaps when a WorldAttached is GC'd during runtime

View File

@@ -1,13 +1,13 @@
package nl.requios.effortlessbuilding.create.foundation.utility;
import net.minecraft.core.Registry;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.level.LevelAccessor;
public class WorldHelper {
public static ResourceLocation getDimensionID(LevelAccessor world) {
return world.registryAccess()
.registryOrThrow(Registry.DIMENSION_TYPE_REGISTRY)
.registryOrThrow(Registries.DIMENSION_TYPE)
.getKey(world.dimensionType());
}
}

View File

@@ -1,6 +1,7 @@
package nl.requios.effortlessbuilding.create.foundation.utility.animation;
import nl.requios.effortlessbuilding.create.foundation.utility.AngleHelper;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.util.Mth;
@@ -94,7 +95,7 @@ public class LerpedFloat {
}
public boolean settled() {
return Mth.equal((double) previousValue, value);
return Mth.equal((double) previousValue, value) && (chaseFunction == null || Mth.equal((double) value, chaseTarget));
}
public float getChaseTarget() {

View File

@@ -1,9 +1,9 @@
package nl.requios.effortlessbuilding.create.foundation.utility.animation;
import net.minecraft.util.Mth;
import java.util.ArrayList;
import net.minecraft.util.Mth;
public class PhysicalFloat {
float previousValue;

View File

@@ -1,14 +1,15 @@
package nl.requios.effortlessbuilding.create.foundation.utility.worldWrappers;
import net.minecraft.world.level.entity.EntityAccess;
import net.minecraft.world.level.entity.EntityTypeTest;
import net.minecraft.world.level.entity.LevelEntityGetter;
import net.minecraft.world.phys.AABB;
import java.util.Collections;
import java.util.UUID;
import java.util.function.Consumer;
import net.minecraft.util.AbortableIterationConsumer;
import net.minecraft.world.level.entity.EntityAccess;
import net.minecraft.world.level.entity.EntityTypeTest;
import net.minecraft.world.level.entity.LevelEntityGetter;
import net.minecraft.world.phys.AABB;
public class DummyLevelEntityGetter<T extends EntityAccess> implements LevelEntityGetter<T> {
@Override
@@ -27,7 +28,7 @@ public class DummyLevelEntityGetter<T extends EntityAccess> implements LevelEnti
}
@Override
public <U extends T> void get(EntityTypeTest<T, U> p_156935_, Consumer<U> p_156936_) {
public <U extends T> void get(EntityTypeTest<T, U> p_156935_, AbortableIterationConsumer<U> p_156936_) {
}
@Override
@@ -35,7 +36,7 @@ public class DummyLevelEntityGetter<T extends EntityAccess> implements LevelEnti
}
@Override
public <U extends T> void get(EntityTypeTest<T, U> p_156932_, AABB p_156933_, Consumer<U> p_156934_) {
public <U extends T> void get(EntityTypeTest<T, U> p_156932_, AABB p_156933_, AbortableIterationConsumer<U> p_156934_) {
}
}

View File

@@ -1,11 +1,11 @@
package nl.requios.effortlessbuilding.create.foundation.utility.worldWrappers;
import javax.annotation.Nullable;
import net.minecraft.server.level.progress.ChunkProgressListener;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.chunk.ChunkStatus;
import javax.annotation.Nullable;
public class DummyStatusListener implements ChunkProgressListener {
@Override

View File

@@ -1,14 +1,14 @@
package nl.requios.effortlessbuilding.create.foundation.utility.worldWrappers;
import java.util.HashMap;
import java.util.function.Predicate;
import net.minecraft.core.BlockPos;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.material.FluidState;
import java.util.HashMap;
import java.util.function.Predicate;
public class PlacementSimulationServerWorld extends WrappedServerWorld {
public HashMap<BlockPos, BlockState> blocksAdded;

View File

@@ -1,5 +1,7 @@
package nl.requios.effortlessbuilding.create.foundation.utility.worldWrappers;
import java.util.function.BiFunction;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.LevelAccessor;
@@ -7,8 +9,6 @@ import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.material.FluidState;
import java.util.function.BiFunction;
public class RayTraceWorld implements BlockGetter {
private final LevelAccessor template;

View File

@@ -1,5 +1,10 @@
package nl.requios.effortlessbuilding.create.foundation.utility.worldWrappers;
import java.util.List;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.core.BlockPos;
@@ -18,10 +23,6 @@ import net.minecraft.world.level.material.FluidState;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
import java.util.List;
@OnlyIn(Dist.CLIENT)
@SuppressWarnings("deprecation")
@ParametersAreNonnullByDefault

View File

@@ -1,5 +1,12 @@
package nl.requios.effortlessbuilding.create.foundation.utility.worldWrappers;
import java.util.Collections;
import java.util.List;
import javax.annotation.ParametersAreNonnullByDefault;
import nl.requios.effortlessbuilding.create.foundation.mixin.accessor.EntityAccessor;
import net.minecraft.MethodsReturnNonnullByDefault;
import net.minecraft.Util;
import net.minecraft.core.BlockPos;
@@ -20,10 +27,6 @@ import net.minecraft.world.level.saveddata.maps.MapItemSavedData;
import net.minecraft.world.level.storage.ServerLevelData;
import net.minecraft.world.ticks.LevelTicks;
import javax.annotation.ParametersAreNonnullByDefault;
import java.util.Collections;
import java.util.List;
@ParametersAreNonnullByDefault
@MethodsReturnNonnullByDefault
public class WrappedServerWorld extends ServerLevel {
@@ -35,7 +38,7 @@ public class WrappedServerWorld extends ServerLevel {
(ServerLevelData) world.getLevelData(), world.dimension(),
new LevelStem(world.dimensionTypeRegistration(), world.getChunkSource().getGenerator()),
new DummyStatusListener(), world.isDebug(), world.getBiomeManager().biomeZoomSeed,
Collections.emptyList(), false);
Collections.emptyList(), false, world.getRandomSequences());
this.world = world;
}
@@ -92,7 +95,7 @@ public class WrappedServerWorld extends ServerLevel {
@Override
public boolean addFreshEntity(Entity entityIn) {
entityIn.level = world;
((EntityAccessor) entityIn).create$callSetLevel(world);
return world.addFreshEntity(entityIn);
}

View File

@@ -1,10 +1,23 @@
package nl.requios.effortlessbuilding.create.foundation.utility.worldWrappers;
import net.minecraft.core.*;
import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;
import javax.annotation.Nullable;
import nl.requios.effortlessbuilding.create.foundation.mixin.accessor.EntityAccessor;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.Holder;
import net.minecraft.core.RegistryAccess;
import net.minecraft.core.SectionPos;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.flag.FeatureFlagSet;
import net.minecraft.world.item.crafting.RecipeManager;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.biome.Biome;
@@ -23,11 +36,6 @@ import net.minecraft.world.phys.Vec3;
import net.minecraft.world.scores.Scoreboard;
import net.minecraft.world.ticks.LevelTickAccess;
import javax.annotation.Nullable;
import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;
public class WrappedWorld extends Level {
protected Level world;
@@ -36,7 +44,7 @@ public class WrappedWorld extends Level {
protected LevelEntityGetter<Entity> entityGetter = new DummyLevelEntityGetter<>();
public WrappedWorld(Level world) {
super((WritableLevelData) world.getLevelData(), world.dimension(), world.dimensionTypeRegistration(),
super((WritableLevelData) world.getLevelData(), world.dimension(), world.registryAccess(), world.dimensionTypeRegistration(),
world::getProfiler, world.isClientSide, world.isDebug(), 0, 0);
this.world = world;
}
@@ -110,11 +118,15 @@ public class WrappedWorld extends Level {
@Override
public void playSeededSound(Player p_220363_, double p_220364_, double p_220365_, double p_220366_,
SoundEvent p_220367_, SoundSource p_220368_, float p_220369_, float p_220370_, long p_220371_) {}
SoundEvent p_220367_, SoundSource p_220368_, float p_220369_, float p_220370_, long p_220371_) {}
@Override
public void playSeededSound(Player p_220372_, Entity p_220373_, SoundEvent p_220374_, SoundSource p_220375_,
float p_220376_, float p_220377_, long p_220378_) {}
public void playSeededSound(Player pPlayer, double pX, double pY, double pZ, Holder<SoundEvent> pSound,
SoundSource pSource, float pVolume, float pPitch, long pSeed) {}
@Override
public void playSeededSound(Player pPlayer, Entity pEntity, Holder<SoundEvent> pSound, SoundSource pCategory,
float pVolume, float pPitch, long pSeed) {}
@Override
public void playSound(@Nullable Player player, double x, double y, double z, SoundEvent soundIn,
@@ -136,7 +148,7 @@ public class WrappedWorld extends Level {
@Override
public boolean addFreshEntity(Entity entityIn) {
entityIn.level = world;
((EntityAccessor) entityIn).create$callSetLevel(world);
return world.addFreshEntity(entityIn);
}
@@ -247,4 +259,10 @@ public class WrappedWorld extends Level {
public int getSectionYFromSectionIndex(int sectionIndex) {
return sectionIndex + this.getMinSection();
}
@Override
public FeatureFlagSet enabledFeatures() {
return world.enabledFeatures();
}
}

View File

@@ -1,6 +1,6 @@
@ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault
package nl.requios.effortlessbuilding.create.foundation.utility.worldWrappers;
import net.minecraft.MethodsReturnNonnullByDefault;
import javax.annotation.ParametersAreNonnullByDefault;
import net.minecraft.MethodsReturnNonnullByDefault;