mirror of
https://github.com/VolmitSoftware/Iris.git
synced 2026-12-01 18:24:06 +00:00
Port the Jigsaw Studio onto the tool-world api
The studio service, painter, menus, tool items, preview and board now use ToolWorld, ToolPlayer, ChunkPainter, BlockState and BlockEntityData instead of Bukkit, Engine and the INMS bridge. A tool world takes the studio slot through StudioSlotOccupant, and JigsawStudioActivation is a plain registry owned by the service. CommandJigsaw reaches the service through JigsawStudioBridge until its rewrite.
This commit is contained in:
1 parent
18c6b189d1
commit
6879af515e
52 files changed
+5914
-4713
No files matched your search
@@ -932,10 +932,6 @@ public final class StudioOpenCoordinator {
|
||||
false,
|
||||
true,
|
||||
IrisCreator.DatapackPreparation.REUSE_LOADED_RUNTIME_IF_READY),
|
||||
JIGSAW(
|
||||
false,
|
||||
false,
|
||||
IrisCreator.DatapackPreparation.REUSE_LOADED_RUNTIME_IF_READY),
|
||||
TOOL(
|
||||
false,
|
||||
false,
|
||||
@@ -966,7 +962,7 @@ public final class StudioOpenCoordinator {
|
||||
}
|
||||
|
||||
public boolean prepareGeneratorState() {
|
||||
return this != JIGSAW && this != TOOL;
|
||||
return this != TOOL;
|
||||
}
|
||||
|
||||
public IrisCreator.DatapackPreparation datapackPreparation() {
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.runtime;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
/**
|
||||
* A tool world that holds the studio slot, the way an open studio project does: opening another studio, the studio
|
||||
* close command and a server stop go through it. The studio service asks it, and the platform's tool world answers for
|
||||
* the tool that owns the world.
|
||||
*/
|
||||
public interface StudioSlotOccupant {
|
||||
/** A message that vetoes closing the world now; empty lets it close. */
|
||||
Optional<String> closeRefusal();
|
||||
|
||||
/**
|
||||
* Gets the world ready to be replaced by another studio, such as finishing a save. Completes when the world may be
|
||||
* closed, or fails with the message to show the user.
|
||||
*
|
||||
* @param requestedBy the player who asked for the replacement; empty when the console did
|
||||
*/
|
||||
CompletableFuture<Void> prepareReplacement(Optional<UUID> requestedBy);
|
||||
|
||||
/** Closes the world and sends its players back; completes when it is unloaded and deleted. */
|
||||
CompletableFuture<Void> close();
|
||||
}
|
||||
@@ -60,11 +60,9 @@ import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class BoardSVC implements IrisService, BoardProvider {
|
||||
private static final String SEPARATOR = "&7&m-------------------";
|
||||
private static final Pattern LEGACY_COLOR = Pattern.compile("(?i)\\u00a7[0-9A-FK-ORX]");
|
||||
|
||||
private final Map<Player, PlayerBoard> boards = new ConcurrentHashMap<>();
|
||||
private final Map<UUID, JigsawStudioBoardContext> jigsawContexts = new ConcurrentHashMap<>();
|
||||
private final Map<UUID, ToolSidebar> toolSidebars = new ConcurrentHashMap<>();
|
||||
private final Map<UUID, UUID> yieldedWorlds = new ConcurrentHashMap<>();
|
||||
private final Set<UUID> hiddenPlayers = ConcurrentHashMap.newKeySet();
|
||||
@@ -118,7 +116,6 @@ public class BoardSVC implements IrisService, BoardProvider {
|
||||
board.cancel();
|
||||
}
|
||||
boards.clear();
|
||||
jigsawContexts.clear();
|
||||
toolSidebars.clear();
|
||||
yieldedWorlds.clear();
|
||||
hiddenPlayers.clear();
|
||||
@@ -138,7 +135,6 @@ public class BoardSVC implements IrisService, BoardProvider {
|
||||
@EventHandler(priority = EventPriority.HIGHEST)
|
||||
public void on(PlayerQuitEvent e) {
|
||||
remove(e.getPlayer());
|
||||
jigsawContexts.remove(e.getPlayer().getUniqueId());
|
||||
toolSidebars.remove(e.getPlayer().getUniqueId());
|
||||
yieldedWorlds.remove(e.getPlayer().getUniqueId());
|
||||
clearPlayerPreference(e.getPlayer().getUniqueId());
|
||||
@@ -166,7 +162,6 @@ public class BoardSVC implements IrisService, BoardProvider {
|
||||
}
|
||||
|
||||
if (!isEligibleWorld(p)) {
|
||||
jigsawContexts.remove(playerId);
|
||||
toolSidebars.remove(playerId);
|
||||
remove(p);
|
||||
return;
|
||||
@@ -174,11 +169,8 @@ public class BoardSVC implements IrisService, BoardProvider {
|
||||
|
||||
PlayerBoard playerBoard = boards.computeIfAbsent(p, PlayerBoard::new);
|
||||
ToolSidebar toolSidebar = currentToolSidebar(p);
|
||||
JigsawStudioBoardContext jigsawContext = currentJigsawContext(p);
|
||||
if (toolSidebar != null) {
|
||||
playerBoard.showTool(toolSidebar);
|
||||
} else if (jigsawContext != null) {
|
||||
playerBoard.showJigsaw(jigsawContext);
|
||||
} else {
|
||||
playerBoard.showOrdinary();
|
||||
}
|
||||
@@ -219,32 +211,6 @@ public class BoardSVC implements IrisService, BoardProvider {
|
||||
updatePlayer(player);
|
||||
}
|
||||
|
||||
public void applyJigsawContext(Player player, JigsawStudioBoardContext context) {
|
||||
Objects.requireNonNull(player, "Jigsaw Studio board player");
|
||||
Objects.requireNonNull(context, "Jigsaw Studio board context");
|
||||
if (!J.isOwnedByCurrentRegion(player)) {
|
||||
J.runEntity(player, () -> applyJigsawContext(player, context));
|
||||
return;
|
||||
}
|
||||
if (!player.isOnline()) {
|
||||
return;
|
||||
}
|
||||
jigsawContexts.put(player.getUniqueId(), context);
|
||||
if (context.worldId().equals(player.getWorld().getUID())) {
|
||||
updatePlayer(player);
|
||||
}
|
||||
}
|
||||
|
||||
public void clearJigsawContext(Player player) {
|
||||
Objects.requireNonNull(player, "Jigsaw Studio board player");
|
||||
if (!J.isOwnedByCurrentRegion(player)) {
|
||||
J.runEntity(player, () -> clearJigsawContext(player));
|
||||
return;
|
||||
}
|
||||
jigsawContexts.remove(player.getUniqueId());
|
||||
updatePlayer(player);
|
||||
}
|
||||
|
||||
public void refreshOrdinaryContext(Player player) {
|
||||
Objects.requireNonNull(player, "Studio board player");
|
||||
if (!J.isOwnedByCurrentRegion(player)) {
|
||||
@@ -253,7 +219,6 @@ public class BoardSVC implements IrisService, BoardProvider {
|
||||
}
|
||||
PlayerBoard previousBoard = boards.get(player);
|
||||
boolean alreadyOrdinary = previousBoard != null && previousBoard.isOrdinary();
|
||||
jigsawContexts.remove(player.getUniqueId());
|
||||
toolSidebars.remove(player.getUniqueId());
|
||||
updatePlayer(player);
|
||||
PlayerBoard playerBoard = boards.get(player);
|
||||
@@ -322,45 +287,6 @@ public class BoardSVC implements IrisService, BoardProvider {
|
||||
&& generator.getEngine() != null;
|
||||
}
|
||||
|
||||
static List<String> jigsawLines(JigsawStudioBoardContext context) {
|
||||
Objects.requireNonNull(context, "Jigsaw Studio board context");
|
||||
List<String> lines = new ArrayList<>(11);
|
||||
lines.add(SEPARATOR);
|
||||
lines.add("&dJigsaw Studio");
|
||||
lines.add("&bStructure&7: " + untrustedBoardValue(context.structureKey()));
|
||||
if (!context.insideWorkcell()) {
|
||||
lines.add("&bMode&7: " + context.modeDisplayName());
|
||||
lines.add(SEPARATOR);
|
||||
lines.add("&eWalk into a workcell");
|
||||
if (!context.controlHint().isEmpty()) {
|
||||
lines.add("&7" + untrustedBoardValue(context.controlHint()));
|
||||
}
|
||||
lines.add(SEPARATOR);
|
||||
return List.copyOf(lines);
|
||||
}
|
||||
|
||||
lines.add("&bWorkcell&7: " + untrustedBoardValue(context.workcellName()));
|
||||
if (!context.workcellRole().isEmpty() && !context.workcellRole().equals(context.workcellName())) {
|
||||
lines.add("&bRole&7: " + untrustedBoardValue(context.workcellRole()));
|
||||
}
|
||||
lines.add("&bVariant&7: " + untrustedBoardValue(
|
||||
context.variantName().isEmpty() ? "None" : context.variantName()));
|
||||
lines.add("&bState&7: " + context.state().displayName());
|
||||
lines.add(SEPARATOR);
|
||||
if (!context.controlHint().isEmpty()) {
|
||||
lines.add("&e" + untrustedBoardValue(context.controlHint()));
|
||||
}
|
||||
lines.add(SEPARATOR);
|
||||
return List.copyOf(lines);
|
||||
}
|
||||
|
||||
static boolean shouldRenderJigsaw(
|
||||
JigsawStudioBoardContext previous,
|
||||
JigsawStudioBoardContext next
|
||||
) {
|
||||
return !Objects.equals(previous, next);
|
||||
}
|
||||
|
||||
static String untrustedBoardValue(String value) {
|
||||
String normalized = value == null ? "" : value.replace('\n', ' ').replace('\r', ' ');
|
||||
return LEGACY_COLOR.matcher(normalized).replaceAll("")
|
||||
@@ -401,19 +327,10 @@ public class BoardSVC implements IrisService, BoardProvider {
|
||||
return sidebar.lines().stream().map(BoardSVC::untrustedBoardValue).toList();
|
||||
}
|
||||
|
||||
private JigsawStudioBoardContext currentJigsawContext(Player player) {
|
||||
JigsawStudioBoardContext context = jigsawContexts.get(player.getUniqueId());
|
||||
if (context == null || !context.worldId().equals(player.getWorld().getUID())) {
|
||||
return null;
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
||||
public class PlayerBoard {
|
||||
private final Player player;
|
||||
private final Board board;
|
||||
private volatile List<String> lines;
|
||||
private volatile JigsawStudioBoardContext jigsawContext;
|
||||
private volatile ToolSidebar toolSidebar;
|
||||
private volatile String title;
|
||||
private volatile BoardView view;
|
||||
@@ -424,7 +341,6 @@ public class BoardSVC implements IrisService, BoardProvider {
|
||||
this.player = player;
|
||||
this.board = new Board(player, settings);
|
||||
this.lines = List.of();
|
||||
this.jigsawContext = null;
|
||||
this.toolSidebar = null;
|
||||
this.title = "";
|
||||
this.view = BoardView.NONE;
|
||||
@@ -442,7 +358,6 @@ public class BoardSVC implements IrisService, BoardProvider {
|
||||
}
|
||||
boolean switched = view != BoardView.ORDINARY;
|
||||
view = BoardView.ORDINARY;
|
||||
jigsawContext = null;
|
||||
toolSidebar = null;
|
||||
if (switched) {
|
||||
updateOrdinary();
|
||||
@@ -463,24 +378,6 @@ public class BoardSVC implements IrisService, BoardProvider {
|
||||
return !cancelled && view == BoardView.ORDINARY;
|
||||
}
|
||||
|
||||
private void showJigsaw(JigsawStudioBoardContext context) {
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
if (!board.ownsScoreboardAssignment()) {
|
||||
yieldBoard(player, this);
|
||||
return;
|
||||
}
|
||||
if (view == BoardView.JIGSAW && !shouldRenderJigsaw(jigsawContext, context)) {
|
||||
return;
|
||||
}
|
||||
view = BoardView.JIGSAW;
|
||||
jigsawContext = context;
|
||||
toolSidebar = null;
|
||||
lines = jigsawLines(context);
|
||||
board.update();
|
||||
}
|
||||
|
||||
private void showTool(ToolSidebar sidebar) {
|
||||
if (cancelled) {
|
||||
return;
|
||||
@@ -494,7 +391,6 @@ public class BoardSVC implements IrisService, BoardProvider {
|
||||
}
|
||||
view = BoardView.TOOL;
|
||||
toolSidebar = sidebar;
|
||||
jigsawContext = null;
|
||||
title = untrustedBoardValue(sidebar.title());
|
||||
lines = toolLines(sidebar);
|
||||
board.update();
|
||||
@@ -533,11 +429,6 @@ public class BoardSVC implements IrisService, BoardProvider {
|
||||
showTool(sidebar);
|
||||
return;
|
||||
}
|
||||
JigsawStudioBoardContext context = currentJigsawContext(player);
|
||||
if (context != null) {
|
||||
showJigsaw(context);
|
||||
return;
|
||||
}
|
||||
if (!board.ownsScoreboardAssignment()) {
|
||||
yieldBoard(player, this);
|
||||
return;
|
||||
@@ -623,7 +514,6 @@ public class BoardSVC implements IrisService, BoardProvider {
|
||||
private enum BoardView {
|
||||
NONE,
|
||||
ORDINARY,
|
||||
JIGSAW,
|
||||
TOOL
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package art.arcane.iris.core.service;
|
||||
|
||||
import art.arcane.iris.engine.object.prefab.ObjectTurn;
|
||||
import com.volmit.block.BlockRegistry;
|
||||
import com.volmit.block.BlockState;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
/** The few block facts the studio needs, asked of api block states. */
|
||||
public final class JigsawStudioBlocks {
|
||||
public static final BlockState AIR = BlockState.parse("minecraft:air");
|
||||
public static final String JIGSAW_BLOCK = "minecraft:jigsaw";
|
||||
public static final String ORIENTATION_PROPERTY = "orientation";
|
||||
private static final String CHEST_BLOCK = "minecraft:chest";
|
||||
private static final String STRUCTURE_VOID_BLOCK = "minecraft:structure_void";
|
||||
private static final Set<String> AIR_BLOCKS = Set.of("minecraft:air", "minecraft:cave_air", "minecraft:void_air");
|
||||
|
||||
private JigsawStudioBlocks() {
|
||||
}
|
||||
|
||||
public static boolean isAir(BlockState state) {
|
||||
return AIR_BLOCKS.contains(state.material().toString());
|
||||
}
|
||||
|
||||
public static boolean isJigsaw(BlockState state) {
|
||||
return JIGSAW_BLOCK.equals(state.material().toString());
|
||||
}
|
||||
|
||||
public static boolean isChest(BlockState state) {
|
||||
return CHEST_BLOCK.equals(state.material().toString());
|
||||
}
|
||||
|
||||
public static boolean isStructureVoid(BlockState state) {
|
||||
return STRUCTURE_VOID_BLOCK.equals(state.material().toString());
|
||||
}
|
||||
|
||||
public static BlockState jigsawMarker(String orientation) {
|
||||
return BlockState.parse(JIGSAW_BLOCK + "[" + ORIENTATION_PROPERTY + "=" + orientation + "]");
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code state} turned like {@code rotation}; null when the block cannot face the way it is turned, which the
|
||||
* registry reports as air.
|
||||
*/
|
||||
public static BlockState rotated(BlockRegistry registry, BlockState state, ObjectTurn rotation) {
|
||||
if (!rotation.canRotate()) {
|
||||
return state;
|
||||
}
|
||||
BlockState turned = registry.rotate(state, rotation.blockTurn());
|
||||
boolean dropped = turned.equals(AIR) && !state.equals(AIR);
|
||||
return dropped ? null : turned;
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,8 @@ package art.arcane.iris.core.service;
|
||||
|
||||
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioMode;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
|
||||
@@ -16,6 +18,10 @@ public record JigsawStudioBoardContext(
|
||||
JigsawStudioBoardState state,
|
||||
String controlHint
|
||||
) {
|
||||
private static final String SIDEBAR_TITLE = "Iris";
|
||||
private static final String SEPARATOR = "-------------------";
|
||||
private static final int SIDEBAR_LINE_CAPACITY = 11;
|
||||
|
||||
public JigsawStudioBoardContext {
|
||||
worldId = Objects.requireNonNull(worldId, "Jigsaw Studio board world ID");
|
||||
requestId = Objects.requireNonNull(requestId, "Jigsaw Studio board request ID");
|
||||
@@ -35,6 +41,40 @@ public record JigsawStudioBoardContext(
|
||||
return !workcellName.isEmpty();
|
||||
}
|
||||
|
||||
public String sidebarTitle() {
|
||||
return SIDEBAR_TITLE;
|
||||
}
|
||||
|
||||
/** The sidebar lines for this context, top to bottom, as plain text. */
|
||||
public List<String> sidebarLines() {
|
||||
List<String> lines = new ArrayList<>(SIDEBAR_LINE_CAPACITY);
|
||||
lines.add(SEPARATOR);
|
||||
lines.add("Jigsaw Studio");
|
||||
lines.add("Structure: " + structureKey);
|
||||
if (!insideWorkcell()) {
|
||||
lines.add("Mode: " + modeDisplayName());
|
||||
lines.add(SEPARATOR);
|
||||
lines.add("Walk into a workcell");
|
||||
if (!controlHint.isEmpty()) {
|
||||
lines.add(controlHint);
|
||||
}
|
||||
lines.add(SEPARATOR);
|
||||
return List.copyOf(lines);
|
||||
}
|
||||
lines.add("Workcell: " + workcellName);
|
||||
if (!workcellRole.isEmpty() && !workcellRole.equals(workcellName)) {
|
||||
lines.add("Role: " + workcellRole);
|
||||
}
|
||||
lines.add("Variant: " + (variantName.isEmpty() ? "None" : variantName));
|
||||
lines.add("State: " + state.displayName());
|
||||
lines.add(SEPARATOR);
|
||||
if (!controlHint.isEmpty()) {
|
||||
lines.add(controlHint);
|
||||
}
|
||||
lines.add(SEPARATOR);
|
||||
return List.copyOf(lines);
|
||||
}
|
||||
|
||||
public String modeDisplayName() {
|
||||
return switch (mode) {
|
||||
case PLANAR_JIGSAW -> "Planar";
|
||||
|
||||
@@ -5,7 +5,6 @@ import art.arcane.iris.engine.object.value.IrisDirection;
|
||||
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConnector;
|
||||
import art.arcane.iris.engine.object.value.IrisPosition;
|
||||
import art.arcane.iris.engine.object.structure.jigsaw.JigsawJoint;
|
||||
import org.bukkit.block.Orientation;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
@@ -17,7 +16,7 @@ final class JigsawStudioMarkerParser {
|
||||
|
||||
static IrisJigsawConnector parse(
|
||||
Map<String, Object> nbt,
|
||||
Orientation orientation,
|
||||
String orientation,
|
||||
int x,
|
||||
int y,
|
||||
int z
|
||||
@@ -45,20 +44,23 @@ final class JigsawStudioMarkerParser {
|
||||
.setPlacementPriority(optionalInt(properties, "placement_priority"));
|
||||
}
|
||||
|
||||
static Directions directions(Orientation orientation) {
|
||||
return switch (Objects.requireNonNull(orientation, "Jigsaw orientation")) {
|
||||
case DOWN_EAST -> new Directions(IrisDirection.DOWN_NEGATIVE_Y, IrisDirection.EAST_POSITIVE_X);
|
||||
case DOWN_NORTH -> new Directions(IrisDirection.DOWN_NEGATIVE_Y, IrisDirection.NORTH_NEGATIVE_Z);
|
||||
case DOWN_SOUTH -> new Directions(IrisDirection.DOWN_NEGATIVE_Y, IrisDirection.SOUTH_POSITIVE_Z);
|
||||
case DOWN_WEST -> new Directions(IrisDirection.DOWN_NEGATIVE_Y, IrisDirection.WEST_NEGATIVE_X);
|
||||
case UP_EAST -> new Directions(IrisDirection.UP_POSITIVE_Y, IrisDirection.EAST_POSITIVE_X);
|
||||
case UP_NORTH -> new Directions(IrisDirection.UP_POSITIVE_Y, IrisDirection.NORTH_NEGATIVE_Z);
|
||||
case UP_SOUTH -> new Directions(IrisDirection.UP_POSITIVE_Y, IrisDirection.SOUTH_POSITIVE_Z);
|
||||
case UP_WEST -> new Directions(IrisDirection.UP_POSITIVE_Y, IrisDirection.WEST_NEGATIVE_X);
|
||||
case WEST_UP -> new Directions(IrisDirection.WEST_NEGATIVE_X, IrisDirection.UP_POSITIVE_Y);
|
||||
case EAST_UP -> new Directions(IrisDirection.EAST_POSITIVE_X, IrisDirection.UP_POSITIVE_Y);
|
||||
case NORTH_UP -> new Directions(IrisDirection.NORTH_NEGATIVE_Z, IrisDirection.UP_POSITIVE_Y);
|
||||
case SOUTH_UP -> new Directions(IrisDirection.SOUTH_POSITIVE_Z, IrisDirection.UP_POSITIVE_Y);
|
||||
/** The front and top a jigsaw block's {@code orientation} property names, such as {@code down_east}. */
|
||||
static Directions directions(String orientation) {
|
||||
String name = Objects.requireNonNull(orientation, "Jigsaw orientation").toLowerCase(Locale.ROOT);
|
||||
return switch (name) {
|
||||
case "down_east" -> new Directions(IrisDirection.DOWN_NEGATIVE_Y, IrisDirection.EAST_POSITIVE_X);
|
||||
case "down_north" -> new Directions(IrisDirection.DOWN_NEGATIVE_Y, IrisDirection.NORTH_NEGATIVE_Z);
|
||||
case "down_south" -> new Directions(IrisDirection.DOWN_NEGATIVE_Y, IrisDirection.SOUTH_POSITIVE_Z);
|
||||
case "down_west" -> new Directions(IrisDirection.DOWN_NEGATIVE_Y, IrisDirection.WEST_NEGATIVE_X);
|
||||
case "up_east" -> new Directions(IrisDirection.UP_POSITIVE_Y, IrisDirection.EAST_POSITIVE_X);
|
||||
case "up_north" -> new Directions(IrisDirection.UP_POSITIVE_Y, IrisDirection.NORTH_NEGATIVE_Z);
|
||||
case "up_south" -> new Directions(IrisDirection.UP_POSITIVE_Y, IrisDirection.SOUTH_POSITIVE_Z);
|
||||
case "up_west" -> new Directions(IrisDirection.UP_POSITIVE_Y, IrisDirection.WEST_NEGATIVE_X);
|
||||
case "west_up" -> new Directions(IrisDirection.WEST_NEGATIVE_X, IrisDirection.UP_POSITIVE_Y);
|
||||
case "east_up" -> new Directions(IrisDirection.EAST_POSITIVE_X, IrisDirection.UP_POSITIVE_Y);
|
||||
case "north_up" -> new Directions(IrisDirection.NORTH_NEGATIVE_Z, IrisDirection.UP_POSITIVE_Y);
|
||||
case "south_up" -> new Directions(IrisDirection.SOUTH_POSITIVE_Z, IrisDirection.UP_POSITIVE_Y);
|
||||
default -> throw new IllegalArgumentException("Unsupported jigsaw orientation '" + orientation + "'");
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,94 @@
|
||||
package art.arcane.iris.core.service;
|
||||
|
||||
import com.volmit.tooling.world.MenuButton;
|
||||
import com.volmit.tooling.world.MenuClick;
|
||||
import com.volmit.tooling.world.ToolItem;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/** One slot of a studio menu: an icon with a name and lore, and what each kind of click on it does. */
|
||||
final class JigsawStudioMenuElement {
|
||||
private final String id;
|
||||
private final List<String> lore = new ArrayList<>();
|
||||
private JigsawStudioMenuIcon icon = JigsawStudioMenuIcon.BARRIER;
|
||||
private String name = "";
|
||||
private boolean enchanted;
|
||||
private Consumer<JigsawStudioMenuElement> onLeftClick;
|
||||
private Consumer<JigsawStudioMenuElement> onRightClick;
|
||||
private Consumer<JigsawStudioMenuElement> onShiftLeftClick;
|
||||
private Consumer<JigsawStudioMenuElement> onShiftRightClick;
|
||||
private Consumer<JigsawStudioMenuElement> onMiddleClick;
|
||||
|
||||
JigsawStudioMenuElement(String id) {
|
||||
this.id = Objects.requireNonNull(id, "Jigsaw Studio menu element ID");
|
||||
}
|
||||
|
||||
String id() {
|
||||
return id;
|
||||
}
|
||||
|
||||
JigsawStudioMenuElement setIcon(JigsawStudioMenuIcon icon) {
|
||||
this.icon = Objects.requireNonNull(icon, "Jigsaw Studio menu icon");
|
||||
return this;
|
||||
}
|
||||
|
||||
JigsawStudioMenuElement setName(String name) {
|
||||
this.name = Objects.requireNonNull(name, "Jigsaw Studio menu name");
|
||||
return this;
|
||||
}
|
||||
|
||||
JigsawStudioMenuElement setEnchanted(boolean enchanted) {
|
||||
this.enchanted = enchanted;
|
||||
return this;
|
||||
}
|
||||
|
||||
JigsawStudioMenuElement addLore(String line) {
|
||||
lore.add(Objects.requireNonNull(line, "Jigsaw Studio menu lore"));
|
||||
return this;
|
||||
}
|
||||
|
||||
JigsawStudioMenuElement onLeftClick(Consumer<JigsawStudioMenuElement> action) {
|
||||
onLeftClick = action;
|
||||
return this;
|
||||
}
|
||||
|
||||
JigsawStudioMenuElement onRightClick(Consumer<JigsawStudioMenuElement> action) {
|
||||
onRightClick = action;
|
||||
return this;
|
||||
}
|
||||
|
||||
JigsawStudioMenuElement onShiftLeftClick(Consumer<JigsawStudioMenuElement> action) {
|
||||
onShiftLeftClick = action;
|
||||
return this;
|
||||
}
|
||||
|
||||
JigsawStudioMenuElement onShiftRightClick(Consumer<JigsawStudioMenuElement> action) {
|
||||
onShiftRightClick = action;
|
||||
return this;
|
||||
}
|
||||
|
||||
JigsawStudioMenuElement onMiddleClick(Consumer<JigsawStudioMenuElement> action) {
|
||||
onMiddleClick = action;
|
||||
return this;
|
||||
}
|
||||
|
||||
/** The api button for this element on {@code slot}. */
|
||||
MenuButton toButton(int slot) {
|
||||
ToolItem item = new ToolItem(icon.id(), name, List.copyOf(lore), enchanted, "");
|
||||
return new MenuButton(slot, item, this::click);
|
||||
}
|
||||
|
||||
private void click(MenuClick click) {
|
||||
Consumer<JigsawStudioMenuElement> action = click.middle()
|
||||
? onMiddleClick
|
||||
: click.shift()
|
||||
? click.right() ? onShiftRightClick : onShiftLeftClick
|
||||
: click.right() ? onRightClick : onLeftClick;
|
||||
if (action != null) {
|
||||
action.accept(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package art.arcane.iris.core.service;
|
||||
|
||||
import com.volmit.resource.ResourceId;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
/** The items the studio menus draw, named as the platform names them. */
|
||||
enum JigsawStudioMenuIcon {
|
||||
ARROW,
|
||||
BARRIER,
|
||||
BLUE_DYE,
|
||||
BOOK,
|
||||
CHEST,
|
||||
CLOCK,
|
||||
COMPARATOR,
|
||||
COPPER_INGOT,
|
||||
CRAFTING_TABLE,
|
||||
EMERALD,
|
||||
EMERALD_BLOCK,
|
||||
ENDER_EYE,
|
||||
GOLD_INGOT,
|
||||
GOLD_NUGGET,
|
||||
GRAY_DYE,
|
||||
GRAY_WOOL,
|
||||
GREEN_DYE,
|
||||
IRON_BARS,
|
||||
IRON_INGOT,
|
||||
JIGSAW,
|
||||
LAVA_BUCKET,
|
||||
LEVER,
|
||||
LIGHT_BLUE_DYE,
|
||||
LIGHT_GRAY_WOOL,
|
||||
LIME_DYE,
|
||||
LIME_WOOL,
|
||||
NAME_TAG,
|
||||
NETHER_STAR,
|
||||
ORANGE_WOOL,
|
||||
PAPER,
|
||||
PURPLE_DYE,
|
||||
RECOVERY_COMPASS,
|
||||
RED_DYE,
|
||||
REDSTONE,
|
||||
REDSTONE_TORCH,
|
||||
REPEATER,
|
||||
SCAFFOLDING,
|
||||
STICK,
|
||||
STRUCTURE_VOID,
|
||||
TARGET,
|
||||
TRIPWIRE_HOOK,
|
||||
YELLOW_DYE,
|
||||
YELLOW_WOOL;
|
||||
|
||||
private final ResourceId id = ResourceId.parse("minecraft:" + name().toLowerCase(Locale.ROOT));
|
||||
|
||||
ResourceId id() {
|
||||
return id;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package art.arcane.iris.core.service;
|
||||
|
||||
import com.volmit.tooling.world.MenuButton;
|
||||
import com.volmit.tooling.world.ToolMenu;
|
||||
import com.volmit.tooling.world.ToolPlayer;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.TreeMap;
|
||||
|
||||
/**
|
||||
* A studio menu the controller builds up element by element, the way it lays out a window: each element sits at a
|
||||
* column counted from the middle of the row (left of it negative) and a row from the top. While the window is open every
|
||||
* change is shown to the player, and a batch of changes is shown once.
|
||||
*
|
||||
* <p>Used on the viewer's thread only.
|
||||
*/
|
||||
final class JigsawStudioMenuWindow {
|
||||
private static final int ROW_WIDTH = ToolMenu.SLOTS_PER_ROW;
|
||||
private static final int MIDDLE_COLUMN = ROW_WIDTH / 2;
|
||||
|
||||
private final ToolPlayer viewer;
|
||||
private final Map<Integer, JigsawStudioMenuElement> elements = new TreeMap<>();
|
||||
private String title = "";
|
||||
private int viewportRows = ToolMenu.MAX_ROWS;
|
||||
private Runnable onClosed = () -> { };
|
||||
private int batchDepth;
|
||||
private boolean open;
|
||||
private long shownGeneration;
|
||||
|
||||
JigsawStudioMenuWindow(ToolPlayer viewer) {
|
||||
this.viewer = Objects.requireNonNull(viewer, "Jigsaw Studio menu viewer");
|
||||
}
|
||||
|
||||
ToolPlayer getViewer() {
|
||||
return viewer;
|
||||
}
|
||||
|
||||
JigsawStudioMenuWindow setViewportHeight(int rows) {
|
||||
viewportRows = Math.max(1, Math.min(ToolMenu.MAX_ROWS, rows));
|
||||
return this;
|
||||
}
|
||||
|
||||
JigsawStudioMenuWindow setTitle(String title) {
|
||||
this.title = Objects.requireNonNull(title, "Jigsaw Studio menu title");
|
||||
return this;
|
||||
}
|
||||
|
||||
JigsawStudioMenuWindow onClosed(Runnable onClosed) {
|
||||
this.onClosed = Objects.requireNonNull(onClosed, "Jigsaw Studio menu close handler");
|
||||
return this;
|
||||
}
|
||||
|
||||
JigsawStudioMenuWindow setElement(int position, int row, JigsawStudioMenuElement element) {
|
||||
elements.put(slotOf(position, row), element);
|
||||
showUnlessBatching();
|
||||
return this;
|
||||
}
|
||||
|
||||
JigsawStudioMenuWindow clearElements() {
|
||||
elements.clear();
|
||||
showUnlessBatching();
|
||||
return this;
|
||||
}
|
||||
|
||||
JigsawStudioMenuWindow batch(Runnable changes) {
|
||||
batchDepth++;
|
||||
try {
|
||||
changes.run();
|
||||
} finally {
|
||||
batchDepth--;
|
||||
}
|
||||
showUnlessBatching();
|
||||
return this;
|
||||
}
|
||||
|
||||
JigsawStudioMenuWindow open() {
|
||||
open = true;
|
||||
show();
|
||||
return this;
|
||||
}
|
||||
|
||||
JigsawStudioMenuWindow close() {
|
||||
if (!open) {
|
||||
return this;
|
||||
}
|
||||
open = false;
|
||||
shownGeneration++;
|
||||
viewer.closeMenu();
|
||||
onClosed.run();
|
||||
return this;
|
||||
}
|
||||
|
||||
private static int slotOf(int position, int row) {
|
||||
int column = Math.max(-MIDDLE_COLUMN, Math.min(MIDDLE_COLUMN, position)) + MIDDLE_COLUMN;
|
||||
return row * ROW_WIDTH + column;
|
||||
}
|
||||
|
||||
private void showUnlessBatching() {
|
||||
if (open && batchDepth == 0) {
|
||||
show();
|
||||
}
|
||||
}
|
||||
|
||||
private void show() {
|
||||
long generation = ++shownGeneration;
|
||||
List<MenuButton> buttons = new ArrayList<>(elements.size());
|
||||
for (Map.Entry<Integer, JigsawStudioMenuElement> entry : elements.entrySet()) {
|
||||
if (entry.getKey() >= 0 && entry.getKey() < viewportRows * ROW_WIDTH) {
|
||||
buttons.add(entry.getValue().toButton(entry.getKey()));
|
||||
}
|
||||
}
|
||||
viewer.openMenu(new ToolMenu(title, viewportRows, buttons, () -> closedByHost(generation)));
|
||||
}
|
||||
|
||||
private void closedByHost(long generation) {
|
||||
if (generation != shownGeneration || !open) {
|
||||
return;
|
||||
}
|
||||
open = false;
|
||||
onClosed.run();
|
||||
}
|
||||
}
|
||||
@@ -2,19 +2,13 @@ package art.arcane.iris.core.service;
|
||||
|
||||
import art.arcane.iris.engine.framework.PlacedStructurePiece;
|
||||
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConnector;
|
||||
import art.arcane.iris.engine.object.prefab.IrisObject;
|
||||
import art.arcane.iris.engine.object.prefab.ObjectTurn;
|
||||
import art.arcane.iris.engine.object.prefab.BlockStateRotation;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import art.arcane.iris.spi.PlatformBlockState;
|
||||
import art.arcane.iris.util.common.data.B;
|
||||
import art.arcane.volmlib.util.math.IrisBlockVector;
|
||||
import art.arcane.iris.util.common.scheduling.J;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.block.Block;
|
||||
import org.bukkit.block.data.BlockData;
|
||||
import com.volmit.ModuleLog;
|
||||
import com.volmit.block.BlockRegistry;
|
||||
import com.volmit.block.BlockState;
|
||||
import com.volmit.object.ObjectBlock;
|
||||
import com.volmit.tooling.world.ToolWorld;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
@@ -24,6 +18,7 @@ import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
@@ -34,10 +29,17 @@ public final class JigsawStudioPreviewRenderer {
|
||||
private static final int MAX_BLOCKS = 250_000;
|
||||
private static final String AIR = "minecraft:air";
|
||||
private static final String STRUCTURE_VOID = "minecraft:structure_void";
|
||||
private static final BlockState AIR_STATE = BlockState.parse(AIR);
|
||||
private static final int CHUNK_SHIFT = 4;
|
||||
|
||||
private final Map<UUID, RenderState> requests = new HashMap<>();
|
||||
private final ModuleLog log;
|
||||
|
||||
public static PreviewPlan plan(List<PlacedStructurePiece> pieces) throws IOException {
|
||||
public JigsawStudioPreviewRenderer(ModuleLog log) {
|
||||
this.log = Objects.requireNonNull(log, "Jigsaw Studio preview log");
|
||||
}
|
||||
|
||||
public static PreviewPlan plan(List<PlacedStructurePiece> pieces, BlockRegistry registry) throws IOException {
|
||||
List<PlacedStructurePiece> source = List.copyOf(Objects.requireNonNull(
|
||||
pieces,
|
||||
"Jigsaw Studio preview pieces"));
|
||||
@@ -62,8 +64,8 @@ public final class JigsawStudioPreviewRenderer {
|
||||
maximumX = Math.max(maximumX, piece.getMaxX());
|
||||
maximumY = Math.max(maximumY, piece.getMaxY());
|
||||
maximumZ = Math.max(maximumZ, piece.getMaxZ());
|
||||
appendObject(blocks, piece);
|
||||
appendFinalStates(blocks, piece);
|
||||
appendObject(blocks, piece, registry);
|
||||
appendFinalStates(blocks, piece, registry);
|
||||
if (blocks.size() > MAX_BLOCKS) {
|
||||
throw new IOException("The seed-1337 preview exceeds the Studio render limit of "
|
||||
+ MAX_BLOCKS + " explicit blocks");
|
||||
@@ -75,13 +77,13 @@ public final class JigsawStudioPreviewRenderer {
|
||||
}
|
||||
|
||||
public void render(
|
||||
World world,
|
||||
ToolWorld world,
|
||||
UUID requestId,
|
||||
long generation,
|
||||
PreviewPlan plan,
|
||||
Consumer<RenderResult> completion
|
||||
) {
|
||||
World activeWorld = Objects.requireNonNull(world, "Jigsaw Studio preview world");
|
||||
ToolWorld activeWorld = Objects.requireNonNull(world, "Jigsaw Studio preview world");
|
||||
UUID activeRequestId = Objects.requireNonNull(requestId, "Jigsaw Studio preview request ID");
|
||||
PreviewPlan activePlan = Objects.requireNonNull(plan, "Jigsaw Studio preview plan");
|
||||
Consumer<RenderResult> callback = Objects.requireNonNull(completion, "Jigsaw Studio preview callback");
|
||||
@@ -90,10 +92,10 @@ public final class JigsawStudioPreviewRenderer {
|
||||
Map<Long, List<BlockUpdate>> updates;
|
||||
synchronized (this) {
|
||||
RenderState old = requests.get(activeRequestId);
|
||||
previous = old == null || !old.worldId().equals(activeWorld.getUID())
|
||||
previous = old == null || old.world() != activeWorld
|
||||
? Map.of()
|
||||
: old.blocks();
|
||||
uncertain = old == null || !old.worldId().equals(activeWorld.getUID())
|
||||
uncertain = old == null || old.world() != activeWorld
|
||||
? Set.of()
|
||||
: Set.copyOf(old.pending());
|
||||
updates = updates(previous, activePlan.blocks(), uncertain);
|
||||
@@ -104,7 +106,7 @@ public final class JigsawStudioPreviewRenderer {
|
||||
}
|
||||
}
|
||||
requests.put(activeRequestId, new RenderState(
|
||||
activeWorld.getUID(), generation, activePlan.blocks(), activePlan.bounds(), pending));
|
||||
activeWorld, generation, activePlan.blocks(), activePlan.bounds(), pending));
|
||||
}
|
||||
if (updates.isEmpty()) {
|
||||
callback.accept(new RenderResult(true, 0, ""));
|
||||
@@ -115,7 +117,8 @@ public final class JigsawStudioPreviewRenderer {
|
||||
for (Map.Entry<Long, List<BlockUpdate>> chunk : updates.entrySet()) {
|
||||
int chunkX = chunkX(chunk.getKey());
|
||||
int chunkZ = chunkZ(chunk.getKey());
|
||||
boolean scheduled = J.runRegion(
|
||||
JigsawStudioThreads.onRegion(
|
||||
log,
|
||||
activeWorld,
|
||||
chunkX,
|
||||
chunkZ,
|
||||
@@ -126,16 +129,16 @@ public final class JigsawStudioPreviewRenderer {
|
||||
chunk.getValue(),
|
||||
remaining,
|
||||
failed,
|
||||
callback));
|
||||
if (!scheduled) {
|
||||
failed.set(true);
|
||||
if (remaining.decrementAndGet() == 0) {
|
||||
callback.accept(new RenderResult(
|
||||
false,
|
||||
activePlan.blocks().size(),
|
||||
"One or more preview chunks could not be scheduled"));
|
||||
}
|
||||
}
|
||||
callback),
|
||||
() -> {
|
||||
failed.set(true);
|
||||
if (remaining.decrementAndGet() == 0) {
|
||||
callback.accept(new RenderResult(
|
||||
false,
|
||||
activePlan.blocks().size(),
|
||||
"One or more preview chunks could not be scheduled"));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -158,10 +161,7 @@ public final class JigsawStudioPreviewRenderer {
|
||||
removed = requests.remove(requestId);
|
||||
}
|
||||
if (removed != null) {
|
||||
World world = Bukkit.getWorld(removed.worldId());
|
||||
if (world != null) {
|
||||
clear(world, removalPositions(removed));
|
||||
}
|
||||
clear(removed.world(), removalPositions(removed));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -181,38 +181,35 @@ public final class JigsawStudioPreviewRenderer {
|
||||
requests.clear();
|
||||
}
|
||||
for (RenderState state : removed.values()) {
|
||||
World world = Bukkit.getWorld(state.worldId());
|
||||
if (world != null) {
|
||||
clear(world, removalPositions(state));
|
||||
}
|
||||
clear(state.world(), removalPositions(state));
|
||||
}
|
||||
}
|
||||
|
||||
private static void appendObject(
|
||||
Map<BlockPosition, String> blocks,
|
||||
PlacedStructurePiece piece
|
||||
PlacedStructurePiece piece,
|
||||
BlockRegistry registry
|
||||
) throws IOException {
|
||||
IrisObject object = piece.getObject();
|
||||
ObjectTurn rotation = piece.getRotation();
|
||||
for (Map.Entry<IrisBlockVector, PlatformBlockState> entry : object.getBlocks()) {
|
||||
IrisBlockVector rotated = rotation.rotate(entry.getKey());
|
||||
PlatformBlockState state = BlockStateRotation.rotate(rotation, entry.getValue());
|
||||
for (ObjectBlock block : piece.getObject().geometry().blocks()) {
|
||||
IrisBlockVector rotated = rotation.rotate(new IrisBlockVector(
|
||||
block.position().x(), block.position().y(), block.position().z()));
|
||||
putState(
|
||||
blocks,
|
||||
new BlockPosition(
|
||||
piece.getX() + rotated.getBlockX(),
|
||||
piece.getY() + rotated.getBlockY(),
|
||||
piece.getZ() + rotated.getBlockZ()),
|
||||
state,
|
||||
JigsawStudioBlocks.rotated(registry, block.state(), rotation),
|
||||
"object block");
|
||||
}
|
||||
}
|
||||
|
||||
private static void appendFinalStates(
|
||||
Map<BlockPosition, String> blocks,
|
||||
PlacedStructurePiece piece
|
||||
PlacedStructurePiece piece,
|
||||
BlockRegistry registry
|
||||
) throws IOException {
|
||||
IrisObject object = piece.getObject();
|
||||
ObjectTurn rotation = piece.getRotation();
|
||||
if (piece.getPiece().getConnectors() == null) {
|
||||
return;
|
||||
@@ -222,19 +219,18 @@ public final class JigsawStudioPreviewRenderer {
|
||||
throw new IOException("Jigsaw Studio preview contains an incomplete connector");
|
||||
}
|
||||
IrisBlockVector signed = new IrisBlockVector(
|
||||
connector.getPosition().getX() - object.getCenter().getBlockX(),
|
||||
connector.getPosition().getY() - object.getCenter().getBlockY(),
|
||||
connector.getPosition().getZ() - object.getCenter().getBlockZ());
|
||||
connector.getPosition().getX() - piece.getObject().center().x(),
|
||||
connector.getPosition().getY() - piece.getObject().center().y(),
|
||||
connector.getPosition().getZ() - piece.getObject().center().z());
|
||||
IrisBlockVector rotated = rotation.rotate(signed);
|
||||
PlatformBlockState source = B.getStateOrNull(connector.getFinalState(), false);
|
||||
PlatformBlockState state = source == null ? null : BlockStateRotation.rotate(rotation, source);
|
||||
BlockState source = registry.find(connector.getFinalState()).orElse(null);
|
||||
putState(
|
||||
blocks,
|
||||
new BlockPosition(
|
||||
piece.getX() + rotated.getBlockX(),
|
||||
piece.getY() + rotated.getBlockY(),
|
||||
piece.getZ() + rotated.getBlockZ()),
|
||||
state,
|
||||
source == null ? null : JigsawStudioBlocks.rotated(registry, source, rotation),
|
||||
"connector final state");
|
||||
}
|
||||
}
|
||||
@@ -242,7 +238,7 @@ public final class JigsawStudioPreviewRenderer {
|
||||
private static void putState(
|
||||
Map<BlockPosition, String> blocks,
|
||||
BlockPosition position,
|
||||
PlatformBlockState state,
|
||||
BlockState state,
|
||||
String source
|
||||
) throws IOException {
|
||||
if (state == null || state.key() == null || state.key().isBlank()) {
|
||||
@@ -257,7 +253,7 @@ public final class JigsawStudioPreviewRenderer {
|
||||
}
|
||||
|
||||
private void applyChunk(
|
||||
World world,
|
||||
ToolWorld world,
|
||||
UUID requestId,
|
||||
long generation,
|
||||
List<BlockUpdate> updates,
|
||||
@@ -268,24 +264,25 @@ public final class JigsawStudioPreviewRenderer {
|
||||
int changed = 0;
|
||||
List<BlockPosition> applied = new ArrayList<>(updates.size());
|
||||
try {
|
||||
if (!isCurrent(world.getUID(), requestId, generation)) {
|
||||
if (!isCurrent(world, requestId, generation)) {
|
||||
return;
|
||||
}
|
||||
for (BlockUpdate update : updates) {
|
||||
Block block = world.getBlockAt(update.position().x(), update.position().y(), update.position().z());
|
||||
BlockData data = Bukkit.createBlockData(update.stateKey());
|
||||
block.setBlockData(data, false);
|
||||
world.setBlock(
|
||||
new com.volmit.geometry.BlockPosition(update.position().x(), update.position().y(), update.position().z()),
|
||||
BlockState.parse(update.stateKey()),
|
||||
Optional.empty());
|
||||
applied.add(update.position());
|
||||
changed++;
|
||||
}
|
||||
} catch (RuntimeException exception) {
|
||||
failed.set(true);
|
||||
IrisLogging.reportError(exception);
|
||||
log.error("The Jigsaw Studio preview could not be rendered.", exception);
|
||||
} finally {
|
||||
synchronized (this) {
|
||||
RenderState active = requests.get(requestId);
|
||||
if (active != null
|
||||
&& active.worldId().equals(world.getUID())
|
||||
&& active.world() == world
|
||||
&& active.generation() == generation) {
|
||||
active.pending().removeAll(applied);
|
||||
}
|
||||
@@ -298,7 +295,7 @@ public final class JigsawStudioPreviewRenderer {
|
||||
pendingEmpty = state != null && state.pending().isEmpty();
|
||||
}
|
||||
boolean current = state != null
|
||||
&& state.worldId().equals(world.getUID())
|
||||
&& state.world() == world
|
||||
&& state.generation() == generation;
|
||||
completion.accept(new RenderResult(
|
||||
current && pendingEmpty && !failed.get(),
|
||||
@@ -310,9 +307,9 @@ public final class JigsawStudioPreviewRenderer {
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized boolean isCurrent(UUID worldId, UUID requestId, long generation) {
|
||||
private synchronized boolean isCurrent(ToolWorld world, UUID requestId, long generation) {
|
||||
RenderState state = requests.get(requestId);
|
||||
return state != null && state.worldId().equals(worldId) && state.generation() == generation;
|
||||
return state != null && state.world() == world && state.generation() == generation;
|
||||
}
|
||||
|
||||
private static Map<Long, List<BlockUpdate>> updates(
|
||||
@@ -346,23 +343,23 @@ public final class JigsawStudioPreviewRenderer {
|
||||
|| !next.getOrDefault(position, AIR).equals(previous.get(position));
|
||||
}
|
||||
|
||||
private static void clear(World world, Set<BlockPosition> positions) {
|
||||
private void clear(ToolWorld world, Set<BlockPosition> positions) {
|
||||
Map<Long, List<BlockUpdate>> updates = new HashMap<>();
|
||||
for (BlockPosition position : positions) {
|
||||
updates.computeIfAbsent(
|
||||
chunkKey(position.x() >> 4, position.z() >> 4),
|
||||
chunkKey(position.x() >> CHUNK_SHIFT, position.z() >> CHUNK_SHIFT),
|
||||
ignored -> new ArrayList<>()).add(new BlockUpdate(position, AIR));
|
||||
}
|
||||
for (Map.Entry<Long, List<BlockUpdate>> chunk : updates.entrySet()) {
|
||||
J.runRegion(world, chunkX(chunk.getKey()), chunkZ(chunk.getKey()), () -> {
|
||||
JigsawStudioThreads.onRegion(log, world, chunkX(chunk.getKey()), chunkZ(chunk.getKey()), () -> {
|
||||
for (BlockUpdate update : chunk.getValue()) {
|
||||
world.getBlockAt(
|
||||
update.position().x(),
|
||||
update.position().y(),
|
||||
update.position().z())
|
||||
.setType(Material.AIR, false);
|
||||
world.setBlock(
|
||||
new com.volmit.geometry.BlockPosition(
|
||||
update.position().x(), update.position().y(), update.position().z()),
|
||||
AIR_STATE,
|
||||
Optional.empty());
|
||||
}
|
||||
});
|
||||
}, () -> { });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -437,14 +434,14 @@ public final class JigsawStudioPreviewRenderer {
|
||||
}
|
||||
|
||||
private record RenderState(
|
||||
UUID worldId,
|
||||
ToolWorld world,
|
||||
long generation,
|
||||
Map<BlockPosition, String> blocks,
|
||||
PreviewBounds bounds,
|
||||
Set<BlockPosition> pending
|
||||
) {
|
||||
private RenderState {
|
||||
Objects.requireNonNull(worldId, "Jigsaw Studio preview world ID");
|
||||
Objects.requireNonNull(world, "Jigsaw Studio preview world");
|
||||
blocks = Map.copyOf(Objects.requireNonNull(blocks, "Jigsaw Studio preview state blocks"));
|
||||
bounds = Objects.requireNonNull(bounds, "Jigsaw Studio preview state bounds");
|
||||
pending = Objects.requireNonNull(pending, "Jigsaw Studio preview pending blocks");
|
||||
|
||||
@@ -0,0 +1,365 @@
|
||||
package art.arcane.iris.core.service;
|
||||
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCellDimensions;
|
||||
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCompatibilityTarget;
|
||||
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioLayout;
|
||||
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioMode;
|
||||
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioSession;
|
||||
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioVariantCatalog;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
/**
|
||||
* Which Jigsaw Studio requests are active for each pack, which one is being opened, and the staged replacement of an
|
||||
* active one. One registry belongs to one studio service; it holds no platform state.
|
||||
*/
|
||||
public final class JigsawStudioRegistry {
|
||||
private final Map<String, ActiveRequest> active = new ConcurrentHashMap<>();
|
||||
private final AtomicReference<UUID> openingOwner = new AtomicReference<>();
|
||||
private final AtomicReference<StagedState> staged = new AtomicReference<>();
|
||||
|
||||
public JigsawStudioRequest activate(
|
||||
String packKey,
|
||||
String structureKey,
|
||||
JigsawStudioMode mode,
|
||||
JigsawStudioCompatibilityTarget compatibilityTarget,
|
||||
JigsawStudioCellDimensions cellDimensions,
|
||||
IrisData source
|
||||
) {
|
||||
JigsawStudioLayout layout = JigsawStudioLayout.create(
|
||||
mode,
|
||||
cellDimensions,
|
||||
JigsawStudioVariantCatalog.empty());
|
||||
return activate(
|
||||
packKey,
|
||||
structureKey,
|
||||
mode,
|
||||
compatibilityTarget,
|
||||
cellDimensions,
|
||||
source,
|
||||
layout,
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
public JigsawStudioRequest activate(
|
||||
String packKey,
|
||||
String structureKey,
|
||||
JigsawStudioMode mode,
|
||||
JigsawStudioCompatibilityTarget compatibilityTarget,
|
||||
JigsawStudioCellDimensions cellDimensions,
|
||||
IrisData source,
|
||||
JigsawStudioLayout initialLayout
|
||||
) {
|
||||
return activate(
|
||||
packKey,
|
||||
structureKey,
|
||||
mode,
|
||||
compatibilityTarget,
|
||||
cellDimensions,
|
||||
source,
|
||||
initialLayout,
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
public synchronized JigsawStudioRequest activate(
|
||||
String packKey,
|
||||
String structureKey,
|
||||
JigsawStudioMode mode,
|
||||
JigsawStudioCompatibilityTarget compatibilityTarget,
|
||||
JigsawStudioCellDimensions cellDimensions,
|
||||
IrisData source,
|
||||
JigsawStudioLayout initialLayout,
|
||||
UUID ownerId
|
||||
) {
|
||||
if (staged.get() != null) {
|
||||
throw new IllegalStateException("A Jigsaw Studio replacement is already staged");
|
||||
}
|
||||
if (ownerId != null && !ownerId.equals(openingOwner.get())) {
|
||||
throw new IllegalStateException("Jigsaw Studio activation does not own the active opening lease");
|
||||
}
|
||||
UUID activeOwnerId = activeOwnerId();
|
||||
if (ownerId != null && activeOwnerId != null && !ownerId.equals(activeOwnerId)) {
|
||||
throw new IllegalStateException("Jigsaw Studio is owned by another player session");
|
||||
}
|
||||
ActiveRequest activeRequest = createActiveRequest(
|
||||
packKey,
|
||||
structureKey,
|
||||
mode,
|
||||
compatibilityTarget,
|
||||
cellDimensions,
|
||||
source,
|
||||
initialLayout,
|
||||
ownerId);
|
||||
active.put(normalize(packKey), activeRequest);
|
||||
return activeRequest.request();
|
||||
}
|
||||
|
||||
public synchronized StagedActivation stage(
|
||||
String packKey,
|
||||
String structureKey,
|
||||
JigsawStudioMode mode,
|
||||
JigsawStudioCompatibilityTarget compatibilityTarget,
|
||||
JigsawStudioCellDimensions cellDimensions,
|
||||
IrisData source,
|
||||
JigsawStudioLayout initialLayout,
|
||||
UUID ownerId,
|
||||
UUID preservedRequestId
|
||||
) {
|
||||
UUID opening = openingOwner.get();
|
||||
UUID activeOwner = activeOwnerId();
|
||||
UUID requestedOwner = Objects.requireNonNull(ownerId, "Jigsaw Studio staged owner ID");
|
||||
if (!requestedOwner.equals(opening)) {
|
||||
throw new IllegalStateException("Jigsaw Studio staging does not own the active opening lease");
|
||||
}
|
||||
if (activeOwner != null && !requestedOwner.equals(activeOwner)) {
|
||||
throw new IllegalStateException("Jigsaw Studio is owned by another player session");
|
||||
}
|
||||
if (staged.get() != null) {
|
||||
throw new IllegalStateException("A Jigsaw Studio replacement is already staged");
|
||||
}
|
||||
ActiveRequest preserved = preservedRequestId == null ? null : active(preservedRequestId);
|
||||
if (preservedRequestId != null && preserved == null) {
|
||||
throw new IllegalStateException("The Jigsaw Studio being replaced is no longer active");
|
||||
}
|
||||
if (activeOwner != null && preserved == null) {
|
||||
throw new IllegalStateException("The active Jigsaw Studio must be preserved during replacement");
|
||||
}
|
||||
if (preserved != null && preserved.request().ownerId() != null
|
||||
&& !requestedOwner.equals(preserved.request().ownerId())) {
|
||||
throw new IllegalStateException("The Jigsaw Studio being replaced belongs to another player session");
|
||||
}
|
||||
ActiveRequest candidate = createActiveRequest(
|
||||
packKey,
|
||||
structureKey,
|
||||
mode,
|
||||
compatibilityTarget,
|
||||
cellDimensions,
|
||||
source,
|
||||
initialLayout,
|
||||
requestedOwner);
|
||||
StagedActivation activation = new StagedActivation(
|
||||
UUID.randomUUID(), candidate.request(), candidate.session());
|
||||
staged.set(new StagedState(activation, candidate, preserved, false));
|
||||
return activation;
|
||||
}
|
||||
|
||||
public synchronized boolean beginStagedGeneration(StagedActivation expected) {
|
||||
StagedState state = stagedState(expected);
|
||||
if (state == null || state.generationVisible()) {
|
||||
return false;
|
||||
}
|
||||
staged.set(new StagedState(state.staged(), state.candidate(), state.preserved(), true));
|
||||
return true;
|
||||
}
|
||||
|
||||
public synchronized boolean commit(StagedActivation expected) {
|
||||
StagedState state = stagedState(expected);
|
||||
if (state == null || !state.generationVisible()) {
|
||||
return false;
|
||||
}
|
||||
if (state.preserved() != null) {
|
||||
active.remove(normalize(state.preserved().request().packKey()), state.preserved());
|
||||
}
|
||||
active.put(normalize(state.candidate().request().packKey()), state.candidate());
|
||||
staged.set(null);
|
||||
return true;
|
||||
}
|
||||
|
||||
public synchronized boolean rollback(StagedActivation expected) {
|
||||
StagedState state = stagedState(expected);
|
||||
if (state == null) {
|
||||
return false;
|
||||
}
|
||||
staged.set(null);
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean tryBeginOpen(UUID ownerId) {
|
||||
UUID requestedOwner = Objects.requireNonNull(ownerId, "Jigsaw Studio opening owner ID");
|
||||
UUID activeOwnerId = activeOwnerId();
|
||||
if (activeOwnerId != null && !requestedOwner.equals(activeOwnerId)) {
|
||||
return false;
|
||||
}
|
||||
return openingOwner.compareAndSet(null, requestedOwner);
|
||||
}
|
||||
|
||||
public void finishOpen(UUID ownerId) {
|
||||
if (ownerId != null) {
|
||||
openingOwner.compareAndSet(ownerId, null);
|
||||
}
|
||||
}
|
||||
|
||||
public UUID openingOwnerId() {
|
||||
return openingOwner.get();
|
||||
}
|
||||
|
||||
public UUID activeOwnerId() {
|
||||
for (ActiveRequest activeRequest : active.values()) {
|
||||
UUID ownerId = activeRequest.request().ownerId();
|
||||
if (ownerId != null) {
|
||||
return ownerId;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public void deactivate(String packKey) {
|
||||
if (packKey != null) {
|
||||
active.remove(normalize(packKey));
|
||||
StagedState state = staged.get();
|
||||
if (state != null && (normalize(state.candidate().request().packKey()).equals(normalize(packKey))
|
||||
|| state.preserved() != null && normalize(state.preserved().request().packKey())
|
||||
.equals(normalize(packKey)))) {
|
||||
staged.compareAndSet(state, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public boolean deactivate(String packKey, UUID requestId) {
|
||||
if (packKey == null || requestId == null) {
|
||||
return false;
|
||||
}
|
||||
StagedState stagedState = staged.get();
|
||||
if (stagedState != null && stagedState.preserved() != null
|
||||
&& requestId.equals(stagedState.preserved().request().requestId())
|
||||
&& normalize(packKey).equals(normalize(stagedState.preserved().request().packKey()))) {
|
||||
return false;
|
||||
}
|
||||
AtomicBoolean removed = new AtomicBoolean(false);
|
||||
active.computeIfPresent(normalize(packKey), (key, activeRequest) -> {
|
||||
if (!requestId.equals(activeRequest.request().requestId())) {
|
||||
return activeRequest;
|
||||
}
|
||||
removed.set(true);
|
||||
return null;
|
||||
});
|
||||
return removed.get();
|
||||
}
|
||||
|
||||
public boolean isActive(String packKey) {
|
||||
return getRequest(packKey) != null;
|
||||
}
|
||||
|
||||
public JigsawStudioRequest getRequest(String packKey) {
|
||||
ActiveRequest activeRequest = active(packKey);
|
||||
return activeRequest == null ? null : activeRequest.request();
|
||||
}
|
||||
|
||||
public JigsawStudioSession getSession(String packKey) {
|
||||
ActiveRequest activeRequest = active(packKey);
|
||||
return activeRequest == null ? null : activeRequest.session();
|
||||
}
|
||||
|
||||
public JigsawStudioLayout getLayout(String packKey) {
|
||||
JigsawStudioSession session = getSession(packKey);
|
||||
return session == null ? null : session.layout();
|
||||
}
|
||||
|
||||
public JigsawStudioRequest getRequest(UUID requestId) {
|
||||
ActiveRequest activeRequest = active(requestId);
|
||||
return activeRequest == null ? null : activeRequest.request();
|
||||
}
|
||||
|
||||
public JigsawStudioSession getSession(UUID requestId) {
|
||||
ActiveRequest activeRequest = active(requestId);
|
||||
return activeRequest == null ? null : activeRequest.session();
|
||||
}
|
||||
|
||||
private ActiveRequest active(String packKey) {
|
||||
if (packKey == null) {
|
||||
return null;
|
||||
}
|
||||
return active.get(normalize(packKey));
|
||||
}
|
||||
|
||||
private ActiveRequest active(UUID requestId) {
|
||||
if (requestId == null) {
|
||||
return null;
|
||||
}
|
||||
for (ActiveRequest activeRequest : active.values()) {
|
||||
if (requestId.equals(activeRequest.request().requestId())) {
|
||||
return activeRequest;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static ActiveRequest createActiveRequest(
|
||||
String packKey,
|
||||
String structureKey,
|
||||
JigsawStudioMode mode,
|
||||
JigsawStudioCompatibilityTarget compatibilityTarget,
|
||||
JigsawStudioCellDimensions cellDimensions,
|
||||
IrisData source,
|
||||
JigsawStudioLayout initialLayout,
|
||||
UUID ownerId
|
||||
) {
|
||||
JigsawStudioRequest request = new JigsawStudioRequest(
|
||||
UUID.randomUUID(),
|
||||
packKey,
|
||||
structureKey,
|
||||
mode,
|
||||
compatibilityTarget,
|
||||
cellDimensions,
|
||||
source,
|
||||
ownerId);
|
||||
JigsawStudioLayout layout = Objects.requireNonNull(initialLayout, "Initial Jigsaw Studio layout");
|
||||
if (layout.mode() != mode) {
|
||||
throw new IllegalArgumentException("Initial Jigsaw Studio layout mode does not match the request");
|
||||
}
|
||||
if (!layout.cellDimensions().equals(cellDimensions)) {
|
||||
throw new IllegalArgumentException("Initial Jigsaw Studio layout cell dimensions do not match the request");
|
||||
}
|
||||
JigsawStudioSession session = new JigsawStudioSession(
|
||||
request.requestId(),
|
||||
request.packKey(),
|
||||
request.structureKey(),
|
||||
layout);
|
||||
return new ActiveRequest(request, session);
|
||||
}
|
||||
|
||||
private StagedState stagedState(StagedActivation expected) {
|
||||
StagedActivation activation = Objects.requireNonNull(expected, "Staged Jigsaw Studio activation");
|
||||
StagedState state = staged.get();
|
||||
return state != null && state.staged().stageId().equals(activation.stageId()) ? state : null;
|
||||
}
|
||||
|
||||
private static String normalize(String key) {
|
||||
return key.trim().toLowerCase(Locale.ROOT);
|
||||
}
|
||||
|
||||
private record ActiveRequest(JigsawStudioRequest request, JigsawStudioSession session) {
|
||||
}
|
||||
|
||||
private record StagedState(
|
||||
StagedActivation staged,
|
||||
ActiveRequest candidate,
|
||||
ActiveRequest preserved,
|
||||
boolean generationVisible
|
||||
) {
|
||||
}
|
||||
|
||||
public record StagedActivation(
|
||||
UUID stageId,
|
||||
JigsawStudioRequest request,
|
||||
JigsawStudioSession session
|
||||
) {
|
||||
public StagedActivation {
|
||||
Objects.requireNonNull(stageId, "Jigsaw Studio stage ID");
|
||||
Objects.requireNonNull(request, "Jigsaw Studio staged request");
|
||||
Objects.requireNonNull(session, "Jigsaw Studio staged session");
|
||||
if (!request.requestId().equals(session.sessionId())) {
|
||||
throw new IllegalArgumentException("Staged Jigsaw Studio request and session IDs do not match");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package art.arcane.iris.core.service;
|
||||
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCellDimensions;
|
||||
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCompatibilityTarget;
|
||||
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioMode;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
|
||||
/** What one open Jigsaw Studio was asked to edit, and who owns it. */
|
||||
public record JigsawStudioRequest(
|
||||
UUID requestId,
|
||||
String packKey,
|
||||
String structureKey,
|
||||
JigsawStudioMode mode,
|
||||
JigsawStudioCompatibilityTarget compatibilityTarget,
|
||||
JigsawStudioCellDimensions cellDimensions,
|
||||
IrisData source,
|
||||
UUID ownerId
|
||||
) {
|
||||
public JigsawStudioRequest {
|
||||
requestId = Objects.requireNonNull(requestId, "Jigsaw Studio request ID");
|
||||
packKey = requireKey(packKey, "pack");
|
||||
structureKey = requireKey(structureKey, "structure");
|
||||
mode = Objects.requireNonNull(mode, "Jigsaw Studio mode");
|
||||
compatibilityTarget = Objects.requireNonNull(
|
||||
compatibilityTarget,
|
||||
"Jigsaw Studio compatibility target"
|
||||
);
|
||||
cellDimensions = Objects.requireNonNull(cellDimensions, "Jigsaw Studio cell dimensions");
|
||||
source = Objects.requireNonNull(source, "Jigsaw Studio source data");
|
||||
}
|
||||
|
||||
private static String requireKey(String value, String name) {
|
||||
Objects.requireNonNull(value, "Jigsaw Studio " + name + " key");
|
||||
String normalized = value.trim();
|
||||
if (normalized.isEmpty()) {
|
||||
throw new IllegalArgumentException("Jigsaw Studio " + name + " key cannot be blank");
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package art.arcane.iris.core.service;
|
||||
|
||||
import com.volmit.ModuleLog;
|
||||
import com.volmit.tooling.world.ToolPlayer;
|
||||
import com.volmit.tooling.world.ToolWorld;
|
||||
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledThreadPoolExecutor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
/**
|
||||
* The studio's own clock: background work, and work that waits some game ticks before it hops to the thread that owns a
|
||||
* player or a chunk. A tick is {@value #TICK_MILLIS} milliseconds here, as the server runs when it keeps up.
|
||||
*/
|
||||
final class JigsawStudioScheduler {
|
||||
static final long TICK_MILLIS = 50L;
|
||||
private static final int WORKER_THREADS = 2;
|
||||
private static final String THREAD_NAME_PREFIX = "jigsaw-studio-";
|
||||
|
||||
private final ModuleLog log;
|
||||
private final ScheduledExecutorService executor;
|
||||
private final Set<UUID> departedPlayers = ConcurrentHashMap.newKeySet();
|
||||
|
||||
JigsawStudioScheduler(ModuleLog log) {
|
||||
this.log = log;
|
||||
AtomicInteger threadNumber = new AtomicInteger();
|
||||
ScheduledThreadPoolExecutor pool = new ScheduledThreadPoolExecutor(WORKER_THREADS, task -> {
|
||||
Thread thread = new Thread(task, THREAD_NAME_PREFIX + threadNumber.incrementAndGet());
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
});
|
||||
pool.setRemoveOnCancelPolicy(true);
|
||||
this.executor = pool;
|
||||
}
|
||||
|
||||
/** Runs {@code task} off the server's threads, as soon as a worker is free. */
|
||||
void async(Runnable task) {
|
||||
try {
|
||||
executor.execute(guarded(task));
|
||||
} catch (RejectedExecutionException stopped) {
|
||||
log.debug("A Jigsaw Studio background task was dropped because the studio stopped.");
|
||||
}
|
||||
}
|
||||
|
||||
/** Runs {@code task} on a studio worker after {@code delayTicks}; it hops to a platform thread itself where it must. */
|
||||
void later(int delayTicks, Runnable task) {
|
||||
try {
|
||||
executor.schedule(guarded(task), delayTicks * TICK_MILLIS, TimeUnit.MILLISECONDS);
|
||||
} catch (RejectedExecutionException stopped) {
|
||||
log.debug("A Jigsaw Studio timer was dropped because the studio stopped.");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs {@code task} on the player's thread after {@code delayTicks}. {@code retired} runs instead when the player has
|
||||
* left by then or the scheduler is stopped.
|
||||
*/
|
||||
void onPlayerLater(ToolPlayer player, Runnable task, int delayTicks, Runnable retired) {
|
||||
Runnable hop = () -> {
|
||||
if (departedPlayers.contains(player.id())) {
|
||||
retired.run();
|
||||
return;
|
||||
}
|
||||
JigsawStudioThreads.run(player, task);
|
||||
};
|
||||
try {
|
||||
executor.schedule(guarded(hop), delayTicks * TICK_MILLIS, TimeUnit.MILLISECONDS);
|
||||
} catch (RejectedExecutionException stopped) {
|
||||
retired.run();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs {@code task} on the thread that owns the chunk after {@code delayTicks}. {@code notScheduled} runs instead when
|
||||
* the host cannot schedule it.
|
||||
*/
|
||||
void onRegionLater(ToolWorld world, int chunkX, int chunkZ, Runnable task, int delayTicks, Runnable notScheduled) {
|
||||
Runnable hop = () -> JigsawStudioThreads.onRegion(log, world, chunkX, chunkZ, task, notScheduled);
|
||||
try {
|
||||
executor.schedule(guarded(hop), delayTicks * TICK_MILLIS, TimeUnit.MILLISECONDS);
|
||||
} catch (RejectedExecutionException stopped) {
|
||||
notScheduled.run();
|
||||
}
|
||||
}
|
||||
|
||||
void playerEntered(UUID playerId) {
|
||||
departedPlayers.remove(playerId);
|
||||
}
|
||||
|
||||
void playerLeft(UUID playerId) {
|
||||
departedPlayers.add(playerId);
|
||||
}
|
||||
|
||||
void stop() {
|
||||
executor.shutdownNow();
|
||||
}
|
||||
|
||||
private Runnable guarded(Runnable task) {
|
||||
return () -> {
|
||||
try {
|
||||
task.run();
|
||||
} catch (Throwable failure) {
|
||||
log.error("A Jigsaw Studio background task failed.", failure);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,89 @@
|
||||
package art.arcane.iris.core.service;
|
||||
|
||||
import com.volmit.ModuleLog;
|
||||
import com.volmit.geometry.BlockPosition;
|
||||
import com.volmit.tooling.world.ToolPlayer;
|
||||
import com.volmit.tooling.world.ToolWorld;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.function.BooleanSupplier;
|
||||
|
||||
/**
|
||||
* Moves work onto the thread that owns a player or a chunk, the way the studio needs it: a method that must run on a
|
||||
* player's thread asks {@link #owns} and, when it does not, hands itself to {@link #call}, which runs it at once when the
|
||||
* caller already is that thread.
|
||||
*/
|
||||
final class JigsawStudioThreads {
|
||||
private static final int CHUNK_SHIFT = 4;
|
||||
|
||||
private JigsawStudioThreads() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the calling thread is the one that owns the player. A player runs a task at once on their own thread and
|
||||
* later on any other, so a probe task tells which this is.
|
||||
*/
|
||||
static boolean owns(ToolPlayer player) {
|
||||
boolean[] ranDuringCall = {false};
|
||||
boolean[] stillInCall = {true};
|
||||
player.run(() -> ranDuringCall[0] = stillInCall[0]);
|
||||
stillInCall[0] = false;
|
||||
return ranDuringCall[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs {@code task} on the player's thread and returns what it returned. When the task has to wait for the thread it
|
||||
* returns {@code true}, standing for "scheduled".
|
||||
*/
|
||||
static boolean call(ToolPlayer player, BooleanSupplier task) {
|
||||
boolean[] result = {true};
|
||||
player.run(() -> result[0] = task.getAsBoolean());
|
||||
return result[0];
|
||||
}
|
||||
|
||||
/** Runs {@code task} on the player's thread, now when the caller is that thread. */
|
||||
static void run(ToolPlayer player, Runnable task) {
|
||||
player.run(task);
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs {@code task} on the thread that owns the chunk. {@code notScheduled} runs instead when the host cannot
|
||||
* schedule it; a task that throws is reported to {@code log}.
|
||||
*/
|
||||
static void onRegion(
|
||||
ModuleLog log,
|
||||
ToolWorld world,
|
||||
int chunkX,
|
||||
int chunkZ,
|
||||
Runnable task,
|
||||
Runnable notScheduled
|
||||
) {
|
||||
AtomicBoolean started = new AtomicBoolean();
|
||||
world.call(chunkOrigin(chunkX, chunkZ), () -> {
|
||||
started.set(true);
|
||||
runReporting(log, task);
|
||||
return null;
|
||||
}).whenComplete((ignored, failure) -> {
|
||||
if (failure != null && !started.get()) {
|
||||
notScheduled.run();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** Whether the calling thread owns the chunk. */
|
||||
static boolean ownsRegion(ToolWorld world, int chunkX, int chunkZ) {
|
||||
return world.owns(chunkOrigin(chunkX, chunkZ));
|
||||
}
|
||||
|
||||
static BlockPosition chunkOrigin(int chunkX, int chunkZ) {
|
||||
return new BlockPosition(chunkX << CHUNK_SHIFT, 0, chunkZ << CHUNK_SHIFT);
|
||||
}
|
||||
|
||||
private static void runReporting(ModuleLog log, Runnable task) {
|
||||
try {
|
||||
task.run();
|
||||
} catch (Throwable failure) {
|
||||
log.error("A Jigsaw Studio region task failed.", failure);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package art.arcane.iris.core.service;
|
||||
|
||||
import art.arcane.volmlib.util.collection.KMap;
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.google.gson.Strictness;
|
||||
import com.google.gson.ToNumberPolicy;
|
||||
import com.volmit.object.BlockEntityData;
|
||||
import com.volmit.resource.ResourceId;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.DataInputStream;
|
||||
import java.io.DataOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* The block entities of the studio's jigsaw markers in the host's tile format, {@code iris:tile} version 1: the block's
|
||||
* key and its NBT as JSON, which is the form the host keeps tile data in everywhere else.
|
||||
*/
|
||||
final class JigsawStudioTileCodec {
|
||||
static final ResourceId TILE_FORMAT = ResourceId.parse("iris:tile");
|
||||
static final int TILE_FORMAT_VERSION = 1;
|
||||
|
||||
private static final Gson GSON = new GsonBuilder()
|
||||
.disableHtmlEscaping()
|
||||
.setStrictness(Strictness.LENIENT)
|
||||
.setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE)
|
||||
.create();
|
||||
|
||||
private JigsawStudioTileCodec() {
|
||||
}
|
||||
|
||||
static BlockEntityData encode(String blockKey, Map<String, Object> nbt) {
|
||||
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
|
||||
try (DataOutputStream out = new DataOutputStream(bytes)) {
|
||||
out.writeUTF(blockKey);
|
||||
out.writeUTF(GSON.toJson(nbt));
|
||||
} catch (IOException failure) {
|
||||
throw new UncheckedIOException("Cannot store the NBT of " + blockKey, failure);
|
||||
}
|
||||
return new BlockEntityData(TILE_FORMAT, TILE_FORMAT_VERSION, bytes.toByteArray());
|
||||
}
|
||||
|
||||
/** The NBT {@code data} holds; empty when it is not in the tile format. */
|
||||
static Optional<KMap<String, Object>> nbt(BlockEntityData data) {
|
||||
if (!TILE_FORMAT.equals(data.format()) || data.version() != TILE_FORMAT_VERSION) {
|
||||
return Optional.empty();
|
||||
}
|
||||
try (DataInputStream in = new DataInputStream(new ByteArrayInputStream(data.payload()))) {
|
||||
in.readUTF();
|
||||
@SuppressWarnings("unchecked")
|
||||
KMap<String, Object> nbt = GSON.fromJson(in.readUTF(), KMap.class);
|
||||
return Optional.ofNullable(nbt);
|
||||
} catch (IOException failure) {
|
||||
throw new UncheckedIOException("Cannot read a block entity of format " + TILE_FORMAT, failure);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,14 +2,11 @@ package art.arcane.iris.core.service;
|
||||
|
||||
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioToolAction;
|
||||
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioToolPayload;
|
||||
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.NamespacedKey;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.meta.ItemMeta;
|
||||
import org.bukkit.persistence.PersistentDataContainer;
|
||||
import org.bukkit.persistence.PersistentDataType;
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParseException;
|
||||
import com.volmit.resource.ResourceId;
|
||||
import com.volmit.tooling.world.ToolItem;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
@@ -17,98 +14,82 @@ import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
/** Turns a studio tool payload into the tool item a player holds, and the item back into the payload. */
|
||||
public final class JigsawStudioToolCodec {
|
||||
static final NamespacedKey SCHEMA_KEY = new NamespacedKey("iris", "jigsaw_tool_schema");
|
||||
static final NamespacedKey ACTION_KEY = new NamespacedKey("iris", "jigsaw_tool_action");
|
||||
static final NamespacedKey REQUEST_KEY = new NamespacedKey("iris", "jigsaw_tool_request");
|
||||
static final NamespacedKey WORKCELL_KEY = new NamespacedKey("iris", "jigsaw_tool_workcell");
|
||||
static final NamespacedKey PIECE_KEY = new NamespacedKey("iris", "jigsaw_tool_piece");
|
||||
static final NamespacedKey POOL_KEY = new NamespacedKey("iris", "jigsaw_tool_pool");
|
||||
static final NamespacedKey ENTRY_INDEX_KEY = new NamespacedKey("iris", "jigsaw_tool_entry_index");
|
||||
static final NamespacedKey AMOUNT_KEY = new NamespacedKey("iris", "jigsaw_tool_amount");
|
||||
static final ResourceId TOOL_ITEM = ResourceId.parse("minecraft:stick");
|
||||
static final String NAME_PREFIX = "Jigsaw Studio: ";
|
||||
static final String SCHEMA_FIELD = "schema";
|
||||
static final String ACTION_FIELD = "action";
|
||||
static final String REQUEST_FIELD = "request";
|
||||
static final String WORKCELL_FIELD = "workcell";
|
||||
static final String PIECE_FIELD = "piece";
|
||||
static final String POOL_FIELD = "pool";
|
||||
static final String ENTRY_INDEX_FIELD = "entryIndex";
|
||||
static final String AMOUNT_FIELD = "amount";
|
||||
|
||||
public ItemStack create(JigsawStudioToolPayload payload) {
|
||||
ItemStack tool = new ItemStack(Material.STICK);
|
||||
bind(tool, payload);
|
||||
return tool;
|
||||
}
|
||||
private static final Gson GSON = new Gson();
|
||||
|
||||
public void bind(ItemStack tool, JigsawStudioToolPayload payload) {
|
||||
ItemStack item = Objects.requireNonNull(tool, "Jigsaw Studio tool item");
|
||||
public ToolItem create(JigsawStudioToolPayload payload) {
|
||||
JigsawStudioToolPayload binding = requireCurrentSchema(payload);
|
||||
if (item.getType() != Material.STICK) {
|
||||
throw new IllegalArgumentException("Jigsaw Studio tools must use a stick");
|
||||
}
|
||||
ItemMeta meta = item.getItemMeta();
|
||||
if (meta == null) {
|
||||
throw new IllegalStateException("Jigsaw Studio tool stick has no item metadata");
|
||||
}
|
||||
write(meta.getPersistentDataContainer(), binding);
|
||||
meta.setDisplayName(ChatColor.AQUA + "Jigsaw Studio: " + binding.action().displayName());
|
||||
meta.setLore(lore(binding));
|
||||
if (!item.setItemMeta(meta)) {
|
||||
throw new IllegalStateException("Jigsaw Studio tool metadata was rejected");
|
||||
}
|
||||
return new ToolItem(
|
||||
TOOL_ITEM,
|
||||
NAME_PREFIX + binding.action().displayName(),
|
||||
lore(binding),
|
||||
false,
|
||||
encode(binding));
|
||||
}
|
||||
|
||||
public Optional<JigsawStudioToolPayload> decode(ItemStack tool) {
|
||||
if (tool == null || tool.getType() != Material.STICK || !tool.hasItemMeta()) {
|
||||
public Optional<JigsawStudioToolPayload> decode(ToolItem tool) {
|
||||
if (tool == null || !TOOL_ITEM.equals(tool.item())) {
|
||||
return Optional.empty();
|
||||
}
|
||||
ItemMeta meta = tool.getItemMeta();
|
||||
return meta == null ? Optional.empty() : decode(meta.getPersistentDataContainer());
|
||||
return decode(tool.payload());
|
||||
}
|
||||
|
||||
public boolean isTool(ItemStack tool) {
|
||||
public boolean isTool(ToolItem tool) {
|
||||
return decode(tool).isPresent();
|
||||
}
|
||||
|
||||
void write(PersistentDataContainer container, JigsawStudioToolPayload payload) {
|
||||
PersistentDataContainer data = Objects.requireNonNull(
|
||||
container,
|
||||
"Jigsaw Studio tool persistent data");
|
||||
String encode(JigsawStudioToolPayload payload) {
|
||||
JigsawStudioToolPayload binding = requireCurrentSchema(payload);
|
||||
data.set(SCHEMA_KEY, PersistentDataType.INTEGER, binding.schemaVersion());
|
||||
data.set(ACTION_KEY, PersistentDataType.STRING, binding.action().name());
|
||||
data.set(REQUEST_KEY, PersistentDataType.STRING, binding.requestId().toString());
|
||||
data.set(WORKCELL_KEY, PersistentDataType.STRING, binding.workcellId());
|
||||
data.set(PIECE_KEY, PersistentDataType.STRING, binding.pieceKey());
|
||||
data.set(POOL_KEY, PersistentDataType.STRING, binding.poolKey());
|
||||
data.set(ENTRY_INDEX_KEY, PersistentDataType.INTEGER, binding.entryIndex());
|
||||
data.set(AMOUNT_KEY, PersistentDataType.INTEGER, binding.amount());
|
||||
JsonObject json = new JsonObject();
|
||||
json.addProperty(SCHEMA_FIELD, binding.schemaVersion());
|
||||
json.addProperty(ACTION_FIELD, binding.action().name());
|
||||
json.addProperty(REQUEST_FIELD, binding.requestId().toString());
|
||||
json.addProperty(WORKCELL_FIELD, binding.workcellId());
|
||||
json.addProperty(PIECE_FIELD, binding.pieceKey());
|
||||
json.addProperty(POOL_FIELD, binding.poolKey());
|
||||
json.addProperty(ENTRY_INDEX_FIELD, binding.entryIndex());
|
||||
json.addProperty(AMOUNT_FIELD, binding.amount());
|
||||
return GSON.toJson(json);
|
||||
}
|
||||
|
||||
Optional<JigsawStudioToolPayload> decode(PersistentDataContainer container) {
|
||||
if (container == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
Integer schemaVersion = container.get(SCHEMA_KEY, PersistentDataType.INTEGER);
|
||||
String actionName = container.get(ACTION_KEY, PersistentDataType.STRING);
|
||||
String requestValue = container.get(REQUEST_KEY, PersistentDataType.STRING);
|
||||
if (schemaVersion == null
|
||||
|| schemaVersion != JigsawStudioToolPayload.CURRENT_SCHEMA_VERSION
|
||||
|| actionName == null
|
||||
|| requestValue == null) {
|
||||
Optional<JigsawStudioToolPayload> decode(String payload) {
|
||||
if (payload == null || payload.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
try {
|
||||
JigsawStudioToolAction action = JigsawStudioToolAction.valueOf(actionName);
|
||||
UUID requestId = UUID.fromString(requestValue);
|
||||
String workcellId = optionalString(container, WORKCELL_KEY);
|
||||
String pieceKey = optionalString(container, PIECE_KEY);
|
||||
String poolKey = optionalString(container, POOL_KEY);
|
||||
Integer entryIndex = container.get(ENTRY_INDEX_KEY, PersistentDataType.INTEGER);
|
||||
Integer amount = container.get(AMOUNT_KEY, PersistentDataType.INTEGER);
|
||||
JsonObject json = GSON.fromJson(payload, JsonObject.class);
|
||||
if (json == null
|
||||
|| !json.has(SCHEMA_FIELD)
|
||||
|| !json.has(ACTION_FIELD)
|
||||
|| !json.has(REQUEST_FIELD)
|
||||
|| json.get(SCHEMA_FIELD).getAsInt() != JigsawStudioToolPayload.CURRENT_SCHEMA_VERSION) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(new JigsawStudioToolPayload(
|
||||
schemaVersion,
|
||||
action,
|
||||
requestId,
|
||||
workcellId,
|
||||
pieceKey,
|
||||
poolKey,
|
||||
entryIndex == null ? JigsawStudioToolPayload.NO_ENTRY_INDEX : entryIndex,
|
||||
amount == null ? 0 : amount));
|
||||
} catch (IllegalArgumentException exception) {
|
||||
json.get(SCHEMA_FIELD).getAsInt(),
|
||||
JigsawStudioToolAction.valueOf(json.get(ACTION_FIELD).getAsString()),
|
||||
UUID.fromString(json.get(REQUEST_FIELD).getAsString()),
|
||||
optionalString(json, WORKCELL_FIELD),
|
||||
optionalString(json, PIECE_FIELD),
|
||||
optionalString(json, POOL_FIELD),
|
||||
json.has(ENTRY_INDEX_FIELD)
|
||||
? json.get(ENTRY_INDEX_FIELD).getAsInt()
|
||||
: JigsawStudioToolPayload.NO_ENTRY_INDEX,
|
||||
json.has(AMOUNT_FIELD) ? json.get(AMOUNT_FIELD).getAsInt() : 0));
|
||||
} catch (IllegalArgumentException | IllegalStateException | UnsupportedOperationException
|
||||
| JsonParseException exception) {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
@@ -122,29 +103,28 @@ public final class JigsawStudioToolCodec {
|
||||
return binding;
|
||||
}
|
||||
|
||||
private static String optionalString(PersistentDataContainer container, NamespacedKey key) {
|
||||
String value = container.get(key, PersistentDataType.STRING);
|
||||
return value == null ? "" : value;
|
||||
private static String optionalString(JsonObject json, String field) {
|
||||
return json.has(field) ? json.get(field).getAsString() : "";
|
||||
}
|
||||
|
||||
private static List<String> lore(JigsawStudioToolPayload payload) {
|
||||
List<String> lore = new ArrayList<>();
|
||||
if (!payload.workcellId().isEmpty()) {
|
||||
lore.add(ChatColor.GRAY + "Workcell: " + payload.workcellId());
|
||||
lore.add("Workcell: " + payload.workcellId());
|
||||
}
|
||||
if (!payload.pieceKey().isEmpty()) {
|
||||
lore.add(ChatColor.GRAY + "Variant: " + payload.pieceKey());
|
||||
lore.add("Variant: " + payload.pieceKey());
|
||||
}
|
||||
if (!payload.poolKey().isEmpty()) {
|
||||
lore.add(ChatColor.GRAY + "Pool: " + payload.poolKey()
|
||||
lore.add("Pool: " + payload.poolKey()
|
||||
+ (payload.entryIndex() < 0 ? "" : " [" + payload.entryIndex() + "]"));
|
||||
}
|
||||
if (payload.amount() != 0) {
|
||||
lore.add(ChatColor.GRAY + "Amount: " + payload.amount());
|
||||
lore.add("Amount: " + payload.amount());
|
||||
}
|
||||
lore.add(payload.action().destructive()
|
||||
? ChatColor.RED + "Right-click twice to confirm"
|
||||
: ChatColor.YELLOW + "Right-click to use");
|
||||
? "Right-click twice to confirm"
|
||||
: "Right-click to use");
|
||||
return List.copyOf(lore);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package art.arcane.iris.core.service;
|
||||
|
||||
import com.volmit.geometry.BlockPosition;
|
||||
import com.volmit.tooling.world.BlockChange;
|
||||
import com.volmit.tooling.world.ToolPlayer;
|
||||
import com.volmit.tooling.world.ToolUse;
|
||||
import com.volmit.tooling.world.ToolWorldListener;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
/**
|
||||
* What a Jigsaw Studio world hears from its host: the world's players, blocks and commands, handed to the studio service
|
||||
* that decides. The studio's id is the id of its request.
|
||||
*/
|
||||
final class JigsawStudioWorldListener implements ToolWorldListener {
|
||||
private final JigsawStudioService service;
|
||||
private final UUID studioId;
|
||||
|
||||
JigsawStudioWorldListener(JigsawStudioService service, UUID studioId) {
|
||||
this.service = Objects.requireNonNull(service, "Jigsaw Studio service");
|
||||
this.studioId = Objects.requireNonNull(studioId, "Jigsaw Studio ID");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void entered(ToolPlayer player) {
|
||||
service.playerEntered(player);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void left(ToolPlayer player) {
|
||||
service.playerLeft(player);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void moved(ToolPlayer player, BlockPosition to) {
|
||||
service.playerMoved(player, to);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sneakToggled(ToolPlayer player, boolean sneaking) {
|
||||
service.sneakToggled(player, sneaking);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean used(ToolPlayer player, ToolUse use) {
|
||||
return service.playerUsed(studioId, player, use);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean blockChanging(BlockChange change) {
|
||||
return service.blockChanging(studioId, change);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean command(Optional<ToolPlayer> sender, String line) {
|
||||
return service.command(studioId, sender, line);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void chunkLoaded(int chunkX, int chunkZ) {
|
||||
service.chunkLoaded(studioId, chunkX, chunkZ);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> closeRefusal() {
|
||||
return service.closeRefusal(studioId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> closing(Optional<ToolPlayer> by) {
|
||||
return service.closing(studioId, by);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void closed() {
|
||||
service.worldClosed(studioId);
|
||||
}
|
||||
}
|
||||
@@ -42,9 +42,9 @@ import art.arcane.iris.core.project.IrisPackageCompiler;
|
||||
import art.arcane.iris.core.project.IrisCodeWorkspace;
|
||||
import art.arcane.iris.core.project.IrisProjectCopier;
|
||||
import art.arcane.iris.core.runtime.StudioOpenCoordinator;
|
||||
import art.arcane.iris.core.runtime.StudioSlotOccupant;
|
||||
import art.arcane.iris.core.runtime.TransientWorldCleanupSupport;
|
||||
import art.arcane.iris.core.runtime.WorldDeletionQueue;
|
||||
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioActivation;
|
||||
import art.arcane.iris.core.tools.IrisToolbelt;
|
||||
import art.arcane.volmlib.util.cache.AtomicCache;
|
||||
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
|
||||
@@ -100,6 +100,7 @@ public class StudioSVC implements IrisService {
|
||||
private final StudioTransitionQueue studioTransitions = new StudioTransitionQueue();
|
||||
private final Object downloadAdmissionMonitor = new Object();
|
||||
private volatile IrisProject activeProject;
|
||||
private volatile StudioSlotOccupant activeToolWorld;
|
||||
private volatile CompletableFuture<StudioOpenCoordinator.StudioOpenResult> activeOpen;
|
||||
private PackDownloadExecution activeDownload;
|
||||
private boolean downloadAdmissionOpen;
|
||||
@@ -511,7 +512,7 @@ public class StudioSVC implements IrisService {
|
||||
}
|
||||
}
|
||||
|
||||
private static BrokenPackException reportPackAdmissionFailure(
|
||||
public static BrokenPackException reportPackAdmissionFailure(
|
||||
VolmitSender sender,
|
||||
String dimm,
|
||||
StudioOpenCoordinator.StudioOpenKind openKind
|
||||
@@ -603,91 +604,6 @@ public class StudioSVC implements IrisService {
|
||||
});
|
||||
}
|
||||
|
||||
public CompletableFuture<StudioOpenCoordinator.StudioOpenResult> openTracked(
|
||||
VolmitSender sender,
|
||||
long seed,
|
||||
String dimension,
|
||||
StudioOpenCoordinator.StudioOpenKind openKind,
|
||||
Runnable beforeOpen,
|
||||
Consumer<World> onDone
|
||||
) {
|
||||
long requestedAtNanos = System.nanoTime();
|
||||
BrokenPackException failure = reportPackAdmissionFailure(sender, dimension, openKind);
|
||||
if (failure != null) {
|
||||
return CompletableFuture.failedFuture(failure);
|
||||
}
|
||||
return studioTransitions.submit(() -> replaceActiveProjectTracked(
|
||||
sender,
|
||||
seed,
|
||||
dimension,
|
||||
Objects.requireNonNull(openKind, "Studio open kind"),
|
||||
Objects.requireNonNull(beforeOpen, "Studio before-open callback"),
|
||||
Objects.requireNonNull(onDone, "Studio open completion callback"),
|
||||
requestedAtNanos));
|
||||
}
|
||||
|
||||
private CompletableFuture<StudioOpenCoordinator.StudioOpenResult> replaceActiveProjectTracked(
|
||||
VolmitSender sender,
|
||||
long seed,
|
||||
String dimension,
|
||||
StudioOpenCoordinator.StudioOpenKind openKind,
|
||||
Runnable beforeOpen,
|
||||
Consumer<World> onDone,
|
||||
long requestedAtNanos
|
||||
) {
|
||||
return closeActiveProject().thenCompose(closeResult -> {
|
||||
if (closeResult == null) {
|
||||
return CompletableFuture.failedFuture(
|
||||
new IllegalStateException("Studio close completed without a result."));
|
||||
}
|
||||
if (closeResult.failureCause() != null) {
|
||||
return CompletableFuture.failedFuture(closeResult.failureCause());
|
||||
}
|
||||
beforeOpen.run();
|
||||
return beginStudioOpenTracked(
|
||||
sender,
|
||||
seed,
|
||||
dimension,
|
||||
openKind,
|
||||
onDone,
|
||||
requestedAtNanos);
|
||||
});
|
||||
}
|
||||
|
||||
private CompletableFuture<StudioOpenCoordinator.StudioOpenResult> beginStudioOpenTracked(
|
||||
VolmitSender sender,
|
||||
long seed,
|
||||
String dimension,
|
||||
StudioOpenCoordinator.StudioOpenKind openKind,
|
||||
Consumer<World> onDone,
|
||||
long requestedAtNanos
|
||||
) {
|
||||
IrisProject project = new IrisProject(new File(getWorkspaceFolder(), dimension));
|
||||
activeProject = project;
|
||||
CompletableFuture<StudioOpenCoordinator.StudioOpenResult> opening;
|
||||
try {
|
||||
opening = project.open(sender, seed, openKind, onDone, requestedAtNanos);
|
||||
} catch (IrisException exception) {
|
||||
if (activeProject == project) {
|
||||
activeProject = null;
|
||||
}
|
||||
return CompletableFuture.failedFuture(exception);
|
||||
}
|
||||
|
||||
activeOpen = opening;
|
||||
return opening.thenApply(result -> Objects.requireNonNull(
|
||||
result,
|
||||
"Studio open completed without a result."))
|
||||
.whenComplete((result, throwable) -> {
|
||||
if (activeOpen == opening) {
|
||||
activeOpen = null;
|
||||
}
|
||||
if (throwable != null && activeProject == project && !project.isOpen()) {
|
||||
activeProject = null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private CompletableFuture<Void> replaceActiveProject(
|
||||
VolmitSender sender,
|
||||
long seed,
|
||||
@@ -791,19 +707,13 @@ public class StudioSVC implements IrisService {
|
||||
CompletableFuture<StudioOpenCoordinator.StudioCloseResult> closeActiveProjectForReplacement(
|
||||
VolmitSender sender
|
||||
) {
|
||||
IrisProject project = activeProject;
|
||||
if (project == null) {
|
||||
StudioSlotOccupant toolWorld = activeToolWorld;
|
||||
if (toolWorld == null || !sender.isPlayer()) {
|
||||
return closeActiveProject();
|
||||
}
|
||||
JigsawStudioActivation.Request request = JigsawStudioActivation.getRequest(project.getName());
|
||||
if (request == null || !sender.isPlayer()) {
|
||||
return closeActiveProject();
|
||||
}
|
||||
UUID ownerId = sender.player().getUniqueId();
|
||||
return JigsawStudioService.get()
|
||||
.awaitCloseForReplacement(request.requestId(), ownerId)
|
||||
return toolWorld.prepareReplacement(Optional.of(sender.player().getUniqueId()))
|
||||
.thenCompose(ignored -> {
|
||||
if (activeProject != project) {
|
||||
if (activeToolWorld != toolWorld) {
|
||||
return CompletableFuture.failedFuture(new IllegalStateException(
|
||||
"The active Studio project changed while replacement was waiting to close."));
|
||||
}
|
||||
@@ -811,7 +721,62 @@ public class StudioSVC implements IrisService {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Gives the studio slot to a tool world: closes what holds the slot now, then runs {@code opening}, which creates the
|
||||
* world. The slot is free again when the opening fails, or when the world is {@link #releaseStudioSlot gone}.
|
||||
*/
|
||||
public CompletableFuture<Void> occupyStudioSlot(
|
||||
StudioSlotOccupant occupant,
|
||||
Supplier<CompletableFuture<?>> opening
|
||||
) {
|
||||
Objects.requireNonNull(occupant, "Studio slot occupant");
|
||||
Objects.requireNonNull(opening, "Studio slot opening");
|
||||
return studioTransitions.submit(() -> closeActiveProject().thenCompose(closeResult -> {
|
||||
if (closeResult == null) {
|
||||
return CompletableFuture.<Void>failedFuture(
|
||||
new IllegalStateException("Studio close completed without a result."));
|
||||
}
|
||||
if (closeResult.failureCause() != null) {
|
||||
return CompletableFuture.<Void>failedFuture(closeResult.failureCause());
|
||||
}
|
||||
activeToolWorld = occupant;
|
||||
return opening.get().<Void>handle((opened, failure) -> {
|
||||
if (failure == null) {
|
||||
return null;
|
||||
}
|
||||
releaseStudioSlot(occupant);
|
||||
throw failure instanceof java.util.concurrent.CompletionException completion
|
||||
? completion
|
||||
: new java.util.concurrent.CompletionException(failure);
|
||||
});
|
||||
}));
|
||||
}
|
||||
|
||||
/** Frees the studio slot when {@code occupant} still holds it. */
|
||||
public void releaseStudioSlot(StudioSlotOccupant occupant) {
|
||||
if (activeToolWorld == occupant) {
|
||||
activeToolWorld = null;
|
||||
}
|
||||
}
|
||||
|
||||
private CompletableFuture<StudioOpenCoordinator.StudioCloseResult> closeToolWorld(StudioSlotOccupant toolWorld) {
|
||||
Optional<String> refusal = toolWorld.closeRefusal();
|
||||
if (refusal.isPresent()) {
|
||||
return CompletableFuture.failedFuture(new IllegalStateException(refusal.get()));
|
||||
}
|
||||
return toolWorld.close().handle((ignored, failure) -> {
|
||||
if (failure == null) {
|
||||
releaseStudioSlot(toolWorld);
|
||||
}
|
||||
return new StudioOpenCoordinator.StudioCloseResult(null, failure == null, failure == null, false, failure);
|
||||
});
|
||||
}
|
||||
|
||||
private CompletableFuture<StudioOpenCoordinator.StudioCloseResult> closeActiveProject() {
|
||||
StudioSlotOccupant toolWorld = activeToolWorld;
|
||||
if (toolWorld != null) {
|
||||
return closeToolWorld(toolWorld);
|
||||
}
|
||||
IrisProject project = activeProject;
|
||||
if (project == null) {
|
||||
return CompletableFuture.completedFuture(new StudioOpenCoordinator.StudioCloseResult(
|
||||
@@ -823,15 +788,6 @@ public class StudioSVC implements IrisService {
|
||||
));
|
||||
}
|
||||
|
||||
JigsawStudioActivation.Request jigsawRequest = JigsawStudioActivation.getRequest(project.getName());
|
||||
if (jigsawRequest != null) {
|
||||
String protectionFailure = JigsawStudioService.get()
|
||||
.closeProtectionFailure(jigsawRequest.requestId());
|
||||
if (protectionFailure != null) {
|
||||
return CompletableFuture.failedFuture(new IllegalStateException(protectionFailure));
|
||||
}
|
||||
}
|
||||
|
||||
IrisLogging.debug("Closing Active Project");
|
||||
CompletableFuture<StudioOpenCoordinator.StudioCloseResult> closing = project.close();
|
||||
return closing.whenComplete((result, throwable) -> {
|
||||
|
||||
@@ -35,8 +35,6 @@ import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.core.nms.INMS;
|
||||
import art.arcane.iris.core.runtime.ObjectStudioActivation;
|
||||
import art.arcane.iris.core.runtime.StudioPainterSlots;
|
||||
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioActivation;
|
||||
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioSession;
|
||||
import art.arcane.iris.core.service.StudioSVC;
|
||||
import art.arcane.iris.core.tools.IrisToolbelt;
|
||||
import art.arcane.iris.engine.IrisEngine;
|
||||
@@ -53,7 +51,6 @@ import art.arcane.iris.engine.object.world.dimension.IrisDimensionRuntimeContrac
|
||||
import art.arcane.iris.engine.object.world.IrisWorld;
|
||||
import art.arcane.iris.engine.object.runtime.StudioMode;
|
||||
import art.arcane.iris.engine.platform.studio.StudioGenerator;
|
||||
import art.arcane.iris.engine.platform.studio.generators.JigsawStudioGenerator;
|
||||
import art.arcane.iris.engine.platform.studio.generators.PainterStudioGenerator;
|
||||
import art.arcane.iris.platform.bukkit.BukkitWorldBinding;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
@@ -131,9 +128,8 @@ public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChun
|
||||
private volatile Engine engine;
|
||||
private volatile Looper hotloader;
|
||||
private volatile StudioMode lastMode;
|
||||
private volatile UUID lastJigsawStudioRequestId;
|
||||
private volatile StudioPainterSlots.Slot lastPainterSlot;
|
||||
private volatile boolean jigsawStudioActive;
|
||||
private volatile boolean paintedStudioActive;
|
||||
private volatile DummyBiomeProvider dummyBiomeProvider;
|
||||
private volatile Throwable initializationFailure;
|
||||
private volatile IrisDimension validatedDimension;
|
||||
@@ -162,7 +158,7 @@ public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChun
|
||||
new KList<>()
|
||||
);
|
||||
this.initializationFailure = null;
|
||||
this.jigsawStudioActive = false;
|
||||
this.paintedStudioActive = false;
|
||||
this.validatedDimension = null;
|
||||
this.validatedWorldContract = null;
|
||||
this.closing = false;
|
||||
@@ -347,25 +343,14 @@ public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChun
|
||||
|
||||
private void setupEngine() {
|
||||
lastMode = StudioMode.NORMAL;
|
||||
lastJigsawStudioRequestId = null;
|
||||
lastPainterSlot = null;
|
||||
EngineTarget engineTarget = getTarget();
|
||||
String packKey = engineTarget.getDimension().getLoadKey();
|
||||
JigsawStudioActivation.Request request = studio
|
||||
? JigsawStudioActivation.getGeneratorRequest(packKey)
|
||||
: null;
|
||||
JigsawStudioSession session = request == null
|
||||
? null
|
||||
: JigsawStudioActivation.getGeneratorSession(packKey);
|
||||
boolean jigsawRequestActive = request != null
|
||||
&& session != null
|
||||
&& session.sessionId().equals(request.requestId());
|
||||
jigsawStudioActive = jigsawRequestActive || paintedStudioSlot().isPresent();
|
||||
paintedStudioActive = paintedStudioSlot().isPresent();
|
||||
IrisEngine createdEngine = new IrisEngine(
|
||||
engineTarget,
|
||||
selectInitializationMode(studio, jigsawStudioActive));
|
||||
selectInitializationMode(studio, paintedStudioActive));
|
||||
createdEngine.setNativeStructureVolumeQueriesEnabled(shouldGenerateNativeStructures(
|
||||
jigsawStudioActive,
|
||||
paintedStudioActive,
|
||||
studioEntryBootstrapActive.get(),
|
||||
initializationFailure != null));
|
||||
engine = createdEngine;
|
||||
@@ -373,11 +358,11 @@ public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChun
|
||||
targetCache.reset();
|
||||
}
|
||||
|
||||
static IrisEngine.InitializationMode selectInitializationMode(boolean studio, boolean jigsawStudioActive) {
|
||||
static IrisEngine.InitializationMode selectInitializationMode(boolean studio, boolean paintedStudioActive) {
|
||||
if (!studio) {
|
||||
return IrisEngine.InitializationMode.RUNTIME;
|
||||
}
|
||||
return jigsawStudioActive
|
||||
return paintedStudioActive
|
||||
? IrisEngine.InitializationMode.JIGSAW_STUDIO
|
||||
: IrisEngine.InitializationMode.STUDIO;
|
||||
}
|
||||
@@ -441,7 +426,7 @@ public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChun
|
||||
getWorld().setRawWorldSeed(world.getSeed());
|
||||
setupEngine();
|
||||
setup.set(true);
|
||||
this.hotloader = shouldRunStudioHotload(studio, closing, jigsawStudioActive) ? new Looper() {
|
||||
this.hotloader = shouldRunStudioHotload(studio, closing, paintedStudioActive) ? new Looper() {
|
||||
@Override
|
||||
protected long loop() {
|
||||
Engine activeEngine = engine;
|
||||
@@ -593,7 +578,7 @@ public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChun
|
||||
Engine activeEngine = engine;
|
||||
if (activeEngine instanceof IrisEngine irisEngine) {
|
||||
irisEngine.setNativeStructureVolumeQueriesEnabled(shouldGenerateNativeStructures(
|
||||
jigsawStudioActive,
|
||||
paintedStudioActive,
|
||||
false,
|
||||
initializationFailure != null));
|
||||
}
|
||||
@@ -604,13 +589,13 @@ public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChun
|
||||
return studioEntryBootstrapActive.get();
|
||||
}
|
||||
|
||||
public boolean isJigsawStudioActive() {
|
||||
return jigsawStudioActive;
|
||||
public boolean isPaintedStudioActive() {
|
||||
return paintedStudioActive;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void hotload() {
|
||||
if (!shouldRunStudioHotload(isStudio(), closing, jigsawStudioActive)) {
|
||||
if (!shouldRunStudioHotload(isStudio(), closing, paintedStudioActive)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -618,7 +603,7 @@ public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChun
|
||||
}
|
||||
|
||||
private void hotloadFromWatcher() {
|
||||
if (!shouldRunStudioHotload(isStudio(), closing, jigsawStudioActive)) {
|
||||
if (!shouldRunStudioHotload(isStudio(), closing, paintedStudioActive)) {
|
||||
return;
|
||||
}
|
||||
withExclusiveControlFuture(() -> getEngine().hotload(), 30L, TimeUnit.SECONDS).join();
|
||||
@@ -633,8 +618,8 @@ public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChun
|
||||
return withExclusiveControlFuture(activeEngine::hotloadComplex, acquisitionTimeout, unit);
|
||||
}
|
||||
|
||||
static boolean shouldRunStudioHotload(boolean studio, boolean closing, boolean jigsawStudioActive) {
|
||||
return studio && !closing && !jigsawStudioActive;
|
||||
static boolean shouldRunStudioHotload(boolean studio, boolean closing, boolean paintedStudioActive) {
|
||||
return studio && !closing && !paintedStudioActive;
|
||||
}
|
||||
|
||||
public GenerationStagePermit acquireGenerationStage(String operation) {
|
||||
@@ -953,25 +938,6 @@ public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChun
|
||||
}
|
||||
|
||||
private void computeStudioGenerator() {
|
||||
String packKey = getEngine().getDimension().getLoadKey();
|
||||
JigsawStudioActivation.Request jigsawRequest = studio
|
||||
? JigsawStudioActivation.getGeneratorRequest(packKey)
|
||||
: null;
|
||||
if (jigsawRequest != null) {
|
||||
JigsawStudioSession session = JigsawStudioActivation.getGeneratorSession(packKey);
|
||||
if (session != null && session.sessionId().equals(jigsawRequest.requestId())) {
|
||||
if (!jigsawRequest.requestId().equals(lastJigsawStudioRequestId)) {
|
||||
setStudioGenerator(new JigsawStudioGenerator(getEngine(), jigsawRequest, session));
|
||||
lastJigsawStudioRequestId = jigsawRequest.requestId();
|
||||
lastMode = null;
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (lastJigsawStudioRequestId != null) {
|
||||
lastJigsawStudioRequestId = null;
|
||||
lastMode = null;
|
||||
}
|
||||
if (installPaintedStudioGenerator()) {
|
||||
return;
|
||||
}
|
||||
@@ -1039,17 +1005,17 @@ public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChun
|
||||
@Override
|
||||
public boolean shouldGenerateStructures() {
|
||||
return shouldGenerateNativeStructures(
|
||||
jigsawStudioActive,
|
||||
paintedStudioActive,
|
||||
studioEntryBootstrapActive.get(),
|
||||
initializationFailure != null);
|
||||
}
|
||||
|
||||
static boolean shouldGenerateNativeStructures(
|
||||
boolean jigsawStudioActive,
|
||||
boolean paintedStudioActive,
|
||||
boolean studioEntryBootstrapActive,
|
||||
boolean initializationFailed
|
||||
) {
|
||||
return !jigsawStudioActive && !studioEntryBootstrapActive && !initializationFailed;
|
||||
return !paintedStudioActive && !studioEntryBootstrapActive && !initializationFailed;
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+147
-185
@@ -3,7 +3,6 @@ package art.arcane.iris.engine.platform.studio.generators;
|
||||
import art.arcane.iris.engine.framework.structure.StructureResources;
|
||||
import art.arcane.iris.core.runtime.jigsaw.JigsawPlanarDirection;
|
||||
import art.arcane.iris.core.runtime.jigsaw.JigsawPlanarTopology;
|
||||
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioActivation;
|
||||
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioBay;
|
||||
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioBounds;
|
||||
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCellDimensions;
|
||||
@@ -11,95 +10,89 @@ import art.arcane.iris.core.runtime.jigsaw.JigsawStudioControlPosition;
|
||||
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioLayout;
|
||||
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioSession;
|
||||
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioVariant;
|
||||
import art.arcane.iris.core.service.JigsawStudioService;
|
||||
import art.arcane.iris.engine.data.chunk.TerrainChunk;
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.engine.framework.GenerationSessionLease;
|
||||
import art.arcane.iris.engine.framework.WrongEngineBroException;
|
||||
import art.arcane.iris.core.service.JigsawStudioBlocks;
|
||||
import art.arcane.iris.core.service.JigsawStudioRequest;
|
||||
import art.arcane.iris.engine.object.value.IrisDirection;
|
||||
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConnector;
|
||||
import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece;
|
||||
import art.arcane.iris.engine.object.prefab.IrisObject;
|
||||
import art.arcane.iris.engine.object.prefab.ObjectTurn;
|
||||
import art.arcane.iris.engine.object.prefab.BlockStateRotation;
|
||||
import art.arcane.iris.engine.object.value.IrisPosition;
|
||||
import art.arcane.iris.engine.object.structure.jigsaw.JigsawJoint;
|
||||
import art.arcane.iris.engine.object.prefab.TileData;
|
||||
import art.arcane.iris.engine.platform.studio.EnginedStudioGenerator;
|
||||
import art.arcane.iris.platform.bukkit.BukkitWorldBinding;
|
||||
import art.arcane.iris.spi.PlatformBlockState;
|
||||
import art.arcane.iris.util.common.data.B;
|
||||
import art.arcane.volmlib.util.data.VectorMap;
|
||||
import art.arcane.volmlib.util.math.IrisBlockVector;
|
||||
import art.arcane.volmlib.util.math.Vector3i;
|
||||
import art.arcane.iris.util.project.context.IrisContext;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import org.bukkit.World;
|
||||
import com.volmit.block.BlockRegistry;
|
||||
import com.volmit.block.BlockState;
|
||||
import com.volmit.geometry.BlockPosition;
|
||||
import com.volmit.object.BlockEntityData;
|
||||
import com.volmit.object.ObjectBlock;
|
||||
import com.volmit.object.PlaceableObject;
|
||||
import com.volmit.resource.PackResources;
|
||||
import com.volmit.tooling.ToolPack;
|
||||
import com.volmit.tooling.world.ChunkCanvas;
|
||||
import com.volmit.tooling.world.ChunkPainter;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
public final class JigsawStudioGenerator extends EnginedStudioGenerator {
|
||||
public final class JigsawStudioGenerator implements ChunkPainter {
|
||||
private static final int CHECKER_SIZE = 4;
|
||||
private static final int CHUNK_SIZE = 16;
|
||||
|
||||
private final JigsawStudioActivation.Request request;
|
||||
private final ToolPack pack;
|
||||
private final JigsawStudioRequest request;
|
||||
private final JigsawStudioSession session;
|
||||
private final PlatformBlockState lightFloor;
|
||||
private final PlatformBlockState darkFloor;
|
||||
private final PlatformBlockState frame;
|
||||
private final PlatformBlockState topologyBase;
|
||||
private final PlatformBlockState topologyPath;
|
||||
private final PlatformBlockState connectorCap;
|
||||
private final PlatformBlockState invalidMarker;
|
||||
private final PlatformBlockState controlChest;
|
||||
private final BlockState lightFloor;
|
||||
private final BlockState darkFloor;
|
||||
private final BlockState frame;
|
||||
private final BlockState topologyBase;
|
||||
private final BlockState topologyPath;
|
||||
private final BlockState connectorCap;
|
||||
private final BlockState invalidMarker;
|
||||
private final BlockState controlChest;
|
||||
private final FinalStateRenderer finalStateRenderer;
|
||||
private final AtomicBoolean serviceRegistered = new AtomicBoolean(false);
|
||||
private final ConcurrentMap<RenderKey, RenderedBay> renderedBays = new ConcurrentHashMap<>();
|
||||
private final ConcurrentMap<String, PlatformBlockState> jigsawStates = new ConcurrentHashMap<>();
|
||||
private final ConcurrentMap<String, BlockState> jigsawStates = new ConcurrentHashMap<>();
|
||||
|
||||
public JigsawStudioGenerator(
|
||||
Engine engine,
|
||||
JigsawStudioActivation.Request request,
|
||||
ToolPack pack,
|
||||
JigsawStudioRequest request,
|
||||
JigsawStudioSession session
|
||||
) {
|
||||
this(
|
||||
engine,
|
||||
pack,
|
||||
request,
|
||||
session,
|
||||
B.getState("minecraft:smooth_stone"),
|
||||
B.getState("minecraft:polished_deepslate"),
|
||||
B.getState("minecraft:white_concrete"),
|
||||
B.getState("minecraft:light_gray_wool"),
|
||||
B.getState("minecraft:red_wool"),
|
||||
B.getState("minecraft:sea_lantern"),
|
||||
B.getState("minecraft:red_stained_glass"),
|
||||
B.getState("minecraft:chest[facing=south,type=single,waterlogged=false]"),
|
||||
JigsawStudioGenerator::rotatedFinalState
|
||||
BlockState.parse("minecraft:smooth_stone"),
|
||||
BlockState.parse("minecraft:polished_deepslate"),
|
||||
BlockState.parse("minecraft:white_concrete"),
|
||||
BlockState.parse("minecraft:light_gray_wool"),
|
||||
BlockState.parse("minecraft:red_wool"),
|
||||
BlockState.parse("minecraft:sea_lantern"),
|
||||
BlockState.parse("minecraft:red_stained_glass"),
|
||||
BlockState.parse("minecraft:chest[facing=south,type=single,waterlogged=false]"),
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
JigsawStudioGenerator(
|
||||
Engine engine,
|
||||
JigsawStudioActivation.Request request,
|
||||
ToolPack pack,
|
||||
JigsawStudioRequest request,
|
||||
JigsawStudioSession session,
|
||||
PlatformBlockState lightFloor,
|
||||
PlatformBlockState darkFloor,
|
||||
PlatformBlockState frame,
|
||||
PlatformBlockState topologyBase,
|
||||
PlatformBlockState topologyPath,
|
||||
PlatformBlockState connectorCap,
|
||||
PlatformBlockState invalidMarker,
|
||||
PlatformBlockState controlChest,
|
||||
BlockState lightFloor,
|
||||
BlockState darkFloor,
|
||||
BlockState frame,
|
||||
BlockState topologyBase,
|
||||
BlockState topologyPath,
|
||||
BlockState connectorCap,
|
||||
BlockState invalidMarker,
|
||||
BlockState controlChest,
|
||||
FinalStateRenderer finalStateRenderer
|
||||
) {
|
||||
super(engine);
|
||||
this.pack = Objects.requireNonNull(pack, "Jigsaw Studio pack");
|
||||
this.request = Objects.requireNonNull(request, "Jigsaw Studio request");
|
||||
this.session = Objects.requireNonNull(session, "Jigsaw Studio session");
|
||||
this.lightFloor = Objects.requireNonNull(lightFloor, "Jigsaw Studio light floor block");
|
||||
@@ -110,9 +103,7 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator {
|
||||
this.connectorCap = Objects.requireNonNull(connectorCap, "Jigsaw Studio connector cap block");
|
||||
this.invalidMarker = Objects.requireNonNull(invalidMarker, "Jigsaw Studio invalid marker block");
|
||||
this.controlChest = Objects.requireNonNull(controlChest, "Jigsaw Studio control chest block");
|
||||
this.finalStateRenderer = Objects.requireNonNull(
|
||||
finalStateRenderer,
|
||||
"Jigsaw Studio connector final-state renderer");
|
||||
this.finalStateRenderer = finalStateRenderer == null ? this::rotatedFinalState : finalStateRenderer;
|
||||
if (!request.requestId().equals(session.sessionId())) {
|
||||
throw new IllegalArgumentException("Jigsaw Studio request and session IDs do not match");
|
||||
}
|
||||
@@ -121,7 +112,11 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator {
|
||||
}
|
||||
}
|
||||
|
||||
public JigsawStudioActivation.Request getRequest() {
|
||||
public ToolPack getPack() {
|
||||
return pack;
|
||||
}
|
||||
|
||||
public JigsawStudioRequest getRequest() {
|
||||
return request;
|
||||
}
|
||||
|
||||
@@ -176,29 +171,21 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void generateChunk(Engine engine, TerrainChunk terrainChunk, int chunkX, int chunkZ)
|
||||
throws WrongEngineBroException {
|
||||
try (GenerationSessionLease lease = engine.acquireGenerationLease("bukkit_jigsaw_studio_stage");
|
||||
IrisContext.Scope ignored = IrisContext.open(engine, lease.sessionId(), null)) {
|
||||
paintChunk(terrainChunk, chunkX, chunkZ);
|
||||
ensureServiceRegistered(engine);
|
||||
if (serviceRegistered.get()) {
|
||||
JigsawStudioService.get().markChunkGenerated(engine, this, chunkX, chunkZ);
|
||||
}
|
||||
}
|
||||
public void paint(int chunkX, int chunkZ, ChunkCanvas canvas) {
|
||||
paintChunk(canvas, chunkX, chunkZ);
|
||||
}
|
||||
|
||||
public void paintChunk(TerrainChunk terrainChunk, int chunkX, int chunkZ) {
|
||||
Objects.requireNonNull(terrainChunk, "Jigsaw Studio terrain chunk");
|
||||
int floorY = Math.max(terrainChunk.getMinHeight(), JigsawStudioLayout.FLOOR_Y);
|
||||
if (floorY >= terrainChunk.getMaxHeight()) {
|
||||
public void paintChunk(ChunkCanvas canvas, int chunkX, int chunkZ) {
|
||||
Objects.requireNonNull(canvas, "Jigsaw Studio chunk canvas");
|
||||
int floorY = Math.max(canvas.minY(), JigsawStudioLayout.FLOOR_Y);
|
||||
if (floorY >= canvas.maxY()) {
|
||||
return;
|
||||
}
|
||||
|
||||
int chunkWorldX = chunkX << 4;
|
||||
int chunkWorldZ = chunkZ << 4;
|
||||
paintFloor(terrainChunk, floorY, chunkWorldX, chunkWorldZ);
|
||||
paintControlChest(terrainChunk, chunkWorldX, chunkWorldZ);
|
||||
paintFloor(canvas, floorY, chunkWorldX, chunkWorldZ);
|
||||
paintControlChest(canvas, chunkWorldX, chunkWorldZ);
|
||||
|
||||
int chunkMaxX = chunkWorldX + 15;
|
||||
int chunkMaxZ = chunkWorldZ + 15;
|
||||
@@ -211,21 +198,21 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator {
|
||||
chunkMaxZ + 1)) {
|
||||
continue;
|
||||
}
|
||||
paintCage(terrainChunk, workcell, chunkWorldX, chunkWorldZ);
|
||||
paintCage(canvas, workcell, chunkWorldX, chunkWorldZ);
|
||||
if (workcell.archetype().isPresent()) {
|
||||
paintTopologyGlyph(terrainChunk, workcell, chunkWorldX, chunkWorldZ);
|
||||
paintTopologyGlyph(canvas, workcell, chunkWorldX, chunkWorldZ);
|
||||
}
|
||||
RenderedBay renderedBay = renderBay(workcell);
|
||||
if (!renderedBay.valid()) {
|
||||
paintInvalidBay(terrainChunk, workcell, chunkWorldX, chunkWorldZ);
|
||||
paintInvalidBay(canvas, workcell, chunkWorldX, chunkWorldZ);
|
||||
continue;
|
||||
}
|
||||
paintObject(terrainChunk, workcell, renderedBay, chunkWorldX, chunkWorldZ);
|
||||
paintObject(canvas, workcell, renderedBay, chunkWorldX, chunkWorldZ);
|
||||
if (session.workcellSnapshot(workcell.stableId()).connectorsVisible()) {
|
||||
paintConnectors(terrainChunk, workcell, renderedBay, chunkWorldX, chunkWorldZ);
|
||||
paintConnectors(canvas, workcell, renderedBay, chunkWorldX, chunkWorldZ);
|
||||
} else {
|
||||
paintHiddenConnectorFinalStates(
|
||||
terrainChunk,
|
||||
canvas,
|
||||
workcell,
|
||||
renderedBay,
|
||||
chunkWorldX,
|
||||
@@ -234,48 +221,23 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator {
|
||||
}
|
||||
}
|
||||
|
||||
private void ensureServiceRegistered(Engine engine) {
|
||||
if (serviceRegistered.get()) {
|
||||
return;
|
||||
}
|
||||
World world = BukkitWorldBinding.world(engine.getTarget().getWorld());
|
||||
if (world == null) {
|
||||
return;
|
||||
}
|
||||
publishServiceRegistration(() -> JigsawStudioService.get().register(engine, this));
|
||||
}
|
||||
|
||||
void publishServiceRegistration(Runnable registration) {
|
||||
Objects.requireNonNull(registration, "Jigsaw Studio service registration");
|
||||
if (serviceRegistered.get()) {
|
||||
return;
|
||||
}
|
||||
synchronized (serviceRegistered) {
|
||||
if (serviceRegistered.get()) {
|
||||
return;
|
||||
}
|
||||
registration.run();
|
||||
serviceRegistered.set(true);
|
||||
}
|
||||
}
|
||||
|
||||
private void paintFloor(TerrainChunk terrainChunk, int floorY, int chunkWorldX, int chunkWorldZ) {
|
||||
for (int localX = 0; localX < 16; localX++) {
|
||||
for (int localZ = 0; localZ < 16; localZ++) {
|
||||
private void paintFloor(ChunkCanvas canvas, int floorY, int chunkWorldX, int chunkWorldZ) {
|
||||
for (int localX = 0; localX < CHUNK_SIZE; localX++) {
|
||||
for (int localZ = 0; localZ < CHUNK_SIZE; localZ++) {
|
||||
int worldX = chunkWorldX + localX;
|
||||
int worldZ = chunkWorldZ + localZ;
|
||||
int tileX = Math.floorDiv(worldX, CHECKER_SIZE);
|
||||
int tileZ = Math.floorDiv(worldZ, CHECKER_SIZE);
|
||||
PlatformBlockState block = ((tileX + tileZ) & 1) == 0 ? lightFloor : darkFloor;
|
||||
terrainChunk.setBlock(localX, floorY, localZ, block);
|
||||
BlockState block = ((tileX + tileZ) & 1) == 0 ? lightFloor : darkFloor;
|
||||
canvas.set(localX, floorY, localZ, block);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void paintControlChest(TerrainChunk terrainChunk, int chunkWorldX, int chunkWorldZ) {
|
||||
private void paintControlChest(ChunkCanvas canvas, int chunkWorldX, int chunkWorldZ) {
|
||||
JigsawStudioControlPosition control = getLayout().controlPosition();
|
||||
setWorldBlock(
|
||||
terrainChunk,
|
||||
canvas,
|
||||
control.worldX(),
|
||||
control.worldY(),
|
||||
control.worldZ(),
|
||||
@@ -285,7 +247,7 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator {
|
||||
}
|
||||
|
||||
private void paintCage(
|
||||
TerrainChunk terrainChunk,
|
||||
ChunkCanvas canvas,
|
||||
JigsawStudioBay workcell,
|
||||
int chunkWorldX,
|
||||
int chunkWorldZ
|
||||
@@ -299,7 +261,7 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator {
|
||||
int topY = bounds.maxY() + 1;
|
||||
|
||||
paintRectangle(
|
||||
terrainChunk,
|
||||
canvas,
|
||||
minimumX,
|
||||
maximumX,
|
||||
bottomY,
|
||||
@@ -308,7 +270,7 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator {
|
||||
chunkWorldX,
|
||||
chunkWorldZ);
|
||||
paintRectangle(
|
||||
terrainChunk,
|
||||
canvas,
|
||||
minimumX,
|
||||
maximumX,
|
||||
topY,
|
||||
@@ -317,15 +279,15 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator {
|
||||
chunkWorldX,
|
||||
chunkWorldZ);
|
||||
for (int y = bottomY + 1; y < topY; y++) {
|
||||
setWorldBlock(terrainChunk, minimumX, y, minimumZ, frame, chunkWorldX, chunkWorldZ);
|
||||
setWorldBlock(terrainChunk, maximumX, y, minimumZ, frame, chunkWorldX, chunkWorldZ);
|
||||
setWorldBlock(terrainChunk, minimumX, y, maximumZ, frame, chunkWorldX, chunkWorldZ);
|
||||
setWorldBlock(terrainChunk, maximumX, y, maximumZ, frame, chunkWorldX, chunkWorldZ);
|
||||
setWorldBlock(canvas, minimumX, y, minimumZ, frame, chunkWorldX, chunkWorldZ);
|
||||
setWorldBlock(canvas, maximumX, y, minimumZ, frame, chunkWorldX, chunkWorldZ);
|
||||
setWorldBlock(canvas, minimumX, y, maximumZ, frame, chunkWorldX, chunkWorldZ);
|
||||
setWorldBlock(canvas, maximumX, y, maximumZ, frame, chunkWorldX, chunkWorldZ);
|
||||
}
|
||||
}
|
||||
|
||||
private void paintRectangle(
|
||||
TerrainChunk terrainChunk,
|
||||
ChunkCanvas canvas,
|
||||
int minimumX,
|
||||
int maximumX,
|
||||
int y,
|
||||
@@ -335,17 +297,17 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator {
|
||||
int chunkWorldZ
|
||||
) {
|
||||
for (int x = minimumX; x <= maximumX; x++) {
|
||||
setWorldBlock(terrainChunk, x, y, minimumZ, frame, chunkWorldX, chunkWorldZ);
|
||||
setWorldBlock(terrainChunk, x, y, maximumZ, frame, chunkWorldX, chunkWorldZ);
|
||||
setWorldBlock(canvas, x, y, minimumZ, frame, chunkWorldX, chunkWorldZ);
|
||||
setWorldBlock(canvas, x, y, maximumZ, frame, chunkWorldX, chunkWorldZ);
|
||||
}
|
||||
for (int z = minimumZ + 1; z < maximumZ; z++) {
|
||||
setWorldBlock(terrainChunk, minimumX, y, z, frame, chunkWorldX, chunkWorldZ);
|
||||
setWorldBlock(terrainChunk, maximumX, y, z, frame, chunkWorldX, chunkWorldZ);
|
||||
setWorldBlock(canvas, minimumX, y, z, frame, chunkWorldX, chunkWorldZ);
|
||||
setWorldBlock(canvas, maximumX, y, z, frame, chunkWorldX, chunkWorldZ);
|
||||
}
|
||||
}
|
||||
|
||||
private void paintTopologyGlyph(
|
||||
TerrainChunk terrainChunk,
|
||||
ChunkCanvas canvas,
|
||||
JigsawStudioBay workcell,
|
||||
int chunkWorldX,
|
||||
int chunkWorldZ
|
||||
@@ -366,14 +328,14 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator {
|
||||
int localX = worldX - bounds.originX();
|
||||
for (int worldZ = minimumZ; worldZ <= maximumZ; worldZ++) {
|
||||
int localZ = worldZ - bounds.originZ();
|
||||
PlatformBlockState state = topologyGlyphState(topology, bounds.dimensions(), localX, localZ,
|
||||
BlockState state = topologyGlyphState(topology, bounds.dimensions(), localX, localZ,
|
||||
centerX, centerZ);
|
||||
setWorldBlock(terrainChunk, worldX, glyphY, worldZ, state, chunkWorldX, chunkWorldZ);
|
||||
setWorldBlock(canvas, worldX, glyphY, worldZ, state, chunkWorldX, chunkWorldZ);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private PlatformBlockState topologyGlyphState(
|
||||
private BlockState topologyGlyphState(
|
||||
JigsawPlanarTopology topology,
|
||||
JigsawStudioCellDimensions dimensions,
|
||||
int localX,
|
||||
@@ -426,7 +388,8 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator {
|
||||
}
|
||||
|
||||
private RenderedBay buildRenderedBay(JigsawStudioBay workcell, JigsawStudioVariant variant) {
|
||||
IrisJigsawPiece piece = StructureResources.piece(request.source().getPackResources(), variant.pieceKey());
|
||||
PackResources resources = pack.resources();
|
||||
IrisJigsawPiece piece = StructureResources.piece(resources, variant.pieceKey());
|
||||
if (piece == null) {
|
||||
return RenderedBay.invalid(
|
||||
workcell.bounds().dimensions(),
|
||||
@@ -443,13 +406,13 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator {
|
||||
"piece '" + variant.pieceKey() + "' changed its object from '" + variant.objectKey()
|
||||
+ "' to '" + piece.getObject() + "'");
|
||||
}
|
||||
IrisObject object = request.source().getObjectLoader().load(variant.objectKey(), false);
|
||||
PlaceableObject object = resources.objects().object(resources.idOf(variant.objectKey())).orElse(null);
|
||||
if (object == null) {
|
||||
return RenderedBay.invalid(
|
||||
workcell.bounds().dimensions(),
|
||||
"object '" + variant.objectKey() + "' is missing");
|
||||
}
|
||||
if (object.getW() < 1 || object.getH() < 1 || object.getD() < 1) {
|
||||
if (object.width() < 1 || object.height() < 1 || object.depth() < 1) {
|
||||
return RenderedBay.invalid(
|
||||
workcell.bounds().dimensions(),
|
||||
"object '" + variant.objectKey() + "' has invalid dimensions");
|
||||
@@ -464,7 +427,7 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator {
|
||||
}
|
||||
|
||||
ObjectTurn rotation = ObjectTurn.of(0, -90.0D * quarterTurns, 0);
|
||||
List<RenderedBlock> blocks = renderBlocks(object, dimensions, quarterTurns, rotation);
|
||||
List<RenderedBlock> blocks = renderBlocks(resources.blocks(), object, dimensions, quarterTurns, rotation);
|
||||
if (blocks == null) {
|
||||
return RenderedBay.invalid(
|
||||
dimensions,
|
||||
@@ -479,29 +442,28 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator {
|
||||
}
|
||||
|
||||
private List<RenderedBlock> renderBlocks(
|
||||
IrisObject object,
|
||||
BlockRegistry registry,
|
||||
PlaceableObject object,
|
||||
JigsawStudioCellDimensions dimensions,
|
||||
int quarterTurns,
|
||||
ObjectTurn rotation
|
||||
) {
|
||||
VectorMap<PlatformBlockState> sourceBlocks = object.getBlocks();
|
||||
VectorMap<TileData> sourceTiles = object.getStates();
|
||||
Vector3i center = object.getCenter();
|
||||
BlockPosition center = object.center();
|
||||
List<ObjectBlock> sourceBlocks = object.geometry().blocks();
|
||||
List<RenderedBlock> blocks = new ArrayList<>(sourceBlocks.size());
|
||||
for (Map.Entry<IrisBlockVector, PlatformBlockState> entry : sourceBlocks) {
|
||||
IrisBlockVector signed = entry.getKey();
|
||||
int sourceX = signed.getBlockX() + center.getBlockX();
|
||||
int sourceY = signed.getBlockY() + center.getBlockY();
|
||||
int sourceZ = signed.getBlockZ() + center.getBlockZ();
|
||||
if (!inside(sourceX, sourceY, sourceZ, object.getW(), object.getH(), object.getD())) {
|
||||
for (ObjectBlock source : sourceBlocks) {
|
||||
int sourceX = source.position().x() + center.x();
|
||||
int sourceY = source.position().y() + center.y();
|
||||
int sourceZ = source.position().z() + center.z();
|
||||
if (!inside(sourceX, sourceY, sourceZ, object.width(), object.height(), object.depth())) {
|
||||
return null;
|
||||
}
|
||||
RotatedPosition position = rotatePosition(
|
||||
sourceX,
|
||||
sourceY,
|
||||
sourceZ,
|
||||
object.getW(),
|
||||
object.getD(),
|
||||
object.width(),
|
||||
object.depth(),
|
||||
quarterTurns);
|
||||
if (!inside(
|
||||
position.x(),
|
||||
@@ -512,26 +474,25 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator {
|
||||
dimensions.depth())) {
|
||||
return null;
|
||||
}
|
||||
PlatformBlockState blockState = quarterTurns == 0
|
||||
? entry.getValue()
|
||||
: BlockStateRotation.rotate(rotation, entry.getValue());
|
||||
BlockState blockState = quarterTurns == 0
|
||||
? source.state()
|
||||
: JigsawStudioBlocks.rotated(registry, source.state(), rotation);
|
||||
if (blockState == null) {
|
||||
return null;
|
||||
}
|
||||
TileData tileData = sourceTiles.get(signed);
|
||||
blocks.add(new RenderedBlock(
|
||||
position.x(),
|
||||
position.y(),
|
||||
position.z(),
|
||||
blockState,
|
||||
tileData == null ? null : tileData.clone()));
|
||||
source.blockEntity().orElse(null)));
|
||||
}
|
||||
return List.copyOf(blocks);
|
||||
}
|
||||
|
||||
private ConnectorRenderResult renderConnectors(
|
||||
IrisJigsawPiece piece,
|
||||
IrisObject object,
|
||||
PlaceableObject object,
|
||||
JigsawStudioCellDimensions dimensions,
|
||||
int quarterTurns,
|
||||
ObjectTurn rotation
|
||||
@@ -551,17 +512,17 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator {
|
||||
sourcePosition.getX(),
|
||||
sourcePosition.getY(),
|
||||
sourcePosition.getZ(),
|
||||
object.getW(),
|
||||
object.getH(),
|
||||
object.getD())) {
|
||||
object.width(),
|
||||
object.height(),
|
||||
object.depth())) {
|
||||
return ConnectorRenderResult.invalid("connector " + index + " is outside its object bounds");
|
||||
}
|
||||
RotatedPosition position = rotatePosition(
|
||||
sourcePosition.getX(),
|
||||
sourcePosition.getY(),
|
||||
sourcePosition.getZ(),
|
||||
object.getW(),
|
||||
object.getD(),
|
||||
object.width(),
|
||||
object.depth(),
|
||||
quarterTurns);
|
||||
IrisDirection front = quarterTurns == 0
|
||||
? source.getDirection()
|
||||
@@ -601,24 +562,21 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator {
|
||||
return ConnectorRenderResult.valid(connectors);
|
||||
}
|
||||
|
||||
private static String rotatedFinalState(
|
||||
String finalState,
|
||||
ObjectTurn rotation,
|
||||
int quarterTurns
|
||||
) {
|
||||
PlatformBlockState state = B.getStateOrNull(finalState, false);
|
||||
private String rotatedFinalState(String finalState, ObjectTurn rotation, int quarterTurns) {
|
||||
BlockRegistry registry = pack.resources().blocks();
|
||||
BlockState state = registry.find(finalState).orElse(null);
|
||||
if (state == null) {
|
||||
return null;
|
||||
}
|
||||
if (quarterTurns == 0) {
|
||||
return state.key();
|
||||
}
|
||||
PlatformBlockState rotated = BlockStateRotation.rotate(rotation, state);
|
||||
BlockState rotated = JigsawStudioBlocks.rotated(registry, state, rotation);
|
||||
return rotated == null ? null : rotated.key();
|
||||
}
|
||||
|
||||
private void paintObject(
|
||||
TerrainChunk terrainChunk,
|
||||
ChunkCanvas canvas,
|
||||
JigsawStudioBay workcell,
|
||||
RenderedBay renderedBay,
|
||||
int chunkWorldX,
|
||||
@@ -627,7 +585,7 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator {
|
||||
JigsawStudioBounds bounds = workcell.bounds();
|
||||
for (RenderedBlock block : renderedBay.blocks()) {
|
||||
setWorldBlock(
|
||||
terrainChunk,
|
||||
canvas,
|
||||
bounds.originX() + block.x(),
|
||||
bounds.originY() + block.y(),
|
||||
bounds.originZ() + block.z(),
|
||||
@@ -638,7 +596,7 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator {
|
||||
}
|
||||
|
||||
private void paintConnectors(
|
||||
TerrainChunk terrainChunk,
|
||||
ChunkCanvas canvas,
|
||||
JigsawStudioBay workcell,
|
||||
RenderedBay renderedBay,
|
||||
int chunkWorldX,
|
||||
@@ -646,22 +604,24 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator {
|
||||
) {
|
||||
JigsawStudioBounds bounds = workcell.bounds();
|
||||
for (RenderedConnector connector : renderedBay.connectors()) {
|
||||
PlatformBlockState state = jigsawStates.computeIfAbsent(
|
||||
BlockState state = jigsawStates.computeIfAbsent(
|
||||
connector.orientation(),
|
||||
key -> B.getState("minecraft:jigsaw[orientation=" + key + "]"));
|
||||
key -> pack.resources().blocks()
|
||||
.find("minecraft:jigsaw[orientation=" + key + "]")
|
||||
.orElse(invalidMarker));
|
||||
setWorldBlock(
|
||||
terrainChunk,
|
||||
canvas,
|
||||
bounds.originX() + connector.x(),
|
||||
bounds.originY() + connector.y(),
|
||||
bounds.originZ() + connector.z(),
|
||||
state == null ? invalidMarker : state,
|
||||
state,
|
||||
chunkWorldX,
|
||||
chunkWorldZ);
|
||||
}
|
||||
}
|
||||
|
||||
private void paintHiddenConnectorFinalStates(
|
||||
TerrainChunk terrainChunk,
|
||||
ChunkCanvas canvas,
|
||||
JigsawStudioBay workcell,
|
||||
RenderedBay renderedBay,
|
||||
int chunkWorldX,
|
||||
@@ -671,14 +631,15 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator {
|
||||
for (RenderedBlock block : renderedBay.blocks()) {
|
||||
occupied.add(new RenderedPosition(block.x(), block.y(), block.z()));
|
||||
}
|
||||
BlockRegistry registry = pack.resources().blocks();
|
||||
JigsawStudioBounds bounds = workcell.bounds();
|
||||
for (RenderedConnector connector : renderedBay.connectors()) {
|
||||
if (occupied.contains(new RenderedPosition(connector.x(), connector.y(), connector.z()))) {
|
||||
continue;
|
||||
}
|
||||
PlatformBlockState finalState = B.getStateOrNull(connector.connector().getFinalState(), false);
|
||||
BlockState finalState = registry.find(connector.connector().getFinalState()).orElse(null);
|
||||
setWorldBlock(
|
||||
terrainChunk,
|
||||
canvas,
|
||||
bounds.originX() + connector.x(),
|
||||
bounds.originY() + connector.y(),
|
||||
bounds.originZ() + connector.z(),
|
||||
@@ -689,7 +650,7 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator {
|
||||
}
|
||||
|
||||
private void paintInvalidBay(
|
||||
TerrainChunk terrainChunk,
|
||||
ChunkCanvas canvas,
|
||||
JigsawStudioBay workcell,
|
||||
int chunkWorldX,
|
||||
int chunkWorldZ
|
||||
@@ -699,7 +660,7 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator {
|
||||
int length = Math.min(bounds.dimensions().width(), bounds.dimensions().depth());
|
||||
for (int offset = 0; offset < length; offset++) {
|
||||
setWorldBlock(
|
||||
terrainChunk,
|
||||
canvas,
|
||||
bounds.originX() + offset,
|
||||
y,
|
||||
bounds.originZ() + offset,
|
||||
@@ -707,7 +668,7 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator {
|
||||
chunkWorldX,
|
||||
chunkWorldZ);
|
||||
setWorldBlock(
|
||||
terrainChunk,
|
||||
canvas,
|
||||
bounds.maxX() - offset,
|
||||
y,
|
||||
bounds.originZ() + offset,
|
||||
@@ -766,10 +727,10 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator {
|
||||
return directionName(activeFront) + "_up";
|
||||
}
|
||||
|
||||
private static JigsawStudioCellDimensions rotatedDimensions(IrisObject object, int quarterTurns) {
|
||||
private static JigsawStudioCellDimensions rotatedDimensions(PlaceableObject object, int quarterTurns) {
|
||||
return Math.floorMod(quarterTurns, 2) == 0
|
||||
? new JigsawStudioCellDimensions(object.getW(), object.getH(), object.getD())
|
||||
: new JigsawStudioCellDimensions(object.getD(), object.getH(), object.getW());
|
||||
? new JigsawStudioCellDimensions(object.width(), object.height(), object.depth())
|
||||
: new JigsawStudioCellDimensions(object.depth(), object.height(), object.width());
|
||||
}
|
||||
|
||||
private static boolean fits(JigsawStudioCellDimensions object, JigsawStudioCellDimensions bay) {
|
||||
@@ -830,23 +791,23 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator {
|
||||
}
|
||||
|
||||
private void setWorldBlock(
|
||||
TerrainChunk terrainChunk,
|
||||
ChunkCanvas canvas,
|
||||
int worldX,
|
||||
int worldY,
|
||||
int worldZ,
|
||||
PlatformBlockState block,
|
||||
BlockState block,
|
||||
int chunkWorldX,
|
||||
int chunkWorldZ
|
||||
) {
|
||||
int localX = worldX - chunkWorldX;
|
||||
int localZ = worldZ - chunkWorldZ;
|
||||
if (localX < 0 || localX >= 16 || localZ < 0 || localZ >= 16) {
|
||||
if (localX < 0 || localX >= CHUNK_SIZE || localZ < 0 || localZ >= CHUNK_SIZE) {
|
||||
return;
|
||||
}
|
||||
if (worldY < terrainChunk.getMinHeight() || worldY >= terrainChunk.getMaxHeight()) {
|
||||
if (worldY < canvas.minY() || worldY >= canvas.maxY()) {
|
||||
return;
|
||||
}
|
||||
terrainChunk.setBlock(localX, worldY, localZ, block);
|
||||
canvas.set(localX, worldY, localZ, block);
|
||||
}
|
||||
|
||||
public record RenderedBay(
|
||||
@@ -883,7 +844,8 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator {
|
||||
}
|
||||
}
|
||||
|
||||
public record RenderedBlock(int x, int y, int z, PlatformBlockState state, TileData tileData) {
|
||||
/** A block of the object in the workcell, with the block entity it carries; the entity is null for a plain block. */
|
||||
public record RenderedBlock(int x, int y, int z, BlockState state, BlockEntityData blockEntity) {
|
||||
public RenderedBlock {
|
||||
state = Objects.requireNonNull(state, "Jigsaw Studio rendered block state");
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user