diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/IrisRuntime.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/IrisRuntime.java index 6437648c0..0c49e7b1f 100644 --- a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/IrisRuntime.java +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/IrisRuntime.java @@ -21,6 +21,7 @@ package art.arcane.iris; import art.arcane.iris.api.terrain.IrisTerrainService; import art.arcane.iris.command.CommandSVC; import art.arcane.iris.configuration.IrisSettings; +import art.arcane.iris.studio.app.StudioAppInstaller; import art.arcane.iris.configuration.SettingsHotloadWatch; import art.arcane.iris.diagnostics.LogFilterSVC; import art.arcane.iris.diagnostics.splash.IrisSplashComposer; @@ -976,6 +977,7 @@ public final class IrisRuntime implements IrisPluginRuntime { return; } BukkitGuiHost.install(); + StudioAppInstaller.installInBackground(); // super.onEnable() already registers this instance as a listener. plugin.enablePlugin(); if (IrisStartupValidation.isRestartRequired()) { diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/command/CommandStudio.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/command/CommandStudio.java index 67bd6a710..d1f734397 100644 --- a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/command/CommandStudio.java +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/command/CommandStudio.java @@ -24,6 +24,7 @@ import art.arcane.iris.configuration.IrisSettings; import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.studio.bridge.StudioBridge; import art.arcane.iris.studio.bridge.StudioBridges; +import art.arcane.iris.studio.bridge.StudioLaunch; import art.arcane.iris.studio.bridge.StudioWindow; import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.studio.workspace.IrisProject; @@ -105,6 +106,7 @@ import java.util.function.Consumer; import art.arcane.iris.localization.IrisLanguage; import art.arcane.iris.localization.BukkitCommandMessages; import art.arcane.volmlib.util.localization.MessageArgument; +import art.arcane.volmlib.util.localization.TextKey; import art.arcane.volmlib.util.localization.LanguageAudience; import art.arcane.iris.localization.BukkitCommandMessagesExtended; @Director(name = "studio", aliases = {"std", "s"}, description = "Studio Commands", descriptionKey = "iris.director.commandstudio.director.studio_commands") @@ -271,9 +273,7 @@ public class CommandStudio implements DirectorExecutor { @Param(name = "world", description = "The Iris world whose pack the noise explorer reads", descriptionKey = "iris.director.commandstudio.param.world_open_generator", contextual = true, contextualOverride = true) World world ) { - if (openStudioApp(world)) { - sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_NOISE_EXPLORER)); - } + openStudioApp(world, BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_NOISE_EXPLORER); } @Director(description = "Open the image-map studio (External GUI)", descriptionKey = "iris.director.commandstudio.director.open_image_map_studio_external_gui", aliases = {"imap"}) @@ -281,9 +281,7 @@ public class CommandStudio implements DirectorExecutor { @Param(name = "world", description = "The Iris world whose active pack receives image-map exports", descriptionKey = "iris.director.commandstudio.param.world_open_image_map_studio", contextual = true, contextualOverride = true) World world ) { - if (openStudioApp(world)) { - sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_IMAGE_MAP_STUDIO)); - } + openStudioApp(world, BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_IMAGE_MAP_STUDIO); } @Director(description = "Show loot if a chest were right here", descriptionKey = "iris.director.commandstudio.director.show_loot_if_chest_were_right_here", origin = DirectorOrigin.PLAYER, sync = true) @@ -415,9 +413,7 @@ public class CommandStudio implements DirectorExecutor { @Param(name = "world", description = "The world to open the generator for", descriptionKey = "iris.director.commandstudio.param.world_open_generator", contextual = true, contextualOverride = true) World world ) { - if (openStudioApp(world)) { - sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_MAP)); - } + openStudioApp(world, BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_MAP); } @Director(description = "Open the Iris Studio app on a world", descriptionKey = "iris.director.commandstudio.director.render_world_map_external_gui", aliases = "app") @@ -425,29 +421,37 @@ public class CommandStudio implements DirectorExecutor { @Param(name = "world", description = "The world to open the generator for", descriptionKey = "iris.director.commandstudio.param.world_open_generator", contextual = true, contextualOverride = true) World world ) { - if (openStudioApp(world)) { - sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_MAP)); - } + openStudioApp(world, BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_MAP); } - /** Opens the app on the world, or logs its link when no app is set up; false, after telling the sender why, when it could not. */ - private boolean openStudioApp(World world) { + /** Opens the app on the world; when it can't, tells the sender why and hands over the link to connect by hand. */ + private void openStudioApp(World world, TextKey openedMessage) { if (!IrisToolbelt.isIrisWorld(world)) { sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_YOU_NEED_BE_SPECIFY_IRIS_GENERATED_WORLD)); - return false; + return; } UUID openerId = sender().isPlayer() ? player().getUniqueId() : null; PlatformChunkGenerator generator = IrisToolbelt.access(world); + StudioBridge bridge; try { - StudioBridge bridge = StudioBridges.open(world.getName(), generator::getEngine, openerId); - if (!StudioWindow.show(bridge)) { - IrisLogging.info("Iris Studio link for %s: %s", world.getName(), bridge.link()); - } - return true; + bridge = StudioBridges.open(world.getName(), generator::getEngine, openerId); } catch (IOException error) { IrisLogging.warn("Could not open the studio bridge: %s", error.getMessage()); - return false; + return; } + StudioLaunch launch = StudioWindow.show(bridge); + if (launch.opened()) { + sender().sendMessage(IrisLanguage.text(openedMessage)); + return; + } + IrisLogging.info("Iris Studio link for %s: %s", world.getName(), bridge.link()); + sendStudioLink(launch, bridge.link()); + } + + private void sendStudioLink(StudioLaunch launch, String link) { + sender().sendMessage(C.RED + IrisLanguage.text(launch.failureMessage())); + sender().sendCopyButton(IrisLanguage.text(RuntimeUiMessages.STUDIO_LINK_COPY_BUTTON), + IrisLanguage.text(RuntimeUiMessages.STUDIO_LINK_COPY_HOVER), link); } @Director(description = "Profiles the performance of a dimension", descriptionKey = "iris.director.commandstudio.director.profiles_performance_dimension", origin = DirectorOrigin.PLAYER) diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedEngineBootstrap.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedEngineBootstrap.java index b2b94a0d9..f92cabd28 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedEngineBootstrap.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedEngineBootstrap.java @@ -46,6 +46,7 @@ import art.arcane.volmlib.nativelib.minecraft26_2.modded.NativeEntityBehavior; import art.arcane.volmlib.nativelib.minecraft26_2.modded.NativeStateMerger; import art.arcane.volmlib.nativelib.minecraft26_2.modded.ModdedServerAccess; +import art.arcane.iris.studio.app.StudioAppInstaller; import art.arcane.iris.studio.view.GuiHost; import art.arcane.iris.localization.IrisLanguage; import art.arcane.iris.generation.decoration.DecoratorPlatformHooks; @@ -492,6 +493,7 @@ public final class ModdedEngineBootstrap { GuiHost.Provider previousGuiHost = GuiHost.get(); ModdedGuiHost.install(); rollback.add(() -> GuiHost.set(previousGuiHost)); + StudioAppInstaller.installInBackground(); ModdedDecoratorHooks decoratorHooks = new ModdedDecoratorHooks(); DecoratorPlatformHooks.Bindings previousDecoratorBindings = DecoratorPlatformHooks.bind(decoratorHooks, decoratorHooks); diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedStudioCommands.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedStudioCommands.java index 834bdc772..53f04f6ea 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedStudioCommands.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedStudioCommands.java @@ -26,6 +26,7 @@ import art.arcane.iris.configuration.IrisSettings; import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.studio.bridge.StudioBridge; import art.arcane.iris.studio.bridge.StudioBridges; +import art.arcane.iris.studio.bridge.StudioLaunch; import art.arcane.iris.studio.bridge.StudioWindow; import art.arcane.iris.studio.view.GuiHost; import art.arcane.iris.pack.loading.IrisData; @@ -95,6 +96,9 @@ import java.util.regex.Pattern; import java.util.stream.Stream; import art.arcane.iris.localization.IrisLanguage; +import art.arcane.iris.localization.RuntimeUiMessages; +import art.arcane.volmlib.nativelib.minecraft26_2.modded.NativeCommandText; +import art.arcane.volmlib.nativelib.minecraft26_2.modded.NativeCommandText.Format; import art.arcane.iris.modded.localization.ModdedCommandMessages; import art.arcane.volmlib.util.localization.LanguageAudience; import art.arcane.volmlib.util.localization.MessageArgument; @@ -273,7 +277,7 @@ public final class ModdedStudioCommands { )); } - /** Opens the studio app on the source's world, or logs its link when no app is set up. */ + /** Opens the studio app on the source's world; when it can't, tells the source why and hands over the link to connect by hand. */ private static int openStudioApp(NativeCommandSource source, Engine engine, String openedMessage) { if (GuiHost.isDesktopSuppressed()) { IrisModdedCommands.fail(source, guiUnavailableMessage()); @@ -283,19 +287,35 @@ public final class ModdedStudioCommands { NativeProtocolPlayer player = source.player(); UUID openerId = player == null ? null : player.id(); ModdedGuiHost.bindContext(worldView(source.server(), level), engine, openerId); + StudioBridge bridge; try { - StudioBridge bridge = StudioBridges.open(level.name(), () -> engine, openerId); - if (!StudioWindow.show(bridge)) { - IrisLogging.info("Iris Studio link for %s: %s", level.name(), bridge.link()); - } + bridge = StudioBridges.open(level.name(), () -> engine, openerId); } catch (IOException error) { IrisModdedCommands.fail(source, "Could not open the studio bridge: " + error.getMessage()); return 0; } + StudioLaunch launch = StudioWindow.show(bridge); + if (!launch.opened()) { + IrisLogging.info("Iris Studio link for %s: %s", level.name(), bridge.link()); + sendStudioLink(source, launch, bridge.link()); + return 0; + } IrisModdedCommands.ok(source, openedMessage); return 1; } + private static void sendStudioLink(NativeCommandSource source, StudioLaunch launch, String link) { + IrisModdedCommands.fail(source, IrisLanguage.plain(launch.failureMessage())); + if (source.player() == null) { + return; + } + NativeCommandText hover = NativeCommandText.literal(IrisLanguage.plain(RuntimeUiMessages.STUDIO_LINK_COPY_HOVER)); + NativeCommandText button = NativeCommandText.literal(IrisLanguage.plain(RuntimeUiMessages.STUDIO_LINK_COPY_BUTTON)) + .withStyle(Format.GREEN) + .withStyle(style -> style.copyToClipboard(link).hover(hover)); + IrisModdedCommands.ok(source, button); + } + private static LiteralArgumentBuilder workspaceTree(String name, boolean open) { return NativeCommandRegistration.literal(name) .executes(ModdedCommandTree.localized((CommandContext context) -> workspace(context.getSource(), null, open))) diff --git a/build.gradle b/build.gradle index 8e8dc4253..d3bd0a7f4 100644 --- a/build.gradle +++ b/build.gradle @@ -190,6 +190,63 @@ def generateNoiseNatives = tasks.register('generateNoiseNatives') { } } } +// The studio app ships inside the Bukkit jar. The Electron build it runs on is 100+ MB per platform, so it stays out +// and is pinned instead: StudioAppInstaller downloads the host's archive from Electron's release at startup and +// checks it against these checksums. +File studioAppDirectory = file('studio') +List electronPlatforms = ['linux-x64', 'linux-arm64', 'win32-x64', 'win32-arm64', 'darwin-x64', 'darwin-arm64'] +Provider electronVersion = providers.fileContents(layout.projectDirectory.file('studio/package-lock.json')).asText.map { String lock -> + (String) ((Map) ((Map) new groovy.json.JsonSlurper().parseText(lock)).packages).get('node_modules/electron').version +} +List npmCommand = System.getProperty('os.name').toLowerCase(Locale.ROOT).contains('win') ? ['cmd', '/c', 'npm'] : ['npm'] +def installStudioDependencies = tasks.register('installStudioDependencies', Exec) { + inputs.files('studio/package.json', 'studio/package-lock.json') + outputs.file('studio/node_modules/.package-lock.json') + workingDir(studioAppDirectory) + commandLine(npmCommand + ['ci', '--no-audit', '--no-fund']) +} +def buildStudioApp = tasks.register('buildStudioApp', Exec) { + dependsOn(installStudioDependencies) + inputs.dir('studio/src') + inputs.files('studio/package.json', 'studio/package-lock.json', 'studio/electron.vite.config.ts', 'studio/tsconfig.json', 'studio/components.json') + outputs.dir('studio/out') + workingDir(studioAppDirectory) + commandLine(npmCommand + ['run', 'build']) +} +def bundleStudioApp = tasks.register('bundleStudioApp', Zip) { + from(buildStudioApp) { + into('out') + } + from('studio/package.json') + archiveFileName.set('studio-app.zip') + destinationDirectory.set(layout.buildDirectory.dir('generated/studio-app')) + preserveFileTimestamps = false + reproducibleFileOrder = true +} +def pinElectronRuntime = tasks.register('pinElectronRuntime') { + inputs.property('electronVersion', electronVersion) + inputs.property('platforms', electronPlatforms) + def pins = layout.buildDirectory.file('generated/studio-app-pins/studio-app.properties') + outputs.file(pins) + doLast { + String version = electronVersion.get() + String checksums = URI.create("https://github.com/electron/electron/releases/download/v${version}/SHASUMS256.txt") + .toURL().getText('UTF-8') + Map checksumByArchive = checksums.readLines().collectEntries { String line -> + def match = line.trim() =~ /^([0-9a-f]{64}) \*?(\S+)$/ + match.matches() ? [(match.group(2)): match.group(1)] : [:] + } + List lines = ["electron.version=${version}".toString()] + electronPlatforms.each { String platform -> + String checksum = checksumByArchive.get("electron-v${version}-${platform}.zip".toString()) + if (checksum == null) { + throw new GradleException("Electron ${version} publishes no ${platform} archive") + } + lines.add("${platform}.sha256=${checksum}".toString()) + } + pins.get().asFile.setText(lines.join('\n') + '\n', 'UTF-8') + } +} def jarJar = configurations.create('jarJar') dependencies { add('included', project(path: ':core', configuration: 'shadow')) @@ -208,6 +265,12 @@ tasks.named('jar', Jar).configure { duplicatesStrategy = DuplicatesStrategy.EXCLUDE includeEmptyDirs = false from(jarJar) + from(bundleStudioApp) { + into('META-INF/iris') + } + from(pinElectronRuntime) { + into('META-INF/iris') + } from(provider { included.resolve().collect { zipTree(it) } }) { exclude('META-INF/INDEX.LIST') exclude('languages/**') @@ -529,6 +592,8 @@ List requiredBukkitArtifactEntries = [ 'slimjar-resolutions.dat', 'META-INF/iris/native-runtime.properties', NoiseNativeArtifacts.MANIFEST, + 'META-INF/iris/studio-app.zip', + 'META-INF/iris/studio-app.properties', 'META-INF/volmit/volmlib.properties', 'iris-language-source.properties', 'agent.jar', diff --git a/core/src/externalProviderTest/java/art/arcane/iris/integration/data/CraftEngineDataProviderTest.java b/core/src/externalProviderTest/java/art/arcane/iris/integration/data/CraftEngineDataProviderTest.java index e5bd73717..9d02911a7 100644 --- a/core/src/externalProviderTest/java/art/arcane/iris/integration/data/CraftEngineDataProviderTest.java +++ b/core/src/externalProviderTest/java/art/arcane/iris/integration/data/CraftEngineDataProviderTest.java @@ -28,6 +28,7 @@ import org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.Location; import org.bukkit.Material; +import org.bukkit.NamespacedKey; import org.bukkit.block.Block; import org.bukkit.block.data.BlockData; import org.bukkit.entity.Entity; @@ -35,6 +36,7 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.Plugin; import org.junit.Test; import org.mockito.MockedStatic; +import org.mockito.Mockito; import java.util.List; import java.util.Map; @@ -196,6 +198,68 @@ public class CraftEngineDataProviderTest { } } + @Test + public void decayingCustomLeavesAreMadePersistentAndKeepTheirCustomIdentity() { + BooleanProperty persistent = BooleanProperty.create("persistent", false); + BlockDefinition definition = mock(BlockDefinition.class); + ImmutableBlockState decaying = blockState(definition, "test:leaves[persistent=false]"); + ImmutableBlockState kept = blockState(definition, "test:leaves[persistent=true]"); + BlockData base = mock(BlockData.class); + BlockData keptBase = mock(BlockData.class); + doReturn(persistent).when(decaying).getProperty("persistent"); + doReturn(false).when(decaying).get(persistent); + when(decaying.with(persistent, true)).thenReturn(kept); + try (MockedStatic blocks = mockStatic(CraftEngineBlocks.class)) { + blocks.when(() -> CraftEngineBlocks.getCustomBlockState(base)).thenReturn(decaying); + blocks.when(() -> CraftEngineBlocks.getBukkitBlockData(kept)).thenReturn(keptBase); + + IrisCustomData result = (IrisCustomData) new CraftEngineDataProvider() + .withoutDecay(IrisCustomData.of(base, new Identifier("craftengine", "test/leaves[persistent=false]"))); + + assertSame(keptBase, result.getBase()); + assertEquals(new Identifier("test", "leaves[persistent=true]"), result.getCustom()); + } + } + + @Test + public void persistentOrDecaylessCustomBlocksAreKeptAsTheyAre() { + BooleanProperty persistent = BooleanProperty.create("persistent", false); + BlockDefinition definition = mock(BlockDefinition.class); + ImmutableBlockState alreadyPersistent = blockState(definition, "test:leaves[persistent=true]"); + ImmutableBlockState withoutProperty = blockState(definition, "test:log"); + BlockData persistentData = mock(BlockData.class); + BlockData logData = mock(BlockData.class); + BlockData vanilla = mock(BlockData.class); + doReturn(persistent).when(alreadyPersistent).getProperty("persistent"); + doReturn(true).when(alreadyPersistent).get(persistent); + try (MockedStatic blocks = mockStatic(CraftEngineBlocks.class)) { + blocks.when(() -> CraftEngineBlocks.getCustomBlockState(persistentData)).thenReturn(alreadyPersistent); + blocks.when(() -> CraftEngineBlocks.getCustomBlockState(logData)).thenReturn(withoutProperty); + CraftEngineDataProvider provider = new CraftEngineDataProvider(); + + assertSame(persistentData, provider.withoutDecay(persistentData)); + assertSame(logData, provider.withoutDecay(logData)); + assertSame(vanilla, provider.withoutDecay(vanilla)); + } + } + + @Test + public void customBlocksCarryTheTagsTheirSettingsListEvenWhenWrapped() { + ImmutableBlockState state = mock(ImmutableBlockState.class, Mockito.RETURNS_DEEP_STUBS); + BlockData base = mock(BlockData.class); + BlockData vanilla = mock(BlockData.class); + when(state.settings().tags()).thenReturn(Set.of(Key.of("minecraft:logs"))); + try (MockedStatic blocks = mockStatic(CraftEngineBlocks.class)) { + blocks.when(() -> CraftEngineBlocks.getCustomBlockState(base)).thenReturn(state); + CraftEngineDataProvider provider = new CraftEngineDataProvider(); + BlockData wrapped = IrisCustomData.of(base, new Identifier("craftengine", "test/log")); + + assertTrue(provider.hasBlockTag(wrapped, NamespacedKey.minecraft("logs"))); + assertFalse(provider.hasBlockTag(wrapped, NamespacedKey.minecraft("leaves"))); + assertFalse(provider.hasBlockTag(vanilla, NamespacedKey.minecraft("logs"))); + } + } + @Test public void unknownOrInvalidBlockPropertiesFailBeforeNativeConversion() { Identifier id = new Identifier("test", "lamp"); diff --git a/core/src/main/java/art/arcane/iris/configuration/IrisSettings.java b/core/src/main/java/art/arcane/iris/configuration/IrisSettings.java index efd8d9523..daf405cf4 100644 --- a/core/src/main/java/art/arcane/iris/configuration/IrisSettings.java +++ b/core/src/main/java/art/arcane/iris/configuration/IrisSettings.java @@ -404,6 +404,7 @@ public class IrisSettings { public boolean disableTimeAndWeather = true; public boolean entitySpawning = true; public boolean autoStartDefaultStudio = false; + public boolean downloadApp = true; public String studioApp = ""; public String electron = "electron"; } diff --git a/core/src/main/java/art/arcane/iris/generation/block/B.java b/core/src/main/java/art/arcane/iris/generation/block/B.java index 7686f7a62..f9bdbd994 100644 --- a/core/src/main/java/art/arcane/iris/generation/block/B.java +++ b/core/src/main/java/art/arcane/iris/generation/block/B.java @@ -84,6 +84,14 @@ public class B { return state != null && state.isTreeBlock(); } + public static boolean isLog(NativeBlockState state) { + return state != null && state.isLog(); + } + + public static boolean isLeaves(NativeBlockState state) { + return state != null && state.isLeaves(); + } + public static boolean isFoliagePlantable(NativeBlockState state) { return state != null && state.isFoliagePlantable(); } diff --git a/core/src/main/java/art/arcane/iris/generation/noise/IrisNoiseGenerator.java b/core/src/main/java/art/arcane/iris/generation/noise/IrisNoiseGenerator.java index 1ea234e8c..8589d0f21 100644 --- a/core/src/main/java/art/arcane/iris/generation/noise/IrisNoiseGenerator.java +++ b/core/src/main/java/art/arcane/iris/generation/noise/IrisNoiseGenerator.java @@ -62,6 +62,9 @@ public class IrisNoiseGenerator { private static final long GENERATOR_SEED_SALT = 33_955_677L; private static final int MINIMUM_FRACTURE_DEPTH = 4; private static final int MAXIMUM_FRACTURE_NODES = 32; + // Fracture axes as CNG.reseededForAxis numbers them for a 2D read: x is axis 0, z is axis 1. + static final int X_AXIS = 0; + static final int Z_AXIS = 1; private static final ThreadLocal FRACTURE_SAMPLES = ThreadLocal.withInitial(FractureSamples::new); @Getter(AccessLevel.NONE) @@ -144,6 +147,14 @@ public class IrisNoiseGenerator { } double getNoise(long superSeed, double xv, double zv, IrisData data, Engine engine) { + return getNoiseForAxis(superSeed, xv, zv, data, engine, X_AXIS); + } + + /** + * This layer read as the fracture of one axis. Each axis samples this layer's generator reseeded for that axis at + * the same coordinates, so the x and z warps are uncorrelated instead of mirror images of each other. + */ + private double getNoiseForAxis(long superSeed, double xv, double zv, IrisData data, Engine engine, int axis) { if (!enabled) { return offsetY; } @@ -154,7 +165,7 @@ public class IrisNoiseGenerator { samples.active = true; try { if (samples.prepare(this, superSeed, data, engine)) { - return samples.sample(xv, zv); + return samples.sample(xv, zv, axis); } } finally { samples.clear(); @@ -169,13 +180,13 @@ public class IrisNoiseGenerator { for (IrisNoiseGenerator i : fracture) { if (i.isEnabled()) { double fractureOffset = i.getOpacity() / 2D; - x += i.getNoise(superSeed + seed + g, xv, zv, data, engine) - fractureOffset; - z += i.getNoise(superSeed + seed + g, zv, xv, data, engine) - fractureOffset; + x += i.getNoiseForAxis(superSeed + seed + g, xv, zv, data, engine, X_AXIS) - fractureOffset; + z += i.getNoiseForAxis(superSeed + seed + g, xv, zv, data, engine, Z_AXIS) - fractureOffset; } g += 819; } - return sample(getGenerator(superSeed, data, engine), x, z); + return sample(getGenerator(superSeed, data, engine).reseededForAxis(axis), x, z); } boolean supportsBatch() { @@ -200,6 +211,10 @@ public class IrisNoiseGenerator { } NoiseLayerProgram compileProgram(long superSeed, IrisData data, Engine engine) { + return compileProgram(superSeed, data, engine, false); + } + + private NoiseLayerProgram compileProgram(long superSeed, IrisData data, Engine engine, boolean readAsFracture) { if (!enabled) { return NoiseLayerProgram.disabled(this); } @@ -215,13 +230,14 @@ public class IrisNoiseGenerator { int compiled = 0; for (IrisNoiseGenerator child : fracture) { if (child.isEnabled()) { - children[compiled] = child.compileProgram(superSeed + seed + salt, data, engine); + children[compiled] = child.compileProgram(superSeed + seed + salt, data, engine, true); offsets[compiled++] = child.getOpacity() / 2D; } salt += 819; } CNG generator = Objects.requireNonNull(getGenerator(superSeed, data, engine), "Noise layer generator"); - return NoiseLayerProgram.of(this, NoiseProgram.compile2D(generator), children, offsets); + NoiseProgram zAxisProgram = readAsFracture ? NoiseProgram.compile2D(generator.reseededForAxis(Z_AXIS)) : null; + return NoiseLayerProgram.of(this, NoiseProgram.compile2D(generator), zAxisProgram, children, offsets); } public KList getAllComposites() { @@ -357,20 +373,26 @@ public class IrisNoiseGenerator { return false; } - private double sample(double x, double z) { + /** + * Both axes of a fracture node read the same warped coordinates, since a reseeded generator shares the + * node's own fracture, so each level samples its generator once per axis. + */ + private double sample(double x, double z, int rootAxis) { int leaf = size - 1; - double forward = nodes[leaf].sample(generators[leaf], x, z); - double reverse = nodes[leaf].sample(generators[leaf], z, x); - for (int index = leaf - 1; index >= 0; index--) { - double offset = nodes[index + 1].opacity / 2D; - double forwardX = x + (forward - offset); - double forwardZ = z + (reverse - offset); - forward = nodes[index].sample(generators[index], forwardX, forwardZ); - if (index > 0) { - reverse = nodes[index].sample(generators[index], forwardZ, forwardX); - } + if (leaf == 0) { + return nodes[0].sample(generators[0].reseededForAxis(rootAxis), x, z); } - return forward; + double warpX = nodes[leaf].sample(generators[leaf], x, z); + double warpZ = nodes[leaf].sample(generators[leaf].reseededForAxis(Z_AXIS), x, z); + for (int index = leaf - 1; index > 0; index--) { + double offset = nodes[index + 1].opacity / 2D; + double warpedX = x + (warpX - offset); + double warpedZ = z + (warpZ - offset); + warpX = nodes[index].sample(generators[index], warpedX, warpedZ); + warpZ = nodes[index].sample(generators[index].reseededForAxis(Z_AXIS), warpedX, warpedZ); + } + double offset = nodes[1].opacity / 2D; + return nodes[0].sample(generators[0].reseededForAxis(rootAxis), x + (warpX - offset), z + (warpZ - offset)); } private void clear() { diff --git a/core/src/main/java/art/arcane/iris/generation/noise/NoiseLayerProgram.java b/core/src/main/java/art/arcane/iris/generation/noise/NoiseLayerProgram.java index c5528d10a..25cfc1170 100644 --- a/core/src/main/java/art/arcane/iris/generation/noise/NoiseLayerProgram.java +++ b/core/src/main/java/art/arcane/iris/generation/noise/NoiseLayerProgram.java @@ -9,6 +9,7 @@ public final class NoiseLayerProgram { private final boolean enabled; private final double offsetY; private final NoiseProgram program; + private final NoiseProgram zAxisProgram; private final double zoom; private final double opacity; private final double offsetX; @@ -21,10 +22,12 @@ public final class NoiseLayerProgram { private final NoiseLayerProgram[] children; private final double[] childOffsets; - private NoiseLayerProgram(IrisNoiseGenerator layer, NoiseProgram program, NoiseLayerProgram[] children, double[] childOffsets) { + private NoiseLayerProgram(IrisNoiseGenerator layer, NoiseProgram program, NoiseProgram zAxisProgram, + NoiseLayerProgram[] children, double[] childOffsets) { this.enabled = program != null; this.offsetY = layer.getOffsetY(); this.program = program; + this.zAxisProgram = zAxisProgram; this.zoom = layer.getZoom(); this.opacity = layer.getOpacity(); this.offsetX = layer.getOffsetX(); @@ -39,11 +42,16 @@ public final class NoiseLayerProgram { } static NoiseLayerProgram disabled(IrisNoiseGenerator layer) { - return new NoiseLayerProgram(layer, null, new NoiseLayerProgram[0], new double[0]); + return new NoiseLayerProgram(layer, null, null, new NoiseLayerProgram[0], new double[0]); } - static NoiseLayerProgram of(IrisNoiseGenerator layer, NoiseProgram program, NoiseLayerProgram[] children, double[] childOffsets) { - return new NoiseLayerProgram(layer, program, children, childOffsets); + /** + * zAxisProgram is the layer's generator reseeded for the z axis; only a layer read as a fracture needs it, and the + * root layer passes null. + */ + static NoiseLayerProgram of(IrisNoiseGenerator layer, NoiseProgram program, NoiseProgram zAxisProgram, + NoiseLayerProgram[] children, double[] childOffsets) { + return new NoiseLayerProgram(layer, program, zAxisProgram, children, childOffsets); } public void evaluate(TerrainBatchScratch scratch, double[] xs, double[] zs, int count, double[] out) { @@ -53,143 +61,110 @@ public final class NoiseLayerProgram { } int mark = scratch.mark(); try { - fill(scratch, xs, zs, count, out); + double[] sampleX = scratch.buffer(count); + double[] sampleZ = scratch.buffer(count); + warpedSampleCoordinates(scratch, xs, zs, count, sampleX, sampleZ); + program.fill2D(scratch.noise(), sampleX, sampleZ, count, out); + applyPost(out, count); } finally { scratch.reset(mark); } } - private void fill(TerrainBatchScratch scratch, double[] xs, double[] zs, int count, double[] out) { - double[] sampleX = scratch.buffer(count); - double[] sampleZ = scratch.buffer(count); - if (children.length == 0) { - for (int index = 0; index < count; index++) { - sampleX[index] = (xs[index] / zoom) + offsetX; - sampleZ[index] = (zs[index] / zoom) + offsetZ; - } - } else { - System.arraycopy(xs, 0, sampleX, 0, count); - System.arraycopy(zs, 0, sampleZ, 0, count); - double[] forward = scratch.buffer(count); - double[] reverse = scratch.buffer(count); - for (int child = 0; child < children.length; child++) { - children[child].evaluatePair(scratch, xs, zs, count, forward, reverse); - double offset = childOffsets[child]; - for (int index = 0; index < count; index++) { - sampleX[index] += forward[index] - offset; - sampleZ[index] += reverse[index] - offset; - } - } - for (int index = 0; index < count; index++) { - sampleX[index] = (sampleX[index] / zoom) + offsetX; - sampleZ[index] = (sampleZ[index] / zoom) + offsetZ; - } - } - program.fill2D(scratch.noise(), sampleX, sampleZ, count, out); - for (int index = 0; index < count; index++) { - out[index] = post(out[index]); - } - } - - void evaluatePair(TerrainBatchScratch scratch, double[] xs, double[] zs, int count, double[] forward, double[] reverse) { + /** Fills this layer read as a fracture: the x warp from its generator, the z warp from its z-axis generator. */ + void evaluateAxes(TerrainBatchScratch scratch, double[] xs, double[] zs, int count, double[] xWarp, double[] zWarp) { if (!enabled) { - Arrays.fill(forward, 0, count, offsetY); - Arrays.fill(reverse, 0, count, offsetY); + Arrays.fill(xWarp, 0, count, offsetY); + Arrays.fill(zWarp, 0, count, offsetY); return; } int mark = scratch.mark(); try { - fillPair(scratch, xs, zs, count, forward, reverse); + double[] sampleX = scratch.buffer(count); + double[] sampleZ = scratch.buffer(count); + warpedSampleCoordinates(scratch, xs, zs, count, sampleX, sampleZ); + program.fill2D(scratch.noise(), sampleX, sampleZ, count, xWarp); + zAxisProgram.fill2D(scratch.noise(), sampleX, sampleZ, count, zWarp); + applyPost(xWarp, count); + applyPost(zWarp, count); } finally { scratch.reset(mark); } } - private void fillPair(TerrainBatchScratch scratch, double[] xs, double[] zs, int count, double[] forward, double[] reverse) { - int pairs = count * 2; - double[] sampleX = scratch.buffer(pairs); - double[] sampleZ = scratch.buffer(pairs); + private void warpedSampleCoordinates(TerrainBatchScratch scratch, double[] xs, double[] zs, int count, + double[] sampleX, double[] sampleZ) { System.arraycopy(xs, 0, sampleX, 0, count); System.arraycopy(zs, 0, sampleZ, 0, count); - System.arraycopy(zs, 0, sampleX, count, count); - System.arraycopy(xs, 0, sampleZ, count, count); if (children.length > 0) { - double[] childForward = scratch.buffer(count); - double[] childReverse = scratch.buffer(count); + double[] childX = scratch.buffer(count); + double[] childZ = scratch.buffer(count); for (int child = 0; child < children.length; child++) { - children[child].evaluatePair(scratch, xs, zs, count, childForward, childReverse); + children[child].evaluateAxes(scratch, xs, zs, count, childX, childZ); double offset = childOffsets[child]; for (int index = 0; index < count; index++) { - sampleX[index] += childForward[index] - offset; - sampleZ[index] += childReverse[index] - offset; - sampleX[count + index] += childReverse[index] - offset; - sampleZ[count + index] += childForward[index] - offset; + sampleX[index] += childX[index] - offset; + sampleZ[index] += childZ[index] - offset; } } } - for (int index = 0; index < pairs; index++) { + for (int index = 0; index < count; index++) { sampleX[index] = (sampleX[index] / zoom) + offsetX; sampleZ[index] = (sampleZ[index] / zoom) + offsetZ; } - double[] values = scratch.buffer(pairs); - program.fill2D(scratch.noise(), sampleX, sampleZ, pairs, values); - for (int index = 0; index < count; index++) { - forward[index] = post(values[index]); - reverse[index] = post(values[count + index]); - } } public double sample(TerrainBatchScratch scratch, double x, double z) { if (!enabled) { return offsetY; } - double sampleX = x; - double sampleZ = z; - if (children.length > 0) { - int mark = scratch.mark(); - try { - double[] pair = scratch.buffer(2); - for (int child = 0; child < children.length; child++) { - children[child].samplePair(scratch, x, z, pair); - double offset = childOffsets[child]; - sampleX += pair[0] - offset; - sampleZ += pair[1] - offset; - } - } finally { - scratch.reset(mark); - } + int mark = scratch.mark(); + try { + double[] sampleCoordinates = scratch.buffer(2); + warpedSampleCoordinate(scratch, x, z, sampleCoordinates); + return post(program.sample2D(sampleCoordinates[0], sampleCoordinates[1])); + } finally { + scratch.reset(mark); } - return post(program.sample2D((sampleX / zoom) + offsetX, (sampleZ / zoom) + offsetZ)); } - private void samplePair(TerrainBatchScratch scratch, double x, double z, double[] out) { + private void sampleAxes(TerrainBatchScratch scratch, double x, double z, double[] out) { if (!enabled) { out[0] = offsetY; out[1] = offsetY; return; } - double forwardX = x; - double forwardZ = z; - double reverseX = z; - double reverseZ = x; + int mark = scratch.mark(); + try { + double[] sampleCoordinates = scratch.buffer(2); + warpedSampleCoordinate(scratch, x, z, sampleCoordinates); + out[0] = post(program.sample2D(sampleCoordinates[0], sampleCoordinates[1])); + out[1] = post(zAxisProgram.sample2D(sampleCoordinates[0], sampleCoordinates[1])); + } finally { + scratch.reset(mark); + } + } + + private void warpedSampleCoordinate(TerrainBatchScratch scratch, double x, double z, double[] out) { + double sampleX = x; + double sampleZ = z; if (children.length > 0) { - int mark = scratch.mark(); - try { - double[] pair = scratch.buffer(2); - for (int child = 0; child < children.length; child++) { - children[child].samplePair(scratch, x, z, pair); - double offset = childOffsets[child]; - forwardX += pair[0] - offset; - forwardZ += pair[1] - offset; - reverseX += pair[1] - offset; - reverseZ += pair[0] - offset; - } - } finally { - scratch.reset(mark); + double[] warp = scratch.buffer(2); + for (int child = 0; child < children.length; child++) { + children[child].sampleAxes(scratch, x, z, warp); + double offset = childOffsets[child]; + sampleX += warp[0] - offset; + sampleZ += warp[1] - offset; } } - out[0] = post(program.sample2D((forwardX / zoom) + offsetX, (forwardZ / zoom) + offsetZ)); - out[1] = post(program.sample2D((reverseX / zoom) + offsetX, (reverseZ / zoom) + offsetZ)); + out[0] = (sampleX / zoom) + offsetX; + out[1] = (sampleZ / zoom) + offsetZ; + } + + private void applyPost(double[] values, int count) { + for (int index = 0; index < count; index++) { + values[index] = post(values[index]); + } } private double post(double raw) { diff --git a/core/src/main/java/art/arcane/iris/integration/ExternalDataProvider.java b/core/src/main/java/art/arcane/iris/integration/ExternalDataProvider.java index 2524cf0e7..43ce00405 100644 --- a/core/src/main/java/art/arcane/iris/integration/ExternalDataProvider.java +++ b/core/src/main/java/art/arcane/iris/integration/ExternalDataProvider.java @@ -14,6 +14,7 @@ import lombok.NonNull; import lombok.RequiredArgsConstructor; import org.bukkit.Bukkit; import org.bukkit.Location; +import org.bukkit.NamespacedKey; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.data.BlockData; @@ -128,6 +129,25 @@ public abstract class ExternalDataProvider { return false; } + /** + * @param data The block to keep, possibly an {@link IrisCustomData} this provider returned from {@link #getBlockData} + * @return The block made to never decay, like custom leaves, or {@code data} itself when it is not one of the + * provider's decaying blocks + */ + @NotNull + public BlockData withoutDecay(@NotNull BlockData data) { + return data; + } + + /** + * @param data The block to check, possibly an {@link IrisCustomData} this provider returned from {@link #getBlockData} + * @param tag A block tag, like {@code minecraft:logs} + * @return Whether the block is one of the provider's blocks and carries that tag + */ + public boolean hasBlockTag(@NotNull BlockData data, @NotNull NamespacedKey tag) { + return false; + } + /** * Spawns a mob in the specified location using the given engine and entity identifier. * diff --git a/core/src/main/java/art/arcane/iris/integration/ExternalDataSVC.java b/core/src/main/java/art/arcane/iris/integration/ExternalDataSVC.java index 2fed55c79..2a2247a07 100644 --- a/core/src/main/java/art/arcane/iris/integration/ExternalDataSVC.java +++ b/core/src/main/java/art/arcane/iris/integration/ExternalDataSVC.java @@ -30,6 +30,7 @@ import art.arcane.volmlib.util.collection.KMap; import art.arcane.iris.platform.bukkit.plugin.IrisService; import org.bukkit.Bukkit; import org.bukkit.Location; +import org.bukkit.NamespacedKey; import org.bukkit.block.Block; import org.bukkit.block.data.BlockData; import org.bukkit.entity.Entity; @@ -193,6 +194,26 @@ public class ExternalDataSVC implements IrisService { return blockData; } + /** The block made to never decay by the provider it belongs to, or {@code data} itself. */ + public BlockData withoutDecay(BlockData data) { + for (ExternalDataProvider provider : activeProviders) { + BlockData kept = provider.withoutDecay(data); + if (kept == data) { + continue; + } + if (kept instanceof IrisCustomData custom && data instanceof IrisCustomData) { + return IrisCustomData.of(custom.getBase(), qualifyBlockId(provider, custom.getCustom())); + } + return kept; + } + return data; + } + + /** Whether {@code data} is a provider's block carrying {@code tag}. */ + public boolean hasBlockTag(BlockData data, NamespacedKey tag) { + return activeProviders.stream().anyMatch(provider -> provider.hasBlockTag(data, tag)); + } + public Optional getBlockData(final Identifier key) { Pair> pair; try { diff --git a/core/src/main/java/art/arcane/iris/integration/data/CraftEngineDataProvider.java b/core/src/main/java/art/arcane/iris/integration/data/CraftEngineDataProvider.java index 0fd0ec657..96c00ed63 100644 --- a/core/src/main/java/art/arcane/iris/integration/data/CraftEngineDataProvider.java +++ b/core/src/main/java/art/arcane/iris/integration/data/CraftEngineDataProvider.java @@ -30,6 +30,7 @@ import net.momirealms.craftengine.core.util.Key; import org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.Location; +import org.bukkit.NamespacedKey; import org.bukkit.block.Block; import org.bukkit.block.data.BlockData; import org.bukkit.entity.Entity; @@ -57,6 +58,7 @@ public class CraftEngineDataProvider extends ExternalDataProvider implements Lis BlockProperty.ofBoolean("randomPitch", false), BlockProperty.ofDouble("pitch", 0, 0, 360f, false, true) ); + private static final String PERSISTENT_PROPERTY = "persistent"; private static final ContentRegistry EMPTY_CONTENT = new ContentRegistry(Set.of(), Set.of(), false); private volatile ContentRegistry content = EMPTY_CONTENT; @@ -131,6 +133,32 @@ public class CraftEngineDataProvider extends ExternalDataProvider implements Lis return state == null || state.isEmpty() ? Optional.empty() : Optional.of(Identifier.fromString(state.toString())); } + @Override + public @NotNull BlockData withoutDecay(@NotNull BlockData data) { + ImmutableBlockState state = customStateOf(data); + if (state == null) { + return data; + } + Property persistent = state.getProperty(PERSISTENT_PROPERTY); + if (persistent == null || persistent.valueClass() != Boolean.class || state.get(persistent)) { + return data; + } + ImmutableBlockState kept = state.with(persistent, true); + return IrisCustomData.of(CraftEngineBlocks.getBukkitBlockData(kept), Identifier.fromString(kept.toString())); + } + + @Override + public boolean hasBlockTag(@NotNull BlockData data, @NotNull NamespacedKey tag) { + ImmutableBlockState state = customStateOf(data); + return state != null && state.settings().tags().contains(Key.of(tag.getNamespace(), tag.getKey())); + } + + private static ImmutableBlockState customStateOf(BlockData data) { + BlockData nativeData = data instanceof IrisCustomData custom ? custom.getBase() : data; + ImmutableBlockState state = CraftEngineBlocks.getCustomBlockState(nativeData); + return state == null || state.isEmpty() ? null : state; + } + @Override public boolean placeBlock(@NotNull Block block, @NotNull Identifier blockId) { Pair> parsed = ExternalDataSVC.parseState(blockId); diff --git a/core/src/main/java/art/arcane/iris/localization/RuntimeUiMessages.java b/core/src/main/java/art/arcane/iris/localization/RuntimeUiMessages.java index e23f378a6..a5055f3b2 100644 --- a/core/src/main/java/art/arcane/iris/localization/RuntimeUiMessages.java +++ b/core/src/main/java/art/arcane/iris/localization/RuntimeUiMessages.java @@ -78,6 +78,14 @@ public final class RuntimeUiMessages { public static final TextKey DUST_OBJECTS_IN_CHUNK = TextKey.of("iris.runtime.dust.objects_in_chunk", "Objects in chunk: {objects}"); public static final TextKey DUST_COPY_BUTTON = TextKey.of("iris.runtime.dust.copy_button", "[Click to copy these stats]"); public static final TextKey DUST_COPY_HOVER = TextKey.of("iris.runtime.dust.copy_hover", "Copy block stats to clipboard"); + public static final TextKey STUDIO_APP_DOWNLOAD_OFF = TextKey.of("iris.runtime.studio.app_download_off", "Studio app download is off: set studio.downloadApp to true in iris.json."); + public static final TextKey STUDIO_APP_NO_DISPLAY = TextKey.of("iris.runtime.studio.app_no_display", "This server has no display to open the studio app on."); + public static final TextKey STUDIO_APP_DOWNLOADING = TextKey.of("iris.runtime.studio.app_downloading", "Studio app is still downloading; try again in a moment."); + public static final TextKey STUDIO_APP_UNAVAILABLE = TextKey.of("iris.runtime.studio.app_unavailable", "Studio app unavailable; see the console."); + public static final TextKey STUDIO_APP_NOT_BUILT = TextKey.of("iris.runtime.studio.app_not_built", "Studio app not built: run npm run build in its folder."); + public static final TextKey STUDIO_APP_FAILED_TO_START = TextKey.of("iris.runtime.studio.app_failed_to_start", "Studio app failed to start; see the console."); + public static final TextKey STUDIO_LINK_COPY_BUTTON = TextKey.of("iris.runtime.studio.link_copy_button", "[Copy studio link]"); + public static final TextKey STUDIO_LINK_COPY_HOVER = TextKey.of("iris.runtime.studio.link_copy_hover", "Paste it into the studio app's connect screen"); public static final TextKey DUST_REVEAL_FAILED = TextKey.of("iris.runtime.dust.reveal_failed", "Object reveal failed; see the console for details."); public static final TextKey DUST_BIOME_LOADING = TextKey.of("iris.runtime.dust.biome_loading", "Saved biome information is loading. Try revealing this block again shortly."); public static final TextKey WHAT_MATERIAL = TextKey.of("iris.runtime.what.material", "Material: {material}"); @@ -196,6 +204,14 @@ public final class RuntimeUiMessages { DUST_OBJECTS_IN_CHUNK, DUST_COPY_BUTTON, DUST_COPY_HOVER, + STUDIO_APP_DOWNLOAD_OFF, + STUDIO_APP_NO_DISPLAY, + STUDIO_APP_DOWNLOADING, + STUDIO_APP_UNAVAILABLE, + STUDIO_APP_NOT_BUILT, + STUDIO_APP_FAILED_TO_START, + STUDIO_LINK_COPY_BUTTON, + STUDIO_LINK_COPY_HOVER, DUST_REVEAL_FAILED, DUST_BIOME_LOADING, WHAT_MATERIAL, diff --git a/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/noise/NoiseStyleCompiler.java b/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/noise/NoiseStyleCompiler.java index 28712d7a8..9b39fbc4b 100644 --- a/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/noise/NoiseStyleCompiler.java +++ b/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/noise/NoiseStyleCompiler.java @@ -143,7 +143,7 @@ public final class NoiseStyleCompiler implements StyleCompiler { Field center = new Field.Const(-child.getOpacity() / 2.0); String childPath = path + "/f" + index + "_" + child.getSeed(); warpX = sum(warpX, binary(Field.BinaryOp.ADD, layer(child, domain, emit, childPath + "x"), center)); - warpZ = sum(warpZ, binary(Field.BinaryOp.ADD, layer(child, domain.swapped(), emit, childPath + "z"), center)); + warpZ = sum(warpZ, binary(Field.BinaryOp.ADD, layer(child, domain, emit, childPath + "z"), center)); } Domain sampled = domain.layer(positive(layer.getZoom(), "layer zoom"), layer.getOffsetX(), layer.getOffsetZ(), warpX, warpZ); Field value = style(layer.getStyle(), layer.getOctaves(), sampled, emit, path); @@ -208,7 +208,7 @@ public final class NoiseStyleCompiler implements StyleCompiler { Displacement leafDisplacement = displacement; if (warped(cng)) { Field warpX = displacement(node(cng.getFracture(), displacement, emit, path + "/x"), cng.getFscale()); - Field warpZ = displacement(node(cng.getFracture(), displacement.swapped(), emit, path + "/z"), cng.getFscale()); + Field warpZ = displacement(node(cng.getFracture(), displacement, emit, path + "/z"), cng.getFscale()); leafDisplacement = displacement.warped(warpX, warpZ); } value = leaf(type, cng.getOct(), cng.getEffectiveScale() * multiplier, leafDisplacement, emit, path); @@ -483,19 +483,11 @@ public final class NoiseStyleCompiler implements StyleCompiler { sum(warpX, layerWarpX == null ? null : scaled(layerWarpX, zoom)), sum(warpZ, layerWarpZ == null ? null : scaled(layerWarpZ, zoom))); } - - private Domain swapped() { - return new Domain(zoom, offsetZ, offsetX, warpZ, warpX); - } } private record Displacement(double offsetX, double offsetZ, Field warpX, Field warpZ) { private static final Displacement NONE = new Displacement(0.0, 0.0, null, null); - private Displacement swapped() { - return new Displacement(offsetZ, offsetX, warpZ, warpX); - } - private Displacement warped(Field addedX, Field addedZ) { return new Displacement(offsetX, offsetZ, sum(warpX, addedX), sum(warpZ, addedZ)); } diff --git a/core/src/main/java/art/arcane/iris/pack/validation/MissingBlockState.java b/core/src/main/java/art/arcane/iris/pack/validation/MissingBlockState.java index 81d89ea1a..f3c16cafa 100644 --- a/core/src/main/java/art/arcane/iris/pack/validation/MissingBlockState.java +++ b/core/src/main/java/art/arcane/iris/pack/validation/MissingBlockState.java @@ -129,6 +129,16 @@ public final class MissingBlockState implements NativeBlockState { return false; } + @Override + public boolean isLog() { + return false; + } + + @Override + public boolean isLeaves() { + return false; + } + @Override public boolean isFoliagePlantable() { return false; diff --git a/core/src/main/java/art/arcane/iris/platform/bukkit/BukkitBlockResolution.java b/core/src/main/java/art/arcane/iris/platform/bukkit/BukkitBlockResolution.java index 783b0d553..1f296acfc 100644 --- a/core/src/main/java/art/arcane/iris/platform/bukkit/BukkitBlockResolution.java +++ b/core/src/main/java/art/arcane/iris/platform/bukkit/BukkitBlockResolution.java @@ -100,8 +100,12 @@ public final class BukkitBlockResolution { } Identifier key = Identifier.fromString(ix); - Optional bd = IrisServices.get(ExternalDataSVC.class).getBlockData(key); + ExternalDataSVC external = IrisServices.get(ExternalDataSVC.class); + Optional bd = external.getBlockData(key); debug("Loading block data " + key); + if (bd.isPresent() && shouldPreventLeafDecay()) { + return external.withoutDecay(bd.get()); + } return bd.orElse(null); } diff --git a/core/src/main/java/art/arcane/iris/platform/bukkit/BukkitBlockState.java b/core/src/main/java/art/arcane/iris/platform/bukkit/BukkitBlockState.java index b9ef9cec2..5d0064ace 100644 --- a/core/src/main/java/art/arcane/iris/platform/bukkit/BukkitBlockState.java +++ b/core/src/main/java/art/arcane/iris/platform/bukkit/BukkitBlockState.java @@ -27,9 +27,11 @@ import art.arcane.volmlib.nativelib.terrain.BlockStateKey; import art.arcane.volmlib.nativelib.terrain.NativeBlockState; import art.arcane.iris.generation.block.IrisCustomData; import art.arcane.iris.generation.geometry.IrisBlockVector; +import art.arcane.iris.spi.IrisServices; import art.arcane.volmlib.util.collection.KMap; import org.bukkit.Axis; import org.bukkit.Bukkit; +import org.bukkit.Material; import org.bukkit.Tag; import org.bukkit.block.BlockFace; import org.bukkit.block.data.BlockData; @@ -75,6 +77,8 @@ public final class BukkitBlockState implements NativeBlockState { private byte updatable; private byte foliage; private byte treeBlock; + private byte log; + private byte leaves; private byte foliagePlantable; private byte decorant; private byte storage; @@ -318,12 +322,41 @@ public final class BukkitBlockState implements NativeBlockState { public boolean isTreeBlock() { byte cached = treeBlock; if (cached == UNKNOWN) { - cached = flag(Tag.LOGS.isTagged(data.getMaterial()) || Tag.LEAVES.isTagged(data.getMaterial())); + cached = flag(isLog() || isLeaves()); treeBlock = cached; } return cached == TRUE; } + @Override + public boolean isLog() { + byte cached = log; + if (cached == UNKNOWN) { + cached = flag(hasTag(Tag.LOGS)); + log = cached; + } + return cached == TRUE; + } + + @Override + public boolean isLeaves() { + byte cached = leaves; + if (cached == UNKNOWN) { + cached = flag(hasTag(Tag.LEAVES)); + leaves = cached; + } + return cached == TRUE; + } + + // A plugin's custom block shows up as some other material, so the plugin is asked for its own tags too. + private boolean hasTag(Tag tag) { + if (tag.isTagged(data.getMaterial())) { + return true; + } + ExternalDataSVC external = IrisServices.getOrNull(ExternalDataSVC.class); + return external != null && external.hasBlockTag(data, tag.getKey()); + } + @Override public boolean isFoliagePlantable() { byte cached = foliagePlantable; diff --git a/core/src/main/java/art/arcane/iris/platform/bukkit/plugin/VolmitSender.java b/core/src/main/java/art/arcane/iris/platform/bukkit/plugin/VolmitSender.java index 2a8067812..1ca11c4f7 100644 --- a/core/src/main/java/art/arcane/iris/platform/bukkit/plugin/VolmitSender.java +++ b/core/src/main/java/art/arcane/iris/platform/bukkit/plugin/VolmitSender.java @@ -32,6 +32,9 @@ import art.arcane.volmlib.util.math.M; import lombok.Getter; import lombok.Setter; import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.event.ClickEvent; +import net.kyori.adventure.text.event.HoverEvent; +import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.text.minimessage.MiniMessage; import org.bukkit.Server; import org.bukkit.Sound; @@ -326,6 +329,17 @@ public class VolmitSender implements CommandSender { deliver(ComponentText.component(component)); } + /** A green line that copies {@code payload} to a player's clipboard when clicked; a console gets nothing. */ + public void sendCopyButton(String label, String hover, String payload) { + if (!isPlayer()) { + return; + } + sendComponent(Component.text(label) + .color(NamedTextColor.GREEN) + .clickEvent(ClickEvent.copyToClipboard(payload)) + .hoverEvent(HoverEvent.showText(Component.text(hover)))); + } + private void deliver(ComponentText message) { ComponentMessenger.send(s, message); } diff --git a/core/src/main/java/art/arcane/iris/structure/object/ObjectBlockPass.java b/core/src/main/java/art/arcane/iris/structure/object/ObjectBlockPass.java index e864c0ca8..e8e0ffa38 100644 --- a/core/src/main/java/art/arcane/iris/structure/object/ObjectBlockPass.java +++ b/core/src/main/java/art/arcane/iris/structure/object/ObjectBlockPass.java @@ -141,8 +141,9 @@ final class ObjectBlockPass { private boolean handleCustomData(NativeBlockState data, boolean air, TileData tile, String marker, int xx, int yy, int zz) { // Short-circuit order matters for cost only: the mantle read is paid solely - // for vine blocks. Both operands are pure, so the value is unchanged. - boolean wouldReplace = !is(ObjectPlaceMode.STRUCTURE_PIECE) && B.isVineBlock(data) && B.isSolid(state.placer.get(xx, yy, zz)); + // for vine blocks and leaves. Both operands are pure, so the value is unchanged. + boolean wouldReplace = !is(ObjectPlaceMode.STRUCTURE_PIECE) && readsExistingBlock(data) + && keepsExisting(data, state.placer.get(xx, yy, zz)); boolean place = shouldPlaceObjectBlock(is(ObjectPlaceMode.STRUCTURE_PIECE), air, wouldReplace); if (data.isCustom() || place) { state.placer.set(xx, yy, zz, data); @@ -160,6 +161,15 @@ final class ObjectBlockPass { return false; } + private static boolean readsExistingBlock(NativeBlockState data) { + return B.isVineBlock(data) || B.isLeaves(data); + } + + /** Vines never replace solid blocks, and leaves never cut a log: the trunk above the cut would float. */ + static boolean keepsExisting(NativeBlockState data, NativeBlockState existing) { + return B.isVineBlock(data) ? B.isSolid(existing) : B.isLeaves(data) && B.isLog(existing); + } + private EditResult applyEdits(double[] exact, int index, NativeBlockState data, TileData tile) { double exactX = exact[index * 3]; double exactY = exact[index * 3 + 1]; diff --git a/core/src/main/java/art/arcane/iris/structure/object/PlacementPalette.java b/core/src/main/java/art/arcane/iris/structure/object/PlacementPalette.java index 6328050e3..a6d776250 100644 --- a/core/src/main/java/art/arcane/iris/structure/object/PlacementPalette.java +++ b/core/src/main/java/art/arcane/iris/structure/object/PlacementPalette.java @@ -70,8 +70,7 @@ final class PlacementPalette { NativeBlockState resolved = decayed[entry]; if (resolved == null) { NativeBlockState data = source(entry); - resolved = preventingDecay && IrisProceduralBlocks.hasProperty(data, "distance") - && "false".equals(IrisProceduralBlocks.propertyValue(data, "persistent")) + resolved = preventingDecay && "false".equals(IrisProceduralBlocks.propertyValue(data, "persistent")) ? data.withProperty("persistent", "true") : data; decayed[entry] = resolved; } diff --git a/core/src/main/java/art/arcane/iris/studio/app/BundledStudioApp.java b/core/src/main/java/art/arcane/iris/studio/app/BundledStudioApp.java new file mode 100644 index 000000000..106ef6399 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/studio/app/BundledStudioApp.java @@ -0,0 +1,63 @@ +/* + * 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 . + */ + +package art.arcane.iris.studio.app; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; + +/** The studio app the jar carries, unpacked into a folder named by its checksum so each build gets its own copy. */ +final class BundledStudioApp { + static final String RESOURCE = "META-INF/iris/studio-app.zip"; + private static final String FOLDER_PREFIX = "app-"; + private static final int FOLDER_CHECKSUM_LENGTH = 12; + + private BundledStudioApp() { + } + + static Path install(Path root, ClassLoader resources) throws IOException { + Path archive = root.resolve("studio-app.zip.part"); + try { + copyResource(resources, archive); + Path folder = root.resolve(FOLDER_PREFIX + ElectronRuntime.sha256(archive).substring(0, FOLDER_CHECKSUM_LENGTH)); + if (!Files.isRegularFile(folder.resolve("package.json"))) { + ZipArchives.extract(archive, folder); + } + return folder; + } finally { + Files.deleteIfExists(archive); + } + } + + static boolean isAppFolder(Path folder) { + return folder.getFileName().toString().startsWith(FOLDER_PREFIX); + } + + private static void copyResource(ClassLoader resources, Path archive) throws IOException { + try (InputStream input = resources.getResourceAsStream(RESOURCE)) { + if (input == null) { + throw new IOException("this build does not bundle the studio app; point studio.studioApp at a studio checkout"); + } + Files.createDirectories(archive.getParent()); + Files.copy(input, archive, StandardCopyOption.REPLACE_EXISTING); + } + } +} diff --git a/core/src/main/java/art/arcane/iris/studio/app/ElectronRuntime.java b/core/src/main/java/art/arcane/iris/studio/app/ElectronRuntime.java new file mode 100644 index 000000000..786566cf6 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/studio/app/ElectronRuntime.java @@ -0,0 +1,179 @@ +/* + * 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 . + */ + +package art.arcane.iris.studio.app; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Duration; +import java.util.HexFormat; +import java.util.Locale; +import java.util.Properties; + +/** + * The Electron build the studio app runs on. The build pins its version and each platform's SHA-256 in the studio app + * manifest; the archive comes from Electron's own GitHub release and is unpacked once into the studio folder. + */ +final class ElectronRuntime { + private static final String RELEASE_ROOT = "https://github.com/electron/electron/releases/download/"; + private static final String VERSION_KEY = "electron.version"; + private static final String CHECKSUM_SUFFIX = ".sha256"; + private static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(10); + private static final Duration DOWNLOAD_TIMEOUT = Duration.ofMinutes(15); + + private final String version; + private final Platform platform; + private final String sha256; + + private ElectronRuntime(String version, Platform platform, String sha256) { + this.version = version; + this.platform = platform; + this.sha256 = sha256; + } + + static ElectronRuntime pinned(Properties manifest, Platform platform) throws IOException { + String version = manifest.getProperty(VERSION_KEY); + String sha256 = manifest.getProperty(platform.name() + CHECKSUM_SUFFIX); + if (version == null || sha256 == null) { + throw new IOException("no Electron build is pinned for " + platform.name()); + } + return new ElectronRuntime(version, platform, sha256.toLowerCase(Locale.ROOT)); + } + + String folderName() { + return "electron-v" + version + "-" + platform.name(); + } + + URI source() { + return URI.create(RELEASE_ROOT + "v" + version + "/" + folderName() + ".zip"); + } + + /** The Electron executable under {@code root}, downloaded, checked and unpacked first when it is not there yet. */ + Path install(Path root, Downloader downloader) throws IOException { + Path executable = root.resolve(folderName()).resolve(platform.executable()); + if (Files.isRegularFile(executable)) { + return executable; + } + Path archive = root.resolve(folderName() + ".zip.part"); + try { + downloader.download(source(), archive); + requireChecksum(archive); + if (platform.macOS()) { + ZipArchives.extractWithDitto(archive, root.resolve(folderName())); + } else { + ZipArchives.extract(archive, root.resolve(folderName())); + } + } finally { + Files.deleteIfExists(archive); + } + if (!Files.isRegularFile(executable)) { + throw new IOException(source() + " has no " + platform.executable()); + } + return executable; + } + + private void requireChecksum(Path archive) throws IOException { + String actual = sha256(archive); + if (!actual.equals(sha256)) { + throw new IOException(source() + " failed its checksum (expected " + sha256 + ", got " + actual + ")"); + } + } + + static String sha256(Path file) throws IOException { + try (InputStream input = Files.newInputStream(file)) { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + byte[] buffer = new byte[1 << 16]; + int read; + while ((read = input.read(buffer)) >= 0) { + digest.update(buffer, 0, read); + } + return HexFormat.of().formatHex(digest.digest()); + } catch (NoSuchAlgorithmException missing) { + throw new IllegalStateException(missing); + } + } + + @FunctionalInterface + interface Downloader { + void download(URI source, Path target) throws IOException; + + static Downloader http() { + return (source, target) -> { + HttpClient client = HttpClient.newBuilder() + .connectTimeout(CONNECT_TIMEOUT) + .followRedirects(HttpClient.Redirect.NORMAL) + .build(); + HttpRequest request = HttpRequest.newBuilder(source) + .timeout(DOWNLOAD_TIMEOUT) + .header("User-Agent", "Iris") + .build(); + try { + HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofFile(target)); + if (response.statusCode() != 200) { + throw new IOException(source + " answered HTTP " + response.statusCode()); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IOException("download of " + source + " was interrupted", interrupted); + } + }; + } + } + + /** An Electron release platform, named as its archives are, and where the executable sits inside them. */ + record Platform(String name, String executable) { + static Platform current() { + return of(System.getProperty("os.name", ""), System.getProperty("os.arch", "")); + } + + /** Null for a system Electron publishes no build for. */ + static Platform of(String operatingSystem, String architecture) { + String os = operatingSystem.toLowerCase(Locale.ROOT); + String arch = switch (architecture) { + case "aarch64", "arm64" -> "arm64"; + case "amd64", "x86_64" -> "x64"; + default -> null; + }; + if (arch == null) { + return null; + } + if (os.contains("linux")) { + return new Platform("linux-" + arch, "electron"); + } + if (os.contains("win")) { + return new Platform("win32-" + arch, "electron.exe"); + } + if (os.contains("mac")) { + return new Platform("darwin-" + arch, "Electron.app/Contents/MacOS/Electron"); + } + return null; + } + + boolean macOS() { + return name.startsWith("darwin"); + } + } +} diff --git a/core/src/main/java/art/arcane/iris/studio/app/StudioAppInstall.java b/core/src/main/java/art/arcane/iris/studio/app/StudioAppInstall.java new file mode 100644 index 000000000..dee1bd047 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/studio/app/StudioAppInstall.java @@ -0,0 +1,25 @@ +/* + * 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 . + */ + +package art.arcane.iris.studio.app; + +import java.nio.file.Path; + +/** A studio app ready to start: the Electron executable and the app folder it runs. */ +public record StudioAppInstall(Path electron, Path app) { +} diff --git a/core/src/main/java/art/arcane/iris/studio/app/StudioAppInstaller.java b/core/src/main/java/art/arcane/iris/studio/app/StudioAppInstaller.java new file mode 100644 index 000000000..003e0f483 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/studio/app/StudioAppInstaller.java @@ -0,0 +1,168 @@ +/* + * 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 . + */ + +package art.arcane.iris.studio.app; + +import art.arcane.iris.configuration.IrisSettings; +import art.arcane.iris.spi.IrisLogging; +import art.arcane.iris.spi.IrisPlatforms; +import art.arcane.iris.studio.view.GuiHost; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Properties; +import java.util.stream.Stream; + +/** + * Installs the studio app into the Iris data folder in the background at startup: the app from the jar, and the + * Electron build it runs on from Electron's release. Servers without a display skip it, since the window could not + * open there anyway. + */ +public final class StudioAppInstaller { + static final String MANIFEST = "META-INF/iris/studio-app.properties"; + private static final String DATA_FOLDER = "studio"; + private static final String STAGING_SUFFIX = ".part"; + + private static StudioAppState state = StudioAppState.NOT_STARTED; + private static StudioAppInstall installed; + private static String unavailableReason = ""; + + private StudioAppInstaller() { + } + + /** Starts the install unless it is done, running, or off; the state it leaves, for a caller about to open the app. */ + public static synchronized StudioAppState installInBackground() { + if (state == StudioAppState.DOWNLOADING || state == StudioAppState.READY || state == StudioAppState.UNAVAILABLE) { + return state; + } + state = blockedState(); + if (state != StudioAppState.DOWNLOADING) { + return state; + } + Thread.ofPlatform().daemon().name("Iris Studio install").start(StudioAppInstaller::install); + return state; + } + + public static synchronized StudioAppInstall installed() { + return installed; + } + + public static synchronized String unavailableReason() { + return unavailableReason; + } + + static boolean hasDisplay(String operatingSystem, Map environment) { + String os = operatingSystem.toLowerCase(Locale.ROOT); + if (os.contains("win") || os.contains("mac")) { + return true; + } + return isSet(environment.get("DISPLAY")) || isSet(environment.get("WAYLAND_DISPLAY")); + } + + private static StudioAppState blockedState() { + if (!IrisSettings.get().getStudio().isDownloadApp()) { + return StudioAppState.DOWNLOAD_OFF; + } + if (GuiHost.isDesktopSuppressed() || !hasDisplay(System.getProperty("os.name", ""), System.getenv())) { + return StudioAppState.NO_DISPLAY; + } + return StudioAppState.DOWNLOADING; + } + + private static void install() { + long startedNanos = System.nanoTime(); + try { + ElectronRuntime.Platform platform = ElectronRuntime.Platform.current(); + if (platform == null) { + throw new IOException("Electron has no build for " + System.getProperty("os.name") + " " + System.getProperty("os.arch")); + } + ElectronRuntime electron = ElectronRuntime.pinned(manifest(), platform); + Path root = IrisPlatforms.get().dataFolder(DATA_FOLDER).toPath(); + Path executable = installElectron(electron, root); + Path app = BundledStudioApp.install(root, StudioAppInstaller.class.getClassLoader()); + removeStaleInstalls(root, List.of(app, root.resolve(electron.folderName()))); + ready(new StudioAppInstall(executable, app), (System.nanoTime() - startedNanos) / 1_000_000L); + } catch (IOException | RuntimeException error) { + unavailable(error.getMessage() == null ? error.getClass().getSimpleName() : error.getMessage()); + } + } + + private static Path installElectron(ElectronRuntime electron, Path root) throws IOException { + if (!Files.isDirectory(root.resolve(electron.folderName()))) { + IrisLogging.info("Downloading the studio app runtime from %s", electron.source()); + } + return electron.install(root, ElectronRuntime.Downloader.http()); + } + + private static Properties manifest() throws IOException { + Properties manifest = new Properties(); + try (InputStream input = StudioAppInstaller.class.getClassLoader().getResourceAsStream(MANIFEST)) { + if (input == null) { + throw new IOException("this build does not bundle the studio app; point studio.studioApp at a studio checkout"); + } + manifest.load(input); + } + return manifest; + } + + /** Drops the Electron builds and app copies earlier versions left, and any half-finished download or unpack. */ + private static void removeStaleInstalls(Path root, List current) { + try (Stream children = Files.list(root)) { + for (Path child : children.toList()) { + if (current.contains(child) || !isInstallArtifact(child)) { + continue; + } + try { + ZipArchives.deleteRecursively(child); + } catch (IOException error) { + IrisLogging.debug("Could not remove the old studio install %s: %s", child, error.getMessage()); + } + } + } catch (IOException error) { + IrisLogging.debug("Could not list the studio folder %s: %s", root, error.getMessage()); + } + } + + private static boolean isInstallArtifact(Path child) { + String name = child.getFileName().toString(); + return name.startsWith("electron-v") || BundledStudioApp.isAppFolder(child) || name.endsWith(STAGING_SUFFIX); + } + + private static synchronized void ready(StudioAppInstall install, long elapsedMillis) { + installed = install; + unavailableReason = ""; + state = StudioAppState.READY; + IrisLogging.info("Studio app ready in %d ms", elapsedMillis); + } + + private static synchronized void unavailable(String reason) { + installed = null; + unavailableReason = reason; + state = StudioAppState.UNAVAILABLE; + IrisLogging.warn("Studio app unavailable: %s", reason); + } + + private static boolean isSet(String value) { + return value != null && !value.isBlank(); + } +} diff --git a/core/src/main/java/art/arcane/iris/studio/app/StudioAppState.java b/core/src/main/java/art/arcane/iris/studio/app/StudioAppState.java new file mode 100644 index 000000000..d37891920 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/studio/app/StudioAppState.java @@ -0,0 +1,29 @@ +/* + * 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 . + */ + +package art.arcane.iris.studio.app; + +/** Where the downloaded studio app stands on this server. */ +public enum StudioAppState { + NOT_STARTED, + DOWNLOAD_OFF, + NO_DISPLAY, + DOWNLOADING, + READY, + UNAVAILABLE +} diff --git a/core/src/main/java/art/arcane/iris/studio/app/ZipArchives.java b/core/src/main/java/art/arcane/iris/studio/app/ZipArchives.java new file mode 100644 index 000000000..7e76b9895 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/studio/app/ZipArchives.java @@ -0,0 +1,247 @@ +/* + * 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 . + */ + +package art.arcane.iris.studio.app; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.channels.FileChannel; +import java.nio.charset.StandardCharsets; +import java.nio.file.AtomicMoveNotSupportedException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.nio.file.attribute.PosixFilePermission; +import java.util.Collections; +import java.util.Comparator; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.TimeUnit; +import java.util.stream.Stream; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + +/** + * Unpacks archives into a folder that only appears once it is complete: everything lands in a staging folder first, + * which is then moved into place, so a crash halfway never leaves a folder that looks installed. + */ +final class ZipArchives { + private static final long DITTO_TIMEOUT_MINUTES = 5; + private static final int FILE_TYPE_MASK = 0170000; + private static final int SYMLINK_TYPE = 0120000; + private static final int PERMISSION_MASK = 0777; + private static final List PERMISSION_BITS = List.of( + PosixFilePermission.OTHERS_EXECUTE, PosixFilePermission.OTHERS_WRITE, PosixFilePermission.OTHERS_READ, + PosixFilePermission.GROUP_EXECUTE, PosixFilePermission.GROUP_WRITE, PosixFilePermission.GROUP_READ, + PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.OWNER_WRITE, PosixFilePermission.OWNER_READ); + + private ZipArchives() { + } + + /** Keeps each entry's Unix mode and symlinks, so executables stay executable. */ + static void extract(Path archive, Path folder) throws IOException { + Path staging = staging(folder); + boolean posix = staging.getFileSystem().supportedFileAttributeViews().contains("posix"); + Map modes = posix ? unixModes(archive) : Map.of(); + try (ZipFile zip = new ZipFile(archive.toFile())) { + for (ZipEntry entry : Collections.list(zip.entries())) { + extractEntry(zip, entry, staging, modes.getOrDefault(entry.getName(), 0), posix); + } + } + moveIntoPlace(staging, folder); + } + + /** Unpacks with macOS's ditto, which keeps everything an app bundle relies on. */ + static void extractWithDitto(Path archive, Path folder) throws IOException { + Path staging = staging(folder); + Process ditto = new ProcessBuilder("ditto", "-x", "-k", archive.toString(), staging.toString()) + .redirectErrorStream(true) + .start(); + try { + if (!ditto.waitFor(DITTO_TIMEOUT_MINUTES, TimeUnit.MINUTES)) { + ditto.destroyForcibly(); + throw new IOException("ditto did not finish unpacking " + archive); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IOException("unpacking " + archive + " was interrupted", interrupted); + } + if (ditto.exitValue() != 0) { + throw new IOException("ditto could not unpack " + archive + ": " + + new String(ditto.getInputStream().readAllBytes(), StandardCharsets.UTF_8).trim()); + } + moveIntoPlace(staging, folder); + } + + static void deleteRecursively(Path path) throws IOException { + if (!Files.exists(path, java.nio.file.LinkOption.NOFOLLOW_LINKS)) { + return; + } + try (Stream walk = Files.walk(path)) { + for (Path entry : walk.sorted(Comparator.reverseOrder()).toList()) { + Files.delete(entry); + } + } + } + + private static void extractEntry(ZipFile zip, ZipEntry entry, Path staging, int mode, boolean posix) throws IOException { + Path target = insideStaging(staging, staging.resolve(entry.getName())); + if (entry.isDirectory()) { + Files.createDirectories(target); + return; + } + Files.createDirectories(target.getParent()); + try (InputStream input = zip.getInputStream(entry)) { + if (posix && (mode & FILE_TYPE_MASK) == SYMLINK_TYPE) { + Path linkTarget = Path.of(new String(input.readAllBytes(), StandardCharsets.UTF_8)); + insideStaging(staging, target.getParent().resolve(linkTarget)); + Files.createSymbolicLink(target, linkTarget); + return; + } + Files.copy(input, target); + } + if (posix && mode != 0) { + Files.setPosixFilePermissions(target, permissions(mode)); + } + } + + private static Path insideStaging(Path staging, Path path) throws IOException { + Path normalized = path.normalize(); + if (!normalized.startsWith(staging)) { + throw new IOException("archive entry " + path + " points outside its folder"); + } + return normalized; + } + + private static Set permissions(int mode) { + Set permissions = EnumSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE); + int bits = mode & PERMISSION_MASK; + for (int bit = 0; bit < PERMISSION_BITS.size(); bit++) { + if ((bits & (1 << bit)) != 0) { + permissions.add(PERMISSION_BITS.get(bit)); + } + } + return permissions; + } + + /** + * Each entry's Unix mode, read from the archive's central directory, where zip tools made on Unix keep it in the + * high half of the external attributes. {@link ZipFile} reads the entries but not this field. + */ + static Map unixModes(Path archive) throws IOException { + try (FileChannel channel = FileChannel.open(archive)) { + CentralDirectory directory = CentralDirectory.locate(channel); + ByteBuffer records = read(channel, directory.offset(), directory.size()); + Map modes = new HashMap<>(); + int position = 0; + for (long index = 0; index < directory.entries(); index++) { + if (records.getInt(position) != CentralDirectory.ENTRY_SIGNATURE) { + throw new IOException(archive + " has a damaged central directory"); + } + int madeBySystem = (records.getShort(position + 4) >> 8) & 0xFF; + int nameLength = records.getShort(position + 28) & 0xFFFF; + int extraLength = records.getShort(position + 30) & 0xFFFF; + int commentLength = records.getShort(position + 32) & 0xFFFF; + int externalAttributes = records.getInt(position + 38); + byte[] name = new byte[nameLength]; + records.get(position + 46, name); + if (madeBySystem == CentralDirectory.MADE_ON_UNIX) { + modes.put(new String(name, StandardCharsets.UTF_8), externalAttributes >>> 16); + } + position += 46 + nameLength + extraLength + commentLength; + } + return modes; + } + } + + private static ByteBuffer read(FileChannel channel, long offset, long length) throws IOException { + if (length > Integer.MAX_VALUE - 8 || offset < 0 || offset + length > channel.size()) { + throw new IOException("zip structure points outside the archive"); + } + ByteBuffer buffer = ByteBuffer.allocate((int) length).order(ByteOrder.LITTLE_ENDIAN); + while (buffer.hasRemaining()) { + if (channel.read(buffer, offset + buffer.position()) < 0) { + throw new IOException("archive ended early"); + } + } + return buffer.flip(); + } + + private record CentralDirectory(long offset, long size, long entries) { + static final int ENTRY_SIGNATURE = 0x02014b50; + static final int MADE_ON_UNIX = 3; + private static final int END_SIGNATURE = 0x06054b50; + private static final int ZIP64_LOCATOR_SIGNATURE = 0x07064b50; + private static final int ZIP64_END_SIGNATURE = 0x06064b50; + private static final int END_RECORD_LENGTH = 22; + private static final int ZIP64_LOCATOR_LENGTH = 20; + private static final int MAX_COMMENT_LENGTH = 0xFFFF; + + static CentralDirectory locate(FileChannel channel) throws IOException { + long size = channel.size(); + int tailLength = (int) Math.min(size, END_RECORD_LENGTH + MAX_COMMENT_LENGTH); + long tailOffset = size - tailLength; + ByteBuffer tail = read(channel, tailOffset, tailLength); + for (int end = tailLength - END_RECORD_LENGTH; end >= 0; end--) { + if (tail.getInt(end) == END_SIGNATURE) { + return fromEndRecord(channel, tail, end, tailOffset + end); + } + } + throw new IOException("not a zip archive"); + } + + private static CentralDirectory fromEndRecord(FileChannel channel, ByteBuffer tail, int end, long endOffset) throws IOException { + long entries = tail.getShort(end + 10) & 0xFFFFL; + long size = tail.getInt(end + 12) & 0xFFFFFFFFL; + long offset = tail.getInt(end + 16) & 0xFFFFFFFFL; + if (entries != 0xFFFFL && size != 0xFFFFFFFFL && offset != 0xFFFFFFFFL) { + return new CentralDirectory(offset, size, entries); + } + ByteBuffer locator = read(channel, endOffset - ZIP64_LOCATOR_LENGTH, ZIP64_LOCATOR_LENGTH); + if (locator.getInt(0) != ZIP64_LOCATOR_SIGNATURE) { + throw new IOException("zip64 archive without its locator"); + } + ByteBuffer zip64End = read(channel, locator.getLong(8), 56); + if (zip64End.getInt(0) != ZIP64_END_SIGNATURE) { + throw new IOException("zip64 archive without its end record"); + } + return new CentralDirectory(zip64End.getLong(48), zip64End.getLong(40), zip64End.getLong(32)); + } + } + + private static Path staging(Path folder) throws IOException { + Path staging = folder.resolveSibling(folder.getFileName() + ".part"); + deleteRecursively(staging); + Files.createDirectories(staging); + return staging; + } + + private static void moveIntoPlace(Path staging, Path folder) throws IOException { + deleteRecursively(folder); + try { + Files.move(staging, folder, StandardCopyOption.ATOMIC_MOVE); + } catch (AtomicMoveNotSupportedException unsupported) { + Files.move(staging, folder); + } + } +} diff --git a/core/src/main/java/art/arcane/iris/studio/bridge/StudioLaunch.java b/core/src/main/java/art/arcane/iris/studio/bridge/StudioLaunch.java new file mode 100644 index 000000000..316974ffe --- /dev/null +++ b/core/src/main/java/art/arcane/iris/studio/bridge/StudioLaunch.java @@ -0,0 +1,47 @@ +/* + * 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 . + */ + +package art.arcane.iris.studio.bridge; + +import art.arcane.iris.localization.RuntimeUiMessages; +import art.arcane.volmlib.util.localization.TextKey; + +/** How a request to show the studio window ended; every outcome but {@link #OPENED} leaves the bridge link as the only way in. */ +public enum StudioLaunch { + OPENED(null), + DOWNLOAD_OFF(RuntimeUiMessages.STUDIO_APP_DOWNLOAD_OFF), + NO_DISPLAY(RuntimeUiMessages.STUDIO_APP_NO_DISPLAY), + DOWNLOADING(RuntimeUiMessages.STUDIO_APP_DOWNLOADING), + UNAVAILABLE(RuntimeUiMessages.STUDIO_APP_UNAVAILABLE), + NOT_BUILT(RuntimeUiMessages.STUDIO_APP_NOT_BUILT), + FAILED_TO_START(RuntimeUiMessages.STUDIO_APP_FAILED_TO_START); + + private final TextKey failureMessage; + + StudioLaunch(TextKey failureMessage) { + this.failureMessage = failureMessage; + } + + public boolean opened() { + return this == OPENED; + } + + public TextKey failureMessage() { + return failureMessage; + } +} diff --git a/core/src/main/java/art/arcane/iris/studio/bridge/StudioWindow.java b/core/src/main/java/art/arcane/iris/studio/bridge/StudioWindow.java index bfb16fb2c..3c60d804f 100644 --- a/core/src/main/java/art/arcane/iris/studio/bridge/StudioWindow.java +++ b/core/src/main/java/art/arcane/iris/studio/bridge/StudioWindow.java @@ -20,6 +20,8 @@ package art.arcane.iris.studio.bridge; import art.arcane.iris.configuration.IrisSettings; import art.arcane.iris.spi.IrisLogging; +import art.arcane.iris.studio.app.StudioAppInstall; +import art.arcane.iris.studio.app.StudioAppInstaller; import java.io.IOException; import java.nio.file.Files; @@ -28,7 +30,8 @@ import java.util.ArrayList; import java.util.List; /** - * Opens the Iris Studio window on a bridge, from the app folder the studio settings name. The app keeps one window: + * Opens the Iris Studio window on a bridge, from the studio checkout the settings name or else from the app the + * server downloaded at startup. The app keeps one window: * a second start hands its link to the open window and exits. Windows the server started close when it stops, as * their bridges go with it. */ @@ -43,25 +46,47 @@ public final class StudioWindow { private StudioWindow() { } - /** False when no app is set or it could not start, so the caller's printed link is the only way in. */ - public static synchronized boolean show(StudioBridge bridge) { + public static synchronized StudioLaunch show(StudioBridge bridge) { IrisSettings.IrisSettingsStudio settings = IrisSettings.get().getStudio(); - String appFolder = settings.getStudioApp(); - if (appFolder == null || appFolder.isBlank()) { - return false; + String checkout = settings.getStudioApp(); + if (checkout != null && !checkout.isBlank()) { + return showCheckout(Path.of(checkout), electronBinary(settings), bridge.link()); } - Path app = Path.of(appFolder); + return showDownloaded(bridge.link()); + } + + private static StudioLaunch showCheckout(Path app, String electron, String link) { if (!Files.isRegularFile(app.resolve(BUILT_MAIN))) { IrisLogging.warn("Iris Studio is not built in %s; run npm run build there.", app); - return false; + return StudioLaunch.NOT_BUILT; } + return launch(electron, app, link); + } + + private static StudioLaunch showDownloaded(String link) { + return switch (StudioAppInstaller.installInBackground()) { + case READY -> { + StudioAppInstall install = StudioAppInstaller.installed(); + yield launch(install.electron().toString(), install.app(), link); + } + case NOT_STARTED, DOWNLOADING -> StudioLaunch.DOWNLOADING; + case DOWNLOAD_OFF -> StudioLaunch.DOWNLOAD_OFF; + case NO_DISPLAY -> StudioLaunch.NO_DISPLAY; + case UNAVAILABLE -> { + IrisLogging.warn("Studio app unavailable: %s", StudioAppInstaller.unavailableReason()); + yield StudioLaunch.UNAVAILABLE; + } + }; + } + + private static StudioLaunch launch(String electron, Path app, String link) { try { STARTED.removeIf(process -> !process.isAlive()); - STARTED.add(start(electronBinary(settings), app, bridge.link())); - return true; + STARTED.add(start(electron, app, link)); + return StudioLaunch.OPENED; } catch (IOException error) { IrisLogging.warn("Could not open Iris Studio: %s", error.getMessage()); - return false; + return StudioLaunch.FAILED_TO_START; } } diff --git a/core/src/main/java/art/arcane/iris/studio/view/PregeneratorJob.java b/core/src/main/java/art/arcane/iris/studio/view/PregeneratorJob.java index a3271a648..e2dceedeb 100644 --- a/core/src/main/java/art/arcane/iris/studio/view/PregeneratorJob.java +++ b/core/src/main/java/art/arcane/iris/studio/view/PregeneratorJob.java @@ -420,7 +420,7 @@ public class PregeneratorJob implements PregenListener, PregenRenderSource { try { StudioBridge bridge = StudioBridges.open(engine.getWorld().name(), () -> engine, null); studioWatching = true; - if (!StudioWindow.show(bridge)) { + if (!StudioWindow.show(bridge).opened()) { IrisLogging.info("Iris Studio link for the pregeneration of %s: %s", engine.getWorld().name(), bridge.link()); } } catch (IOException error) { diff --git a/core/src/main/resources/languages/de_DE.toml b/core/src/main/resources/languages/de_DE.toml index ca1cbdc21..28310a506 100644 --- a/core/src/main/resources/languages/de_DE.toml +++ b/core/src/main/resources/languages/de_DE.toml @@ -1580,6 +1580,14 @@ failed_fragment = " fehlgeschlagen {failed}" "commandpack.update_world_unchanged" = "§aWelt '{world}' verwendet bereits {pack} v{version} mit denselben Generierungseinstellungen. Kein Neustart erforderlich." [iris.runtime.studio] +app_download_off = "Studio-App-Download ist aus: Setze studio.downloadApp in iris.json auf true." +app_no_display = "Dieser Server hat keine Anzeige, auf der sich die Studio-App öffnen kann." +app_downloading = "Die Studio-App wird noch heruntergeladen; versuche es gleich noch einmal." +app_unavailable = "Studio-App nicht verfügbar; siehe Konsole." +app_not_built = "Studio-App nicht gebaut: Führe npm run build in ihrem Ordner aus." +app_failed_to_start = "Studio-App konnte nicht starten; siehe Konsole." +link_copy_button = "[Studio-Link kopieren]" +link_copy_hover = "In den Verbindungsbildschirm der Studio-App einfügen" opening = "§6Studio §bÖFFNET" opening_progress = "§6Studio §bÖFFNET§7 {percent}%" failed_progress = "§6Studio §cFEHLGESCHLAGEN§7 {percent}%" diff --git a/core/src/main/resources/languages/es_ES.toml b/core/src/main/resources/languages/es_ES.toml index 35cb8a152..c13f6d48f 100644 --- a/core/src/main/resources/languages/es_ES.toml +++ b/core/src/main/resources/languages/es_ES.toml @@ -1580,6 +1580,14 @@ failed_fragment = " fallidos {failed}" "commandpack.update_world_unchanged" = "§aEl mundo '{world}' ya usa {pack} v{version} con los mismos ajustes de generación. No hace falta reiniciar." [iris.runtime.studio] +app_download_off = "La descarga de la app de Studio está desactivada: pon studio.downloadApp a true en iris.json." +app_no_display = "Este servidor no tiene pantalla donde abrir la app de Studio." +app_downloading = "La app de Studio aún se está descargando; vuelve a intentarlo en un momento." +app_unavailable = "La app de Studio no está disponible; consulta la consola." +app_not_built = "La app de Studio no está compilada: ejecuta npm run build en su carpeta." +app_failed_to_start = "La app de Studio no pudo iniciarse; consulta la consola." +link_copy_button = "[Copiar enlace de Studio]" +link_copy_hover = "Pégalo en la pantalla de conexión de la app de Studio" opening = "§6Studio §bABRIENDO" opening_progress = "§6Studio §bABRIENDO§7 {percent}%" failed_progress = "§6Studio §cFALLÓ§7 {percent}%" diff --git a/core/src/main/resources/languages/fi_FI.toml b/core/src/main/resources/languages/fi_FI.toml index 3a6578970..c456791f8 100644 --- a/core/src/main/resources/languages/fi_FI.toml +++ b/core/src/main/resources/languages/fi_FI.toml @@ -1585,6 +1585,14 @@ failed_fragment = " epäonnistui {failed}" "commandpack.update_world_unchanged" = "§aMaailma '{world}' käyttää jo pakettia {pack} v{version} samoilla generointiasetuksilla. Uudelleenkäynnistystä ei tarvita." [iris.runtime.studio] +app_download_off = "Studio-sovelluksen lataus on pois päältä: aseta studio.downloadApp arvoon true tiedostossa iris.json." +app_no_display = "Tällä palvelimella ei ole näyttöä, jolla Studio-sovelluksen voisi avata." +app_downloading = "Studio-sovellusta ladataan vielä; yritä hetken päästä uudelleen." +app_unavailable = "Studio-sovellus ei ole käytettävissä; katso konsoli." +app_not_built = "Studio-sovellusta ei ole käännetty: suorita npm run build sen kansiossa." +app_failed_to_start = "Studio-sovelluksen käynnistys epäonnistui; katso konsoli." +link_copy_button = "[Kopioi Studio-linkki]" +link_copy_hover = "Liitä se Studio-sovelluksen yhdistämisnäkymään" opening = "§6Studio §bAVATAAN" opening_progress = "§6Studio §bAVATAAN§7 {percent}%" failed_progress = "§6Studio §cEPÄONNISTUI§7 {percent}%" diff --git a/core/src/main/resources/languages/fr_FR.toml b/core/src/main/resources/languages/fr_FR.toml index a6b38abbd..9301c40ac 100644 --- a/core/src/main/resources/languages/fr_FR.toml +++ b/core/src/main/resources/languages/fr_FR.toml @@ -1580,6 +1580,14 @@ failed_fragment = " échecs {failed}" "commandpack.update_world_unchanged" = "§aLe monde '{world}' utilise déjà {pack} v{version} avec les mêmes paramètres de génération. Aucun redémarrage nécessaire." [iris.runtime.studio] +app_download_off = "Le téléchargement de l'application Studio est désactivé : mettez studio.downloadApp à true dans iris.json." +app_no_display = "Ce serveur n'a pas d'écran pour ouvrir l'application Studio." +app_downloading = "L'application Studio est encore en téléchargement ; réessayez dans un instant." +app_unavailable = "Application Studio indisponible ; consultez la console." +app_not_built = "Application Studio non compilée : lancez npm run build dans son dossier." +app_failed_to_start = "L'application Studio n'a pas pu démarrer ; consultez la console." +link_copy_button = "[Copier le lien Studio]" +link_copy_hover = "Collez-le dans l'écran de connexion de l'application Studio" opening = "§6Studio §bOUVERTURE" opening_progress = "§6Studio §bOUVERTURE§7 {percent}%" failed_progress = "§6Studio §cÉCHEC§7 {percent}%" diff --git a/core/src/main/resources/languages/he_IL.toml b/core/src/main/resources/languages/he_IL.toml index 304652c73..28df3d81f 100644 --- a/core/src/main/resources/languages/he_IL.toml +++ b/core/src/main/resources/languages/he_IL.toml @@ -1585,6 +1585,14 @@ failed_fragment = " נכשל {failed}" "commandpack.update_world_unchanged" = "§aהעולם '{world}' כבר משתמש בחבילה {pack} v{version} עם אותן הגדרות יצירה. אין צורך בהפעלה מחדש." [iris.runtime.studio] +app_download_off = "הורדת אפליקציית Studio כבויה: הגדר את studio.downloadApp ל-true בקובץ iris.json." +app_no_display = "לשרת הזה אין מסך שבו אפשר לפתוח את אפליקציית Studio." +app_downloading = "אפליקציית Studio עדיין יורדת; נסה שוב בעוד רגע." +app_unavailable = "אפליקציית Studio אינה זמינה; ראה את הקונסולה." +app_not_built = "אפליקציית Studio לא נבנתה: הרץ npm run build בתיקייה שלה." +app_failed_to_start = "אפליקציית Studio לא הצליחה לעלות; ראה את הקונסולה." +link_copy_button = "[העתק קישור Studio]" +link_copy_hover = "הדבק אותו במסך החיבור של אפליקציית Studio" opening = "§6Studio §bנפתח" opening_progress = "§6Studio §bנפתח§7 {percent}%" failed_progress = "§6Studio §cנכשל§7 {percent}%" diff --git a/core/src/main/resources/languages/it_IT.toml b/core/src/main/resources/languages/it_IT.toml index 4796db3c5..fa0cea047 100644 --- a/core/src/main/resources/languages/it_IT.toml +++ b/core/src/main/resources/languages/it_IT.toml @@ -1580,6 +1580,14 @@ failed_fragment = " non riusciti {failed}" "commandpack.update_world_unchanged" = "§aIl mondo '{world}' usa già {pack} v{version} con le stesse impostazioni di generazione. Non serve riavviare." [iris.runtime.studio] +app_download_off = "Il download dell'app Studio è disattivato: imposta studio.downloadApp su true in iris.json." +app_no_display = "Questo server non ha uno schermo su cui aprire l'app Studio." +app_downloading = "L'app Studio è ancora in download; riprova tra un momento." +app_unavailable = "App Studio non disponibile; controlla la console." +app_not_built = "App Studio non compilata: esegui npm run build nella sua cartella." +app_failed_to_start = "Impossibile avviare l'app Studio; controlla la console." +link_copy_button = "[Copia link Studio]" +link_copy_hover = "Incollalo nella schermata di connessione dell'app Studio" opening = "§6Studio §bAPERTURA" opening_progress = "§6Studio §bAPERTURA§7 {percent}%" failed_progress = "§6Studio §cNON RIUSCITO§7 {percent}%" diff --git a/core/src/main/resources/languages/ja-JP.toml b/core/src/main/resources/languages/ja-JP.toml index 441c4bde7..04e10d467 100644 --- a/core/src/main/resources/languages/ja-JP.toml +++ b/core/src/main/resources/languages/ja-JP.toml @@ -1583,6 +1583,14 @@ failed_fragment = " 失敗 {failed}" "commandpack.update_world_unchanged" = "§aワールド '{world}' は同じ生成設定の {pack} v{version} を使用しています。再起動は不要です。" [iris.runtime.studio] +app_download_off = "Studio アプリのダウンロードがオフです: iris.json の studio.downloadApp を true にしてください。" +app_no_display = "このサーバーには Studio アプリを開くディスプレイがありません。" +app_downloading = "Studio アプリはまだダウンロード中です。少し待ってから再試行してください。" +app_unavailable = "Studio アプリを利用できません。コンソールを確認してください。" +app_not_built = "Studio アプリがビルドされていません: そのフォルダで npm run build を実行してください。" +app_failed_to_start = "Studio アプリを起動できませんでした。コンソールを確認してください。" +link_copy_button = "[Studio リンクをコピー]" +link_copy_hover = "Studio アプリの接続画面に貼り付けてください" opening = "§6Studio §bオープン中" opening_progress = "§6Studio §bオープン中§7 {percent}%" failed_progress = "§6Studio §c失敗§7 {percent}%" diff --git a/core/src/main/resources/languages/ko_KR.toml b/core/src/main/resources/languages/ko_KR.toml index 749285469..1b43f8007 100644 --- a/core/src/main/resources/languages/ko_KR.toml +++ b/core/src/main/resources/languages/ko_KR.toml @@ -1583,6 +1583,14 @@ failed_fragment = " 실패 {failed}" "commandpack.update_world_unchanged" = "§a월드 '{world}'는 이미 같은 생성 설정으로 {pack} v{version}을 사용 중입니다. 재시작할 필요가 없습니다." [iris.runtime.studio] +app_download_off = "Studio 앱 다운로드가 꺼져 있습니다: iris.json에서 studio.downloadApp을 true로 설정하세요." +app_no_display = "이 서버에는 Studio 앱을 열 디스플레이가 없습니다." +app_downloading = "Studio 앱을 아직 다운로드하는 중입니다. 잠시 후 다시 시도하세요." +app_unavailable = "Studio 앱을 사용할 수 없습니다. 콘솔을 확인하세요." +app_not_built = "Studio 앱이 빌드되지 않았습니다: 해당 폴더에서 npm run build를 실행하세요." +app_failed_to_start = "Studio 앱을 시작하지 못했습니다. 콘솔을 확인하세요." +link_copy_button = "[Studio 링크 복사]" +link_copy_hover = "Studio 앱의 연결 화면에 붙여 넣으세요" opening = "§6Studio §b여는 중" opening_progress = "§6Studio §b여는 중§7 {percent}%" failed_progress = "§6Studio §c실패§7 {percent}%" diff --git a/core/src/main/resources/languages/lt_LT.toml b/core/src/main/resources/languages/lt_LT.toml index 49fd93ae6..fd8022320 100644 --- a/core/src/main/resources/languages/lt_LT.toml +++ b/core/src/main/resources/languages/lt_LT.toml @@ -1585,6 +1585,14 @@ failed_fragment = " nepavyko {failed}" "commandpack.update_world_unchanged" = "§aPasaulis '{world}' jau naudoja {pack} v{version} su tais pačiais generavimo nustatymais. Paleisti iš naujo nereikia." [iris.runtime.studio] +app_download_off = "Studio programos atsisiuntimas išjungtas: iris.json faile nustatykite studio.downloadApp į true." +app_no_display = "Šis serveris neturi ekrano, kuriame būtų galima atidaryti Studio programą." +app_downloading = "Studio programa dar atsisiunčiama; netrukus bandykite dar kartą." +app_unavailable = "Studio programa nepasiekiama; žr. konsolę." +app_not_built = "Studio programa nesukompiliuota: jos aplanke paleiskite npm run build." +app_failed_to_start = "Nepavyko paleisti Studio programos; žr. konsolę." +link_copy_button = "[Kopijuoti Studio nuorodą]" +link_copy_hover = "Įklijuokite ją Studio programos prisijungimo ekrane" opening = "§6Studio §bATIDAROMA" opening_progress = "§6Studio §bATIDAROMA§7 {percent}%" failed_progress = "§6Studio §cNEPAVYKO§7 {percent}%" diff --git a/core/src/main/resources/languages/nl_NL.toml b/core/src/main/resources/languages/nl_NL.toml index 871f58cea..f4c5d29dd 100644 --- a/core/src/main/resources/languages/nl_NL.toml +++ b/core/src/main/resources/languages/nl_NL.toml @@ -1580,6 +1580,14 @@ failed_fragment = " mislukt {failed}" "commandpack.update_world_unchanged" = "§aWereld '{world}' gebruikt al {pack} v{version} met dezelfde generatie-instellingen. Herstarten is niet nodig." [iris.runtime.studio] +app_download_off = "Download van de Studio-app staat uit: zet studio.downloadApp op true in iris.json." +app_no_display = "Deze server heeft geen scherm om de Studio-app op te openen." +app_downloading = "De Studio-app wordt nog gedownload; probeer het zo opnieuw." +app_unavailable = "Studio-app niet beschikbaar; zie de console." +app_not_built = "Studio-app niet gebouwd: voer npm run build uit in de map." +app_failed_to_start = "Studio-app kon niet starten; zie de console." +link_copy_button = "[Studio-link kopiëren]" +link_copy_hover = "Plak hem in het verbindingsscherm van de Studio-app" opening = "§6Studio §bOPENEN" opening_progress = "§6Studio §bOPENEN§7 {percent}%" failed_progress = "§6Studio §cMISLUKT§7 {percent}%" diff --git a/core/src/main/resources/languages/pl_PL.toml b/core/src/main/resources/languages/pl_PL.toml index 03d68ab3d..2d464d777 100644 --- a/core/src/main/resources/languages/pl_PL.toml +++ b/core/src/main/resources/languages/pl_PL.toml @@ -1585,6 +1585,14 @@ failed_fragment = " nieudane {failed}" "commandpack.update_world_unchanged" = "§aŚwiat '{world}' już używa {pack} v{version} z tymi samymi ustawieniami generowania. Restart nie jest potrzebny." [iris.runtime.studio] +app_download_off = "Pobieranie aplikacji Studio jest wyłączone: ustaw studio.downloadApp na true w iris.json." +app_no_display = "Ten serwer nie ma ekranu, na którym można otworzyć aplikację Studio." +app_downloading = "Aplikacja Studio wciąż się pobiera; spróbuj ponownie za chwilę." +app_unavailable = "Aplikacja Studio jest niedostępna; sprawdź konsolę." +app_not_built = "Aplikacja Studio nie jest zbudowana: uruchom npm run build w jej folderze." +app_failed_to_start = "Nie udało się uruchomić aplikacji Studio; sprawdź konsolę." +link_copy_button = "[Kopiuj link Studio]" +link_copy_hover = "Wklej go na ekranie połączenia aplikacji Studio" opening = "§6Studio §bOTWIERANIE" opening_progress = "§6Studio §bOTWIERANIE§7 {percent}%" failed_progress = "§6Studio §cNIEPOWODZENIE§7 {percent}%" diff --git a/core/src/main/resources/languages/pt_PT.toml b/core/src/main/resources/languages/pt_PT.toml index c9fb021fd..821ae8443 100644 --- a/core/src/main/resources/languages/pt_PT.toml +++ b/core/src/main/resources/languages/pt_PT.toml @@ -1580,6 +1580,14 @@ failed_fragment = " falhou {failed}" "commandpack.update_world_unchanged" = "§aO mundo '{world}' já utiliza {pack} v{version} com as mesmas definições de geração. Não é necessário reiniciar." [iris.runtime.studio] +app_download_off = "A transferência da app Studio está desligada: define studio.downloadApp como true no iris.json." +app_no_display = "Este servidor não tem ecrã onde abrir a app Studio." +app_downloading = "A app Studio ainda está a ser transferida; tenta novamente daqui a pouco." +app_unavailable = "A app Studio não está disponível; vê a consola." +app_not_built = "A app Studio não está compilada: executa npm run build na pasta dela." +app_failed_to_start = "Não foi possível iniciar a app Studio; vê a consola." +link_copy_button = "[Copiar link do Studio]" +link_copy_hover = "Cola-o no ecrã de ligação da app Studio" opening = "§6Studio §bA ABRIR" opening_progress = "§6Studio §bA ABRIR§7 {percent}%" failed_progress = "§6Studio §cFALHOU§7 {percent}%" diff --git a/core/src/main/resources/languages/ru_RU.toml b/core/src/main/resources/languages/ru_RU.toml index 4137db8ef..f5120412d 100644 --- a/core/src/main/resources/languages/ru_RU.toml +++ b/core/src/main/resources/languages/ru_RU.toml @@ -1585,6 +1585,14 @@ failed_fragment = " ошибок {failed}" "commandpack.update_world_unchanged" = "§aМир '{world}' уже использует {pack} v{version} с теми же настройками генерации. Перезапуск не требуется." [iris.runtime.studio] +app_download_off = "Загрузка приложения Studio отключена: установите studio.downloadApp в true в iris.json." +app_no_display = "У этого сервера нет дисплея, на котором можно открыть приложение Studio." +app_downloading = "Приложение Studio ещё загружается; попробуйте снова через минуту." +app_unavailable = "Приложение Studio недоступно; см. консоль." +app_not_built = "Приложение Studio не собрано: выполните npm run build в его папке." +app_failed_to_start = "Не удалось запустить приложение Studio; см. консоль." +link_copy_button = "[Копировать ссылку Studio]" +link_copy_hover = "Вставьте её на экране подключения приложения Studio" opening = "§6Studio §bОТКРЫТИЕ" opening_progress = "§6Studio §bОТКРЫТИЕ§7 {percent}%" failed_progress = "§6Studio §cОШИБКА§7 {percent}%" diff --git a/core/src/main/resources/languages/tr_TR.toml b/core/src/main/resources/languages/tr_TR.toml index f14fc4ff0..d1db26e1a 100644 --- a/core/src/main/resources/languages/tr_TR.toml +++ b/core/src/main/resources/languages/tr_TR.toml @@ -1585,6 +1585,14 @@ failed_fragment = " başarısız {failed}" "commandpack.update_world_unchanged" = "§a'{world}' dünyası aynı üretim ayarlarıyla zaten {pack} v{version} kullanıyor. Yeniden başlatma gerekmiyor." [iris.runtime.studio] +app_download_off = "Studio uygulaması indirmesi kapalı: iris.json içinde studio.downloadApp değerini true yap." +app_no_display = "Bu sunucuda Studio uygulamasını açacak bir ekran yok." +app_downloading = "Studio uygulaması hâlâ indiriliyor; birazdan tekrar dene." +app_unavailable = "Studio uygulaması kullanılamıyor; konsola bak." +app_not_built = "Studio uygulaması derlenmemiş: klasöründe npm run build çalıştır." +app_failed_to_start = "Studio uygulaması başlatılamadı; konsola bak." +link_copy_button = "[Studio bağlantısını kopyala]" +link_copy_hover = "Studio uygulamasının bağlantı ekranına yapıştır" opening = "§6Studio §bAÇILIYOR" opening_progress = "§6Studio §bAÇILIYOR§7 {percent}%" failed_progress = "§6Studio §cBAŞARISIZ§7 {percent}%" diff --git a/core/src/main/resources/languages/vi_VI.toml b/core/src/main/resources/languages/vi_VI.toml index 2d3e3d7b7..8c780f06b 100644 --- a/core/src/main/resources/languages/vi_VI.toml +++ b/core/src/main/resources/languages/vi_VI.toml @@ -1583,6 +1583,14 @@ failed_fragment = " lỗi {failed}" "commandpack.update_world_unchanged" = "§aThế giới '{world}' đã dùng {pack} v{version} với cùng thiết lập tạo địa hình. Không cần khởi động lại." [iris.runtime.studio] +app_download_off = "Tải ứng dụng Studio đang tắt: đặt studio.downloadApp thành true trong iris.json." +app_no_display = "Máy chủ này không có màn hình để mở ứng dụng Studio." +app_downloading = "Ứng dụng Studio vẫn đang tải; hãy thử lại sau giây lát." +app_unavailable = "Ứng dụng Studio không khả dụng; xem console." +app_not_built = "Ứng dụng Studio chưa được build: chạy npm run build trong thư mục của nó." +app_failed_to_start = "Không khởi động được ứng dụng Studio; xem console." +link_copy_button = "[Sao chép liên kết Studio]" +link_copy_hover = "Dán vào màn hình kết nối của ứng dụng Studio" opening = "§6Studio §bĐANG MỞ" opening_progress = "§6Studio §bĐANG MỞ§7 {percent}%" failed_progress = "§6Studio §cTHẤT BẠI§7 {percent}%" diff --git a/core/src/main/resources/languages/zh_CN.toml b/core/src/main/resources/languages/zh_CN.toml index abc8f1176..5ce2c1df5 100644 --- a/core/src/main/resources/languages/zh_CN.toml +++ b/core/src/main/resources/languages/zh_CN.toml @@ -1583,6 +1583,14 @@ failed_fragment = " 失败 {failed}" "commandpack.update_world_unchanged" = "§a世界 '{world}' 已使用 {pack} v{version},且生成设置相同。无需重启。" [iris.runtime.studio] +app_download_off = "Studio 应用下载已关闭:请在 iris.json 中将 studio.downloadApp 设为 true。" +app_no_display = "此服务器没有可打开 Studio 应用的显示器。" +app_downloading = "Studio 应用仍在下载;请稍后再试。" +app_unavailable = "Studio 应用不可用;请查看控制台。" +app_not_built = "Studio 应用未构建:请在其文件夹中运行 npm run build。" +app_failed_to_start = "Studio 应用启动失败;请查看控制台。" +link_copy_button = "[复制 Studio 链接]" +link_copy_hover = "粘贴到 Studio 应用的连接界面" opening = "§6Studio §b正在打开" opening_progress = "§6Studio §b正在打开§7 {percent}%" failed_progress = "§6Studio §c失败§7 {percent}%" diff --git a/core/src/main/resources/languages/zh_TW.toml b/core/src/main/resources/languages/zh_TW.toml index d97b370aa..9523efdd2 100644 --- a/core/src/main/resources/languages/zh_TW.toml +++ b/core/src/main/resources/languages/zh_TW.toml @@ -1583,6 +1583,14 @@ failed_fragment = " 失敗 {failed}" "commandpack.update_world_unchanged" = "§a世界 '{world}' 已使用 {pack} v{version},且生成設定相同。無需重新啟動。" [iris.runtime.studio] +app_download_off = "Studio 應用程式下載已關閉:請在 iris.json 中將 studio.downloadApp 設為 true。" +app_no_display = "此伺服器沒有可開啟 Studio 應用程式的顯示器。" +app_downloading = "Studio 應用程式仍在下載;請稍後再試。" +app_unavailable = "Studio 應用程式無法使用;請查看主控台。" +app_not_built = "Studio 應用程式未建置:請在其資料夾中執行 npm run build。" +app_failed_to_start = "Studio 應用程式無法啟動;請查看主控台。" +link_copy_button = "[複製 Studio 連結]" +link_copy_hover = "貼到 Studio 應用程式的連線畫面" opening = "§6Studio §b正在開啟" opening_progress = "§6Studio §b正在開啟§7 {percent}%" failed_progress = "§6Studio §c失敗§7 {percent}%" diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/IrisCaveCarver3DCellKernelTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/IrisCaveCarver3DCellKernelTest.java index f147d7576..0949188db 100644 --- a/core/src/test/java/art/arcane/iris/generation/mantle/IrisCaveCarver3DCellKernelTest.java +++ b/core/src/test/java/art/arcane/iris/generation/mantle/IrisCaveCarver3DCellKernelTest.java @@ -85,7 +85,7 @@ public class IrisCaveCarver3DCellKernelTest { @Test public void packStyleProfilesSharingFieldsMatchGoldenWriteSequence() throws Exception { - assertScenario(Scenario.PACK_SHARED, 0xdbe20a1ca87f9cc7L, 269035); + assertScenario(Scenario.PACK_SHARED, 0xb464b50d050e766dL, 288720); } @Test diff --git a/core/src/test/java/art/arcane/iris/generation/noise/IrisNoiseGeneratorFractureMirrorTest.java b/core/src/test/java/art/arcane/iris/generation/noise/IrisNoiseGeneratorFractureMirrorTest.java new file mode 100644 index 000000000..1f77d9f0e --- /dev/null +++ b/core/src/test/java/art/arcane/iris/generation/noise/IrisNoiseGeneratorFractureMirrorTest.java @@ -0,0 +1,68 @@ +package art.arcane.iris.generation.noise; + +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.noise.NoiseGenerator; +import org.junit.Test; + +import static org.junit.Assert.assertTrue; + +public final class IrisNoiseGeneratorFractureMirrorTest { + private static final long SEED = 71L; + private static final int GRID_SIZE = 40; + private static final double GRID_STEP = 7.3D; + private static final double MIRRORED = 1.0E-12D; + private static final int ALLOWED_MIRRORED_SAMPLES = 2; + + @Test + public void aCompositeFractureIsNotMirroredAcrossTheDiagonal() { + IrisNoiseGenerator fractured = diagonalSymmetricRoot().setFracture(new KList<>(fracture())); + + assertTrue(mirroredSamples(fractured) <= ALLOWED_MIRRORED_SAMPLES); + } + + @Test + public void theDiagonalSymmetricRootIsMirroredWithoutAFracture() { + assertTrue(mirroredSamples(diagonalSymmetricRoot()) > ALLOWED_MIRRORED_SAMPLES); + } + + private static int mirroredSamples(IrisNoiseGenerator noise) { + int mirroredSamples = 0; + for (int i = 0; i < GRID_SIZE; i++) { + for (int j = i + 1; j < GRID_SIZE; j++) { + double a = i * GRID_STEP; + double b = j * GRID_STEP + 0.5D; + if (Math.abs(noise.getNoise(SEED, a, b, null) - noise.getNoise(SEED, b, a, null)) < MIRRORED) { + mirroredSamples++; + } + } + } + return mirroredSamples; + } + + private static IrisNoiseGenerator diagonalSymmetricRoot() { + IrisNoiseGenerator root = new IrisNoiseGenerator().setStyle(NoiseStyle.SIMPLEX.style()).setSeed(5L); + root.getGenerator(SEED, null, null).setGenerator(new DiagonalSymmetricGenerator()); + return root; + } + + private static IrisNoiseGenerator fracture() { + return new IrisNoiseGenerator().setStyle(NoiseStyle.SIMPLEX.style()).setSeed(9L).setZoom(40D).setOpacity(40D); + } + + private static final class DiagonalSymmetricGenerator implements NoiseGenerator { + @Override + public double noise(double x) { + return noise(x, 0D, 0D); + } + + @Override + public double noise(double x, double z) { + return noise(x, z, 0D); + } + + @Override + public double noise(double x, double y, double z) { + return 0.5D + (Math.sin(x * 0.11D) + Math.sin(y * 0.11D) + Math.sin(z * 0.11D)) / 6D; + } + } +} diff --git a/core/src/test/java/art/arcane/iris/generation/noise/IrisNoiseGeneratorFractureTest.java b/core/src/test/java/art/arcane/iris/generation/noise/IrisNoiseGeneratorFractureTest.java index 774fb7568..b1203c5b1 100644 --- a/core/src/test/java/art/arcane/iris/generation/noise/IrisNoiseGeneratorFractureTest.java +++ b/core/src/test/java/art/arcane/iris/generation/noise/IrisNoiseGeneratorFractureTest.java @@ -225,6 +225,11 @@ public final class IrisNoiseGeneratorFractureTest { private static double reference(IrisNoiseGenerator node, long superSeed, double xv, double zv, IrisData data, Engine engine) { + return reference(node, superSeed, xv, zv, data, engine, IrisNoiseGenerator.X_AXIS); + } + + private static double reference(IrisNoiseGenerator node, long superSeed, double xv, double zv, + IrisData data, Engine engine, int axis) { if (!node.isEnabled()) { return node.getOffsetY(); } @@ -234,14 +239,16 @@ public final class IrisNoiseGeneratorFractureTest { for (IrisNoiseGenerator child : node.getFracture()) { if (child.isEnabled()) { double offset = child.getOpacity() / 2D; - x += reference(child, superSeed + node.getSeed() + salt, xv, zv, data, engine) - offset; - z += reference(child, superSeed + node.getSeed() + salt, zv, xv, data, engine) - offset; + long childSeed = superSeed + node.getSeed() + salt; + x += reference(child, childSeed, xv, zv, data, engine, IrisNoiseGenerator.X_AXIS) - offset; + z += reference(child, childSeed, xv, zv, data, engine, IrisNoiseGenerator.Z_AXIS) - offset; } salt += 819; } double sampleX = (x / node.getZoom()) + node.getOffsetX(); double sampleZ = (z / node.getZoom()) + node.getOffsetZ(); - double result = node.getGenerator(superSeed, data, engine).noiseFast2D(sampleX, sampleZ) * node.getOpacity(); + CNG generator = node.getGenerator(superSeed, data, engine).reseededForAxis(axis); + double result = generator.noiseFast2D(sampleX, sampleZ) * node.getOpacity(); result = node.isNegative() ? -result + node.getOpacity() : result; result = (node.getExponent() != 1D ? result < 0D ? -Math.pow(-result, node.getExponent()) : Math.pow(result, node.getExponent()) : result) + node.getOffsetY(); diff --git a/core/src/test/java/art/arcane/iris/generation/noise/NoiseSeedCohesionTest.java b/core/src/test/java/art/arcane/iris/generation/noise/NoiseSeedCohesionTest.java index adcbcad0f..dd83f59e5 100644 --- a/core/src/test/java/art/arcane/iris/generation/noise/NoiseSeedCohesionTest.java +++ b/core/src/test/java/art/arcane/iris/generation/noise/NoiseSeedCohesionTest.java @@ -18,7 +18,7 @@ public class NoiseSeedCohesionTest { private static final long[] SEEDS = {813753L, -935731L, Long.MIN_VALUE}; private static final double[] COORDINATES = {-29_999_983.25D, -513D, -64D, -1D, 0D, 0.125D, 17D, 64D, 8192D, 29_999_983.25D}; private static final double PINNED_SAMPLE_SCALE = 1.0E9D; - private static final long PINNED_HASH_WINDOWS = 2597318414939754011L; + private static final long PINNED_HASH_WINDOWS = 6074446696529759284L; private static final long PINNED_HASH_MAC = -602781966673993721L; @Test diff --git a/core/src/test/java/art/arcane/iris/generation/stage/IrisDepositModifierOrderingTest.java b/core/src/test/java/art/arcane/iris/generation/stage/IrisDepositModifierOrderingTest.java index 3479b4a56..a067bd3be 100644 --- a/core/src/test/java/art/arcane/iris/generation/stage/IrisDepositModifierOrderingTest.java +++ b/core/src/test/java/art/arcane/iris/generation/stage/IrisDepositModifierOrderingTest.java @@ -208,6 +208,16 @@ public class IrisDepositModifierOrderingTest { return false; } + @Override + public boolean isLog() { + return false; + } + + @Override + public boolean isLeaves() { + return false; + } + @Override public boolean isFoliagePlantable() { return false; diff --git a/core/src/test/java/art/arcane/iris/generation/stage/IrisDepositModifierParityTest.java b/core/src/test/java/art/arcane/iris/generation/stage/IrisDepositModifierParityTest.java index bd11ff5ac..7fd6f7c06 100644 --- a/core/src/test/java/art/arcane/iris/generation/stage/IrisDepositModifierParityTest.java +++ b/core/src/test/java/art/arcane/iris/generation/stage/IrisDepositModifierParityTest.java @@ -466,6 +466,16 @@ public class IrisDepositModifierParityTest { return false; } + @Override + public boolean isLog() { + return false; + } + + @Override + public boolean isLeaves() { + return false; + } + @Override public boolean isFoliagePlantable() { return false; diff --git a/core/src/test/java/art/arcane/iris/generation/stage/IrisPerfectionModifierColumnTest.java b/core/src/test/java/art/arcane/iris/generation/stage/IrisPerfectionModifierColumnTest.java index c91f8340e..fcca913cc 100644 --- a/core/src/test/java/art/arcane/iris/generation/stage/IrisPerfectionModifierColumnTest.java +++ b/core/src/test/java/art/arcane/iris/generation/stage/IrisPerfectionModifierColumnTest.java @@ -339,6 +339,16 @@ public class IrisPerfectionModifierColumnTest { return false; } + @Override + public boolean isLog() { + return false; + } + + @Override + public boolean isLeaves() { + return false; + } + @Override public boolean isFoliagePlantable() { return false; diff --git a/core/src/test/java/art/arcane/iris/pack/validation/CompatFixtures.java b/core/src/test/java/art/arcane/iris/pack/validation/CompatFixtures.java index e4397e193..9fe96f37c 100644 --- a/core/src/test/java/art/arcane/iris/pack/validation/CompatFixtures.java +++ b/core/src/test/java/art/arcane/iris/pack/validation/CompatFixtures.java @@ -252,6 +252,16 @@ final class CompatFixtures { return false; } + @Override + public boolean isLog() { + return false; + } + + @Override + public boolean isLeaves() { + return false; + } + @Override public boolean isFoliagePlantable() { return false; diff --git a/core/src/test/java/art/arcane/iris/pack/value/IrisMathNoiseHotPathParityTest.java b/core/src/test/java/art/arcane/iris/pack/value/IrisMathNoiseHotPathParityTest.java index 26b0b7458..0ba33fb6a 100644 --- a/core/src/test/java/art/arcane/iris/pack/value/IrisMathNoiseHotPathParityTest.java +++ b/core/src/test/java/art/arcane/iris/pack/value/IrisMathNoiseHotPathParityTest.java @@ -38,17 +38,17 @@ public class IrisMathNoiseHotPathParityTest { .setStyle(NoiseStyle.PERLIN_IRIS.style()) .setExponent(1.15D); - assertEquals(0.5084984235498856D, noiseGenerator.getNoise(9988L, 31.25D, -17.5D, null), 0D); + assertEquals(0.4646529061250786D, noiseGenerator.getNoise(9988L, 31.25D, -17.5D, null), 0D); IrisGeneratorStyle style = NoiseStyle.IRIS_DOUBLE.style(); - assertEquals(0.6224926166486215D, style.createNoCache(new RNG(112233L), null).noiseFast2D(42.5D, -19.75D), 0D); + assertEquals(0.6855680984398492D, style.createNoCache(new RNG(112233L), null).noiseFast2D(42.5D, -19.75D), 0D); IrisGenerator generator = new IrisGenerator() .setZoom(9.5D) .setOpacity(0.91D) .setComposite(new KList().qadd(noiseGenerator)); - assertEquals(0.43997118860461754D, generator.getHeight(63.0D, -27.0D, 445566L), 0D); + assertEquals(0.5023367573389593D, generator.getHeight(63.0D, -27.0D, 445566L), 0D); } @Test diff --git a/core/src/test/java/art/arcane/iris/platform/bukkit/BukkitPersistedBlockStateTest.java b/core/src/test/java/art/arcane/iris/platform/bukkit/BukkitPersistedBlockStateTest.java index 8b01a3f29..610ed03dc 100644 --- a/core/src/test/java/art/arcane/iris/platform/bukkit/BukkitPersistedBlockStateTest.java +++ b/core/src/test/java/art/arcane/iris/platform/bukkit/BukkitPersistedBlockStateTest.java @@ -119,8 +119,12 @@ public class BukkitPersistedBlockStateTest { IrisCustomData custom = IrisCustomData.of(carrier, Identifier.fromString(key)); ExternalDataSVC provider = mock(ExternalDataSVC.class); when(provider.getBlockData(Identifier.fromString(key))).thenReturn(Optional.of(custom)); - try (MockedStatic services = mockStatic(IrisServices.class)) { + when(provider.withoutDecay(custom)).thenReturn(custom); + IrisSettings configuration = new IrisSettings(); + try (MockedStatic services = mockStatic(IrisServices.class); + MockedStatic settings = mockStatic(IrisSettings.class)) { services.when(() -> IrisServices.get(ExternalDataSVC.class)).thenReturn(provider); + settings.when(IrisSettings::get).thenReturn(configuration); NativeBlockState decoded = registries.decodeBlockState(key); assertEquals(key, decoded.key()); assertEquals(key, decoded.deferredPlacementKey()); diff --git a/core/src/test/java/art/arcane/iris/structure/object/IrisObjectTransformsNearestBlockIndexTest.java b/core/src/test/java/art/arcane/iris/structure/object/IrisObjectTransformsNearestBlockIndexTest.java index e06a899be..c95928573 100644 --- a/core/src/test/java/art/arcane/iris/structure/object/IrisObjectTransformsNearestBlockIndexTest.java +++ b/core/src/test/java/art/arcane/iris/structure/object/IrisObjectTransformsNearestBlockIndexTest.java @@ -172,6 +172,16 @@ public class IrisObjectTransformsNearestBlockIndexTest { return false; } + @Override + public boolean isLog() { + return false; + } + + @Override + public boolean isLeaves() { + return false; + } + @Override public boolean isFoliagePlantable() { return false; diff --git a/core/src/test/java/art/arcane/iris/structure/object/ObjectLeafAndLogRulesTest.java b/core/src/test/java/art/arcane/iris/structure/object/ObjectLeafAndLogRulesTest.java new file mode 100644 index 000000000..1f3716ec2 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/structure/object/ObjectLeafAndLogRulesTest.java @@ -0,0 +1,92 @@ +package art.arcane.iris.structure.object; + +import art.arcane.volmlib.nativelib.terrain.NativeBlockState; +import org.junit.Test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class ObjectLeafAndLogRulesTest { + @Test + public void leavesNeverCutALog() { + assertTrue(ObjectBlockPass.keepsExisting(leaves(), log())); + } + + @Test + public void leavesReplaceOtherLeavesAndAir() { + assertFalse(ObjectBlockPass.keepsExisting(leaves(), leaves())); + assertFalse(ObjectBlockPass.keepsExisting(leaves(), null)); + } + + @Test + public void logsStillReplaceLeaves() { + assertFalse(ObjectBlockPass.keepsExisting(log(), leaves())); + } + + @Test + public void vinesStillKeepSolidBlocks() { + NativeBlockState vine = mock(NativeBlockState.class); + when(vine.isVineBlock()).thenReturn(true); + NativeBlockState solid = mock(NativeBlockState.class); + when(solid.isSolid()).thenReturn(true); + + assertTrue(ObjectBlockPass.keepsExisting(vine, solid)); + assertFalse(ObjectBlockPass.keepsExisting(vine, leaves())); + } + + @Test + public void customLeavesLosingTheirDecayAreMadePersistent() { + NativeBlockState persistent = mock(NativeBlockState.class); + NativeBlockState decaying = mock(NativeBlockState.class); + when(decaying.key()).thenReturn("craftengine:test/leaves[persistent=false,distance=7]"); + when(decaying.withProperty("persistent", "true")).thenReturn(persistent); + + assertSame(persistent, paletteOf(true, decaying).decayed(0)); + } + + @Test + public void customLeavesWithoutADistanceAreMadePersistentToo() { + NativeBlockState persistent = mock(NativeBlockState.class); + NativeBlockState decaying = mock(NativeBlockState.class); + when(decaying.key()).thenReturn("craftengine:test/leaves[persistent=false]"); + when(decaying.withProperty("persistent", "true")).thenReturn(persistent); + + assertSame(persistent, paletteOf(true, decaying).decayed(0)); + } + + @Test + public void decayIsLeftAloneWhenItIsNotPrevented() { + NativeBlockState decaying = mock(NativeBlockState.class); + when(decaying.key()).thenReturn("minecraft:oak_leaves[distance=3,persistent=false]"); + + assertSame(decaying, paletteOf(false, decaying).decayed(0)); + } + + @Test + public void blocksWithoutAPersistentPropertyAreLeftAlone() { + NativeBlockState stone = mock(NativeBlockState.class); + when(stone.key()).thenReturn("minecraft:stone"); + + assertSame(stone, paletteOf(true, stone).decayed(0)); + } + + private static PlacementPalette paletteOf(boolean preventingDecay, NativeBlockState state) { + return new PlacementPalette(new NativeBlockState[]{state}, new IrisObjectRotation(), 0, 0, 0, + preventingDecay, false, java.util.Set.of()); + } + + private static NativeBlockState leaves() { + NativeBlockState state = mock(NativeBlockState.class); + when(state.isLeaves()).thenReturn(true); + return state; + } + + private static NativeBlockState log() { + NativeBlockState state = mock(NativeBlockState.class); + when(state.isLog()).thenReturn(true); + return state; + } +} diff --git a/core/src/test/java/art/arcane/iris/structure/object/ObjectPlacementGoldenTest.java b/core/src/test/java/art/arcane/iris/structure/object/ObjectPlacementGoldenTest.java index e12a848ea..0562e30be 100644 --- a/core/src/test/java/art/arcane/iris/structure/object/ObjectPlacementGoldenTest.java +++ b/core/src/test/java/art/arcane/iris/structure/object/ObjectPlacementGoldenTest.java @@ -583,7 +583,17 @@ public class ObjectPlacementGoldenTest { @Override public boolean isTreeBlock() { - return material.endsWith("_log") || material.endsWith("_leaves"); + return isLog() || isLeaves(); + } + + @Override + public boolean isLog() { + return material.endsWith("_log"); + } + + @Override + public boolean isLeaves() { + return material.endsWith("_leaves"); } @Override diff --git a/core/src/test/java/art/arcane/iris/studio/app/BundledStudioAppTest.java b/core/src/test/java/art/arcane/iris/studio/app/BundledStudioAppTest.java new file mode 100644 index 000000000..7e9b1dad3 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/studio/app/BundledStudioAppTest.java @@ -0,0 +1,97 @@ +/* + * 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 . + */ + +package art.arcane.iris.studio.app; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.IOException; +import java.net.URL; +import java.net.URLClassLoader; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +public class BundledStudioAppTest { + @Rule + public TemporaryFolder temporary = new TemporaryFolder(); + + @Test + public void unpacksTheBundledAppIntoAFolderNamedByItsChecksum() throws IOException { + Path root = temporary.newFolder("studio").toPath(); + + try (URLClassLoader resources = jarResources(appArchive("out/main/index.js"))) { + Path app = BundledStudioApp.install(root, resources); + + assertTrue(app.getFileName().toString().matches("app-[0-9a-f]{12}")); + assertTrue(Files.isRegularFile(app.resolve("package.json"))); + assertTrue(Files.isRegularFile(app.resolve("out/main/index.js"))); + assertEquals(app, BundledStudioApp.install(root, resources)); + assertFalse(Files.exists(root.resolve("studio-app.zip.part"))); + } + } + + @Test + public void refusesAnArchiveEntryThatLeavesItsFolder() throws IOException { + Path root = temporary.newFolder("studio").toPath(); + + try (URLClassLoader resources = jarResources(appArchive("../../escaped.js"))) { + assertThrows(IOException.class, () -> BundledStudioApp.install(root, resources)); + } + assertFalse(Files.exists(root.getParent().resolve("escaped.js"))); + } + + @Test + public void reportsABuildWithoutTheApp() throws IOException { + Path root = temporary.newFolder("studio").toPath(); + + try (URLClassLoader resources = new URLClassLoader(new URL[0], null)) { + assertThrows(IOException.class, () -> BundledStudioApp.install(root, resources)); + } + } + + private Path appArchive(String scriptEntry) throws IOException { + Path archive = temporary.newFolder().toPath().resolve("studio-app.zip"); + try (ZipOutputStream zip = new ZipOutputStream(Files.newOutputStream(archive))) { + zip.putNextEntry(new ZipEntry("package.json")); + zip.write("{\"main\":\"out/main/index.js\"}".getBytes(StandardCharsets.UTF_8)); + zip.closeEntry(); + zip.putNextEntry(new ZipEntry(scriptEntry)); + zip.write("export {}".getBytes(StandardCharsets.UTF_8)); + zip.closeEntry(); + } + return archive; + } + + private URLClassLoader jarResources(Path archive) throws IOException { + Path classpath = temporary.newFolder().toPath(); + Path resource = classpath.resolve(BundledStudioApp.RESOURCE); + Files.createDirectories(resource.getParent()); + Files.copy(archive, resource); + return new URLClassLoader(new URL[]{classpath.toUri().toURL()}, null); + } +} diff --git a/core/src/test/java/art/arcane/iris/studio/app/ElectronRuntimeTest.java b/core/src/test/java/art/arcane/iris/studio/app/ElectronRuntimeTest.java new file mode 100644 index 000000000..dd7d4352e --- /dev/null +++ b/core/src/test/java/art/arcane/iris/studio/app/ElectronRuntimeTest.java @@ -0,0 +1,124 @@ +/* + * 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 . + */ + +package art.arcane.iris.studio.app; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermission; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +public class ElectronRuntimeTest { + private static final ElectronRuntime.Platform LINUX = new ElectronRuntime.Platform("linux-x64", "electron"); + private static final String ELECTRON_FIXTURE = "/studio-app/electron-fixture.zip"; + + @Rule + public TemporaryFolder temporary = new TemporaryFolder(); + + @Test + public void namesPlatformsTheWayElectronReleasesDo() { + assertEquals("linux-x64", ElectronRuntime.Platform.of("Linux", "amd64").name()); + assertEquals("linux-arm64", ElectronRuntime.Platform.of("Linux", "aarch64").name()); + assertEquals("electron.exe", ElectronRuntime.Platform.of("Windows 11", "amd64").executable()); + assertEquals("Electron.app/Contents/MacOS/Electron", ElectronRuntime.Platform.of("Mac OS X", "aarch64").executable()); + assertNull(ElectronRuntime.Platform.of("FreeBSD", "amd64")); + assertNull(ElectronRuntime.Platform.of("Linux", "riscv64")); + } + + @Test + public void downloadsFromTheElectronReleaseOfThePinnedVersion() throws IOException { + ElectronRuntime electron = ElectronRuntime.pinned(pins("45.2.3", "0".repeat(64)), LINUX); + + assertEquals(URI.create("https://github.com/electron/electron/releases/download/v45.2.3/electron-v45.2.3-linux-x64.zip"), + electron.source()); + } + + @Test + public void refusesAPlatformTheBuildDidNotPin() { + assertThrows(IOException.class, () -> ElectronRuntime.pinned(pins("45.2.3", "0".repeat(64)), + new ElectronRuntime.Platform("darwin-arm64", "Electron.app/Contents/MacOS/Electron"))); + } + + @Test + public void unpacksAVerifiedArchiveWithItsExecutableBitOnce() throws IOException { + Path archive = electronArchive(); + Path root = temporary.newFolder("studio").toPath(); + ElectronRuntime electron = ElectronRuntime.pinned(pins("45.2.3", ElectronRuntime.sha256(archive)), LINUX); + List downloads = new ArrayList<>(); + ElectronRuntime.Downloader downloader = (source, target) -> { + downloads.add(source); + Files.copy(archive, target); + }; + + Path executable = electron.install(root, downloader); + electron.install(root, downloader); + + assertEquals(root.resolve("electron-v45.2.3-linux-x64/electron"), executable); + Path lib = root.resolve("electron-v45.2.3-linux-x64/lib"); + assertTrue(Files.getPosixFilePermissions(executable).contains(PosixFilePermission.OWNER_EXECUTE)); + assertFalse(Files.getPosixFilePermissions(lib.resolve("libffmpeg.so")).contains(PosixFilePermission.OWNER_EXECUTE)); + assertEquals(Path.of("libffmpeg.so"), Files.readSymbolicLink(lib.resolve("libffmpeg.so.1"))); + assertEquals("library", Files.readString(lib.resolve("libffmpeg.so.1"))); + assertEquals(1, downloads.size()); + assertFalse(Files.exists(root.resolve("electron-v45.2.3-linux-x64.zip.part"))); + } + + @Test + public void leavesNothingInstalledWhenTheChecksumIsWrong() throws IOException { + Path archive = electronArchive(); + Path root = temporary.newFolder("studio").toPath(); + ElectronRuntime electron = ElectronRuntime.pinned(pins("45.2.3", "0".repeat(64)), LINUX); + + assertThrows(IOException.class, () -> electron.install(root, (source, target) -> Files.copy(archive, target))); + + try (var children = Files.list(root)) { + assertEquals(List.of(), children.toList()); + } + } + + /** Made by Info-ZIP, as Electron's archives are: an executable, a plain file and a symlink to it. */ + private Path electronArchive() throws IOException { + Path archive = temporary.getRoot().toPath().resolve("electron.zip"); + try (InputStream fixture = ElectronRuntimeTest.class.getResourceAsStream(ELECTRON_FIXTURE)) { + Files.copy(fixture, archive); + } + return archive; + } + + private static Properties pins(String version, String linuxChecksum) { + Properties pins = new Properties(); + pins.setProperty("electron.version", version); + pins.setProperty("linux-x64.sha256", linuxChecksum); + return pins; + } +} diff --git a/core/src/test/java/art/arcane/iris/studio/app/StudioAppInstallerTest.java b/core/src/test/java/art/arcane/iris/studio/app/StudioAppInstallerTest.java new file mode 100644 index 000000000..2d355086a --- /dev/null +++ b/core/src/test/java/art/arcane/iris/studio/app/StudioAppInstallerTest.java @@ -0,0 +1,38 @@ +/* + * 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 . + */ + +package art.arcane.iris.studio.app; + +import org.junit.Test; + +import java.util.Map; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class StudioAppInstallerTest { + @Test + public void seesADisplayOnlyWhenLinuxHasOne() { + assertTrue(StudioAppInstaller.hasDisplay("Linux", Map.of("WAYLAND_DISPLAY", "wayland-1"))); + assertTrue(StudioAppInstaller.hasDisplay("Linux", Map.of("DISPLAY", ":0"))); + assertFalse(StudioAppInstaller.hasDisplay("Linux", Map.of())); + assertFalse(StudioAppInstaller.hasDisplay("Linux", Map.of("DISPLAY", " "))); + assertTrue(StudioAppInstaller.hasDisplay("Windows 11", Map.of())); + assertTrue(StudioAppInstaller.hasDisplay("Mac OS X", Map.of())); + } +} diff --git a/core/src/test/java/art/arcane/iris/studio/tree/TreePlausibilizerTest.java b/core/src/test/java/art/arcane/iris/studio/tree/TreePlausibilizerTest.java index 55fbe5194..b1106e305 100644 --- a/core/src/test/java/art/arcane/iris/studio/tree/TreePlausibilizerTest.java +++ b/core/src/test/java/art/arcane/iris/studio/tree/TreePlausibilizerTest.java @@ -183,6 +183,16 @@ public class TreePlausibilizerTest { return false; } + @Override + public boolean isLog() { + return false; + } + + @Override + public boolean isLeaves() { + return false; + } + @Override public boolean isFoliagePlantable() { return false; diff --git a/core/src/test/java/art/arcane/iris/testsupport/KeyedBlockState.java b/core/src/test/java/art/arcane/iris/testsupport/KeyedBlockState.java index 8fcdce7ec..371c81acc 100644 --- a/core/src/test/java/art/arcane/iris/testsupport/KeyedBlockState.java +++ b/core/src/test/java/art/arcane/iris/testsupport/KeyedBlockState.java @@ -89,6 +89,16 @@ public final class KeyedBlockState implements NativeBlockState { return false; } + @Override + public boolean isLog() { + return false; + } + + @Override + public boolean isLeaves() { + return false; + } + @Override public boolean isFoliagePlantable() { return false; diff --git a/core/src/test/java/art/arcane/iris/testsupport/PlantBlockState.java b/core/src/test/java/art/arcane/iris/testsupport/PlantBlockState.java index d8c05756e..7d6b85207 100644 --- a/core/src/test/java/art/arcane/iris/testsupport/PlantBlockState.java +++ b/core/src/test/java/art/arcane/iris/testsupport/PlantBlockState.java @@ -136,6 +136,16 @@ public final class PlantBlockState implements NativeBlockState { return false; } + @Override + public boolean isLog() { + return false; + } + + @Override + public boolean isLeaves() { + return false; + } + @Override public boolean isFoliagePlantable() { return false; diff --git a/core/src/test/resources/studio-app/electron-fixture.zip b/core/src/test/resources/studio-app/electron-fixture.zip new file mode 100644 index 000000000..4bfdd0b60 Binary files /dev/null and b/core/src/test/resources/studio-app/electron-fixture.zip differ diff --git a/probe/src/main/java/art/arcane/iris/probe/StubPlatform.java b/probe/src/main/java/art/arcane/iris/probe/StubPlatform.java index 233a06aa8..fe58386c5 100644 --- a/probe/src/main/java/art/arcane/iris/probe/StubPlatform.java +++ b/probe/src/main/java/art/arcane/iris/probe/StubPlatform.java @@ -208,12 +208,21 @@ public final class StubPlatform implements IrisPlatform { @Override public boolean isTreeBlock() { + return isLog() || isLeaves(); + } + + @Override + public boolean isLog() { String blockKey = blockKey(); return blockKey.endsWith("_log") || blockKey.endsWith("_wood") || blockKey.endsWith("_stem") - || blockKey.endsWith("_hyphae") - || blockKey.endsWith("_leaves"); + || blockKey.endsWith("_hyphae"); + } + + @Override + public boolean isLeaves() { + return blockKey().endsWith("_leaves"); } @Override diff --git a/studio/package-lock.json b/studio/package-lock.json index fec043457..56977d11d 100644 --- a/studio/package-lock.json +++ b/studio/package-lock.json @@ -11,6 +11,7 @@ "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "cn": "^0.5.2", + "lucide-react": "^1.73.0", "radix-ui": "^1.8.1", "react": "^19.3.1", "react-dom": "^19.3.1", @@ -3806,6 +3807,21 @@ "yallist": "^3.0.2" } }, + "node_modules/lucide-react": { + "version": "1.73.0", + "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-1.73.0.tgz", + "integrity": "sha512-fVOzGviL9mTfHenG1PbCfIceavyGlnpYNSYr+aGZHLRymAJ7DTP6KHuqt0uBkCKAoenr1UVkwSbDIYt2xIesEQ==", + "license": "ISC", + "peerDependencies": { + "@types/react": "*", + "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, "node_modules/magic-string": { "version": "1.4.5", "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz", diff --git a/studio/package.json b/studio/package.json index 4e8bae009..b888410d0 100644 --- a/studio/package.json +++ b/studio/package.json @@ -31,6 +31,7 @@ "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "cn": "^0.5.2", + "lucide-react": "^1.73.0", "radix-ui": "^1.8.1", "react": "^19.3.1", "react-dom": "^19.3.1", diff --git a/studio/src/renderer/src/components/IdeIcon.tsx b/studio/src/renderer/src/components/IdeIcon.tsx deleted file mode 100644 index 83bead22a..000000000 --- a/studio/src/renderer/src/components/IdeIcon.tsx +++ /dev/null @@ -1,69 +0,0 @@ -import { cn } from '@/lib/utils' - -// IntelliJ's expui icons and the studio's own drawn to match (see icons/NOTICE.txt): each has a light file and a "_dark" twin in its own colours. -const ICON_URLS = import.meta.glob('../icons/**/*.svg', { eager: true, query: '?url', import: 'default' }) -const DARK_SUFFIX = '_dark' - -export type IdeIconName = - | 'actualZoom' - | 'add' - | 'blocks' - | 'borders' - | 'checked' - | 'closeSmall' - | 'chevronLeft' - | 'chevronRight' - | 'decoration' - | 'delete' - | 'exit' - | 'grid' - | 'groups' - | 'help' - | 'lightning' - | 'locate' - | 'locked' - | 'memory' - | 'mob' - | 'redo' - | 'refresh' - | 'reset' - | 'search' - | 'settings' - | 'shading' - | 'stopWatch' - | 'symlink' - | 'theme' - | 'undo' - | 'web' - | 'views/biomes' - | 'views/cave-profiles' - | 'views/fluid-profiles' - | 'views/formation-profiles' - | 'views/tree-profiles' - | 'views/noise' - | 'views/objects' - | 'views/palettes' - | 'views/procedural' - | 'views/regions' - | 'views/rivers' - | 'views/saved-world' - | 'views/world-3d' - -function iconUrl(name: string): string { - const url = ICON_URLS[`../icons/${name}.svg`] - if (url === undefined) { - throw new Error(`No icon named ${name}`) - } - return url -} - -/** An IntelliJ icon, 16 px unless sized, in the light or dark colours the window shows. */ -export function IdeIcon({ name, className }: { name: IdeIconName; className?: string }): React.JSX.Element { - const size = cn('size-4 shrink-0', className) - return ( - <> - - - - ) -} diff --git a/studio/src/renderer/src/components/ui/context-menu.tsx b/studio/src/renderer/src/components/ui/context-menu.tsx index 2c427349a..3dbc666bb 100644 --- a/studio/src/renderer/src/components/ui/context-menu.tsx +++ b/studio/src/renderer/src/components/ui/context-menu.tsx @@ -1,6 +1,6 @@ import * as React from "react" import { cn } from "@/lib/utils" -import { IdeIcon } from "@/components/IdeIcon" +import { Check, ChevronRight } from "lucide-react" import { ContextMenu as ContextMenuPrimitive } from "radix-ui" function ContextMenu({ @@ -70,7 +70,7 @@ function ContextMenuSubTrigger({ > {children} - + ) @@ -154,7 +154,7 @@ function ContextMenuCheckboxItem({ > - + {children} diff --git a/studio/src/renderer/src/components/ui/dialog.tsx b/studio/src/renderer/src/components/ui/dialog.tsx index c024d32ea..514919e37 100644 --- a/studio/src/renderer/src/components/ui/dialog.tsx +++ b/studio/src/renderer/src/components/ui/dialog.tsx @@ -2,7 +2,7 @@ import * as React from "react" import { cn } from "@/lib/utils" -import { IdeIcon } from "@/components/IdeIcon" +import { X } from "lucide-react" import { Dialog as DialogPrimitive } from "radix-ui" import { Button } from "@/components/ui/button" @@ -72,7 +72,7 @@ function DialogContent({ data-slot="dialog-close" className="absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4" > - + Close )} diff --git a/studio/src/renderer/src/components/ui/dropdown-menu.tsx b/studio/src/renderer/src/components/ui/dropdown-menu.tsx new file mode 100644 index 000000000..56a8e372e --- /dev/null +++ b/studio/src/renderer/src/components/ui/dropdown-menu.tsx @@ -0,0 +1,61 @@ +import * as React from "react" +import { cn } from "@/lib/utils" +import { ChevronRight } from "lucide-react" +import { DropdownMenu as DropdownMenuPrimitive } from "radix-ui" + +const MENU_SURFACE = + "z-50 min-w-[8rem] overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md backdrop-blur-sm data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0" +const MENU_ROW = + "relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50" + +function DropdownMenu(props: React.ComponentProps) { + return +} + +function DropdownMenuTrigger(props: React.ComponentProps) { + return +} + +function DropdownMenuContent({ className, sideOffset = 2, ...props }: React.ComponentProps) { + return ( + + + + ) +} + +function DropdownMenuItem({ className, ...props }: React.ComponentProps) { + return +} + +function DropdownMenuSub(props: React.ComponentProps) { + return +} + +function DropdownMenuSubTrigger({ className, children, ...props }: React.ComponentProps) { + return ( + + {children} + + + ) +} + +function DropdownMenuSubContent({ className, ...props }: React.ComponentProps) { + return ( + + + + ) +} + +export { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem, DropdownMenuSub, DropdownMenuSubTrigger, DropdownMenuSubContent } diff --git a/studio/src/renderer/src/components/ui/popover.tsx b/studio/src/renderer/src/components/ui/popover.tsx new file mode 100644 index 000000000..7598a30a8 --- /dev/null +++ b/studio/src/renderer/src/components/ui/popover.tsx @@ -0,0 +1,30 @@ +import * as React from "react" +import { cn } from "@/lib/utils" +import { Popover as PopoverPrimitive } from "radix-ui" + +function Popover(props: React.ComponentProps) { + return +} + +function PopoverAnchor(props: React.ComponentProps) { + return +} + +function PopoverContent({ className, align = "start", sideOffset = 4, ...props }: React.ComponentProps) { + return ( + + + + ) +} + +export { Popover, PopoverAnchor, PopoverContent } diff --git a/studio/src/renderer/src/editor/curves.test.ts b/studio/src/renderer/src/editor/curves.test.ts index 8e00a484b..d74723ca5 100644 --- a/studio/src/renderer/src/editor/curves.test.ts +++ b/studio/src/renderer/src/editor/curves.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { canBecomeCurve, curveAt, curveFrom, isCurve, keyframesFrom, samplesOf, shapeFrom, withAddedKeyframe, withKeyframe, withoutKeyframe, withSetting, withShape } from './curves' +import { canBecomeCurve, curveAt, curveFrom, curveLiteral, isCurve, keyframesFrom, plotRange, roundedNumber, samplesOf, shapeFrom, withAddedKeyframe, withKeyframe, withoutKeyframe, withSetting, withShape } from './curves' describe('isCurve', () => { it('holds only for keyframes and named shapes', () => { @@ -82,3 +82,27 @@ describe('editing keyframes', () => { expect(withoutKeyframe([[1, 3]], 0)).toEqual([[1, 3]]) }) }) + +describe('plotRange', () => { + it('spans 0 to 1 at least, a tenth past the highest, and below 0 only when the curve goes there', () => { + const rounded = (range: [number, number]): number[] => range.map((end) => Math.round(end * 100) / 100) + + expect(rounded(plotRange([0.2, 0.5]))).toEqual([0, 1.1]) + expect(rounded(plotRange([0, 3]))).toEqual([0, 3.3]) + expect(rounded(plotRange([-1, 1]))).toEqual([-1.2, 1.2]) + }) +}) + +describe('curveLiteral', () => { + it('writes keyframes and shapes spaced like hand-written JSON', () => { + expect(curveLiteral([[0, 1.4], [1, 0.4]])).toBe('[[0, 1.4], [1, 0.4]]') + expect(curveLiteral({ shape: 'power', from: 0, to: 2 })).toBe('{"shape": "power", "from": 0, "to": 2}') + }) +}) + +describe('roundedNumber', () => { + it('reads a number with two decimals at most', () => { + expect(roundedNumber(1.3333)).toBe('1.33') + expect(roundedNumber(2)).toBe('2') + }) +}) diff --git a/studio/src/renderer/src/editor/curves.ts b/studio/src/renderer/src/editor/curves.ts index 5cf2a1fc9..1e7d7bfdd 100644 --- a/studio/src/renderer/src/editor/curves.ts +++ b/studio/src/renderer/src/editor/curves.ts @@ -21,6 +21,8 @@ const NARROWEST_BELL = 1e-6 const SHAPE_STOPS = 5 const FIRST_STOP = 0 const LAST_STOP = 1 +const PLOT_MARGIN = 0.1 +const READ_PRECISION = 100 export const CURVE_SHAPES: CurveShape[] = [ { key: 'linear', parameters: [], at: (t) => t }, @@ -157,6 +159,27 @@ export function samplesOf(value: unknown, count: number): number[] | null { return Array.from({ length: count }, (_, index) => curveAt(value, count === 1 ? 0 : index / (count - 1))) } +/** + * The values a plot of the curve with {@code samples} spans: from 0 to 1 at least and a tenth past its highest. It goes + * below 0 only when the curve already does, since most values along a part, like a radius, can't be negative. + */ +export function plotRange(samples: number[]): [number, number] { + const low = Math.min(0, ...samples) + const high = Math.max(1, ...samples) + const margin = (high - low) * PLOT_MARGIN + return [low < 0 ? low - margin : 0, high + margin] +} + +/** The curve as the JSON written to the file, spaced like hand-written JSON: {@code [[0, 1.4], [1, 0.4]]}. */ +export function curveLiteral(curve: unknown): string { + return JSON.stringify(curve).replaceAll(',', ', ').replaceAll('":', '": ') +} + +/** A number only to be read, never typed back: two decimals at most, like 1.3 or 0.25. */ +export function roundedNumber(value: number): string { + return String(Math.round(value * READ_PRECISION) / READ_PRECISION) +} + /** The curve as keyframes, such as to move a named curve's shape by hand: its values at evenly spaced points. */ export function keyframesFrom(value: unknown): Keyframe[] { if (isKeyframes(value)) { diff --git a/studio/src/renderer/src/editor/nodeLayout.test.ts b/studio/src/renderer/src/editor/nodeLayout.test.ts index 78e4d8f97..07fd4fad0 100644 --- a/studio/src/renderer/src/editor/nodeLayout.test.ts +++ b/studio/src/renderer/src/editor/nodeLayout.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest' import type { GraphNode, JsonPath } from '../bridge/types' import { NO_PART } from '../bridge/types' -import { isWithin, layoutNodes, nodeDrawingPart, NODE_WIDTH } from './nodeLayout' +import { canRegrow, GRID, isWithin, layoutNodes, nodeAt, nodeDrawingPart, NODE_WIDTH, type PlacedNode } from './nodeLayout' function node(path: JsonPath, children: GraphNode[] = []): GraphNode { return { @@ -20,21 +20,65 @@ function node(path: JsonPath, children: GraphNode[] = []): GraphNode { } describe('layoutNodes', () => { - it('sets a parent level with the middle of its children, a column to their left', () => { - const layout = layoutNodes([node([], [node(['parts', 0]), node(['parts', 1]), node(['parts', 2])])]) - const [first, , last, parent] = layout.nodes + const height = (): number => 50 + const placedAt = (layout: ReturnType, path: JsonPath): PlacedNode => layout.nodes.find((placed) => placed.id === JSON.stringify(path))! - expect(parent.y).toBe((first.y + last.y) / 2) - expect(first.x - parent.x).toBeGreaterThan(NODE_WIDTH) - expect(layout.wires).toHaveLength(3) + it('sets a node level with its first child, a column to its left, and each next child on the rows below', () => { + const layout = layoutNodes([node([], [node(['parts', 0]), node(['parts', 1])])], height) + const [parent, first, second] = [placedAt(layout, []), placedAt(layout, ['parts', 0]), placedAt(layout, ['parts', 1])] + + expect(first.y).toBe(parent.y) + expect(first.x - parent.x).toBe(NODE_WIDTH + 2 * GRID) + expect(second.y).toBeGreaterThanOrEqual(first.y + 50 + 10) + expect(layout.wires).toHaveLength(2) }) - it('lays the next root out under the tree before it', () => { - const layout = layoutNodes([node([], [node(['parts', 0])]), node(['materials', 0])]) - const material = layout.nodes.find((placed) => placed.id === JSON.stringify(['materials', 0]))! + it('stacks the other roots under the first, in its column, and starts every node on a grid point', () => { + const layout = layoutNodes([node([], [node(['parts', 0])]), node(['materials', 0])], height) + const [object, material] = [placedAt(layout, []), placedAt(layout, ['materials', 0])] - expect(material.x).toBe(0) - expect(material.y).toBeGreaterThan(Math.max(...layout.nodes.filter((placed) => placed !== material).map((placed) => placed.y))) + expect(material.x).toBe(object.x) + expect(material.y).toBeGreaterThan(object.y + 50) + expect(layout.nodes.every((placed) => placed.x % GRID === 0 && placed.y % GRID === 0)).toBe(true) + }) + + it('makes room below a tall node before its next sibling', () => { + const tall = (graphNode: GraphNode): number => (graphNode.path.length === 2 && graphNode.path[1] === 0 ? 300 : 50) + const layout = layoutNodes([node([], [node(['parts', 0]), node(['parts', 1])])], tall) + + expect(placedAt(layout, ['parts', 1]).y).toBeGreaterThan(placedAt(layout, ['parts', 0]).y + 300) + }) + + it('puts a node where it was dragged, and marks which nodes have sockets', () => { + const layout = layoutNodes([node([], [node(['parts', 0])])], height, new Map([[JSON.stringify(['parts', 0]), { x: 500, y: 44 }]])) + const part = placedAt(layout, ['parts', 0]) + + expect([part.x, part.y]).toEqual([500, 44]) + expect([part.grown, part.growing]).toEqual([true, false]) + expect([placedAt(layout, []).grown, placedAt(layout, []).growing]).toEqual([false, true]) + }) +}) + +describe('nodeAt', () => { + it('finds the node under a point by its own height', () => { + const layout = layoutNodes([node([], [node(['parts', 0])])], () => 50) + const part = layout.nodes[1] + + expect(nodeAt(layout.nodes, { x: part.x + 5, y: part.y + 49 })?.id).toBe(part.id) + expect(nodeAt(layout.nodes, { x: part.x + 5, y: part.y + 51 })).toBeNull() + }) +}) + +describe('canRegrow', () => { + const withList = (path: JsonPath, children: GraphNode[] = []): GraphNode => ({ ...node(path, children), childList: [...path, 'children'] }) + + it('lets a part grow from another that takes children, but not from inside itself or where it already grows', () => { + const part = withList(['parts', 0]) + + expect(canRegrow(part, withList(['parts', 1]))).toBe(true) + expect(canRegrow(part, withList(['parts', 0, 'children', 0]))).toBe(false) + expect(canRegrow(withList(['parts', 1, 'children', 0]), withList(['parts', 1]))).toBe(false) + expect(canRegrow({ ...part, movable: false }, withList(['parts', 1]))).toBe(false) }) }) diff --git a/studio/src/renderer/src/editor/nodeLayout.ts b/studio/src/renderer/src/editor/nodeLayout.ts index 4f300a441..5e2ba68a3 100644 --- a/studio/src/renderer/src/editor/nodeLayout.ts +++ b/studio/src/renderer/src/editor/nodeLayout.ts @@ -1,10 +1,16 @@ import type { GraphNode, JsonPath } from '../bridge/types' -export const NODE_WIDTH = 168 -export const NODE_HEIGHT = 46 -const COLUMN_GAP = 64 -const ROW_GAP = 10 -const TREE_GAP = 26 +/** The spacing nodes snap to, and the dots of the canvas mark. */ +export const GRID = 22 +export const NODE_WIDTH = 12 * GRID +const MARGIN = GRID +const COLUMN_GAP = 2 * GRID +const MIN_ROW_GAP = 10 + +export interface Point { + x: number + y: number +} /** A node where the canvas draws it, by its top left corner; `id` tells it from every other node of the file. */ export interface PlacedNode { @@ -12,6 +18,11 @@ export interface PlacedNode { node: GraphNode x: number y: number + height: number + /** Whether it grows from another node, so it has an input socket. */ + grown: boolean + /** Whether other nodes grow from it, so it has an output socket. */ + growing: boolean } export interface PlacedWire { @@ -23,8 +34,13 @@ export interface PlacedWire { export interface NodeLayout { nodes: PlacedNode[] wires: PlacedWire[] - width: number - height: number +} + +export interface Bounds { + left: number + top: number + right: number + bottom: number } export function idOf(path: JsonPath): string { @@ -71,38 +87,95 @@ export function isWithin(path: JsonPath, ancestor: JsonPath): boolean { return ancestor.length <= path.length && ancestor.every((step, index) => path[index] === step) } +export function snappedToGrid(coordinate: number): number { + return Math.round(coordinate / GRID) * GRID +} + +function nextRowBelow(bottom: number): number { + return Math.ceil((bottom + MIN_ROW_GAP) / GRID) * GRID +} + +function columnLeft(column: number): number { + return MARGIN + column * (NODE_WIDTH + COLUMN_GAP) +} + /** - * Lays each root's tree out from left to right, a column per generation, one tree under the other. Leaves take a row - * each and a parent sits level with the middle of its children, so wires never cross. + * Lays the nodes out on the grid: the roots, such as the object, its materials and its decorations, stacked in the + * first column, and what grows from them to the right, a column per generation. Each subtree takes the rows below the + * last, and a node sits level with its first child, so it is read beside what grows from it. A node in + * {@code placed}, by its id, sits where it was dragged instead. */ -export function layoutNodes(roots: GraphNode[]): NodeLayout { +export function layoutNodes(roots: GraphNode[], heightOf: (node: GraphNode) => number, placed: ReadonlyMap = new Map()): NodeLayout { const nodes: PlacedNode[] = [] const wires: PlacedWire[] = [] - let nextTop = 0 - let width = 0 - const place = (node: GraphNode, depth: number): PlacedNode => { - const x = depth * (NODE_WIDTH + COLUMN_GAP) - width = Math.max(width, x + NODE_WIDTH) - const children = node.children.map((link) => ({ label: link.wire, placed: place(link.node, depth + 1) })) - const y = children.length === 0 ? takeRow() : (children[0].placed.y + children[children.length - 1].placed.y) / 2 - const placed: PlacedNode = { id: idOf(node.path), node, x, y } - nodes.push(placed) - for (const child of children) { - wires.push({ from: placed, to: child.placed, label: child.label }) + const add = (node: GraphNode, x: number, y: number, grown: boolean): PlacedNode => { + const id = idOf(node.path) + const at = placed.get(id) ?? { x, y } + const box: PlacedNode = { id, node, x: at.x, y: at.y, height: heightOf(node), grown, growing: node.children.length > 0 } + nodes.push(box) + return box + } + + // Returns the bottom of the subtree as laid out, which a node dragged elsewhere does not change. + const placeTree = (link: GraphNode['children'][number], parent: PlacedNode, column: number, top: number): number => { + const box = add(link.node, columnLeft(column), top, true) + wires.push({ from: parent, to: box, label: link.wire }) + let bottom = top + box.height + let childTop = top + for (const child of link.node.children) { + const childBottom = placeTree(child, box, column + 1, childTop) + bottom = Math.max(bottom, childBottom) + childTop = nextRowBelow(childBottom) } - return placed + return bottom } - const takeRow = (): number => { - const top = nextTop - nextTop += NODE_HEIGHT + ROW_GAP - return top + let firstColumnTop = MARGIN + const rootBoxes = roots.map((root) => { + const box = add(root, MARGIN, firstColumnTop, false) + firstColumnTop = nextRowBelow(firstColumnTop + box.height) + return box + }) + let treeTop = MARGIN + roots.forEach((root, index) => { + for (const link of root.children) { + treeTop = nextRowBelow(placeTree(link, rootBoxes[index], 1, treeTop)) + } + }) + return { nodes, wires } +} + +/** The smallest rectangle around every node; null when there are none. */ +export function boundsOf(nodes: PlacedNode[]): Bounds | null { + if (nodes.length === 0) { + return null + } + return { + left: Math.min(...nodes.map((node) => node.x)), + top: Math.min(...nodes.map((node) => node.y)), + right: Math.max(...nodes.map((node) => node.x + NODE_WIDTH)), + bottom: Math.max(...nodes.map((node) => node.y + node.height)) + } +} + +/** The node under {@code point}, the one drawn last when they overlap; null over the background. */ +export function nodeAt(nodes: PlacedNode[], point: Point): PlacedNode | null { + for (let index = nodes.length - 1; index >= 0; index--) { + const box = nodes[index] + if (point.x >= box.x && point.x <= box.x + NODE_WIDTH && point.y >= box.y && point.y <= box.y + box.height) { + return box + } } + return null +} - for (const root of roots) { - place(root, 0) - nextTop += TREE_GAP +/** Whether {@code dragged} may grow from {@code over}: it takes children, and is neither inside it nor already its parent. */ +export function canRegrow(dragged: GraphNode, over: GraphNode): boolean { + const toList = over.childList + if (!dragged.movable || toList === null || isWithin(toList, dragged.path)) { + return false } - return { nodes, wires, width, height: Math.max(0, nextTop - ROW_GAP - TREE_GAP) } + const alreadyThere = dragged.path.length === toList.length + 1 && isWithin(dragged.path, toList) + return !alreadyThere } diff --git a/studio/src/renderer/src/editor/nodePositions.test.ts b/studio/src/renderer/src/editor/nodePositions.test.ts new file mode 100644 index 000000000..c73495e97 --- /dev/null +++ b/studio/src/renderer/src/editor/nodePositions.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, it } from 'vitest' +import { idOf } from './nodeLayout' +import { pathAfterRemoval, positionsAfterEdit } from './nodePositions' + +const at = { x: 44, y: 88 } + +describe('pathAfterRemoval', () => { + it('moves an element after the removed one, and what it holds, up an index', () => { + expect(pathAfterRemoval(['parts', 2, 'children', 0], ['parts', 1])).toEqual(['parts', 1, 'children', 0]) + }) + + it('leaves an element before it and one of another array alone', () => { + expect(pathAfterRemoval(['parts', 0], ['parts', 1])).toEqual(['parts', 0]) + expect(pathAfterRemoval(['materials', 3], ['parts', 1])).toEqual(['materials', 3]) + }) +}) + +describe('positionsAfterEdit', () => { + it('drops a deleted node and what grows from it, and moves the later ones up', () => { + const positions = { [idOf(['parts', 0])]: at, [idOf(['parts', 0, 'children', 0])]: at, [idOf(['parts', 1])]: at } + + expect(positionsAfterEdit(positions, { op: 'delete', path: ['parts', 0] }, {})).toEqual({ [idOf(['parts', 0])]: at }) + }) + + it('keeps a moved node where it was, under the path it gets at the end of the list it joins', () => { + const values = { parts: [{}, { children: [{}] }] } + const positions = { [idOf(['parts', 0])]: at, [idOf(['parts', 0, 'children', 0])]: { x: 0, y: 0 } } + + expect(positionsAfterEdit(positions, { op: 'move', path: ['parts', 0], toList: ['parts', 1, 'children'] }, values)).toEqual({ + [idOf(['parts', 0, 'children', 1])]: at, + [idOf(['parts', 0, 'children', 1, 'children', 0])]: { x: 0, y: 0 } + }) + }) + + it('leaves the positions as they were for an edit that moves no node', () => { + const positions = { [idOf(['parts', 0])]: at } + + expect(positionsAfterEdit(positions, { op: 'set', object: ['parts', 0], key: 'role', literal: '"a"' }, {})).toBe(positions) + }) +}) diff --git a/studio/src/renderer/src/editor/nodePositions.ts b/studio/src/renderer/src/editor/nodePositions.ts new file mode 100644 index 000000000..321a4e94c --- /dev/null +++ b/studio/src/renderer/src/editor/nodePositions.ts @@ -0,0 +1,45 @@ +import type { GraphEdit, JsonPath } from '../bridge/types' +import { valueAt } from './jsonValues' +import { idOf, isWithin, type Point } from './nodeLayout' + +/** Where nodes were dragged to, by the id of their path in the file. */ +export type NodePositions = Readonly> + +/** + * The positions after {@code edit} changed the file {@code values} holds. A deleted node's position goes; the + * elements after a removed one move up an index, and so do the positions named by them. A moved node keeps its + * position under its new path, at the end of the list it joins. + */ +export function positionsAfterEdit(positions: NodePositions, edit: GraphEdit, values: unknown): NodePositions { + if (edit.op === 'delete') { + return remapped(positions, (path) => (isWithin(path, edit.path) ? null : pathAfterRemoval(path, edit.path))) + } + if (edit.op !== 'move') { + return positions + } + const joined = valueAt(values, edit.toList) + const newPath = [...pathAfterRemoval(edit.toList, edit.path), Array.isArray(joined) ? joined.length : 0] + return remapped(positions, (path) => (isWithin(path, edit.path) ? [...newPath, ...path.slice(edit.path.length)] : pathAfterRemoval(path, edit.path))) +} + +/** {@code path} once the array element at {@code removed} is gone: one index lower when it is after it in that array. */ +export function pathAfterRemoval(path: JsonPath, removed: JsonPath): JsonPath { + const index = removed.at(-1) + const array = removed.slice(0, -1) + const step = path[array.length] + if (typeof index !== 'number' || path.length <= array.length || !isWithin(path, array) || typeof step !== 'number' || step <= index) { + return path + } + return [...array, step - 1, ...path.slice(array.length + 1)] +} + +function remapped(positions: NodePositions, newPathOf: (path: JsonPath) => JsonPath | null): NodePositions { + const next: Record = {} + for (const [id, position] of Object.entries(positions)) { + const newPath = newPathOf(JSON.parse(id) as JsonPath) + if (newPath !== null) { + next[idOf(newPath)] = position + } + } + return next +} diff --git a/studio/src/renderer/src/editor/nodeRows.test.ts b/studio/src/renderer/src/editor/nodeRows.test.ts new file mode 100644 index 000000000..3dd7edc24 --- /dev/null +++ b/studio/src/renderer/src/editor/nodeRows.test.ts @@ -0,0 +1,69 @@ +import { describe, expect, it } from 'vitest' +import type { GraphNode, SettingOption, SettingsType, ValueKind } from '../bridge/types' +import { NODE_HEADER, NODE_HEADING, NODE_PADDING, NODE_ROW, NODE_STRIPE, nodeRows } from './nodeRows' + +function option(name: string, kind: ValueKind): SettingOption { + return { name, description: '', required: false, minimum: null, maximum: null, minItems: null, defaultValue: null, kind } +} + +const any: ValueKind = { kind: 'any' } +const types: Record = { + Part: { description: '', options: [option('role', { kind: 'text', format: 'PLAIN' }), option('offset', { kind: 'object', type: 'Offset' })] }, + Stem: { description: '', options: [option('length', any), option('taper', any)] }, + Offset: { description: '', options: [option('x', any), option('y', any)] } +} + +const stem: GraphNode = { + kind: 'Stem', + title: 'Stem', + path: ['parts', 0], + partId: 0, + roles: ['wood'], + settings: [ + { title: 'Part', path: ['parts', 0], type: 'Part', shownAsNodes: [] }, + { title: 'Stem', path: ['parts', 0, 'stem'], type: 'Stem', shownAsNodes: [] } + ], + children: [], + childList: null, + movable: true, + duplicable: true, + additions: [] +} + +const file = { parts: [{ role: 'wood', offset: { x: 2 }, stem: { length: 6 } }] } + +describe('nodeRows', () => { + it('lists the first section plainly, a later one under its heading, and a folded section as one row', () => { + const { rows } = nodeRows(stem, types, file, new Set(), true) + + expect(rows.map((row) => row.kind)).toEqual(['setting', 'fold', 'heading', 'setting', 'addSetting']) + expect(rows.flatMap((row) => (row.kind === 'setting' ? [row.option.name, row.value] : []))).toEqual(['role', 'wood', 'length', 6]) + }) + + it('lists what an unfolded section holds right under it', () => { + const { rows } = nodeRows(stem, types, file, new Set([JSON.stringify(['parts', 0, 'offset'])]), true) + + expect(rows.map((row) => (row.kind === 'setting' ? row.option.name : row.kind))).toEqual(['role', 'fold', 'x', 'heading', 'length', 'addSetting']) + }) + + it('adds up its height from its rows', () => { + const { height } = nodeRows(stem, types, file, new Set(), true) + + expect(height).toBe(NODE_STRIPE + NODE_HEADER + 4 * NODE_ROW + NODE_HEADING + NODE_PADDING) + }) + + it('offers the sections with settings left to add, but no row to add them while the file is read only', () => { + const editable = nodeRows(stem, types, file, new Set(), true) + const readOnly = nodeRows(stem, types, file, new Set(), false) + + expect(editable.addable.map((fold) => fold.title)).toEqual(['offset', 'Stem']) + expect(readOnly.rows.some((row) => row.kind === 'addSetting')).toBe(false) + }) + + it('draws a node without settings, such as a shared part, as its header alone', () => { + const { rows, height } = nodeRows({ ...stem, settings: [] }, types, file, new Set(), true) + + expect(rows).toEqual([]) + expect(height).toBe(NODE_STRIPE + NODE_HEADER + NODE_PADDING) + }) +}) diff --git a/studio/src/renderer/src/editor/nodeRows.ts b/studio/src/renderer/src/editor/nodeRows.ts new file mode 100644 index 000000000..df996e488 --- /dev/null +++ b/studio/src/renderer/src/editor/nodeRows.ts @@ -0,0 +1,67 @@ +import type { GraphNode, SettingOption, SettingsType } from '../bridge/types' +import { valueAt } from './jsonValues' +import { idOf } from './nodeLayout' +import { foldedSections, idOfFold, visibleFolds, type SettingsFold } from './settingFolds' + +export const NODE_STRIPE = 3 +export const NODE_HEADER = 28 +export const NODE_ROW = 24 +export const NODE_HEADING = 20 +export const NODE_PADDING = 8 + +export type NodeRow = + | { kind: 'heading'; id: string; fold: SettingsFold } + | { kind: 'fold'; id: string; fold: SettingsFold; open: boolean } + | { kind: 'setting'; id: string; fold: SettingsFold; option: SettingOption; value: unknown } + | { kind: 'addSetting'; id: string } + +/** What a node lists below its header, how tall that makes it, and the sections that have settings left to add. */ +export interface NodeRows { + rows: NodeRow[] + height: number + addable: SettingsFold[] +} + +const ADD_SETTING_ID = 'add-setting' + +export function heightOfRow(row: NodeRow): number { + return row.kind === 'heading' ? NODE_HEADING : NODE_ROW +} + +/** + * The rows of {@code node}: each of its sections' settings, the first section's plainly, a later one's under its + * heading, and a folding section's only while it is in {@code open}. An editable node with settings left to add ends + * in a row to add one. + */ +export function nodeRows(node: GraphNode, types: Record, values: unknown, open: ReadonlySet, editable: boolean): NodeRows { + const rows: NodeRow[] = [] + const addable: SettingsFold[] = [] + let ownSections = 0 + for (const section of node.settings) { + const folds = foldedSections(section, types, values) + addable.push(...folds.filter((fold) => fold.unset.length > 0)) + for (const fold of visibleFolds(folds, open)) { + const id = idOfFold(fold) + if (fold.kind !== 'own') { + rows.push({ kind: 'fold', id: `fold:${id}`, fold, open: open.has(id) }) + } else if (ownSections++ > 0) { + rows.push({ kind: 'heading', id: `heading:${id}`, fold }) + } + if (fold.kind === 'own' || open.has(id)) { + rows.push(...settingRows(fold, values)) + } + } + } + if (editable && addable.length > 0) { + rows.push({ kind: 'addSetting', id: ADD_SETTING_ID }) + } + const height = NODE_STRIPE + NODE_HEADER + rows.reduce((sum, row) => sum + heightOfRow(row), 0) + NODE_PADDING + return { rows, height, addable } +} + +function settingRows(fold: SettingsFold, values: unknown): NodeRow[] { + return fold.settings.map((option) => { + const path = [...fold.path, option.name] + return { kind: 'setting', id: idOf(path), fold, option, value: valueAt(values, path) } + }) +} diff --git a/studio/src/renderer/src/editor/settingFolds.test.ts b/studio/src/renderer/src/editor/settingFolds.test.ts index 90b180090..00664109a 100644 --- a/studio/src/renderer/src/editor/settingFolds.test.ts +++ b/studio/src/renderer/src/editor/settingFolds.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from 'vitest' import type { NodeSettings, SettingOption, SettingsType, ValueKind } from '../bridge/types' import { foldedSections, idOfFold, visibleFolds } from './settingFolds' +import { SPAN_TYPE } from './settingText' function option(name: string, kind: ValueKind): SettingOption { return { name, description: '', required: false, minimum: null, maximum: null, minItems: null, defaultValue: null, kind } @@ -47,10 +48,34 @@ describe('foldedSections', () => { expect(folds[2].holder).toEqual({ object: ['materials', 0], key: 'rules' }) }) - it('leaves the folded settings and the ones shown as nodes out of the fields of the section that holds them', () => { + it('leaves the folded settings and the ones shown as nodes out of the rows of the section that holds them', () => { const [own] = foldedSections(material, types, file) - expect(own.options.map((setting) => setting.name)).toEqual(['role', 'block']) + expect(own.settings.map((setting) => setting.name)).toEqual(['role', 'block']) + }) + + it('lists only what is written, and keeps the rest to add', () => { + const [own] = foldedSections(material, types, { materials: [{ block: 'minecraft:stone' }] }) + + expect(own.settings.map((setting) => setting.name)).toEqual(['block']) + expect(own.unset.map((setting) => setting.name)).toEqual(['role', 'offset', 'rules']) + }) + + it('lists a plain setting the type requires even while it is unset, so its default shows', () => { + const required: Record = { ...types, Material: { ...types.Material, options: [{ ...option('role', text), required: true }] } } + const [own] = foldedSections(material, required, { materials: [{}] }) + + expect(own.settings.map((setting) => setting.name)).toEqual(['role']) + expect(own.unset).toEqual([]) + }) + + it('keeps a span a row rather than a section, since it is typed as a range', () => { + const spanned: Record = { ...types, Material: { description: '', options: [option('along', { kind: 'object', type: SPAN_TYPE })] }, [SPAN_TYPE]: { description: '', options: [option('from', any), option('to', any)] } } + const folds = foldedSections(material, spanned, { materials: [{ along: { from: 0.2, to: 0.8 } }] }) + + expect(folds).toHaveLength(1) + expect(folds[0].settings.map((setting) => setting.name)).toEqual(['along']) + expect(folds[0].summary).toBe('along 0.2 – 0.8') }) it('sums a section up by what it holds, a curve as curve and the default namespace left off', () => { @@ -61,11 +86,11 @@ describe('foldedSections', () => { expect(folds[2].summary).toBe('2 items') }) - it('keeps a setting that is not written as an object a field', () => { - const [own, ...inside] = foldedSections(material, types, { materials: [{ role: 'wood' }] }) + it('keeps an object setting that is not written as an object a row', () => { + const [own, ...inside] = foldedSections(material, types, { materials: [{ offset: 3 }] }) expect(inside).toEqual([]) - expect(own.options.map((setting) => setting.name)).toEqual(['role', 'block', 'offset', 'rules']) + expect(own.settings.map((setting) => setting.name)).toEqual(['offset']) }) }) diff --git a/studio/src/renderer/src/editor/settingFolds.ts b/studio/src/renderer/src/editor/settingFolds.ts index f6a9dc943..27eab1fcb 100644 --- a/studio/src/renderer/src/editor/settingFolds.ts +++ b/studio/src/renderer/src/editor/settingFolds.ts @@ -1,7 +1,7 @@ -import type { JsonPath, NodeSettings, SettingOption, SettingsType } from '../bridge/types' +import type { JsonPath, NodeSettings, SettingOption, SettingsType, ValueKind } from '../bridge/types' import { isCurve } from './curves' import { isWithin } from './nodeLayout' -import { textOf } from './settingText' +import { isSpan, textOf } from './settingText' import { valueAt } from './jsonValues' const SUMMARY_SETTINGS = 3 @@ -14,7 +14,7 @@ const DEFAULT_NAMESPACE = 'minecraft:' */ export type FoldKind = 'own' | 'group' | 'list' | 'item' -/** One object of the file whose settings the inspector shows, below the ones that hold it. */ +/** One object of the file whose settings a node lists, below the ones that hold it. */ export interface SettingsFold { title: string path: JsonPath @@ -26,8 +26,10 @@ export interface SettingsFold { summary: string /** The object and member that hold a group or list, to unset it; null for the rest. */ holder: { object: JsonPath; key: string } | null - /** The settings written plainly in it, as fields; those that are folds of their own are not among them. */ - options: SettingOption[] + /** The settings listed as rows: those written plainly in it, and the plain ones it requires but leaves unset. */ + settings: SettingOption[] + /** What it could set but leaves at the default, to add. */ + unset: SettingOption[] } function isObject(value: unknown): value is Record { @@ -42,10 +44,19 @@ export function idOfFold(fold: SettingsFold): string { return JSON.stringify(fold.path) } +/** The schema type of a setting that folds open as a section of its own when written; null for one that is a row. */ +function groupTypeOf(kind: ValueKind): string | null { + return kind.kind === 'object' && !isSpan(kind) ? kind.type : null +} + +function itemTypeOf(kind: ValueKind): string | null { + return kind.kind === 'list' && kind.element.kind === 'object' ? kind.element.type : null +} + /** * The sections of one object of a node and the objects inside it, in file order, each followed by those inside it. A - * setting that is itself an object whose type the schema describes is a section of its own one level deeper, and so is - * each element of a list of objects; one that is not written stays a field. + * setting written as an object whose type the schema describes is a section of its own one level deeper, and so is + * each element of a list of objects. Only what is written is listed; the rest can be added. */ export function foldedSections(section: NodeSettings, types: Record, values: unknown): SettingsFold[] { const folds: SettingsFold[] = [] @@ -56,7 +67,8 @@ export function foldedSections(section: NodeSettings, types: Record function addFold(into: SettingsFold[], types: Record, values: unknown, head: FoldHead, shownAsNodes: Set): void { - const options: SettingOption[] = [] + const settings: SettingOption[] = [] + const unset: SettingOption[] = [] const inside: SettingsFold[] = [] const summary: string[] = [] for (const option of types[head.type]?.options ?? []) { @@ -66,10 +78,18 @@ function addFold(into: SettingsFold[], types: Record, valu const path = [...head.path, option.name] const value = valueAt(values, path) const holder = { object: head.path, key: option.name } - const objectType = option.kind.kind === 'object' ? option.kind.type : null - const itemType = option.kind.kind === 'list' && option.kind.element.kind === 'object' ? option.kind.element.type : null - if (objectType !== null && isObject(value) && types[objectType] !== undefined) { - addFold(inside, types, values, { title: option.name, path, type: objectType, kind: 'group', depth: head.depth + 1, holder }, new Set()) + const groupType = groupTypeOf(option.kind) + const itemType = itemTypeOf(option.kind) + if (value === undefined) { + if (option.required && groupType === null && itemType === null) { + settings.push(option) + } else { + unset.push(option) + } + continue + } + if (groupType !== null && isObject(value) && types[groupType] !== undefined) { + addFold(inside, types, values, { title: option.name, path, type: groupType, kind: 'group', depth: head.depth + 1, holder }, new Set()) continue } if (itemType !== null && isObjects(value) && types[itemType] !== undefined) { @@ -77,12 +97,10 @@ function addFold(into: SettingsFold[], types: Record, valu summary.push(`${option.name} ${value.length}`) continue } - options.push(option) - if (value !== undefined) { - summary.push(`${option.name} ${shortText(option, value)}`) - } + settings.push(option) + summary.push(`${option.name} ${shortText(option, value)}`) } - into.push({ ...head, summary: summary.slice(0, SUMMARY_SETTINGS).join(SUMMARY_SEPARATOR), options }) + into.push({ ...head, summary: summary.slice(0, SUMMARY_SETTINGS).join(SUMMARY_SEPARATOR), settings, unset }) into.push(...inside) } @@ -104,7 +122,8 @@ function addList(into: SettingsFold[], types: Record, valu depth: list.depth, summary: `${list.count} ${list.count === 1 ? 'item' : 'items'}`, holder: list.holder, - options: [] + settings: [], + unset: [] }) for (let index = 0; index < list.count; index++) { addFold( diff --git a/studio/src/renderer/src/editor/settingText.test.ts b/studio/src/renderer/src/editor/settingText.test.ts index 9b21e067c..9adfc125e 100644 --- a/studio/src/renderer/src/editor/settingText.test.ts +++ b/studio/src/renderer/src/editor/settingText.test.ts @@ -1,8 +1,14 @@ import { describe, expect, it } from 'vitest' -import type { ValueKind } from '../bridge/types' -import { literalOf, textOf } from './settingText' +import type { SettingOption, ValueKind } from '../bridge/types' +import { defaultLiteral, defaultText, literalOf, problemWith, SPAN_TYPE, textOf } from './settingText' const roles: ValueKind = { kind: 'list', element: { kind: 'text', format: 'PLAIN' }, unique: false } +const any: ValueKind = { kind: 'any' } +const span: ValueKind = { kind: 'object', type: SPAN_TYPE } + +function option(kind: ValueKind, changes: Partial = {}): SettingOption { + return { name: 'radius', description: '', required: false, minimum: null, maximum: null, minItems: null, defaultValue: null, kind, ...changes } +} describe('string lists', () => { it('read as commas and are written back quoted', () => { @@ -25,3 +31,61 @@ describe('text', () => { expect(literalOf(text, 'wood "a"')).toBe('"wood \\"a\\""') }) }) + +describe('ranges', () => { + it('show a [min, max] value and a span with a dash', () => { + expect(textOf(any, [5, 7])).toBe('5 – 7') + expect(textOf(span, { from: 0.45, to: 0.95 })).toBe('0.45 – 0.95') + expect(textOf(span, { to: 0.5 })).toBe('0 – 0.5') + }) + + it('are read back however the dash is typed', () => { + expect(literalOf(any, '2 – 4')).toBe('[2, 4]') + expect(literalOf(any, '2-4')).toBe('[2, 4]') + expect(literalOf(any, '2 to 4')).toBe('[2, 4]') + expect(literalOf(any, '-1, 3.5')).toBe('[-1, 3.5]') + expect(literalOf(span, '0.2 – 0.8')).toBe('{"from": 0.2, "to": 0.8}') + }) + + it('leave a plain number and a curve as typed', () => { + expect(literalOf(any, ' 3 ')).toBe('3') + expect(literalOf(any, '[[0, 1], [1, 0]]')).toBe('[[0, 1], [1, 0]]') + }) +}) + +describe('defaults', () => { + it('start an added setting at its default, or at an empty value of its kind', () => { + expect(defaultLiteral(option(any, { defaultValue: 2 }))).toBe('2') + expect(defaultLiteral(option({ kind: 'boolean' }))).toBe('false') + expect(defaultLiteral(option({ kind: 'enum', constants: [{ name: 'ROUND', description: '' }] }))).toBe('"ROUND"') + expect(defaultLiteral(option(roles))).toBe('[]') + expect(defaultLiteral(option({ kind: 'object', type: 'Offset' }))).toBe('{}') + }) + + it('show what an unset setting falls back to, or nothing', () => { + expect(defaultText(option({ kind: 'text', format: 'PLAIN' }, { defaultValue: 'main' }))).toBe('main') + expect(defaultText(option(any))).toBe('') + }) +}) + +describe('problemWith', () => { + it('holds a number to its kind and limits', () => { + const count = option({ kind: 'integer' }, { minimum: 1, maximum: 64 }) + + expect(problemWith(count, 'a')).toBe('Not a number') + expect(problemWith(count, '2.5')).toBe('Not a whole number') + expect(problemWith(count, '0')).toBe('At least 1') + expect(problemWith(count, '65')).toBe('At most 64') + expect(problemWith(count, '6')).toBeNull() + }) + + it('takes a number, a range or JSON for a value that may be a curve', () => { + expect(problemWith(option(any), '4 – 6')).toBeNull() + expect(problemWith(option(any), '[[0, 1]]')).toBeNull() + expect(problemWith(option(any), 'tall')).toBe('Takes a number, or a range like 4 – 6') + }) + + it('lets an empty draft through, since it unsets the setting', () => { + expect(problemWith(option({ kind: 'integer' }), ' ')).toBeNull() + }) +}) diff --git a/studio/src/renderer/src/editor/settingText.ts b/studio/src/renderer/src/editor/settingText.ts index d02ebe432..8f105ef1b 100644 --- a/studio/src/renderer/src/editor/settingText.ts +++ b/studio/src/renderer/src/editor/settingText.ts @@ -1,30 +1,71 @@ -import type { ValueKind } from '../bridge/types' +import type { SettingOption, ValueKind } from '../bridge/types' export const NOT_SET = '' export const LIST_SEPARATOR = ', ' +export const RANGE_DASH = ' – ' +/** The schema type of a stretch along a part from 0 to 1, shown and typed as a range rather than folded open. */ +export const SPAN_TYPE = 'art.arcane.iris.generation.procedural.part.ProceduralSpan' + +const NUMBER = '(-?\\d+(?:\\.\\d+)?)' +const RANGE = new RegExp(`^\\s*${NUMBER}\\s*(?:–|—|\\.\\.|to|,|-)\\s*${NUMBER}\\s*$`) +const RANGE_SIZE = 2 +const SPAN_FROM = 'from' +const SPAN_TO = 'to' +const SPAN_DEFAULT_FROM = 0 +const SPAN_DEFAULT_TO = 1 /** Whether {@code kind} is a string naming something, typed as text. */ export function isText(kind: ValueKind): boolean { return kind.kind === 'text' || kind.kind === 'reference' || kind.kind === 'resource' } +export function isNumber(kind: ValueKind): boolean { + return kind.kind === 'integer' || kind.kind === 'decimal' +} + /** Whether {@code kind} is a list of strings, such as the roles a decoration goes on, which is typed as {@code a, b}. */ export function isStringList(kind: ValueKind): boolean { return kind.kind === 'list' && isText(kind.element) } +/** Whether {@code kind} is a stretch from 0 to 1, written {@code {"from": a, "to": b}} and typed {@code a – b}. */ +export function isSpan(kind: ValueKind): boolean { + return kind.kind === 'object' && kind.type === SPAN_TYPE +} + function isStrings(value: unknown): value is string[] { return Array.isArray(value) && value.every((element) => typeof element === 'string') } -/** What the field shows for the value the file holds. */ +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +/** The two ends of a {@code [min, max]} value, or of a span; null for anything else. */ +export function rangeOf(kind: ValueKind, value: unknown): [number, number] | null { + if (kind.kind === 'any' && Array.isArray(value) && value.length === RANGE_SIZE && value.every((end) => typeof end === 'number')) { + return [value[0], value[1]] + } + if (!isSpan(kind) || !isRecord(value)) { + return null + } + const from = value[SPAN_FROM] ?? SPAN_DEFAULT_FROM + const to = value[SPAN_TO] ?? SPAN_DEFAULT_TO + return typeof from === 'number' && typeof to === 'number' ? [from, to] : null +} + +/** What the node shows for the value the file holds: strings unquoted, ranges as {@code 2 – 4}, anything else as JSON. */ export function textOf(kind: ValueKind, value: unknown): string { if (value === undefined) { return NOT_SET } - if (isText(kind) && typeof value === 'string') { + if ((isText(kind) || kind.kind === 'enum') && typeof value === 'string') { return value } + const range = rangeOf(kind, value) + if (range !== null) { + return range.join(RANGE_DASH) + } return isStringList(kind) && isStrings(value) ? value.join(LIST_SEPARATOR) : JSON.stringify(value) } @@ -36,13 +77,102 @@ export function itemsOf(draft: string): string[] { .filter((item) => item !== '') } -/** What the field holds as JSON to write; a list typed as {@code a, b} is written as an array unless it already is one. */ +/** + * What was typed as JSON to write. A range may be typed {@code 2 – 4}, {@code 2-4}, {@code 2 to 4} or {@code 2, 4}; a + * list typed as {@code a, b} or without its brackets gets them. + */ export function literalOf(kind: ValueKind, draft: string): string { - if (isText(kind)) { + if (isText(kind) || kind.kind === 'enum') { return JSON.stringify(draft) } - if (isStringList(kind) && !draft.trim().startsWith('[')) { - return JSON.stringify(itemsOf(draft)) + const typed = draft.trim() + if (isStringList(kind) && !typed.startsWith('[')) { + return JSON.stringify(itemsOf(typed)) + } + const range = RANGE.exec(typed) + if (range !== null && kind.kind === 'any') { + return `[${range[1]}, ${range[2]}]` + } + if (range !== null && isSpan(kind)) { + return `{"${SPAN_FROM}": ${range[1]}, "${SPAN_TO}": ${range[2]}}` + } + return !isJson(typed) && isJson(`[${typed}]`) ? `[${typed}]` : typed +} + +/** What a setting added from the node starts at: its default, or an empty value of its kind when it has none. */ +export function defaultLiteral(option: SettingOption): string { + if (option.defaultValue !== null && option.defaultValue !== undefined) { + return JSON.stringify(option.defaultValue) + } + return placeholderOf(option.kind) +} + +function placeholderOf(kind: ValueKind): string { + switch (kind.kind) { + case 'boolean': + return 'false' + case 'text': + case 'reference': + case 'resource': + return '""' + case 'enum': + return JSON.stringify(kind.constants[0]?.name ?? '') + case 'list': + return '[]' + case 'integer': + case 'decimal': + case 'any': + return '0' + default: + return '{}' + } +} + +/** What an unset setting falls back to, as the node shows it; empty when it has no default. */ +export function defaultText(option: SettingOption): string { + return option.defaultValue === null || option.defaultValue === undefined ? NOT_SET : textOf(option.kind, option.defaultValue) +} + +/** Why {@code draft} can't be written as the value of {@code option}, or null when it can; an empty draft unsets it. */ +export function problemWith(option: SettingOption, draft: string): string | null { + const { kind } = option + if (draft.trim() === NOT_SET || isText(kind) || kind.kind === 'enum') { + return null + } + if (isNumber(kind)) { + return numberProblem(option, draft) + } + if (isJson(literalOf(kind, draft))) { + return null + } + if (kind.kind === 'any') { + return `Takes a number, or a range like 4${RANGE_DASH}6` + } + return isSpan(kind) ? `Takes a stretch from 0 to 1, like 0.2${RANGE_DASH}0.8` : 'Not JSON' +} + +function numberProblem(option: SettingOption, draft: string): string | null { + const number = Number(draft) + if (!Number.isFinite(number)) { + return 'Not a number' + } + if (option.kind.kind === 'integer' && !Number.isInteger(number)) { + return 'Not a whole number' + } + if (option.minimum !== null && number < option.minimum) { + return `At least ${option.minimum}` + } + if (option.maximum !== null && number > option.maximum) { + return `At most ${option.maximum}` + } + return null +} + +function isJson(text: string): boolean { + try { + JSON.parse(text) + return true + } catch { + return false } - return draft.trim() } diff --git a/studio/src/renderer/src/editor/suggestions.test.ts b/studio/src/renderer/src/editor/suggestions.test.ts index a2ae79600..6fc13f9ce 100644 --- a/studio/src/renderer/src/editor/suggestions.test.ts +++ b/studio/src/renderer/src/editor/suggestions.test.ts @@ -32,8 +32,8 @@ describe('suggestionSourceOf', () => { it('takes the roles for the settings that name one', () => { const on = option('on', { kind: 'list', element: { kind: 'text', format: 'PLAIN' }, unique: false }) - expect(suggestionSourceOf('art.arcane.iris.engine.procedural.part.ProceduralDecoration', on)).toEqual({ from: 'roles' }) - expect(suggestionSourceOf('art.arcane.iris.engine.procedural.part.ProceduralDecoration', option('at', { kind: 'text', format: 'PLAIN' }))).toBeNull() + expect(suggestionSourceOf('art.arcane.iris.generation.procedural.part.ProceduralDecoration', on)).toEqual({ from: 'roles' }) + expect(suggestionSourceOf('art.arcane.iris.generation.procedural.part.ProceduralDecoration', option('at', { kind: 'text', format: 'PLAIN' }))).toBeNull() }) it('takes the elements of a list of references, and nothing for free text', () => { diff --git a/studio/src/renderer/src/editor/suggestions.ts b/studio/src/renderer/src/editor/suggestions.ts index cd71ead34..38d53a1a6 100644 --- a/studio/src/renderer/src/editor/suggestions.ts +++ b/studio/src/renderer/src/editor/suggestions.ts @@ -6,9 +6,9 @@ export type SuggestionSource = { from: 'reference'; reference: string } | { from /** Settings that name a role of the object being edited, by the schema type and option (ProceduralPart, ProceduralMaterial and ProceduralDecoration). */ const ROLE_OPTIONS: ReadonlySet = new Set([ - 'art.arcane.iris.engine.procedural.part.ProceduralPart.role', - 'art.arcane.iris.engine.procedural.part.ProceduralMaterial.role', - 'art.arcane.iris.engine.procedural.part.ProceduralDecoration.on' + 'art.arcane.iris.generation.procedural.part.ProceduralPart.role', + 'art.arcane.iris.generation.procedural.part.ProceduralMaterial.role', + 'art.arcane.iris.generation.procedural.part.ProceduralDecoration.on' ]) /** A source the server lists, as opposed to the roles, which the studio reads from the nodes. */ diff --git a/studio/src/renderer/src/icons/LICENSE-APACHE-2.0.txt b/studio/src/renderer/src/icons/LICENSE-APACHE-2.0.txt deleted file mode 100644 index d64569567..000000000 --- a/studio/src/renderer/src/icons/LICENSE-APACHE-2.0.txt +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/studio/src/renderer/src/icons/NOTICE.txt b/studio/src/renderer/src/icons/NOTICE.txt deleted file mode 100644 index e3d07cdd4..000000000 --- a/studio/src/renderer/src/icons/NOTICE.txt +++ /dev/null @@ -1,6 +0,0 @@ -The icons in this folder and its subfolders come from the IntelliJ Platform (https://github.com/JetBrains/intellij-community), -platform/icons/src/expui, Copyright 2000-2023 JetBrains s.r.o. and contributors, -used under the Apache License 2.0 (LICENSE-APACHE-2.0.txt). -memory.svg is profileMemory.svg with its profiling badge removed. -theme.svg, blocks.svg, borders.svg, shading.svg, mob.svg, actualZoom.svg, decoration.svg, and in views/ biomes.svg, regions.svg, -world-3d.svg, saved-world.svg, noise.svg and objects.svg are the studio's own, drawn to match. diff --git a/studio/src/renderer/src/icons/actualZoom.svg b/studio/src/renderer/src/icons/actualZoom.svg deleted file mode 100644 index 08981f5e8..000000000 --- a/studio/src/renderer/src/icons/actualZoom.svg +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/studio/src/renderer/src/icons/actualZoom_dark.svg b/studio/src/renderer/src/icons/actualZoom_dark.svg deleted file mode 100644 index 0cc5f18b6..000000000 --- a/studio/src/renderer/src/icons/actualZoom_dark.svg +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/studio/src/renderer/src/icons/add.svg b/studio/src/renderer/src/icons/add.svg deleted file mode 100644 index 57eaaf561..000000000 --- a/studio/src/renderer/src/icons/add.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/add_dark.svg b/studio/src/renderer/src/icons/add_dark.svg deleted file mode 100644 index 397e9321b..000000000 --- a/studio/src/renderer/src/icons/add_dark.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/blocks.svg b/studio/src/renderer/src/icons/blocks.svg deleted file mode 100644 index aa609f646..000000000 --- a/studio/src/renderer/src/icons/blocks.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/blocks_dark.svg b/studio/src/renderer/src/icons/blocks_dark.svg deleted file mode 100644 index d215432f4..000000000 --- a/studio/src/renderer/src/icons/blocks_dark.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/borders.svg b/studio/src/renderer/src/icons/borders.svg deleted file mode 100644 index 4fe3957a7..000000000 --- a/studio/src/renderer/src/icons/borders.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/studio/src/renderer/src/icons/borders_dark.svg b/studio/src/renderer/src/icons/borders_dark.svg deleted file mode 100644 index 2f7ce7863..000000000 --- a/studio/src/renderer/src/icons/borders_dark.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/studio/src/renderer/src/icons/checked.svg b/studio/src/renderer/src/icons/checked.svg deleted file mode 100644 index 863bbc418..000000000 --- a/studio/src/renderer/src/icons/checked.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/checked_dark.svg b/studio/src/renderer/src/icons/checked_dark.svg deleted file mode 100644 index 3e1d9ecc3..000000000 --- a/studio/src/renderer/src/icons/checked_dark.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/chevronLeft.svg b/studio/src/renderer/src/icons/chevronLeft.svg deleted file mode 100644 index c6c4fa041..000000000 --- a/studio/src/renderer/src/icons/chevronLeft.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/chevronLeft_dark.svg b/studio/src/renderer/src/icons/chevronLeft_dark.svg deleted file mode 100644 index d4284d234..000000000 --- a/studio/src/renderer/src/icons/chevronLeft_dark.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/chevronRight.svg b/studio/src/renderer/src/icons/chevronRight.svg deleted file mode 100644 index 5120ed891..000000000 --- a/studio/src/renderer/src/icons/chevronRight.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/chevronRight_dark.svg b/studio/src/renderer/src/icons/chevronRight_dark.svg deleted file mode 100644 index 838142106..000000000 --- a/studio/src/renderer/src/icons/chevronRight_dark.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/closeSmall.svg b/studio/src/renderer/src/icons/closeSmall.svg deleted file mode 100644 index c375b9331..000000000 --- a/studio/src/renderer/src/icons/closeSmall.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/closeSmall_dark.svg b/studio/src/renderer/src/icons/closeSmall_dark.svg deleted file mode 100644 index 237d6d45d..000000000 --- a/studio/src/renderer/src/icons/closeSmall_dark.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/decoration.svg b/studio/src/renderer/src/icons/decoration.svg deleted file mode 100644 index fb2a026ea..000000000 --- a/studio/src/renderer/src/icons/decoration.svg +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/studio/src/renderer/src/icons/decoration_dark.svg b/studio/src/renderer/src/icons/decoration_dark.svg deleted file mode 100644 index 0e0b87790..000000000 --- a/studio/src/renderer/src/icons/decoration_dark.svg +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/studio/src/renderer/src/icons/delete.svg b/studio/src/renderer/src/icons/delete.svg deleted file mode 100644 index a858096ac..000000000 --- a/studio/src/renderer/src/icons/delete.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/delete_dark.svg b/studio/src/renderer/src/icons/delete_dark.svg deleted file mode 100644 index 03ff9f241..000000000 --- a/studio/src/renderer/src/icons/delete_dark.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/exit.svg b/studio/src/renderer/src/icons/exit.svg deleted file mode 100644 index 8ff96d714..000000000 --- a/studio/src/renderer/src/icons/exit.svg +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/studio/src/renderer/src/icons/exit_dark.svg b/studio/src/renderer/src/icons/exit_dark.svg deleted file mode 100644 index e4cdd4abf..000000000 --- a/studio/src/renderer/src/icons/exit_dark.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - diff --git a/studio/src/renderer/src/icons/grid.svg b/studio/src/renderer/src/icons/grid.svg deleted file mode 100644 index 8b28efaf4..000000000 --- a/studio/src/renderer/src/icons/grid.svg +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/studio/src/renderer/src/icons/grid_dark.svg b/studio/src/renderer/src/icons/grid_dark.svg deleted file mode 100644 index 98f561847..000000000 --- a/studio/src/renderer/src/icons/grid_dark.svg +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/studio/src/renderer/src/icons/groups.svg b/studio/src/renderer/src/icons/groups.svg deleted file mode 100644 index d4ab80fbb..000000000 --- a/studio/src/renderer/src/icons/groups.svg +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/studio/src/renderer/src/icons/groups_dark.svg b/studio/src/renderer/src/icons/groups_dark.svg deleted file mode 100644 index 2769c3ce0..000000000 --- a/studio/src/renderer/src/icons/groups_dark.svg +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/studio/src/renderer/src/icons/help.svg b/studio/src/renderer/src/icons/help.svg deleted file mode 100644 index 203346d24..000000000 --- a/studio/src/renderer/src/icons/help.svg +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/studio/src/renderer/src/icons/help_dark.svg b/studio/src/renderer/src/icons/help_dark.svg deleted file mode 100644 index d571baabe..000000000 --- a/studio/src/renderer/src/icons/help_dark.svg +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/studio/src/renderer/src/icons/lightning.svg b/studio/src/renderer/src/icons/lightning.svg deleted file mode 100644 index 4ac384edd..000000000 --- a/studio/src/renderer/src/icons/lightning.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/lightning_dark.svg b/studio/src/renderer/src/icons/lightning_dark.svg deleted file mode 100644 index 251f75413..000000000 --- a/studio/src/renderer/src/icons/lightning_dark.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/locate.svg b/studio/src/renderer/src/icons/locate.svg deleted file mode 100644 index 2343fa2e3..000000000 --- a/studio/src/renderer/src/icons/locate.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/locate_dark.svg b/studio/src/renderer/src/icons/locate_dark.svg deleted file mode 100644 index a2ba607aa..000000000 --- a/studio/src/renderer/src/icons/locate_dark.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/locked.svg b/studio/src/renderer/src/icons/locked.svg deleted file mode 100644 index 666daddf5..000000000 --- a/studio/src/renderer/src/icons/locked.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/locked_dark.svg b/studio/src/renderer/src/icons/locked_dark.svg deleted file mode 100644 index 9658ca553..000000000 --- a/studio/src/renderer/src/icons/locked_dark.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/memory.svg b/studio/src/renderer/src/icons/memory.svg deleted file mode 100644 index 6af68790d..000000000 --- a/studio/src/renderer/src/icons/memory.svg +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/studio/src/renderer/src/icons/memory_dark.svg b/studio/src/renderer/src/icons/memory_dark.svg deleted file mode 100644 index 92038e383..000000000 --- a/studio/src/renderer/src/icons/memory_dark.svg +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/studio/src/renderer/src/icons/mob.svg b/studio/src/renderer/src/icons/mob.svg deleted file mode 100644 index bcd9e1a0e..000000000 --- a/studio/src/renderer/src/icons/mob.svg +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/studio/src/renderer/src/icons/mob_dark.svg b/studio/src/renderer/src/icons/mob_dark.svg deleted file mode 100644 index f1b911136..000000000 --- a/studio/src/renderer/src/icons/mob_dark.svg +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/studio/src/renderer/src/icons/redo.svg b/studio/src/renderer/src/icons/redo.svg deleted file mode 100644 index 862b8f574..000000000 --- a/studio/src/renderer/src/icons/redo.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/redo_dark.svg b/studio/src/renderer/src/icons/redo_dark.svg deleted file mode 100644 index a39093042..000000000 --- a/studio/src/renderer/src/icons/redo_dark.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/refresh.svg b/studio/src/renderer/src/icons/refresh.svg deleted file mode 100644 index 7a4c73dfd..000000000 --- a/studio/src/renderer/src/icons/refresh.svg +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/studio/src/renderer/src/icons/refresh_dark.svg b/studio/src/renderer/src/icons/refresh_dark.svg deleted file mode 100644 index 3362992af..000000000 --- a/studio/src/renderer/src/icons/refresh_dark.svg +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/studio/src/renderer/src/icons/reset.svg b/studio/src/renderer/src/icons/reset.svg deleted file mode 100644 index de5d2b170..000000000 --- a/studio/src/renderer/src/icons/reset.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/reset_dark.svg b/studio/src/renderer/src/icons/reset_dark.svg deleted file mode 100644 index 28d58e10e..000000000 --- a/studio/src/renderer/src/icons/reset_dark.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/search.svg b/studio/src/renderer/src/icons/search.svg deleted file mode 100644 index 021b0c394..000000000 --- a/studio/src/renderer/src/icons/search.svg +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/studio/src/renderer/src/icons/search_dark.svg b/studio/src/renderer/src/icons/search_dark.svg deleted file mode 100644 index d5a82d9c1..000000000 --- a/studio/src/renderer/src/icons/search_dark.svg +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/studio/src/renderer/src/icons/settings.svg b/studio/src/renderer/src/icons/settings.svg deleted file mode 100644 index c30de8209..000000000 --- a/studio/src/renderer/src/icons/settings.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/settings_dark.svg b/studio/src/renderer/src/icons/settings_dark.svg deleted file mode 100644 index 62f328167..000000000 --- a/studio/src/renderer/src/icons/settings_dark.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/shading.svg b/studio/src/renderer/src/icons/shading.svg deleted file mode 100644 index c545e1d8b..000000000 --- a/studio/src/renderer/src/icons/shading.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/shading_dark.svg b/studio/src/renderer/src/icons/shading_dark.svg deleted file mode 100644 index cc2b121d0..000000000 --- a/studio/src/renderer/src/icons/shading_dark.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/stopWatch.svg b/studio/src/renderer/src/icons/stopWatch.svg deleted file mode 100644 index 33f0d5917..000000000 --- a/studio/src/renderer/src/icons/stopWatch.svg +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/studio/src/renderer/src/icons/stopWatch_dark.svg b/studio/src/renderer/src/icons/stopWatch_dark.svg deleted file mode 100644 index 10bec586b..000000000 --- a/studio/src/renderer/src/icons/stopWatch_dark.svg +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/studio/src/renderer/src/icons/symlink.svg b/studio/src/renderer/src/icons/symlink.svg deleted file mode 100644 index 4c2ccbb21..000000000 --- a/studio/src/renderer/src/icons/symlink.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/symlink_dark.svg b/studio/src/renderer/src/icons/symlink_dark.svg deleted file mode 100644 index fcc2390a9..000000000 --- a/studio/src/renderer/src/icons/symlink_dark.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/theme.svg b/studio/src/renderer/src/icons/theme.svg deleted file mode 100644 index 3f4ab8713..000000000 --- a/studio/src/renderer/src/icons/theme.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/theme_dark.svg b/studio/src/renderer/src/icons/theme_dark.svg deleted file mode 100644 index 375b1b72c..000000000 --- a/studio/src/renderer/src/icons/theme_dark.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/undo.svg b/studio/src/renderer/src/icons/undo.svg deleted file mode 100644 index 7a98c7583..000000000 --- a/studio/src/renderer/src/icons/undo.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/undo_dark.svg b/studio/src/renderer/src/icons/undo_dark.svg deleted file mode 100644 index 2fa3c0d42..000000000 --- a/studio/src/renderer/src/icons/undo_dark.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/views/biomes.svg b/studio/src/renderer/src/icons/views/biomes.svg deleted file mode 100644 index 78c98d754..000000000 --- a/studio/src/renderer/src/icons/views/biomes.svg +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - diff --git a/studio/src/renderer/src/icons/views/biomes_dark.svg b/studio/src/renderer/src/icons/views/biomes_dark.svg deleted file mode 100644 index 731013503..000000000 --- a/studio/src/renderer/src/icons/views/biomes_dark.svg +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - diff --git a/studio/src/renderer/src/icons/views/cave-profiles.svg b/studio/src/renderer/src/icons/views/cave-profiles.svg deleted file mode 100644 index 237f5e687..000000000 --- a/studio/src/renderer/src/icons/views/cave-profiles.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/views/cave-profiles_dark.svg b/studio/src/renderer/src/icons/views/cave-profiles_dark.svg deleted file mode 100644 index 65b25848d..000000000 --- a/studio/src/renderer/src/icons/views/cave-profiles_dark.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/views/fluid-profiles.svg b/studio/src/renderer/src/icons/views/fluid-profiles.svg deleted file mode 100644 index 58443c12b..000000000 --- a/studio/src/renderer/src/icons/views/fluid-profiles.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/studio/src/renderer/src/icons/views/fluid-profiles_dark.svg b/studio/src/renderer/src/icons/views/fluid-profiles_dark.svg deleted file mode 100644 index 1e15e5ae5..000000000 --- a/studio/src/renderer/src/icons/views/fluid-profiles_dark.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/studio/src/renderer/src/icons/views/formation-profiles.svg b/studio/src/renderer/src/icons/views/formation-profiles.svg deleted file mode 100644 index 081586c7f..000000000 --- a/studio/src/renderer/src/icons/views/formation-profiles.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/views/formation-profiles_dark.svg b/studio/src/renderer/src/icons/views/formation-profiles_dark.svg deleted file mode 100644 index 28ebb7862..000000000 --- a/studio/src/renderer/src/icons/views/formation-profiles_dark.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/views/noise.svg b/studio/src/renderer/src/icons/views/noise.svg deleted file mode 100644 index e735984cf..000000000 --- a/studio/src/renderer/src/icons/views/noise.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/studio/src/renderer/src/icons/views/noise_dark.svg b/studio/src/renderer/src/icons/views/noise_dark.svg deleted file mode 100644 index 187dd72f4..000000000 --- a/studio/src/renderer/src/icons/views/noise_dark.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/studio/src/renderer/src/icons/views/objects.svg b/studio/src/renderer/src/icons/views/objects.svg deleted file mode 100644 index 6297b050c..000000000 --- a/studio/src/renderer/src/icons/views/objects.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/views/objects_dark.svg b/studio/src/renderer/src/icons/views/objects_dark.svg deleted file mode 100644 index 4e3d96e86..000000000 --- a/studio/src/renderer/src/icons/views/objects_dark.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/views/palettes.svg b/studio/src/renderer/src/icons/views/palettes.svg deleted file mode 100644 index 67e265433..000000000 --- a/studio/src/renderer/src/icons/views/palettes.svg +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/studio/src/renderer/src/icons/views/palettes_dark.svg b/studio/src/renderer/src/icons/views/palettes_dark.svg deleted file mode 100644 index 8d120c93e..000000000 --- a/studio/src/renderer/src/icons/views/palettes_dark.svg +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/studio/src/renderer/src/icons/views/procedural.svg b/studio/src/renderer/src/icons/views/procedural.svg deleted file mode 100644 index 5ad2cdb16..000000000 --- a/studio/src/renderer/src/icons/views/procedural.svg +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/studio/src/renderer/src/icons/views/procedural_dark.svg b/studio/src/renderer/src/icons/views/procedural_dark.svg deleted file mode 100644 index 3c5f7ed0d..000000000 --- a/studio/src/renderer/src/icons/views/procedural_dark.svg +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/studio/src/renderer/src/icons/views/regions.svg b/studio/src/renderer/src/icons/views/regions.svg deleted file mode 100644 index f2848a5ee..000000000 --- a/studio/src/renderer/src/icons/views/regions.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/views/regions_dark.svg b/studio/src/renderer/src/icons/views/regions_dark.svg deleted file mode 100644 index f28c07a18..000000000 --- a/studio/src/renderer/src/icons/views/regions_dark.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/views/rivers.svg b/studio/src/renderer/src/icons/views/rivers.svg deleted file mode 100644 index a38c67edb..000000000 --- a/studio/src/renderer/src/icons/views/rivers.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/views/rivers_dark.svg b/studio/src/renderer/src/icons/views/rivers_dark.svg deleted file mode 100644 index 5ca99ca0e..000000000 --- a/studio/src/renderer/src/icons/views/rivers_dark.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/views/saved-world.svg b/studio/src/renderer/src/icons/views/saved-world.svg deleted file mode 100644 index ba35672af..000000000 --- a/studio/src/renderer/src/icons/views/saved-world.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/views/saved-world_dark.svg b/studio/src/renderer/src/icons/views/saved-world_dark.svg deleted file mode 100644 index f9880f87b..000000000 --- a/studio/src/renderer/src/icons/views/saved-world_dark.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/views/tree-profiles.svg b/studio/src/renderer/src/icons/views/tree-profiles.svg deleted file mode 100644 index ade20e40c..000000000 --- a/studio/src/renderer/src/icons/views/tree-profiles.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/views/tree-profiles_dark.svg b/studio/src/renderer/src/icons/views/tree-profiles_dark.svg deleted file mode 100644 index e1e79850a..000000000 --- a/studio/src/renderer/src/icons/views/tree-profiles_dark.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/views/world-3d.svg b/studio/src/renderer/src/icons/views/world-3d.svg deleted file mode 100644 index 233fbbd78..000000000 --- a/studio/src/renderer/src/icons/views/world-3d.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/views/world-3d_dark.svg b/studio/src/renderer/src/icons/views/world-3d_dark.svg deleted file mode 100644 index 46f0ee93d..000000000 --- a/studio/src/renderer/src/icons/views/world-3d_dark.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/web.svg b/studio/src/renderer/src/icons/web.svg deleted file mode 100644 index 897fab392..000000000 --- a/studio/src/renderer/src/icons/web.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/icons/web_dark.svg b/studio/src/renderer/src/icons/web_dark.svg deleted file mode 100644 index 0ca6194ab..000000000 --- a/studio/src/renderer/src/icons/web_dark.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/studio/src/renderer/src/main.tsx b/studio/src/renderer/src/main.tsx index 3ea6345e0..4ba5fffc5 100644 --- a/studio/src/renderer/src/main.tsx +++ b/studio/src/renderer/src/main.tsx @@ -1,13 +1,19 @@ +import { LucideProvider } from 'lucide-react' import { StrictMode } from 'react' import { createRoot } from 'react-dom/client' import { TooltipProvider } from '@/components/ui/tooltip' import { App } from './App' import './styles.css' +const ICON_SIZE_PX = 16 +const ICON_STROKE_PX = 1.5 + createRoot(document.getElementById('root')!).render( - - - + + + + + ) diff --git a/studio/src/renderer/src/studio/BakeMeter.tsx b/studio/src/renderer/src/studio/BakeMeter.tsx index 424837d12..d15544053 100644 --- a/studio/src/renderer/src/studio/BakeMeter.tsx +++ b/studio/src/renderer/src/studio/BakeMeter.tsx @@ -1,4 +1,4 @@ -import { IdeIcon } from '@/components/IdeIcon' +import { Timer } from 'lucide-react' import { useEffect, useState } from 'react' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { cn } from '@/lib/utils' @@ -49,7 +49,7 @@ export function BakeMeter({ timing }: BakeMeterProps): React.JSX.Element {
- + {timing === null ? MEASURING_LABEL : weight.label} diff --git a/studio/src/renderer/src/studio/ConnectScreen.tsx b/studio/src/renderer/src/studio/ConnectScreen.tsx index b6fc69fe5..b10381432 100644 --- a/studio/src/renderer/src/studio/ConnectScreen.tsx +++ b/studio/src/renderer/src/studio/ConnectScreen.tsx @@ -1,5 +1,5 @@ import { useEffect, useRef, useState } from 'react' -import { IdeIcon } from '@/components/IdeIcon' +import { Globe, RefreshCw } from 'lucide-react' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import type { BridgeConnection } from '../../../shared/bridge' @@ -56,7 +56,7 @@ export function ConnectScreen({ connecting, error, onConnect, onLink }: ConnectS
{bridges.length === 0 ? (
- Waiting for a server on this machine + Waiting for a server on this machine
) : ( bridges.map((bridge) => ( @@ -66,7 +66,7 @@ export function ConnectScreen({ connecting, error, onConnect, onLink }: ConnectS onClick={() => onConnect(bridge)} className="flex items-center gap-3 rounded-md px-3 py-2 text-left hover:bg-accent disabled:opacity-60" > - + {bridge.world} port {bridge.port} @@ -83,7 +83,7 @@ export function ConnectScreen({ connecting, error, onConnect, onLink }: ConnectS > setLink(event.target.value)} placeholder="iris-studio://…" className="h-8" /> {error !== null &&

{error}

} diff --git a/studio/src/renderer/src/studio/CurveEditor.tsx b/studio/src/renderer/src/studio/CurveEditor.tsx new file mode 100644 index 000000000..fbff016cf --- /dev/null +++ b/studio/src/renderer/src/studio/CurveEditor.tsx @@ -0,0 +1,298 @@ +import { Plus, Trash2 } from 'lucide-react' +import { useRef, useState } from 'react' +import { Button } from '@/components/ui/button' +import { Input } from '@/components/ui/input' +import { + CURVE_SHAPES, + isShape, + keyframesFrom, + plotRange, + roundedNumber, + samplesOf, + shapeFrom, + shapeNamed, + sortedKeyframes, + withAddedKeyframe, + withKeyframe, + withoutKeyframe, + withSetting, + withShape, + type Keyframe +} from '../editor/curves' + +const PREVIEW_SAMPLES = 40 +const PREVIEW_WIDTH = 100 +const PREVIEW_HEIGHT = 12 +const PLOT_WIDTH = 280 +const PLOT_HEIGHT = 140 +const PLOT_INSET = 10 +const PLOT_SAMPLES = 96 +const POINT_RADIUS = 4 +const POINTS_HINT = 'Drag a point · Double-click adds · Right-click removes' +const GUIDE_LEVELS = [0, 1] +const DRAGGED_PRECISION = 1000 + +/** A curve drawn across a value's field, its lowest to highest filling the height, with what it starts and ends at beside it. */ +export function CurvePreview({ value }: { value: unknown }): React.JSX.Element { + const samples = samplesOf(value, PREVIEW_SAMPLES) ?? [0] + const low = Math.min(...samples) + const span = Math.max(...samples) - low + const points = samples.map((sample, index) => { + const x = (index / Math.max(1, samples.length - 1)) * PREVIEW_WIDTH + const y = span === 0 ? PREVIEW_HEIGHT / 2 : PREVIEW_HEIGHT - ((sample - low) / span) * PREVIEW_HEIGHT + return `${x.toFixed(1)},${y.toFixed(1)}` + }) + return ( + <> + + + + + {roundedNumber(samples[0])} → {roundedNumber(samples[samples.length - 1])} + + + ) +} + +interface CurveEditorProps { + value: unknown + locked: boolean + /** Called with the curve after every change, so the object bakes again while it is shaped. */ + onWrite(next: unknown): void +} + +/** Edits a value that changes along a part as a curve: points to drag or type, or a named shape with its settings. */ +export function CurveEditor({ value, locked, onWrite }: CurveEditorProps): React.JSX.Element { + const byShape = isShape(value) + return ( +
+
+ + +
+ + {byShape ? } locked={locked} onWrite={onWrite} /> : } +
+ ) +} + +interface PlotDrag { + index: number + keys: Keyframe[] + range: [number, number] +} + +/** The curve from t = 0 to 1, with its points to drag while it is made of points; a drag is written when it ends. */ +function CurvePlot({ value, locked, onWrite }: CurveEditorProps): React.JSX.Element { + const [drag, setDrag] = useState(null) + const [hint, setHint] = useState(POINTS_HINT) + const plot = useRef(null) + const shown = drag?.keys ?? value + const samples = samplesOf(shown, PLOT_SAMPLES) ?? [] + const range = drag?.range ?? plotRange(samples) + const keys = isShape(shown) ? [] : sortedKeyframes(shown as Keyframe[]) + const area = { left: PLOT_INSET, top: PLOT_INSET, width: PLOT_WIDTH - 2 * PLOT_INSET, height: PLOT_HEIGHT - 2 * PLOT_INSET } + const screenX = (t: number): number => area.left + t * area.width + const screenY = (level: number): number => area.top + area.height - ((level - range[0]) / (range[1] - range[0])) * area.height + const keyframeAt = (event: React.PointerEvent | React.MouseEvent): Keyframe => { + const bounds = plot.current!.getBoundingClientRect() + const x = ((event.clientX - bounds.left) / bounds.width) * PLOT_WIDTH + const y = ((event.clientY - bounds.top) / bounds.height) * PLOT_HEIGHT + const t = clamp((x - area.left) / area.width, 0, 1) + const level = range[0] + ((area.top + area.height - y) / area.height) * (range[1] - range[0]) + return [roundTo(t), roundTo(clamp(level, range[0], range[1]))] + } + + // A point stays between its neighbours along t, so the points never swap order under the pointer. + const dragTo = (event: React.PointerEvent): void => { + if (drag === null) { + return + } + const [t, level] = keyframeAt(event) + const earliest = drag.index === 0 ? 0 : drag.keys[drag.index - 1][0] + const latest = drag.index === drag.keys.length - 1 ? 1 : drag.keys[drag.index + 1][0] + const moved: Keyframe = [clamp(t, earliest, latest), level] + setDrag({ ...drag, keys: withKeyframe(drag.keys, drag.index, moved) }) + setHint(`t ${roundedNumber(moved[0])} · ${roundedNumber(moved[1])}`) + } + + const finishDrag = (): void => { + if (drag !== null) { + onWrite(drag.keys) + } + setDrag(null) + setHint(POINTS_HINT) + } + + return ( +
+ !locked && onWrite(sortedKeyframes([...keys, keyframeAt(event)]))} + > + {GUIDE_LEVELS.map((level) => ( + + + + {level} + + + ))} + `${screenX(index / (samples.length - 1)).toFixed(1)},${screenY(sample).toFixed(1)}`).join(' ')} + fill="none" + className="stroke-primary" + strokeWidth={2} + strokeLinecap="round" + strokeLinejoin="round" + /> + {!locked && + keys.map(([t, level], index) => ( + { + event.stopPropagation() + if (event.button === 2) { + return + } + event.currentTarget.ownerSVGElement?.setPointerCapture(event.pointerId) + setDrag({ index, keys, range }) + }} + onContextMenu={(event) => { + event.preventDefault() + event.stopPropagation() + onWrite(withoutKeyframe(keys, index)) + }} + /> + ))} + + {!isShape(value) &&

{hint}

} +
+ ) +} + +function PointsForm({ keys, locked, onWrite }: { keys: Keyframe[]; locked: boolean; onWrite(next: Keyframe[]): void }): React.JSX.Element { + return ( +
+ {keys.map(([t, value], index) => ( +
+ next !== undefined && onWrite(withKeyframe(keys, index, [next, value]))} /> + next !== undefined && onWrite(withKeyframe(keys, index, [t, next]))} /> + +
+ ))} + +
+ ) +} + +function ShapeForm({ shape, locked, onWrite }: { shape: Record; locked: boolean; onWrite(next: unknown): void }): React.JSX.Element { + const named = shapeNamed(shape.shape)! + const numeric = (name: string): number | undefined => (typeof shape[name] === 'number' ? shape[name] : undefined) + return ( +
+ +
+ onWrite(withSetting(shape, 'from', next))} /> + onWrite(withSetting(shape, 'to', next))} /> +
+ {named.parameters.map((parameter) => ( + onWrite(withSetting(shape, parameter.name, next))} + /> + ))} +
+ ) +} + +interface NumberBoxProps { + label: string + value: number | undefined + placeholder?: string + disabled: boolean + /** The number typed, or undefined when it was emptied; text that is no number is dropped. */ + onCommit(next: number | undefined): void +} + +function NumberBox({ label, value, placeholder, disabled, onCommit }: NumberBoxProps): React.JSX.Element { + const shown = value === undefined ? '' : String(value) + const [draft, setDraft] = useState(shown) + const [seen, setSeen] = useState(shown) + if (seen !== shown) { + setSeen(shown) + setDraft(shown) + } + const commit = (): void => { + if (draft === shown) { + return + } + const next = draft.trim() === '' ? undefined : Number(draft) + if (next !== undefined && !Number.isFinite(next)) { + setDraft(shown) + return + } + onCommit(next) + } + return ( + + ) +} + +function roundTo(value: number): number { + return Math.round(value * DRAGGED_PRECISION) / DRAGGED_PRECISION +} + +function clamp(value: number, lowest: number, highest: number): number { + return Math.min(highest, Math.max(lowest, value)) +} diff --git a/studio/src/renderer/src/studio/CurveField.tsx b/studio/src/renderer/src/studio/CurveField.tsx deleted file mode 100644 index a88f6d010..000000000 --- a/studio/src/renderer/src/studio/CurveField.tsx +++ /dev/null @@ -1,190 +0,0 @@ -import { IdeIcon } from '@/components/IdeIcon' -import { useState } from 'react' -import { Button } from '@/components/ui/button' -import { Input } from '@/components/ui/input' -import { cn } from '@/lib/utils' -import { - CURVE_SHAPES, - isShape, - keyframesFrom, - samplesOf, - shapeFrom, - shapeNamed, - withAddedKeyframe, - withKeyframe, - withoutKeyframe, - withSetting, - withShape, - type Keyframe -} from '../editor/curves' -import { FieldRow, type SettingFieldProps } from './FieldRow' - -const SPARKLINE_WIDTH = 100 -const SPARKLINE_HEIGHT = 24 -const SPARKLINE_SAMPLES = 40 -const SPARKLINE_MARGIN = 2 - -interface CurveFieldProps extends SettingFieldProps { - open: boolean - onToggle(): void -} - -/** A value written as a curve: a sparkline of it that opens an editor for its keyframes, or for the named shape it follows. */ -export function CurveField(props: CurveFieldProps): React.JSX.Element { - const { value, locked, open, onToggle, onSet } = props - return ( - <> - - - - {open && onSet(JSON.stringify(next))} />} - - ) -} - -function Sparkline({ value }: { value: unknown }): React.JSX.Element { - const samples = samplesOf(value, SPARKLINE_SAMPLES) ?? [] - const low = Math.min(...samples) - const span = Math.max(...samples) - low - const drawable = SPARKLINE_HEIGHT - 2 * SPARKLINE_MARGIN - const points = samples.map((sample, index) => { - const x = (index / (samples.length - 1)) * SPARKLINE_WIDTH - const y = SPARKLINE_MARGIN + (span === 0 ? drawable / 2 : drawable - ((sample - low) / span) * drawable) - return `${x.toFixed(1)},${y.toFixed(1)}` - }) - return ( - - - - ) -} - -function CurveEditor({ value, locked, onWrite }: { value: unknown; locked: boolean; onWrite(next: unknown): void }): React.JSX.Element { - const byShape = isShape(value) - return ( -
-
- - -
- {isShape(value) ? : } -
- ) -} - -function PointsEditor({ keys, locked, onWrite }: { keys: Keyframe[]; locked: boolean; onWrite(next: Keyframe[]): void }): React.JSX.Element { - return ( - <> - {keys.map(([t, value], index) => ( -
- next !== undefined && onWrite(withKeyframe(keys, index, [next, value]))} /> - next !== undefined && onWrite(withKeyframe(keys, index, [t, next]))} /> - -
- ))} - - - ) -} - -function ShapeEditor({ shape, locked, onWrite }: { shape: Record; locked: boolean; onWrite(next: unknown): void }): React.JSX.Element { - const named = shapeNamed(shape.shape)! - const numeric = (name: string): number | undefined => (typeof shape[name] === 'number' ? shape[name] : undefined) - return ( - <> - -
- onWrite(withSetting(shape, 'from', next))} /> - onWrite(withSetting(shape, 'to', next))} /> -
- {named.parameters.map((parameter) => ( - onWrite(withSetting(shape, parameter.name, next))} - /> - ))} - - ) -} - -interface NumberBoxProps { - label: string - value: number | undefined - placeholder?: string - disabled: boolean - /** The number typed, or undefined when it was emptied; text that is no number is dropped. */ - onCommit(next: number | undefined): void -} - -function NumberBox({ label, value, placeholder, disabled, onCommit }: NumberBoxProps): React.JSX.Element { - const shown = value === undefined ? '' : String(value) - const [draft, setDraft] = useState(shown) - const [seen, setSeen] = useState(shown) - if (seen !== shown) { - setSeen(shown) - setDraft(shown) - } - const commit = (): void => { - if (draft === shown) { - return - } - const next = draft.trim() === '' ? undefined : Number(draft) - if (next !== undefined && !Number.isFinite(next)) { - setDraft(shown) - return - } - onCommit(next) - } - return ( - - ) -} diff --git a/studio/src/renderer/src/studio/EntryBrowser.tsx b/studio/src/renderer/src/studio/EntryBrowser.tsx index 71673396a..a99928c76 100644 --- a/studio/src/renderer/src/studio/EntryBrowser.tsx +++ b/studio/src/renderer/src/studio/EntryBrowser.tsx @@ -1,4 +1,4 @@ -import { IdeIcon } from '@/components/IdeIcon' +import { ChevronRight, Plus } from 'lucide-react' import { useEffect, useMemo, useState } from 'react' import { Button } from '@/components/ui/button' import { ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuTrigger } from '@/components/ui/context-menu' @@ -73,7 +73,7 @@ export function EntryBrowser({ title, entries, current, onSelect, fileActions, c

{title}

{fileActions !== undefined && ( )}
@@ -172,7 +172,7 @@ function FolderBranch({ folder, depth, context }: { folder: FolderNode; depth: n className="flex h-[26px] w-full items-center gap-1 rounded-md px-2 text-left hover:bg-accent" style={{ paddingLeft: indentOf(depth) }} > - + {folder.name} {NUMBER.format(folder.size)} diff --git a/studio/src/renderer/src/studio/FieldRow.tsx b/studio/src/renderer/src/studio/FieldRow.tsx deleted file mode 100644 index 08a16163a..000000000 --- a/studio/src/renderer/src/studio/FieldRow.tsx +++ /dev/null @@ -1,41 +0,0 @@ -import { IdeIcon } from '@/components/IdeIcon' -import { Button } from '@/components/ui/button' -import { cn } from '@/lib/utils' -import type { SettingOption } from '../bridge/types' - -export interface SettingFieldProps { - option: SettingOption - /** What the file sets it to; undefined when it is not set. */ - value: unknown - locked: boolean - onSet(literal: string): void - onUnset(): void -} - -/** A setting's name on the left and, on the right, what edits it, with the button that unsets it and why the draft is refused. */ -export function FieldRow({ option, value, locked, onUnset, problem, children }: SettingFieldProps & { problem: string | null; children: React.ReactNode }): React.JSX.Element { - return ( -
-
- -
- {children} - -
-
- {problem !== null &&

{problem}

} -
- ) -} - -export function defaultLabel(option: SettingOption): string { - if (option.defaultValue === null || option.defaultValue === undefined) { - return option.required ? 'Required' : 'Not set' - } - const text = typeof option.defaultValue === 'string' ? option.defaultValue : JSON.stringify(option.defaultValue) - return `Default ${text}` -} diff --git a/studio/src/renderer/src/studio/MapStudio.tsx b/studio/src/renderer/src/studio/MapStudio.tsx index 25fadf8db..03d599ab0 100644 --- a/studio/src/renderer/src/studio/MapStudio.tsx +++ b/studio/src/renderer/src/studio/MapStudio.tsx @@ -5,7 +5,7 @@ import type { MapHover, MapLabel, Marker, ModuleViewInfo, PickDisplay, ServerUsa import type { Share } from '../map/census' import type { MapController, MapStatus, MapToggles } from '../map/MapController' import type { Highlight } from '../map/tileStyle' -import { IdeIcon } from '@/components/IdeIcon' +import { Waves } from 'lucide-react' import { HelpDialog } from './HelpDialog' import { HoverCard } from './HoverCard' import { Legend } from './Legend' @@ -280,7 +280,7 @@ export function MapStudio({ client, world, theme, onDisconnect }: MapStudioProps {viewId === 'rivers' && !world.hydrology && (
- +

No rivers planned

Enable hydrology in

dimensions/{world.dimension}.json

diff --git a/studio/src/renderer/src/studio/NodeBox.tsx b/studio/src/renderer/src/studio/NodeBox.tsx new file mode 100644 index 000000000..3b65ab23b --- /dev/null +++ b/studio/src/renderer/src/studio/NodeBox.tsx @@ -0,0 +1,95 @@ +import { memo } from 'react' +import { cn } from '@/lib/utils' +import type { GraphNode } from '../bridge/types' +import { NODE_WIDTH, type PlacedNode, type Point } from '../editor/nodeLayout' +import { NODE_HEADER, NODE_STRIPE, type NodeRows } from '../editor/nodeRows' +import { colorOfKind, colorOfRole } from './nodeColors' +import { NodeRowView } from './NodeRows' + +/** Where a node's sockets sit below its top: level with the middle of its header. */ +export const SOCKET_TOP = NODE_STRIPE + NODE_HEADER / 2 +const SOCKET_SIZE = 9 +const CHIP_FILL_ALPHA = '47' + +interface NodeBoxProps { + placed: PlacedNode + rows: NodeRows + selected: boolean + /** Whether the part being dragged would grow from it if dropped now. */ + dropTarget: boolean + /** How far it is being dragged from where it sits, or null. */ + offset: Point | null + /** Whether the file can be written. */ + locked: boolean +} + +/** + * One node as the editor draws it: a stripe in the colour of its kind, a header with its title and roles, and a row + * per setting, edited in place. A part has an input socket on its left, a ring to drag when it can grow elsewhere; a + * node others grow from has an output socket on its right. + */ +export const NodeBox = memo(function NodeBox({ placed, rows, selected, dropTarget, offset, locked }: NodeBoxProps): React.JSX.Element { + const { node } = placed + const editable = !locked && node.settings.length > 0 + return ( +
+
+ + {rows.rows.map((row) => ( + + ))} + {placed.grown && } + {placed.growing && } +
+ ) +}) + +function NodeHeader({ node }: { node: GraphNode }): React.JSX.Element { + return ( +
+ + {node.title} + + {node.roles.map((role) => ( + + ))} +
+ ) +} + +function RoleChip({ role }: { role: string }): React.JSX.Element { + const color = colorOfRole(role) + return ( + + {role} + + ) +} + +// A part that can grow elsewhere has a ring for an input, a handle to drag onto the node it should grow from. +function InputSocket({ handle }: { handle: boolean }): React.JSX.Element { + return ( + + ) +} + +function socketStyle(side: 'left' | 'right'): React.CSSProperties { + return { [side]: -SOCKET_SIZE / 2, top: SOCKET_TOP - SOCKET_SIZE / 2, width: SOCKET_SIZE, height: SOCKET_SIZE } +} diff --git a/studio/src/renderer/src/studio/NodeCanvas.tsx b/studio/src/renderer/src/studio/NodeCanvas.tsx index 8b357bd2f..d25e4ee7a 100644 --- a/studio/src/renderer/src/studio/NodeCanvas.tsx +++ b/studio/src/renderer/src/studio/NodeCanvas.tsx @@ -1,314 +1,304 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react' -import { ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuSeparator, ContextMenuShortcut, ContextMenuSub, ContextMenuSubContent, ContextMenuSubTrigger, ContextMenuTrigger } from '@/components/ui/context-menu' -import { IdeIcon, type IdeIconName } from '@/components/IdeIcon' -import { cn } from '@/lib/utils' -import type { GraphEdit, GraphNode, JsonPath } from '../bridge/types' -import { idOf, isWithin, layoutNodes, NODE_HEIGHT, NODE_WIDTH, type NodeLayout, type PlacedNode } from '../editor/nodeLayout' -import { useKeyText } from './useBindings' +import { ContextMenu, ContextMenuTrigger } from '@/components/ui/context-menu' +import type { GraphEdit, GraphNode, SettingsType } from '../bridge/types' +import { boundsOf, canRegrow, GRID, idOf, layoutNodes, NODE_WIDTH, nodeAt, snappedToGrid, type PlacedNode, type Point } from '../editor/nodeLayout' +import { positionsAfterEdit } from '../editor/nodePositions' +import { nodeRows, type NodeRows } from '../editor/nodeRows' +import type { SuggestionStore } from '../editor/suggestionStore' +import { rolesOf, type SuggestionSource } from '../editor/suggestions' +import { NodeBox } from './NodeBox' +import { NodeEditingContext, type NodeEditing, type SettingRow } from './nodeEditing' +import { NodeMenu, type MenuTarget } from './NodeMenus' +import { NodeWires } from './NodeWires' +import { useNodeCamera, type Camera } from './useNodeCamera' +import { useNodePositions } from './useNodePositions' -const PART_ICON: IdeIconName = 'views/procedural' -const KIND_ICONS: Record = { - Object: 'views/objects', - Stem: PART_ICON, - Blob: PART_ICON, - Branches: PART_ICON, - Cluster: PART_ICON, - Group: 'groups', - 'Shared part': 'symlink', - Material: 'views/palettes', - Decoration: 'decoration' -} -const FIT_MARGIN = 24 -const LARGEST_FIT_SCALE = 1 -// Below this the node text can't be read; a larger tree is panned instead of shrunk further. -const SMALLEST_FIT_SCALE = 0.8 -const SMALLEST_SCALE = 0.25 -const LARGEST_SCALE = 2 -const WHEEL_ZOOM_PER_PIXEL = 0.0015 -const DRAG_START_PIXELS = 4 -const GRID_SPACING = 16 +const DRAG_START_PIXELS = 3 +const MIDDLE_BUTTON = 1 +const SMALLEST_DOT_SPACING = 6 +const DOT_RADIUS = 1 -interface Camera { - x: number - y: number - scale: number -} - -interface NodeDrag { - placed: PlacedNode - startX: number - startY: number - pointerX: number - pointerY: number - moved: boolean - target: PlacedNode | null -} +/** A node being dragged to another place, or a part's ring being dragged onto the node it should grow from. */ +type NodeGesture = + | { kind: 'moving'; placed: PlacedNode; start: Point; moved: boolean; offset: Point } + | { kind: 'regrowing'; placed: PlacedNode; pointer: Point; target: PlacedNode | null } interface NodeCanvasProps { roots: GraphNode[] - /** Tells files apart, so a new one is fitted into view. */ - fileKey: string + types: Record + /** The file parsed, to read what each setting is set to. */ + values: unknown + /** The file, by its place in the pack, which keeps where its nodes were dragged. */ + file: string selectedId: string | null locked: boolean + suggestions: SuggestionStore /** Filled with the way to fit every node into view, for the keys that live outside the canvas. */ showAllRef: React.RefObject<(() => void) | null> onSelect(node: GraphNode | null): void onEdit(edit: GraphEdit): void } -/** The file as a tree of nodes: drag the background to look around, drag a node onto another to grow it from there. */ -export function NodeCanvas({ roots, fileKey, selectedId, locked, showAllRef, onSelect, onEdit }: NodeCanvasProps): React.JSX.Element { - const layout = useMemo(() => layoutNodes(roots), [roots]) +/** + * The file's nodes on a grid, each listing its settings to edit in place, wired to the nodes they grow from. Drag the + * background to look around, a node to move it, and a part's ring onto another node to grow it from there. + */ +export function NodeCanvas({ roots, types, values, file, selectedId, locked, suggestions, showAllRef, onSelect, onEdit }: NodeCanvasProps): React.JSX.Element { const frame = useRef(null) - const [camera, setCamera] = useCamera(frame, layout, fileKey) - const [drag, setDrag] = useState(null) - const [menuNode, setMenuNode] = useState(null) - const pan = useRef<{ x: number; y: number } | null>(null) - const showAll = useCallback(() => setCamera(fitted(frame.current!, layout)), [setCamera, layout]) + const [open, setOpen] = useState>(new Set()) + const [openCurve, setOpenCurve] = useState(null) + const [positions, setPositions] = useNodePositions(file) + const rowsById = useMemo(() => rowsOfNodes(roots, types, values, open, !locked), [roots, types, values, open, locked]) + const layout = useMemo(() => layoutNodes(roots, (node) => rowsById.get(idOf(node.path))!.height, new Map(Object.entries(positions))), [roots, rowsById, positions]) + const view = useNodeCamera(frame, boundsOf(layout.nodes)) + const [gesture, setGesture] = useState(null) + const [menu, setMenu] = useState(null) + const panFrom = useRef(null) + const settingUnderMenu = useRef(null) + const chosenHere = useRef(null) + + const edit = useCallback( + (change: GraphEdit) => { + setPositions((current) => positionsAfterEdit(current, change, values)) + onEdit(change) + }, + [setPositions, onEdit, values] + ) + const select = useCallback( + (node: GraphNode) => { + chosenHere.current = idOf(node.path) + onSelect(node) + }, + [onSelect] + ) + const { showAll } = view + const showEveryNode = useCallback(() => showAll(boundsOf(layout.nodes)), [showAll, layout]) useEffect(() => { - showAllRef.current = showAll + showAllRef.current = showEveryNode return () => { showAllRef.current = null } - }, [showAllRef, showAll]) + }, [showAllRef, showEveryNode]) + useRevealChosen(layout.nodes, selectedId, chosenHere, view.reveal) + const editing = useEditing({ roots, locked, openCurve, setOpenCurve, setOpen, edit, suggestions, settingUnderMenu }) - const canvasPoint = (clientX: number, clientY: number): { x: number; y: number } => { - const bounds = frame.current!.getBoundingClientRect() - return { x: (clientX - bounds.left - camera.x) / camera.scale, y: (clientY - bounds.top - camera.y) / camera.scale } - } - - const pointerDown = (event: React.PointerEvent): void => { - if (event.button !== 0) { + const pointerDown = (event: React.PointerEvent): void => { + const target = event.target as Element + if (!event.currentTarget.contains(target) || (event.button !== 0 && event.button !== MIDDLE_BUTTON)) { + return + } + const placed = event.button === 0 ? placedUnder(target, layout.nodes) : null + if (placed === null) { + event.currentTarget.setPointerCapture(event.pointerId) + panFrom.current = { x: event.clientX, y: event.clientY } + return + } + select(placed.node) + if (target.closest('[data-node-control]') !== null) { return } event.currentTarget.setPointerCapture(event.pointerId) - const placed = nodeAt(layout, canvasPoint(event.clientX, event.clientY)) - if (placed === null) { - pan.current = { x: event.clientX, y: event.clientY } - return + if (target.closest('[data-socket="regrow"]') !== null) { + setGesture({ kind: 'regrowing', placed, pointer: view.graphPoint(event.clientX, event.clientY), target: null }) + } else { + setGesture({ kind: 'moving', placed, start: { x: event.clientX, y: event.clientY }, moved: false, offset: { x: 0, y: 0 } }) } - setDrag({ placed, startX: event.clientX, startY: event.clientY, pointerX: event.clientX, pointerY: event.clientY, moved: false, target: null }) + } + + // The gesture as it stands at {@code event}, worked out from the event itself: a release can come before the last + // move was drawn. + const gestureAt = (event: React.PointerEvent): NodeGesture | null => { + if (gesture?.kind === 'moving') { + const [dx, dy] = [event.clientX - gesture.start.x, event.clientY - gesture.start.y] + const moved = gesture.moved || Math.hypot(dx, dy) > DRAG_START_PIXELS + return { ...gesture, moved, offset: moved ? { x: dx / view.camera.scale, y: dy / view.camera.scale } : gesture.offset } + } + if (gesture?.kind === 'regrowing') { + const pointer = view.graphPoint(event.clientX, event.clientY) + const over = nodeAt(layout.nodes, pointer) + const takesIt = over !== null && over !== gesture.placed && canRegrow(gesture.placed.node, over.node) + return { ...gesture, pointer, target: takesIt ? over : null } + } + return null } const pointerMove = (event: React.PointerEvent): void => { - if (pan.current !== null) { - const [dx, dy] = [event.clientX - pan.current.x, event.clientY - pan.current.y] - pan.current = { x: event.clientX, y: event.clientY } - setCamera((current) => ({ ...current, x: current.x + dx, y: current.y + dy })) + if (panFrom.current !== null) { + view.panBy(event.clientX - panFrom.current.x, event.clientY - panFrom.current.y) + panFrom.current = { x: event.clientX, y: event.clientY } return } - if (drag === null) { - return + if (gesture !== null) { + setGesture(gestureAt(event)) } - const moved = drag.moved || Math.hypot(event.clientX - drag.startX, event.clientY - drag.startY) > DRAG_START_PIXELS - const canMove = moved && !locked && drag.placed.node.movable - const target = canMove ? moveTarget(layout, drag.placed, canvasPoint(event.clientX, event.clientY)) : null - setDrag({ ...drag, pointerX: event.clientX, pointerY: event.clientY, moved, target }) } - const pointerUp = (): void => { - pan.current = null - if (drag === null) { - return + const pointerUp = (event: React.PointerEvent): void => { + panFrom.current = null + const finished = gestureAt(event) + setGesture(null) + if (finished?.kind === 'moving' && finished.moved) { + const { placed, offset } = finished + const dropped = { x: snappedToGrid(placed.x + offset.x), y: snappedToGrid(placed.y + offset.y) } + if (dropped.x !== placed.x || dropped.y !== placed.y) { + setPositions((current) => ({ ...current, [placed.id]: dropped })) + } + } else if (finished?.kind === 'regrowing' && finished.target !== null) { + edit({ op: 'move', path: finished.placed.node.path, toList: finished.target.node.childList! }) } - if (!drag.moved) { - onSelect(drag.placed.node) - } else if (drag.target !== null) { - onEdit({ op: 'move', path: drag.placed.node.path, toList: drag.target.node.childList! }) - } - setDrag(null) } - const dragging = drag !== null && drag.moved && drag.placed.node.movable && !locked - const dragOffset = dragging ? { x: (drag.pointerX - drag.startX) / camera.scale, y: (drag.pointerY - drag.startY) / camera.scale } : null + const contextMenu = (event: React.MouseEvent): void => { + const target = event.target as Element + const setting = settingUnderMenu.current + settingUnderMenu.current = null + if (!event.currentTarget.contains(target)) { + event.preventDefault() + return + } + const placed = placedUnder(target, layout.nodes) + if (placed === null) { + setMenu({ on: 'background', root: roots[0] ?? null }) + return + } + select(placed.node) + setMenu({ on: 'node', node: placed.node, setting }) + } + + const moved = gesture?.kind === 'moving' && gesture.moved ? { id: gesture.placed.id, offset: gesture.offset } : null + const regrow = gesture?.kind === 'regrowing' ? { part: gesture.placed, pointer: gesture.pointer, onTarget: gesture.target !== null } : null + const dropTargetId = gesture?.kind === 'regrowing' ? (gesture.target?.id ?? null) : null + const { camera } = view return ( - !open && setMenuNode(null)}> + !isOpen && setMenu(null)}>
{ - pan.current = null - setDrag(null) + panFrom.current = null + setGesture(null) }} - onContextMenu={(event) => { - const placed = nodeAt(layout, canvasPoint(event.clientX, event.clientY)) - setMenuNode(placed?.node ?? null) - if (placed === null) { - event.preventDefault() - } else { - onSelect(placed.node) - } - }} - onDoubleClick={(event) => nodeAt(layout, canvasPoint(event.clientX, event.clientY)) === null && showAll()} + onContextMenu={contextMenu} + onDoubleClick={(event) => placedUnder(event.target as Element, layout.nodes) === null && event.currentTarget.contains(event.target as Element) && showEveryNode()} >
- - {layout.nodes.map((placed) => ( - - ))} + + + {layout.nodes.map((placed) => ( + + ))} +
+ {Math.abs(camera.scale - 1) > 0.001 && ( + {Math.round(camera.scale * 100)}% + )}
- {menuNode !== null && } + {menu !== null && ( + setPositions({})} + onShowAll={showEveryNode} + onResetZoom={view.resetZoom} + /> + )}
) } -function NodeBox({ placed, selected, target, offset }: { placed: PlacedNode; selected: boolean; target: boolean; offset: { x: number; y: number } | null }): React.JSX.Element { - const { node } = placed - const icon = KIND_ICONS[node.kind] ?? PART_ICON - const detail = node.roles.length > 0 ? node.roles.join(', ') : node.title === node.kind ? null : node.kind - return ( -
- -
-
{node.title}
- {detail !== null &&
{detail}
} -
-
- ) -} - -function Wires({ layout }: { layout: NodeLayout }): React.JSX.Element { - return ( - - {layout.wires.map(({ from, to, label }) => { - const [startX, startY] = [from.x + NODE_WIDTH, from.y + NODE_HEIGHT / 2] - const [endX, endY] = [to.x, to.y + NODE_HEIGHT / 2] - const bend = (endX - startX) / 2 - return ( - ${to.id}`}> - - {label !== '' && ( - - {label} - - )} - - ) - })} - - ) -} - -function NodeMenu({ node, locked, onEdit }: { node: GraphNode; locked: boolean; onEdit(edit: GraphEdit): void }): React.JSX.Element { - const keyText = useKeyText() - const removable = node.duplicable - return ( - - {node.additions.length > 0 && ( - - Add - - {node.additions.map((addition) => ( - onEdit({ op: 'append', list: addition.list, literal: addition.literal })}> - {addition.label} - - ))} - - - )} - onEdit({ op: 'duplicate', path: node.path })}> - Duplicate - {keyText('duplicateNode')} - - - onEdit({ op: 'delete', path: node.path })}> - Delete - {keyText('deleteNode')} - - - ) -} - -function nodeAt(layout: NodeLayout, point: { x: number; y: number }): PlacedNode | null { - return layout.nodes.find((placed) => point.x >= placed.x && point.x <= placed.x + NODE_WIDTH && point.y >= placed.y && point.y <= placed.y + NODE_HEIGHT) ?? null -} - -// A node can grow from any other that takes children, except from inside itself or from where it already grows. -function moveTarget(layout: NodeLayout, dragged: PlacedNode, point: { x: number; y: number }): PlacedNode | null { - const over = nodeAt(layout, point) - const toList = over?.node.childList - if (over === null || toList === null || toList === undefined || isWithin(toList, dragged.node.path) || isParentList(dragged.node.path, toList)) { - return null +function rowsOfNodes(roots: GraphNode[], types: Record, values: unknown, open: ReadonlySet, editable: boolean): Map { + const rows = new Map() + const visit = (node: GraphNode): void => { + rows.set(idOf(node.path), nodeRows(node, types, values, open, editable)) + node.children.forEach((link) => visit(link.node)) } - return over + roots.forEach(visit) + return rows } -function isParentList(path: JsonPath, list: JsonPath): boolean { - return path.length === list.length + 1 && isWithin(path, list) +function placedUnder(target: Element, nodes: PlacedNode[]): PlacedNode | null { + const id = target.closest('[data-node-id]')?.getAttribute('data-node-id') + return nodes.find((placed) => placed.id === id) ?? null } -function useCamera(frame: React.RefObject, layout: NodeLayout, fileKey: string): [Camera, React.Dispatch>] { - const [camera, setCamera] = useState({ x: FIT_MARGIN, y: FIT_MARGIN, scale: 1 }) - const fittedFile = useRef(null) +// Each dot sits on a point nodes snap to, so they stay on the dots at any zoom. +function gridStyle(camera: Camera): React.CSSProperties { + const spacing = GRID * camera.scale + if (spacing < SMALLEST_DOT_SPACING) { + return {} + } + return { + backgroundImage: `radial-gradient(circle at ${DOT_RADIUS}px ${DOT_RADIUS}px, var(--overlay-border) ${DOT_RADIUS}px, transparent ${DOT_RADIUS + 0.5}px)`, + backgroundSize: `${spacing}px ${spacing}px`, + backgroundPosition: `${camera.x - DOT_RADIUS}px ${camera.y - DOT_RADIUS}px` + } +} +// A node chosen elsewhere, such as by picking its part in the scene, is brought into sight; one chosen here already is. +function useRevealChosen(nodes: PlacedNode[], selectedId: string | null, chosenHere: React.RefObject, reveal: (area: { left: number; top: number; right: number; bottom: number }) => void): void { + const handled = useRef(null) useEffect(() => { - if (frame.current === null || layout.nodes.length === 0 || fittedFile.current === fileKey) { + if (selectedId === handled.current) { return } - fittedFile.current = fileKey - setCamera(fitted(frame.current, layout)) - }, [frame, layout, fileKey]) - - useEffect(() => { - const element = frame.current - if (element === null) { + handled.current = selectedId + const placed = nodes.find((candidate) => candidate.id === selectedId) + if (placed === undefined || selectedId === chosenHere.current) { return } - const wheel = (event: WheelEvent): void => { - event.preventDefault() - const bounds = element.getBoundingClientRect() - const [pointerX, pointerY] = [event.clientX - bounds.left, event.clientY - bounds.top] - setCamera((current) => { - const scale = clamp(current.scale * Math.exp(-event.deltaY * WHEEL_ZOOM_PER_PIXEL), SMALLEST_SCALE, LARGEST_SCALE) - const ratio = scale / current.scale - return { scale, x: pointerX - (pointerX - current.x) * ratio, y: pointerY - (pointerY - current.y) * ratio } - }) - } - element.addEventListener('wheel', wheel, { passive: false }) - return () => element.removeEventListener('wheel', wheel) - }, [frame]) - - return [camera, setCamera] + reveal({ left: placed.x, top: placed.y, right: placed.x + NODE_WIDTH, bottom: placed.y + placed.height }) + }, [nodes, selectedId, chosenHere, reveal]) } -function fitted(frame: HTMLDivElement, layout: NodeLayout): Camera { - const [width, height] = [frame.clientWidth - 2 * FIT_MARGIN, frame.clientHeight - 2 * FIT_MARGIN] - const scale = clamp(Math.min(width / Math.max(layout.width, 1), height / Math.max(layout.height, 1)), SMALLEST_FIT_SCALE, LARGEST_FIT_SCALE) - return { scale, x: FIT_MARGIN, y: FIT_MARGIN + Math.max(0, (height - layout.height * scale) / 2) } +interface EditingInputs { + roots: GraphNode[] + locked: boolean + openCurve: string | null + setOpenCurve(rowId: string | null): void + setOpen: React.Dispatch>> + edit(change: GraphEdit): void + suggestions: SuggestionStore + settingUnderMenu: React.RefObject } -function clamp(value: number, lowest: number, highest: number): number { - return Math.min(highest, Math.max(lowest, value)) +function useEditing({ roots, locked, openCurve, setOpenCurve, setOpen, edit, suggestions, settingUnderMenu }: EditingInputs): NodeEditing { + const roles = useMemo(() => rolesOf(roots), [roots]) + return useMemo( + () => ({ + locked, + openCurve, + onOpenCurve: setOpenCurve, + onToggleFold: (foldId: string) => + setOpen((current) => { + const next = new Set(current) + if (!next.delete(foldId)) { + next.add(foldId) + } + return next + }), + onEdit: edit, + loadSuggestions: (source: SuggestionSource) => (source.from === 'roles' ? Promise.resolve(roles) : suggestions.load(source)), + onSettingMenu: (row: SettingRow) => { + settingUnderMenu.current = row + } + }), + [locked, openCurve, setOpenCurve, setOpen, edit, roles, suggestions, settingUnderMenu] + ) } diff --git a/studio/src/renderer/src/studio/NodeInspector.tsx b/studio/src/renderer/src/studio/NodeInspector.tsx deleted file mode 100644 index c3f60c7ae..000000000 --- a/studio/src/renderer/src/studio/NodeInspector.tsx +++ /dev/null @@ -1,295 +0,0 @@ -import { IdeIcon } from '@/components/IdeIcon' -import { useMemo, useState } from 'react' -import { Button } from '@/components/ui/button' -import { ScrollArea } from '@/components/ui/scroll-area' -import { cn } from '@/lib/utils' -import type { EditorState, GraphEdit, GraphNode, NodeSettings, SettingOption, ValueKind } from '../bridge/types' -import { canBecomeCurve, curveFrom, isCurve } from '../editor/curves' -import { valueAt } from '../editor/jsonValues' -import { foldedSections, idOfFold, visibleFolds, type SettingsFold } from '../editor/settingFolds' -import { NOT_SET, isStringList, isText, literalOf, textOf } from '../editor/settingText' -import type { SuggestionStore } from '../editor/suggestionStore' -import { rolesOf, suggestionSourceOf, type SuggestionSource } from '../editor/suggestions' -import { CurveField } from './CurveField' -import { FieldRow, defaultLabel, type SettingFieldProps } from './FieldRow' -import { SuggestionInput } from './SuggestionInput' - -const FOLD_INDENT_PX = 10 - -interface NodeInspectorProps { - node: GraphNode - state: EditorState - /** The file parsed, to read what each setting is set to. */ - values: unknown - suggestions: SuggestionStore - onEdit(edit: GraphEdit): void -} - -/** What the fields of a section share: the file and the edits made to it, and which folds and curves are open. */ -interface SectionContext { - state: EditorState - values: unknown - locked: boolean - open: ReadonlySet - roles: string[] - suggestions: SuggestionStore - onToggle(id: string): void - onEdit(edit: GraphEdit): void -} - -/** The settings of the chosen node, a field per option of its schema type; an empty field leaves the option unset. */ -export function NodeInspector({ node, state, values, suggestions, onEdit }: NodeInspectorProps): React.JSX.Element { - const [open, setOpen] = useState>(new Set()) - const roles = useMemo(() => rolesOf(state.roots ?? []), [state.roots]) - const context: SectionContext = { - state, - values, - locked: state.locked !== null, - open, - roles, - suggestions, - onToggle: (id) => - setOpen((current) => { - const next = new Set(current) - if (!next.delete(id)) { - next.add(id) - } - return next - }), - onEdit - } - return ( -
-
-

{node.title}

-

{node.roles.length > 0 ? node.roles.join(', ') : node.kind}

-
- -
- {node.settings.map((section) => ( - - ))} -
-
-
- ) -} - -function SettingsSection({ section, context }: { section: NodeSettings; context: SectionContext }): React.JSX.Element { - const { state, values, open } = context - const folds = visibleFolds(foldedSections(section, state.types, values), open) - return ( -
- {folds.map((fold) => - fold.kind === 'own' ? ( -
-

- {fold.title} -

- -
- ) : ( -
- - {open.has(idOfFold(fold)) && } -
- ) - )} -
- ) -} - -function FoldHeader({ fold, context }: { fold: SettingsFold; context: SectionContext }): React.JSX.Element { - const { open, locked, onToggle, onEdit } = context - const id = idOfFold(fold) - const unfolded = open.has(id) - const holder = fold.holder - return ( -
- - {fold.kind === 'list' && ( - - )} - {holder !== null && ( - - )} - {fold.kind === 'item' && ( - - )} -
- ) -} - -function FoldFields({ fold, context }: { fold: SettingsFold; context: SectionContext }): React.JSX.Element { - const { values, locked, open, roles, suggestions, onToggle, onEdit } = context - return ( -
- {fold.options.map((option) => { - const value = valueAt(values, [...fold.path, option.name]) - const curveId = JSON.stringify([...fold.path, option.name]) - return ( - onToggle(curveId)} - loadSuggestions={(source) => (source.from === 'roles' ? Promise.resolve(roles) : suggestions.load(source))} - onSet={(literal) => onEdit({ op: 'set', object: fold.path, key: option.name, literal })} - onUnset={() => onEdit({ op: 'unset', object: fold.path, key: option.name })} - /> - ) - })} -
- ) -} - -interface FieldProps extends SettingFieldProps { - /** The schema type of the object the option is in. */ - owner: string - curveOpen: boolean - onToggleCurve(): void - loadSuggestions(source: SuggestionSource): Promise -} - -function SettingField(props: FieldProps): React.JSX.Element { - const kind = props.option.kind.kind - if (kind === 'boolean' || kind === 'enum') { - return - } - if (kind === 'any' && isCurve(props.value)) { - return - } - return -} - -function ChoiceField(props: SettingFieldProps): React.JSX.Element { - const { option, value, locked, onSet, onUnset } = props - const choices = option.kind.kind === 'enum' ? option.kind.constants.map((constant) => constant.name) : ['true', 'false'] - const literalOfChoice = (choice: string): string => (option.kind.kind === 'enum' ? JSON.stringify(choice) : choice) - return ( - - - - ) -} - -// Numbers, text and anything else are typed in; a draft that does not fit the option says why and is not written. -// A number or range of an option that takes any JSON value can be made a curve, which a curve is an option's to take. -function TypedField(props: FieldProps): React.JSX.Element { - const { option, value, locked, owner, onSet, onUnset, onToggleCurve, loadSuggestions } = props - const shown = textOf(option.kind, value) - const [draft, setDraft] = useState(shown) - const problem = draft.trim() === NOT_SET ? null : problemWith(option, draft) - const source = suggestionSourceOf(owner, option) - const commit = (): void => { - if (draft === shown || problem !== null) { - return - } - if (draft.trim() === NOT_SET) { - onUnset() - return - } - onSet(literalOf(option.kind, draft)) - } - return ( - - loadSuggestions(source)} - disabled={locked} - placeholder={defaultLabel(option)} - aria-invalid={problem !== null} - title={option.description} - inputMode={isNumber(option.kind) ? 'decimal' : undefined} - className={cn('h-7 px-2 text-[12px] md:text-[12px]', isNumber(option.kind) ? 'tabular-nums' : !isText(option.kind) && 'font-mono text-[11.5px] placeholder:font-sans md:text-[11.5px]')} - onBlur={commit} - onKeyDown={(event) => { - if (event.key === 'Enter') { - commit() - } else if (event.key === 'Escape') { - setDraft(shown) - } - }} - /> - {option.kind.kind === 'any' && canBecomeCurve(value) && ( - - )} - - ) -} - -function isNumber(kind: ValueKind): boolean { - return kind.kind === 'integer' || kind.kind === 'decimal' -} - -function problemWith(option: SettingOption, draft: string): string | null { - if (isText(option.kind) || isStringList(option.kind)) { - return isStringList(option.kind) && draft.trim().startsWith('[') && !isJson(draft) ? 'Not JSON' : null - } - if (!isNumber(option.kind)) { - return isJson(draft) ? null : 'Not JSON' - } - const number = Number(draft) - if (draft.trim() === '' || !Number.isFinite(number)) { - return 'Not a number' - } - if (option.kind.kind === 'integer' && !Number.isInteger(number)) { - return 'Not a whole number' - } - if (option.minimum !== null && number < option.minimum) { - return `At least ${option.minimum}` - } - if (option.maximum !== null && number > option.maximum) { - return `At most ${option.maximum}` - } - return null -} - -function isJson(text: string): boolean { - try { - JSON.parse(text) - return true - } catch { - return false - } -} diff --git a/studio/src/renderer/src/studio/NodeMenus.tsx b/studio/src/renderer/src/studio/NodeMenus.tsx new file mode 100644 index 000000000..28660bf58 --- /dev/null +++ b/studio/src/renderer/src/studio/NodeMenus.tsx @@ -0,0 +1,132 @@ +import { ContextMenuContent, ContextMenuItem, ContextMenuSeparator, ContextMenuShortcut, ContextMenuSub, ContextMenuSubContent, ContextMenuSubTrigger } from '@/components/ui/context-menu' +import type { GraphEdit, GraphNode } from '../bridge/types' +import { canBecomeCurve, curveFrom, curveLiteral, isCurve, roundedNumber, samplesOf } from '../editor/curves' +import { idOf } from '../editor/nodeLayout' +import type { SettingRow } from './nodeEditing' +import { useKeyText } from './useBindings' + +const ADD_PREFIX = 'Add ' + +/** What a right-click is on: a node, and the setting under the pointer if any; or the background, with the file's first node. */ +export type MenuTarget = { on: 'node'; node: GraphNode; setting: SettingRow | null } | { on: 'background'; root: GraphNode | null } + +interface NodeMenuProps { + target: MenuTarget + locked: boolean + onEdit(edit: GraphEdit): void + onOpenCurve(rowId: string): void + onArrange(): void + onShowAll(): void + onResetZoom(): void +} + +export function NodeMenu(props: NodeMenuProps): React.JSX.Element { + const { target } = props + return {target.on === 'node' ? : } +} + +function NodeItems({ node, setting, locked, onEdit, onOpenCurve }: NodeMenuProps & { node: GraphNode; setting: SettingRow | null }): React.JSX.Element { + const keyText = useKeyText() + const isRoot = node.path.length === 0 + return ( + <> + {setting !== null && } + + {!isRoot && ( + <> + {node.additions.length > 0 && } + onEdit({ op: 'duplicate', path: node.path })}> + Duplicate + {keyText('duplicateNode')} + + onEdit({ op: 'delete', path: node.path })}> + {node.children.length === 0 ? 'Delete' : 'Delete with what grows from it'} + {keyText('deleteNode')} + + + )} + + ) +} + +// A value that runs along a part can be turned into a curve and back, at the top of its node's menu. +function CurveItems({ setting, locked, onEdit, onOpenCurve }: { setting: SettingRow; locked: boolean; onEdit(edit: GraphEdit): void; onOpenCurve(rowId: string): void }): React.JSX.Element | null { + const { option, fold, value } = setting + const current = value ?? option.defaultValue + if (option.kind.kind !== 'any' || (!isCurve(current) && !canBecomeCurve(current))) { + return null + } + const set = (literal: string): void => onEdit({ op: 'set', object: fold.path, key: option.name, literal }) + const makeCurve = (): void => { + set(curveLiteral(curveFrom(current))) + onOpenCurve(setting.id) + } + return ( + <> + {isCurve(current) ? ( + set(roundedNumber(samplesOf(current, 1)![0]))}> + Make it one number + + ) : ( + + Make it a curve + + )} + + + ) +} + +/** + * What can be added under the node: the parts it can grow in one submenu, anything else, like the object's materials + * and decorations, as an item each. + */ +function AdditionItems({ node, locked, onEdit }: { node: GraphNode; locked: boolean; onEdit(edit: GraphEdit): void }): React.JSX.Element { + const byList = new Map() + for (const addition of node.additions) { + byList.set(idOf(addition.list), [...(byList.get(idOf(addition.list)) ?? []), addition]) + } + const partsTitle = node.path.length === 0 ? 'Add part' : 'Add part growing from this' + return ( + <> + {[...byList.entries()].map(([list, additions]) => + additions.length > 1 ? ( + + {partsTitle} + + {additions.map((addition) => ( + onEdit({ op: 'append', list: addition.list, literal: addition.literal })}> + {addition.label} + + ))} + + + ) : ( + onEdit({ op: 'append', list: additions[0].list, literal: additions[0].literal })}> + {ADD_PREFIX + additions[0].label.toLowerCase()} + + ) + )} + + ) +} + +function BackgroundItems({ root, locked, onEdit, onArrange, onShowAll, onResetZoom }: NodeMenuProps & { root: GraphNode | null }): React.JSX.Element { + const keyText = useKeyText() + return ( + <> + {root !== null && root.additions.length > 0 && ( + <> + + + + )} + Arrange nodes + + Show every node + {keyText('showAllNodes')} + + Reset zoom + + ) +} diff --git a/studio/src/renderer/src/studio/NodePane.tsx b/studio/src/renderer/src/studio/NodePane.tsx index cec2168a0..cdb5e20c9 100644 --- a/studio/src/renderer/src/studio/NodePane.tsx +++ b/studio/src/renderer/src/studio/NodePane.tsx @@ -1,25 +1,31 @@ -import { IdeIcon } from '@/components/IdeIcon' +import { Lock, Redo2, Undo2 } from 'lucide-react' import { useEffect, useRef } from 'react' import { Button } from '@/components/ui/button' import type { GraphNode } from '../bridge/types' +import { idOf } from '../editor/nodeLayout' +import type { SuggestionStore } from '../editor/suggestionStore' import type { NodeEditor } from '../editor/useNodeEditor' import { NodeCanvas } from './NodeCanvas' import { isInEntryBrowser, isTypingInto, nodeEditorActionFor, type NodeEditorAction } from './shortcuts' -import { useBindings } from './useBindings' +import { useBindings, useKeyText } from './useBindings' interface NodePaneProps { editor: NodeEditor /** The entry the file belongs to. */ entryKey: string + /** The file parsed, to read what each setting is set to. */ + values: unknown + suggestions: SuggestionStore selected: GraphNode | null onSelect(node: GraphNode | null): void } -/** The node editor under the scene: the entry's file as nodes, with undo and redo. */ -export function NodePane({ editor, entryKey, selected, onSelect }: NodePaneProps): React.JSX.Element { +/** The node editor under the scene: the entry's file as nodes, their settings edited in place, with undo and redo. */ +export function NodePane({ editor, entryKey, values, suggestions, selected, onSelect }: NodePaneProps): React.JSX.Element { const { state } = editor const locked = state === null || state.locked !== null const showAllRef = useRef<(() => void) | null>(null) + const keyText = useKeyText() useEditorKeys(editor, selected, locked, showAllRef, onSelect) return ( @@ -28,18 +34,19 @@ export function NodePane({ editor, entryKey, selected, onSelect }: NodePaneProps

Nodes

{state?.file ?? entryKey} + {!locked && Right-click to add or delete · Drag a ring onto a node to regrow · {keyText('undo')} undoes} {state?.locked != null && ( - + Read only )} {editor.saving && Saving…}
@@ -52,10 +59,14 @@ export function NodePane({ editor, entryKey, selected, onSelect }: NodePaneProps )} {state !== null && state.roots !== null && ( + case 'fold': + return + case 'setting': + return + case 'addSetting': + return + } +} + +function HeadingRow({ title }: { title: string }): React.JSX.Element { + return ( +
+ {title} +
+ ) +} + +// ▸ palette zoom 2 · palette 3 folded; ▾ palette open. A list gets a + to add an element, an element a × to remove it. +function FoldRow({ fold, open, editable }: { fold: SettingsFold; open: boolean; editable: boolean }): React.JSX.Element { + const { onToggleFold, onEdit } = useNodeEditing() + const holder = fold.holder + const showsSummary = !open || fold.kind === 'list' + return ( +
+ + {fold.kind === 'list' &&
+ ) +} + +/** Offers the settings left at their default, a submenu per section when more than one has some. */ +function AddSettingRow({ addable }: { addable: SettingsFold[] }): React.JSX.Element { + return ( +
+ + + + + + {addable.length === 1 ? ( + + ) : ( + addable.map((fold) => ( + + {sectionLabel(fold)} + + + + + )) + )} + + +
+ ) +} + +function UnsetItems({ fold }: { fold: SettingsFold }): React.JSX.Element { + const { onEdit } = useNodeEditing() + const add = (option: SettingOption): void => onEdit({ op: 'set', object: fold.path, key: option.name, literal: defaultLiteral(option) }) + return ( + <> + {fold.unset.map((option) => ( + add(option)}> + {option.name} + {defaultText(option)} + + ))} + + ) +} + +function sectionLabel(fold: SettingsFold): string { + return fold.kind === 'item' ? `${String(fold.path.at(-2))} #${fold.title}` : fold.title +} diff --git a/studio/src/renderer/src/studio/NodeSettingRow.tsx b/studio/src/renderer/src/studio/NodeSettingRow.tsx new file mode 100644 index 000000000..6b552555a --- /dev/null +++ b/studio/src/renderer/src/studio/NodeSettingRow.tsx @@ -0,0 +1,267 @@ +import { Check, ChevronDown } from 'lucide-react' +import { useRef, useState } from 'react' +import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu' +import { Popover, PopoverAnchor, PopoverContent } from '@/components/ui/popover' +import { cn } from '@/lib/utils' +import { curveLiteral, isCurve } from '../editor/curves' +import { NODE_ROW } from '../editor/nodeRows' +import { defaultText, isNumber, isStringList, literalOf, NOT_SET, problemWith, textOf } from '../editor/settingText' +import { suggestionSourceOf } from '../editor/suggestions' +import { CurveEditor, CurvePreview } from './CurveEditor' +import { useNodeEditing, type SettingRow } from './nodeEditing' +import { SuggestionInput } from './SuggestionInput' + +export const ROW_LABEL_WIDTH = 86 +export const ROW_INDENT = 10 +const FIELD = 'flex h-5 w-full min-w-0 items-center gap-1.5 rounded-sm border border-input bg-muted px-1.5 text-left' +const EDITABLE_FIELD = 'hover:border-secondary-text' +const CURVE_HINT = 'Click to shape the curve · right-click to make it one number' + +interface SettingRowProps { + row: SettingRow + /** Whether its value can be changed: the file can be written and the node has settings of its own. */ + editable: boolean +} + +/** One setting of a node: its name, its value edited in place, and a control to remove it so it falls back to its default. */ +export function NodeSettingRow({ row, editable }: SettingRowProps): React.JSX.Element { + const { onEdit } = useNodeEditing() + const { option, fold, value } = row + const fallback = defaultText(option) + return ( +
+ + {option.name} + +
+ +
+
+ ) +} + +interface RowButtonProps { + glyph: '×' | '+' + tone: 'remove' | 'add' + hidden?: boolean + title: string + onClick(): void +} + +/** A menu in a node gives no focus back to what opened it, which would leave a focus ring on the node. */ +export function keepFocusOnCanvas(event: Event): void { + event.preventDefault() +} + +/** The small round control at a row's right end: × removes, + adds. */ +export function RowButton({ glyph, tone, hidden = false, title, onClick }: RowButtonProps): React.JSX.Element { + return ( + + ) +} + +function SettingValue({ row, editable }: SettingRowProps): React.JSX.Element { + const kind = row.option.kind.kind + if (kind === 'boolean') { + return + } + if (kind === 'enum') { + return + } + if (kind === 'any' && isCurve(row.value)) { + return + } + return +} + +/** The value as the field shows it, or the default it falls back to, dimmed, while it is unset. */ +function ShownText({ row }: { row: SettingRow }): React.JSX.Element { + const isSet = row.value !== undefined + const text = isSet ? textOf(row.option.kind, row.value) : defaultText(row.option) + return {text} +} + +function CheckValue({ row, editable }: SettingRowProps): React.JSX.Element { + const { onEdit } = useNodeEditing() + const checked = (row.value ?? row.option.defaultValue) === true + return ( + + ) +} + +function ChoiceValue({ row, editable }: SettingRowProps): React.JSX.Element { + const { onEdit } = useNodeEditing() + const constants = row.option.kind.kind === 'enum' ? row.option.kind.constants : [] + const current = row.value ?? row.option.defaultValue + return ( + + + + + + {constants.map((constant) => ( + onEdit({ op: 'set', object: row.fold.path, key: row.option.name, literal: JSON.stringify(constant.name) })} + > + {constant.name} + + ))} + + + ) +} + +function CurveValue({ row, editable }: SettingRowProps): React.JSX.Element { + const { openCurve, onOpenCurve, onEdit, onSettingMenu } = useNodeEditing() + return ( + onOpenCurve(open ? row.id : null)}> + + + + event.preventDefault()}> + onEdit({ op: 'set', object: row.fold.path, key: row.option.name, literal: curveLiteral(next) })} /> + + + ) +} + +// Clicked, the value turns into a text field over the same spot until it is saved or given up. +function TypedValue({ row, editable }: SettingRowProps): React.JSX.Element { + const { onSettingMenu } = useNodeEditing() + const [typing, setTyping] = useState(false) + if (typing) { + return setTyping(false)} /> + } + return ( + + ) +} + +/** + * The value being typed. Enter saves it, or keeps it open to fix with why it was refused; leaving the field saves it + * too, or puts back what was saved when it is refused. Escape gives it up, and an emptied value is removed. + */ +function ValueInput({ row, onDone }: { row: SettingRow; onDone(): void }): React.JSX.Element { + const { onEdit, loadSuggestions } = useNodeEditing() + const { option, fold, value } = row + const saved = textOf(option.kind, value) + const [draft, setDraft] = useState(saved) + const [shownProblem, setShownProblem] = useState(null) + const finished = useRef(false) + const source = suggestionSourceOf(fold.type, option) + + // The field leaving the page can blur it once more, which must not save a second time. + const finish = (): void => { + finished.current = true + onDone() + } + + const commit = (stayOnRefusal: boolean): void => { + if (finished.current) { + return + } + const problem = problemWith(option, draft) + if (problem !== null && stayOnRefusal) { + setShownProblem(problem) + return + } + finish() + if (problem !== null || draft.trim() === saved.trim()) { + return + } + if (draft.trim() === NOT_SET) { + onEdit({ op: 'unset', object: fold.path, key: option.name }) + return + } + onEdit({ op: 'set', object: fold.path, key: option.name, literal: literalOf(option.kind, draft) }) + } + + return ( +
+ { + setDraft(next) + setShownProblem(null) + }} + isList={isStringList(option.kind)} + load={source === null ? null : () => loadSuggestions(source)} + autoFocus + placeholder={defaultText(option)} + aria-invalid={shownProblem !== null} + inputMode={isNumber(option.kind) ? 'decimal' : undefined} + className="h-5 rounded-sm bg-popover px-1.5 py-0 text-[11.5px] shadow-none focus-visible:ring-2 md:text-[11.5px] dark:bg-popover" + onFocus={(event) => event.currentTarget.select()} + onBlur={() => commit(false)} + onKeyDown={(event) => { + if (event.key === 'Enter') { + commit(true) + } else if (event.key === 'Escape') { + event.stopPropagation() + finish() + } + }} + /> + {shownProblem !== null && ( +

+ {shownProblem} +

+ )} +
+ ) +} diff --git a/studio/src/renderer/src/studio/NodeWires.tsx b/studio/src/renderer/src/studio/NodeWires.tsx new file mode 100644 index 000000000..c2d924a5d --- /dev/null +++ b/studio/src/renderer/src/studio/NodeWires.tsx @@ -0,0 +1,69 @@ +import { memo } from 'react' +import { cn } from '@/lib/utils' +import { NODE_WIDTH, type PlacedNode, type PlacedWire, type Point } from '../editor/nodeLayout' +import { colorOfKind } from './nodeColors' +import { SOCKET_TOP } from './NodeBox' + +/** The wire to a part placed once per copy, such as a branch of branches, rather than once. */ +export const EACH_COPY_WIRE = 'each copy' +const SMALLEST_BEND = 30 +const COPY_DASH = '5 5' + +/** A node being dragged: how far it is from where it sits. */ +export interface MovedNode { + id: string + offset: Point +} + +/** A part's ring being dragged to grow it elsewhere: the pointer, and whether it is over a node that takes it. */ +export interface RegrowLine { + part: PlacedNode + pointer: Point + onTarget: boolean +} + +interface NodeWiresProps { + wires: PlacedWire[] + selectedId: string | null + moved: MovedNode | null + regrow: RegrowLine | null +} + +/** The wires from each node to the nodes that grow from it; a copy's is dashed in its parent's colour. */ +export const NodeWires = memo(function NodeWires({ wires, selectedId, moved, regrow }: NodeWiresProps): React.JSX.Element { + const at = (placed: PlacedNode): Point => (moved?.id === placed.id ? { x: placed.x + moved.offset.x, y: placed.y + moved.offset.y } : placed) + return ( + + {wires.map(({ from, to, label }) => { + const lit = selectedId === from.id || selectedId === to.id + const copies = label === EACH_COPY_WIRE + const [start, end] = [at(from), at(to)] + return ( + ${to.id}`} + d={curve({ x: start.x + NODE_WIDTH, y: start.y + SOCKET_TOP }, { x: end.x, y: end.y + SOCKET_TOP })} + className={cn('fill-none', lit ? 'stroke-primary' : !copies && 'stroke-input')} + style={copies && !lit ? { stroke: colorOfKind(from.node.kind) } : undefined} + strokeWidth={lit ? 2 : 1.5} + strokeDasharray={copies ? COPY_DASH : undefined} + strokeLinecap="round" + /> + ) + })} + {regrow !== null && ( + + )} + + ) +}) + +function curve(from: Point, to: Point): string { + const bend = Math.max(SMALLEST_BEND, Math.abs(to.x - from.x) / 2) + return `M${from.x},${from.y} C${from.x + bend},${from.y} ${to.x - bend},${to.y} ${to.x},${to.y}` +} diff --git a/studio/src/renderer/src/studio/NoiseStudio.tsx b/studio/src/renderer/src/studio/NoiseStudio.tsx index 8d9ad0284..21e8243d6 100644 --- a/studio/src/renderer/src/studio/NoiseStudio.tsx +++ b/studio/src/renderer/src/studio/NoiseStudio.tsx @@ -1,4 +1,4 @@ -import { IdeIcon } from '@/components/IdeIcon' +import { RefreshCw, RotateCcw, Search } from 'lucide-react' import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' @@ -92,7 +92,7 @@ export function NoiseStudio({ title, client, packRevision, onSummary, tell }: No {display === 'terrain' && source?.blockRange === null && } {display === 'flat' && ( )} @@ -166,7 +166,7 @@ function SeedField({ seed, usesSeed, onChange }: { seed: string; usesSeed: boole onKeyDown={(event) => event.key === 'Enter' && commit()} />
{!usesSeed &&

Keeps the world's seed

} @@ -232,7 +232,7 @@ function SourceList({ sources, current, onSelect }: { sources: NoiseSource[]; cu
- + setFilter(event.target.value)} />
diff --git a/studio/src/renderer/src/studio/PatternStudio.tsx b/studio/src/renderer/src/studio/PatternStudio.tsx index dd6a4543d..f3f590b55 100644 --- a/studio/src/renderer/src/studio/PatternStudio.tsx +++ b/studio/src/renderer/src/studio/PatternStudio.tsx @@ -1,4 +1,4 @@ -import { IdeIcon } from '@/components/IdeIcon' +import { RotateCcw } from 'lucide-react' import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { Button } from '@/components/ui/button' import { ScrollArea } from '@/components/ui/scroll-area' @@ -70,7 +70,7 @@ export function PatternStudio({ client, view, packRevision, onSummary, tell }: P chooseDepth(depth - 1)} onOn={() => chooseDepth(depth + 1)} /> )} } diff --git a/studio/src/renderer/src/studio/PickInspector.tsx b/studio/src/renderer/src/studio/PickInspector.tsx index d1a007d4f..923caae53 100644 --- a/studio/src/renderer/src/studio/PickInspector.tsx +++ b/studio/src/renderer/src/studio/PickInspector.tsx @@ -1,4 +1,4 @@ -import { IdeIcon } from '@/components/IdeIcon' +import { ChevronRight } from 'lucide-react' import { useState } from 'react' import { ScrollArea } from '@/components/ui/scroll-area' import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group' @@ -92,7 +92,7 @@ function RegionSection({ section, open, onToggle }: { section: PickSection; open return (
diff --git a/studio/src/renderer/src/studio/SavedWorldStudio.tsx b/studio/src/renderer/src/studio/SavedWorldStudio.tsx index 51058ed23..517261086 100644 --- a/studio/src/renderer/src/studio/SavedWorldStudio.tsx +++ b/studio/src/renderer/src/studio/SavedWorldStudio.tsx @@ -1,4 +1,4 @@ -import { IdeIcon } from '@/components/IdeIcon' +import { RefreshCw } from 'lucide-react' import { useEffect, useMemo, useRef, useState } from 'react' import { Button } from '@/components/ui/button' import { ScrollArea } from '@/components/ui/scroll-area' @@ -107,7 +107,7 @@ export function SavedWorldStudio({ title, client, world, onSummary, onProgress, } diff --git a/studio/src/renderer/src/studio/SceneStudio.tsx b/studio/src/renderer/src/studio/SceneStudio.tsx index 27903d64d..5ce5bca74 100644 --- a/studio/src/renderer/src/studio/SceneStudio.tsx +++ b/studio/src/renderer/src/studio/SceneStudio.tsx @@ -19,7 +19,6 @@ import { BakeMeter, useBakeTiming } from './BakeMeter' import { BlockIcon } from './BlockIcon' import { EntryBrowser } from './EntryBrowser' import { useEntryFiles } from './EntryFileDialogs' -import { NodeInspector } from './NodeInspector' import { NodePane } from './NodePane' import { ProfileFormPanel } from './ProfileFormPanel' import { Panel, SidebarPanel, SizeChoice, Stepper, ViewIsland } from './Sidebar' @@ -41,7 +40,7 @@ interface SceneStudioProps { /** * A scene view: its entries on the right, the chosen one in 3D in the middle, with the blocks it is made of. An - * editable view shows the entry's file as nodes under the scene, and the chosen node's settings on the right. + * editable view shows the entry's file as nodes under the scene, each with its settings edited in place. */ export function SceneStudio({ client, view, packRevision, onSummary, tell }: SceneStudioProps): React.JSX.Element { const [waiting, setWaiting] = useState(null) @@ -150,6 +149,8 @@ export function SceneStudio({ client, view, packRevision, onSummary, tell }: Sce { setSelectedPath(node?.path ?? null) @@ -158,14 +159,10 @@ export function SceneStudio({ client, view, packRevision, onSummary, tell }: Sce /> )}
- + {view.form === true && setTyped({ owner: typedOwner, values: NO_OVERRIDES })} />} {view.baked && entry !== null && } - {selected !== null && editor.state !== null ? ( - - ) : ( - - )} + ) diff --git a/studio/src/renderer/src/studio/Sidebar.tsx b/studio/src/renderer/src/studio/Sidebar.tsx index 51bb1aa8a..441bc1cdd 100644 --- a/studio/src/renderer/src/studio/Sidebar.tsx +++ b/studio/src/renderer/src/studio/Sidebar.tsx @@ -1,6 +1,6 @@ import { createContext, useContext } from 'react' import { createPortal } from 'react-dom' -import { IdeIcon, type IdeIconName } from '@/components/IdeIcon' +import { ChevronLeft, ChevronRight, type LucideIcon } from 'lucide-react' import { Button } from '@/components/ui/button' import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group' import { cn } from '@/lib/utils' @@ -35,11 +35,11 @@ export function Stepper({ label, backHint, onHint, onBack, onOn }: StepperProps) return ( {label} ) @@ -74,15 +74,15 @@ interface ViewIslandProps { } /** The shown view's icon in the stripe, which its island repeats beside its name so the two are learned together. */ -export const ShownViewIcon = createContext(null) +export const ShownViewIcon = createContext(null) /** The island a view draws in, under a header with the view's icon, its name and its tools, as an IntelliJ tool window has. */ export function ViewIsland({ title, tools, className, children }: ViewIslandProps): React.JSX.Element { - const icon = useContext(ShownViewIcon) + const ViewIcon = useContext(ShownViewIcon) return (
- {icon !== null && } + {ViewIcon !== null && }

{title}

{tools} diff --git a/studio/src/renderer/src/studio/StatusBar.tsx b/studio/src/renderer/src/studio/StatusBar.tsx index dc22a0cf5..272b0155a 100644 --- a/studio/src/renderer/src/studio/StatusBar.tsx +++ b/studio/src/renderer/src/studio/StatusBar.tsx @@ -1,4 +1,4 @@ -import { IdeIcon } from '@/components/IdeIcon' +import { MemoryStick, Zap } from 'lucide-react' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { cn } from '@/lib/utils' import type { ServerUsage } from '../bridge/types' @@ -61,12 +61,12 @@ function UsageReadout({ usage }: { usage: ServerUsage }): React.JSX.Element { return ( } + icon={} value={formatCpu(usage)} high={cpuIsHigh(usage)} hint={`Server CPU, 100% per busy thread, ${usage.threads} threads in all`} /> - } value={formatHeap(usage)} high={heapIsHigh(usage)} hint="Java memory the server uses, of its maximum" /> + } value={formatHeap(usage)} high={heapIsHigh(usage)} hint="Java memory the server uses, of its maximum" /> ) } diff --git a/studio/src/renderer/src/studio/StudioToolbar.tsx b/studio/src/renderer/src/studio/StudioToolbar.tsx index 3d4f41a4d..a4890654e 100644 --- a/studio/src/renderer/src/studio/StudioToolbar.tsx +++ b/studio/src/renderer/src/studio/StudioToolbar.tsx @@ -1,5 +1,5 @@ import type { ReactNode } from 'react' -import { IdeIcon } from '@/components/IdeIcon' +import { Blocks, ChevronDown, CircleQuestionMark, Grid3x3, LocateFixed, Mountain, PawPrint, RefreshCw, ScanSearch, Settings, SquareDashed, SunMoon } from 'lucide-react' import { Button } from '@/components/ui/button' import { Kbd } from '@/components/ui/kbd' import { Separator } from '@/components/ui/separator' @@ -32,21 +32,21 @@ export function StudioToolbar({ world, theme, onHelp, onSettings, onDisconnect } {world.world} {world.dimensionName} - +
- +
@@ -66,30 +66,30 @@ export function MapTools({ toggles, hasPlayers, onToggle, onRefresh, onResetZoom return ( <> onToggle('grid')}> - + onToggle('regionBorders')}> - + onToggle('shading')}> - + onToggle('blocks')}> - + onToggle('entities')}> - + onToggle('follow')}> - + - + - + ) @@ -137,7 +137,7 @@ function ToolToggle({ action, hint, pressed, disabled, onPressed, children }: To pressed={pressed} disabled={disabled} onPressedChange={onPressed} - className="size-7 min-w-7 p-0 hover:bg-accent hover:text-foreground data-[state=on]:bg-selection data-[state=on]:text-foreground [&_svg:not([class*='size-'])]:size-3.5" + className="size-7 min-w-7 p-0 hover:bg-accent hover:text-foreground data-[state=on]:bg-selection data-[state=on]:text-foreground" > {children} diff --git a/studio/src/renderer/src/studio/ViewList.tsx b/studio/src/renderer/src/studio/ViewList.tsx index ed990afd4..28fc4dcd6 100644 --- a/studio/src/renderer/src/studio/ViewList.tsx +++ b/studio/src/renderer/src/studio/ViewList.tsx @@ -1,6 +1,33 @@ import { DropdownMenu } from 'radix-ui' import { Fragment } from 'react' -import { IdeIcon, type IdeIconName } from '@/components/IdeIcon' +import { + AudioWaveform, + Box, + Boxes, + Droplets, + Ellipsis, + Fish, + Flower2, + Gem, + HardDrive, + ImageIcon, + Layers, + Map, + MountainSnow, + Package, + Palette, + Pickaxe, + Pyramid, + Shapes, + Sprout, + TreeDeciduous, + TreePine, + Trees, + Waves, + Workflow, + Zap, + type LucideIcon +} from 'lucide-react' import { Kbd } from '@/components/ui/kbd' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { cn } from '@/lib/utils' @@ -8,40 +35,45 @@ import type { ViewInfo } from '../bridge/types' import { viewShortcutId } from './shortcuts' import { useKeyText } from './useBindings' -const VIEW_ICONS: Record = { - biomes: 'views/biomes', - regions: 'views/regions', - rivers: 'views/rivers', - height: 'shading', - 'land-biomes': 'views/biomes', - 'sea-biomes': 'views/biomes', - 'cave-biomes': 'views/biomes', - 'object-load': 'views/objects', - 'decorator-load': 'decoration', - 'layer-load': 'groups', - caveProfiles: 'views/cave-profiles', - treeProfiles: 'views/tree-profiles', - formationProfiles: 'views/formation-profiles', - fluidProfiles: 'views/fluid-profiles', - world3d: 'views/world-3d', - savedWorld: 'views/saved-world', - 'iris:terrain/palettes': 'views/palettes', - 'iris:decorant/decorators': 'decoration', - 'iris:objects': 'views/objects', - 'iris:objects/procedural': 'views/procedural', - noise: 'views/noise', - imageMaps: 'grid', - pregen: 'lightning' +const VIEW_ICONS: Record = { + biomes: Trees, + regions: Map, + rivers: Waves, + height: MountainSnow, + 'land-biomes': TreeDeciduous, + 'sea-biomes': Fish, + 'cave-biomes': Gem, + 'object-load': Boxes, + 'decorator-load': Sprout, + 'layer-load': Layers, + caveProfiles: Pickaxe, + treeProfiles: TreePine, + formationProfiles: Pyramid, + fluidProfiles: Droplets, + world3d: Box, + savedWorld: HardDrive, + 'iris:terrain/palettes': Palette, + 'iris:decorant/decorators': Flower2, + 'iris:objects': Package, + 'iris:objects/procedural': Workflow, + noise: AudioWaveform, + imageMaps: ImageIcon, + pregen: Zap } -const FALLBACK_ICON: IdeIconName = 'blocks' +const FALLBACK_ICON: LucideIcon = Shapes /** Inset, because the stripe scrolls and so clips anything drawn outside its buttons. */ const STRIPE_BUTTON = 'flex size-8 shrink-0 items-center justify-center rounded-lg outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-inset' /** The icon a view has in the stripe, which its island's header repeats beside its name. */ -export function viewIcon(viewId: string): IdeIconName { +export function viewIcon(viewId: string): LucideIcon { return VIEW_ICONS[viewId] ?? FALLBACK_ICON } +function ViewIcon({ viewId, className }: { viewId: string; className: string }): React.JSX.Element { + const Icon = viewIcon(viewId) + return +} + interface ViewListProps { views: ViewInfo[] current: string @@ -99,9 +131,9 @@ function ViewButton({ view, selected, onSelect }: { view: ViewInfo; selected: bo onClick={onSelect} aria-label={view.label} aria-pressed={selected} - className={cn(STRIPE_BUTTON, selected ? 'bg-primary [&_img]:brightness-0 [&_img]:invert' : 'hover:bg-selection')} + className={cn(STRIPE_BUTTON, selected ? 'bg-primary text-primary-foreground' : 'hover:bg-selection')} > - + @@ -122,11 +154,7 @@ function NamedViews({ groups, current, onSelect }: { groups: ViewGroup[]; curren @@ -143,7 +171,7 @@ function NamedViews({ groups, current, onSelect }: { groups: ViewGroup[]; curren view.id === current && 'bg-selection' )} > - + {view.label} {keyText(viewShortcutId(view.id)) !== '' && ( {keyText(viewShortcutId(view.id))} diff --git a/studio/src/renderer/src/studio/nodeColors.ts b/studio/src/renderer/src/studio/nodeColors.ts new file mode 100644 index 000000000..1852c32d8 --- /dev/null +++ b/studio/src/renderer/src/studio/nodeColors.ts @@ -0,0 +1,33 @@ +/** The colours of the node editor: one per kind of node, and one per role so its nodes are found at a glance. */ +const PRIMARY = 'var(--primary)' +const BY_KIND: Record = { + Object: PRIMARY, + Stem: '#c08552', + Blob: '#5fb865', + Branches: '#d9a23f', + Cluster: '#9c7bd6', + Group: '#8c9099', + 'Shared part': '#548af7', + Material: '#d8709a', + Decoration: '#4fb6c6' +} +const ROLE_COLORS = ['#c08552', '#5fb865', '#548af7', '#d9a23f', '#9c7bd6', '#4fb6c6', '#d8709a', '#a3b84f'] +const KNOWN_ROLES: Record = { wood: ROLE_COLORS[0], leaves: ROLE_COLORS[1] } +const FALLBACK_KIND_COLOR = BY_KIND.Group + +export function colorOfKind(kind: string): string { + return BY_KIND[kind] ?? FALLBACK_KIND_COLOR +} + +/** The same role always gets the same colour, wherever it is used. */ +export function colorOfRole(role: string): string { + return KNOWN_ROLES[role] ?? ROLE_COLORS[hashOf(role) % ROLE_COLORS.length] +} + +function hashOf(text: string): number { + let hash = 0 + for (let index = 0; index < text.length; index++) { + hash = (Math.imul(hash, 31) + text.charCodeAt(index)) >>> 0 + } + return hash +} diff --git a/studio/src/renderer/src/studio/nodeEditing.ts b/studio/src/renderer/src/studio/nodeEditing.ts new file mode 100644 index 000000000..1f8195b94 --- /dev/null +++ b/studio/src/renderer/src/studio/nodeEditing.ts @@ -0,0 +1,29 @@ +import { createContext, useContext } from 'react' +import type { GraphEdit } from '../bridge/types' +import type { NodeRow } from '../editor/nodeRows' +import type { SuggestionSource } from '../editor/suggestions' + +export type SettingRow = Extract + +/** What the nodes' rows share: the edits they make to the file, and which curve editor is open. */ +export interface NodeEditing { + locked: boolean + /** The id of the setting row whose curve editor is open, or null. */ + openCurve: string | null + onOpenCurve(rowId: string | null): void + onToggleFold(foldId: string): void + onEdit(edit: GraphEdit): void + loadSuggestions(source: SuggestionSource): Promise + /** Notes the setting a right-click is on, so the node's menu can offer to make it a curve or one number. */ + onSettingMenu(row: SettingRow): void +} + +export const NodeEditingContext = createContext(null) + +export function useNodeEditing(): NodeEditing { + const editing = useContext(NodeEditingContext) + if (editing === null) { + throw new Error('A node row was drawn outside a node canvas') + } + return editing +} diff --git a/studio/src/renderer/src/studio/useNodeCamera.ts b/studio/src/renderer/src/studio/useNodeCamera.ts new file mode 100644 index 000000000..c8ff7b293 --- /dev/null +++ b/studio/src/renderer/src/studio/useNodeCamera.ts @@ -0,0 +1,105 @@ +import { useCallback, useEffect, useState } from 'react' +import { GRID, type Bounds, type Point } from '../editor/nodeLayout' + +const MARGIN = GRID +const SMALLEST_SCALE = 0.25 +const LARGEST_SCALE = 2.5 +const WHEEL_ZOOM_PER_PIXEL = 0.0015 + +/** Where the canvas looks: the screen offset of the graph's origin, and how much it is zoomed. */ +export interface Camera { + x: number + y: number + scale: number +} + +export interface NodeCamera { + camera: Camera + panBy(dx: number, dy: number): void + /** Zooms out, never in past 100%, until every node fits, and centres them. */ + showAll(bounds: Bounds | null): void + resetZoom(): void + /** Moves the view so the rectangle is in sight, when it is not already. */ + reveal(area: Bounds): void + /** The graph point under a point of the window. */ + graphPoint(clientX: number, clientY: number): Point +} + +/** The view of the node canvas in {@code frame}: dragged to pan, zoomed by the wheel around the pointer; it opens at 100% on the top left node. */ +export function useNodeCamera(frame: React.RefObject, opening: Bounds | null): NodeCamera { + const [camera, setCamera] = useState(() => ({ x: MARGIN - (opening?.left ?? MARGIN), y: MARGIN - (opening?.top ?? MARGIN), scale: 1 })) + + useEffect(() => { + const element = frame.current + if (element === null) { + return + } + const wheel = (event: WheelEvent): void => { + event.preventDefault() + const bounds = element.getBoundingClientRect() + setCamera((current) => zoomedAround(current, { x: event.clientX - bounds.left, y: event.clientY - bounds.top }, Math.exp(-event.deltaY * WHEEL_ZOOM_PER_PIXEL))) + } + element.addEventListener('wheel', wheel, { passive: false }) + return () => element.removeEventListener('wheel', wheel) + }, [frame]) + + const panBy = useCallback((dx: number, dy: number) => setCamera((current) => ({ ...current, x: current.x + dx, y: current.y + dy })), []) + + const showAll = useCallback( + (bounds: Bounds | null) => { + const element = frame.current + if (element === null || bounds === null) { + return + } + const [width, height] = [bounds.right - bounds.left + 2 * MARGIN, bounds.bottom - bounds.top + 2 * MARGIN] + const scale = clamp(Math.min(element.clientWidth / width, element.clientHeight / height), SMALLEST_SCALE, 1) + setCamera({ scale, x: element.clientWidth / 2 - ((bounds.left + bounds.right) / 2) * scale, y: element.clientHeight / 2 - ((bounds.top + bounds.bottom) / 2) * scale }) + }, + [frame] + ) + + const resetZoom = useCallback(() => { + const element = frame.current + if (element !== null) { + setCamera((current) => zoomedAround(current, { x: element.clientWidth / 2, y: element.clientHeight / 2 }, 1 / current.scale)) + } + }, [frame]) + + const reveal = useCallback( + (area: Bounds) => { + const element = frame.current + if (element === null) { + return + } + setCamera((current) => { + const [left, top] = [current.x + area.left * current.scale, current.y + area.top * current.scale] + const [right, bottom] = [current.x + area.right * current.scale, current.y + area.bottom * current.scale] + const height = Math.min(bottom - top, element.clientHeight) + const dx = left < 0 || right > element.clientWidth ? MARGIN - left : 0 + const dy = top < 0 || top + height > element.clientHeight ? MARGIN - top : 0 + return dx === 0 && dy === 0 ? current : { ...current, x: current.x + dx, y: current.y + dy } + }) + }, + [frame] + ) + + const graphPoint = useCallback( + (clientX: number, clientY: number): Point => { + const bounds = frame.current!.getBoundingClientRect() + return { x: (clientX - bounds.left - camera.x) / camera.scale, y: (clientY - bounds.top - camera.y) / camera.scale } + }, + [frame, camera] + ) + + return { camera, panBy, showAll, resetZoom, reveal, graphPoint } +} + +function zoomedAround(current: Camera, anchor: Point, factor: number): Camera { + const scale = clamp(current.scale * factor, SMALLEST_SCALE, LARGEST_SCALE) + const ratio = scale / current.scale + return { scale, x: anchor.x - (anchor.x - current.x) * ratio, y: anchor.y - (anchor.y - current.y) * ratio } +} + +function clamp(value: number, lowest: number, highest: number): number { + return Math.min(highest, Math.max(lowest, value)) +} diff --git a/studio/src/renderer/src/studio/useNodePositions.ts b/studio/src/renderer/src/studio/useNodePositions.ts new file mode 100644 index 000000000..325efc777 --- /dev/null +++ b/studio/src/renderer/src/studio/useNodePositions.ts @@ -0,0 +1,34 @@ +import { useEffect, useState } from 'react' +import type { Point } from '../editor/nodeLayout' +import type { NodePositions } from '../editor/nodePositions' + +const STORAGE_PREFIX = 'iris-studio.node-positions:' + +function isPoint(value: unknown): value is Point { + return typeof value === 'object' && value !== null && typeof (value as Point).x === 'number' && typeof (value as Point).y === 'number' +} + +// Unreadable positions just mean every node sits where the layout puts it. +function storedPositions(file: string): NodePositions { + try { + const stored: unknown = JSON.parse(localStorage.getItem(STORAGE_PREFIX + file) ?? '{}') + return Object.fromEntries(Object.entries(stored as Record).filter(([, position]) => isPoint(position))) as NodePositions + } catch { + return {} + } +} + +/** Where the nodes of {@code file} were dragged to, kept by the studio so the file only holds settings. */ +export function useNodePositions(file: string): [NodePositions, React.Dispatch>] { + const [positions, setPositions] = useState(() => storedPositions(file)) + + useEffect(() => { + if (Object.keys(positions).length === 0) { + localStorage.removeItem(STORAGE_PREFIX + file) + } else { + localStorage.setItem(STORAGE_PREFIX + file, JSON.stringify(positions)) + } + }, [file, positions]) + + return [positions, setPositions] +}